text:
Q: What causes "Reconnections made" statistics on network? A client site is having hard-to-diagnose issues related to their network. While working on the problem, I ran the command "net statistics workstation" on one of the computers. I got the following data covering approximately a week of activity:
Bytes received                               23791085485
Server Message Blocks (SMBs) received        22410645
Bytes transmitted                            8962989188
Server Message Blocks (SMBs) transmitted     22410618
Read operations                              4481436
Write operations                             2275694
Raw reads denied                             0
Raw writes denied                            0

Network errors                               0
Connections made                             629
Reconnections made                           990560
Server disconnects                           40

Sessions started                             0
Hung sessions                                0
Failed sessions                              0
Failed operations                            22
Use count                                    1212
Failed use count                             198

I'm thinking the very large number of "Reconnections made" (almost a million of them, so almost 2 per second for a week) should be telling me something about what's going on with this network. What precisely does that number represent and what does it indicate? How about the other numbers?
Thanks for any help!

A: You can use the Redirector object in perfmon to get statistics about the Workstation service.  The descriptions of each counter in perfmon is a good place to start when you have no idea what they mean.
Directly from perfmon, here is the Microsoft description of "Reconnections Made" which is labelled as "Server Reconnects" in perfmon:

Server Reconnects counts the number of times your Redirector has had
  to reconnect to a server in order to complete a new active request.
  You can be disconnected by the Server if you remain inactive for too
  long.  Locally even if all your remote files are closed, the
  Redirector will keep your connections intact for (nominally) ten
  minutes.  Such inactive connections are called Dormant Connections.
  Reconnecting is expensive in time.


text:
Q: soap fault invalid xml error I am using soap with nodejs. I am getting invalid xml error response. Can any one help?
{ Fault:
   { faultcode: 500,
     faultstring: 'Invalid XML',
     detail: 'Error: Attribute without value\nLine: 5\nColumn: 23\nChar: >',
     statusCode: 500 }
}

redpajama_set_name: RedPajamaStackExchange


text:
Q: Use a Cell Value as a Worksheet Name I want to paste data from a Workbook to another workbook into a sheet which has the name of a cell value. I don't know if that's possible, but I'm struggling with that and I can't find anything similar on internet.
This is my code so far:
'This creates a sheet from a range and gives it the name of the cell so it can be from 5 to 10 sheets'

For Each Cell In Range("G5:G15")
    If Cell.Value <> "" Then
        Sheets.Add(After:=Sheets(Sheets.Count)).Name = Cell.Value
    End If
Next

After other code which is not important, I made this:
Dim AutoFilterRng As Range
Dim WorksheetName As String

For Each Cell In Range("H5", Range("H5").End(xlDown))
    If Cell.Value <> "" Then
        WorksheetName = Cell.Offset(0, -1).Value
        Workbooks.Open MJFile                    'Opens the file where data I want to copy
        ActiveSheet.Range("A:U").AutoFilter Field:=12, Criteria1:="*" & Cell.Value    'Filters depending on the cell value
        With ActiveSheet.AutoFilter.Range
            Set AutoFilterRng = .Offset(1, 0).Resize(.Rows.Count - 1, 1).SpecialCells(xlCellTypeVisible)
        End With
        ActiveSheet.AutoFilter.Range.Offset(1, 0).Resize(ActiveSheet.AutoFilter.Range.Count - 1).Copy
        Workbooks.Open WBOR    'Opens the Workbook where I want to paste data
        Worksheets(WorksheetName).Range("A1").Paste    'This gives an  error and it is where I would like to paste my data
        Workbooks.Open MJFile
        AutoFilterMode = False
    End If
Next

Thank you very much in advance
If you want to see the whole code:
Sub AddTO()
Application.Calculation = xlManual
Application.ScreenUpdating = False
Application.EnableEvents = False
'------------------------------------------------------------------------------------------------------------------------------------------------------'

'Open TO FIle'

Dim WBOR As String
Dim MJFile As String
Dim TOFile As String
Dim Path As String

WBOR = ActiveWorkbook.Path & "\" & ActiveWorkbook.Name

'On Error GoTo Fin
MsgBox "Choose Bear File"
With Application.FileDialog(msoFileDialogFilePicker)
    .Filters.Clear
    .AllowMultiSelect = False
    If .Show = -1 Then
        TOFile = .SelectedItems(1)
    End If
End With

Workbooks.Open TOFile

'Filter Bear File to Only Necessary TO'
Dim NameRng As Range
Dim TORng As Range
Dim DeliveryWeek As String
Dim i As Long

Workbooks.Open WBOR
Set NameRng = Worksheets("Tasks_Orders_Info").Range("E5", Range("E5").End(xlDown))
Workbooks.Open TOFile
Set TORng = Worksheets("WS Lead Plan1").Range("G2", Range("G2").End(xlDown))
Workbooks.Open WBOR
DeliveryWeek = "*Week_" & Worksheets("Tasks_Orders_Info").Range("C5").Value & "*"

Workbooks.Open TOFile
For i = TORng.Count To 1 Step -1
    Select Case True
        Case TORng.Cells(i) Like DeliveryWeek
        Case Else
            TORng.Cells(i).EntireRow.Delete
    End Select
Next i

'Add TO to MJ File'
Workbooks.Open WBOR
TORng.Copy
Worksheets("Tasks_Orders_Info").Range("G5").PasteSpecial xlPasteValues
Worksheets("Tasks_Orders_Info").Range("G5").End(xlDown).PasteSpecial xlPasteValues

Workbooks.Open TOFile
ActiveWorkbook.Close SaveChanges:=False

Range("H5:H15") = "=IF(ISERR(FIND("" "",Table2[@Coder])),"""",LEFT(Table2[@Coder],FIND("" "",Table2[@Coder])-1))"
Range("I5:I15") = "=MID(Table2[@Coder],SEARCH("" "",Table2[@Coder],1)+1,SEARCH("" "", Table2[@Coder],SEARCH("" "",Table2[@Coder],1)+1)-SEARCH("" "",Table2[@Coder],1))"
Range("J5:J15") = "=IFERROR(MID(Table2[@Coder],FIND("" "",Table2[@Coder],FIND("" "",Table2[@Coder])+1)+1,FIND("" "",Table2[@Coder],FIND("" "",Table2[@Coder],FIND("" "",Table2[@Coder])+1)+1)-FIND("" "",Table2[@Coder],FIND("" "",Table2[@Coder])+1)-1),"""")"

Form1 = "=IF(OR(ISNUMBER(FIND(H5,G5,1)),ISNUMBER(FIND(I5,G5,1)),IF(J5="""",FALSE,ISNUMBER(FIND(J5,G5,1)))),LEFT(G5,FIND(""  "",G5,1)-3),IF(OR(ISNUMBER(FIND(H5,G6,1)),ISNUMBER(FIND(I5,G6,1)),IF(J5="""",FALSE,ISNUMBER(FIND(J5,G6,1)))),LEFT(G6,FIND(""  "",G6,1)-3),IF(OR(ISNUMBER(FIND(H5,G7,1)),ISNUMBER(FIND(I5,G7,1)),IF(J5="""",FALSE,ISNUMBER(FIND(J5,G7,1)))),LEFT(G7,FIND(""  "",G7,1)-3),IF(OR(ISNUMBER(FIND(H5,G8,1)),ISNUMBER(FIND(I5,G8,1)),IF(J5="""",FALSE,ISNUMBER(FIND(J5,G8,1)))),LEFT(G8,FIND(""  "",G8,1)-3),IF(OR("
Form2 = "ISNUMBER(FIND(H5,G9,1)),ISNUMBER(FIND(I5,G9,1)),IF(J5="""",FALSE,ISNUMBER(FIND(J5,G9,1)))),LEFT(G9,FIND(""  "",G9,1)-3),IF(OR(ISNUMBER(FIND(H5,G10,1)),ISNUMBER(FIND(I5,G10,1)),IF(J5="""",FALSE,ISNUMBER(FIND(J5,G10,1)))),LEFT(G10,FIND(""  "",G10,1)-3),IF(OR(ISNUMBER(FIND(H5,G11,1)),ISNUMBER(FIND(I5,G11,1)),IF(J5="""",FALSE,ISNUMBER(FIND(J5,G11,1)))),LEFT(G11,FIND(""  "",G11,1)-3),IF(OR(ISNUMBER(FIND(H5,G12,1)),ISNUMBER(FIND(I5,G12,1)),IF(J5="""",FALSE,ISNUMBER(FIND(J5,G12,1)))),LEFT(G12,FIND(""  "",G12,1)-3),IF("
Form3 = "OR(ISNUMBER(FIND(H5,G13,1)),ISNUMBER(FIND(I5,G13,1)),IF(J5="""",FALSE,ISNUMBER(FIND(J5,G13,1)))),LEFT(G13,FIND(""  "",G13,1)-3),IF(OR(ISNUMBER(FIND(H5,G14,1)),ISNUMBER(FIND(I5,G14,1)),IF(J5="""",FALSE,ISNUMBER(FIND(J5,G14,1)))),LEFT(G14,FIND(""  "",G14,1)-3),IF(OR(ISNUMBER(FIND(H5,G15,1)),ISNUMBER(FIND(I5,G15,1)),IF(J5="""",FALSE,ISNUMBER(FIND(J5,G15,1)))),LEFT(G15,FIND(""  "",G15,1)-3),""NOT FOUND"")))))))))))"
Range("B5", Range("B5").End(xlDown)) = Form1 + Form2 + Form3

Range("B5", Range("B5").End(xlDown)).Copy
Range("B5", Range("B5").End(xlDown)).PasteSpecial xlPasteValues
Range("G5", Range("G5").End(xlDown)).ClearContents

'Create New Sheets"
Range("G5:G15") = "=IFERROR(CONCAT(RIGHT(Table2[@[TASK ORDER]],LEN(Table2[@[TASK ORDER]])-SEARCH("" TO"",Table2[@[TASK ORDER]],1)),""_"",H5),"""")"
Range("G5:G15").Copy
Range("G5:G15").PasteSpecial xlPasteValues

Range("H5", Range("H5").End(xlDown)).Select
Range(Selection, Selection.End(xlToRight)).Delete

For Each Cell In Range("G5:G15")
    If Cell.Value <> "" Then
        Sheets.Add(After:=Sheets(Sheets.Count)).Name = Cell.Value
    End If
Next

Worksheets("Tasks_Orders_Info").Activate

'Open MJ File'
MsgBox "Choose mj extraction"
With Application.FileDialog(msoFileDialogFilePicker)
    .Filters.Clear
    .AllowMultiSelect = False
    If .Show = -1 Then
        MJFile = .SelectedItems(1)
    End If
End With

Workbooks.Open MJFile

'Delete non Users'
Dim mapjobdata As Range
Dim WorkUserRg As Range

Worksheets("map_jobs_-_feedback_and_observa").Range("A1").Select
Worksheets("map_jobs_-_feedback_and_observa").Range(Selection, Selection.End(xlDown)).Select
Worksheets("map_jobs_-_feedback_and_observa").Range(Selection, Selection.End(xlToRight)).Select

Set mapjobdata = Worksheets("map_jobs_-_feedback_and_observa").Range(Selection.Address)
Set WorkUserRg = mapjobdata.Find("Worked on by User", , xlValues, xlWhole, , , True).Offset(1, 0)
Set WorkUserRg = Worksheets("map_jobs_-_feedback_and_observa").Range(WorkUserRg, WorkUserRg.End(xlDown))

For i = WorkUserRg.Count To 1 Step -1
    If WorkUserRg.Cells(i) Like "*@email.com*" Then
        Else
            WorkUserRg.Cells(i).EntireRow.Delete
    End If
Next i

'Add MapJobs to each Sheet'
Workbooks.Open WBOR
Range("H5:H15") = "=IFERROR(RIGHT(Table2[@Coder],FIND("")"",Table2[@Coder],1)-(FIND("" ("",Table2[@Coder],1))),"""")"
Range("H5", Range("H5").End(xlDown)).Copy
Range("H5", Range("H5").End(xlDown)).PasteSpecial xlPasteValues

Dim AutoFilterRng As Range
Dim WorksheetName As String

For Each Cell In Range("H5", Range("H5").End(xlDown))
    If Cell.Value <> "" Then
        WorksheetName = Cell.Offset(0, -1).Value
        Workbooks.Open MJFile
        ActiveSheet.Range("A:U").AutoFilter Field:=12, Criteria1:="*" & Cell.Value
        With ActiveSheet.AutoFilter.Range
            Set AutoFilterRng = .Offset(1, 0).Resize(.Rows.Count - 1, 1).SpecialCells(xlCellTypeVisible)
        End With
        ActiveSheet.AutoFilter.Range.Offset(1, 0).Resize(ActiveSheet.AutoFilter.Range.Count - 1).Copy
        Workbooks.Open WBOR
        Worksheets(WorksheetName).Range("A1").Paste
        Workbooks.Open MJFile
        AutoFilterMode = False
    End If
Next

'------------------------------------------------------------------------------------------------------------------------------------------------------'
Fin:
Application.EnableEvents = True
Application.Calculation = xlAutomatic
Application.ScreenUpdating = True
End Sub

This is the error I get and debug shows the next line:

A: This is not the answer BUT may help you:
Sub test()

    Dim shtName As String

    With ThisWorkbook

        'Let assume that the sheet name we want appears in Sheet3, range A1
        'Get sheet name
        shtName = .Worksheets("Sheet3").Range("A1").Value
        'Activate sheet with name shtName
        .Worksheets(shtName).Activate

    End With

End Sub

A: This is an untested code. I do not have the necessary data to test  it. It must give you some hints in order to understand what is to be done:
Please add Option Explicit on top of your module. This will oblige you to declare all variables...
Sub sheetsAddAndCopy()
Dim WBOR As Workbook, Wmjf As Workbook, shW As Worksheet, shMJ As Worksheet
Dim AutoFilterRng As Range, WorksheetName As String, cell As Range

Const MJFile As String = "your workbook full path"
Set WBOR = ThisWorkbook
Set Wmjf = Workbooks.Open(MJFile) 'Opens the file where data I want to copy

For Each cell In WBOR.Range("H5", Range("H5").End(xlDown))
    If cell.Value <> "" Then
        WorksheetName = cell.Offset(0, -1).Value
        Set shW = WBOR.Sheets.Add(After:=Sheets(Sheets.count))
           shW.Name = WorksheetName
           Set shMJ = Wmjf.ActiveSheet
           shMJ.Range("A:U").AutoFilter field:=12, Criteria1:="*" & cell.Value    'Filters depending on the cell value
            Set AutoFilterRng = shMJ.AutoFilter.Range.Offset(1, 0).Resize(.Rows.count - 1, 1).SpecialCells(xlCellTypeVisible)
            shMJ.AutoFilter.Range.Offset(1, 0).Resize(shMJ.AutoFilter.Range.count - 1).Copy shW.Range("A1")
          shMJ.AutoFilterMode = False
    End If
Next

A: I should not use .paste instead it should be .PasteSpecial and set the Worksheet. In this case WorksheetName = Cell.Offset(0,-1).Value and then set the Worksheet with that name so it will be Dim CurrentWSName, Set CurrentWSName = ActiveWorkbook.Sheets(WorksheetName) Code will be like this:
Dim AutoFilterRng As Range
Dim WorksheetName As String
Dim CurrentWSName As Worksheet

For Each Cell In Range("H5", Range("H5").End(xlDown))
    If Cell.Value <> "" Then
        WorksheetName = Cell.Offset(0, -1).Value
        Set CurrentWSName = ActiveWorkbook.Sheets(WorksheetName)
        Workbooks.Open MJFile
        ActiveSheet.Range("A:U").AutoFilter Field:=12, Criteria1:="*" & Cell.Value
        With ActiveSheet.AutoFilter.Range
            Set AutoFilterRng = .Offset(1, 0).Resize(.Rows.Count - 1, 1).SpecialCells(xlCellTypeVisible)
        End With
        ActiveSheet.AutoFilter.Range.Offset(1, 0).Resize(ActiveSheet.AutoFilter.Range.Count - 1).Copy
        Workbooks.Open WBOR
        CurrentWSName.Activate
        Range("A1").PasteSpecial
        Workbooks.Open MJFile
        AutoFilterMode = False
        Workbooks.Open WBOR
    End If
Next


text:
Q: creating a custom left tab to magento admin customer pages I want to create an left tab to magento backend customer page.
I tried to add a module i found. but it doesnt work for Magento 1.9 version.
here's the LINK

A: There are issue with
Issue: Mydons_Customertab.xml  file <codepool> syntex should be
and
Issue2: config.xml path location should be  Mydons/Customertab/etc


text:
Q: searching in google from differents PC return different results I am searching for a specific keyword in google and from different computers I am getting different results. On one computer, the website I was expecting for is the 3rd on the first page and on other computer, the website is not listed at all in the first page.
Is there some cache that I need to clear in order to have the search returning unique results on all computers?

A: Google's Personalized Search feature uses search history to personalize your search results. Since all searches on Google Search are associated with a browser cookie record, previous search results and visited websites can be used to provide more relevant results.
See "Step 3" of Google's Search and Browse Privately support page to turn off result customization.

A: If I am correct, your problem could be in the URL itself. This totally depends on the OS. (this is assuming you search is "keywords" and your OS is Ubuntu -->)If the OS'es are different, then it should be the client part in "https://www.google.com/search?q=keywords&client=ubuntu" (there are more parts to the url, but that's all i need to explain it. Just try taking out the client part from the URL.


text:
Q: Applying percentage in one dataframe to columns in other data frame to create new dataframe I am new to python so maybe a silly and easy question.
I have two data frames, the first data frame have a percentage column which needs to applied on column A, B, C in Dataframe2. Any suggestions ?
Dataframe 1
Region      Percentage
South       34.4%
North       27.0%
West        21.2%
Eastern     14.8%
other       2.6%
Dataframe 2
Week ending Upper Limit Forecasted value    Lower Limit State   Forecasting Date
22/05/2022  2112.2  2316.4  2525.9  CA  30/05/2022
29/05/2022  2123.8  2331.1  2523.4  CA  30/05/2022
5/06/2022   2136.5  2340.5  2553.8  CA  30/05/2022
12/06/2022  2148.466667 2353.433333 2562.266667 CA  30/05/2022
19/06/2022  2160.616667 2365.483333 2576.216667 CA  30/05/2022
26/06/2022  2172.766667 2377.533333 2590.166667 CA  30/05/2022
Desired Data frame
Region  Week ending Upper Limit Forecasted value    Lower Limit State   Forecasting Date
South   22/05/2022  726.6   796.8   868.9   CA  30/05/2022
North   22/05/2022  570.3   625.4   682.0   CA  30/05/2022
West    22/05/2022  447.8   491.1   535.5   CA  30/05/2022
Eastern     22/05/2022  312.6   342.8   373.8   CA  30/05/2022
other   22/05/2022  54.9    60.2    65.7    CA  30/05/2022
South   29/05/2022  730.6   801.9   868.0   CA  30/05/2022
North   29/05/2022  573.4   629.4   681.3   CA  30/05/2022
West    29/05/2022  450.2   494.2   535.0   CA  30/05/2022
Eastern     29/05/2022  314.3   345.0   373.5   CA  30/05/2022
other   29/05/2022  55.2    60.6    65.6    CA  30/05/2022
South   5/06/2022   735.0   805.1   878.5   CA  30/05/2022
North   5/06/2022   576.9   631.9   689.5   CA  30/05/2022
West    5/06/2022   452.9   496.2   541.4   CA  30/05/2022
Eastern     5/06/2022   316.2   346.4   378.0   CA  30/05/2022
other   5/06/2022   55.5    60.9    66.4    CA  30/05/2022
Please find below excel image, hopefully above data with excel image would make more sense. I would have love to attach excel if they would have let me. Thanks in advance on any assistance.
enter image description here

A: 1. Because we don't have common keys (columns), we can't merge them, so the trick is to make both DF same size.
1.1 Make df1 to 30 rows, repeating same row block:
df1 = pd.concat([df1]*6, ignore_index=True)

1.2 Make df2 to 30 rows repeating by index this time:
df2 = df2.loc[df2.index.repeat(5)].reset_index(drop=True)

2. Now that we have 2 dfs with same size (length), we can concat() them:
df3 = pd.concat([df1, df2], axis=1)

3. Time now to multiply the 3 columns by the "Percentage" (I've removed the "%" to make it easier) one:
df3[["Upper Limit", "Forecasted value", 'Lower limit']] = (df3[["Upper Limit", "Forecasted value", 'Lower limit']].multiply(df3["Percentage"], axis="index")/100).round(1)
df3


text:
Q: How can I create a setup file to add to the Windows Store? I have a Win Form(.net 4.7.2) project developed with C#. I right click on my project in Visual Studo and use the Publish menu to create setup files. I have a code signing certificate for my project that I renew every year.I get an error when I want to add my app to the Windows Store.
`App Policies: 10.2.9
Win32 products must be submitted as a standalone/offline installer. Installers must not be a downloader that downloads the bits it needs to run. Please resubmit with an appropriate installer.`
For more details for App Policies: 10.2.9: https://learn.microsoft.com/tr-tr/windows/uwp/publish/store-policies
Do I need to create a setup project in Visual Studio? I didn't understand exactly what to do. How can I research this?
When I Publish the project, the installation file and many folders are created. I know this is not a professional setup file, but I need a solid, secure setup file signed with certificates. I couldn't figure out how to do this, I don't even know how to search.

A: The simplest way to distribute a C# (WinForms/WPF) application in Microsoft Store would be to package the app into an Appx package using Visual Studio. I uploaded my WPF application to MS Store by the following procedure:

*

*Add a Windows Application Packaging Project to my solution in Visual Studio

*Right click Dependencies of the Packaging project -> Add Project Reference to my application project

*Right click the Packaging project -> Publish -> Create App Packages


text:
Q: Trouble centering text vertically inside container I am having some trouble with centering text vertically in it's container. I have tried setting display: inline-block; and vertical-align: middle; but it doesn't seem to work. Any help is very appreciated!

HTML:

Upcoming Events

    <?php query_posts('post_type=event&posts_per_page=4'); ?>
    <?php while (have_posts()) : the_post(); ?>

    <a href="<?php the_permalink(); ?>">

NOV

17

TUE

<?php the_title(); ?>

<?php the_field('time'); ?>

    <?php endwhile; wp_reset_query(); ?>

CSS:
.news-events .col2 .event-container {
  background-color: #ECF0F1;
  border-radius: 3px;
  padding: 5px 15px;
  margin-bottom: 25px;
  font-family: Verdana;
}

.news-events .col2 .event-container .col1 {
  width: 15%;
  display: inline-block;
  vertical-align: middle;
  margin: 0 auto;
}

.news-events .col2 .event-container .col1 p {
  vertical-align: middle;
}

.news-events .col2 .event-container .col2 {
  width: 85%;
  display: inline-block;
  margin: 0 auto;
  vertical-align: middle;
}

.news-events .col2 .event-container h2 {
  font-weight: 400;
  font-family: 'Merriweather';
  margin-top: 10px;
  margin-bottom: 5px;
}

.news-events .col2 .event-container p {
  margin-top: 5px;
  margin-bottom: 5px;
}

A: vertical-align: middle property work with display:table-cell. Try both together.

A: A basic example would be to use flex on the .event-container

.event-container {
  display: flex;
  align-items: center;
}

/* DEMO PURPOSES */
body {
  background: grey;
}
h2 {
  margin: 0;
}
.event-container {
  border: solid 1px;
  background: #fff;
}

NOV

17

TUE

The title

10:30

NOV

17

TUE

The title The title The title The title The title

10:30


text:
Q: When the server starts, the message is logged out I'm writing a "npm start" and gives this error.

"concurrently" ▒▒ ▒▒▒▒ ▒▒▒▒७▒▒▒ ▒▒▒ ▒▒▒譥▒ ▒▒▒▒▒▒▒▒, ▒ᯮ▒▒塞▒▒ ▒ணࠬ▒▒▒
  ▒▒▒ ▒▒▒▒▒▒ 䠩▒▒▒.
npm ERR! code ELIFECYCLE
npm ERR! errno 1
npm ERR! 05_html@1.0.0 open: concurrently "livereloadx -s -p 8080"
  "start http://localhost:8080"
npm ERR! Exit status 1
npm ERR!
npm ERR! Failed at the 05_html@1.0.0 open script.
npm ERR! This is probably not a problem with npm. There is likely
  additional logging output above.
npm WARN Local package.json exists, but node_modules missing, did you
  mean to install?
npm ERR! A complete log of this run can be found in: npm ERR!
  C:\Users\lFoster\AppData\Roaming\npm-cache_logs\2018-10-29T11_23_36_759Z-debug.log
npm ERR! code ELIFECYCLE
npm ERR! errno 1
npm ERR! 05_html@1.0.0 start: npm run open
npm ERR! Exit status 1
npm ERR!
npm ERR! Failed at the 05_html@1.0.0 start script.
npm ERR! This is probably not a problem with npm. There is likely
  additional logging output above.
npm WARN Local package.json exists, but node_modules missing, did you
  mean to install?
npm ERR! A complete log of this run can be found in: npm ERR!
  C:\Users\lFoster\AppData\Roaming\npm-cache_logs\2018-10-29T11_23_36_803Z-debug.log

package.json:
{
  "name": "05_html",
  "version": "1.0.0",
  "description": "",
  "main": "index.js",
  "scripts": {
    "start": "npm run open",
    "open": "concurrently \"livereloadx -s -p 8080\" \"start http://localhost:8080\""
  },
  "keywords": [],
  "author": "",
  "license": "ISC",
  "devDependencies": {
    "concurrently": "^4.0.1",
    "livereloadx": "^0.3.10"
  }
}


text:
Q: Out of bounds in array loop Can anyone explain to me how this  nums.length-2 works so that you would be able to use i+1 and i+2 in the loop
public boolean array123(int[] nums) {

    for (int i=0; i < nums.length-2; i++) {
        if (nums[i]==1 && nums[i+1]==2 && nums[i+2]==3) return true;
    }
return false;
}

A: Please refer to this, and start some pen work.
things will be more clear.
Let say array is int[] nums as below.

A: Change the for loop condition to    i <= nums.length-2    instead of i < nums.length-2, it works!!

A: You can understand this thing by taking an example array.
Suppose you have an array [1,2,3,4] so now your length is 4 and loop condition is i


text:
Q: JIRA, add a Workflow to a Workflow Scheme? In JIRA, what is the appropriate procedure to add a Workflow to a Workflow Scheme?
In my case I created a new Issue Type which is referenced by a newly created Workflow. In order to add the Workflow to a Workflow Scheme, the Workflow Scheme must be Inactive. In order for the Workflow Scheme to be Inactive, I have change each Project's Workflow Scheme to something else. Only when there are no Projects using the Workflow Scheme can I edit it.
When changing a Project to a different Workflow Scheme ("Associate Workflow Scheme to Project"), JIRA warns that a backup should be made and that every single issue will be changed. Something tells me this is an overkill for such a simple change. I really don't want to alter every issue just to add a new Workflow to a Workflow Scheme.
Am I missing something?
Follow up: According to Atlassian, there's no choice but to migrate to the new Workflow Scheme.

A: Go to Admin, Schemes, Workflow Schemes. Copy the Workflow scheme currently in use by your project. Edit the copy and assign the new workflow to the issue type. Then go back to the project and select the new workflow scheme, which may prompt you about migration of issues if necessary.
It's not overkill, it's just being careful. You don't actually change anything unless you have to, for example if there are issues of the new issue type in the project.
~Matt


text:
Q: Proving $\dim_K V = \dim_E V \cdot [E:K]$ for a field extension $K \subseteq E$ Let $K \subseteq E$ be a field extension. Then according to Wikipedia, for a vector space $V$ over $E$ we have that
$$\dim_K V = \dim_E V \cdot [E:K]$$ where $[E:K]$ denotes the degree of the field extension $K \subseteq E$.
This formula makes sense to me. However, since I am not really familiar with field extensions, I tried looking for resources, i.e. a proof of this. I checked my algebra books, but did not find something. So my question is: Has anyone a good resource of this or even a proof? I think it should be not that hard. Since $E$ can be seen as a vector space over $K$, we could write elements out in a basis.

A: HINT: Let $\{v_1,...,v_s\}$ be a basis of $V$ over $E$ and let $\{\lambda_1,...,\lambda_r\}$ be a basis of $E$ over $K$.
Then the set $\{\lambda_iv_j\}_{1\leq i\leq r,1\leq j\leq s}$ is a basis of $V$ over $K$.

A: I'll assume $V$ finite dimensional over $E$ and $E$ a finite field extension of $K$.
If $\dim_E V=0$, the statement is clear. Suppose $\dim_E V\ne0$. Then there is $v\in V$, $v\ne0$. Let $U$ be a complement of $Ev$ (the $E$-subspace generated by $v$). Then
$$
V=Ev\oplus U
$$
Since $Ev\cong E$ as vector spaces over $E$ (and over $K$), $\dim_K Ev=[E:K]$. Since $\dim_E U=\dim_E V-1$, we can apply induction.


text:
Q: .Net Multitargeting with Single File Exe I need to distribute a single file exe built in .Net 3.5 (i.e. 2.0) but that will also run on .Net 4.x.
The executable runs fine without prompting to install .Net if the Foo.exe.config file is there specifying the <supportedRuntime>. But without that file, it asks to install .Net 3.5 (if it's not already installed).
Is there any way to specify the supported runtimes within the exe file, without a .config file? Or is there some other way to bootstrap the app into whatever runtime is available?


text:
Q: Why do i get this ValueError: could not convert string to float: '2.300\xa0%'?

Taux moyen pondéré

2,300%

2,330%

3,134 %

....

df['Taux moyen pondéré']= df["Taux moyen pondéré"].str.replace(',', '.').astype(float)

A: You are just replacing the commas (,) with dots (.) You have to remove the percentage (%) sign also before trying to convert it to a float. A string cannot be converted to a float when it has special characters like the % sign inside it.


text:
Q: joins() and where() request on association with custom table name I have two models
Album.rb
class Album < ActiveRecord::Base
  has_many :tracks
  self.table_name = 'prefix_album'
end

Track.rb
class Track < ActiveRecord::Base
  belongs_to :album
  self.table_name = 'prefix_track'
end

Now, because reasons, the table names are prefixed, so I have prefix_album and prefix_track tables in my database. For basic use, it works fine.
Now the problem with the following query :
Album.joins(:tracks).where(tracks: { id: [10, 15] })

Results in the following SQL :
SELECT * FROM "prefix_albums" INNER JOIN "prefix_tracks" ON "prefix_tracks"."album_id" = "prefix_albums"."id" WHERE "tracks"."id" IN (10, 15)

Which fails because WHERE "tracks"."id" should be WHERE "prefix_tracks"."id". Any idea why active_record is able to get the correct table name for .joins(:tracks) but not for .where(tracks: {}) ?
Anyway I have figured this workout : Album.joins(:tracks).merge(Track.where(id: [10,15])) which gives the same result and works.
But I would like to know why the former didn't work

A: Try it like :
Album.joins(:tracks).where(prefix_tracks: { id: [10, 15] })

You can add table_name to the model like :
class Album < ActiveRecord::Base
  self.table_name = "prefix_album"
end


text:
Q: @media print div: How to solve overlapping page text on pages? I found some answers for this question, but that doesn't apply for my css.
Currently i want to print into A4 landscape. I create each div as a page, which has css and print css as follow:
.page {
    background-color: #FFF;
    margin: 10pt 0pt 10pt 0pt;
    width: 800pt;
    height: 600pt;
    padding: 22pt;
}

and
@media print {
    .page {
        height: 210mm;
        width: 297mm;
        size: A4;
        bottom: 3em;
    }

JSfiddle https://jsfiddle.net/vc5L29m9/
but the divs in each pages overlapping each others and tend to move to the top.
What css am i missing from the div?

A: *

*Move the size property to @page rule.

*Add size: landscape.

*Use the page-break-after property to control page breaks after every page class.
Also added a class to hide elements on print. Do the same for things you don't need. (print button)
Here is the updated Fiddle
CSS
@page {
  size: landscape;
}

@media print {
  .page {
    page-break-after: always
  }
  .no-print {
    display: none;
  }
}


text: Q: Running Hyperledger Composer in multi-org multi-host environment I just finished setting up multi-org in Hyperledger Composer using the official tutorial. But that tutorial deals with only a single host. Now to add another org in another host, what are the changes that I need to incorporate to achieve this? Is there a tutorial for this?


text:
Q: Radial Grid Search Algorithm I'm sure there's a clean way to do this, but I'm probably not using the right keywords for find it.
So let's say I have a grid. Starting from a position on the grid, return all of the grid coordinates that fall within a given distance. So I call something like:
getCoordinates( currentPosition, distance )

And for each coordinate, starting from the initial position, add all cardinal directions, and then add the spaces around those and so forth until the distance is reached. I imagine that on a grid this would look like a diamond. The function would return that array of coordinates. Can someone point me to a routine that will do this efficiently ( I'm working in AS3, for what it's worth )?
In the desired output, iteration 1 would be:
.x.
xxx
.x.

Iteration 2 would be:
..x..
.xxx.
xxxxx
.xxx.
..x..

Iteration 3:
...x...
..xxx..
.xxxxx.
xxxxxxx
.xxxxx.
..xxx..
...x...

and so on...

A: Edit: Updated the algorithm to reflect what the OP wanted.
Iteration 1:
.x.
xxx
.x.

Iteration 2:
..x..
.xxx.
xxxxx
.xxx.
..x..

...
Iteration 4:
....x....
...xxx...
..xxxxx..
.xxxxxxx.
xxxxxxxxx
.xxxxxxx.
..xxxxx..
...xxx...
....x....

Clearly, you can determine the coordinates without iterating.
If the starting point is (X, Y), and the iteration is n
for(int i = x - n; i <= x + n; i++)
{
    for(int j = y - n; j <= y + n; j++)
    {
        int dx = abs(i - x);
        int dy = abs(j - y);
        if(dx + dy <= n) //Produces a diamond, n+1 would produce a diamond with cut corners
        {
            //The point at (i, j) is within the marked area.
        }
    }
}

A: It depends what kind of data structure you're using to represent your grid, but generally a breadth-first search should take care of this for you.

A: BFS + FIFO queue:
P = U = 0;
Q[P] = currentPosition;
D[ Q[P] ] = 0; D[~all the rest~] = infinity (or really any flag, such as -1)

while ( P <= U )
{
  current = Q[P];
  ++P;

  for ( each neighbor N = (X', Y') of (current.X, current.Y) )
    if ( D[N] == inf && D[current] + 1 <= distance )
    {
      D[N] = D[current] + 1;

      ++U;
      Q[U] = N;
    }
}

A: Two possibilities, depending on what kins of distance you want and how much programming you are willing to do:
(1) Dijkstra's algorithm. If you imagine that each two neighboring points on you grid are connected (only vertical and horizontal connections, so each point has 4 neighbors), you'll get your diamond. You don't have to implement any data structure for the graph -- you only need to generate lists of neighbors for current vertex, as you go.
(2) Fast marching. This'll give you true Euclidean distance within the numerical error, so you'll get an approximate circle, not a diamond.

A: For Iteration N, you want all points P' such that distance from P to P' <= N, where distance is |X' - X| + |Y' - Y|.
for (int i = -N; i <= N; i++)
   for (int j = abs(i) - N; j <= N - abs(i); j++)
   {
      results.Add(new Point(X+i, Y+j));
   }
}

return results;

A: I realise this question is 9 years old, but an algorithm that actually iterates radially from the centre (in a diamond) would look like:
for (int mag = 0; mag <= range; ++mag)
    for (int xm = 0; xm <= mag; ++xm)
    {
        int ym = mag - xm;
        int xms = (xm == 0) ? -1 : 1;
        int yms = (ym == 0) ? -1 : 1;
        for (int xs = -1; xs <= xms; xs += 2)
            for (int ys = -1; ys <= yms; ys += 2)
            {
                int x = x_centre + xm * xs;
                int y = y_centre + ym * ys;
                // Do whatever with x, y here
            }
    }


text:
Q: Eliminating Duplicate Records in a DB2 Table How do delete duplicate records in a DB2 table?  I want to be left with a single record for each group of dupes.

A: *

*Create another table "no_dups" that has exactly the same columns as the table you want to eliminate the duplicates from.  (You may want to add an identity column, just to make it easier to identify individual rows).

*Insert into "no_dups", select distinct column1, column2...columnN from the original table.  The "select distinct" should only bring back one row for every duplicate in the original table.  If it doesn't you may have to alter the list of columns or have a closer look at your data, it may look like duplicate data but actually is not.

*When step 2 is done, you will have your original table, and "no_dups" will have all the rows without duplicates.  At this point you can do any number of things - drop and rename tables, or delete all from the original and insert into the original, select * from no_dups.

*If you're running into problems identifying duplicates, and you've added an identity column to "no_dups," you should be able to delete rows one by one using the identity column value.


text:
Q: Python, Qt5 GUI App, and asyncio results in program not closing when window closed I have an application I am working on which has a Qt GUI made to control a gRPC back end.  I prefer using python-betterproto to process the gRPC .proto files, however these classes use asyncio.  After a lot of searching, the only solution I found that allows my Qt Application Class to send signals back and forth between my backend application class was

*

*have my backend class inherit from QtCore.QObject

*use QEventLoop and asyncSlot from asyncqt

*and launch the application as follows

app = QtWidgets.QApplication(sys.argv)
loop = QEventLoop(app)
asyncio.set_event_loop(loop)
window = Ui()
app.exec()
with loop:
    loop.run_forever()

The application is working, and signals can be connected to slots in both directions.  However, when I close the GUI Window, the application is still running, I assume because I told the loop to 'run_forever()'
How can I make this event loop stop listening when the application closes?


text:
Q: iterating through a list of printf I have a list of prinf functions and i want to know how to iterate through them.
#include <stdio.h>

void N()
{
    int count;
    count += count;
}

int main()

{
   int pfReturnCount = 0;

   pfReturnCount = printf("#####.00000000000.......00000...00000#### \n");
   pfReturnCount = printf("#####..000.....000......000000...000.#### \n");
   pfReturnCount = printf("#####..000.....000......000.000..000.#### \n");
   pfReturnCount = printf("#####..0000000000.......000..000.000.#### \n");
   pfReturnCount = printf("#####..000.....000......000...000000.#### \n");
   pfReturnCount = printf("#####..000.....000......000....00000.#### \n");
   pfReturnCount = printf("#####.00000000000......00000...00000.#### \n");

   N(pfReturnCount);
   printf("data value after calling the N funtion is %d\n",pfReturnCount);

   return (0);
}

I got it to give me the value of the first printf but i don't know how to iterate through the whole list so i can sum up the total number of characters i have in all the printf functions.

A: Just replace = with +=
#include <stdio.h>

void N()
{
    int count;
    count += count;
}

int main()

{
   int pfReturnCount = 0;

   pfReturnCount += printf("#####.00000000000.......00000...00000#### \n");
   pfReturnCount += printf("#####..000.....000......000000...000.#### \n");
   pfReturnCount += printf("#####..000.....000......000.000..000.#### \n");
   pfReturnCount += printf("#####..0000000000.......000..000.000.#### \n");
   pfReturnCount += printf("#####..000.....000......000...000000.#### \n");
   pfReturnCount += printf("#####..000.....000......000....00000.#### \n");
   pfReturnCount += printf("#####.00000000000......00000...00000.#### \n");

   N(pfReturnCount);
   printf("data value after calling the N funtion is %d\n",pfReturnCount);

   return (0);
}

A: You can push each line to an array of strings and then simply get the length of each element in the array.


text:
Q: How to locate the webservice Host point This is my first question on the Stackoverflow. I decided to ask this question after spending considerable time on the mentioned matter. I recently joined to a company which develops windows applications. It has a server EXE and a client EXE. The Server EXE communicates with a web service to get the latest updates and user registration information. It uses the following code to test the availability of web services.
private void testWebService()
{
    if (WebServiceClient.IsValidHttpAddress(txtWebserviceURL.Text))
    {
        WebServiceClient svc = new WebServiceClient(new Uri(txtWebserviceURL.Text), txtWebserviceUserName.Text, txtWebservicePassword.Text);

        string response;
        if (svc.CheckWebResponse(new UserEndPoint(), out response))
        {
            //Mark the webservice url as read only again
            txtWebserviceURL.ReadOnly = true;
        }
        MessageBox.Show(response, "Web Service Reponse", MessageBoxButtons.OK, MessageBoxIcon.Information);
    }
    else
        MessageBox.Show(string.Format("URL of '{0}' is invalid.{1}{1}It should start with 'http'.", txtWebserviceURL.Text, System.Environment.NewLine), "Web Service URL", MessageBoxButtons.OK, MessageBoxIcon.Information);
}

When I let the above method to be executed, eventually it calls the following method and returns an exception - "The remote server returned an error: (500) Internal Server Error."
    /// <summary>
    /// Gets a web response from the web service on the required endpoint.
    /// </summary>
    /// <param name="pEndPoint">The endpoint to connect to the web service with.</param>
    /// <returns>The response returned from the web request.</returns>
    private HttpWebResponse GetWebResponse(WebServiceEndPointBase pEndPoint)
    {
        WebRequest fRequest = WebRequest.Create(pEndPoint == null ? this.Url : pEndPoint.GetEndPointUrl(this.Url));
        fRequest.ContentType = "application/json";
        fRequest.Headers.Add("Authorization", "Basic " + this.Credentials);
        fRequest.Method = "GET";
        fRequest.Timeout = this.Timeout;

        HttpWebResponse fResponse = fRequest.GetResponse() as HttpWebResponse;
        return fResponse != null && fResponse.StatusCode == HttpStatusCode.OK ? fResponse : null;
    }

I believe web service is stopped for some reason. As I am new to the company and no information related to the web service is documented, I cannot figure out where the web service is hosted. The web service name is "http://services.mycomanyname.com.au".
What I did so far.

*

*I checked all the servers (windows) that belong to our company and
checked each IIS server, I couldn't find any hosted service.

*I used the 'dig' command to find more information. I was able to find
the related IP address to the service, but when I was trying to
retrieve the Hostname from the IP address, it did not return any
name.
What I want

*

*Please advise me to find the location where the web service is hosted. Asking from existing staff is not an option for me at the moment.

*Please guide me to obtain the cause of the 500 error.


text:
Q: split string into groups with given condition Given a String only made of only 2 letters a,b. Now the task is to split this string into exactly 3 groups such that the number of a's in each group must be same. Then find how many such groups are possible.
Example:
Input:
ababab

Possiblities:
ab ab ab

Output:
1 as we can create only 1 such group, with single a in each group

Example:
Input:
ababbabbaaba

Possiblities:

aba bbabba aba
abab babba aba
ababb abba aba

Output:3
as we can create 3 such possible groups with 2 a's in each group.

Now I came across below code that is solving this task.
public static int findGroups(String input) {
    int numberOfAs = 0;
    for (int i = 0; i < input.length(); i++) {
        if (input.charAt(i) == 'a')
            numberOfAs++;
    }
    int n = input.length();
    if (numberOfAs == 0) {
        return (n - 1) * (n - 2) / 2;
    }

    if (numberOfAs % 3 != 0)
        return 0;

    int numberOfAsInAGroup = numberOfAs / 3;

    int lastAIn1stGroup = 0; // last occurrence of A in 1st group
    int firstAIn2ndGroup = 0; // 1st occurrence of A in 2nd group
    int lastAIn2ndGroup = 0; // last occurrence of A in 2nd group
    int firstAIn3rdGroup = 0; // 1st occurrence of A in 3rd group
    int aCount = 0;
    for (int i = 0; i < n; i++) {
        if (input.charAt(i) == 'a') {
            aCount++;
            if (aCount == numberOfAsInAGroup) {
                lastAIn1stGroup = i;
            } else if (aCount == numberOfAsInAGroup + 1) {
                firstAIn2ndGroup = i;
            }
            if (aCount == 2 * numberOfAsInAGroup) {
                lastAIn2ndGroup = i;
            } else if (aCount == 2 * numberOfAsInAGroup + 1) {
                firstAIn3rdGroup = i;
                break;
            }
        }
    }

    int betweenSecondAndFirstGroup = firstAIn2ndGroup - lastAIn1stGroup;
    int betweenThirdAndSecondGroup = firstAIn3rdGroup - lastAIn2ndGroup;

    return betweenSecondAndFirstGroup * betweenThirdAndSecondGroup;
}

This code is working perfectly finw without any errors. But I am trying to understand for past several days what formulas are being used in this code to solve this task.
Part - 1:
    if (numberOfAs == 0) {
        return (n - 1) * (n - 2) / 2;
    }

After searching in google for several hrs I found the explanation here  - number-of-ways-of-distributing-n-identical-objects-among-r-groups:
Part - 2:
    int betweenSecondAndFirstGroup = firstAIn2ndGroup - lastAIn1stGroup;
    int betweenThirdAndSecondGroup = firstAIn3rdGroup - lastAIn2ndGroup;

    return betweenSecondAndFirstGroup * betweenThirdAndSecondGroup;

I am not able to understand this part 2 formula, how this is solving the given problem, is there any explanation as mentioned for part 1.
Also just curious to know, is there any alternate version to solve this task without using formulas like this?

A: It can be done in linear time.
public class Main {

    public static int Nth_A_After(String s, int n, int index){
        for(int i = index + 1; i < s.length(); i++) {
            if(s.charAt(i) == 'a'){
                n--;
                if(n == 0) return i;
            }
        }
        return -1;
    }
    public static void main(String[] args) {
        String s = "ababab";

        int count = 0;

        for(int i = 0; i < s.length(); i++) if(s.charAt(i) == 'a') count++;

        if(count % 3 != 0) {
            System.out.println("Impossible!");
            return;
        }

        int pos = count / 3;

        int firstEnd = Nth_A_After(s, pos, -1);
        int secondBegin = Nth_A_After(s, 1, firstEnd);
        int secondEnd = Nth_A_After(s, pos - 1, secondBegin);
        int thirdBegin = Nth_A_After(s, 1, secondEnd);

        int leftDif = secondBegin - firstEnd;
        int rightDif = thirdBegin - secondEnd;
        if(leftDif > 1) leftDif++;
        if(rightDif > 1) rightDif++;

        System.out.println(leftDif * rightDif);
    }
}

I guess there is a problem in your example ababab, since there is more than just one possibility:
1. a ba bab
2. a bab ab
3. ab a bab
4. ab ab ab

A: The code you're looking at is finding the boundary As of each group, then is counting the number of spaces the dividing line between the groups could go. This depends on the number of Bs separating the groups of As, since these don't affect the count.
The answer is the number of possible dividing lines on the left, times the number on the right.
AA|B|B|AABAA <-- in this example there are 3 on the left
AABBAA|B|AA <-- and 2 on the right
for a total of 6.

AA|BBAA|BAA
AA|BBAAB|AA
AAB|BAA|BAA
AAB|BAAB|AA
AABB|AA|BAA
AABB|AAB|AA


text:
Q: How to manage the sections of a website with Django? am a newbie in Django, and am developing my first website with this framework. Is it correct to make one app for each section (home, about, contact), or I have to make one app that contains ALL the website?
Thanks in advance

A: It's a bit of an art to determine how to split up a Django project, and you likely won't get it right the first time. Without knowing more about the actual functionality of your site it's a bit hard to tell.
If each one of these sections has its own custom functionality, I'd put them in separate applications. As the functionality of each section grows (e.g. you may end up with a few views for your contact section, which'd warrant its own app), you won't end up with unwieldy views or models modules, which is what happens when you try to put everything in the one app.
If one of these sections is just a standard content page, consider using the flatpages app as it may save you a lot of time.
As I said, this is something that'll just get easier with time. You will get a feel for how much code is required for certain pieces of functionality, and get a feel for what is a manageable / unmanageable amount of code, and 'naturally' split your projects up accordingly.


text:
Q: Oracle dynamic cursor in for in loop I have a procedure that have to select from different tables according to a input parameter. Input parameter select the table I have to query. Actually I have a static situation.
CURSOR c IS SELECT ... FROM TBL;
BEGIN
FOR idx IN c LOOP
....
END LOOP;

Is there a way to change cursor query definition at run time


text:
Q: Why does using headerReferenceSize with self-sizing cells in a collection view cause a crash in iOS 8? I managed to figure out the approach for self-sizing collection view cells under iOS 8.
I want to do this as a part of a accessory view.
I get a crash ... the interesting part of the stacktrace is as follows:
** Terminating app due to uncaught exception 'NSInvalidArgumentException', reason: '*** -[__NSArrayM insertObject:atIndex:]: object cannot be nil'
*** First throw call stack:
(
  0   CoreFoundation    __exceptionPreprocess + 165
  1   libobjc.A.dylib   objc_exception_throw + 45
  2   CoreFoundation    -[__NSArrayM insertObject:atIndex:] + 954
  3   UIKit             -[UICollectionViewFlowLayout layoutAttributesForElementsInRect:] + 384
  4   UIKit             __45-[UICollectionViewData validateLayoutInRect:]_block_invoke + 144
  5   UIKit             -[UICollectionViewData validateLayoutInRect:] + 1396
  6   UIKit             -[UICollectionView layoutSubviews] + 170
  7   UIKit             -[UIView(CALayerDelegate) layoutSublayersOfLayer:] + 521
  8   QuartzCore        -[CALayer layoutSublayers] + 150
  9   QuartzCore        _ZN2CA5Layer16layout_if_neededEPNS_11TransactionE + 380
  10  UIKit             -[UIView(Hierarchy) layoutBelowIfNeeded] + 611
  11  UIKit             -[UIInputSetHostView layoutIfNeeded] + 105
  12  UIKit             __43-[UIInputWindowController setInputViewSet:]_block_invoke + 112
  13  UIKit             +[UIView(Animation) performWithoutAnimation:] + 65
  14  UIKit             -[UIInputWindowController setInputViewSet:] + 291
  15  UIKit             -[UIInputWindowController performOperations:withAnimationStyle:] + 50
  16  UIKit             -[UIPeripheralHost(UIKitInternal) setInputViews:animationStyle:] + 1054
  17  UIKit             -[UIResponder becomeFirstResponder] + 468
  18  UIKit             -[UIView(Hierarchy) becomeFirstResponder] + 99
  19  UIKit             -[UITextView becomeFirstResponder] + 75
  ...

This looks like an Apple bug. Why does the layout seem to return an empty layout attribute?

A: The best idea I have so far is based on this repository: https://github.com/algal/SelfSizingCellsDemo
On line 50 of ViewController.swift we have label.preferredMaxLayoutWidth = 320 which produces a cell that fills the whole screen and wraps the lines if there is enough text. This would need to be changed to fit whatever size screen you are working with. Then after each section you would need to add enough text to fill that label like is done on line 20 let items = smallitems.componentsSeparatedByString(" ") + [onelongitem]
The problem with this approach is that I don't yet know how I would put different views in that cell, besides text. This might work enough for your situation though.


text:
Q: Show first 10 letters from a string variable I have a variable. I want to show 10 letter from there.
$msg = "Hello World! How are you.";

I want to show only Hello Worl this(first 10 letters).

A: You need to use the substr() function
echo substr($msg, 0, 10);


text:
Q: activiti - service task was frozen I've a instance of workflow, but it freeze at service task. The class which handle for service task just do simple process (sure that don't have  infinite loop). It seem my JavaDelegate class wasn't called.
Any ideas about root cause?


text:
Q: Checked property is not accessible in asp.net I want to access "Checked" property against a checkbox control in GridView, please see my aspx page code below firstly:
<asp:GridView ID="GridView1" runat="server" AutoGenerateColumns="False">
    <Columns>
    <asp:TemplateField>
        <HeaderTemplate>
        <asp:CheckBox ID="cbDeleteAll" runat="server" OnCheckedChanged="cbDeleteAll_CheckedChanged" />
        </HeaderTemplate>
        <ItemTemplate>
        <asp:CheckBox ID="cbDelete" runat="server" OnCheckedChanged="cbDelete_CheckedChanged" />
        </ItemTemplate>
    </asp:TemplateField>
    <asp:TemplateField HeaderText="Employee ID">
        <ItemTemplate>
        <asp:Label ID="lblEmpId" runat="server" Text='<%# Bind("DeptID") %>'></asp:Label>
        </ItemTemplate>
    </asp:TemplateField>
    <asp:BoundField DataField="EmployeeName" HeaderText="Employee Name" />
    <asp:BoundField DataField="DeptID" HeaderText="Department" />
    </Columns>
</asp:GridView>

in the "cbDeleteAll_CheckedChanged" event, I would like to see the Checked property on the header template and set value to Checked property to checkboxes in the item template, see below:

as you can see, there is a red wave line under "Checked" property, when I rebuild the solution, I can see the error message as below:

so, I was totally confused I don't know why I cannot access this property in the code?
can anyone help me or give me some instructions?

A: Look at the error. It says WebApplication1.CheckBox. It appears you have a CheckBox class in your app and therefore you're casting to the wrong type. Don't name your classes the same thing as something built into the framework.
To find the offending file put your cursor over CheckBox in your class and press Function 12 or right click it and select Go To Definition. Then right click that class and rename it something more appropriate.
The correct CheckBox class is in System.Web.UI.WebControls namespace.


text:
Q: Does getting hit by a gravitational wave hurt? Recently a paper in Nature about 2 black holes PG 1302-102 merging and causing a supernova 100 million times more powerful than common ones got me thinking.
How much damage do  gravitational waves do and how close would someone have to be to the source for it to hurt them? or would you not feel a thing from it?
(The link given in comments does not answer whether a gravitational wave would do any damage or whether you would feel it. It does not cover how big a collision would have to be and how far away you would have to be to feel it. What you would feel and how the wave would interact with your body to cause the feeling.
There is a +100 bounty still on the question so I assume it has not been answered)

A: The bounty on the link that @KyleKanos provided (physics.stackexchange.com/q/168274) was awarded because the answer is correct. It gives information about how close you'd need to be to detect the distortion with human senses.  At what point it "hurts" I think is not clear - How much can we stretch you before it hurts?  That's not just a question of physics.
What is true and related, is that we believe that we're constantly exposed to gravitational waves passing by.  As in the answer at the link provided, these waves are very weak by the time that they reach us and therefore have no noticeable effect of any type on "ordinary" human scales.  What effect there is manifests as an alternating compression and stretching of your body.  In theory, if you were close enough, this would hurt and if you were closer still it would rip you apart.  Again, these effects are very small at any reasonable distance for any reasonable sized event generating gravitational waves.


text:
Q: how to fix the following error : undefined method `PUT' for # in rails 3.2? I am currently trying to create a shopping cart for my rails application and once populated my cart should be saved in the session.
Everytime i try to run the server to test if working or not, it seems my routes are not working at all...
See below my routes.rb, my cart controller and my index.
Any help will be appreciated.
routes.rb
    Sewingsupplies::Application.routes.draw do
  get "cart/index"

  get "cart/success"

  PUT "/cart/:id" => "cart#add"
  DELETE "/cart/:id" => "cart#remove"
  DELETE "/cart" => "cart#clear"
  POST "/cart/checkout"

  devise_for :admins

  resources :catalogues

  devise_for :users

cart controller
      def index
        sessions[:cart] = {}
        render 'cart/index'
      end

      def success
      end

      def add

        @catalogue = Catalogue.find(params[:id])
        cart = sessions[:cart]
        cart = {:catalogue => @catalogue.name,category => @catalogue.category, :code => @catalogue.code , :colour=> @catalogue.colour, :description => @catalogue.description, :image  => @catalogue.image , :unitprice => += @catalogue.unitprice, :unitquantity => +=1, :unitweight => += @catalogue.unitweight }
        sessions[:cart] = cart
        render 'cart/add'
      end
end

and my index page

Listing catalogues

    Name
    Code
    Category
    Description
    Unitprice
    Unitquantity
    Unitweight
    Colour
    Image
    User

<% @catalogues.each do |catalogue| %>

    <%= catalogue.name %>
    <%= catalogue.code %>
    <%= catalogue.category %>
    <%= catalogue.description %>
    <%= catalogue.unitprice %>
    <%= catalogue.unitquantity %>
    <%= catalogue.unitweight %>
    <%= catalogue.colour %>
    <%= image_tag(catalogue.image, :width => 150) if catalogue.image.present?%>
    <%= catalogue.user.email %>
    <%= link_to 'Show', catalogue %>
    <%= link_to 'Edit', edit_catalogue_path(catalogue) %>
    <%= link_to 'Destroy', catalogue, method: :delete, data: { confirm: 'Are you sure?' } %>
    <%= link_to "Add to cart", controller: "cart", action: "add", id: @catalogue.id, method: :post %>

<% end %>

<%= link_to "View cart", controller: "cart", action: "index" %>

<%= link_to 'New Catalogue', new_catalogue_path %>

A: In your routes.rb file you have defined the routes with PUT and DELETE in uppercase. Define the routes in lowercase like put and delete as these are methods of ActionDispatch::Routing::Mapper class which are called to setup routes for your application. As ruby is case sensitive you need to call the method with correct case.


text:
Q: cURL an API in python and return the response as JSON I'm learning Python and try to use it in my class project. I'm looking for a way to curl an API and return the response json. For example, the response after curling an API is JSON and how can I return it also as JSON
        response = requests.get("https://github.com/timeline.json")
        response = response.content

return response doesn't return it in json while return with jsonify(reponse) get this error (Object of type bytes is not JSON serializable).
Sorry for my English.

A: response = requests.get("https://github.com/timeline.json")
response_json = response.json()
print(response_json["message"])
print(response_json["documentation_url"])

The method json() returns the json-encoded content of a response as a dict. Additionally, you may want to use the new API at https://api.github.com/events (docs).


text:
Q: Android: How to set private MutableLiveData in unit test I am trying to test my viewmodel by writing some unit tests. My problem is that I can't achieve my goals, without setting some values for the MutableLiveData manually (in production they are set via databinding). The problem here is that my MutableLiveData is (obviously) private and therefore I can't set the value by writing mutablelivedata.value = "Some Value" in my unit test.
I've read some articles and some say that I just should expose my MutableLiveData by writing a custom setter like:
private val _myMutableLiveData = MutableLiveData<String>()
val myPublicLiveData: LiveData<String> get() = _myMutableLiveData

// setter
fun setStringForLiveData(value: String) {
   _myMutableLiveData.value = value
}

Here comes my question: WHAT is the point of setting the MutableLiveData to private but exposing the setter with a custom setStringForLiveData(value: String) and the getter with myPublicLiveData. I mean when I expose both the getter and setter of my private field why shouldn't I just make it public?
Here is my current approach to test my MutableLiveData (I don't know if this makes any sense or even works)
@Test
fun `first shipping text should be set correctly`() {
   (viewModel.secondDropDownVisibility as MutableLiveData<Boolean>).value = false
   (viewModel.shippingFirstDdText as MutableLiveData<String>).value = "Toast"
    assertEquals("Toast", viewModel.decideShippingTextOne())
}

I hope there is a better way than writing a custom setter for every mutablelivedata (I have over 20 and this is just ugly boilerplate code). Maybe I have misunderstood something here.
Please bear in mind that I am rather new to Android Development and the concept of MVVM and especially Livedata.
I appreciate every help, thank you!

A: Okay, this may not be the best answer, but this works for me. At this point, I don't really care about "oh no, but this is not right in android programming" or "but you shouldn't do that in unit testing". The test cases work and that's all I need.
@Test
fun `first shipping text should be set correctly`() {
   (viewModel.secondDropDownVisibility as MutableLiveData<Boolean>).value = false
   (viewModel.shippingFirstDdText as MutableLiveData<String>).value = "Toast"
    assertEquals("Toast", viewModel.decideShippingTextOne())
}

I have two private field _secondDropDownVisibility and _shippingFirstDdText of type MutableLiveData<T> and two public fields secondDropDownVisibility and shippingFirstDdText of type LiveData<T>
Cheers

A: private val _myMutableLiveData = MutableLiveData<String>()
val myPublicLiveData: LiveData<String> get() = _myMutableLiveData

// setter
fun setStringForLiveData(value: String) {
   _myMutableLiveData.value = value
}

Sorry but this code just doesn't make sense. If you absolutely need to go this way, then there is no need to go with the double fields as you are exposing the mutable state anyway.
That being say I´d argue that you need resort to this and its usually a code smell. I cant see your whole view model but I´d assume you have a public function ( or some init code ) that triggers some work and it pushes data to the live data, and that's what you have to test instead. If you want to upload your full view model I could try to suggest the testing approach by updating the answer. Cheers!

A: You should just make the MutableLiveData public as is if you need to modify it from outside (without any additional guarantees made to the methods).
If you had been using Databinding, you'd be exposing ObservableField, which is also read/writeable.


text:
Q: Typescript: Why doesn't my code compile if a property value comes from a nested object? I apologize for the poor title, but I don't have the vocabulary to word it better. Let me show you my code:
type Foo = "bar" | "baz";

type Consistency  = {
    [K in Foo]: {
        foo: K;
        fooTemplate: `${K} in a template`;
    }
}[Foo]

// I want this to compile (and it does)
const valid1: Consistency = {
    foo: "bar",
    fooTemplate: "bar in a template",
}

const valid2: Consistency = {
    foo: "baz",
    fooTemplate: "baz in a template",
}

export const anFoo: Foo = "bar"

const valid3: Consistency = {
    foo: anFoo,
    fooTemplate: `${anFoo} in a template` as const
}

export interface MyObj {
  temporary: {
    myProperty: Foo;
  };
}
const state: MyObj = {
    temporary: {
        myProperty: "bar"
    }
}
const i: Foo = state.temporary.myProperty;
const valid4: Consistency = { // Why doesn't this one compile????
    foo: i,
    fooTemplate: `${i} in a template` as const
}

// I don't want this to compile (and it doesn't)
const invalid1: Consistency = {
    foo: "bar",
    fooTemplate: "baz in a template",
}

const invalid2: Consistency = {
    foo: "baz",
    fooTemplate: "bar in a template",
}

You can play with this here. This all works the way I expect accept for valid4. For some reason, valid4 doesn't compile, and I want it to.  Why isn't it compiling and how do I make it compile?

The answer doesn't explicitly say this so I will: There's no solution to this problem.

A: I believe the answer is this, but maybe Jcalz can correct me.
Unions of "A" | "B" actually have 3 assignability's.
"A" is assignable.
"B" is assignable.
And "A" | "B" is assignable
Its this third case that breaks valid4.
At a value level this is impossible, but at a type level its possible that its both "bar" | "baz" and therefore it thinks...
{foo: "baz", fooTemplate: "bar as template"}

is possible.
As for valid3, this is because Typescript compiler can detect you've hardcoded the value there and therefore even though you're asserting "Foo" the actual type it considers that is "bar"


text:
Q: og:description warning I have just tried to connect my programming joke blog to Facebook via the OpenGraph API. However when I check using the developer debug tool, it gives a warning:
Objects of this type do not allow properties named 'fb:description'

and
The parser's result for this metadata did not match the input metadata. Likely, this was caused by the data being ordered in an unexpected way, multiple values being given for a property only expecting a single value, or property values for a given property being mismatched. Here are the input properties that were not seen in the parsed result: 'fb:description'

If I inversely remove this property, it tells me I should explicitly define it. Is this warning going to cause me problems?

A: <meta property="fb:description" content="For all those people who know what C is but can still remember what fun is">
Should be
<meta property="og:description" content="For all those people who know what C is but can still remember what fun is">
The key part being og:description


text:
Q: How to add Ivy to Ant dynamically Typically, to make Ivy tasks available to an Ant build, you need to:

*

*Add ivy.jar to ${ANT_HOME}/lib.

*Add an xmlns:ivy="antlib:org.apache.ivy.ant" declaration to your build.xml's <project> element.

*Add a <taskdef> declaration inside build.xml that reference's the ivy.jar's antlib.xml file where all other tasks are defined.

I'd like to accomplish all of the above except the first step (adding ivy.jar to ${ANT_HOME}/lib). I'd like to have ivy.jar living somewhere inside my project, say, at lib/buildtime/ivy.jar, and somehow reference lib/buildtime/ivy.jar as where Ivy is located.
Is this possible? If so, how? If not, why? Thanks in advance!

A: The taskdef (step 3) is not required if the ivy jar is located in a standard ANT library directory.
I would recommend including a special "bootstrap" target that will install the ivy jar. Once this is done all other dependencies (including 3rd party ANT tasks) can be downloaded by ivy as a build dependency.
Here is my default build file that demonstrates the concept:
<project name="demo" default="resolve" xmlns:ivy="antlib:org.apache.ivy.ant">

    <target name="bootstrap" description="Install ivy">
        <mkdir dir="${user.home}/.ant/lib"/>
        <get dest="${user.home}/.ant/lib/ivy.jar" src="http://search.maven.org/remotecontent?filepath=org/apache/ivy/ivy/2.3.0/ivy-2.3.0.jar"/>
    </target>

    <target name="resolve" description="Use ivy to resolve classpaths">
        <ivy:resolve/>

        <ivy:report todir='build/ivy-reports' graph='false' xml='false'/>

        <ivy:cachepath pathid="compile.path" conf="compile"/>
        <ivy:cachepath pathid="test.path"    conf="test"/>
    </target>

    <target name="clean" description="Cleanup build files">
        <delete dir="build"/>
    </target>

    <target name="clean-all" depends="clean" description="Additionally purge ivy cache">
        <ivy:cleancache/>
    </target>

</project>

Notes:

*

*The "bootstrap" target only needs to be run once on a new development environment. Once installed the ivy jar is available to all future ANT runs.

*This example doesn't use "$ANT_HOME/lib" (which you may not have write permissions for). Instead it uses the lesser known "$HOME/.ant/lib" directory which serves the same purpose.


text:
Q: ASP.NET Routing I have sucesfully implemented url routing in my web app, the one task is not complete.
I would like to route all request from
http://www.mydomain.com/?curl=http://www.google.com
to
http://www.mydomain.com/convert.aspx?curl=http://www.google.com
How to do that?

A: One way would be to handle the curl parameter in your Default.aspx page.

A: Could you not just get the query string from url and then do a redirect?


text:
Q: Filtering timestamps that happened within 5 minutes of each other. I'm trying to find glucose results for samples that were done within the last five minutes and filter them out. Below is my PostgreSQL Code and it's output.
SELECT date
       , blood_glucose
       , extract(epoch from date - lag(date) OVER(ORDER BY date))/60
FROM glucose
ORDER BY DATE

date               |glucose|minutes since last
----------------------------------------------
2017-10-02 08:05:00|183    |681
2017-10-04 08:19:00|275    |2894
2017-10-05 08:03:00|273    |1424
2017-10-05 08:03:00|294    |0
2017-10-05 08:04:00|277    |1
2017-10-05 18:19:00|187    |615
2017-10-09 21:26:00|190    |5947

I'm trying to get a result as such:
date               |glucose|minutes since last
----------------------------------------------
2017-10-05 08:03:00|273    |1424
2017-10-05 08:03:00|294    |0
2017-10-05 08:04:00|277    |1

I want to get all tests that happened within 5 mins. Not sure how I can contain the first one in this case the very first row with glucose level 273.

A: this below sql produces three rows which i think is what you want. It returns any record that had a previous record occurring within 5 minutes, or the next record occurring within 5 minutes.  This is for sqlserver so may not be like for like with postgresql
2017-10-05 08:03:00 294 -1424   0
2017-10-05 08:03:00 273 0   1
2017-10-05 08:04:00 277 -1  615
with dat as
(
select '2017-10-02 08:05:00' t,183 g union all
select '2017-10-04 08:19:00',275 union all
select '2017-10-05 08:03:00',273 union all
select '2017-10-05 08:03:00',294 union all
select '2017-10-05 08:04:00',277 union all
select '2017-10-05 18:19:00',187 union all
select '2017-10-09 21:26:00',190
)
select * from
(
    select dat.t,
           g,
           datediff(mi,t,lag (t,1) over (order by t)) timeprev,
           datediff(mi,t,lead (t,1) over (order by t)) timenext
    from   dat
) x
where timeprev >=-5 or timenext <=5

A: You seem to want sequences with more than one element where the difference is less than 5 between any two adjacent elements.
You can do this using lag() to identify where the sequences start, then a cumulative sum to identify the sequences, and finally window functions for the length of the sequence.
with g as (
      select g.*,
             extract(epoch from date - lag(date) over (order by date)) / 60 as minutes_since_last
      from glucose g
     ),
     gg as (
      select g.*, sum( (minutes_since_last <= 5)::int) over (order by date) as grp
      from g
     ),
     ggg as (
      select gg.*, count(*) over (partition by grp) as cnt
      from gg
     )
select ggg.*
from ggg
where cnt > 1
order by date;


text:
Q: using .split() to take out and modify certain parts of a string, modifying and displaying them differently JavaScript I want to split the 'Example Response' and 'Example Request' from a response I'm getting in a markdown file, and want to display them in h3 tags on my html page, but I don't know how I can .split() using JavaScript because I can't write a script to delete a certain number of characters ahead since there will be other responses that will be different.
Example Request:
https://somelink.com/
Example Response:
{
  head: { .... },
  data: [
    {
      blah: "bl4h, blah, bl4h"
    }
  ]
}

A: I think you don't want to split the response (at the position of e.g. Example Request) but select different parts of it and show them differently. A great use case for Regular Expressions.

function parse(raw) {
  var elements = raw.match(/(.|[\r\n])*(Example Request)((.|[\r\n])*)(Example Response)((.|[\r\n])*)/i).slice(2);
  console.log(elements);
  return '
' + elements[0] + '

' + elements[1] + '

' + elements[3] + '

' + elements[4] + '
';
}

document.getElementById('action').addEventListener('click', function() {
  var raw = document.getElementById('text').value;
  document.getElementById('result').innerHTML = parse(raw);
});
textarea { display: block; width: 100%; height: 5em; }
<textarea id="text"></textarea><button id="action">render</button>

It's actually quite tricky. You have to match newlines as well ((.|[\r\n])), this generates unnecessary groups (the jump from elements[1] to elements[3]). See this as a first hint, there are lot things that should never make it into productive code.


text:
Q: Signing ClickOnce with a certificate? What is the process of obtaining a certificate to sign my ClickOnce assembly(ies)?
I've got a few ClickOnce applications at my company, but they are all signed with temporary certificates created by Visual Studio. Those are obviously not Trusted Root Authorities nor Trusted Publishers. I've followed along the article Configuring ClickOnce Trusted Publishers, and I like the experience when something is signed with a certificate that is both a Trusted Root Authority and Trusted Publisher (that is, no prompt, just an install).

*

*Can I use the same certificate to sign multiple ClickOnce assemblies?

*How much does a certificate cost?

*What information do I need to provide when obtaining the certificate?

*Does the certificate need to be aware of where the publishing location is? For example, if I currently have my ClickOnce applications available from http://apps.mycompany.com/ and I want to change this later, for example http://www.mycompany.com/apps or http://apps.mysubcompany.com, will I have to obtain another certificate?

*Are there recommended publishers to obtain from for ClickOnce signing (for example, someone who might already be in an Windows XP, Windows Vista, or Windows 7 Trusted Root Authority store)?

*How can I streamline installation to the Trusted Publisher store?

A: I had to work through the signed ClickOnce recently. It was not the most smooth experience, but once this has been done (and wired to the automated publishing) it started working like a marvel. Here's the actual product, if you are interested in the behavior: Forecasting Add-in for Excel.
Article on ClickOnce Manifest Signing and Strong-Name Assembly Signing was a good start.

Can I use the same certificate to sign multiple ClickOnce assemblies?

Yes.

How much does a certificate cost?

Tucows offers certificates for 75$, but the process is rather slow.

What information do I need to provide when obtaining the certificate?

They check your documents (e.g. a scan of your certificate of incorporation), check your whois record and things like this.

Does the certificate need to be aware of where the publishing location is?

This was not needed in our case.

A: I have a code signing certificate from Thawte, and it has worked very well (once I got the signing procedure figured out...)

*

*It costs US$299 per year (Microsoft Authenticode (Multi-Purpose) Certificate)

*Thawte is already a trusted root in Windows so for clients it works fine. (I had to install extra root certificates on the signing machine, though.)
You are welcome to check out our app at http://www.ludesi.com/download.


text:
Q: Using sed to align text starting from pattern to end of line I have a text like this:
    LDX LEVEL
    LDA INITD015,X       ; INITIAL ACTIVE SPRITES
    STA $D015
    STA SAVED015
    LDA INITXPOS,X      ; INITIAL HERO X COORDINATE
    STA XPOS
    LDA INITYPOS,X               ; INITIAL HERO Y COORDINATE
    STA YPOS
    LDA INITXPOSMUM,X            ; INITIAL MUMMY X COORDINATE
    STA XPOSMUM
    LDA LEVEL
    BNE NOTLOADENDELEMENTS
    LDA FLAGLOSELIFE
    BNE NOTLOADENDELEMENTS
;    LDX #<BIGELEMENTSFILE  ; LOW BYTE
;    LDY #>BIGELEMENTSFILE ; HI BYTE
;    JSR LOADFILE_EXOMIZER

where i need to align text starting at ";" that IS NOT first char of a line, to end of line, at char number 41 of the line.
Lines starting with ";" must be untouched until (and if) the second ";" is ecountred, then staring from second ";" to end of line should be aligned at char 41.
Maybe the second ";" is before or after char 41.
Can be this achieved using SED or AWK?

A: How about perl?
perl -pe 's/^(.+?)(?=;)/$1 . " "x(41-length($1))/e' file

    LDX LEVEL
    LDA INITD015,X                       ; INITIAL ACTIVE SPRITES
    STA $D015
    STA SAVED015
    LDA INITXPOS,X                       ; INITIAL HERO X COORDINATE
    STA XPOS
    LDA INITYPOS,X                       ; INITIAL HERO Y COORDINATE
    STA YPOS
    LDA INITXPOSMUM,X                    ; INITIAL MUMMY X COORDINATE
    STA XPOSMUM
    LDA LEVEL
    BNE NOTLOADENDELEMENTS
    LDA FLAGLOSELIFE
    BNE NOTLOADENDELEMENTS
;    LDX #<BIGELEMENTSFILE               ; LOW BYTE
;    LDY #>BIGELEMENTSFILE               ; HI BYTE
;    JSR LOADFILE_EXOMIZER

awk
awk '
    (p=index(substr($0,2), ";")) > 0 {
        printf "%-40s%s\n", substr($0,1,p), substr($0,p)
        next
    }
    {print}
' file


text:
Q: Is this an example of ellipsis? '... , only a glimmer of the moon.'
There wasn't much light, only a glimmer of the moon.

In this sentence, is the highlighted part an example of ellipsis? Could we expand this to the following sentence?

There wasn't much light, as there was only a glimmer of the moon.

In English, we don't talk like robots, so it's not uncommon to encounter such constructions. However, these types of sentences always confuse me when I try to break them down in terms of grammar.
Consider these other examples:

He hated spirits, especially vodka.

The company had expanded its operations to overseas territories, namely Japan and the US.

A: This is an ellipsis, but the expanded sentence is not the one you give. The expanded sentence is

There wasn't much light, [there was] only the glimmer of the moon.

For your other examples, you would expand them as:

He hated spirits, [he] especially [hated] vodka.

and

The company had expanded its operations to overseas territories, namely [it had expanded its operations to] Japan and the US.

In English, you generally expand ellipses with elements that are already in the sentence. In your first example, adding the as in

[as there was] only the glimmer of the moon,

is incorrect, as there wasn't an "as" already in the sentence, even though the meaning of both expansions is essentially the same.

A: Ellipsis is not a term much used in modern syntax or grammar. It's not nearly specific enough, since it refers only to something being "left out" of the sentence, without specifying what it was, where it was, how big it was, or why it got left out. Linguists don't use it because it's handwaving, using a general term for a lot of different phenomena.
There are dozens of rules that could be (and often are) called "ellipses", but modern syntax requires specifics of each deletion type and the conditions it obtains under. For instance, the absence of you in

*

*Get out of here!
can be called "ellipsis", but it's an ellipsis that (a) only occurs in imperatives and (b) only occurs with second-person subjects. It's not just any old ellipsis; it has constraints. They all do.
There's Conversational Deletion, which produces

*

*Ever been to Miami?

*Not exactly what I was hoping for.
under certain circumstances. Under other circumstances, Whiz- Deletion omits a Wh- word (or that) subject, and its following be auxiliary from a relative clause, converting, for instance,

*

*the man who was standing there to the man standing there, and

*the book that is on the landing to the book on the landing.
Or there is rule-based deletion of individual function words like to-deletion that is obligatory with modal auxiliaries and sense verbs

*

**They may/should/can/must to arrive at 5, but They may/should/can/must arrive at 5.

**I saw/heard/felt him to slam the door, but I saw/heard/felt him slam the door.
or the for that often occurs along with to in infinitives

*

*For him to say such a thing is surprising.

*They didn't expect (for) him to say such a thing
... and so on. You can find lots more in this list of English transformational rules.


text:
Q: GWT style code splitting in Flex I do a lot of work with GWT but don't have experience of Flex. I was talking to a guy today who was looking at moving some large Flex based applications to GWT due to the Flex application getting too big and using too much memory in the browser. This is a problem I have had before with GWT - browser apps using lots of memory as all the code gets loaded when it starts.
However, in GWT 2.0 there is now a code splitting feature to overcome the problem of the client code getting too big. This allows all the code (javascript) not to be loaded as one big file on start up but instead code split into different files that can be loaded when required.
I was thinking as to if there is anything similar in Flex. I assume the Flex application code all lives in one single SWF file which loads at start-up so this approach is not possible but thought there might be other solutions.

A: You might want to look into Modules. Otherwise the code is in one SWF. You can also move the Flex framework code out of yur SWF. And you can always dynamically load your resources such as images.


text:
Q: How to explain this construct in typescript? I am learning ts, and I have stumbled upon this piece of code
export const Field:<T> (x:T) => T;

I can't wrap my head around it.
It does look like the function definition below
type myFunction<T> = (x: T) => T

so I would see it as anonymous type definition but am I correct, how to use it?

A: This:
<T>(x: T) => T

Is the type of an identity function. It uses a generic type parameter T set by the type of the argument x, and returns an object of type T. Or more simply, it returns the type that it received as an argument.
The javascript implementation would be simply:
(x) => x

To implement that type in Typescript, you might do:
const fn: Field = <T>(x: T) => x

Playground


text:
Q: cookies not being deleted I have a basic login system. The basic login / logout functions are as follows:
function login() {
    global $page;

    if ($_COOKIE['adminUser'] == adminUser && $_COOKIE['adminPass'] == adminPass):
        $_SESSION['adminLogin'] = true;
        redirect($_SERVER['REQUEST_URI']);
    elseif ($_POST['adminUser'] == adminUser && $_POST['adminPass'] == adminPass):
        setcookie('adminUser', $_POST['adminUser'], time() + 60 * 60 * 24 * 7);
        setcookie('adminPass', $_POST['adminPass'], time() + 60 * 60 * 24 * 7);
        $_SESSION['adminLogin'] = true;
        redirect($_SERVER['REQUEST_URI']);
    else:
        $page->content->table = new template('admin/login.tpl');
        // it shows the login form
    endif;
}

    function logout() {
        $_SESSION['adminLogin'] = false;
        setcookie('adminUser', false, time() - 60*100000);
        setcookie('adminPass', false, time() - 60*100000);
        redirect(pathApp);
    }

redirect($x) is header("Location: $x"); die;.
No other COOKIES are being set anywhere in the entire script.
The problem is that the logout function is not working. I tried to debug this via Firebug, to see what headers are being sent and all seems ok to me. Here is Firebug's log for logout:
Response Headers

HTTP/1.1 200 OK
Date: Fri, 15 Apr 2011 18:48:57 GMT
Server: Apache
X-Powered-By: PHP/5.2.13
Expires: Thu, 19 Nov 1981 08:52:00 GMT
Cache-Control: no-store, no-cache, must-revalidate, post-check=0, pre-check=0
Pragma: no-cache
Set-Cookie: adminUser=deleted; expires=Thu, 15-Apr-2010 18:48:56 GMT
adminPass=deleted; expires=Thu, 15-Apr-2010 18:48:56 GMT
Content-Length: 1041
Connection: close
Content-Type: text/html

Request Headers

GET /freeads/admin/logout HTTP/1.1
Host: clienti.bsorin.ro
User-Agent: Mozilla/5.0 (Macintosh; U; Intel Mac OS X 10.6; en-US; rv:1.9.2.15) Gecko/20110303 Firefox/3.6.15
Accept: text/html,application/xhtml+xml,application/xml;q=0.9,*/*;q=0.8
Accept-Language: en-us,en;q=0.5
Accept-Encoding: gzip,deflate
Accept-Charset: ISO-8859-1,utf-8;q=0.7,*;q=0.7
Keep-Alive: 115
Connection: keep-alive
Referer: http://clienti.bsorin.ro/freeads/admin
Cookie: adminUser=q; adminPass=q; PHPSESSID=22faf6e20467b88d97dc7838572cbd47

The script is live at http://clienti.bsorin.ro/freeads/admin. Username and password are both set to 'q'.
Thanks!

A: I noticed that you are using a sub-domain. setCookie has a fifth parameter that will specify the domain. It is tricky with sub-domains to delete cookies. This worked for me
setCookie("clockInTime", $param, date('U')+86502,'/', '.mywebsite.com')

The last param will pick up any and all sub-domains of mywebsite using the '.' before the domain.

A: It seems the system was flawed to start with because I didn't set up the cookies properly. I didn't use the path parameter. The cookies were being set at /path/login and were being deleted at path/logout.
The correct way would have been to change both setcookie() command pairs (login & logout) to:
setcookie('adminUser', $_POST['adminUser'], time() + 60 * 60 * 24 * 7, '/');
setcookie('adminPass', $_POST['adminPass'], time() + 60 * 60 * 24 * 7, '/');

setcookie('adminUser', false, time() - 60*100000, '/');
setcookie('adminPass', false, time() - 60*100000, '/');

Notice the fourth parameter, path, being set to /. Took me a while but I figured it out :).

A: *

*check you're not sending any headers before using setcookie.

*change your conditionals to use curlybraces (I beg you)

*make sure you're setting the cookies/deleting them on the same domain (and path) try using setcookie($name, $val, $time, '/');
I can see the following error when logout is called.

  DEBUGGING:
  [class_dispatcher.php : 26] [scalar
  [integer / float / string / boolean]]
  page->content is not of class
  'template'

This is most likely the cause - as it's being outputted BEFORE setcookie is called.

A: You can change cookie's expiry time using setcookie().
Important: Expiry time of cookie must be update before any data is sent to the browser because browser identifies a cookie and stores it based on headers sent from the server to the browser, so you must use setcookie() before headers for updating cookie expiry time

A: The issue in my case, is that when I made the request to the backend using the fetch api, I forgot to set the credientials parameter to 'include'. {credentials: 'include'}


text:
Q: 'docker run -v' does not work on Windows using Docker Toolbox When running the following command from a CoreOS VM, it works as expected:
docker run --rm -v $PWD:/data composer init

It will initialize the composer.json file in the current working directory by using the Docker volume mapping as specified. The Docker container basically has the PHP tool composer installed and will run that tool inside the /data folder of the container. By using the mapping it actually applies it on the files on the host machine.
However when trying to run this command on Windows using Docker Toolbox I get the following error.
$ docker run --rm -v $PWD:/data composer --help
invalid value "C:\\Users\\Marco;C:\\Program Files\\Git\\data" for flag -v: bad mount mode specified : \Program Files\Git\data
See 'C:\ProgramData\Chocolatey\lib\docker\bin\docker.exe run --help'.

What I notice here is although I am in Git Bash when executing the command it still uses Windows paths. So then I tried following (surround with quotes):
$ "docker run --rm -v $PWD:/data composer --help"
bash: docker run --rm -v /c/Users/Marco:/data composer --help: No such file or directory

Now it is unable to find the directory.
I also tried without the $PWD variable, but this doesn't make a difference.
How do I make this work on Windows?

A: This should work:
$ docker run --rm -v //c/Users/Marco:/data composer --help

A: Try MSYS_NO_PATHCONV=1 docker run ...
Git Bash tries to convert the path for other Windows commands.


text:
Q: ResourceBundle file not found, properties file not in jar About the resourcebundle errors, I've read other questions about the same subject, but I didn't get any wiser. Tried different things, doesn't help. To give a little background: I developed a small app (JDK6), that does some flat file parsing and editing automatically. The app starts by reading some data from a properties file.
Important:
I want to be able to change the properties file. I don't want to put it in the jar file.
However, even with the little example app that I tried creating, based on another questions/answer [here][1]:
package restestapp;

import java.util.Locale;
import java.util.ResourceBundle;

public class ResourceBundleTester
{
    public static void main(String[] args)
    {
        Locale locale = Locale.getDefault();
        String basename ="myresource";
        ResourceBundle resourceBundle = ResourceBundle.getBundle(basename, locale);
        System.out.println(resourceBundle.getString("STARTING_MYAPP"));
    }
}

Both files are here:
/home/dakoina/Documents/ResTestapp/ResTestApp.jar
/home/dakoina/Documents/ResTestapp/myresource.properties

or even
c:/temp/ResTestApp.jar
c:/temp/myresource.properties

But when I run it, it gives me this output:
dakoina@ubuntu:~/Documents/ResTestapp$ java -cp /home/dakoina/Documents/ResTestapp/ -jar "ResTestApp.jar"
Exception in thread "main" java.util.MissingResourceException: Can't find bundle for base name myresource, locale en_US
    at java.util.ResourceBundle.throwMissingResourceException(ResourceBundle.java:1539)
    at java.util.ResourceBundle.getBundleImpl(ResourceBundle.java:1278)
    at java.util.ResourceBundle.getBundle(ResourceBundle.java:805)
    at restestapp.ResTestApp.main(ResTestApp.java:19)

and in Windows, the same...
c:\temp>java -jar ResTestApp.jar
Exception in thread "main" java.util.MissingResourceException: Can't find bundle
 for base name myresource, locale en_US
        at java.util.ResourceBundle.throwMissingResourceException(Unknown Source)
        at java.util.ResourceBundle.getBundleImpl(Unknown Source)
        at java.util.ResourceBundle.getBundle(Unknown Source)
        at restestapp.ResTestApp.main(ResTestApp.java:19)
  [1]: http://stackoverflow.com/questions/3742158/using-resourcebundle-with-an-external-file-java

I can't see where I am wrong :/

A: -jar means: compose the classpath from the given jar and from all the ones it references in its manifest. So the -cp option is ignored.
Your command line should be:
java -cp /home/dakoina/Documents/ResTestapp;/home/dakoina/Documents/ResTestapp/ResTestApp.jar the.main.Class

That said, a resource bundle is used to load internationalized labels. If you just want to read properties, you'd bette use the java.util.Properties class.

A: myresource.properties needs to be in classpath for jar file
put this properties file into jar and configure classpath (as described in the link)


text:
Q: Android Webviews load Javascript with 1mb? I started playing with Xamarin and Android development. I wanted to program a WebView app, sadly I get an error when loading a JS with about 1mb.
This is my code so far:
public class MainActivity : Activity
{
    private WebView web_view;

    protected override void OnCreate (Bundle bundle)
    {
        base.OnCreate (bundle);

        // Set our view from the "main" layout resource
        SetContentView (Resource.Layout.Main);

        web_view = FindViewById<WebView> (Resource.Id.webview);
        web_view.Settings.JavaScriptEnabled = true;
        web_view.SetWebChromeClient (new WebChromeClient ());
        web_view.LoadUrl ("https://my-domain.com/my-js.js");

    }
}

And this is the error I get:
"Uncaught RangeError: Maximum call stack size exceeded"
Is my assumption correct that the JS file is to big? Is there a workaround for the problem?

A: I fixed my problem yesterday. I had to enable the dom storage:
web_view.Settings.DomStorageEnabled = true;

This line of code fixed the problem and the Javascript had no problem to load.


text:
Q: In Numpy, how can I obtain an equivalent to an arr percentile, but including negative numbers? I couldn't make a better title. Let me explain:
Numpy has the percentile() function, which calculates the Nth percentile of any array:
import numpy as np

arr = np.arange(0, 10)

print(arr)
print(np.percentile(arr, 80))

>>> [0 1 2 3 4 5 6 7 8 9]
>>> 7.2

Which is great - 7.2 marks the 80th percentile on that array.
How can I obtain the same percentile type of calculation, but find out the Nth percentile of both extremities of an array (the positive and negative numbers)?
For example, my array may be:
[-10 -9 -8 -7 -6 -5 -4 -3 -2 -1  0  1  2  3  4  5  6  7  8  9]
So I place them in a number line, it would go from -10 to 10. I like to get the Nth percentile that marks extremities of that number line. For 90th percentile, the output could look like -8.1 and 7.5, for example, since since 90% of the values in the array fall within that range, and the remaining 10% are lower than -8.1 or greater than 7.5.
I made these numbers up of course, just for illustrating what I'm trying to calculate.
Is there any NumPy method for obtaining such boundaries?
Please let me know if I can explain or clarify further, I know this is a complicated question to ask and I'm trying my best to make it clear. Thanks a lot!

A: Are you looking for something like
import numpy as np

def extremities(array, pct):
    # assert 50 <= pct <= 100
    return np.percentile(array, [100 - pct, pct])

arr = np.arange(-10, 10)
print(extremities(arr, 90)) # [-8.1, 7.1]


text:
Q: --Java-- Server not correctly playing Audio from Client --Real Time Streaming-- I have a client and server application.
The server requests an audio stream and the client handles well.
The client proceeds to setup an AudioFormat(Note: settings are the same on both ends) and TargetDataLine. It Then writes the data to a Socket output stream using a ByteArrayOutput Stream.
The server receives the Data and reads it in a threaded method. During each buffer read it it saves to a AudioInputStream which is passed to a playSound method which is threaded and synchronized to proceed to play the sound.
When i make the playSound method non threaded it works well but slightly glitchy.
Also i know having the play sound non threaded can cause sound frames to jam up
Any help is well appreciated, and any ways I can make this audio stream more efficient and fast is also welcomed.
Client:
private void captureAudio() throws CommandException {
    Socket session = new Socket(host_, port_);
        try {
            final AudioFormat format = getFormat();
            DataLine.Info info = new DataLine.Info(
            TargetDataLine.class, format);
            final TargetDataLine line = (TargetDataLine)
            AudioSystem.getLine(info);
            line.open(format);
            line.start();

            int bufferSize = (int)format.getSampleRate() * format.getFrameSize();
            byte buffer[] = new byte[bufferSize];
            running = true;
                try {
                    while (running) {

                            int count = line.read(buffer, 0, buffer.length);
                            if (count > 0) {
                               BufferedOutputStream out_ = null;
                               out_ = new BufferedOutputStream(socket_.getOutputStream());
                               out_.write(buffer, 0, count);
                               out_.flush();

                              }
                    }
                    out_.close();
                    line.close();
                } catch (IOException e) {
                    throw new CommandException("I/O problems: " + e,Command.TRANSFER_ERROR);
                }
        } catch (LineUnavailableException e) {
            throw new CommandException("Line unavailable: " + e,Command.ERROR);
        }
    else {
        throw new CommandException("Unable to Connect to Server",Command.CONNECTION_ERROR);
    }
}

private AudioFormat getFormat() {
    float sampleRate = 16000;
    int sampleSizeInBits = 16;
    int channels = 2;
    boolean signed = true;
    boolean bigEndian = true;
    return new AudioFormat(sampleRate,sampleSizeInBits, channels, signed, bigEndian);

}
Server:
        public void readSocket(final Socket socket) {
        new Thread() {
        @Override
        public void run() {
            InputStream input;
            try {
                input = socket.getInputStream();

                final AudioFormat format = getFormat();
                int bufferSize = (int)format.getSampleRate() * format.getFrameSize();
                byte buffer[] = new byte[bufferSize];
                int bytesRead;
                while (((bytesRead = input.read(buffer, 0, bufferSize)) != -1 ) ) {
                    if (bytesRead > 0) {
                        play(new AudioInputStream(input, format, buffer.length / format.getFrameSize()));
                    }
                }
                socket.close();
            } catch (Exception ex) {

            }

        }
    }.start();

}

private AudioFormat getFormat() {
  float sampleRate = 16000;
  int sampleSizeInBits = 16;
  int channels = 2;
  boolean signed = true;
  boolean bigEndian = true;
  return new AudioFormat(sampleRate,
    sampleSizeInBits, channels, signed, bigEndian);
}

private synchronized void play(final AudioInputStream ais)  {
        new Thread() {
        @Override
        public void run() {
            try {
                final AudioFormat format = getFormat();
                DataLine.Info info = new DataLine.Info(SourceDataLine.class, format);
                SourceDataLine line = (SourceDataLine)AudioSystem.getLine(info);
                line.open(format);
                line.start();

                int bufferSize = (int) format.getSampleRate()
                  * format.getFrameSize();
                byte buffer[] = new byte[bufferSize];

                int count;
                while ((count = ais.read(buffer, 0, buffer.length)) != -1) {
                  if (count > 0) {
                    line.write(buffer, 0, count);
                  }
                }
                line.drain();
                line.close();
                ais.close();
            } catch (LineUnavailableException ex) {
            } catch (IOException ex) {

            }
        }
    }.start();

}


text:
Q: jQuery Validation not showing correct errors when overriding errorPlacement I'm replacing the default errors with tooltips from bootstrap overriding the errorPlacement method. But when items are required and also have any other type of validation, the required supersedes any other error.
I'm wondering if I'm missing something in the validation or if this is expected behavior.
An example in jsfiddle is here: http://jsfiddle.net/CwnUR/8/
$(function() {
    $('form').validate({
       errorElement: 'span',
       errorClass: 'error',
       validClass: 'success',
       errorPlacement: function (error, element) {

            element.attr({ 'title': error.text() }).tooltip({
                placement: 'right',
                trigger: 'manual',
                delay: { show: 500, hide: 5000 }
            }).tooltip('show');

        },
        success: function (label, element) {
            $(element).tooltip('destroy');
        }
    });

    $("#exampleInputEmail1").rules("add", {
        required: true,
        email: true
    });

    $("#exampleInputEmail2").rules("add", {
        required: true,
        equalTo: $("#exampleInputEmail1"),
        messages: {
            equalTo: 'Please retype the same email again.'
        }
    });

});

A: The problem is that the tooltip is not updating properly. When an error firsts triggers it displays the correct warning. For example, if I click submit with an empty email address I get the correct error saying the field is required. Any subsequent tries to get any other error (like invalid email address) do not show. But, it I write some text before I hit submit, I get the invalid email address error and then that supersedes any other error.
So, what I did to make it work was to destroy the tooltip inside the errorPlacement function.
Code extract:
errorPlacement: function (error, element) {
    $(element).tooltip('destroy');
    element.attr({
        'title': error.text()
    }).tooltip({