text:
Q: Android app facebook https urls not loading Trying to develop an android app that integrates social networking, and the first one i am testing out is Facebook. When doing the authorize function i have it using the WebView instead of calling up the native app (although i have let it try to use the native app as well and get the same results). When executing the authorize function it shows the "loading" dialog, but after awhile it just dies and goes back to my Activity.
When working in the emulator everything works fine the Login/ allow/deny screen shows up, its when i try to use it on an actual device that none of the https urls will load ( example: https://graph.facebook.com/19292868552 https://m.facebook.com/dialog/ etc ).
The weird thing is when trying to put the same facebook https links that the app tries to use in any browser on the android device, they dont load there either, i get a "Web page Unavailable". All other https links work fine gmail, paypal, greendotcard, etc. When trying the same https links in a browser on my PC though the pages load fine.
The device:

*

*Android 2.2.2 (LG-P505)

*Connected using WIFI ( yes the connection is
working )

I have tried this on another device (exact same model and android version ) and get the same result. However if i switch my device to use Android 4.0.3 ( clockworkmod/rom manager etc ) the app works like it should (facebook https links work fine)
I seen others have similar problems so ive tried the following:

*

*Rebooting the phone

*Checked internet connection

*Setting the onReceiveSslError in the WebViewClient:

public void onReceivedSslError (WebView view, SslErrorHandler handler, SslError error)
{
  Log.d("Facebook connection","SSL ERROR");
  handler.proceed() ;
}

Code executing the facebook authorize function:
    facebook.authorize(this, new String[] { "read_stream", "publish_stream" }, new DialogListener() {
        public void onComplete(Bundle values)
        {
            Log.d("Facebook onComplete",""+values);
        }

        public void onFacebookError(FacebookError error) {
            Log.d("Facebook onFacebookError",error.getMessage());
        }

        public void onError(DialogError e)
        {
            Log.d("Facebook onError",e.getMessage());
        }

        public void onCancel()
        {
            Log.d("Facebook onCancel","It canceled?");
        }
    });

LogCat:
06-06 10:43:48.991: V/webkit(22468): BrowserFrame constructor: this=Handler{44be3ba0}
06-06 10:43:49.001: V/webcore(22468): LOAD_URL arg1=0 arg2=0 obj=android.webkit.WebViewCore$GetUrlData@44be55c8
06-06 10:43:49.011: V/webcore(22468):  CORE loadUrl https://m.facebook.com/dialog/oauth?display=touch&client_id=CLIENTID&scope=read_stream%2Cpublish_stream&type=user_agent&redirect_uri=fbconnect%3A%2F%2Fsuccess
06-06 10:43:49.011: V/webkit(22468): startLoadingResource: url=https://m.facebook.com/dialog/oauth?display=touch&client_id=CLIENTID&scope=read_stream%2Cpublish_stream&type=user_agent&redirect_uri=fbconnect%3A%2F%2Fsuccess, method=GET, postData=null, isMainFramePage=true, mainResource=true, userGesture=true
06-06 10:43:49.021: V/webkit(22468): LoadListener constructor url=https://m.facebook.com/dialog/oauth?display=touch&client_id=CLIENTID&scope=read_stream%2Cpublish_stream&type=user_agent&redirect_uri=fbconnect%3A%2F%2Fsuccess
06-06 10:43:49.021: D/KeyguardViewMediator(1384): setHidden false
06-06 10:43:49.031: V/http(22468): 44550853 http0 RequestQueue.getRequest() => null
06-06 10:43:49.031: V/http(22468): 44550854 http0 ConnectionThread: Waiting for work
06-06 10:43:49.031: V/webview(22468): sendOurVisibleRect=(14,39,r=306,b=466
06-06 10:43:49.031: V/http(22468): 44550856 http1 RequestQueue.getRequest() => null
06-06 10:43:49.031: V/http(22468): 44550856 http1 ConnectionThread: Waiting for work
06-06 10:43:49.041: V/http(22468): 44550866 http2 RequestQueue.getRequest() => null
06-06 10:43:49.041: V/http(22468): 44550866 http2 ConnectionThread: Waiting for work
06-06 10:43:49.041: V/http(22468): 44550867 http3 RequestQueue.getRequest() => null
06-06 10:43:49.041: V/http(22468): 44550867 http3 ConnectionThread: Waiting for work
06-06 10:43:49.051: D/KeyguardViewMediator(1384): setHidden false
06-06 10:43:49.051: V/webview(22468): WEBCORE_INITIALIZED_MSG_ID
06-06 10:43:49.051: V/webcore(22468): SET_SCROLL_OFFSET arg1=0 arg2=0 obj=Point(0, 0)
06-06 10:43:49.051: V/webcore(22468): SET_GLOBAL_BOUNDS arg1=0 arg2=0 obj=Rect(14, 39 - 306, 466)
06-06 10:43:49.051: V/webcore(22468): VIEW_SIZE_CHANGED arg1=0 arg2=0 obj=android.webkit.WebView$ViewSizeData@44bf1b88
06-06 10:43:49.051: V/webcore(22468): viewSizeChanged w=292; h=427; textwrapWidth=292; scale=1.0
06-06 10:43:49.051: V/webcore(22468): viewSizeChanged
06-06 10:43:49.051: V/webcore(22468): UPDATE_CACHE_AND_TEXT_ENTRY arg1=0 arg2=0 obj=null
06-06 10:43:49.061: V/webview(22468): setCertificate=null
06-06 10:43:49.081: W/Flex(22468): getString FLEX_OPERATOR_CODE ATT
06-06 10:43:49.081: W/Flex(22468): getString FLEX_MCC_CODE 310
06-06 10:43:49.081: W/Flex(22468): getString FLEX_OPERATOR_CODE ATT
06-06 10:43:49.081: W/Flex(22468): getString FLEX_MNC_CODE 410
06-06 10:43:49.081: W/Flex(22468): getString FLEX_OPERATOR_CODE ATT
06-06 10:43:49.091: W/Flex(22468): getString FLEX_OPERATOR_CODE ATT
06-06 10:43:49.091: W/Flex(22468): getString FLEX_OPERATOR_CODE ATT
06-06 10:43:49.131: V/webkit(22468): [web] x-wap-profile info is read from flex.
06-06 10:43:49.131: V/webkit(22468): [web] x-wap-profile added = http://gsm.lge.com/html/gsm/P505-M6-D1.xml
06-06 10:43:49.131: W/Flex(22468): getString FLEX_OPERATOR_CODE ATT
06-06 10:43:49.131: V/webkit(22468): [web] x-att-deviceid : LG-P505/V10i
06-06 10:43:49.141: V/webkit(22468): getCookie: uri: https://m.facebook.com/dialog/oauth?display=touch&client_id=CLIENTID&scope=read_stream%2Cpublish_stream&type=user_agent&redirect_uri=fbconnect%3A%2F%2Fsuccess value: datr=yLHOT47krLHRlqDkKtLSPq5-; m_ts=1338946325; reg_fb_gate=http%3A%2F%2Fm.facebook.com%2Flogin.php%3Fapp_id%3DCLIENTID%26cancel%3Dfbconnect%253A%252F%252Fsuccess%253Ferror_reason%253Duser_denied%2526error%253Daccess_denied%2526error_description%253DThe%252Buser%252Bdenied%252Byour%252Brequest.%26fbconnect%3D1%26next%3Dhttp%253A%252F%252Fm.facebook.com%252Fdialog%252Fpermissions.request%253F_path%253Dpermissions.request%2526app_id%253DCLIENTID%2526redirect_uri%253Dfbconnect%25253A%25252F%25252Fsuccess%2526display%253Dtouch%2526type%253Duser_agent%2526perms%253Dread_stream%25252Cpublish_stream%2526fbconnect%253D1%2526from_login%253D1%2526client_id%253DCLIENTID%26rcount%3D1; reg_fb_ref=http%3A%2F%2Fm.facebook.com%2Flogin.php%3Fapp_id%3DCLIENTID%26cancel%3Dfbconnect%253A%252F%252Fsuccess%253Ferror_reason%253Duser_denied%2526error%253Daccess_denied%2526error_description%253DThe%252Buser%252Bdenied%252Byour%252Brequest.%26fbconnect%3D1%26next%3Dhttp%253A%252F%252Fm.facebook.com%252Fdialog%252Fpermissions.request%253F_path%253Dpermissions.request%2526app_id%253DCLIENTID%2526redirect_uri%253Dfbconnect%25253A%25252F%25252Fsuccess%2526display%253Dtouch%2526type%253Duser_agent%2526perms%253Dread_stream%25252Cpublish_stream%2526fbconnect%253D1%2526from_login%253D1%2526client_id%253DCLIENTID%26rcount%3D1
06-06 10:43:49.141: V/webkit(22468): FrameLoader: http GET load for: https://m.facebook.com/dialog/oauth?display=touch&client_id=CLIENTID&scope=read_stream%2Cpublish_stream&type=user_agent&redirect_uri=fbconnect%3A%2F%2Fsuccess
06-06 10:43:49.151: V/http(22468): 44550972 WebViewWorkerThread RequestQueue.queueRequest https://m.facebook.com/dialog/oauth?display=touch&client_id=CLIENTID&scope=read_stream%2Cpublish_stream&type=user_agent&redirect_uri=fbconnect%3A%2F%2Fsuccess
06-06 10:43:49.151: V/http(22468): 44550974 http0 RequestQueue.getRequest() => /dialog/oauth?display=touch&client_id=CLIENTID&scope=read_stream%2Cpublish_stream&type=user_agent&redirect_uri=fbconnect%3A%2F%2Fsuccess
06-06 10:43:49.151: V/http(22468): 44550974 http0 ConnectionThread: new request https://m.facebook.com:443 /dialog/oauth?display=touch&client_id=CLIENTID&scope=read_stream%2Cpublish_stream&type=user_agent&redirect_uri=fbconnect%3A%2F%2Fsuccess
06-06 10:43:49.151: V/http(22468): 44550975 http0 SEND pipe 0
06-06 10:43:49.161: V/webkit(22468): LoadListener.attachRequestHandle(): requestHandle: android.net.http.RequestHandle@44c0eef8
06-06 10:43:49.201: V/webview(22468): SET_SCROLLBAR_MODES
06-06 10:43:49.201: V/webview(22468): SET_SCROLLBAR_MODES
06-06 10:43:49.201: V/webview(22468): SET_SCROLLBAR_MODES
06-06 10:43:49.201: V/webview(22468): UPDATE_TEXT_ENTRY_MSG_ID
06-06 10:43:49.261: V/webcore(22468): SET_ACTIVE arg1=0 arg2=0 obj=null
06-06 10:43:50.391: D/DfeApi(17382): [1] DfeRequest.deliverResponse: Not delivering second response for request=[[ ] https://android.clients.google.com/fdfe/details?doc=sui.m NORMAL 415]
06-06 10:43:50.391: D/Volley(17382): [1] Request.finish: 5076 ms: [ ] https://android.clients.google.com/fdfe/details?doc=sui.m NORMAL 415
06-06 10:44:00.061: I/hs(21761): android.intent.action.TIME_TICK
06-06 10:44:02.841: D/Finsky(17382): [1] 5.onFinished: Installation state replication succeeded.
06-06 10:44:10.491: V/http(22468): 44572311 http0 Connection.openHttpConnection() 21336 https://m.facebook.com:443
06-06 10:44:10.491: V/http(22468): 44572312 http0 RequestQueue.getRequest() => /dialog/oauth?display=touch&client_id=CLIENTID&scope=read_stream%2Cpublish_stream&type=user_agent&redirect_uri=fbconnect%3A%2F%2Fsuccess
06-06 10:44:10.491: V/http(22468): 44572313 http0 ConnectionThread: new request https://m.facebook.com:443 /dialog/oauth?display=touch&client_id=CLIENTID&scope=read_stream%2Cpublish_stream&type=user_agent&redirect_uri=fbconnect%3A%2F%2Fsuccess
06-06 10:44:10.491: V/http(22468): 44572314 http0 SEND pipe 0
06-06 10:44:31.501: V/http(22468): 44593321 http0 Connection.openHttpConnection() 21006 https://m.facebook.com:443
06-06 10:44:31.501: V/http(22468): 44593321 http0 RequestQueue.getRequest() => /dialog/oauth?display=touch&client_id=CLIENTID&scope=read_stream%2Cpublish_stream&type=user_agent&redirect_uri=fbconnect%3A%2F%2Fsuccess
06-06 10:44:31.501: V/http(22468): 44593322 http0 ConnectionThread: new request https://m.facebook.com:443 /dialog/oauth?display=touch&client_id=CLIENTID&scope=read_stream%2Cpublish_stream&type=user_agent&redirect_uri=fbconnect%3A%2F%2Fsuccess
06-06 10:44:31.501: V/http(22468): 44593323 http0 SEND pipe 0
06-06 10:44:52.511: V/http(22468): 44614331 http0 Connection.openHttpConnection() 21006 https://m.facebook.com:443
06-06 10:44:52.511: V/http(22468): 44614332 http0 httpFailure() ******* java.io.IOException: The operation timed out count 2 https://m.facebook.com:443 /dialog/oauth?display=touch&client_id=CLIENTID&scope=read_stream%2Cpublish_stream&type=user_agent&redirect_uri=fbconnect%3A%2F%2Fsuccess
06-06 10:44:52.511: V/webkit(22468): LoadListener.error url:https://m.facebook.com/dialog/oauth?display=touch&client_id=CLIENTID&scope=read_stream%2Cpublish_stream&type=user_agent&redirect_uri=fbconnect%3A%2F%2Fsuccess id:-6 description:The connection to the server was unsuccessful.
06-06 10:44:52.511: V/webkit(22468): LoadListener.detachRequestHandle(): requestHandle: android.net.http.RequestHandle@44c0eef8
06-06 10:44:52.521: V/http(22468): 44614343 http0 RequestQueue.getRequest() => null
06-06 10:44:52.521: D/Facebook onError(22468): The connection to the server was unsuccessful.
06-06 10:44:52.521: V/http(22468): 44614345 http0 ConnectionThread: Waiting for work
06-06 10:44:52.521: V/webview(22468): setCertificate=null
06-06 10:44:52.551: I/ActivityManager(1384): Displayed activity com.fadedfootsteps/.FadedFootstepsActivity: 64220 ms (total 64220 ms)
06-06 10:44:52.591: V/webkit(22468): startLoadingResource: url=file:///android_asset/webkit/android-weberror.png, method=GET, postData=null, isMainFramePage=true, mainResource=false, userGesture=true
06-06 10:44:52.591: V/webkit(22468): LoadListener constructor url=file:///android_asset/webkit/android-weberror.png
06-06 10:44:52.601: V/webkit(22468): LoadListener: from: file:///android_asset/webkit/android-weberror.png major: 1 minor: 1 code: 200 reason: OK
06-06 10:44:52.601: V/webkit(22468): LoadListener.headers
06-06 10:44:52.601: V/webkit(22468): LoadListener.data(): url: file:///android_asset/webkit/android-weberror.png
06-06 10:44:52.601: V/webkit(22468): LoadListener.endData(): url: file:///android_asset/webkit/android-weberror.png
06-06 10:44:52.601: V/webkit(22468): guessMimeTypeFromExtension: url = file:///android_asset/webkit/android-weberror.png
06-06 10:44:52.631: V/webkit(22468): LoadListener.detachRequestHandle(): requestHandle: null
06-06 10:44:52.631: V/webview(22468): SET_SCROLLBAR_MODES
06-06 10:44:52.631: V/webview(22468): SET_SCROLLBAR_MODES
06-06 10:44:52.631: V/webview(22468): SET_SCROLLBAR_MODES
06-06 10:44:52.641: V/webcore(22468): didFirstLayout standardLoad =true
06-06 10:44:52.641: V/webcore(22468): WEBKIT_DRAW arg1=0 arg2=0 obj=null
06-06 10:44:52.651: V/webcore(22468): webkitDraw start
06-06 10:44:52.651: V/webview(22468): UPDATE_TEXT_ENTRY_MSG_ID
06-06 10:44:52.681: V/webcore(22468): webkitDraw NEW_PICTURE_MSG_ID
06-06 10:44:52.691: V/webview(22468): NEW_PICTURE_MSG_ID
06-06 10:44:52.701: V/webview(22468): NEW_PICTURE_MSG_ID {0,0,1063,427}

A: Figured out the problem. It was due to how i had my wifi network setup. Had internet connection sharing, sharing my mobile broadband (usb device) to my wifi router, and the router was set as a access point. Changed it back over to normal use and put the android device into the DMZ making sure nothing would block its network calls.
Normally would have checked this before hand but all other secure websites were working fine so didnt think of it till later.


text:
Q: MahApps style should not apply to all items I noticed when adding the MahApps.Metro styles to my resource dictionary that these styles are being applied to all items within my application, this is not the desired effect. I only want to use the ToggleSwitch and Combobox Styles. How can this be achieved?
Thanx!

A: put only the following resource dictionaries in your xaml
<ResourceDictionary>
  <ResourceDictionary.MergedDictionaries>
    <ResourceDictionary Source="pack://application:,,,/MahApps.Metro;component/Styles/Colours.xaml" />
    <ResourceDictionary Source="pack://application:,,,/MahApps.Metro;component/Styles/Fonts.xaml" />
    <ResourceDictionary Source="pack://application:,,,/MahApps.Metro;component/Styles/Controls.Buttons.xaml" />
    <ResourceDictionary Source="pack://application:,,,/MahApps.Metro;component/Styles/Controls.ComboBox.xaml" />
    <ResourceDictionary Source="pack://application:,,,/MahApps.Metro;component/Styles/Accents/Blue.xaml" />
    <ResourceDictionary Source="pack://application:,,,/MahApps.Metro;component/Styles/Accents/BaseLight.xaml" />
  </ResourceDictionary.MergedDictionaries>

  <Style TargetType="ToggleButton" BasedOn="{StaticResource MetroToggleButton}" />
  <Style TargetType="ComboBox" BasedOn="{StaticResource MetroComboBox}" />
  <Style TargetType="ComboBoxItem" BasedOn="{StaticResource MetroComboBoxItem}" />
</ResourceDictionary>

hope this helps

redpajama_set_name: RedPajamaStackExchange


text:
Q: Bug developing Pong Game I am creating my first game, Pong, and I have a little bug that I don't know how to fix. If the ball hits the pad from the above, it enters inside it and exit on the other side.
Here is a link with the video to understand the bug better Pong Game Bug.
I'll also post my code here so you can see how I tried to do it.
    // Ball

    ball.move(xVelocityBall, yVelocityBall);

    // Colosion for pad1
    if (ball.getGlobalBounds().intersects(pad1.getGlobalBounds()) == true)
    {
        xVelocityBall = -xVelocityBall;
        hit.play();
    }

    // Colosion for pad2
    if (ball.getGlobalBounds().intersects(pad2.getGlobalBounds()) == true)
    {
        xVelocityBall = -xVelocityBall;
        hit.play();
    }

A: I think the problem is that when your ball intersects with the pad, you change the sign of the x component of your velocity vector but your ball is still on the pad so next frame the velocity's sign is changed again resulting in the ball staying stuck on the pad.
This kind of collisions need some attention because you will encounter alot of edge cases.


text:
Q: How to get connection URL? I am work on Teradata using SQL Assistant. I want to connect to the database using JDBC but I need to get the connection URL.
Where can I find it at
 SQL Assistant?

A: SQL Assistant doesn't support JDBC connections, just ODBC and .NET
For JDBC you might use Teradata Studio Express instead:
http://developer.teradata.com/tools/articles/teradata-studio-express-14-10-01-now-available


text:
Q: Brightness Problem Gradually Changing At Every Restart I am using Ubuntu 12.10. Whenever I restart my Laptop my system brightness is changing.What settings should I make so that brightness doesn't change on every restart

A: *

*Run this command:
gksu gedit /etc/default/grub

*Change the line GRUB_CMDLINE_LINUX="" into GRUB_CMDLINE_LINUX="acpi_osi=Linux".
Save the file and quit the text editor.

*Then run: sudo update-grub

*Restart.

A: this link worked for me..i am using pavillion dv6 ubuntu 12.10
http://www.refreshit.info/2012/08/solved-brightness-increase-and-decrease.html#comment-form


text:
Q: merged cell's contents cut off beyond page break I have a vb .net program that exports information to certain fields of an excel workbook using named ranges. One of the named ranges is a notes section that gets cut off (not visible nor gets printed) if it extends beyond a page break. I am looking for a way to dynamically create new named ranges to accommodate all of the notes' text.
Some other information:

*

*The named range is a merged cell from A2:L36 with text wrap enabled

*Column A is 31 units wide

*Columns B through L are 8.38 units wide

*All of the rows are 15.75 units high

*I do NOT want to print blank pages, resize the font, disable text wrapping, have the end user do any re-formatting, nor change the size of the cells as I have tried these approaches without success.

*Using Excel 2007
HELP PLEASE!
Thanx in advance!
~8th

forgive my ignorance, I'm still a n00b

A: Thanks again Lunatik for your response. I was able to come up with an acceptable workaround before I saw your most recent post. This is not the most graceful solution but it is most suitable for what I was trying to accomplish. I hope this can be of some use to someone else in the future.
Dim sNotes As String = g_strProgram.sNotes
Dim iStartIndex, iEndIndex As Integer
Dim iRow As Integer = 0

If (sNotes.Length > 0) Then
   g_frmMain.ucAdditionalInfo.txtNotes.Text = sNotes
   Do
      iRow += 1
      oWorkSheet.Range("A" & iRow + 1 & ":L" & iRow + 1).Merge()
      iStartIndex = IIf(iRow = 1, 0, iEndIndex + 1)

      If (g_frmMain.ucAdditionalInfo.txtNotes.GetFirstCharIndexFromLine(iRow) >= 0) Then
         iEndIndex = g_frmMain.ucAdditionalInfo.txtNotes.GetFirstCharIndexFromLine(iRow) - 1
      Else
         iEndIndex = g_strProgram.sNotes.Length - 1
      End If

      oWorkSheet.Range("ProgramNote").Offset(iRow, 0).Value = g_strProgram.sNotes.Substring(iStartIndex, iEndIndex - iStartIndex).TrimEnd(vbCrLf)
   Loop While (iEndIndex < g_strProgram.sNotes.Length - 1)
Else
       oWorkSheet.Visible = Excel.XlSheetVisibility.xlSheetHidden
End If

If anyone out there reading this needs clarification with any of the aforementioned, do not hesitate to post a question here!
~8th

A: Aaargh! Merged cells are the work of Satan and should be avoided at all costs.  Even when their presence is assumed to be benign, they can have subtle and devious ways of wrecking an otherwise sound worksheet.
You don't mention whether the text is being cut off vertically or horizontally?
You should probably look at the AutoFit method as a way to forcing the text to remain inside the printed area.  This will resize the cell(s) so that the text fits at your chosen font size and, as the print area is defined by the cell borders, this should ensure that all text remains visible once printed.
If this doesn't work then it might be hard to pin down without getting rid of the merged cells.  Are they absolutely necessary?
I am working on a similar worksheet template to yours right now and have cells that resize themselves to fit a wide range of strings up to 911 characters using nothing more than the normal autofit.


text:
Q: How to get a generic average that works with vectors to compile in Haskell? I tried:
import Data.VectorSpace     -- ^/
import Data.AdditiveGroup   -- sumV
import Data.Foldable        -- length

avg :: (Foldable f, VectorSpace a) => f a -> a
avg xs = sm ^/ sz    -- could be just ^*(1/sz)
 where sm = sumV xs
       sz = fromIntegral (length xs)

and got:
Distancesumcurves.hs:11:10: error:
    • Could not deduce (Fractional (Scalar a))
        arising from a use of '^/'
      from the context: (Foldable f, VectorSpace a)
        bound by the type signature for:
                   avg :: (Foldable f, VectorSpace a) => f a -> a
        at Distancesumcurves.hs:10:1-46
    • In the expression: sm ^/ sz
      In an equation for 'avg':
          avg xs
            = sm ^/ sz
            where
                sm = sumV xs
                sz = fromIntegral (length xs)

Distancesumcurves.hs:13:13: error:
    • Could not deduce (Num (Scalar a))
        arising from a use of 'fromIntegral'
      from the context: (Foldable f, VectorSpace a)
        bound by the type signature for:
                   avg :: (Foldable f, VectorSpace a) => f a -> a
        at Distancesumcurves.hs:10:1-46
    • In the expression: fromIntegral (length xs)
      In an equation for 'sz': sz = fromIntegral (length xs)
      In an equation for 'avg':
          avg xs
            = sm ^/ sz
            where
                sm = sumV xs
                sz = fromIntegral (length xs)

Of course I could just write one specifically for vectors, and get on with my life, but then whats the point of the generic features of Haskell. In a less pedantic language I would be done with it already, and it would work just fine, and it would be reusable. In Haskell I have to write a question here or regress to code-duplication. I consider this a failure of the language.
Its not the first time I got frustrated with Haskell generics. I am past the level of the book Programming in Haskell by Graham Hutton. What should be the next step/book/article for me? So that I dont get into arguments with the compiler, when I know what I want, and it is correct. Its just language-technical skill I lack in this case. Feel free to correct me if I am wrong.

edit:
seems to work in context
approximateCurve :: [Point] -> Path
approximateCurve pts = [] -- TODO
 where center = avg pts
       avg vs = (sum vs) ^/ (fromIntegral (length vs))
       sum = foldr (^+^) (0,0)

A: In this case, I would add the additional constraint suggested in the error message, to get avg :: (Foldable f, VectorSpace a, Fractional (Scalar a)) => f a -> a.
Fractional implies Num, so no need to mention Num.  Also no harm if you add it - the function is not made less generic.
As far as general advice, I think writing lots of generic functions, guided by the type errors, is the best way.  Often adding the suggested constraints is enough; other times you really want the more-general signature, and need to figure out which function is bringing in the unwanted constraint.


text:
Q: How to modify, in list over which I iterate with enumerate, another line than that on which the iteration has arrived? In the following iteration, once the conditions to find a line are satisfied, how can I modify and write to the text file containing the list,a line situated at "n" lines distance from the one where the iteration has arrived?
    llll=['aaa','ww','emmm','wiguy','ynof','sijegy']
    mfw=open(r"D:\file.txt",'r')
    listmfw=mfw.readlines()
    for i, line in enumerate(listmfw):
            if line != '\n':
                if not (line.split()[0] in llll):
                    if (line.strip('\n') == 'wiguy'):
                    i=i-42
                    print('zugyt')

#As the line where I want to write is empty,I tried:
                    line=line.replace('\n\',''zugyt')

But nothing happens
I added what was missing - typing error!

A: I think you may misunderstand what python's file interface does. Even if you changed the open to read/write and then wrote to the file, all that would do is overwrite what's in the file at the point you write. You may want to look at fileinput, below replaces all blank newlines with 'Test\n':
from __future__ import print_function
import fileinput

file = fileinput.input('test.txt', inplace=1)
for line in file:
    if line == '\n':
        print('Test')
    else:
        print(line, end='')

A: I found a working solution which writes what I need in the position I need,relative to another position which is found by the specified conditionis.This is: :
    mfw=open(r"D:\file.txt",'r')
    listmfw=mfw.readlines()
    for i, line in enumerate(listmfw):
            if line != '\n':
                #if not (line.split()[0] in llll):
                    if (line.strip('\n') == 'wiguy'):
                        listmfw[i-43]='bzz'
                        out = open(r"D:\Users\cristina\Documents\horia\Linguistics\file.txt", 'w')
                        out.writelines(listmfw)
                        listmfw[i-31]='vrrr'
                        out.writelines(listmfw)
                        listmfw[i-19]='dopiu'
                        out.writelines(listmfw)
                    if (line.strip('\n') == 'emmm'):
                        listmfw[i-13]='ommm'
                        out.writelines(listmfw)
                    if (line.strip('\n') == 'sijegy'):
                        listmfw[i-19]='mrrr'
                        out.writelines(listmfw)
                        out.flush()
                        out.close()
    mfw.close()


text:
Q: PowerShell Socket-Server connected IP-Addresses I started a socket-server by
    $endpoint = new-object System.Net.IPEndPoint ([system.net.ipaddress]::any, $port)
    $listener = new-object System.Net.Sockets.TcpListener $endpoint

Any client with any IP-Address (subject to change) is able to connect.
How do get the IP-Addresse of a connected client after it has connected and was accepted:
    if ( $listener.Pending()) {
        $client = $listener.AcceptTcpClient()
        $stream = $client.GetStream();
        $writer = New-Object System.IO.StreamWriter $stream
        $writer.AutoFlush = $true
        ...
    }

Unfortunately $client.IPAddress() (error) or $client.IPAddress (nothing) do not exists
Thanks in advance!

A: You can get it through $client.Client.RemoteEndPoint


text:
Q: SFSafariViewController and Javascript I am working on IOS app in which I open login page in SFSafariViewController. And On that login page when the login is successful, a Json response is generated.
I want to get that response and close SFSafariViewController.
In android I did it through Javascript and Javascript interface..
My server side code for android:
<?php
//curl initialize
//Some code
//Curl Execution
$response = curl_exe($ch)
?>
<script>
showAndroidToast("<?php echo $response;?>");
function showAndroidToast(res){
Android.dataResponse(res);
}
</script>

In android.
Android.dataResponse(res) is my javascript interface which i added to my Chrome Custom Tabs (https://developer.chrome.com/multidevice/android/customtabs).
I want similar functionality for my IOS app.I don't know. Is this possible with SFSafariViewController or not?

A: According to this StackOverflow answer you cannot download files with SFSafariViewController Furthermore there seems to be no delegate to initiate the download of the JSON according to Apple's documentation
Given this information I am pretty sure that your safest bet is to go the WKWebView route even though WebKit has all sorts of limitations on iOS. You could probably use this as a starting point.
I would personally just call my login API's and create a native login form thus circumventing Apple's browsing options altogether. I hope this helps!
EDIT
The OP is actually using FitBit's API and OAuth2 and according to FitBit's Documentation:

For native applications, this means the authorization page must open in the default browser. Native applications can use custom URL schemes as redirect URIs to redirect the user back from the browser to the application requesting permission. iOS applications may use the SFSafariViewController class instead of app switching to Safari. Use of the WKWebView or UIWebView class is prohibited.

Pointers for using FitBit's Authorization Code Grant Flow can be found in their documentation but there is no proper guide. But OAuthSwift supports FitBit so that is probably the easiest way to implement the login. A discussion about a sample integration can also be found here and here.


text:
Q: Page does not work after published with Visual Studio 2013 I have an application that works perfectly in the local host, but when I publish it to a remote server I have a problem. I can see the page published that seems fine, but when I click "SAVE" it goes to a blank page and nothing happens.
What could I be missing?
I do not know what kind of information about the application that I could provide here to help to find a solution.

A: I made a change in the Web.config and worked.
This was before:
<system.webServer>
    <modules>
      <remove name="FormsAuthentication" />
    </modules>
</system.webServer>

Now, what worked:
<system.webServer>
    <modules  runAllManagedModulesForAllRequests="true" />
</system.webServer>


text:
Q: Do Two-wire Full Duplex Data Signal Cause Collison at atomic Level Can the transmitting and receiving signal travel in the same wire in Full Duplex (FDD)?
If yes, will there be any collision at atomic level?
If yes, how this phenomena can be explained?

A: On a physics level, the the answer is, that the signal travelling through a conductive cable is an electromagnetic wave. And even electromagnetic waves around wires do not interact strongly (and thus can pass through one another).
So in principle you can use a single wire for full duplex.
The diffuculty is then to separate the signals at the ends of the wire. One method is to use different carrier waves for the two signal directions (then the Fourier stuff you mentioned in the comment applied), but that is rather inefficient bandwidth wise (as you have to modulate the signal slowly compared to the carrier frequency). Another problem is to supress reflection at the wire ends to prevent noise. So again, the main challenge, is engineering, not physics. (And the cost for this added complexity is usually more than that of an extra strand copper).

About collisions: A conductor does not, conduct electrons (or atoms) ballistically! The signal you receive at the end of the wire is not the electrons pushed in on the other end, the drift velocity of electrons in wires is on the scale of µm/s (depending on the material). If this were the signalling mechanism the internet would be useless.
The signals travelling through the wire is actually the electromagnetic field guided by the wire. To illustrate this fact:
A signal representing a bit in a 1Gbit/s Ethernet wire is just about 60cm long (two twisted pairs are used for one datastream, the baudrate is therefore around 500MHz, $c/500\,\mathrm{MHz} \approx 60\,\mathrm{cm}$, $c$ is of course just an approximation of the signal velocity in the cable, it will be somewhat slower). So there are a few bits of information stored in the wire. And this information is not encoded in movement of electrons (this would be damped after a few millimeters) but in the travelling electromagnetic field around the wire!
As the em fields travelling in opposite directions interfere, the electrons do simply not move in opposite directions where there is a signal travelling from the left and one from the right, but do not move at all (as the resulting field will cancel out locally). But this interference will not hinder the propagation of the signal!
On a side note: Considered even more microscopically the "collisions" of electrons actually do something. Electron-electron interactions and interactions of electrons with impurities contribute to the electrical resistance of the wire and therefore are responsible for the damping of the signal over long distances (but this already happends for a single signal travelling throgh the line).


text:
Q: Auto add amount with decimal value in javascript I want to appear in (total amount) automatically the sum of (Amount Paid and OtherCharges) how can I do that?
I'm getting incorrect value in total amount, let say
Amount Paid = 100.90
Other Charges = 10.1
Total Amount = 100.91
here's my code

 $('#AmountPaid, #OtherCharges, #Amount').on('input',function() {

    var AmountPaid = parseFloat($('#AmountPaid').val()).toFixed(2);
    var OtherCharges = parseFloat($('#OtherCharges').val()).toFixed(2);
    var Amount =  parseFloat($('#Amount').val()).toFixed(2);

    $('#Amount').val(parseFloat(AmountPaid + OtherCharges)).toFixed(2);

    });

});

A: toFixed turns your number back into a string. When you + two strings together, you get a concatenated string, like 100.9010.1. Then you're parseFloating that, which will disregard the invalid part and give you 100.901, which you're toFixed'ing, which rounds. I'm not sure why you'd get 100.91 for your inputs (I get 100.90), but fundamentally those are the issues.
The solution is to pay close attention to when you're dealing with strings vs. numbers. Also, you probably don't want to hook input on your output field (#Amount), just your input fields.
So:
$('#AmountPaid, #OtherCharges').on('input', function() {
    var AmountPaid = parseFloat($('#AmountPaid').val());
    var OtherCharges = parseFloat($('#OtherCharges').val());
    var Amount =  AmountPaid + OtherCharges;

    $('#Amount').val(Amount.toFixed(2));
});

Live Example:

$('#AmountPaid, #OtherCharges').on('input', function() {
  var AmountPaid = parseFloat($('#AmountPaid').val());
  var OtherCharges = parseFloat($('#OtherCharges').val());
  var Amount = AmountPaid + OtherCharges;

  $('#Amount').val(Amount.toFixed(2));
});

Fill in either of the first two fields, and the third is updated:

  Amount paid:
  <input type="text" id="AmountPaid" value="100.90">

  Other charges:
  <input type="text" id="OtherCharges" value="">

  Amount:
  <input type="text" id="Amount" value="">

And a general caveat around using JavaScript's numbers for financial calculations: Is floating point math broken?


text:
Q: XML parsing error on symbian s60 I have a problem with Carbide C++.
I'm trying to use function from Nokia Forum to read xml files. So I found this article:
http://wiki.forum.nokia.com/index.php/How_to_parse_XML_file_using_CParser_class
And I've created a XmlHandle.h and XmlHandle.cpp files.
But I don't know how I can use this.
I try something like this:
_LIT( KConfigFile, "config.xml" );
(...)
CXmlHandler* iXmlHandler;
<br>iXmlHandler = CXmlHandler::NewL();
TFileName fileName;
fileName.Append( KConfigFile );
iXmlHandler->StartParsingWithAoL( fileName );

But when I try to compile project I am receiving this error:
No source available for "0x2539636( ekern.exe )() "
Thread myProject::myProject Panic ALLOC: 3bcb1558

Can someone tell me what can I do? Thanks.

A: ALLOC panic means you haven't freed some resources. I guess the StartParsingWithAoL leaves, and the iXmlHandler isn't deleted (either it's a member variable that isn't deleted in destructor, or it's local variable that you haven't put on the cleanup stack). It's hard to tell more without seeing more code.

A: You don't get these errors during compilation. Did you get it actaully when running in emulator?
I don't see :
delete iXMLHandler;
Where exactly in your code does this error occure?


text:
Q: SAS-multiple datasets merging I want to merge several individual datasets through following code. However, it reports error as:

How could I solve this problem?
%macro test(sourcelib=,from=);
proc sql noprint;  /*read datasets in a library*/
  create table mytables as
  select *
  from dictionary.tables
  where libname = &sourcelib
  order by memname ;

  select count(memname)
  into:obs
  from mytables;

  %let obs=&obs.;

  select memname
  into : memname1-:memname&obs.
  from mytables;
quit;

data full;
set
%do i=1 %to &obs.;
  &from.&&memname&i;
%end;
;
run;
%mend;

%test(sourcelib='RESULT',from=RESULT.);

A: Your %DO loop is generating extra semi-colons in the middle of your SET statement.
set
%do i=1 %to &obs.;
  &from.&&memname&i
%end;
;

Also why do you have two macro parameters to pass the same information?  You should be able to just pass in the libref.  Also why make so many macro variables when one will do?
%macro test(sourcelib=);
%local memlist ;
proc sql noprint;
  select catx('.',libname,memname) into :memlist separated by ' '
    from dictionary.tables
    where libname = %upcase("&sourcelib")
    order by 1
  ;
quit;

data full;
  set &memlist ;
run;
%mend;

%test(sourcelib=ReSulT);


text:
Q: Why is undefined returned when accessing properties of a typescript object in an angular2 project? I have an angular2 project in which I am using the http module to make a get request. The object is retrieved from the server and apparently is deserialized properly into its corresponding typescript object, but when I try to access a property it returns undefined, even though when I print the object to the console right before trying to access these properties, the data appears to exist.
This is what my get request method looks like.
  getDataForEmployee(data){
    var url = this.active+"/guest/"+data;

    var headers = new Headers();

    headers.append("Content-Type", "application/json");

    return this.http
      .get(url, {headers:headers})
      .toPromise()
      .then((res:Response)=> res.json() as Employee);

  }

This is how the method looks which is handling the response.
this.employeeHttp.getDataForEmployee(userid)
  .then((employee:Employee)=>{
    console.log(employee);
    console.log("firstname: "+employee.firstName);
    ...

The Employee class looks like this:
 export class Employee {

    ...
      private _firstName:string;
    ...

      get firstName(): string {
        return this._firstName;
      }

      set firstName(value: string) {
        this._firstName = value;
      }

    ...
    }

The image shows the console output when making this request.

I don't understand why when I try to retrieve firstName it returned undefined even though it exists in the object right before.
Any ideas as to why this is happening would be very helpful to me.

A: What you are expecting can be achieved only by inheritance. But declaring a type of an object as a class doesn't make the object inherit the class i.e employee is not a child of Employee in your code.
To call the getter you will have to inherit it first eg:
let emp = new Employee("Dan"); // passing only firstName for demo

Then you will be able to access emp.firstName and it will return Dan. You will also need to accept arguments in your Employee class.
I have made a plnkr demo where the Employee class accepts one argument for firstName. Keep your developer tools open so that it will stop in both getter and setter.
As typescript only checks code at compile type you have no way of checking  if the API returned something else eg: _name instead of _firstName at runtime. So I recommend using an interface instead of a class in your case.


text:
Q: How to efficiently re-order packets in PCAP files based on timestamp? I have a PCAP file which contains many packets. They are however out of order based on the timestamp (it is actually randomized). What is the best way to efficiently sort the PCAP packets based on timestamp for later replay?
Currently I am doing this via Scapy and Python as proposed here. This is working, but is really slow. Further, it loads the dump completely in memory, where the timestamps would actually be sufficient. I know sorting is an expensive operation, but this method takes nearly 4 minutes for a 344MB file containing 778589 packets on a modern Core i7.
I also know that Wireshark should include "reordercap", however this tool is not included in current Debian and Ubuntu builds. Before trying to build Wireshark from source, maybe someone has experience with this tool and can suggest how performance will be.
So, to come back to the question: How to efficiently sort packets in PCAP files based on their timestamp? Memory is not the constraint, as the PCAPs will not be larger than 2GB and enough RAM is available, but rather the runtime is important to me. It should complete as fast as possible.
Thank you in advance!

A: I had the same problem and actually mine was worst because my pcapfile was much bigger than yours so I need a more efficient way to sort its packets. I find libtrace which is developed in C as a good solution.
Unfortunately there is not any direct tools to do the task but its tracemerge tool merges two (or more) files and sorts the packet. So you should first split your file with tracesplit and then merge them with tracemerge.


text:
Q: Chart.JS: How to make sharp lines to smooth curved lines Hi I'm new at charts and this is my chartjs chart, it's working currently, but it's showing in sharp lines and I want to make it smooth curve lines on this chart. Any ideas?
function statistics(data) {
    if ($('#stats-currency').length > 0) {

        if (typeof(stats_currency) !== 'undefined') {
            stats_currency.destroy();
        }
        if (typeof(data) == 'undefined') {
            var currency = $('select[name="currency"]').val();
            $.get(admin_url + 'home/stats_currency/' + currency, function(response) {
                stats_currency = new Chart($('#stats-currency'), {
                    type: 'line',
                    data: response,
                    options: {
                        responsive:true,
                        scales: {
                            yAxes: [{
                              ticks: {
                                beginAtZero: true,
                            }
                        }]
                    },
                },
            });
            }, 'json');
        } else {
            stats_currency = new Chart($('#stats-currency'), {
                type: 'line',
                data: data,
                options: {
                    responsive: true,
                    scales: {
                        yAxes: [{
                          ticks: {
                            beginAtZero: true,
                        }
                    }]
                },
            },
        });
        }

A: you can do it by adding tension value to your charts options
<canvas id="myChart"></canvas>

JS
const config = {
  type: 'line',   // your chart type
  data: data,   // pass here your data
  options: {
    elements: {
        line: {
            tension : 0.4  // smooth lines
        },
    },
  },
};

// pass it like
  const myChart = new Chart(
    document.getElementById('myChart'),
    config
  );

A: This can be done through the option lineTension that needs to be defined on your dataset. Choose a value below 1.
datasets: [{
  ...
  lineTension: 0.8
}]

By default, you should however already see curved smooth lines since accoring to Chart.js documentation, the default value is 0.4.

lineTension: Bezier curve tension of the line. Set to 0 to draw straight lines.
Please note that if the steppedLine value is set to anything other than false, lineTension will be ignored.


text:
Q: Why does string::find return size_type and not an iterator? In C++, why does string::find return size_type and not an iterator?
It would make sense because functions like string::replace or string::insert take iterators as input, so you could find some character and immediately pass the returned iterator to replace, etc.
Also, std::find returns an iterator -- why is std::string::find different?

A: It's probably more useful to get a number from find because then you can use the [] operator or substr() to get to the characters you just searched for are.
Also, if you want an iterator, you can always do begin() + pos

A: All the string functions operate on indexes, some functions (like replace() and insert()) just additionally support iterators. So the result of find() can directly be used in those functions. Since there can't be two find() functions that just differ by return type (one returning an iterator, one returning an index) one had to be chosen.

A: The design of the standard library's shiny new string class was already done when Stroustrup introduced the standard committee to the STL. The committee liked the STL and started incorporating it into the standard, thereby adapting much of what they had already agreed on (and probably also delaying the standard for another year or two).
Among other changes, iterators were added to the already finished string class as an after-thought. You can see this by looking at the various string members taking/returning a position – it's a wild mix of indexes and iterators.
It's not always easy to guess why some member functions have only indices-taking versions and some have iterator-taking ones, too. In the case of std::basic_string<>::find(), however, it seems easy: Since std::find() already returns an iterator, std::basic_string<>::find() was left as it was.

A: I assume it's because in general string members work on indexes rather than iterators and this makes it easy to use the returned value. You can always use std::find if you want to get an iterator.


text:
Q: Proving linearity of map when scalar multiplication defined differently on domain and codomain For $T:V \rightarrow W$, to prove $T$ is linear, we show that for $v_1, v_2 \in V$ and $\lambda \in \mathbb{F}$, that $T(v_1+ \lambda v_2) = T(v_1) + \lambda T(v_2)$, where $\lambda T(v_2)$ denotes standard scalar multiplication.
But now suppose I have $V$ and its complex conjugate vector space $\overline{V}$, where $\overline{V}$ is the same as $V$ except that scalar multiplication is defined as $\overline{S}(\lambda, v_1) = S(\overline{\lambda}, v_1)$, where $S$ is the normal scalar multiplication on $V$, and $\overline{S}$ is the scalar multiplication on the complex conjugate vector space and $v_1 \in V$
Here, if we wanted to show $T:V \rightarrow \overline{V'}$ is linear, where $V'$ denotes the dual space of $V$, under which definition of scalar multiplication do we have to show that $T(\lambda v_1) = \lambda T(v_1)$? Is it the standard scalar multiplication for $T(\lambda v_1)$ and the complex conjugate scalar multiplication for $\lambda T(v_1)$?


text:
Q: Java polymorphism: How to indicate comparison should be made using subclass? Introductory question incoming! The following code...
public class HelloWorld
{
  public static void main(String[] args)
  {
    ArrayList<Object> A = new ArrayList<Object>();
    Integer I = new Integer(3);
    Double D = new Double(3.14);

    A.add(I);
    A.add(D);

    if (A.get(0) > 2)
    {
        System.out.print("Hello World");
    }
  }
}

... fails to compile
bad operand types for binary operator '>'
        if (A.get(0) > 2)
                     ^
  first type:  Object
  second type: int

How can I indicate that I want the comparison to be made with the subclass Integer rather than with Object?

A: As both Integer and Double extend Number then redefine you ArrayList as
ArrayList<Number> A = new ArrayList<Number>();

then
if (A.get(0).intValue () > 2)


text:
Q: VirtualBox: do not preserve attached device changes when snapshotting (how?) (this is similar to my
How to tell virsh: save state of VM and vdisk, but not attached disk? but for VirtualBox and raw devices)
How do I tell VirtualBox to NOT preserve the state of raw attached
devices when snapshotting? Details:

*

*I created a VMDK on the host machine as follows:

VBoxManage internalcommands createrawvmdk -filename sdb.vmdk -rawdisk /dev/sdb
and attached it to the guest.

*

*/dev/sdb now shows up as a pure device file on the guest.

*My clever idea: mount /dev/sdb, and any changes I make there will
be preserved across snapshots, since VirtualBox isn't going to save
the state of /dev/sdb

*I was wrong. By default, VirtualBox will save the state of
/dev/sdb: if you revert to an earlier snapshot, anything you did on
/dev/sdb will be wiped out.

*In other words, my cunning plan failed.

*Is there any way to make it work? I realize I could mount /dev/sdb
on the host and then have the guest mount it or sshfs it or
something, but is there a VirtualBox option that says "do not
preserve/restore /dev/sdb state when snapshotting"?

*I'm trying to use a VM to determine how I want to install CentOS
7.2, and, ideally, I'd like the guest to be as close to a real
system as possible.
I'd like to thank @gilles for his excellent answer, but it turns out that it doesn't quite work.
When I shutdown, detach /dev/sdb, take a snapshot and then later restore the snapshot and re-attach /dev/sdb, I see this (click for full size):

Basically, VirtualBox refuses to touch /dev/sdb, even if I attach it. Rather, it uses differencing disks to store any changes I make, and these changes are reverted when I restore snapshots.
You can actually see the differencing disks in Media Manager:

but I can't find a way to do anything useful with them.
I'm leaving my upvote and checkmark for gilles answer, but will go back to using more normal methods to mount /dev/sdb on the guest.

A: You must unmount the device before making the snapshot. Otherwise, when resuming, the state of the device would not match the state of the disk cache in the guest kernel, which would result in massive corruption.
After you've unmounted the device, detach it from the virtual machine before making the snapshot.


text:
Q: Set file origin when Importing text files to excel with VBA I'm working with a VBA code to import TEXT files from a folder to excel workbooks.
My text file contains non-English encoding/origin and I want to import the file with 1253 Greek windows encoding but can't figure out how to add the origin:="1253" (if i'm right) in this code:
Sub LoadPipeDelimitedFiles()
'UpdatebyKutoolsforExcel20151214
    Dim xStrPath As String
    Dim xFileDialog As FileDialog
    Dim xFile As String
    Dim xCount As Long
    On Error GoTo ErrHandler
    Set xFileDialog = Application.FileDialog(msoFileDialogFolderPicker)
    xFileDialog.AllowMultiSelect = False
    xFileDialog.Title = "Select a folder [Kutools for Excel]"
    If xFileDialog.Show = -1 Then
        xStrPath = xFileDialog.SelectedItems(1)
    End If
    If xStrPath = "" Then Exit Sub
    Application.ScreenUpdating = False
    xFile = Dir(xStrPath & "\*.txt")
    Do While xFile <> ""
        xCount = xCount + 1
        Sheets(xCount).Select
        With ActiveSheet.QueryTables.Add(Connection:="TEXT;" _
          & xStrPath & "\" & xFile, Destination:=Range("A1"))
            .Name = "a" & xCount
            .FieldNames = True
            .RowNumbers = False
            .FillAdjacentFormulas = False
            .PreserveFormatting = True
            .RefreshOnFileOpen = False
            .RefreshStyle = xlInsertDeleteCells
            .SavePassword = False
            .SaveData = True
            .AdjustColumnWidth = True
            .RefreshPeriod = 0
            .TextFilePromptOnRefresh = False
            .TextFilePlatform = 437
            .TextFileStartRow = 1
            .TextFileParseType = xlDelimited
            .TextFileTextQualifier = xlTextQualifierDoubleQuote
            .TextFileConsecutiveDelimiter = False
            .TextFileTabDelimiter = False
            .TextFileSemicolonDelimiter = False
            .TextFileCommaDelimiter = False
            .TextFileSpaceDelimiter = False
            .TextFileOtherDelimiter = "|"
            .TextFileColumnDataTypes = Array(1, 1, 1)
            .TextFileTrailingMinusNumbers = True
            .Refresh BackgroundQuery:=False
            xFile = Dir
        End With
    Loop
    Application.ScreenUpdating = True
    Exit Sub
ErrHandler:
    MsgBox "no files txt", , "Kutools for Excel"
End Sub

A: I guess I was in a rush...
Here is the answer:
.TextFilePlatform = 1253


text:
Q: Dynamic control creation using angular js with html5? I have created a simple sample project for dynamic control creation using angularjs and html5.
I have a xml file with the set of controls with property and event attributes to be generated dynamically.
Intially,all my dynamic controls will be loaded from the xml file and it is parsed as angular js elements.
While clicking the dynamically created button, I have to trigger the button click event specified in the xml file, and Get the values bound with the text boxes and other input controls (checkbox,...) specified in the xml.
Sample XML
<?xml version="1.0" ?>
<page>

  <textbox value='{ "BindingElementName": "Email","caption":"Email Address","id":"txtemail","name":"txt","type":"text" }'/>

  <checkbox value='{ "BindingElementName": "Use","caption":"I want to use email as my username","id":"chkemail","name":"chk","type":"check" }' />

  <textbox value='{ "BindingElementName": "UserName","caption":"UserName","id":"txtuser","name":"txtuser","type":"text" }' />

  <textbox value='{ "BindingElementName": "Password","caption":"Password","id":"txtpass","name":"txtpasswd","type":"password" }'/>

  <textbox value='{ "BindingElementName": "CPassword","caption":"Confirm Password","id":"txtcpass","name":"txtcpasswd","type":"password" }'/>

  <textbox value='{ "BindingElementName": "Answer","caption":"Answer","id":"txtans","name":"txtans","type":"text" }'/>

  <checkbox value='{ "BindingElementName": "Agree","caption":"I agree to sites terms and condition","id":"chkagree","name":"chkagree","type":"check" }'/>

  <checkbox value='{ "BindingElementName": "Remember","caption":"Remember me on this computer to skip security questions next sign-in","id":"chkremember","name":"chkremember","type":"check" }'    />

  <button value='{ "name":"btn1","type":"button","id":"btn1", "text":"Start My Return", "click":"handleClick()"}'/>

  <button value='{ "name":"btn2","type":"button","id":"btn2", "text":"Start My Return1", "click":"handleClick()","handles":""}'/>

</page>

My app.js
var app = angular.module('myApp', []);

var addDiv = $('#container');

app.directive('contentItem', function ($document, $compile) {

    var button = '<button ng-click={{content.click}} >{{content.text}}</button>';

    var getTemplate = function (controls, attributes, controltype) {
        var template = '';
        var control;
        if (controls[0] === undefined) {
            control = controls;
        } else {
            control = controls[0];
        }
        var bindvalue;
        switch (controltype) {
            case "text":
                var textbox = "{{content.caption}}:<input name= {{content.name}} id= {{content.id}} type='text' ng-model='" + control.content.BindingElementName + "' />{{" + control.content.BindingElementName + "}}

";
                template = textbox;
                break;
            case "password":
                var textboxpass = "{{content.caption}}:<input name= {{content.name}} id= {{content.id}} type='password' ng-model='" + control.content.BindingElementName + "' />{{" + control.content.BindingElementName + "}}

";
                template = textboxpass;
                break;
            case "check":
                var checkbox = "<input type='checkbox' name={{content.name}} id={{content.id}} ng-model='" + control.content.BindingElementName + "' ng-true-value='YES' ng-false-value='NO' />{{content.caption}} {{" + control.content.BindingElementName + "}}

";
                template = checkbox;
                break;
            case "button":

                control.handles = function () {

                    var sssc = control.content.Email;
                    alert(sssc);
                    //want to construct the object here.....

                };

                // (or)

                $document.on(
                          "click", "#" + control.content.id,
                          function ($scope) {

                              control.$apply(
                                  function () {

                                      alert("Hi");
                                      //want to construct the object here.....

                                  }
                              );

                          }
                      );
                template = button;

                              break;
            default:
                alert("default");
        }

        return template;

    };

    var linker = function (scope, element, attributes) {

        var test = getTemplate(scope, attributes, scope.content.type);
        element.html(test).show();

        $compile(element.contents())(scope);
    };
    return {
        restrict: "E",
        rep1ace: true,
        link: linker,
        scope: {
            content: '='
        }
    };

});

function ContentCtrl($scope, $http) {
    debugger;
    'use strict';
    $scope.url = 'GenerateXML/Controls.xml?000000';
    $scope.content = [];
    var jsonObj = [];
    $scope.element = [];

    $scope.fetchContent = function () {
        $http.get($scope.url).then(function (result) {
            var xml = $.parseXML(result.data);
            {
                var obj = $.xml2json(xml);
                //for sorting the controls as per in xml file.
                $.each(obj, function (i, item) {
                    var test = jQuery.parseJSON(item.value);
                    jsonObj.push(test);

                });
                $scope.content = jsonObj;
            }
        });
    };

    $scope.fetchContent();

     $scope.handleClick = function () {
        alert('Hello ' + $scope.content.Email);
    };

}

My Html5
 <!DOCTYPE html>

    <title></title>

        <content-item ng-repeat="item in content" content="item"></content-item>

Please suggest me whether i'm going in right way and also assist me on raising the button click event to get the ng-model binded controls values.
Thanks,
G.$@M

A: I implemented a functionally similar components,  want to be able to help you:
source code


text:
Q: UEFI function GetVariable() returns EFI_NOT_FOUND I am trying to create a UEFI driver that will simply read a bunch of variables, and based on the values it will show some output to the screen.
This is my code so far:
#include <efi.h>
#include <efilib.h>
#include <memory.h>

EFI_STATUS
EFIAPI
efi_main (EFI_HANDLE ImageHandle, EFI_SYSTEM_TABLE *SystemTable) {
   InitializeLib(ImageHandle, SystemTable);
   Print(L"Hello, world!\n");

   EFI_GUID guid = EFI_GLOBAL_VARIABLE;
   UINT32 attr = 0;
   UINTN data_size = 0;
   void* data = NULL;

   EFI_STATUS status =
        SystemTable->RuntimeServices->GetVariable(L"Boot0001", &guid, &attr, &data_size, data);

   if(status != EFI_SUCCESS)
   {
       Print(L"GetVariable() failed!\n");
       return status;
   }

   Print(L"Success!\n");

   return EFI_SUCCESS;
}

The issue is that the code above returns the error value of EFI_NOT_FOUND, which indicates that the variable does not exist. If I dump all variables though using dmpstore –all -b, I can clearly see it there:
Variable NV+RT+BS 'EFIGlobalVariable:Boot0001' DataSize = 0x21
  00000000: 03 00 00 00 0D 00 20 00-55 00 53 00 42 00 00 00  *...... .U.S.B...*
  00000010: 05 01 09 00 11 00 00 00-00 7F FF 04 00 00 00 42  *...............B*
  00000020: 4F                                               *O*

Which begs the question now, what am I doing wrong?


text:
Q: result=sum(staffSalary) TypeError: unsupported operand type(s) for +: 'int' and 'str' I am trying to sum the staff salary in a float with 2 digits after the dot in the code below but gave me that error.
I understand the type of error but unfortunately, I don't know how to fix it. I am trying different ways and it comes with the same error.
staffName=[]
staffSalary=[]
for name in range(0,5):
    print('Enter staff name:')
    staffName.append(input())
for salary in range(0,5):
    print('Enter salary:')
    staffSalary.append("{:.2f}".format(float(input())))
print('Staff details entered:\n')
for i in range(0,5):
    print(staffName[i], ' ', staffSalary[i])

result=sum(staffSalary)
print('\nTotal salary amount is: ', result)

totalIncrease=(result * 10) / 100 + result
print('Total salary amount with 10% increase: ',totalIncrease)

A: In your line staffSalary.append("{:.2f}".format(float(input()))), it looks like you are taking the input and converting it to a float (that sounds right) but then you are turning that into a string. So what you finally add to your list is a string, not a float.
I think you just want staffSalary.append(float(input()). Then the list will have all items that are floats. When you have a string later that includes those numbers, you can do some string-transformations then.


text:
Q: Text vertically jump up and down in output. Uses "document.getElementById("firstDiv").innerHTML = document.getElementById("location").value;" I don't really know how to describe my problem, but basically :
I have coded a project in JSFiddle for fun, and somehow my code output just jumps up and down.
If you want to take a look for yourself, click on the link below and then click "Submit Complaint" button.
The problem is : In the output text, some variables and text are higher than all the surrounding text. I don't know why.
Thank you for trying to help!
My project on JSFiddle
Here is a working snippet :

$("#textChanger").click(function() {

 var el     = $("#alarmcard"),
     newone = el.clone(true);

 el.before(newone);

 $("." + el.attr("class") + ":last").remove();

});

$("input:checkbox").on('click', function() {
  // in the handler, 'this' refers to the box clicked on
  var $box = $(this);
  if ($box.is(":checked")) {
    // the name of the box is retrieved using the .attr() method
    // as it is assumed and expected to be immutable
    var group = "input:checkbox[name='" + $box.attr("name") + "']";
    // the checked state of the group/box on the other hand will change
    // and the current value is retrieved using .prop() method
    $(group).prop("checked", false);
    $box.prop("checked", true);
  } else {
    $box.prop("checked", false);
  }
});
.fieldset {
  visibility:hidden;
}

.typewriter {
  vertical-align: baseline;
  display: flex;
  color: black;
  font-family: monospace;
  overflow: hidden;
  /* Ensures the content is not revealed until the animation */
  border-right: .15em solid orange;
  /* The typwriter cursor */
  white-space: nowrap;
  /* Keeps the content on a single line */
  margin: 0 auto;
  /* Gives that scrolling effect as the typing happens */
  letter-spacing: .15em;
  /* Adjust as needed */
  animation: typing 3.5s steps(30, end), blink-caret .5s step-end infinite;
}

/* The typing effect */

@keyframes typing {
  from {
    width: 0
  }
  to {
    width: 100%
  }
}

/* The typewriter cursor effect */

@keyframes blink-caret {
  from,
  to {
    border-color: transparent
  }
  50% {
    border-color: orange
  }
}
<!DOCTYPE HTML>

    <title>Telephone Alarm Card</title>
    <meta charset="UTF-8" />

Telephone Alarm Card

    <form>
      <fieldset>
        <legend>Submission</legend>

          Location in House
          <input type="text" id="location" placeholder="Attic" />

          Address of House
          <input type="text" id="address" placeholder="11 No. Elm, City" />

          Name of Suspect
          <input type="text" id="nameofsus" placeholder="Mrs. Blake" />

          Name or Initials of Submiter
          <input type="text" id="nameofsub" placeholder="E.B." />

          <input type="checkbox" id = "male" name="fooby[1][]" />Male

          <input type="checkbox" id = "female" name="fooby[1][]" />Female

          <input type="button" value="Submit Complaint" id="textChanger" />
      </fieldset>

      <fieldset>

        <legend>Firemen's Alarm Card</legend>

Have reason to suspect

attic

;

11 No. Elm, City

. ---

E.B

; Name is

Elise Larsson

;

Female

      </fieldset>

    </form>

A: The problem is that you don't have any

 surrounding your text inside your DIVs (#firstDiv, #SecondDiv, etc..).
Here is a Minimal, Complete, and Verifiable snippet where you can see the difference between with/without

 :

.typewriter {
  vertical-align: baseline;
  display: flex;
  color: black;
  font-family: monospace;
  overflow: hidden;
  /* Ensures the content is not revealed until the animation */
  border-right: .15em solid orange;
  /* The typwriter cursor */
  white-space: nowrap;
  /* Keeps the content on a single line */
  margin: 0 auto;
  /* Gives that scrolling effect as the typing happens */
  letter-spacing: .15em;
  /* Adjust as needed */
  animation: typing 3.5s steps(30, end), blink-caret .5s step-end infinite;
}

Start |

Test 1

 | end.

Start |

Test 2

 | end.


text:
Q: How do I interchange the XML attribute position in C#? I have XElements in my XML document and most of it contains two attributes, id and class. I want to interchange the position to class and id. I will explain it better now.
My XML content:

Value 1

Value 2

Value 3

Value 4

What I want:

Value 1

Value 2

Value 3

Value 4

A: This will put the first attribute last:
XElement el = XElement.Parse("
");
XAttribute firstAttr = el.FirstAttribute;
firstAttr.Remove();
el.SetAttributeValue(firstAttr.Name, firstAttr.Value);
Console.WriteLine(el);     //


text:
Q: Card Number Masking I'm trying to mask card number with regex.
First 6 and last 2 chars can be shown other should "*".
let cardNumber: String = "5890040000000016"

print("Output: ", cardNumber.mask(regexPattern:"XXXXXXX")) // Output: 589004********16

How can I do that in swift?

A: You can concatenate substrings together:
let cardNumber = "5890040000000016"

let start = cardNumber.startIndex ..< cardNumber.index(cardNumber.startIndex, offsetBy: 6)
let end = cardNumber.index(cardNumber.endIndex, offsetBy: -2) ..< cardNumber.endIndex
let result = cardNumber[start] + Array(repeating: "*", count: cardNumber.count - 8) + cardNumber[end]
print(result)

// Prints: 589004********16

A: Your question contains 2 important parts:
A regex that matches all characters but first 6 and last 2
let regexPattern = "(?<=.{6}).(?=.*.{2}$)"

and
An extension on the String that takes the regex and masks it:
extension String {

    func masked(matching regexPattern: String, with template: String = "*") throws -> String {
        let regex = try NSRegularExpression(pattern: regexPattern, options: NSRegularExpression.Options.caseInsensitive)
        let range = NSMakeRange(0, count)
        return regex.stringByReplacingMatches(in: self, options: [], range: range, withTemplate: template)
    }
}

Usage:
let cardNumber = "5890040000000016"
let regexPattern = "(?<=.{6}).(?=.*.{2}$)"

print("Output:", try! cardNumber.masked(matching: regexPattern))

Output: 589004********16

A: Perhaps you're looking for something like this:
let s = "5890040000000016"
let patt = ##"^(\d{6})(.*)(\d{2})$"## // this is your pattern
let reg = try! NSRegularExpression(pattern: patt, options: [])
if let m = reg.firstMatch(in: s, options: [], range: NSRange(s.startIndex..<s.endIndex, in: s)) {
    let r = m.range(at:2)
    let result = s.replacingCharacters(in: Range(r, in:s)!, with: String(repeating: "X", count: r.length))
    print(result) // 589004XXXXXXXX16
}


text:
Q: Python_ how to change my lines of result? def change_currency(sentence, rate):
    lines = sentence.splitlines()

    words = []
    for i in range(len(lines)):
        words.append(lines[i].split())
    true_wds = sum(words,[])
    for j in range(len(true_wds)):
        if j%4 ==3:
            true_wds[j] = 'YEN'
        elif j%4 ==2:
            true_wds[j] = str(float(true_wds[j])*rate)
        else:
            pass
    ans = ' '.join(true_wds)
    return ans

menu = """Pineapple : 1.5 USD
Biscit : 1 USD
Cupcake : 12 USD
"""

usd = 1000.0 # 1usd = 1000.0yen
result = change_currency(menu, usd)
print(result)

In this situation, my result of code is
Pineapple : 1500.0 YEN Biscit : 1000.0 YEN Cupcake : 12000.0 YEN

But, I want to change my result like this
Pineapple : 1500.0 YEN
Biscit : 1000.0 YEN
Cupcake : 12000.0 YEN

how can i solve this problem?

A: It is simple. Just add a new line character after "Yen" -
true_wds[j] = 'YEN\n'

Output:
 Pineapple : 1500.0 YEN
 Biscit : 1000.0 YEN
 Cupcake : 12000.0 YEN

A: You're making things complicated by flattening the list, because you're appending each word separately to true_wds.
Process each line at once, putting the result in a single element of true_wds. Then join that with newline instead of space.
def change_currency(sentence, rate):
    lines = sentence.splitlines()

    words = [line.split() for line in lines]
    true_wds = []
    for line in sentence.splitlines():
        item, colon, price, currency = line.split()
        true_wds.append(f"{item} : {float(price) * rate} YEN")
    ans = '\n'.join(true_wds)
    return ans

menu = """Pineapple : 1.5 USD
Biscit : 1 USD
Cupcake : 12 USD
"""

usd = 1000.0 # 1usd = 1000.0yen
result = change_currency(menu, usd)
print(result)


text:
Q: How can I creat a static variable which returns the last array index, in PHP? I want to create a function which a static variable because I need to preserve the variable value between functions. The first way, this variable include the last index an array, and the value will be changed the second run. If I use count() to search the last array index, I get the following error: Parse error: parse error, expecting ','' or';'' in C:\wamp\www\rekurzio\index.php on line 11
<form method="POST">
    Search the following number: <input type="number" name="numberQuestion">! <br>
    <input type="submit" name="search" value="Search">
</form>

<?php function search(){
            global $numberArray;
            $numberQuestion = $_POST['numberQuestion'];
            static $searchDirection = "RIGHT";
            static $lowerLimit = 0; //it is the first array index
            static $upperLimit = count($numberArray)-1 /* 8 */; //it is the last array index, but it doesn't work
            if($lowerLimit == $numberQuestion){
                $searchResult = "I found the $numberQuestion value which the $lowerLimit element";
                echo $searchResult;
            }else if($upperLimit == $numberQuestion){
                $searchResult = "I found the $numberQuestion value which the $upperLimit element";
                echo $searchResult;
            }else{
                $middleElement = ($lowerLimit+$upperLimit)/2;
                if($middleElement == $numberQuestion){
                    $searchResult = "I found the $numberQuestion value which the $middleElement element";
                    echo $searchResult;
                }else{
                    if($numberQuestion < $middleElement){
                        $searchDirection = "LEFT";
                    }else if($numberQuestion > $middleElement){
                        $searchDirection = "RIGHT";
                    }
                    if($searchDirection == "RIGHT"){
                        $lowerLimit = $middleElement;
                    }else if($searchDirection == "LEFT"){
                        $upperLimit = $middleElement;
                    }
                    search();
                }
            }
        }
        if(isset($_POST['search'])){
            search();
        } ?>

How can I search the last array index?

A: Static declarations are resolved in compile-time, therefore trying to assign values to these variables which are the result of expressions will cause a parse error. For reference, see the manual.
So static variables may only be initialized using a literal or constant; expressions are not allowed. While you may initialize a static variable to an integer or array (for instance), you may not initialize it to another variable, to a function return value, or to an object.
UPDATE:
In your case I would advise that the 3 static-scoped variables ($searchDirection, $lowerLimit and $upperLimit) be function parameters instead of static variables. In this case their scope is still local to the search function, however you may dynamically set the proper values before the initial and then the recursive calls of the function.

A: I could not comment because I do not have enough reputations.
I suggest you do two things:
First:  convert line 11 into
static $upperLimit = count($numberArray)-1; /* 8 */
Second, do var_dump($numberArray); before the line above. It seems that there is some sort of simple syntax error over there.


text:
Q: switch case em bash Meu switch case não está funcionando corretamente:
while getopts "hvo:umsf" OPTION
do
    case $OPTION in
        i) instalarSniper
        ;;
        h) help
        ;;
        s) simular
        ;;
        d) adicionais
        ;;
        ?) echo "Parametros incorretos, digite -h para ajuda"
        ;;
    esac
done

Mais especificamente, meus parâmetros -h e -s estão funcionando, mas se tento o -i ou -d, ele vai para o caso de parâmetros incorretos.
Alguém saberia me dizer o que está errado?

A: No getopts você deve passar as opções que são aceitas. Como não tem a letra i, ela não vai ser reconhecida. Colocando somente as opções que estão no case, fica assim:
while getopts "hisd" OPTION
do
    case $OPTION in
        i) instalarSniper
        ;;
        h) help
        ;;
        s) simular
        ;;
        d) adicionais
        ;;
        ?) echo "Parametros incorretos, digite -h para ajuda"
        ;;
    esac
done

Assim, os parâmetros aceitos são -h, -i, -s e -d.
Se quiser opções mais complexas, veja o tutorial de getopts.

A: A resposta de @hkotsubo está óptima, junto apenas mais a estrutura típica de um script
bash com opções e parâmetros, de acordo com os meus gostos pessoais:
#!/bin/bash

while getopts "hi:" OPT        ## processar opções
do
    case $OPT in
        i) iv=$OPTARG ; echo instalar $iv;;
        h) echo help           ; exit 0 ;;
       \?) echo "usage: $0 ..."; exit 1 ;;
    esac
done

shift $((OPTIND-1))            ## avançar até argumentos

for a in "$@"                  ## processar argumento
do
  echo "=== processar '$a'==="
done


text:
Q: script tables have one meaning I am a newbie. Sorry for my bad English.
$release = mysql_real_escape_string($_POST["release"]);
$numid = mysql_real_escape_string($_POST["numid"]);
$sql1 = mysql_query("UPDATE gg_cars SET release1='".$release."',numid='".$numid."' WHERE `avtor_id` = '".$_SESSION["id"]."' AND cat='1' ");

When user writes something in one row, all rows have the same meaning.
For example: If user writes in second row in "Release car to": John, and submits it, after refresh, all rows have written John in "release car to".

A: There are a few issues with this code:

*

*It uses the old mysql methods instead of mysqli.

*The where clause is using $_SESSION["id"] - which is a single value based on the session information instead of coming from the POST. This is the real cause of the submitted information being written to all rows.

*Real escape string should be used on all variables being passed to the query.


text:
Q: Percentage and Money Problem A client asks about a home mortgage for a property that is valued at $500,000. They explain that they need a 65% loan and can pay the remainder in cash as a down payment. How much is their down payment?
i) $175,000
ii) $275,000
iii) $325, 000
iv) $350,000
I know this might seem like a simple question, but I need to make sure I solve this example correctly before I start doing real questions. Can someone help me?
My work:
($500,000)(0.65) $= $325,000$
Then
$500,000 - $325,000 = $175,000
Answer is:
$175,000

A: Your work seems correct. Find the part of the total that the loan is covering and subtract that from the total to find what remains to be paid (as a down payment).


text:
Q: two commas on first page When I compile my document I get a very strange first page. It only has 2 commas and the pagenumber on it. Has anyone has this problem before or knows how to solve it? I have included a minimal example below including all packages I use. I am using Texmaker.
\documentclass[11pt, a4paper]{report}
\pagestyle{headings}
\usepackage{textcomp}
\usepackage[official]{eurosym}
\usepackage{epstopdf}
\usepackage[pdftex]{graphicx}
\usepackage{multirow}
\usepackage{array}
\usepackage{tabularx}
\usepackage{textcomp}
\usepackage[font={footnotesize}]{caption}
\usepackage{amsmath}
\usepackage[dutch]{babel}
\usepackage{courier}

\renewcommand{\labelenumi}{\arabic{enumi}}
\renewcommand{\labelenumii}{\arabic{enumi}.\arabic{enumii}}

\begin{document}
\title{Respect my authoritah!}, \author{Cartman, Eric}, \date{\today}
\maketitle

\end{document}

Thanks in advance for the help!

A: The code you have provided is not really a MWE. If you want a standard title page, then do
\documentclass{report}

\title{Respect my authoritah!}
\author{Cartman, Eric}
\date{\today}
\begin{document}
\maketitle
\end{document}

Presumably you want the title page to look different. Maybe something like
\documentclass{report}

\title{Respect my authoritah!}
\author{Cartman, Eric}
\date{\today}
\makeatletter
\renewcommand{\maketitle}{\@title, \@author, \@date}
\makeatother
\begin{document}
\maketitle
\end{document}


text:
Q: Can't make sqlite3 work on Ruby on Rails I just installed ruby on my windows 7 computer. I installed rails and sqlite3 with the gem. I then made my app work on local BUT I still seem to have problems with sqlite3. When I try this:
rake db:create

the only thing i get is an error:
Please install the sqlite3 adapter: "gem install activerecord-sqlite3-adapter" (sqlite3
is not part of the bundle. Add it to the GemFile).

I've been doing some digging here and there, and I could make this error go away adding this line to my GemFile:
gem "sqlite3", group: :sqlite3

And i got a new error:
no driver for sqlite3 found

I tried the 'bundle' command and I have both sqlite3 and sqlite3-ruby, I reinstalled everything but the problem won't go away. This is my gemFile, I hope it helps:
source 'https://rubygems.org'

gem 'rails', '3.2.12'

# Bundle edge Rails instead:
# gem 'rails', :git => 'git://github.com/rails/rails.git'

#I tried this too, but nothig changes
#gem 'sqlite3-ruby', :require => 'sqlite3'

gem 'sqlite3-ruby', '1.2.5', :require => 'sqlite3'
gem "sqlite3", group: :sqlite3

# Gems used only for assets and not required
# in production environments by default.
group :assets do
  gem 'sass-rails',   '~> 3.2.3'
  gem 'coffee-rails', '~> 3.2.1'

  # See https://github.com/sstephenson/execjs#readme for more supported runtimes
  # gem 'therubyracer', :platforms => :ruby

  gem 'uglifier', '>= 1.0.3'
end

gem 'jquery-rails'

I really don't know what to do. It's kind of frustrating, it seems like something is not (obviously) properly working with sqlite3, because fixing one error leads to a new error. How can I possibly fix this problem ?

A: To everybody who's going to have this problem. What I did to fix it was uninstall everything. I though that maybe since I had an updated version of everything, something might not be working properly, maybe some dependencies were wrongly addressed. So I reinstalled everything following this:
Rails Installer Website
Which will make you install everything you need to run your first RoR app. It might not be up to date but it works just fine. Sqlite3 works perfectly now and that was what I needed. I might try to update every single program later, right now I just need something that is actually working. Thanks to everybody else who tried to help.


text:
Q: Starting processes error in vb.net Sorry if this question is 'newbie'
So I have a code that opens some programs that were added to a listbox. These programs range from games to other applications I've made using VB.net to webpages.
I have a problem when I try to start some games. Say I have a button and the code is like this:
Private Sub btnCalculate_Click(sender As Object, e As EventArgs) Handles btnCalculate.Click

    Dim sDirectory1 = "C:\Games\Company of Heroes 2 Master Collection\RelicCoH2.exe"

    Process.Start(sDirectory1)

End Sub

The game is Company of Heroes 2, but it gives me the error 'Cannot find items file' outside of VB. And a few other games have similar errors too, but I can run them myself by directly starting the .exe. Do some programs need more permissions? I've tried running as admin to no avail. Over applications will work, such as applications I've made myself and games with launchers. Thanks.


text:
Q: XML select single node not returning anything I have the following method that is supposed to return a string that holds the calories for a given food item in an xml menu.
public string calorieCount(int choice)
    {
        string calCount = "250";
        XmlDocument doc = new XmlDocument();
        doc.Load(path);
        XmlElement root = doc.DocumentElement;
        XmlNode node = doc.SelectSingleNode("/menu/item[@name='Burger']/calories");
        string checker = node.Value;
        MessageBox.Show(checker);//returning nothing
        return checker;
    }

And my XML file looks like this:
<?xml version="1.0" encoding="utf-8" ?>
<menu>
  <!-- Burger -->
  <item name="Burger">
    <name>Burger</name>
    <price>$5.99</price>
    <calories>500</calories>
    <description>A burger made with 100% angus beef and grilled to your liking. Served     with fries</description>
    <count>25</count>
  </item>

Why is it returning an empty string? Is my call to SelectSingleNode incorrect?
Thank you in advance.

A: Use InnerText instead of Value
Replace
string checker = node.Value;

With
string checker = node.InnerText;


text:
Q: Disable multiple logic apps across different Resource Groups I have a use case where I want to disable the old Logic Apps that our company is no longer using. All the Logic App are present in different environments and needs to disabled from all, ex: dev, sit, uat, prod. Rather than going to different RGs and disabling them one by one I am trying to develop a script which takes the portion of the Logic App name and disables it across all the resource group.
I was following this article but it shows how to disable multiple logic apps under one resource group and not what I am trying to achieve. [https://www.integration-playbook.io/docs/properly-disable-logic-apps-in-powershell][1]
I tried making some changes in the script to solve my use case but not sure how to test it and make necessary adjustments. I am very new to Logic Apps and would appreciate if anyone can help me with this.
I have added the displayName parameter so that that particular logic app is disabled and not all under the resource group. But I am not sure how to move forward.
# This script disables or enables all Logic apps under given resource group
# ./DisableEnable-LogicApps.ps1 "FC-CUS-DEV-INT-RG" "Disabled"
# Parameters are resourceGroupName and Disabled | Enabled

param([string] $displayName, [string] $state)

function ChangeLogicAppState([string] $logicAppName, [string] $resourceGroupName, [string] $desiredState, [string] $displayName)
{
    Write-Host 'Checking logic app ' $logicAppName

    $logicApp = Get-AzLogicApp -displayName $displayName -Name $logicAppName
    Write-Host ($logicApp | Format-List | Out-String)

    $apiOperation = 'unknown'
    if($desiredState -eq 'Enabled')
    {
        $apiOperation = 'enable'
    }
    elseif($desiredState -eq 'Disabled')
    {
        $apiOperation = 'disable'
    }

    if($logicApp -eq $null)
    {
        Write-Host 'Logic App does not exist: ' $logicAppName
    }
    else
    {
        Write-Host 'Logic App does exist: ' $logicAppName

        $currentState = $logicApp.State.ToLower()
        if($currentState -eq $desiredState.ToLower())
        {
            Write-Host 'Logic App ' $logicApp.Name ' is already in the desired state'
            $script:Unchanged++
        }
        else
        {
            $url = 'https://management.azure.com/' + $logicApp.Id + '/' + $apiOperation + '?api-version=2016-06-01'
            $response = az rest --method post --uri $url
            $script:Changed++
            Write-Host 'Logic App Changed'

            $logicApp = Get-AzLogicApp -ResourceGroupName $resourceGroupName -Name $logicAppName
            Write-Host ($logicApp | Format-List | Out-String)
        }

    }
}

Write-Host '================================='
Write-Host 'Starting the script to: ' $state
Write-Host '*********************************'

#Declare variables
$Total = 0
$Changed = 0
$Unchanged = 0

#Get each logic app in loop
Write-Host 'Looping logic apps in Resource Group: ' $resourcegroupName
Get-AzureRmResource -ResourceType "Microsoft.Logic/workflows" -ResourceGroupName $resourcegroupName | ForEach-Object {
ChangeLogicAppState -logicAppName $_.Name -desiredState $state  -resourceGroupName $resourcegroupName
$Total++

}

Write-Host 'Summary:'
Write-Host '#################################'
Write-Host 'Total:' $Total ' Changed:' $Changed  ' Unchanged:' $Unchanged
Write-Host '#################################'

Write-Host '*********************************'
Write-Host 'Ending the script.'
Write-Host '================================='

A: Okay so most of the function within your script is redundant since the functionality is already present within Set-AzLogicApp already.
https://learn.microsoft.com/en-us/powershell/module/az.logicapp/set-azlogicapp?view=azps-7.5.0#syntax
Below is the basic usage of Set-AzLogicApp
Set-AzLogicApp -ResourceGroupName $rg -Name $logicAppName -State Disabled

Get-AzLogicApp Name Filtering
Unfortunately Get-AzLogicApp doesn't allow you to filter for all logic apps by a particular name as it requires you to pass the mandatory resourceGroup and Name parameters.
What you can do though is utilise Get-AzResource cmdlet which does allow wildcard search of resources.
Get-AzResource -ResourceType 'Microsoft.Logic/workflows' -ResourceName testlog*

You can then use the output to disable the logic apps based on a displayName filter.
The below script has been simplified from the example you were looking at earlier by using the cmdlets from the Az.LogicApp module
param (
    [Parameter(Mandatory)]
    [string]$displayName,

    [Parameter(Mandatory)]
    [ValidateSet('Enabled', 'Disabled')]
    [string]$State
)

# This will return all logic apps that start with the name testlog*
$logicApp = Get-AzResource -ResourceType 'Microsoft.Logic/workflows' -ResourceName $displayName*

# Loop through all returned logic apps and set the state
foreach ($app in $logicApp) {
    'Attempting to update state of: {0}' -f $app.Name
    Set-AzLogicApp -ResourceGroupName $app.ResourceGroupName -Name $app.Name -State $State -Force
}

I would normally have just used the pipeline and done something like
$logicApp | Set-AzLogicApp -State Disabled

However this doesn't appear to work on the latest version of the module as Name parameter does not take pipeline input.
I raised an issue on the Azure PowerShell repo to see if that could be fixed in a future release:
https://github.com/Azure/azure-powershell/issues/18053

A: You can enable/disable it from the Azure portal as shown below,


text:
Q: How to resolve an aborted request on awaited call to HttpStatusCode? I'm awaiting a call to send a push notification using the Aero Gear .Net client. The return value from the call to push is a System.Net.HttpStatusCode. The expected code if the push is successful is "Accepted".
But when I await the call to the SendPushNotification method, it throws a "The request was aborted. The connection was closed unexpectedly"error before the HttpStatusCode is returned from the method at this line:
System.Net.HttpStatusCode status = await client.Send(unifiedMessage);

I marked the call from the controller up to the push method as async, and added await where there was a call to an async method.
Question:
How can you resolve an aborted request on awaited call to HttpStatusCode?
This is a gist of the call trickled down from the initial call in the controller to the push class method:
Controller:
//In Controller Post action that calls SendPushNotification

[HttpPost]
public async Task<ActionResult> Index(Order exec_order)
{
    try
    {

        //Send a push notification with the order details
        try
        {
            MyLogger.FileLogger.Info("Before Push Notification");
            System.Net.HttpStatusCode status = await PushsClassLibrary.PushNotification.SendPushNotification(exec_order.Application", "Order Summary");
            MyLogger.FileLogger.Info("Push Notification Status: " + status);
        }
        catch (Exception ex) //request aborted error caught here
        {
            MyLogger.FileLogger.Error("Push Notification Exception -" + ex.Message);
        }

}

Push Class:
//In PushNotification class containing SendPushNotification
public static async Task<System.Net.HttpStatusCode> SendPushNotification(string messageToPush, string serviceName )
{
    string[] listUsers = users.ToArray();
    unifiedMessage.criteria.alias = listUsers;

    System.Net.HttpStatusCode status = await client.Send(unifiedMessage);
    return status;
}

A: I think that status code you will want to check is HttpStatusCode.OK and I'm pretty sure that the error you get: "The request was aborted. The connection was closed unexpectedly" is an exception. Are you sure that the AeroGear server is running and that you don't need Proxy configuration for your PushsClassLibrary?
Otherwise the AeroGear Project also has a C# sender library that you could use.


text:
Q: How to configure sonar.junit.reportPaths I have tried severally to configure this sonarqube property sonar.junit.reportPaths within Gradle but still get the same error message.
Gradle version -> 6.7.1
SonarQube Server version -> 8.9 (docker image)
Java version -> openjdk 11.0.2
Intellij version -> 2021.1.2
My Sonarqube Gradle configuration is as below:
plugins {
    id 'java'
    id 'jacoco'
    id "org.sonarqube" version "3.3"
    id 'org.jetbrains.kotlin.jvm' version '1.5.20'
}

sonarqube {
    properties {
        property 'sonar.projectName', 'Snippets of Java code'
        property 'sonar.junit.reportPaths', 'build/test-results/test'
        property 'sonar.coverage.jacoco.xmlReportPaths', 'build/reports/test/jacocoTestReport.xml'
        property 'sonar.inclusions', '*.java,*.kt'
    }
}

jacocoTestReport {
    reports {
        xml.required = true
        csv.required = false
    }
}

I still get the message below:
Resource not found: com.sammy.service.JavaFareTest under the directory /Users/samuelifere/IdeaProjects/codingChallenges while reading test reports. Please, make sure your "sonar.junit.reportPaths" property is configured properly
Resource not found: com.sammy.model.JavaCardTest under the directory /Users/samuelifere/IdeaProjects/codingChallenges while reading test reports. Please, make sure your "sonar.junit.reportPaths" property is configured properly

I read several stackoverflow pages such as these:
1, 2 but still didn't help in resolving my issue. Any help would be much appreciated, so it can properly find the resources.
The command I use to run to run this through Gradle is:
./gradlew clean build jacocoTestReport sonarqube


text:
Q: Populate variables based on met condition Ansible Does anyone know a good article that explains how I would populate variables based on a condition being met?
Example:
- name: test
  file:
    path: "{{ item.path }}"
    state: directory
    owner: "{{ item.owner }}"
    group: "{{ item.group }}"
    mode: 0755
  loop:
    - { path: "{{ file_location }}", owner: "{{ user }}", group: "{{ group }}" }
    - { path: "{{ configfile_path }}", owner: "{{ user }}", group: "{{ group }}"  }

Need to populate the first: owner: "{{ user }}", group: "{{ group }}" with a user and group named "X" when the machine is named XXX
Then populate the second: owner: "{{ user }}", group: "{{ group }}" with a user and group named "Y" when the machine is named YYY
I haven't tried anything yet because I am unsure how to tackle this, any pointers to documentation or examples would be greatly appreciated.
Thank you

A:
Q: "Populate owner: "x" ... when the machine is named XXX. Then populate owner: "y" ... when the machine is named YYY."

A: It's possible to use inventory. For example in INI format
$ cat hosts
XXX owner='x' group='x'
YYY owner='y' group='y'

, or in YAML
$ cat hosts
---
  hosts:
    XXX:
      owner: 'x'
      group: 'x'
    YYY:
      owner: 'y'
      group: 'y'

, or it is possible to use host_vars
$ tree host_vars
host_vars
├── XXX
├── YYY

$ cat host_vars/XXX
owner: 'x'
group: 'x'

$ cat host_vars/YYY
owner: 'y'
group: 'y'

See Variable precedence: Where should I put a variable?.

A: You could do this with the set_fact module and when clauses.
set_fact:

Synopsis

*

*This module allows setting new variables.

*Variables are set on a host-by-host basis just like facts discovered by the setup module.

*These variables will be available to subsequent plays during an ansible-playbook run.

- set_fact:
    one_fact: something
    other_fact: "{{ local_var * 2 }}"
    another_fact: "{{ some_registered_var.results | map(attribute='ansible_facts.some_fact') | list }}"

when:

Sometimes you will want to skip a particular step on a particular host. This could be something as simple as not installing a certain package if the operating system is a particular version, or it could be something like performing some cleanup steps if a filesystem is getting full.
This is easy to do in Ansible with the when clause, which contains a raw Jinja2 expression without double curly braces (see group_by – Create Ansible groups based on facts). It's actually pretty simple:
tasks:
  - name: "shut down Debian flavored systems"
    command: /sbin/shutdown -t now
    when: ansible_facts['os_family'] == "Debian"


text:
Q: Trying to add a collection to a model and render it in multiple places in a view I'm trying to build an app that allows you to create items in a view in multiple places.
For instance, I can add a model from a collection when I create a new model in the parent collection.
The problem I'm having is, when I add the collection to the model and it iterates, it's adding the collection for each loop. So it ends up with LOTS of collections in the model that are repeated.
The parent model render has the following loop:
        this.noteTasksViewAdding = new NoteTaskListViewAdding({ collection: tasks });
        $('.note-tasks-list-all').append(this.noteTasksViewAdding.render().el);
        this.collection.each(function(note){
            var view = new NoteView({ model: note });
            $('#items-list').prepend(view.render().el);
        });

Then the model has the following render in it:
    render: function() {
        this.noteTasksViewAdding = new NoteTaskListViewAdding({ collection: tasks });
        $('.note-tasks-list-all').append(this.noteTasksViewAdding.render().el);
        this.$el.html(this.template(this.model.toJSON()));
        return this;
    }

What I want to have happen is that the collection is added to the model when it's rendered. I'm open to any suggestions on how to do this better.
Thanks!

A: I faced the problem as well. The solution is to clear the view before you set the collection. In your case, when you set parent view, you might do this:
$('.note-tasks-list-all').html(this.noteTasksViewAdding.render().el);

Then you can append your collection members.


text:
Q: Axios won't post and throws "network error" const Sign_up = () => {
    const [UserRegisteration] = useRegisterUserMutation();
    "127.0.0.1:8000/api/register/"
    const [homeScreen, setHomeScreen] = React.useState({
        username :'',
        email : '',
        password : '',
        repassword: '',
        // tc : null,

    });
    const navigateCheck = async () => {
        const formData = {username : homeScreen.username, email : homeScreen.email, password: homeScreen.password, repassword: homeScreen.repassword, tc : homeScreen.tc}
        if (homeScreen.password === homeScreen.repassword){
            axios.post('http://localhost:8000/api/register/', {
                formData
            })
                .then(function (response) {
                    console.log(response);
                })
                .catch(function (error) {
                    console.log(error);
                });
            const res = await UserRegisteration(formData)
            console.log("Response", res)
            if (res.data) {
                console.log("Response Data", res.data)
                await storeToken(res.data.token)  // Store Token in Storage
                clearTextInput()
                navigation.navigate('HomeScreen')
            }
        }
             else {
                ;Alert.alert(
                    "Incorrect E-mail",
                    "You entered your E-mail/password incorrectly",
                    [
                        {text: "OK", onPress: () => console.log("pressed ok")}
                    ]
                );
            }
        }

I get the response of  LOG  Response {"error": {"error": "TypeError: Network request failed", "status": "FETCH_ERROR"}}
LOG  [AxiosError: Network Error]
please help
I tried using other method but they all failed too