text:
Q: What is the correct way to represent null XML elements? I have seen null elements represented in several ways:
The element is present with xsi:nil="true":
 <book>
     <title>Beowulf</title>
     <author xsi:nil="true"/>
 </book>

The element is present, but represented as an empty element (which I believe is wrong since 'empty' and null are semantically different):
 <book>
     <title>Beowulf</title>
     <author/>
 </book>

 <!-- or: -->
 <book>
     <title>Beowulf</title>
     <author></author>
 </book>

The element is not present at all in the returned markup:
 <book>
     <title>Beowulf</title>
 </book>

The element has a <null/> child element (from TStamper below):
 <book>
     <title>Beowulf</title>
     <author><null/></author>
 </book>

Is there a correct, or canonical way to represent such a null value? Are there additional ways than the above examples?
The XML for the examples above is contrived, so don't read too far into it. :)

A: It depends on how you validate your XML. If you use XML Schema validation, the correct way of representing null values is with the xsi:nil attribute.
[Source]

A: The documentation in the w3 link:
http://www.w3.org/TR/REC-xml/#sec-starttags
says that these are the recommended forms:
<test></test>
<test/>

The attribute mentioned in the other answer is a validation mechanism and not a representation of state. Please refer to: http://www.w3.org/TR/xmlschema-1/#xsi_nil

XML Schema: Structures introduces a mechanism for signaling that an
element should be accepted as ·valid· when it has no content despite a
content type which does not require or even necessarily allow empty
content. An element may be ·valid· without content if it has the
attribute xsi:nil with the value true. An element so labeled must be
empty, but can carry attributes if permitted by the corresponding
complex type.

To clarify this answer:
<?xml version="1.0" encoding="utf-8" ?>
<Books>
  <Book>
    <!--This element should alway be empty-->
    <BuildAttributes HardCover="true" Glued="true" xsi:nil="true"/>
    <Index></Index>
    <pages>
      <page pageNumber="1">Content</page>
    </pages>
    <!--Valid representation of a null or empty ISBN-->
    <ISBN></ISBN>
  </Book>

  <Book>
    <!--Invalid construct since the element attribute xsi:nil="true" signal that the element must be empty-->
    <BuildAttributes HardCover="true" Glued="true" xsi:nil="true">
      <anotherAttribute name="Color">Blue</anotherAttribute>
    </BuildAttributes>
    <Index></Index>
    <pages>
      <page pageNumber="1">Content</page>
    </pages>
    <!--Missing ISBN could be confusing and misguiding since its not present-->
  </Book>
</Books>

A: You use xsi:nil when your schema semantics indicate that an element has a default value, and that the default value should be used if the element isn't present.  I have to assume that there are smart people to whom the preceding sentence is not a self-evidently terrible idea, but it sounds like nine kinds of bad to me.  Every XML format I've ever worked with represents null values by omitting the element.  (Or attribute, and good luck marking an attribute with xsi:nil.)

A: Simply omitting the attribute or element works well in less formal data.
If you need more sophisticated information, the GML schemas add the attribute nilReason, eg: in GeoSciML:

*

*xsi:nil with a value of "true" is used to indicate that no value is available

*nilReason may be used to record additional information for missing values; this may be one of the standard GML reasons (missing, inapplicable, withheld, unknown), or text prepended by other:, or may be a URI link to a more detailed explanation.

When you are exchanging data, the role for which XML is commonly used, data sent to one recipient or for a given purpose may have content obscured that would be available to someone else who paid or had different authentication. Knowing the reason why content was missing can be very important.
Scientists also are concerned with why information is missing. For example, if it was dropped for quality reasons, they may want to see the original bad data.

A: In many cases the purpose of a Null value is to serve for a data value that was not present in a previous version of your application.
So say you have an xml file from your application "ReportMaster" version 1.
Now in ReportMaster version 2 a some more attributes have been added that may or not be defined.
If you use the 'no tag means null' representation you get automatic backward compatibility for reading your ReportMaster 1 xml file.

A: There is no canonical answer, since XML fundamentally has no null concept.
But I assume you want Xml/Object mapping (since object graphs have nulls); so the answer for you is "whatever your tool uses". If you write handling, that means whatever you prefer. For tools that use XML Schema, xsi:nil is the way to go. For most mappers, omitting matching element/attribute is the way to do it.

A: xsi:nil is the correct way to represent a value such that:
When the DOM Level 2 call getElementValue() is issued, the NULL value is returned.
xsi:nil is also used to indicate a valid element with no content even if that elements content type normally doesn't allow empty elements.
If an empty tag is used, getElementValue() returns the empty string ("")
If the tag is omitted, then no author tag is even present. This may be semantically different than setting it to 'nil' (Ex. Setting "Series" to nil may be that the book belongs to no series, while omitting series could mean that series is an inapplicable element to the current element.)
From: The W3C

XML Schema: Structures introduces a
  mechanism for signaling that an
  element should be accepted as ·valid·
  when it has no content despite a
  content type which does not require or
  even necessarily allow empty content.
  An element may be ·valid· without
  content if it has the attribute
  xsi:nil with the value true. An
  element so labeled must be empty, but
  can carry attributes if permitted by
  the corresponding complex type.

A clarification:
If you have a book xml element and one of the child elements is book:series you have several options when filling it out:

*

*Removing the element entirely - This can be done when you wish to indicate that series does not apply to this book or that book is not part of a series. In this case xsl transforms (or other event based processors) that have a template that matches book:series will never be called. For example, if your xsl turns the book element into table row (xhtml:tr) you may get the incorrect number of table cells (xhtml:td) using this method.

*Leaving the element empty - This could indicate that the series is "", or is unknown, or that the book is not part of a series. Any xsl transform (or other evernt based parser) that matches book:series will be called. The value of current() will be "". You will get the same number of xhtml:td tags using this method as with the next described one.

*Using xsi:nil="true" - This signifies that the book:series element is NULL, not just empty. Your xsl transform (or other event based parser) that have a template matching book:series will be called. The value of current() will be empty (not empty string). The main  difference between this method and (2) is that the schema type of book:series does not need to allow the empty string ("") as a valid value. This makes no real sense for a series element, but for a language element that is defined as an enumerated type in the schema, xsi:nil="true" allows the element to have no data. Another example would be elements of type decimal. If you want them to be empty you can union an enumerated string that only allows "" and a decimal, or use a decimal that is nillable.


text:
Q: Conditional with queryset doesn't exist exception in django without using try/except I need to make an "if" condition with a queryset result as follows :
group_child = Groups.objects.get(subgroup = kwargs["group_id"])
            if group_child is None:
                group = get_object_or_404(Groups, group = kwargs["group_id"])
                group.logic_delete()
                messages.success(request, "Deleted successfull")
            else:
                messages.error(request, "It has elements asociated")

But code never enters the conditional if queryset doesn't exist cause of course, it throws a django exception and also, im not sure if "is None" is valid at all in this scenario.
I know one way to solve it it's using try/except to capture the exception but i wana know if there's another way so i can use the "if" statement as i need.
Thanks in advance

A: .get() raises an exception if the object is not present in the database. You can use a combination of .filter() and .exists() like this:
group_child_qs = Groups.objects.filter(subgroup = kwargs["group_id"])
if group_child_qs.exists():
    group = group_child_qs.first()
    group.logic_delete()
    messages.success(request, "Deleted successfully")
else:
    messages.error(request, "It has elements associated")

EDIT:
As @knbk mentions, here is a more optimized solution
group = Groups.objects.filter(subgroup = kwargs["group_id"]).first()
if group:
    group.logic_delete()
    messages.success(request, "Deleted successfully")
else:
    messages.error(request, "It has elements associated")

redpajama_set_name: RedPajamaStackExchange


text:
Q: Changes do not affevt on the map function and do not show :) I'm building a chat app basically i'm calling a function that get the message and push it to an array of objects the array looks like this
newChat = [{message: "new message ", className: "you", date: new Date()}]

and the code looks like this
const send_message = (message) => {
    newChat.push({
        message: message,
        className: 'you',
        date: new Date().toString()
    })
    console.log(newChat)
}
const [message, setmessage] = useState(null)

return (

        {
            newChat.map((message, index) => (

                        <h1 className={`message-${message.className}`}>{message.message}

{message.date.split('T')[0] + ' ' + message.date.split('T')[1]}

            ))
        }

            <Input onChange={(e) => setmessage(e.target.value)} placeholder="Write a message" />
            <Button onClick={() => send_message(message)} type="primary">Send</Button>

)

}
export default Chat
the problem is that the message get pushed to the array but do not show on the screen any suggestions please :)

A: React re-render when state or props has changed. To update component whenever newchat changes, you need to declare it as a state.
const [newChat, setNewChat] = useState([{message: "new message ", className: "you", date: new Date()}])

const send_message = (message) => {
    setNewChat([
       ...newChat,
       {
          message: message,
          className: 'you',
          date: new Date().toString()
       }
    ]);
}


text:
Q: Markdown multiline code blocks in tables when rows have to be specified with one-liners I have a table:
| YAY! | TABLE | \^^/ | 1-liner JSON column! |
| ---- | ----- | ---- | -------------------- |
| That |  has  | JSON | `{a: 1, b: 2, c: 3}` |
| Here |  is   | more | `{d: 4, e: 5, f: 6}` |

Is there any way for me to insert in multiline code blocks into a generated table cell?

A: Replace ` with  tags and use   and
for indentation.
Similarly you can use
 tags instead of ```.

A: Answer by @Meredith is the perfect answer to this. I'd like to add more details and examples below
You cannot replace ` with <code> if you need to add other HTML tags inside the <code> element in your table cell. Instead you need to use backtick (`) inside the
 tag like this:

Markdown Input
HTML Output
HTML Preview

Test Line

Test line

Test Line

Example 2:

Markdown Input
HTML Output
HTML Preview

`{a: 1, b: 2, c: 3}`
{a: 1, b: 2, c: 3}
{a: 1, b: 2, c: 3}

 {JSON:
  ["Key1":"Value1",
  "Key2":"Value2"]
}

 {JSON:
  ["Key1":"Value1",
  "Key2":"Value2"]
 }

{JSON:  ["Key1":"Value1", "Key2":"Value2"]}


text:
Q: ASP.NET Attempt to attach auto-named a database failed?
Parser Error Message: An attempt to
  attach an auto-named database for file
  D:\Projects\Damnation\Damnation.Website\Damnation.Website.Tracker\BugNET_WAP\App_Data\aspnetdb.mdf
  failed. A database with the same name
  exists, or specified file cannot be
  opened, or it is located on UNC share.

Why could this be happening? My connection string doesn't use |DataDirectory|, it is:
<connectionStrings>
  <add name="BugNET" connectionString="Data Source=.\SQLEXPRESS;Initial Catalog=dnmain;Integrated Security=True;"/>
</connectionStrings>

I get this error when I try to load default.aspx, after installing BugNET.

A: Apparently, and certainly for some obscure reason. There is a mistery connection string coming from... nowhere.
Problem solved adding a <clear/> tag.
<connectionStrings>
  <clear/>
  <add name="BugNET" connectionString="Data Source=.\SQLEXPRESS;Initial Catalog=dnmain;Integrated Security=True;"/>
</connectionStrings>

A:
file
  D:\Projects\Damnation\Damnation.Website\Damnation.Website.Tracker\BugNET_WAP\App_Data**aspnetdb.mdf**
  failed.

This is the ASP.NET standard membership system here - not your "regular" database. There must be a second connection string somewhere that references this aspnetdb.mdf and tries to attach it from a file.
Search your solution for this file name - it must be somewhere!


text:
Q: code hangs when running interactive shell using paramiko I have written below code to run 3 command in remote server interactively
But when I checked 3rd command never executed and code stuck here is my code
def execute():
    ssh = paramiko.SSHClient()
    ssh.set_missing_host_key_policy(paramiko.AutoAddPolicy())
    ssh.connect('ipaddress', username='user', password='pw')

    chan = ssh.invoke_shell()  # start the shell before sending commands

    chan.send('cd /path to folder/test')
    chan.send('\n')
    time.sleep(3)
    chan.send("ls -l")
    chan.send('\n')
    buff = ''
    while not buff.endswith("test >"):
        resp = chan.recv(9999)
        # code stuck here after 'path to folder/test >' comes in shell prompt
        buff += resp
        print resp

    print "test"
    chan.send("ls -lh")
    chan.send('\n')
    time.sleep(5)
    buff = ''
    while not buff.endswith("test >"):
        resp = chan.recv(9999)
        buff += resp
        print resp

if __name__ == "__main__":
    execute()

When I ran I got output of ls -l but ls -lh never executed my code stuck in first while loop. Anyone please help to resolve my issue

A: The code has following 2 errors:

*

*The call to channel.recv is blocking, you should first check if channel has any data to be read or not using channel.recv_ready()

*Also don't use  buff.endswith("test >") as a condition.As
the file_name might not always be at the last in buff.
Change the while block to following and it will run the way you want
    while "test >" not in buff:
        if chan.recv_ready():
            resp = chan.recv(9999)
            # code won't stuck here
            buff+=resp
            print resp

A: Unable to leave a comment, but @divyam jaiswal had a great solution!
Here's the Python 3 version:
while "test >" not in buff:
    if chan.recv_ready():
        resp = chan.recv(9999).decode("utf-8")
        # code won't get stuck here
        buff += resp
        print(resp)


text:
Q: Wordpress Plugin, get HTML page or post content as a string I am building a word press plugin and I need to get back the page and post content as an html string. I want it back as a string so that I can search the DOM for particular elements with a tag and then do something with those elements when found.
The problem is when I use
the_content();

or
$content = apply_filters('the_content', $the_content());

It seems to always display (render) the content on my plugin page which is not what I want. I just want the output back as a string.

A: This is wrong
$the_content()

To be honest I am not sure how that works with a $, but any call to the_content() will just output it.
You can use

get_the_content( string $more_link_text = null, bool $strip_teaser = false )
Retrieve the post content [as a string]

In any case you can always use output buffering, if no other way exists
ob_start();
the_content();
$content = ob_get_clean();

you can see this answer about what Output buffering is.
What is output buffering?
Basically when you output "stuff" it goes into a buffer, normally you have no control over this and it eventually gets dumped into the response.  With output buffering you can capture that "stuff" into a buffer you can control.
Obviously it's preferable to use a method that returns a string directly, I just thought I would share the Output buffering "method" in case you need that ability for something that does not provide such a method.
Cheers!


text:
Q: Custom entity search and display I am developing a custom plugin that adds a new product entity with its own tables to the database.
I would like to perform custom queries on those products through a custom search form -the classic search input with "advanced search" options-.
The results should be displayed in a list, with links to individual items.
What would be considered a best practice for implmenting both plugin and theme?
I have thought of writing a plugin that performs all CRUD oeprations, and a custom theme to display the results:

*

*The plugin will add backend forms to let the admin perform basic operations on products.

*The theme will include myproduct-results.php and myproduct.php templates to render both search results and individual products.

*The search box and advanced search options will be rendered throug shortcodes written in funcions.php inside the theme.
Are there better options to make the plugin and template be as independant to each other as possible?
Are there any design patterns that provide general guidance on separation of concerns relative to Wordpress plugins and themes development?

A: I think you're over thinking things. I'd simply create a new Custom Post in the plugin. That will come with it's own backend automatically.
You can then create the individual pages based on the Template Hierarchy for both the listings and individual pages.
For any additional fields you need, you can either set the meta fields to show on the backend or add them via a plugin such as Advanced Custom Fields
Amend wp-query when searching to do queries on your metadata.
That should be enough to get you going.
I personally don't like the way WordPress does things, so I'm not sure exactly how much separation you will be able to achieve. But a good rule of thumb I find is to try and use the built in functions as much as possible, rather than building your own solution.


text:
Q: opengl and Texture mapping with vb.net I use OpenTK with VB.net and I want to add the texture mapping to my code, with the following steps:
1: Loading the texture:
Protected Sub LoadTexture(ByVal textureId As Integer, ByVal filename As String)
    Dim bmp As New Bitmap(filename)
    Dim data As BitmapData = bmp.LockBits(New Rectangle(0, 0, bmp.Width, bmp.Height),
                                            System.Drawing.Imaging.ImageLockMode.ReadOnly,
                                            System.Drawing.Imaging.PixelFormat.Format32bppArgb)

    GL.BindTexture(TextureTarget.Texture2D, textureId)
    GL.TexImage2D(TextureTarget.Texture2D, 0, PixelInternalFormat.Rgba,
                  bmp.Width, bmp.Height, 0, OpenGL.PixelFormat.Bgra,
                  PixelType.UnsignedByte, data.Scan0)

    bmp.UnlockBits(data)
    GL.TexParameter(TextureTarget.Texture2D, TextureParameterName.TextureMinFilter, TextureMinFilter.Linear)
    GL.TexParameter(TextureTarget.Texture2D, TextureParameterName.TextureMagFilter, TextureMagFilter.Linear)
End Sub

2: Enabling and adding:
GL.Enable(EnableCap.DepthTest)
GL.Enable(EnableCap.Texture2D)
GL.GenTextures(textures.Length, textures)
LoadTexture(textures(0), "bricks.bmp")

3: Painting (with GlControl1 loaded, in the GlControl1 Paint):
GL.PushMatrix()
GL.BindTexture(TextureTarget.Texture2D, textures(0))
GL.TexParameter(TextureTarget.Texture2D, TextureParameterName.TextureMinFilter, TextureMinFilter.Linear)
GL.TexParameter(TextureTarget.Texture2D, TextureParameterName.TextureMagFilter, TextureMagFilter.Linear)
GL.Begin(BeginMode.Quads)
GL.Color3(Color.White)
GL.TexCoord2(0.0, 1.0)
GL.Vertex3(200, 0, 200)
GL.TexCoord2(0.0, 1.0)
GL.Vertex3(200, 100, 200)
GL.TexCoord2(0.0, 1.0)
GL.Vertex3(200, 100, -200)
GL.TexCoord2(0.0, 1.0)
GL.Vertex3(200, 0, -200)
GL.End()
GL.PopMatrix()

When i run my code, I get this error: argument Exception was unhandled for this line Dim bmp As New Bitmap(filename).
the exception is (parameter is not valid) like the images

Try And Catch exception

note : I added the image in the root file like this
the Image Place

I used opengl and texture in c++ but I don't have this problem ,my be the error can be in Loading texture function or in another place
the all code :

Imports OpenTK
Imports OpenTK.Graphics
Imports OpenTK.Graphics.OpenGL
Imports System.Drawing.Imaging
Imports System.Drawing

Public Class Form2

Dim loaded As Boolean = False
Protected textures(2) As Integer

Protected Sub LoadTexture(ByVal textureId As Integer, ByVal filename As String)
    Try

        Dim bmp As New Bitmap(filename)

        Dim data As BitmapData = bmp.LockBits(New Rectangle(0, 0, bmp.Width, bmp.Height),
                                                System.Drawing.Imaging.ImageLockMode.ReadOnly,
                                                System.Drawing.Imaging.PixelFormat.Format32bppArgb)

        GL.BindTexture(TextureTarget.Texture2D, textureId)
        GL.TexImage2D(TextureTarget.Texture2D, 0, PixelInternalFormat.Rgba,
                      bmp.Width, bmp.Height, 0, OpenGL.PixelFormat.Bgra,
                      PixelType.UnsignedByte, data.Scan0)

        bmp.UnlockBits(data)
    Catch ex As Exception
        MsgBox(ex.Message)

    End Try
    GL.TexParameter(TextureTarget.Texture2D, TextureParameterName.TextureMinFilter, TextureMinFilter.Linear)
    GL.TexParameter(TextureTarget.Texture2D, TextureParameterName.TextureMagFilter, TextureMagFilter.Linear)

End Sub

Protected Overrides Sub OnLoad(ByVal e As System.EventArgs)
    MyBase.OnLoad(e)
    GL.ClearColor(0.5, 0.5, 0.6, 0)
    GL.Enable(EnableCap.DepthTest)
    GL.Enable(EnableCap.Texture2D)

    LoadTextures()
End Sub
Protected Sub LoadTextures()
    GL.GenTextures(textures.Length, textures)
    LoadTexture(textures(0), "bricks.bmp")
End Sub

Private Sub GlControl1_Load(ByVal sender As System.Object, ByVal e As System.EventArgs) Handles GlControl1.Load

    GL.ClearColor(Color.Black)

    loaded = True

End Sub
Private Sub NumericUpDown1_ValueChanged(ByVal sender As System.Object, ByVal e As System.EventArgs) Handles NumericUpDown1.ValueChanged

    GlControl1.Invalidate()
End Sub
Private Sub NumericUpDown2_ValueChanged(ByVal sender As System.Object, ByVal e As System.EventArgs) Handles NumericUpDown2.ValueChanged

    GlControl1.Invalidate()
End Sub
Private Sub GlControl1_Paint(ByVal sender As Object, ByVal e As System.Windows.Forms.PaintEventArgs) Handles GlControl1.Paint

    GL.Clear(ClearBufferMask.ColorBufferBit)
    GL.Clear(ClearBufferMask.DepthBufferBit)

    Dim perspective As Matrix4 = Matrix4.CreatePerspectiveFieldOfView(1.04, 4 / 3, 1, 10000)
    Dim lookat As Matrix4 = Matrix4.LookAt(10, 0, 0, 300, 0, 0, 0, 1, 0)
    GL.MatrixMode(MatrixMode.Projection)
    GL.LoadIdentity()
    GL.LoadMatrix(perspective)
    GL.MatrixMode(MatrixMode.Modelview)
    GL.LoadIdentity()
    GL.LoadMatrix(lookat)
    GL.Viewport(0, 0, GlControl1.Width, GlControl1.Height)
    GL.Enable(EnableCap.DepthTest)
    GL.DepthFunc(DepthFunction.Less)

    GL.Rotate(NumericUpDown1.Value, 0, 0, 1)
    GL.Rotate(NumericUpDown2.Value, 0, 1, 0)

    GL.PushMatrix()

    GL.Begin(BeginMode.Quads)
    GL.Color3(Color.White)
    GL.TexCoord2(0.0, 1.0)
    GL.Vertex3(200, 0, 200)
    GL.TexCoord2(0.0, 1.0)
    GL.Vertex3(200, 100, 200)
    GL.TexCoord2(0.0, 1.0)
    GL.Vertex3(200, 100, -200)
    GL.TexCoord2(0.0, 1.0)
    GL.Vertex3(200, 0, -200)
    GL.End()
    GL.PopMatrix()

    GraphicsContext.CurrentContext.VSync = True
    GlControl1.SwapBuffers()
End Sub
End Class


text:
Q: How do I layout code in a website with a common header import and jquery scripts? Let's say I have a website, and on every page I import a header and footer that are constant.
<jsp:include page="header.jsp" />

<!-- Page contents go here. -->

<jsp:include page="footer.jsp" />

I tend to put my javascript code in the page header, but I don't want every page to have to load the java script for every other page.  Equally, I don't really like my javascript being strewn throughout the content portion of all of my pages between the header/footer tags.
Is there a standard way of dealing with this?  I'm fairly new to web development, so I'm sure there's a standard convention I just haven't run across yet.

A: Sure, I do the same thing with php.
I split my header into two, so I include three items:
<jsp:include page="headerTop.jsp" />
<!-- custom CSS links go here -->
<!-- javascript references go here -->
<!-- custom javascript goes here -->
<jsp:include page="headerBottom.jsp" />

<!-- Page contents go here. -->

<jsp:include page="footer.jsp" />

The headerTop.jsp file would contain the <head> tag, and the headerBottom.jsp file would contain the closing </head> tag.

A: combining with the first answer you could create a separate file webresources.jsp where you put in the css and javascript and then include the file to your pages:
<jsp:include page="headerTop.jsp" />
<jsp:include page="webresources.jsp" />
<jsp:include page="headerBottom.jsp" />

<!-- Page contents go here. -->

<jsp:include page="footer.jsp" />


text:
Q: Mock open function calls nothing I have a problem with Mock open file testing. When im trying to get mock_calls it returns to me [call()], and when im doing assert_called_once_with i get an exception:
AssertionError: expected call not found.
Expected: open('test.txt', 'w')
Actual: open()
I really can't figure out what i am doing wrong.
Thats the code:
class TestFileData(unittest.TestCase):
    def test_save_data(self):

        m = mock_open()
        with patch('{}.open'.format('task_4'), new_callable=m, create=True) as f:
            with open('test.txt', 'w') as h:
                h.write('this is text')
                print(m.mock_calls)
                m.assert_called_once_with('test.txt', 'w')


text:
Q: CompletionException:client.HttpClientErrorException: 400 and server side HTTP request parsing errors RFC 7230 and has been ignored In my application I call an external API using RestTemplate post method, but the API doesn't accept my request. It's returning java.util.concurrent.CompletionException: org.springframework.web.client.HttpClientErrorException: 400 I am able to access the API via Swagger and Postman. I pass the same value and it's working
Server side I am getting: Error parsing HTTP request header Note: further occurrences of HTTP request parsing errors will be logged at DEBUG level does not conform to RFC 7230 and has been ignored.
my pgm below
 HttpHeaders httpHeaders = new HttpHeaders();
 httpHeaders.add(HttpHeaders.AUTHORIZATION, "Bearer " + "wwwwwwwwwww");
 httpHeaders.add(HttpHeaders.CONTENT_TYPE, MediaType.APPLICATION_JSON_VALUE);
 httpHeaders.add(HttpHeaders.ACCEPT, "*/*");
 httpHeaders.set("key","value");// this is dummy value for this forum
 restTemplate.exchange(join("http://", localhost:9898, "/testData"), POST,
                                    new HttpEntity<>(requestObj.toString(), httpHeaders), String.class)


text:
Q: R: how to add a column into a data matrix with first 1599 rows as "redwine" and next 5000 rows as "whitewine" I want to add a column named "Type" into a data matrix which has 6497 rows.
for 1 to 1599 rows in the column, I want to put in value"redwine", and for 1600 to 6497 rows, I want to put in value "whitewine".
How can I realize this code in R?
Thank you so much because I am a new learner.

A: if you have a data.frame called x, you could use
x$Type <- NA
x$Type[1 : 1599] <- "redwine"
x$Type[1600 : 6497 ] <- "whitewine"

if x is a matrix:
cbind(x, c(rep("redwine",1599), rep("whitewine",6497 - 1599)))

A: Hello data.frame
The data frame is a convenient storage device for problems in R. It is a lot like the matrix that you spoke of in your problem statement. Here is one way to use a data.frame object in R to contain your 1 column of data with N rows.
Create your lists, containing the data you want
list1 <- rep("red",1599)# replicate is build into R, it will clone the first argument, by the second argument's number of times, and return it as a list.
list2 <- rep("white", 4898)
list3 <- list(list1, list2) # this is a list object, containing 2 other lists, accessible via this notation list3[[1]] gets your red wines, and list3[[2]] gets your white wines.
list_flattened <- unlist(list3) # This turns a list of lists, into 1 list of unified items.

df <- data.frame(Type=list_flattened) # this creates a matrix like object, with a column named Type and its entries (or rows) as that big list we generated.

> head(df)# helper function to print the first 5 rows of the df
  Type
1  red
2  red
3  red
4  red
5  red
6  red
> tail(df) # helper function to print the last 5 rows of the df
      Type
6492 white
6493 white
6494 white
6495 white
6496 white
6497 white

Hope this helps!


text:
Q: Change color of a most controls (ie TPanel) in a Firemonkey app in Delphi (XE2 Update4 and XE3 only) NOTE: This question is about a behaviour in delphi XE2 update 4, and delphi XE3, and the style system was changed in XE4, so this question does not apply to Delphi versions XE4 and up.
Many controls like TPanel and so on, do not support a simple way to change color of any element without going into the "Styles" feature.
The way I think it's supposed to work is:

*

*Create a form.

*Put a StyleBook on the form.

*Change or create a style.

*Apply a style to the control.

*Control changes color.

Let's leave aside the fact that something that should be easy (as it was in the VCL) is now convoluted by Styles. What are the actual working steps for Delphi XE2 (Firemonkey Update4) to make a TPanel blue instead of gray (its defaults)?
Actual results: When I try the above, I get a freeze-up lasting about 30 seconds, memory usage exceeding 1 gb of memory for bds.exe, and then I get a crash.Sometimes I get "AQReporter.dll needs to close", and sometimes other errors from other IDE plugins, finally an "Embarcadero RAD Studio for Windows has stopped working" error.

A: It turns out that among other bugs, sometimes the TForm.StyleBook property does not automatically get assigned. If you make sure it is assigned, then the above steps work.
Quick steps:

*

*Create form.

*Drop style book on form, and assign Form.StyleBook = StyleBook1

*Right click on control you wish to modify style on, click Edit Custom Style.

*Go to object inspector and modify Fill property to change background color of panel, for instance.

*Apply and close. (May have to click two, three or four times due to window focus bugs)

Note: This workaround is not useful in Delphi XE4 and up as the feature "Custom style setting" was removed from Mobile application FMX.

A: Following on from Warrens answer, for Delphi versions newer than the ones he was using, XE4 and up, to modify the style of the panel at runtime you need to change the style in the style book and then re-assign the style to the panel.  Specifically:
var
  R: TFMXObject;
begin
  R := StyleBook1.Style.FindStyleResource('Panel1Style1');
  if R is TRectangle then
    TRectangle(R).Fill.Color := claRed;

  Panel1.StyleLookup := 'Panel1Style1';
end;

It's important to remember that for this to work you must have created a custom style in a style book  (as per Warren's answer).  In this example it is called 'Panel1Style1' but you could replace this name with something totally different.


text:
Q: Why is this cursor giving an error? ALTER PROCEDURE [dbo].[sp_Insert_Monthly_Salary_Req]
     @xmlString  ntext
    ,@Message nvarchar(500) output
AS
BEGIN

    SET NOCOUNT ON;
    declare  @Emp_SL int,@Basic  decimal(6,2), @Grad_pay  decimal(6,2), @DA  decimal(6,2), @HRA  decimal(6,2), @MA  decimal(6,2), @Ptax  decimal(6,2), @Itax  decimal(6,2), @pf  decimal(6,2), @LIC  decimal(6,2), @Month_Of  datetime
    Declare @intDoc1 as int
    BEGIN TRANSACTION
    print @xmlString
    exec sp_xml_preparedocument @intDoc1 OUTPUT, @xmlString
    declare Generate_Rq CURSOR FOR
    SELECT Emp_SL,Basic, Grad_pay, DA, HRA, MA, Ptax, Itax, pf, LIC,  Month_Of
    FROM OPENXML (@intDoc1,'/Salaray/TransactionSalary',1)
    WITH ( Emp_SL int,Basic  decimal(6,2), Grad_pay  decimal(6,2), DA  decimal(6,2), HRA  decimal(6,2), MA  decimal(6,2), Ptax  decimal(6,2), Itax  decimal(6,2), pf  decimal(6,2), LIC  decimal(6,2), Month_Of  datetime)

    OPEN Generate_Rq
    FETCH next FROM Generate_Rq
    INTO @Emp_SL,@Basic, @Grad_pay, @DA, @HRA, @MA, @Ptax, @Itax, @pf, @LIC,  @Month_Of
    print 'Line2'
    WHILE @@Fetch_Status<>-1
        BEGIN
            Print 'Line  ' +@Basic+ '    '+ @Grad_pay+ '    '+ @DA+ '    '+ @HRA+ '    '+ @MA+ '    '+ @Ptax+ '    '+ @Itax+ '    '+ @pf+ '    '+ @Month_Of+ '    '+ @LIC+ '    '+ @Emp_SL

            INSERT INTO [Monthly_Salary_Statement]([Basic], [Grad_pay], [DA], [HRA], [MA], [Ptax], [Itax], [pf], [Month_Of], [LIC], [Emp_SL])
            VALUES (@Emp_SL,@Basic, @Grad_pay, @DA, @HRA, @MA, @Ptax, @Itax, @pf, @LIC,  @Month_Of)
            if(@@ERROR<>0)
                BEGIN
                    rollback transaction
                    Set @Message='sp_Insert_PromtList: ' + @@Error
                    close Generate_Rq
                    deallocate Generate_Rq
                    Return
                END
            FETCH next FROM Generate_Rq
            INTO @Emp_SL,@Basic, @Grad_pay, @DA, @HRA, @MA, @Ptax, @Itax, @pf, @LIC,  @Month_Of
        END
    CLOSE Generate_Rq
    DEALLOCATE Generate_Rq
    COMMIT TRANSACTION
    set  @Message='True'
END

The xml
<Salaray>
  <TransactionSalary EmpSL="2" Basic="9860" Grad_pay="4100.00" DA="6282.00" HRA="2094" MA="300.00" Ptax="150.00" pf="2000" Itax="0.00" LIC="0.00" Month_Of="14/Dec/2012" />
  <TransactionSalary EmpSL="1" Basic="12560" Grad_pay="4800.00" DA="7812.00" HRA="2604.00" MA="300" Ptax="150.00" pf="2000" Itax="0.00" LIC="0.00" Month_Of="14/Dec/2012" />
  <TransactionSalary EmpSL="4" Basic="11850" Grad_pay="4800.00" DA="7493.00" HRA="2498.00" MA="300" Ptax="150.00" pf="2000" Itax="0.00" LIC="0.00" Month_Of="14/Dec/2012" />
  </Salaray>',

It shows ..

Msg 8115, Level 16, State 8, Procedure sp_Insert_Monthly_Salary_Req,
  Line 26
  Arithmetic overflow error converting nvarchar to data type numeric.
  Msg 16917, Level 16, State 2, Procedure sp_Insert_Monthly_Salary_Req, Line 27
  Cursor is not open.
  Msg 16917, Level 16, State 1, Procedure sp_Insert_Monthly_Salary_Req, Line 47
  Cursor is not open.

A: Given an input XML, you can use this simple XQuery statement to "shred" the XML into relational rows and columns - just do a simple INSERT INTO ..... and you're done. No messy cursor nor OPENXML stuff needed...
DECLARE @input XML = '<Salaray>
  <TransactionSalary
    EmpSL="2" Basic="9860" Grad_pay="4100.00" DA="6282.00" HRA="2094" MA="300.00" Ptax="150.00" pf="2000"
    Itax="0.00" LIC="0.00" Month_Of="14/Dec/2012" />
  <TransactionSalary EmpSL="1" Basic="12560" Grad_pay="4800.00" DA="7812.00" HRA="2604.00" MA="300" Ptax="150.00" pf="2000" Itax="0.00" LIC="0.00" Month_Of="14/Dec/2012" />
  <TransactionSalary EmpSL="4" Basic="11850" Grad_pay="4800.00" DA="7493.00" HRA="2498.00" MA="300" Ptax="150.00" pf="2000" Itax="0.00" LIC="0.00" Month_Of="14/Dec/2012" />
  </Salaray>'

/* just add this INSERT INTO statement when you're confident the SELECT returns the right data!
INSERT INTO [Monthly_Salary_Statement]([Emp_SL], [Basic], [Grad_pay], [DA], [HRA], [MA], [Ptax], [Itax], [pf],  [LIC], [Month_Of])
*/
 SELECT
    Emp_SL = XTbl.TSal.value('@EmpSL', 'int'),
    [Basic] = XTbl.TSal.value('@Basic', 'decimal(10,2)'),
    Grad_pay = XTbl.TSal.value('@Grad_pay', 'decimal(6,2)'),
    DA = XTbl.TSal.value('@DA', 'decimal(6,2)'),
    HRA = XTbl.TSal.value('@HRA', 'decimal(6,2)'),
    MA = XTbl.TSal.value('@MA', 'decimal(6,2)'),
    Ptax = XTbl.TSal.value('@Ptax', 'decimal(6,2)'),
    Itax = XTbl.TSal.value('@Itax', 'decimal(6,2)'),
    pf = XTbl.TSal.value('@pf', 'decimal(6,2)'),
    LIC = XTbl.TSal.value('@LIC', 'decimal(6,2)'),
    Month_Of = XTbl.TSal.value('@Month_Of', 'datetime')
  FROM
    @input.nodes('/Salaray/TransactionSalary') AS XTbl(TSal)

Also: mind you, you have values like 12560 for your Basic attribute - those will NOT fit into a decimal(6,2) - that's 6 digits total, 2 of which after the comma - which also means: only 4 digits before the comma - not enough to hold 12560. I used decimal(10,2) instead - that works.
Gives me output of:


text:
Q: Parameter based bindings in ninject 2.0 I want to use conditional binding in ninject, based on passed parameters. I have something like below:
public class Subject
{
}

public interface ITarget
{
}

public class Target1 : ITarget
{
}

public class Target2 : ITarget
{
}

And now I need to instantiate ITarget interface:
    public void MethodName(IKernel kernel)
    {
        ITarget target1 = kernel.Get<ITarget>(new Parameter("name", new Subject(), true)); // Should be instance of Target1
        ITarget target2 = kernel.Get<ITarget>(); // Should be instance of Target2
    }

I have problems to define proper bindings. I tried the following:
kernel.Bind<ITarget>().To<Target1>().When(Predicate);
kernel.Bind<ITarget>().To<Target2>();

private bool Predicate(IRequest request)
{
    IParameter parameter = request.Parameters.Count == 0 ? null : request.Parameters[0];
    if (parameter == null)
    {
        return false;
    }
    object parameterValue = parameter.GetValue( /*what to put here?*/);
    return parameterValue != null && parameterValue.GetType().IsAssignableFrom(typeof(Subject));
}

but I don't know how to get value of passed parameter. I need to pass IContext instance to GetValue method, but don't know how to get valid instance of IContext. Or maybe there is better way to accomplish my task?
EDIT:
BindingMetadata is better way to solve my problem. See Contextual bindings with Ninject 2.0 for details
Regards

A: Does IRequest.ParentContext not give you enough ?
Also, if all you are looking for is to use a Name to disambiguate multiple instances [and you'll be in a position to provide it each time and are happy to work in that explicit Service Location manner instead of using DI as IDeity intended], then there is a Get overload with a name and a WithName for on the Bind side.
EDIT: Spent some time in Reflector but am still not much wiser. The parameters mechanism seems to be for the purposes of overriding specific values in the context of an actual binding happening, not as part of selecting the binding that applies. Establishing a context is only done in one place internally (though Context has a public ctor) so it doesnt look like there's a neat factory for that.
Does your actual scenario happen to fit the constraint mechanism (of which using a name to filter is just the simplest case). i.e., can you express your Get as something like:
_kernel.Get<ITarget>( (Ninject.Planning.Bindings.BindingMetadata metadata)=>metadata.Has("x") );

Hopefully @Ian Davis will be along soon as I'd love to know the answer too :D

A: IIRC a request can be part of several contexts. The parameters you see are only parameters that you specify in the Get call. In the example you give, you should be able to pass null as the IContext in order to get your subject instance. Since you supply an object instead of a callback, the parameter constructs a callback as ctx => value -> thus the callback doesn't use the context value you supply.


text:
Q: Statistical analysis of an mbox mail file I have a rather large mbox mail file in Thunderbird, around 46.5GB. I want to do some analysis of it to see where the space is used up and what I might do to archive some mail separately.
I tried mboxgrep but it crashed with a segfault on such a large file. Thunderbird can operate on the file, but is extremely slow. The most I can do with Thunderbird is filter the file and then copy all the messages to another folder to see how big the folder becomes. Also the "save as" feature crashes Thunderbird with a large number of mails selected.
I have access to Windows and Linux.
What tools can I use to analyse this file? Specifically, how can I find groups of messages that are somehow related (e.g. they are all from the same source) and see the size of each group?


text:
Q: Committed memory on my tomcat server I have a problem to configure JVM on my server. The server is a machine runs on AWS with 8G of RAM and 8 CPU. There is only tomcat6 with solr on the server.
Actually I have configured JVM like that:
JAVA_OPTS="-Djava.awt.headless=true -D64 -server -Xms4096M -Xmx4096M -XX:+UseConcMarkSweepGC"

But when the traffic grow up too much I get errors. I guess the problem comes from the commited memory But I don't understand why more than 4G of memory is reserved.

If somebody can help me to configure correctly my JVM and tell me why this problem happens.


text:
Q: Javascript Popstate event prevent Ajax request i had a problem about preventing ajax request on Popstate event.
so, this is my code :
$(window).on('popstate', function(e) {
        var state = e.originalEvent.state;
            if (state !== null) {

    loadProducts(location.pathname);
        }

});

function loadProducts(url) {

    $.ajax({
            type        : "GET",
            url         : url,
            dataType    : "html",
            cache       : true,
            success     : function(checks) {
                            $(".ajaxpage").html(checks);
                    }
            });
};

$('#product').on("click", ".paging a", function(e) {
    e.preventDefault();
    history.pushState(null, null, $(this).attr('href'));
    loadProducts($(this).attr('href'));
});

pushstate event works really well with ajax request. but when i hit "back button" the page will do the same ajax request again. why is that? i don't need ajax anymore cause i already visit that page? just like what Github does?
how to prevent that ajax request on popstate event?
what's wrong with my code?

A: This line is wrong
var state = e.originalEvent.state

You should access the state by writing
var state = e.state

For reference, https://developer.mozilla.org/en-US/docs/Web/Events/popstate


text:
Q: xCode: Error Uploading App I'm trying to upload my app to itunesconnect using my xCode but I'm stuck with 2 Errors "The port of Signiant is unknown" and "ERROR ITMS-90096" (It says my binary is not optimized for iPhone 5, and is telling about Launch Images). All my Launch Images are working well in all devices, I don't know what's wrong.
Please see the image below:


text:
Q: How to create a logout url for Azure Active Directory for SSO , Need suggestion I am working on a SSO Project where I am creating a SAML Auth Request for login and it is redirecting me to Microsoft Page and it is authenticating against Azure Active Directory which is working fine ,I have attached the code of preparation of SAML Request login .Now I have to prepare the code for logout in Azure Active directory ,can anyone help me with the preparation of Azure ACtive directory logout url in the similar way what we did for login. What changes needs to be done in the URL Request .For login in url we need to have SAMLRequest as a query string parameter ,for logout how the Url look like ?
SAML Auth Request LogIN URL (saml end point is the login url which we got)

 public string SSO(string samlEndpoint)
        {
            var queryStringSeparator = samlEndpoint.Contains("?") ? "&" : "?";

        var url = samlEndpoint + queryStringSeparator + "SAMLRequest=" + HttpUtility.UrlEncode(this.GetRequestSSO(AuthRequest.AuthRequestFormat.Base64));

        if (!string.IsNullOrEmpty(relayState))
        {
            url += "&RelayState=" + HttpUtility.UrlEncode(relayState);
        }

        return url;

        }

  public string GetRequestSSO(AuthRequestFormat format)
    {
        using (StringWriter sw = new StringWriter())
        {
            XmlWriterSettings xws = new XmlWriterSettings();
            xws.OmitXmlDeclaration = true;

            using (XmlWriter xw = XmlWriter.Create(sw, xws))
            {
                xw.WriteStartElement("samlp", "AuthnRequest", "urn:oasis:names:tc:SAML:2.0:protocol");
                xw.WriteAttributeString("ID", _id);
                xw.WriteAttributeString("Version", "2.0");
                xw.WriteAttributeString("IssueInstant", _issue_instant);
                xw.WriteAttributeString("ProtocolBinding", "urn:oasis:names:tc:SAML:2.0:bindings:HTTP-POST");
                xw.WriteAttributeString("AssertionConsumerServiceURL", _assertionConsumerServiceUrl);

                xw.WriteStartElement("saml", "Issuer", "urn:oasis:names:tc:SAML:2.0:assertion");
                xw.WriteString(_issuer);
                xw.WriteEndElement();

                xw.WriteStartElement("samlp", "NameIDPolicy", "urn:oasis:names:tc:SAML:2.0:protocol");
                xw.WriteAttributeString("Format", "urn:oasis:names:tc:SAML:1.1:nameid-format:unspecified");
                xw.WriteAttributeString("AllowCreate", "true");
                xw.WriteEndElement();
                xw.WriteEndElement();
            }

            if (format == AuthRequestFormat.Base64)

            {

                var memoryStream = new MemoryStream();
                var writer = new StreamWriter(new DeflateStream(memoryStream, CompressionMode.Compress, true), new UTF8Encoding(false));
                writer.Write(sw.ToString());
                writer.Close();
                string result = Convert.ToBase64String(memoryStream.GetBuffer(), 0, (int)memoryStream.Length, Base64FormattingOptions.None);
                return result;

            }

            return null;
        }
    }


text:
Q: Pentaho Javascript - row manipulation I am trying to manipulate a row using javascript in an older version of pentaho 4.4) and getting some strange results that I can't explain / don't understand what Pentaho is doing
var test = 'field';
Alert (this[test]); //--> Undefined
Alert (this['field']); // --> Expected result
Alert (this[test]); //--> Expected Result

For some reason, the initial request for this[test] is undefined until I use the literal string reference making it impossible to dynamically drive the process (i.e. I can't access row information by references).
Any ideas as to why? Is it simply how Pentaho deals with variables? Effectively I want my end result to allow me to change the row value at any given position. Either:
row[test] = 'New value

or
this[test] = 'New Value

or
this[test].setValue('New Value');

However, none of the above work, without replacing the values making it a very static process.

A: As far as I can see, Kettle does not add a field to the script's scope, unless the field is contained as a substring in the script source code (it should add even if the field mentioned in the comment). See determineUsedFields() and addValues() methods (https://github.com/pentaho/pentaho-kettle/blob/4.4.0/src/org/pentaho/di/trans/steps/scriptvalues_mod/ScriptValuesMod.java#L106).
So, the exact script you've provided, actually, produces either three defined values, or three undefined values, depending on whether the field exists or not. I was able to reproduce your issue only after I've removed strings with the field name from the code completely, and passed the field name in another field.
So, one way to manipulate row values could be to mention all field names in the script (e.g. in a comment), then try to use setValue as you have tried (seems to work in compatibility mode only).
Another possible way is to use the row array variable to get values and getInputRowMeta().indexOfValue(fieldName) to get the index of the field, e.g:
var idx = getInputRowMeta().indexOfValue(fieldName)
// WARNING: you may assign value of any type this way
// and the value will not be converted to a type defined
// in the field's ValueMeta:
row[idx] = 'New value'

However, this approach bypasses type conversions, which are usually performed while passing JavaScript values outside of the JS step in getValueFromJScript() method.
For example, the following code will put invalid value in the output, and you may not even notice it until some subsequent step will handle the value in some improper way:
// Let's assume that fieldName is name of the 0th input field.
// I'd expect, that the value would remain the same
// but in fact the `fieldName` references some wrapper oject
// which looks similar to its value
// but has a different type
row[0] = fieldName;

In subsequent JS step:
for(var i = 0; i < row.length; i++) {
    Alert(row[i]) // alerts same value as the input, e.g. 'test'
    Alert(row[i].class) // alerts undefined. While expected is 'java.lang.String'
    // Some other subsequent steps may crash once this value encountered
}


text:
Q: sidepopupview not scrolling down and scrolling out of bounds I am using a  SidePopupView layer in my application (constructed with a borderpane node). If the borderpane content has a larger height than the display, there is no scrolling property attached to the sidepopupview allowing to see the hidden content. I have replaced the borderpane by a scrollpane and then I can scroll down the content of the underlining borderpane content. However, it appears that the scrolling goes beyond the limit of the scrollpane/borderpane height (scroll overflow or kind of pull and refresh effect) and shows an ugly white background behind before returning to limit position. Is it a bug or the implementation of the scrolling may be made differently ? I precise that this effect does happen only in android and not in the simulator. Here is the (very simple) example code:
BorderPane pane = new BorderPane();
pane.setPrefHeight(900); // to be sure it goes out of mobile screen.
SidePopupView layer = new SidePopupView(borderPane);
// Show the sidepopupview:
MobileApplication.getInstance().addLayerFactory(name, () -> {
return layer;});
MobileApplication.getInstance().showLayer(name);

A related question is : is it possible to embed a ScrollPane in a simple layer ? When I try to do this, it shows nothing:
// In a class extending Layer:
ScrollPane scrollpane = new ScrollPane(pane);
getChildren().addAll(scrollpane);
// Then showing the layer does nothing:
MobileApplication.getInstance().addLayerFactory(name, () -> {
return layer;});
MobileApplication.getInstance().showLayer(name);


text:
Q: Iterating through dataframe with pandas and replacing characters My data frame column named 'Shrinkage' looks like:
-Shrinkage
-($614)
-$0
-$0
-$0
-$0
-$0
-$0
-$0
-($125)
-$320
-$3,779
($2,482)

With the following code, I am trying to perform multiple actions with a for loop and if statement. I would like to iterate through the column and if the object has the character '(' then I want to replace it with the character '-' to make that number negative. As well as finding and replacing the negative numbers, I would like to remove all characters and make the objects into floats to perform math with it.
for i in ['Shrinkage']:
    if df['Shrinkage'] == '(':
        df['Shrinkage'] = df['Shrinkage'].replace({'(': '-'}).astype(float)
        df['Shrinkage'] = df['Shrinkage'].replace({'$': '', ')': '', ',': ''})
    else:
        df['Shrinkage'].replace({'$': '', ',': ''}, regex=True).astype(float)

I am getting a ValueError: The truth value of a Series is ambiguous. Use a.empty, a.bool(), a.item(), a.any() or a.all().
Please understand I am still new to python and haven't got into complex code yet. Some help is needed please.

A: try this, series.replace and use regex to remove un-wanted characters.
df['Shrinkage'] = df['Shrinkage'].str.replace("\(|\$|\)|,", "")

print(df['Shrinkage'].astype(float))

output,
0     -614.0
1       -0.0
2       -0.0
3       -0.0
4       -0.0
5       -0.0
6       -0.0
7       -0.0
8     -125.0
9     -320.0
10   -3779.0
11    2482.0
Name: Shrinkage, dtype: float64

A: You can do this:
df['Shrinkage'] = df['Shrinkage'].str.replace('\$|\)|\,', '')
df['Shrinkage'] = df['Shrinkage'].str.replace('\(', '-')
df['Shrinkage'] = df['Shrinkage'].astype(float)
print(df)

    Shrinkage
0      -614.0
1         0.0
2         0.0
3         0.0
4         0.0
5         0.0
6         0.0
7         0.0
8      -125.0
9       320.0
10     3779.0
11    -2482.0


text:
Q: Acessar String em PHP Boa tarde,
estou usando a api do Woocommerce para automatizar meu site, porém estou tendo problemas quando tento acessar a resposta que ele envia quando cadastra o produto.
Envio a requisição para criar o produto, tudo normalmente, mas quero guardar o id do produto criado, para isso preciso percorrer a resposta, porém a resposta que chega está assim:

public 'response' =>
        object(Automattic\WooCommerce\HttpClient\Response)[8]
          private 'code' => int 201
          private 'headers' =>
            array (size=13)
              ...
          public 'body' => string '{"id":15286,"name":"Produto ABC","slug":"produto-abc-4","permalink":"https:\/\/hrconsultoria.com.br\/teste\/loja\/antartica\/produto-abc-4\/","date_created":"2020-01-31T15:05:18","date_created_gmt":"2020-01-31T18:05:18","date_modified":"2020-01-31T15:05:18","date_modified_gmt":"2020-01-31T18:05:18","type":"simple","status":"publish","featured":false,"catalog_visibility":"visible","description":"Pellentesque habitant morbi tristique senectus et netus et malesuada fames ac turpis egestas. Vestibulum tortor qu'... (length=2801)
      private 'responseHeaders' => string

Quero acessar o id dentro de 'body', porém quando acesso assim:

$teste = (array)$woocommerce->http->response->body;

O erro retornado é o: Trying to get property 'id' of non-object
Tentei de outro modo:

$teste = (array)$woocommerce->http->response->body;
print_r($teste[0]);

Mas dessa forma só exibe o '{' da string
Como posso percorrer essa string para obter o id do produto?

A: O conteúdo do body é uma string JSON. Pra acessar o ID, primeiro você precisa transformar essa string em um objeto:
$body = json_decode($data['response']['body']);

Agora, você consegue acessar qualquer propriedade do body assim:
echo $body->id; // Imprime o ID
echo $body->name; // Imprime o nome do produto


text:
Q: How to reset session on each request?             class userSessionManager
{
    public $_uname;
    private $_pword;
    private $_userDB_Accessor;

    function __construct($userAccessor)
    {
        $this->_userDB_Accessor = $userAccessor;
    }
    function tryLogin()
    {
        //  get user information
        if ($_SERVER['REQUEST_METHOD'] == 'POST')
        {
            // get username and pasword from POST data and make it safe for database
            $this->_uname = quote_smart(htmlspecialchars($_POST['userName']));
            $this->_pword = quote_smart(htmlspecialchars($_POST['password']));
        }
        else // username and password were not set
        {
            return false;
        }

        $loginPassed = $this->_userDB_Accessor->login($this->_uname, $this->_pword);

        if($loginPassed == true)
        {
            $this->makeSession();
        }

        return $loginPassed;
    }
    private function makeSession()
    {
        session_start();
        $_SESSION['userName'] = $this->_uname;
    }
    function userHasSession()
    {
        session_start();
        if(! isset($_SESSION['userName']))  // session not properly created
        {
            return false;
        }

        $this->_uname = $_SESSION['userName'];  //save username to object

        //destroy and recreate session for security reasons
        session_destroy();
        $this->makeSession();
        return true;
    }
}

So, I read this article on how someone could gain access to an account with the session ID number. One solution listed was to reset the session ID number each time the page is loaded. Would this be a secure implementation of that idea?

Thank you all for the suggestions here is what I did to use them:
        private function makeSession()
    {
        session_start();
        session_regenerate_id();    // reset session id for securty
        $_SESSION['userName'] = $this->_uname;
        $_SESSION['userIP'] = $_SERVER['REMOTE_ADDR'];
        $_SESSION['userBrowser'] = $_SERVER['HTTP_USER_AGENT'];
    }
    function userHasSession()
    {
        session_start();

        if(!isset($_SESSION['userName']) || // check for a created user
            $_SESSION['userIP'] != $_SERVER['REMOTE_ADDR'] || // check for the same IP address
            $_SESSION['userBrowser'] != $_SERVER['HTTP_USER_AGENT'] //check for same Browser and OS
            )
        {
            session_regenerate_id();
            session_unset();
            session_destroy();
            return false;
        }
        return true;    // legit user
    }

A: Massive overkill... session_destroy does not remove the session cookie, it just basically does
$_SESSION = array()
and erases the server-side session data. To prevent stealing the session cookie, you have to use session_regenerate_id() to generate a new session ID.

A: You should use [session_unset()][1] and [session_destroy()][2] both. Note that session_destroy() only empties out the variables when the page is reloaded or redirected to some other page. As long as it's the same page, the variables are still usable after invoking [session_destroy()][3], so it is best practice to use [session_unset()][5] just before [session_destroy()][4].

A: If the session identifier is regenerated every time there is a change in the level of privilege,
the risk of session fixation is practically eliminated:
session_regenerate_id()
<?php
$_SESSION['logged_in'] = FALSE;
if (check_login())
{
session_regenerate_id();
$_SESSION['logged_in'] = TRUE;
}
?>

I do not recommend regenerating the session identifier on every page.
  While this seems like a secure approach—and it is—it provides no more
  protection than regenerating the session identifier whenever there is
  a change in the level of privilege. More importantly, it can adversely
  affect your legitimate users, especially if the session identifier is
  being propagated in the URL. A user might use the browser's history
  mechanism to return to a previous page, and the links on that page
  will reference a session identifier that no longer exists. If you
  regenerate the session identifier only when there is a change in the
  level of privilege, the same situation is possible, but a user who
  returns to a page prior to the change in the level of privilege is
  less likely to be surprised by a loss of session, and this situation
  is also less common.

Have a look at http://phpsecurity.org/ch04.pdf for more information.

A: I would add the IP address to the session and check it every request the user does.


text:
Q: What is the value of $\int_{-1}^{1} P(\sin x)P'(\sin x)dx$? I came across the following problem that says:

Let $P(x)=x^4+x^2+1.$  Then $\int_{-1}^{1} P(\sin x)P'(\sin x)dx=?$

My Attempt: $\int_{-1}^{1} P(\sin x)P'(\sin x)dx= \int_{-\pi}^{\pi}[\sin ^4x+\sin ^2x+1][4\sin ^3x+2 \sin x]dx=.....$  .
Am I going in the right direction or Is there any other better approach to tackle the problem? Can someone point me in the right direction? Thanks in advance for your time.

A: The polynomial $P$ is even, so your integrand $f(x)=P(\sin x)P'(\sin x)$ is odd.
Hence, without any calculation:
$$
\int_{-1}^1f(x)dx=0.
$$


text:
Q: Handle RST packets as normal connection termination I have a service that is listening and consuming TCP messages. I recently came across a device that sends TCP messages but instead of ending the connection in the regular way, e.g. using FIN, it always ends connections using RST, which on my end is seen as a connection aborted by remote host and the data in the socket queue is gone.
During my research I've come across different opinions on whether that's valid/acceptable and have seen some conclusions stating that applications need to start accepting terminations via RST instead of FIN (or both).
My question is, how? As soon as the client sends the RST packet to my server I get winsock error 10054 stating that the connection was aborted by the remote host. At my application level I don't seen to have any control over it since I just get the error at that point.
This results in two possible intermittent outcomes, depending on timing:
 - Data in the queue is processed and then the connection is dropped.
 - The connection is dropped before data can be processed and it is lost.
So I'm trying to do what I can to prevent these RST packets from being seen as aborts and be able to handle the data sitting in the queue consistently.


text:
Q: Comparing values of 2 columns from 2 tables and counting the total matches in rails I have 2 tables in my rails application one of them is Products and the other is Users.
In the products table I have a created_by_id which is an integer that matches the id of the User who created it.  I need to display a running total of the Products and I am having an issue doing so.
class ApplicationController < ActionController::Base

  protect_from_forgery with: :exception

  def ensure_logged_in
    unless current_user
      flash[:alert] = "Please log in"
      redirect_to root_path
    end
  end

  def totalprods
   Product.all.joins(:users).where("created_by_id LIKE current_user.id").count
  end

  helper_method :current_user

  private

  def current_user
    @current_user ||= User.find(session[:user_id]) if session[:user_id]
  end

end

i'm new to rails so i am sorry if i am screwing something up

A: In your app/models/user.rb file, add:
has_many :products, foreign_key: 'created_by_id'

Then you can use:
current_user.products.count

PS: It's a good idea to call that column user_id instead of created_by_id since Rails can guess the association column if it's in the format <model_lower_case>_id.

A: Remove the quotes around 'current_user.id'.  Also, have you defined a relationship between your user and product models?

A: Based off your question you could do it one of 2 ways
The Long Way:
def totalProds
   count = 0
   @products = Product.all
   @products.each do |product|
      count = count + 1
   end
   return count
end

If your models are setup properly you should be able to use the short method which would be
def totalProds
   @products = Product.all
   count = @products.count
   return count
end

The second method would be the preferred unless you had to do something in conjunction with the count being added to your counter. Ruby offers a lot of small functions like this already.


text:
Q: how do I build a single project in code::blocks? I tried to compile and execute a file outside a project.
But when I hit F9, the main file in the active project was built.
How do I build and run a single file project?
Reading this article it seemed possible, but it didn't tell me how.

A: Sure you can compile the file outside the project but you can't run it through codeblocks. If project is already open in codeblocks then pressing f9 or build and run button it compile and run the current project. If you have a c/c++ source file outside the project and you want to compile it then at first select the file you want to compile, go to menu and press -> build -> compile current file or press ctrl+shift+F9. But you can't run it through codeblocks so you have to run executable file directly from the directories where .exe file has been build.


text:
Q: char array on stack causes seg fault This might be expected but I'm just curious as to how/why this happens.
When i try to use a char * declared locally char * foo = "\xFF\xFF..." as an integer it seg faults. But if I use malloc it works perfectly well when i try to access it. Why does this happen?
#include <stdint.h>
#include <stdio.h>
#include <string.h>
#include <inttypes.h>
#include <stdlib.h>

int main(int argc, char **argv)
{
  unsigned char *buf = malloc(16);
  memcpy(buf, "\x00\x00\x00\x00\x00\x00\x00\x00\xFF\xFF\xFF\xFF\xFF\xFF\xFF\xFF", 16);
  //unsigned char *buf = "\x00\x00\x00\x00\x00\x00\x00\x00\xFF\xFF\xFF\xFF\xFF\xFF\xFF\xFF"; // seg faults if you sue this instead

  uint64_t *k  = (uint64_t *) buf;
  uint64_t *k2 = (uint64_t *) (buf + 8);
  uint64_t i  = 1000000000;

  printf("-k =%" PRIu64 "\n", *k);
  printf("-k2=%" PRIu64 "\n", *k2);

  printf("Iter * %" PRIu64  "\n", i);
  for (uint64_t c = 0; c < i; ++c)
    {
      *k  += 1;
      *k2 -= 1;
    }

  printf("-k =%" PRIu64 "\n", *k);
  printf("-k2=%" PRIu64 "\n", *k2);

  return 0;

}

Output:
easytiger $ gcc -std=c99 tar.c -Wall -O2 ; time ./a.out
-k =0
-k2=18446744073709551615
Iter * 1000000000
-k =1000000000
-k2=18446744072709551615

A: String literals are immutable. You may not modify the data stored there. Ever.
Even in C nowadays we make this clear and diagnosable by lobbing a const into the pointer type.
C++ actually requires it.

A: There is no guarantee that string literals will be stored in a writable memory page. This means that the *k += 1 operations in the for loop will likely try to write to read-only memory.  Memory allocated by malloc, on the other hand, will always be writable.

A: For a definition of this form:
unsigned char *buf = "some string";

buf points to a static string which is stored in a read-only portion of memory.  When you try to write to it, you get a segfault.
By using malloc, the memory pointed to by buf is writeable.


text:
Q: PHP Warnings, Notices and Errors Hey guys I'm getting three things right now that I'm trying to take care of, and hoping you can help. I have and error, a warning, and a notice in my code that I would like to  patch up and am hoping that you can help me, errors are as follows.
There are the wonderful errors
PHP Warning:  Invalid argument supplied for foreach() in php/libraries/RotateLatestAssets.class.php on line 35
PHP Notice:   Undefined variable: config in php/libraries/RotateLatestAssets.class.php on line 18
PHP Notice:   Undefined variable: json in php/libraries/RotateLatestAssets.class.php on line 31
PHP Notice:   Undefined variable: json in php/libraries/RotateLatestAssets.class.php on line 32

And then there's a really really weird one I comment out in my code....
I'm thinking gnomes, but who knows....
Here's the class
<?php

class RotateLatestAssets
{
    protected   $config;

    public function __construct()
    {
        $this->config = $config;
    }

    //********************************************************************************
    //* Public Methods
    //********************************************************************************

    public function getAssets()
    {

        $this->json = self::jsonDecode($this->config, true);

        define('latest',    __DIR__ . $json['paths']['latest']);
        define('dist',      __DIR__ . $json['paths']['dist']);

        foreach($this->json['files'] as $fileName => $fileVersion)
        {
            $cacheName = implode("-$fileVersion.", explode('.',$fileName) );
            if(!file_exists(dist . $cacheName))
            {
                try {
                    copy(latest . $cacheName, dist . $fileName);
                } catch(Exception $e) {
                    echo 'Copy Exception: ',  $e->getMessage(), "\n";
                }
            }
        }

    }

    //********************************************************************************
    //* Static Methods
    //********************************************************************************

    /**
    * Returns a json decoded object or array
    *
    * @param    string  $json
    * @param    bool    $toAssoc
    * @return   object|array Depending on the parameter supplied
    */

    private static function jsonDecode($json, $toAssoc = true)
    {

        /**
         * Based on known JSON_DECODE() errors
         * 0 = JSON_ERROR_NONE
         * 1 = JSON_ERROR_DEPTH
         * 2 = JSON_ERROR_STATE_MISMATCH
         * 3 = JSON_ERROR_CTRL_CHAR
         * 4 = JSON_ERROR_SYNTAX
         * 5 = JSON_ERROR_UTF8
         */

        $result = json_decode($json, $toAssoc);

        /*  Will produce this sometimes out of the blue after a few refreshes?

            PHP Fatal error:  Uncaught exception 'Exception' with message
            'JSON Error:  - Syntax error, malformed JSON' in php/libraries/RotateLatestAssets.class.php:99

            Stack trace:
            #0 php/libraries/RotateLatestAssets.class.php(28): RotateLatestAssets::jsonDecode(NULL, true)
            #1 php/libraries/RotateLatestAssets.class.php(119): RotateLatestAssets->getAssets()
            #2 {main}
              thrown in php/libraries/RotateLatestAssets.class.php on line 99
        */

        switch(json_last_error())
        {
            case JSON_ERROR_DEPTH:
                $error =  ' - Maximum stack depth exceeded';
                break;
            case JSON_ERROR_STATE_MISMATCH:
                $error = ' - Invalid or malformed JSON encoding';
                break;
            case JSON_ERROR_CTRL_CHAR:
                $error = ' - Unexpected control character found';
                break;
            case JSON_ERROR_SYNTAX:
                $error = ' - Syntax error, malformed JSON';
                break;
            case JSON_ERROR_UTF8:
                $error = ' - Syntax error, malformed UTF-8 characters';
                break;
            case JSON_ERROR_NONE:
            default:
                $error = '';
        }

        if (!empty($error)) throw new Exception('JSON Error: '.$error);
        return $result;
    }

    /**
    * Returns bool value for state of array recieved dev:(true) live:(false)
    *
    * @param    array   $array
    * @return   bool
    */

    private static function checkMode($array)
    {
        if(!is_array($array)) throw new Exception("Wrong Type Passed. Expecting (array), received (".gettype($array).")");
        return ($array['dev'] == 'true') ? true : false;
    }
}

$instance = new RotateLatestAssets($_SERVER['DOCUMENT_ROOT'].'build/config.json');
$instance->getAssets();

?>

A: In your constructor, you have:
$this->config = $config;

Yet the $config variable is never created, so it has no value.
You do the same thing in getAssets(). You use $json, but it has never been defined.
The invalid argument error is because you are essentially doing foreach(null which is wrong, you can only iterate an array.


text:
Q: JBoss 5.1.0 (JSF/Seam) cookies blowing up with accented characters I cannot see this behavior in JBoss 4.2.3. If I try to call addCookie() on HttpServletResponse and my cookie value has accented characters in it (ex. ç) I get this exception:
java.lang.IllegalArgumentException: Control character in cookie value, consider BASE64 encoding your value
Does anyone know what change in JBoss 5.1.0 could be causing these problems?

A: Apparently they fixed a bug so that the cookie name now finally conforms the RFC2109.
Also see the javax.servlet.http.Cookie API specification:

The name must conform to RFC 2109. That means it can contain only ASCII alphanumeric characters and cannot contain commas, semicolons, or white space or begin with a $ character. The cookie's name cannot be changed after creation.

The c with cedille ç is not an ASCII character.

Update: sorry, the problem concerns the cookie value. This is then related to this Tomcat bugfix (JBoss uses Tomcat under the hoods). This should be workaroundable by setting the cookie version as follows:
cookie.setVersion(1);

The ç is not a valid character for the cookie value according the old Netscape specification, but it is according the newer RFC2109 specification. With the Cookie#setVersion() you can toggle between them.


text:
Q: SQL Server 2000 Integer truncating Plain and simple, does anybody know why this:
Select 30 * 220 / 30

Returns 220, which is the correct result, and this:
Select 30 * (220/30)

Returns 210???
On the second case, I realise that 220/30 is being calculated first, generating a decimal (7,333333...) but still... isn't this lousy precision?

A: Under integer division 220/30 = 7 and 99/100 = 0 (note truncation not rounding)
Use non integers to avoid this. e.g. Select 30 * (220/30.0)
Or you can use an explicit cast
Select 30 * (220/cast (30 as float))

A: The one in the parentheses, is always evaluated first, but since the machine logic you are using integer, in that case, the result of the division is 7, wich you multiply by 30, gives you 210


text:
Q: Show and Hide DIV Class from different page file I have two different PHP files:

*

*index.php

*show.php

-
index.php

Show Div 1

Show Div 2

Show Div 3

-
show.php

Div 1 Content

Div 2 Content

Div 3 Content

-
When you read the css style in the show.php, there are no content will be displayed.
If user click which one of
 from index.php, user can only see the .div on show.php which that
 clicked from the index.php.
I assuming this method will make less files. (exactly like what I'm wondering)
Because all contents in which to be shown, are in one file (show.php).
Well, how to make each
 from index.php will only show the content from each div in show.php.

A: You want this in show.php
<?php $id = isset($_GET['id']) ? $_GET['id'] : 0; ?>

Div 1 Content

Div 2 Content

Div 3 Content

A: Something like this should work, but keep in mind this is sort of a "hack". There's better ways to accomplish this, but they'd fall outside of the scope of your question.
index.php:

Show Div 1

Show Div 2

Show Div 3

show.php:

Div 1 Content

Div 2 Content

Div 3 Content

A: This is a bad approach - you should send only relevant content in response - not a bunch of hidden divs.
Edited after comment from @Styphon.
show.php

<?php
    $id = isset($_GET['id']) ? $_GET['id'] : 0;
    if($id == "1"){
        echo "Div 1 Content";
    }
    else if ($id == "2"){
        echo "Div 2 Content";
    }
    else if ($id == "3"){
        echo "Div 3 Content";
    }
    else{
        echo "Default content";
    }
?>

After comments arguing that, this is a better approach but doesn't answer the original question. Please read https://meta.stackexchange.com/questions/66377/what-is-the-xy-problem
This question is an example of XY problem.

A: index.php:

Show Div 1

Show Div 2

Show Div 3

show.php:

<div class="<?php if(!isset($_GET['id'])||$_GET['id']==1) echo 'display'; else echo 'hidden'; ?>">Div 1 Content (default)

<div class="<?php if(isset($_GET['id'])&&$_GET['id']==2) echo 'display'; else echo 'hidden'; ?>">Div 2 Content

<div class="<?php if(isset($_GET['id'])&&$_GET['id']==3) echo 'display'; else echo 'hidden'; ?>">Div 3 Content


text:
Q: Reorder table data with issues to analysis I am using SQL Server 2008.

*

*The table of products above was created from data from another table.
PRODUCT_SORT is the result of sorting the PRODUCT and EVENT_ORDER together

*Non Product records were inserted (lines in Yellow) from other sources

*Table sorted by SERIALNO and DATE

Problem:

*

*In the table above, the products PROD_03 and PROD_04 are OK (green) and PROD_01 and PROD_02 are NOT OK (red)

*The two records of each product must be together and sorted as in the first table at the top

The goal is:
Due to registration, I found many mistakes, so I have to do some corrections to put it in order to make the analysis
Brainstorming my ideas:

*

*I've thinking on how to do some king of sorting

*Maybe to have a Product table and non product table. Create a loop and insert records from one and the other
I am here just to ask for some approaches on how to resolve these problems. That's it, no code needed!
Result table

*

*The two records of each product must be together and sorted as in the first table at the top.

*Non product records must be between two different products ordered by date.

Regards,
Elio Fernandes


text:
Q: I have two models try to render a model product on a view page I have a two models one being places and blogs.
I want to be able to render the blogs.title on the places.index.html page.
When I call <%= place.blogs.title %> I get:

NoMethodError in Places#index

This is the controller where I am calling all the places in the index:
class PlacesController < ApplicationController
  def index
    @places = Place.all
  end
end

This is my first model for place:
class Place < ApplicationRecord
  has_many :blogs
end

This is my second model for blog:
class Blog < ApplicationRecord
  belongs_to :place
  validates_presence_of :title, :body
end

And this is the index page I am trying to render:

Place index with blogs

<% @places.each do |place| %>
  <%= place.country %>
  <%= place.state %>
  <%= place.blogs.title %>
<% end %>

A: place.blogs is a Relation object containing all Blogs that are related to this particular Place.
You need to tell ActiveRecord to pull down all the related Blog records in your query, so that it can do that in the minimum number of requests. This is called eager loading.
class PlacesController < ApplicationController
  def index
    @places = Place.includes(:blogs).all
  end
end

Next, add an inner loop to your template

Place index with blogs

<% @places.each do |place| %>
  <%= place.country %>
  <%= place.state %>

    <% place.blogs.each do |blog| %>

<%= blog.title %>

    <% end %>

<% end %>

The inner loop will appear to work on its own without using includes, but this will result in launching new requests against the DB each loop, which is a serious performance problem.


text:
Q: I'm trying to replicate a jsfiddle to no avail I'm very green with jquery so don't be too harsh.
Here is the jsfiddle I'm trying to use http://jsfiddle.net/RBKaZ/. I get an error on the $("#dialog").dialog({ line:

Object doesn't support this property or method.

Aslo the Div is showing unlike on jsfiddle.
Here is my page:
<%@ Page Language="VB" AutoEventWireup="false" CodeFile="Default4.aspx.vb" Inherits="Default4" %>

<!DOCTYPE html PUBLIC "-//W3C//DTD XHTML 1.0     Transitional//EN" "http://www.w3.org/TR/xhtml1/DTD/xhtml1-transitional.dtd">

<title></title>

    <form id="form1" runat="server">

Please enter your name

    <textarea id="name"></textarea>

Name entered:

<input type="button" id="open" value="Open Dialog" />

    </form>

I downloaded jquery-1.9.1.js from jquery.com and put it in my scripts folder. On jsfiddle they say they use jquery UI 1.9.2. Am I missing something?
Thanks in advance for any help.
EDIT
I've added this and I get rid of the object not supported error, but it still doesn't do anything.

A: Add this script (jQuery UI) below your jQuery script:

A: As mentioned in the comments, you need both jQuery and jQuery UI, they're two different libraries.

*

*jQuery

*jQuery UI

A: I did this and it worked.

Thanks for pointing me in the right direction!


text:
Q: How to manipulate this array? I am a beginner in PHP. I am trying to make an operation in this array. I want to insert this array in my database like on to many in a table.But before the insertion i have to modify the array values.
this is my array.
$services=[0=>('id_e'=>91701,'id_s'=03),
           1=>('id_e'=>'','id_s'=>01),
           2=>('id_e'=>'','id_s'=>02)
           ];

It has to become like as follow.
$services=[0=>('id_e'=>91701,'id_s'=>03),
           1=>('id_e'=>'91701','id_s'=>01),
           2=>('id_e'=>'91701','id_s'=>02)
           ];

And then i want insert into the database. Any idea please?

A: Try this:
$id_e = null;
foreach ($services as &$row) {
    if ($row['id_e']) $id_e = $row['id_e'];
    else $row['id_e'] = $id_e;
}
unset($row);

demo


text:
Q: Click event for Button with Control Template I have a button with a simple Control Template:
<Page.Resources>
   <ControlTemplate x:Key="LButton" TargetType="Button">
        <Border BorderThickness="2" BorderBrush="White"
                HorizontalAlignment="Stretch" VerticalAlignment="Stretch">
            <TextBlock FontSize="52" FontWeight="Thin"
                   TextAlignment="Right"
                   Text="Hello"
                   Margin="30 0 0 30"
                   HorizontalAlignment="Left"
                   VerticalAlignment="Bottom"/>
        </Border>
    </ControlTemplate>
</Page.Resources>

<Button Grid.Row="1" Grid.Column="0"
        Style="{StaticResource launchButton}"
        Template="{StaticResource LButton}"
        Margin="0 10 10 0"
        x:Name="LoyalityButton" Opacity="0" Click="L_Click"/>

But the event click rises only when I click on TextBlock.  What do I need to do to make the click event raises event I touch to empty space on the button ?

A: You can set Border's Background property, now it is transparent, and transparency means not visible to hit test.


text:
Q: Tracking down high latency in Kafka I have Kafka setup in an admittedly slow configuration - but I'm not expecting the numbers I'm seeing.
I have the cluster set to LogAppendTime, so I'm measuring the time between the event is written to Kafka (as decided by the broker) and the time its received by the service. Both the brokers and the application are "co-located" so the ping time between the servers is low and the clocks should be sync'ed or close to it.
I am seeing latencies between 2ms and 600ms, alot are 250ms+...the massive difference makes me think something is up with my setup. It varies between consumer groups also.
Kafka v2.7.0 x 4 brokers
Key broker properties:
default.replication.factor = 4
min.insync.replicas = 2
num.partitions = 50
offsets.topic.num.partitions = 50
offsets.topic.replication.factor = 4
transaction.state.log.min.isr = 2
transaction.state.log.num.partitions = 50
transaction.state.log.replication.factor = 4

Key consumer properties:
fetch.max.wait.ms = 500
fetch.min.bytes = 1
isolation_level = read_committed

Key producer properties:
enable.idempotence = true
linger.ms = 0
transaction.id = <id>

I'm using a transactional producer to commit the offsets with producer.sendOffsetsToTransaction().
There are many consumer groups, all of which are transactional and operate in the same way of reading events, then committing new events along with the new offset.
Are there any settings I'm missing? I know Kafka isn't geared towards low latency but I want to setup to achieve the lowest latency I can...hopefully < 20ms.
EDIT
I've also tried with these settings:
default.replication.factor = 2
min.insync.replicas = 1
num.partitions = 50
offsets.topic.num.partitions = 50
offsets.topic.replication.factor = 2
transaction.state.log.min.isr = 1
transaction.state.log.num.partitions = 50
transaction.state.log.replication.factor = 2

Without using transactions and
enable.idempotence = false

A: num.partitions = 50 and offsets.topic.num.partitions = 50, the number of brokers is 4. I believe that is causing an issue as your cluster is spending a lot of time doing replication and fetching replicas so time is spend in network communications. Also the I/O threads would be limited causing issues.
Reduce the number of partitions if possible. Is there a reason to have 50 partitions on a 4 node cluster?
Suggest you play with the following settings

*

*num.network.threads

*queued.max.requests.

*num.io.threads.

*num.replica.fetchers.


text:
Q: Replacing Reporting Services with Javascript & WebAPI We are currently replacing a existing Asp.net Application with the main purpose of displaying various Reports of Microsoft Reporting Service.
The new application has a Ext.js (JS Framework) front end and communicates with a .net WebAPI back end.
The reports (charts and also matrices) need to be displayed in the webapp(features like sorting or filtering included) as well to be automatically created and sent out via email.
Displaying the report in the browser is relatively easy and we also have some experience using MigraDoc to create PDF reports.
But are there any solutions out there that doesn't need us to create the same report twice and still gives us all the features we need?

A: Take a look at this -
http://blogs.telerik.com/careypayette/posts/13-09-23/bringing-the-power-of-html5-to-telerik-reporting
Telerik reporting has the ability to create reports in a web api project and send that to the browser.


text:
Q: Big O notation preserved under convex functions? Suppose that the random variable $X_T$ is $O_p(1)$ as $T \rightarrow \infty$. Does this imply that the random variable $\max\{0,X_T \}$ is $O_p(1)$?

A: Since $X_T=O_p(1)$, for any $\epsilon>0$ there is $M$ such that
$P\{|X_T|>M\}<\epsilon$
So, fix $\epsilon$ and take corresponding $M$. Then
$P\{|max(0, X_T)|>M\}\le P\{|X_T|>M\}<\epsilon$


text:
Q: Why does USB stick keep becoming read only? I have a 64GB stick that was working fine. I started putting movies on it, and then suddenly, one day it becomes read only. chmod cannot change it. So I reformatted and started again. After 2 days it became read only again for no apparent reason. I reformatted again (FAT32 each time) because I have to plug it into a player that can't read ext4. And again it became read only. So it works for a couple of days after reformatting, then becomes read only.
Any ideas as to why this is happening?

A: A file system that is mounted read-only may not be clean, i.e. properly closed. It then is in an inconsistent state. Have the file system checked, after which it should mount without problems.
You can check and repair a file system using the "Disks" utility included with Ubuntu. You can check a file system only when it is not mounted, so unmount first.
The tool to check a file system at the command line is fsck.
To prevent this from happening again, always make sure to carefully eject the drive using software before physically unplugging it. The system will give you a notification when it is safe to remove the drive. Before that, it may give you a notification that it is not yet safe, if data still needs to be committed to disk.
If you carefully remove a drive, the file system will remain healthy for a longer time. It still is a good idea to check the file system of any removable drive from time to time. File systems on your internal drives that are used by the system are checked automatically on every reboot.

A: It is possible the drive is getting worn out. Flash storage has only so many write cycles before it cannot be written to again. Magnetic storage, as used in hard disk storage as opposed to solid state, does not have this limit. Hard drives have other parts that will wear so they have limited lives too.  USB storage is not built to be as durable as the kind of solid state storage used in a SATA drive, that's how they make them at lower cost. Reformatting the drive only increases this wear. The means to check on the wear status of a drive will vary based on manufacturer and specific technology used. If chmod will not fix the read only issue then that is evidence of a hardware vs software problem.


text:
Q: In kendomobilelistview after scrolling to some extent need to call a function In a kendomobilelistview I just want to call a function after scrolling to some height. Initially i am loading 20 items and my intention is to load another 20 items So i need to call a function.

A: May this link will help you http://docs.telerik.com/kendo-ui/mobile/listview/endless-scrolling, or you can call on scroll event of the listview


text:
Q: R - IMDb datasets not loading I'm trying to write a function which will download and load files from IMDb dataset page available here: https://datasets.imdbws.com/
Problem is that function execution is downloading the file, but loading it to any object.
I have created separate steps code, which is working fine.
url <- "https://datasets.imdbws.com/name.basics.tsv.gz"
tmp <- tempfile()
download.file(url, tmp)

name_basics <- readr::read_tsv(
  file = gzfile(tmp),
  col_names = TRUE,
  quote = "",
  na = "\\N",
  progress = FALSE
)

File is downloaded and loaded to the name_basics.
But when I tried to create function code, then there is no data loaded.
What I have done wrong?
Function code
imdbTSVfiles <- function(fileName){
  url <- paste0("https://datasets.imdbws.com/",fileName,".tsv.gz")
  tmp <- tempfile()
  download.file(url, tmp)

  name <- readr::read_tsv(
      file = gzfile(tmp),
      col_names = TRUE,
      quote = "",
      na = "\\N")
}

imdbTSVfiles("name.basics")

Expected result: provided file name downloaded and loaded.

A: You need to store data to dynamic named variable, which can be easily achieved using assign().
imdbTSVfiles <- function(fileName){
  url <- paste0("https://datasets.imdbws.com/",fileName,".tsv.gz")
  tmp <- tempfile()
  download.file(url, tmp)

  assign(fileName,
         readr::read_tsv(
           file = gzfile(tmp),
           col_names = TRUE,
           quote = "",
           na = "\\N"),
  envir = .GlobalEnv)
}

imdbTSVfiles("name.basics")

This should store data in name.basics variable.


text:
Q: How to deploy Next.js with GraphQL backend on Zeit Now? I have an Next.js/Express/Apollo GraphQL app running fine on localhost.
I try to deploy it on Zeit Now, and the Next.js part works fine, but the GraphQL backend fails because /graphql route returns:
502: An error occurred with your deployment
Code: NO_STATUS_CODE_FROM_LAMBDA

My now.json looks like:
{
  "version": 2,
  "builds": [
    { "src": "next.config.js", "use": "@now/next" },
    { "src": "server/server.js", "use": "@now/node" }
  ],
  "routes": [
    { "src": "/api/(.*)", "dest": "server/server.js" },
    { "src": "/graphql", "dest": "server/server.js" }
  ]
}

Suggestions?

A: Here's a complete example of Next.js/Apollo GraphQL running both on Zeit Now (as serverless function/lambda) and Heroku (with an Express server):
https://github.com/tomsoderlund/nextjs-pwa-graphql-sql-boilerplate

A: I was getting that error until I found on a solution on the Wes Bos slack channel.
The following worked for me, but it's possible you could be getting that error for a different reason.
I'm not sure why it works.
You can see it working here

*

*cd backend

*Run npm install graphql-import

*Update scripts in package.json:

"deploy": "prisma deploy --env-file variables.env&& npm run writeSchema",
"writeSchema": "node src/writeSchema.js"

Note: For non windows users make sure to place space before &&

*Create src/writeSchema.js:

const fs = require('fs');
const { importSchema } = require('graphql-import');
const text = importSchema("src/generated/prisma.graphql");
fs.writeFileSync("src/schema_prep.graphql", text)

*Update src/db.js:

const db = new Prisma({
typeDefs: __dirname + "/schema_prep.graphql",
...
});

*Update src/createServer.js:

return new GraphQLServer({
typeDefs: __dirname + '/schema.graphql',
...
});

*Update src/schema.graphql:

# import * from './schema_prep.graphql'

*Create now.json
{
    "version": 2,
    "name": "Project Name",
    "builds": [
        { "src": "src/index.js", "use": "@now/node-server" }
    ],
    "routes": [
        { "src": "/.*", "dest": "src/index.js" }
    ],
    "env": {
        "SOME_VARIABLE": "xxx",
        ...
    }
}

*Run npm run deploy to initially create schema_prep.graphql.

*Run now

Another reply said this:

You should not mix graphql imports and js/ts imports. The syntax on the graphql file will be interpreted by graphql-import and will be ignored by ncc (the compiler which reads the __dirname stuff and move the file to the correct directory etc)
  In my example 'schema_prep.graphql' is already preprocessed with the imports from the generated graphql file.

Hopefully this helps.


text:
Q: Unable to connect to Windows shared drive - I get repeatedly prompted for credentials Running Ubuntu 18.04 LTS and I have a Surface Pro running Windows 10.  I have a drive connected to my Windows machine with all my media on it and I want access it from the Ubuntu machine.
I shared the drive, giving full permissions and no password required.  When I mapped the drive from my OTHER windows machine, it prompted me for credentials and I put in my Windows credentials and boom, it worked!
I went to the the file explorer on my Ubuntu machine and put in smb://IPADDRESS and it prompted me for the credentials, and I put my Windows credentials in again, and boom, it works!  I can see the shared drive right there.
However when I click on the shared drive, it prompts me AGAIN for my credentials.  When I put in the exact same credentials, it simply repeats the window prompt.  If I put in gibberish for the credentials it tells me permission denied.
I'm at a loss at this point, if I put in my real credentials it just continually prompts me.  Not sure where to go at this point, any help would be appreciated.
Thank you!
EDIT:  I was able to find a solution.  I was following this guide here: https://linhost.info/2012/05/mount-a-network-share-in-linux-ubuntu/
And it still wasn't working, but when I entered in the incorrect file path I noticed that gave me an Error rather than nothing (which was what was happening before).  It gave me an idea!  So I went back through windows and re-named my shared drive with no apostrophes and no white spaces, then I retried the guide above and it worked!  It appears the file path was not in a format Ubuntu liked so much, and now I have the drive in /mnt/share.  Thanks for the help and I thought I should provide my solution in case anyone was having the same problem.


text:
Q: Remove vertical space around multline chemical equation in a table Is there any way to remove the vertical spacing around a chemical equation placed in a multline environment in a table?
I tried setting the length of display skips as suggested in this question but it doesn't seem to work.
Just as information, the \ce command doesn't cause this behavior; it is seen with normal math equations as well.
MWE:
\documentclass[a4paper, 10pt, oneside]{memoir}
\usepackage{mhchem}
\usepackage{amsmath}

% This doesn't work.
\setlength{\abovedisplayskip}{0pt}
\setlength{\belowdisplayskip}{0pt}
\setlength{\abovedisplayshortskip}{0pt}
\setlength{\multlinegap}{0pt}

\begin{document}

\begin{table}
    \begin{tabular}{rp{27em}l}
        1  & \begin{multline*}\ce{This is a very long list of products ->\\[-0.5em] This is another very long list of reactants}\end{multline*} & Align top \\
        2  & \ce{Na+ + Cl- -> NaCl} & Example \\
        3 & \begin{multline}
            This is not a chemical equation environment \\
            But theres still vertical spacing.
        \end{multline} & Align top
    \end{tabular}
\end{table}

\end{document}

Thank you!

A: The multlined environments can take two optional arguments: its vertical position (t, c or b) and its width. I naturally chose the column width:
\documentclass[a4paper, 10pt, oneside]{memoir}
\usepackage{mhchem}
\usepackage{mathtools}
\makeatletter\newcommand*{\compress}{\@minipagetrue}

\setlength{\multlinegap}{20pt}

\begin{document}

\begin{table}
    \begin{tabular}{r|p{27em}|l}
        1 & $ \begin{multlined}[t][27em]\ce{This is a very long list of products ->\\This is another very long list of reactants}\end{multlined} $ & Align top \\
        2 & \ce{Na+ + Cl- -> NaCl} & Example \\
        3 &\leavevmode$ \begin{multlined}[t][27em]
            \text{This is not a chemical equation environment} \\
            \text{But theres still vertical spacing}.
        \end{multlined} $ & Align top
    \end{tabular}
\end{table}

\end{document}


text:
Q: Is it possible to link a static library with linux kernel? If I write a simple library, e.g.
void swap(int *a, int *b) {
    int temp;
    temp = *a;
    *a = *b;
    *b = temp;
}

After compiled to a static library, say "swap.a", is it possible to call this function and link from a kernel code?

This question says linking shared library in kernel is impossible, because loading a shared library demands a loader, which is running on user space. But I don't understand why static library cannot be used in kernel space, as the loader is not needed.


text:
Q: How to truncate file geodatabase tables with Python? I need to truncate file geodatabase tables (1 or all) with Python. What is the code for that?

A: AFAIK, you can use Delete Rows method in arcpy. from Arcgis Resource Center:
Delete Rows (Data Management)

Summary
Deletes all or the selected subset of rows from the input.
If the input rows are from a feature class or table, all rows will be
  deleted. If the input rows are from a layer or table view with no
  selection, all rows will be deleted.

consider this caution:

If run against a layer or table view that does not have a selection,
  the operation cannot be undone using undo/redo.

Example Code:
import arcpy
from arcpy import env

env.workspace = "C:/data"
arcpy.CopyRows_management("accident.dbf", "C:/output/accident2.dbf")
arcpy.DeleteRows_management("C:/output/accident2.dbf")

i hope it helps you...

A: As of 10.1, Esri has added Truncate Table (Data Management). It will remove all records from a table, regardless of a table view selection, and does not support versioned tables. It is much faster, though.
Esri's sample code for truncating all tables in a geodatabase:
# Set the workspace.
arcpy.env.workspace = "C:/work/vancouver.gdb"

# Get a list of all the tables.
tableList = arcpy.ListTables()

# Loop through the list and run truncate
for table in tableList:
    arcpy.TruncateTable_management(table)

A: import arcpy

from arcpy import env

wrksp = r"workspace"

env.workspace = wrksp

fcs = arcpy.ListFeatureClasses()

for fc in fcs:

    arcpy.MakeTableView_management(fc, "fc_Temp")

    arcpy.DeleteRows_management("fc_Temp")