text:
Q: Different array structures and breaking of foreach I generate XML file from dynamic content but I get 2 array types to get images:
First array type is when there are more than 1 images, example:
array(1) {
  ["Images"]=>
  array(3) {
    [0]=>
    array(2) {
      ["Url"]=>
      string(57) "http://example.net/image1.jpg"
      ["Default"]=>
      bool(true)
    }
    [1]=>
    array(2) {
      ["Url"]=>
      string(57) "http://example.net/image2.jpg"
      ["Default"]=>
      bool(false)
    }
    [2]=>
    array(2) {
      ["Url"]=>
      string(57) "http://example.net/image3.jpg"
      ["Default"]=>
      bool(false)
    }
  }
}

Second type is when I had only 1 image, example:
array(1) {
  ["Images"]=>
  array(2) {
    ["Url"]=>
    string(57) "http://example.net/image111.jpg"
    ["Default"]=>
    bool(true)
  }
}

How I can make second type to use type of first array, because when I looping these arrays with foreach there is a problem with content. Is there any function to fix this or something?!
Edit:
This is the foreach now and it works:
$productImages = $product->appendChild($this->_xmlDoc->createElement('ProductImages'));
if(isset($productInfo['ProductImages'])) {
    foreach($productInfo['ProductImages']['Images'] as $image) {
        if(!is_array($image) && is_string($image)) {
            $productImage = $productImages->appendChild($this->_xmlDoc->createElement('ProductImage'));
            $productImage->appendChild($this->_xmlDoc->createElement('ImagePath', $image));
        }
        if(isset($image['Url']) && is_array($image)) {
            $productImage = $productImages->appendChild($this->_xmlDoc->createElement('ProductImage'));
            $productImage->appendChild($this->_xmlDoc->createElement('ImagePath', $image['Url']));
        }
    }
}

This is how foreach looks 20 minutes after my question. So I'll vote for first answer, because its similar to my work around :)
Cheers,
Georgi!

A: I've encountered the same issue before with using a SOAP call. You don't need to change the structure of the array. You can simply change the behaviour of your foreach loop instead, using is_array. It checks if the variable is an array or not. Example, using your arrays:
$first_array = array(
    "Images" => array(
        array("Url" => "http://example.net/image1.jpg", "Default" => true),
        array("Url" => "http://example.net/image2.jpg", "Default" => false),
        array("Url" => "http://example.net/image3.jpg", "Default" => false)
    )
);

$second_array = array(
    "Images" => array(
        "Url" => "http://example.net/image111.jpg",
        "Default" => true
    )
);

echo "Results on the first array:
";

foreach ($first_array["Images"] as $element) {
    if (is_array($element)) {
        foreach ($element as $value) {
            echo $value . "
";
        }
    } else {
        echo $element . "
";
    }
}

echo "
";
echo "Result on the second array:
";

foreach ($second_array["Images"] as $element) {
    if (is_array($element)) {
        foreach ($element as $value) {
            echo $value . "
";
        }
    } else {
        echo $element . "
";
    }
}

PHPFiddle Link: http://phpfiddle.org/main/code/4y8j-4jd1


text:
Q: "MIMEParsingException: Missing start boundary" exception happening only in Chrome Browser, Firefox works fine during Jersey fileUpload FYI, I have the following jersey jars in my app's classpath along with the mimepull jar version as:
jersey-apache-client-1.11.jar
jersey-apache-client4-1.11.jar
jersey-client-1.17.1.jar
jersey-core-1.17.1.jar
jersey-guice-1.17.1.jar
jersey-json-1.17.1.jar
jersey-multipart-1.17.1.jar
jersey-server-1.17.1.jar
jersey-servlet-1.11.jar
mimepull-1.6.jar

I even tried with all of them either 1.11 or 1.17.1 for the jersey specific jars. When I tried to submit a file upload request via my latest Chrome browser (here is the client side html code to submit the file upload):
<form name="uploadFile" action="/app/fileUpload" method="post" enctype="multipart/form-data">
<input type="file" name="file" class="input-file"/><br/>
<button type="submit" id="upload-btn" class="btn btn-primary">Upload</button>
</form>

Strangely enough, my file upload jersey resource is not even hit and I get a 400 error in my Chrome browser with the following exception in my server logs, however it works just fine in my Firefox browser:
[toResponse] WebApplicationExceptionMapper status='400' message='org.jvnet.mimepull.MIMEParsingException: Missing start boundary' url='/app/fileUpload'
    javax.ws.rs.WebApplicationException: org.jvnet.mimepull.MIMEParsingException: Missing start boundary
        at com.sun.jersey.multipart.impl.MultiPartReaderClientSide.readFrom(MultiPartReaderClientSide.java:146)
        at com.sun.jersey.multipart.impl.MultiPartReaderClientSide.readFrom(MultiPartReaderClientSide.java:82)
        at com.sun.jersey.spi.container.ContainerRequest.getEntity(ContainerRequest.java:488)
        at com.sun.jersey.spi.container.ContainerRequest.getEntity(ContainerRequest.java:552)
        at com.sun.jersey.multipart.impl.FormDataMultiPartDispatchProvider$FormDataInjectableValuesProvider.getInjectableValues(FormDataMultiPartDispatchProvider.java:122)
        at com.sun.jersey.server.impl.model.method.dispatch.AbstractResourceMethodDispatchProvider$EntityParamInInvoker.getParams(AbstractResourceMethodDispatchProvider.java:153)
        at com.sun.jersey.server.impl.model.method.dispatch.AbstractResourceMethodDispatchProvider$ResponseOutInvoker._dispatch(AbstractResourceMethodDispatchProvider.java:203)
        at com.sun.jersey.server.impl.model.method.dispatch.ResourceJavaMethodDispatcher.dispatch(ResourceJavaMethodDispatcher.java:75)
        at com.sun.jersey.server.impl.uri.rules.HttpMethodRule.accept(HttpMethodRule.java:302)
        at com.sun.jersey.server.impl.uri.rules.RightHandPathRule.accept(RightHandPathRule.java:147)
        at com.sun.jersey.server.impl.uri.rules.ResourceClassRule.accept(ResourceClassRule.java:108)
        at com.sun.jersey.server.impl.uri.rules.RightHandPathRule.accept(RightHandPathRule.java:147)
        at com.sun.jersey.server.impl.uri.rules.RootResourceClassesRule.accept(RootResourceClassesRule.java:84)
        at com.sun.jersey.server.impl.application.WebApplicationImpl._handleRequest(WebApplicationImpl.java:1511)
        at com.sun.jersey.server.impl.application.WebApplicationImpl._handleRequest(WebApplicationImpl.java:1442)
        at com.sun.jersey.server.impl.application.WebApplicationImpl.handleRequest(WebApplicationImpl.java:1391)
        at com.sun.jersey.server.impl.application.WebApplicationImpl.handleRequest(WebApplicationImpl.java:1381)
        at com.sun.jersey.spi.container.servlet.WebComponent.service(WebComponent.java:416)
        at com.sun.jersey.spi.container.servlet.ServletContainer.service(ServletContainer.java:537)
        at com.sun.jersey.spi.container.servlet.ServletContainer.service(ServletContainer.java:708)
        at javax.servlet.http.HttpServlet.service(HttpServlet.java:803)
    ...
    org.apache.catalina.core.StandardContextValve.invoke(StandardContextValve.java:175)
        at org.apache.catalina.core.StandardHostValve.invoke(StandardHostValve.java:128)
        at org.apache.catalina.valves.ErrorReportValve.invoke(ErrorReportValve.java:104)
        at org.apache.catalina.core.StandardEngineValve.invoke(StandardEngineValve.java:109)
        at org.apache.catalina.connector.CoyoteAdapter.service(CoyoteAdapter.java:216)
        at org.apache.coyote.http11.Http11Processor.process(Http11Processor.java:844)
        at org.apache.coyote.http11.Http11Protocol$Http11ConnectionHandler.process(Http11Protocol.java:634)
        at org.apache.tomcat.util.net.JIoEndpoint$Worker.run(JIoEndpoint.java:445)
        at java.lang.Thread.run(Thread.java:724)
    Caused by: org.jvnet.mimepull.MIMEParsingException: Missing start boundary
        at org.jvnet.mimepull.MIMEParser.skipPreamble(MIMEParser.java:306)
        at org.jvnet.mimepull.MIMEParser.access$300(MIMEParser.java:67)
        at org.jvnet.mimepull.MIMEParser$MIMEEventIterator.next(MIMEParser.java:143)
        at org.jvnet.mimepull.MIMEParser$MIMEEventIterator.next(MIMEParser.java:128)
        at org.jvnet.mimepull.MIMEMessage.makeProgress(MIMEMessage.java:198)
        at org.jvnet.mimepull.MIMEMessage.parseAll(MIMEMessage.java:181)
        at org.jvnet.mimepull.MIMEMessage.getAttachments(MIMEMessage.java:106)
        at com.sun.jersey.multipart.impl.MultiPartReaderClientSide.readMultiPart(MultiPartReaderClientSide.java:187)
        at com.sun.jersey.multipart.impl.MultiPartReaderServerSide.readMultiPart(MultiPartReaderServerSide.java:80)
        at com.sun.jersey.multipart.impl.MultiPartReaderClientSide.readFrom(MultiPartReaderClientSide.java:144)
        ... 46 more

Here is the Request payload which also looks correct when compared with Firefox payload, I dont understand why I see 400 for the same request in Chrome browser but 200OK in Firefox
  Content-Type:multipart/form-data; boundary=----WebKitFormBoundaryNkIU5AivMR0pDmZG
   Host:localhost:8080
   Origin:http://localhost:8080
   Referer:http://localhost:8080/app/files
   User-Agent:Mozilla/5.0 (Macintosh; Intel Mac OS X 10_9_2) AppleWebKit/537.36 (KHTML, like Gecko) Chrome/33.0.1750.152 Safari/537.36
   Request Payload
   ------WebKitFormBoundaryNkIU5AivMR0pDmZG
   Content-Disposition: form-data; name="file"; filename="file.zip"
   Content-Type: application/zip

   ------WebKitFormBoundaryNkIU5AivMR0pDmZG--

Any pointers to resolve this error will be highly appreciated. Please let me know if you need any more information from my side to get further insight into the issue.
Here is the Jersey resource method signature:
@POST
@Path("/fileUpload")
@Consumes(MediaType.MULTIPART_FORM_DATA)
public Response uploadMultiPartFormData(@FormDataParam("file") InputStream file_in,
@FormDataParam("file")FormDataContentDisposition fileName) throws Exception {

redpajama_set_name: RedPajamaStackExchange


text:
Q: Determining if a curve wraps circumferentially around a cylinder or not For a cylinder with equation $r^{2} = y^{2} + z^{2}$, is there a test which could tell me if a closed curve (a connected set of finite points on the surface of the cylinder, for which I know their coordinates in cartesian and cylindrical coordinates) wraps circumferentially around the cylinder like a ring on a finger (1), or lays on the cylinder like an anchor tattoo on a sailor's arm (2)?

A: Project the points down to the $xy$-plane (ignore the $z$ coordinate). Start at one of the points. March along the sequence of points incrementing the angle from the origin as you go. You will end up with an integral multiple of $2\pi$ when you return to the starting point. The integer multiple will tell you how many times you wound around (and in which direction). The tattooed anchor will give $0$.


text:
Q: How to use $_SERVER['DOCUMENT_ROOT'] In Session Header 'Location:' to give path I'm trying to use this code to handle sessions and if the user is not logged in he/she should be redirected to the home.
However the path I need to give inside the header(location) should be an absolute pat since Im using this session throughout the pages in different folders.
For this I'm trying to use the $_SERVER['DOCUMENT_ROOT']  root directory global variable. But my code is not working.
Can someone please tell me what's wrong with this code
<?php

session_start();
if (!isset($_SESSION['ID'])){
    header("Location:" . $_SERVER['DOCUMENT_ROOT'] . "/page1/page2/index.html");
 }

?>

A: $_SERVER['DOCUMENT_ROOT'] is an absolute path on your server's file system, not the relative path accessible from the browser.
In this case, the following will accomplish what you want:
header("Location: /page1/page2/index.html");


text:
Q: Expand and collapse using javascript with [+] and [-] The following is the code i am using for expanding and collapsing my div.
Now I want to make little changes to the code.
When I Expand the div,A "[-]" with div content and when I collapse a "[+]" with div content should come.

[+]
Click here

This is foo

click here1

click here1

 Edit

Edit

 cancel

I am Waiting Fotr your help.
Thanks In Advance

A: is this you want?
function toggle_visibility(id) {
   var e =document.getElementById(id);
   var label = document.getElementById("x");

   if(e.style.display == 'none')
    {
      label.innerHTML = label.innerHTML.replace("[+]","[-]");
      e.style.display = 'block';
      col.innerHTML=valu;
    }
   else
   {
      label.innerHTML = label.innerHTML.replace("[-]","[+]");
      e.style.display = 'none';

   }
}

A: use the show and hide functions of javascript to show and hide the divs:

Javascript:
function showHide(currentElem) {
    if (currentElem.ClassName.indexOf('open') > -1) {
        // This means its open, now close it
        currentElem.className = 'closed';
        currentElem.style.display = 'none';
    } else {
        currentElem.className = 'open';
        currentElem.style.display = 'block';
    }
}

A: function toggle_visibility(id) {
    var e = document.getElementById(id);

    if (e.style.display == 'none') {
        document.getElementById('x').innerText = '[-]';
        e.style.display = 'block';
        //col.innerHTML = valu;
    }
    else {
        e.style.display = 'none';
        document.getElementById('x').innerText = '[+]';
    }
}

When you click the [+] on the div this code shows the div and changes the [+] to [-] and vice versa. if you want to change the [+] to something else? like '[+]click here' you can just change the corresponding string in the code. I do not understand what do you mean by 'you want to change the content also..'. What exactly do you want to change?


text:
Q: Notification system like facebook jewel? Does anyone know any system wich work like facebook request, message, notification bubble system? somethig to alert on every user profile they have a new whatever  so they can reply . I mean obviously facebook has a great level but if anyone know about a similar system . I look for something similar en older question but, didn't find anything. Please let me know as well if theres is something on jquery or others.
What matter to me is only a bubble counting how many new received has the actual user . I'm using Apache on Linux and aware of using something like commet (long polling) does anyone know a working sample of comet,Ajax Push,Reverse Ajax,Two-way-web, HTTP Streaming,HTTP server push (othewr name of comet)?
thank in advance.

A: Not exactly what you are asking for because I think most people just implement this themselves, but you should look at Humane JS.

A: This would require something a little more than just Javascript.
Have a look into Signal R?
It uses long polling to provide fast and efficient responses.


text:
Q: GMaps don't load at first open page, after reload it works I use gmaps4rails gem and maps are not always loaded at first page open, after reload it works.

So, my code
show.html.haml
    %script{:src => "//maps.google.com/maps/api/js?v=3.13&sensor=false&libraries=geometry", :type => "text/javascript"}
    %script{:src => "//google-maps-utility-library-v3.googlecode.com/svn/tags/markerclustererplus/2.0.14/src/markerclusterer_packed.js", :type => "text/javascript"}

........

    .col-lg-8.col-sm-8.col-md-8.col-xs-12
        #map
        %br/

......

    :javascript
        handler = Gmaps.build('Google');
        handler.buildMap({ provider: {}, internal: {id: 'map'}}, function(){
            markers = handler.addMarkers(#{raw @hash.to_json});
            handler.bounds.extendWith(markers);
            handler.fitMapToBounds();
            handler.getMap().setZoom(16);
        });

in parks_controller.rb
  def show
    set_park
    @hash = Gmaps4rails.build_markers(@park) do |park, marker|
      marker.lat park.latitude
      marker.lng park.longitude
      marker.infowindow park.address
    end

in index.html.haml
 - @parks.each do |park|
    .map_index
      .image_wrapper
        = image_tag "http://maps.google.com/maps/api/staticmap?size=400x200&sensor=false&zoom=16&markers=#{park.latitude}%2C#{park.longitude}", class: "map_image"
      %h2
        = link_to park.title, park

Working app - https://geoparks.herokuapp.com/
Tell me, please, what to change or add to code?

A: I just add to links that goes to the maps page parameter
'data-no-turbolink' => true

Code = link_to p.title, parkin index.html.haml changed to
= link_to park.title, park, 'data-no-turbolink' => true


text:
Q: GraphQL filter products by tags AND priceRange I'm using the shopify-buy SDK and the fetchQuery function to issue the following payload:
first: 50
query: "tags:[new] AND priceRange:{minVariantPrice:0 AND maxVariantPrice:40}"
reverse: false
sortKey: "PRICE"

This is returning all products, and as far as I can tell the tags filter isn't working either. Where am I going wrong here? Here is the issued command:
fragment ProductFragment on Product {
  id
  availableForSale
  createdAt
  updatedAt
  descriptionHtml
  description
  handle
  productType
  title
  vendor
  publishedAt
  onlineStoreUrl
  options {
    id
    name
    values
  }
  images(first: 250) {
    pageInfo {
      hasNextPage
      hasPreviousPage
    }
    edges {
      cursor
      node {
        id
        src
        altText
      }
    }
  }
  variants(first: 250) {
    pageInfo {
      hasNextPage
      hasPreviousPage
    }
    edges {
      cursor
      node {
        ...VariantFragment
      }
    }
  }
}

fragment VariantFragment on ProductVariant {
  id
  title
  price
  priceV2 {
    amount
    currencyCode
  }
  presentmentPrices(first: 20) {
    pageInfo {
      hasNextPage
      hasPreviousPage
    }
    edges {
      node {
        price {
          amount
          currencyCode
        }
        compareAtPrice {
          amount
          currencyCode
        }
      }
    }
  }
  weight
  available: availableForSale
  sku
  compareAtPrice
  compareAtPriceV2 {
    amount
    currencyCode
  }
  image {
    id
    src: originalSrc
    altText
  }
  selectedOptions {
    name
    value
  }
  unitPrice {
    amount
    currencyCode
  }
  unitPriceMeasurement {
    measuredType
    quantityUnit
    quantityValue
    referenceUnit
    referenceValue
  }
}

query ($first: Int!, $query: String, $sortKey: ProductSortKeys, $reverse: Boolean) {
  products(first: $first, query: $query, sortKey: $sortKey, reverse: $reverse, after: "eyJsYXN0X2lkIjoxNTQzODk0MjM3MjM5LCJsYXN0X3ZhbHVlIjoiMTU0Mzg5NDIzNzIzOSJ9") {
    pageInfo {
      hasNextPage
      hasPreviousPage
    }
    edges {
      cursor
      node {
        ...ProductFragment
      }
    }
  }
}


text:
Q: strcat giving segfault Why does the following segfault?
I am using standard c99, icc compiler with unix. I can't get this to not segfault, and I am curious why. I am not familiar with strcat/strcpy very much.
char *first = "First";
char *second = "Second";
char *both = (char *)malloc(strlen(first) + strlen(second) + 2);

strcpy(both, first);
strcat(both, " ");
strcat(both, second);

sprintf("%s %s", first, second);

A: sprintf("%s %s", first, second);

The first parameter of sprintf is a destination buffer.  You have given it a constant string as a destination buffer.
If you're just trying to print out something, did you mean printf?
Otherwise, correct use would be something like:
// declaration of "dest" left as exercise for the reader
//
sprintf(dest, "%s %s", first, second);

Although, sprintf has been superseded by snprintf, which is better to avoid buffer overflows.

A: sprintf is "string printf" which prints to strings, formatted.
sprintf is expecting a string destination pointer(a writable buffer of sufficient length) to write to. What you pass in is a constant string literal which is 7 bytes long. And you're trying to write beyond 7 bytes which is causing the segfault.
char *first = "First";
char *second = "Second";
char *both = (char *)malloc(strlen(first) + strlen(second) + 2);

strcpy(both, first); // unnecessary
strcat(both, " "); // unnecessary
strcat(both, second); //unnecessary

printf(both,"%s %s\0", first, second);


text:
Q: How can I modify the attributes of an SVG file from Python? I have an svg file that was generated by the map data-visualisation software 'Kartograph'. It contains a large number of paths representing areas on a map. These paths each have some data fields:
<path d=" ...path info... " data-electorate="Canberra" data-id="Canberra" data-no="23" data-nop="0.92" data-percentile="6" data-state="ACT" data-totalvotes="25" data-yes="2" data-yesp="0.08" id="Canberra"/>

So that I don't have to generate a new svg file every time, I want to modify some attributes, such as the number of 'yes' votes, from within python. Specifically, I would like to increment/increase the 'yes' votes value by one (for each execution of the code).
I have tried lxml and have browsed the documentation for it extensively, but so far this code has not worked:
from lxml import etree

filename = "aus4.svg"
tree = etree.parse(open(filename, 'r'))

for element in tree.iter():
    if element.tag.split("}")[1] == "path":
        if element.get("id") == "Lingiari":
            yes_votes = element.get("data-yes")
            print(yes_votes)
            yes_votes.set(yes_votes, str(int(yes_votes) + 1))
            print(yes_votes)

Is python the best tool to use for this task? If so how might I change the above code or start afresh. Apologies for any confusion. I am new to this 'lxml' module and svg files, so I'm a bit lost.

A: You do not set the attribute again, but use its value instead of the elmenet in this line:
yes_votes.set(yes_votes, str(int(yes_votes) + 1))

yes_votes contains the content of the attribute and not a reference to the attribute itself. Change it to:
element.set( "data-yes", str(int(yes_votes) + 1))


text:
Q: Accessing Webservice from Asp.net MVC I have a MVC2 App which also includes a Non MVC part (regular Asp.Net 3.5 pages).
I am calling webservice (Not WCF) from Non MVC pages to populate autocompletes.
Both MVC parts and Non-MVC parts work fine in my developers machine.
When i host my application in IIS, i cant access the webmethods in my webservice. I checked with firebug it returns
The controller for path '/payroll/WS/MVCArch.asmx/JqUiGetEmp' was not found or does not implement IController. '

Here my virtual directory name is Payroll. and my Non MVC pages are located under a folder called "RepDocs" which is under the root of the application. My Webservice folder "WS" is also under the root of the application. The request was sent from a non mvc page under "RepDocs" folder.
How come the same code works in VSHOST and not in IIS (XP sp3) ? am i missing something ?
Please help.
EDIT
I have modified my global.asax to exclude routes as follow
routes.IgnoreRoute("{resource}.axd/{*pathInfo}");
routes.IgnoreRoute("favicon.ico");
routes.IgnoreRoute("WS/{resource}.asmx/{*pathInfo}");
//routes.IgnoreRoute("{*allasmx}", new { allasmx = @".*\.asmx(/.*)?" });
routes.MapRoute(
    "Default", // Route name
    "{controller}/{action}/{id}", // URL with parameters
    new { controller = "Home", action = "Index", id = UrlParameter.Optional } // Parameter defaults
);

Now i get this error
The HTTP verb POST used to access path '/Payroll/ws/MVCArch.asmx/JqUiGetOffice' is not allowed.

I added the following to the Web.config
<webServices>
    <protocols>
      <add name="HttpGet"/>
      <add name="HttpPost"/>
      </protocols>
</webServices>

Still no luck.

A: You have to ignore the route to the web service in Global.asax.cs
routes.IgnoreRoute("{*allasmx}", new {allasmx=@".*\.asmx(/.*)?"});


text:
Q: What does the error "htmlfile: invalid argument" mean? I'm getting this in excanvas.js I'm hitting this error and I'm not really sure why.  I have a minified version of excanvas.js and something is breaking in IE, specifically on:

var b=a.createStyleSheet();

I'm not sure why.  Does anyone have any insight?  I can provide more information, I'm just not sure what information will help.

A: This is a slightly old thread, but I thought it would be useful to post. There seems to be a limitation on how much style information a page can contain, which causes this error in IE6. I am able to produce an invalid argument error using this simple test page:
<html>
<head>
<title></title>
<script>
for(var i=0;i<32;i++) {
document.createStyleSheet();
}
</script>
</head>
<body>
</body>
</html>

I think this is the source of the problem.
HTH,
Russell

A: The newest version of excanvas.js did not fix this issue for me in IE8 so I updated line 111 of excanvas.js to the code below and I no longer get the exception. The code for this solution is from http://dean.edwards.name/weblog/2010/02/bug85/.
  var ss = null;
  var cssText = 'canvas{display:inline-block;overflow:hidden;' +
      // default size is 300x150 in Gecko and Opera
      'text-align:left;width:300px;height:150px}';
  try{
    ss = doc.createStyleSheet();
    ss.owningElement.id = 'ex_canvas_';
    ss.cssText = cssText;
  } catch(e) {
    ss = document.styleSheets[document.styleSheets.length - 1];
    ss.cssText += "\r\n" + cssText;
  }

A: First thing I'd do is use the un-minified version.  Looks like this coming from an init function called from onreadystatechange, trying to style canvas elements, although that isn't as enlightening as one might hope.

A: The newest version of excanvas fixes this for me. You can always get the newest version from svn trunk.


text:
Q: ERROR ITMS-900158 while submitting application on itunes ERROR ITMS-900158:"The following URL scheme found in your app are not in the correct format: here. URL schemes need, to begin with, an alphabetic character and be comprised of alphanumeric characters, the period, the hyphen or the plus sign only. Please see RFC1738" for more detail.
Please help me with this issue as I'm not getting where I'm going wrong.

A: i Found my answer
i was just making mistake by entering CFBundleURLSchemes values in an array it should be string
correct format :
[Please refer the image url for the correction made]
(http://i.stack.imgur.com/oT5k7.png)

A: URLScheme which represent the protocols you app responds too (like your-app://) and are defined in your Plist file under the key CFBundleURLTypesshould not be an URL


text:
Q: RestKit ActivityIndicator for several requests I have a IBAction which is called via a button in my iPad App.
The IBaction Calls then three different methods which initiate a RestKit Request.
What would be the best way to check of for all three requests the objects where retrieved?
The goal is to show an activityIndicator with the first request and stop/hide the activityIndicator with the retrieval of objects for all three requests.
I'm new to RestKit, so please forgive me if this is a too simple question. I tried to find a solution by myself with the help of the RestKit API - Documentation.

A: I suppose you use asynchronous requests. One simple solution can be a check in your RKObjectLoderDelegate's - (void)objectLoader:(RKObjectLoader*)objectLoader didLoadObjects:(NSArray*)objects method whether all of your data is already loaded.
When initiating RestKit requests, you can add a 'tag' (called userData in RestKit) to a request and retrieve that tag later in the delegate callbacks.
For example, you can implement the following logic:
When you create your requests, add a specific user data to each one:
RKObjectLoader *loader = [[RKObjectManager sharedManager] loadObjectsAtResourcePath:@"/getMyData" objectMapping:mapping delegate:self];
[loader setUserData:@"FirstRequest"];
...
RKObjectLoader *loader = [[RKObjectManager sharedManager] loadObjectsAtResourcePath:@"/getMyData" objectMapping:mapping delegate:self];
[loader setUserData:@"ThirdRequest"];

and check the tags in didLoadObjects:
- (void)objectLoader:(RKObjectLoader*)objectLoader didLoadObjects:(NSArray*)objects {
    if ([[objectLoader userData] isEqual:@"FirstRequest"]) {
        self.firstRequestData = objects;
    }
    ... //handle the remaining requests
    if (self.firstRequestData && self.secondRequestData && self.thirdRequestData) {
        [self hideMyActivityIndicator];
    }
 }

Don't forget to handle error situations when loading the requests.
Alternatively, if this approach will not fit your scenario - you can add and manage requests in a separate queue & track the progress. If you'll need more info on the second option just let me know.

A: There is an easy way, in your objectLoader delegate, you can use objectLoader's the built-in function like this:
- (void)objectLoader:(RKObjectLoader *)objectLoader didLoadObjects:(NSArray *)objects {

    if ([objectLoader wasSentToResourcePath:@"/path1"]) {
       //handle request for /path1
       //objects are loaded for request1

    } else if ([objectLoader wasSentToResourcePath:@"/path2"]){
       //handle request for /path2
       //objects are loaded for request2

    } else if ([objectLoader wasSentToResourcePath:@"/path3"]){
      //handle request for /path3
      //objects are loaded for request3

   }
}

Its just that simple.


text:
Q: How to see spaces in GitKraken free version I use GitKraken and and it is really cool tool!
Is it possible to see spaces in GitKraken?
For example, there are spaces, but GitKraken shows no spaces:

But another git visual tool shows spaces:

Is it possible to see spaces in free version of GitKraken?

A: I'm using GitKraken version 4.0.5 (MacOS and Windows) and spaces are shown:

You have however a designated button for hiding spaces (on the top-right corner):

Which results (same source with spaces):

Maybe is it turned on on your client?


text:
Q: Thermodynamics - please check my proof that $\partial C_p/\partial p$ = 0 for an ideal gas Prove
$$\left(\frac{\partial C_p}{\partial p}\right)_T = 0$$ for an ideal gas.
All the $\partial$s are partial derivatives
Please check to see if this makes sense.
We know that
$$C_p = \left(\frac{\partial H}{\partial T}\right)_P$$
Observe that
$$\left(\frac{\partial C_p}{\partial p}\right)_T = \left(\left(\frac{1}{\partial P}\right)\left(\frac{\partial H}{\partial T}\right)_P\right)_T = \left(\left(\frac{1}{\partial T}\right)\left(\frac{\partial H}{\partial P}\right)_T\right)_P $$
Enthalpy is defined as
$$H=U+PV$$
Equipartition tells us that
$$U=Nk\frac{f}{2}$$
and the ideal gas law tells us that $$PV=NkT$$
Therefore,
$$H=Nk\frac{f}{2}+NkT=\left(1+\frac{f}{2}\right)NkT$$
From knowing
$$H=\left(1+\frac{f}{2}\right)NkT$$
we can see that
$$\left(\frac{\partial H}{\partial P}\right)_T = 0$$
and hence that
$$\left(\frac{\partial C_p}{\partial p}\right)_T =0$$

A: It can be done in an easier way.
Take that $(\partial C_p /\partial P)_T = - T (\partial^2 V /\partial T^2)_P$. If you plug in your ideal gas $PV=nRT$ you directly get the result asked.
Even though, you reasoning is fine if you don't know the equation I showed you.


text:
Q: ASCII Text Browser Vs. cURL I hit this url : http://artii.herokuapp.com/make?text=abc+art&font=smisome1
I see this

Then when I curl exact same URL
curl http://artii.herokuapp.com/make?text=abc+art&font=smisome1
I got this

♂
Does anyone know why this is happening ?
Is there a specific flag in the curl I should pass to make it return the same result as broswer ?
How do I get my Terminal to display the same ASCII text format as the browser ?

A: The ampersand in the URL is breaking up the command.
If you escape the ampersand you should achieved the desired return.
E.G.
    curl http://artii.herokuapp.com/make?text=abc+art\&font=smisome1

A: In browser you using &font=smisome1 (look on end of your url) in terminal you don't using this font because of &.
Maybe this help you. Sorry for not professional answer.


text:
Q: How to fill in the table if $dy/dt=0.5t$? Fill in the missing values in the table below, given that $dy/dt=0.5t$. Assume that  the rate of growth, given by $dy/dt$, is approximately constant over each unit time interval.

What exactly am I supposed to do here? I don't think it's just solving the equation and finding the appropriate $C$, and then evaluating at $t=1,2,3,4$. And I need to use the condition that $dy/dt$ is approx. constant over each unit time interval somehow.

A: The solution of the differential equation
$$\frac{dy}{dt} = 0.5 t$$
is
$$y(t) = a + 0.25 t^2,$$
for a suitable real parameter $a$. If you assume that $y(0) = 8$, then:
$$y(0) = a + 0.25 \cdot 0^2 = 8 \Rightarrow a = 8 \Rightarrow y(t) = 8 + 0.25 t^2.$$

Anyway, if you want to approximate the solution by assuming that the increase is constant in a given time interval, consider that you can use the Euler method:
$$y(t)  = y(t-\tau) + \tau\frac{dy}{dt},$$
where $\tau = 1$ ($\tau$ is the intersample distance).
Therefore:
$$y(t) = y(t-1) + 0.5 t,$$
and hence the approximate solution is:
$$
\begin{array}{cllll}
y(0) & & & = & 8\\
y(1) & = & y(0) + 0.5 \cdot 1 = 8 + 0.5 & = & 8.5\\
y(2) & = & y(1) + 0.5 \cdot 2 = 8.5 + 1 & = & 9.5\\
y(3) & = & y(2) + 0.5 \cdot 3 = 9.5 + 1.5 & = & 11\\
\ldots
\end{array}
$$
and so on.
Notice that the real solution $y(t) = 8 + 0.25 t^2$ gives instead the following values:
$$
\begin{array}{cllll}
y(0) & = & 8 + 0.25 \cdot 0^2 & = & 8\\
y(1) & = & 8 + 0.25 \cdot 1^2 & = & 8.25\\
y(2) & = & 8 + 0.25 \cdot 2^2 & = &9\\
y(3) & = & 8 + 0.25 \cdot 3^2 &= & 10.25\\
\ldots
\end{array}
$$
and so on.

A: You are given:$$y'(t)=0.5t$$
By integrating, you have:
$$y(t)=\dfrac{0.5}{2}t^2+K$$
where K is a constant that is is defined from:
$$y(0)=K=8$$
Thus,
$$y(t)=0.25t^2+8$$


text:
Q: How to get equidistant discrete points on y-axis with a loop? How to get equidistant discrete points on y-axis with a loop? I have done without loop. Please make a loop for this.
\documentclass[tikz, margin=3mm]{standalone}
    \begin{document}
        \begin{tikzpicture}[%x=2cm,y=2cm
        dot/.style = {circle, fill,
                      minimum size=.02ex,
                      }
                            ]
    \draw[-latex, thin, draw=gray] (-5,0)--(5,0) node [right] {$x$};
    \draw[-latex, thin, draw=gray] (0,-5)--(0,5) node [above] {$y$};
    %
    \foreach \Point [count=\i] in {
    (0,-5),(0,-4.5),(0,-4), (0,-3.5), (0,-3), (0,-2.5), (0,-2), (0,-1.5), (0,-1), (0,-.5), (0,0),
    (0,5),(0,4.5),(0,4), (0,3.5), (0,3), (0,2.5), (0,2), (0,1.5), (0,1), (0,.5)
    }
    {
     \node[dot] at \Point {};
    }
        \end{tikzpicture}
    \end{document}

A: Just use special foreach syntax:
\documentclass[tikz, margin=3mm]{standalone}
\begin{document}
\begin{tikzpicture}
    [dot/.style = {circle, fill, minimum size=.02ex, } ]
    \draw[-latex, thin, draw=gray] (-5,0)--(5,0) node [right] {$x$};
    \draw[-latex, thin, draw=gray] (0,-5)--(0,5) node [above] {$y$}; %
    \foreach \y in {-5, -4.5,..., 5} { \node[dot] at (0,\y) {}; }
\end{tikzpicture}
\end{document}

A: \documentclass[tikz, margin=3mm]{standalone}
    \begin{document}
        \begin{tikzpicture}[%x=2cm,y=2cm
        dot/.style = {circle, fill,
                      inner sep=.2ex,
                      }
                            ]
    \draw[-latex, thin, draw=gray] (-5,0)--(5,0) node [right] {$x$};
    \draw[-latex, thin, draw=gray] (0,-5)--(0,5) node [above] {$y$};
    %
    \path foreach \Y in {-10,...,9}
    {(0,\Y/2) coordinate[dot]};
        \end{tikzpicture}
    \end{document}


text:
Q: Android: Check multiple items ListView I am trying to implement multiple items selection in a ListView. The List is managed using the CursoAdapter. I was following the tutorials at http://developer.android.com/guide/topics/ui/menus.html#CAB. However, when I run the app, only 1 item is selected (highlighted). Can you point out, What am I doing wrong?
MainActivity.java
public class MainActivity extends ActionBarActivity {
DbHelper db;
ListView myList;
ActionMode mActionMode;
int checkedCount;
private static final String[] GENRES = new String[] {
        "Action", "Adventure", "Animation", "Children", "Comedy", "Documentary", "Drama",
        "Foreign", "History", "Independent", "Romance", "Sci-Fi", "Television", "Thriller"
};

@Override
protected void onCreate(Bundle savedInstanceState) {
    super.onCreate(savedInstanceState);
    setContentView(R.layout.activity_main);
    db = new DbHelper(this);
    myList = (ListView) findViewById(R.id.newList);
    ArrayAdapter<String> adapter = new ArrayAdapter<String>(this,
            android.R.layout.simple_list_item_activated_1, GENRES);
    myList.setAdapter(adapter);

    loadData();

    myList.setChoiceMode(ListView.CHOICE_MODE_MULTIPLE_MODAL);
    myList.setItemsCanFocus(false);
    myList.setOnLongClickListener(new View.OnLongClickListener() {
        // Called when the user long-clicks on someView
        public boolean onLongClick(View view) {
            if (mActionMode != null) {

                return false;

            }

            // Start the CAB using the ActionMode.Callback defined above
        //    mActionMode = getActivity().startActionMode(mActionMode.Callback);

            view.setSelected(true);
            view.setBackgroundColor(25);
            return true;
        }
    });
    myList.setMultiChoiceModeListener(new AbsListView.MultiChoiceModeListener() {

        @Override
        public void onItemCheckedStateChanged(ActionMode mode, int position,
                                              long id, boolean checked) {
            // Here you can do something when items are selected/de-selected,
            // such as update the title in the CAB
         //   Log.v(ListView.getCheckedItemPositions());
            if(checked)
            {
                checkedCount++;
            }
            else checkedCount--;
            mode.setTitle(checkedCount+" selected");
        }

        @Override
        public boolean onActionItemClicked(ActionMode mode, MenuItem item) {
            // Respond to clicks on the actions in the CAB
            switch (item.getItemId()) {
                case R.id.menu_delete:
                    //   deleteSelectedItems();
                    mode.finish(); // Action picked, so close the CAB
                    return true;
                default:
                    return false;
            }
        }

        @Override
        public boolean onCreateActionMode(ActionMode mode, Menu menu) {
            // Inflate the menu for the CAB
            menu.clear();
            checkedCount=0;
            MenuInflater inflater = mode.getMenuInflater();
            inflater.inflate(R.menu.context_main, menu);
            return true;
        }

        public void onDestroyActionMode(ActionMode mode) {
            // Here you can make any necessary updates to the activity when
            // the CAB is removed. By default, selected items are deselected/unchecked.
        }

        public boolean onPrepareActionMode(ActionMode mode, Menu menu) {
            // Here you can perform updates to the CAB due to
            // an invalidate() request
            return false;
        }
    });
}

public void onResume()
{
    super.onResume();
    loadData();
}

@Override
public boolean onCreateOptionsMenu(Menu menu) {
    // Inflate the menu; this adds items to the action bar if it is present.
    menu.clear();
    getMenuInflater().inflate(R.menu.menu_main, menu);
    return true;
}

@Override
public boolean onOptionsItemSelected(MenuItem item) {
    // Handle action bar item clicks here. The action bar will
    // automatically handle clicks on the Home/Up button, so long
    // as you specify a parent activity in AndroidManifest.xml.
    int id = item.getItemId();

    //noinspection SimplifiableIfStatement
    if (id == R.id.action_settings) {
        return true;
    }

    return super.onOptionsItemSelected(item);
}
public void loadData()
{
    Cursor cursor = null;
    try {
        cursor = db.fetchData();
    }
    catch(NullPointerException e)
    {
        e.printStackTrace();
    }
    ListAdapter myAdapter = new SimpleCursorAdapter(this, R.layout.tasks,
            cursor,
            new String[]{db._ID, db.COLUMN_1, db.COLUMN_2},
            new int[]{R.id.idnum, R.id.c1, R.id.c2}, 0);
    myList.setAdapter(myAdapter);

}
public void addNew(View v)
{
    Intent intent = new Intent(this,AddActivity.class);
    startActivity(intent);

}
}

activity_main.xml
<RelativeLayout xmlns:android="http://schemas.android.com/apk/res/android"
xmlns:tools="http://schemas.android.com/tools" android:layout_width="match_parent"
android:layout_height="match_parent" android:paddingLeft="@dimen/activity_horizontal_margin"
android:paddingRight="@dimen/activity_horizontal_margin"
android:paddingTop="@dimen/activity_vertical_margin"
android:paddingBottom="@dimen/activity_vertical_margin" tools:context=".MainActivity">

<TextView android:text="@string/welcome"
    android:layout_width="fill_parent"
    android:layout_height="wrap_content"
    android:gravity="center"
    android:textSize="20sp"
    android:id="@+id/topic"
/>
<ListView
    android:layout_width="fill_parent"
    android:layout_height="wrap_content"
    android:id="@+id/newList"
    android:layout_below="@+id/topic"
    android:layout_above="@+id/MainButtons"
    android:choiceMode="multipleChoice"
    android:listSelector="@color/background_material_dark"

    ></ListView>
<LinearLayout
    android:layout_width="fill_parent"
    android:layout_height="wrap_content"
    android:layout_alignParentBottom="true"
    android:id="@+id/MainButtons"
>
<Button
    android:layout_width="wrap_content"
    android:layout_height="fill_parent"
    android:layout_weight="1"
    android:text="@string/add"
    android:id="@+id/addButton"
    android:onClick="addNew"
/>
<Button
    android:layout_width="wrap_content"
    android:layout_height="fill_parent"
    android:layout_weight="1"
    android:text="@string/edit"
    android:id="@+id/editButton"
/>
<Button
    android:layout_width="wrap_content"
    android:layout_height="fill_parent"
    android:layout_weight="1"
    android:text="@string/del"
    android:id="@+id/deleteButton"
/>
</LinearLayout>

</RelativeLayout>

tasks.xml
<?xml version="1.0" encoding="utf-8"?>
<RelativeLayout xmlns:android="http://schemas.android.com/apk/res/android"
android:layout_width="match_parent" android:layout_height="match_parent">
<TextView
    android:layout_width="wrap_content"
    android:layout_height="wrap_content"
    android:id="@+id/idnum"
    android:paddingRight="20dp"

    />
<TextView
    android:layout_width="wrap_content"
    android:layout_height="wrap_content"
    android:id="@+id/c1"
    android:layout_toRightOf="@+id/idnum"
    android:paddingRight="20dp"
   />
<TextView
    android:layout_width="wrap_content"
    android:layout_height="wrap_content"
    android:id="@+id/c2"
    android:layout_toRightOf="@+id/c1"
    />
</RelativeLayout>

menu_main.xml
<menu xmlns:android="http://schemas.android.com/apk/res/android"
xmlns:app="http://schemas.android.com/apk/res-auto"
xmlns:tools="http://schemas.android.com/tools" tools:context=".MainActivity">
<item android:id="@+id/action_settings" android:title="@string/action_settings"
    android:orderInCategory="100" app:showAsAction="always"
   />

</menu>

Please comment if I need to add more details.
Edit: I looked at the duplicate question. However, majority of answers suggested using an ArrayAdapter, whereas items in my list are managed using SQLite, and each item consists of 3 separate items (no, text1, text2). How can I make use of an ArrayAdapter here? Also, one highly voted answer says to use CheckedTextView. So shall I use CheckedTextView for all the 3 parts of a list item?

A: I finally solved this by using a selector. Here is the selector.xml file:
<?xml version="1.0" encoding="utf-8"?>

<selector xmlns:android="http://schemas.android.com/apk/res/android">

<item android:state_checked="true"
    android:drawable="@color/link_text_material_dark"

    />
<item android:state_active="true"
android:drawable="@color/primary_dark_material_dark"
/>
<item android:state_selected="true"
    android:drawable="@color/highlighted_text_material_dark"
    />

<item android:state_activated="true" android:drawable="@android:color/white" />

</selector>

The most important one is the state_activated item. It is used to highlight all those items which are selected.
Also, in order to use this selector, add the following line to tasks.xml or wherever you have defined each row (item):
android:background="@drawable/selector"

A: I have modified you code, added little changes. If you still have issues, please follow the sample in you sdk samples folder it will be in the following location.
sdks\samples\android-14\ApiDemos\src\com\example\android\apis\view\List16.java
        public class MainActivity extends ActionBarActivity {

            private static final String[] GENRES = new String[] {
                    "Action", "Adventure", "Animation", "Children", "Comedy", "Documentary", "Drama",![enter image description here][2]
                    "Foreign", "History", "Independent", "Romance", "Sci-Fi", "Television", "Thriller"
            };

            @Override
            protected void onCreate(Bundle savedInstanceState) {
                super.onCreate(savedInstanceState);
                setContentView(R.layout.activity_main);
                ListView myList = (ListView) findViewById(R.id.newList);

    /**
     * the use of CHOICE_MODE_MULTIPLE_MODAL, a.k.a. selection mode on ListView
     * couple with the new simple_list_item_activated_1 which uses a highlighted    border for selected
     * items.
     */
                ArrayAdapter<String> adapter = new ArrayAdapter<String>(this,
                        android.R.layout.simple_list_item_activated_1, GENRES);
                myList.setAdapter(adapter);
                myList.setChoiceMode(ListView.CHOICE_MODE_MULTIPLE_MODAL);
                myList.setMultiChoiceModeListener(new AbsListView.MultiChoiceModeListener() {

                    @Override
                    public void onItemCheckedStateChanged(ActionMode mode, int position,
                            long id, boolean checked) {
                        // Here you can do something when items are selected/de-selected,
                        // such as update the title in the CAB
                    }

                    @Override
                    public boolean onActionItemClicked(ActionMode mode, MenuItem item) {
                        // Respond to clicks on the actions in the CAB
                        switch (item.getItemId()) {
                            case R.id.action_settings:
                                //   deleteSelectedItems();
                                mode.finish(); // Action picked, so close the CAB
                                return true;
                            default:
                                return false;
                        }
                    }

                    @Override
                    public boolean onCreateActionMode(ActionMode mode, Menu menu) {
                        // Inflate the menu for the CAB
                        MenuInflater inflater = mode.getMenuInflater();
                        inflater.inflate(R.menu.menu_main, menu);
                        return true;
                    }

                    public void onDestroyActionMode(ActionMode mode) {
                        // Here you can make any necessary updates to the activity when
                        // the CAB is removed. By default, selected items are deselected/unchecked.
                    }

                    public boolean onPrepareActionMode(ActionMode mode, Menu menu) {
                        // Here you can perform updates to the CAB due to
                        // an invalidate() request
                        return false;
                    }
                });

            }
        }

![enter image description here][1]

menu_main.xml

    <menu xmlns:android="http://schemas.android.com/apk/res/android"
        xmlns:app="http://schemas.android.com/apk/res-auto"
        xmlns:tools="http://schemas.android.com/tools" tools:context=".MainActivity">
        <item android:id="@+id/action_settings" android:title="@string/action_settings"
            android:orderInCategory="100" app:showAsAction="always" android:icon="@drawable/ic_launcher" />
    </menu>

activity_main.xml is same as your layout.


text:
Q: Reading Bytes from an InputStreamReader goes into infinite loop I've a test which fails because reading bytes from an InputStreamReader is going into infinite loop.
@Test
public void testSingleRequest() throws IOException {
        Server server = new Server(9000, 100);
        new Thread(server).start();
        Socket clientSocket = new Socket("localhost", 9000);
        OutputStream out = clientSocket.getOutputStream();
        InputStream in = clientSocket.getInputStream();
        String payload = "a";
        byte[] load = buildPushPayload(payload);
        out.write(load);
        byte[] response = IOUtils.toByteArray(in);
        server.stop();

        assertEquals(0, response[0]);

    }

This is the code that writes to the InputStream
byte[] resp = buildPushResponse();
output.write(resp);

private byte[] buildPushResponse() throws UnsupportedEncodingException {
        ByteBuffer buffer = ByteBuffer.allocate(1);
        buffer.order(ByteOrder.BIG_ENDIAN);
        buffer.putInt(0);
        return buffer.array();
    }

Both the server and the client are write to the clientSocket Input Output stream.
I can't seem to understand why the infinite loop then?

A: What you are missing here is how to know when to stop reading.  You are calling IOUtils.toByteArray(in) which will read until End Of File, which never happens (unless the other side closes their end of the socket).
There are a few schemes you can use to know how many bytes to read from the socket as a message packet before processing the complete message packet.  For example, you could say that all packets are 8 bytes (in which case your read call would specify to read 8 bytes), you could say that the first byte is the count of bytes in the packet, you could say that a packet is variable length, and is terminated with a carriage return byte.
Once you have read a packet, you would normally process the packet and then go back to read another packet or close the socket if you're all done.
Here is a good example of socket programming: https://www.geeksforgeeks.org/socket-programming-in-java/
In that case, they are terminating a packet or message with an End Of Line mark - they are reading one line of text at a time with DataInputStream.readUTF(socket).
server = new ServerSocket(port);
socket = server.accept();

// Create a DataInputStream object that takes input from the socket
in = new DataInputStream(new BufferedInputStream(socket.getInputStream()));

String message = "";

// reads messages from client and prints them
// The loop exits if the message "Over" is received.
try
{
    while (!"Over".equals(message))
    {
        message = in.readUTF();
        System.out.println(message);
    }
}
catch(IOException i)
{
    // handle error
}
// close connection
socket.close();
in.close();


text:
Q: Xdsoft datetime - set a minimum, starting date I am using Xdsoft datetime picker. I want the user to select a date, but starting from today's date with an offset of 3 days.
For example today is 9/10/2015 the datetimepicker should start with a date of 13/10/2015 and so one.
$('#datetimepicker2').datetimepicker({
    yearOffset:222,
    lang:'ch',
    timepicker:false,
    format:'d/m/Y',
    formatDate:'Y/m/d',
    minDate:'-1970/01/02', // yesterday is minimum date
    maxDate:'+1970/01/02' // and tommorow is maximum date calendar
});

A: http://jsfiddle.net/jhvsjfmr/
HTML:
<input id="datetimepicker" type="text"  value="">

JS:
function getDate()
{
    var today = new Date();
    today.setDate(today.getDate()-3);
    var dd = today.getDate();
    var mm = today.getMonth()+1; //January is 0!
    var yyyy = today.getFullYear();

    if(dd<10) dd='0'+dd
    if(mm<10) mm='0'+mm
    today = mm+'/'+dd+'/'+yyyy;

    return today;
}

$('#datetimepicker').val(getDate())

$('#datetimepicker').datetimepicker({
    timepicker:false,
    format:'m/d/Y'
});

A:     jQuery(document).ready(function () {

     'use strict';

        var DVl = new Date();
        DVl.setDate(DVl.getDate() - 2);

        var DVlD = DVl.getDate();
        var DVlM = DVl.getMonth()+1;

        if(DVlD < 10){

            DVlD = '0'+ DVlD;
        }

        if(DVlM < 10){

            DVlM = '0'+ DVlM;
        }

       var FnlD = DVl.getFullYear() +'-'+ DVlM +'-'+ DVlD;

       jQuery('#datetimepicker').datetimepicker({

          format:'d-m-Y ',

          timepicker : false,

          minDate: FnlD
      });
  });

You can set the minDate value directly like minDate : '04-06-2019'. If you want dynamic date changes you could follow the above code.


text:
Q: How to change the key name for each element in array using ng-repeat I have an array of object, which I am showing in table through ng-repeat.

            {{col}}	 //['Name', 'Bank Name','Code', 'Type','Status'];

          {{row[col]}}	 //['name', 'bankName','code', 'type','isActive'];

I am using ng-repeat in 	 and 	 too. But my columnHeaders name and row property(columnRows) names are different. I want to change my property name to same as column header name while using ng-repeat on 	 tag.
I am thought of using alias 'as' but not sure how to use it for each element.
Can anyone help me?

A: Instead of using two columnRows and header rows(array of string) , make a single array of keyHash(column data key and header string )
check running fiddle for this
and code be like :-
   <!DOCTYPE html>

            {{col.displayStr}}

          {{row[col.key]}}


text:
Q: IOReactorShutdownException: I/O reactor has been shut down, using apache httpclient5 we recently upgraded our httpclient version from 4.x to 5.0.3.
The main reason for the upgrade is to get rid of the java.lang.IllegalStateException: Request cannot be executed; I/O reactor status: STOPPED exception that accures on version 4.x.
After the upgrade, for some unknown reason we are experiencing this error now:
22:35:04,160 (pool-9-thread-1] ERROR http.async.HttpAsyncSender - Unable to send request, cause-I/O reactor has been shut down

org.apache.ha.cores.reactor. IOReactorShutdownException: I/O reactor has been shut down at org.apache.ho.cores.reactor.AbstractIOReactorBase.connect(AbstractIOReactorBase.java:50)-thespoores-5.0.2.341/15.0.21

at org.apache.ha.clients.http.impl.nio.Maltihome105essionRequesterfi.executellext (Multihome10Sessionequester.java:105) -[httpolients-5.0.3.3art/25.0.31 37021 at org.apache.he.clients.http.impl.nic.MultihomeI0SessionRequester$1.run (Multihome105essionRequester.java:153) -(httpclients-5.0.3.jar/15.0.3)

at org.apache.hc.clients.http.impl.nio.Multihome10SessionRequester.connect (Multihome 10dessionequester-java:157)-[httpclient5-5.0.3.Jaz1/15.0.31 at org.apache.he.clients.http.impl.nio.DefaultAsyncClientConnectionOperator.connect (DefaultAsyncClientConnectionOperator.java:30) -[httpclients-5.0.3.jar!/15.0.3)

at org.apache.ho.clients.http.impl.nio.PoolingAsyncClientConnectionManager.connect (FoolingAsyncClientConnectionManager.java:369) -[httpclients-5.0.3.jar!/15.0.3)

at org.apache.he.clients.http.impl.wayng.InternalfetpAsyncExecRuntime.connectEndpoint (InternalttpAsynckxeckuntime.JAVA:210)-[httpclients-5.0.3-3art/15.0.31 at org.apache.ho.clients.http.impl.async.AsyncConnectExec.proceedTolfextop (AsyncConnectExec.java:195) -httpeltent5-5.0.3.jar/5.0.31

at org.apache.ba.clients.http.impl.async.AsyncConnectExec.access2000 (AsyncConnectExec.java:79)-[httpclients-5.0.3.jar/15.0.3) at org.apache.ho.clients.http.impl-axyng.AsyncConnectExec.completed (AsyncConnectExec.java:146) -Thespelients-5.0.3.jar!/15.0.3)

at org.apache.bo.clients.http-impl-async.AsyncConnectExecli.completed (AsyncConnectExec.java:135) -(httpelients-5.0.3.jar!/15.0.3)

at org.apache.hc.clients.http.impl.axyng.InternalttpAsyncExecRuntimesi.completed (InternalNetpayncExecRuntime.java:114) -[httpclients-3.0.3.3art/15.0.3) at org.apache.bo.clients.http.impl.async.InternalfetpAryncExecRuntime1.completed [InternalttpAsyncExecRuntime.java:105) -(httpaliest5-5.0.3.jar!/15.0.31

at org.apache.bc.cores.concurrent.Basicfuture.completed (Basicfuture.java:123) (httpoores-5.0.2.jar!/15.0.21 at org.apache.hc.cores.concurrent.ComplexFuture.completed (Complexfuture.179) (httpceres-5.0.2.jart/:5.0.21

at peg.apache.he.clients.http.impl.nio.PoolingAsyncClientConnectionManager$1. leaseCompleted (PoolingAsyncClientConnectionManager.java:240) -[httpclients-5.0.3.3art/15.0.31

at org.apache.ho.clients.http.impl.nio.PoolingAsyncClientConnectionManager$1.completed/FoolingAayneClientConnectionManager.JATA1275)-[httpclients-3.0.3.3az1/15.0.31 at org.apache.ho.clients.http.impl.nio.PoolingAsyncClientConnectionManager$1.completed(PoolingAsyncClientConnectionManager.java:224) -[httpclients-8.0.3.jar!/15.0.31

at org.apache.bs.cores.concurrent.Basicfuture.completed(BasicFuture.java:123) -[httpeores-5.0.2.3art/15.0.23

at org.apache.hc.cores.pool.strictConnPool.fireCallbacks (StrictConnPool.java:383) -(httpcore5-5.0.2.jar!/15.0.23 at org.apache.hc-cores.pool.strictcoonPool.Inase (Strict ConnPool.java:199)-[httpcores-5.0.2.jar!/15.0.21

TRAR at org.apache.bo.clients.http.impl.nio.PoolingAsyncClientConnectionManager.lease (Foolinghayn ClientConnectionManager.java:225) (httpclients-5.0.3.3421/15.0.3) at org.apache.ho.clients.http.impl.anng.InternallttpyncExecRuntime.squireEndpoint (Internal:twyncExecuntime.java:100)-[httpclients-3.0.1.jart/25.0.31 at org.apache.he.clients.http.impl.async-AsyncConnectExec.execute(AsyncConnectExec.java:134)-[httpclients-5.0.2.jar/15.0.

We have no idea why this error accures or what is causing it.
The only major diffference between our version was that in the previus version with httpclient 4.x, we consumed the response:
httpclient 4.x code:
@override
public void completed(HttpResponse response) {
    // some code ...
    EntityUtils.consume(response.getEntity());
}

but now we use SimpleHttpResponse instead of HttpResponse and getEntity() is not a function of SimpleHttpResponse, so we removed this code.
So my question is, why the error above hppends? can it be related to the fact that we do not consume the response? and if so - why is it related? when do you need to use consume()?


text:
Q: Product of Positive Matrices Is the product of non-negative definite matrices also non-negative definite? If not, let A and B be non-negative definite matrices, is '$\operatorname{tr}(A^T B) \ge0$' ?

A:
Lemma 1. Let $k$ be a field of characteristic $\neq 2$, and $A\in k^{n\times n}$ be a symmetric matrix.
(a) Then, there exist an invertible matrix $U\in k^{n\times n}$ and a diagonal matrix $D\in k^{n\times n}$ such that $A=U^TDU$.
(b) Let the field $k$ be ordered. The matrix $A$ is nonnegative-definite if and only if all entries of the matrix $D$ are nonnegative.

I'm writing a proof of this, mainly because too many sources do it wrong (for instance, by assuming $k$ to be ordered in (a), where it is useless, or using the spectral theorem, which is much stronger and requires $k=\mathbb R$). But it isn't necessary for your question: you only seem to need the $k=\mathbb R$ case, where any proof would do.
EDIT: I'm not writing a proof of this. Too tired from the rest. Observe that Lemma 1 (a) is equivalent to the fact that a symmetric bilinear form on a finite-dimensional vector space has an orthogonal basis (indeed, $A$ is the matrix representing the form, and $U$ is the change-of-basis matrix between the standard basis and the orthogonal basis). But this fact is proven, e.g., in Theorem 4.7 of Keith Conrad, Bilinear forms or in Proposition 18.1 in J. S. Milne's "Algebraic Groups, Lie Groups, and their Arithmetic Subgroups" Chapter I. Lemma 1 (b) is easy to derive from Lemma 1 (a).

Corollary 2. Let $k$ be an ordered field. Let $A\in k^{n\times n}$ and $B\in k^{n\times n}$ be two symmetric nonnegative-definite matrices. Then, $\operatorname{Tr}\left(AB\right)\geq 0$.

Proof of Corollary 2. Consider the Kronecker product $A\otimes B\in k^{n^2\times n^2}$ of the two matrices $A$ and $B$. This Kronecker product $A\otimes B$ is defined as the matrix $\left(A_{i,j}B_{i',j'}\right)_{\left(1,1\right)\leq \left(i,i'\right)\leq \left(n,n\right),\ \left(1,1\right)\leq \left(j,j'\right)\leq \left(n,n\right)}$. Here, $A_{i,j}$ is the $\left(i,j\right)$-th entry of the matrix $A$, and $B_{i',j'}$ is the $\left(i',j'\right)$-th entry of the matrix $B$. Besides, the coordinates in the vector space $k^{n^2}$ are indexed by pairs $\left(i,i'\right)\in\left\lbrace 1,2,...,n\right\rbrace^2$, and these pairs are ordered lexicographically.
Lemma 1 (a) yields the existence of an invertible matrix $U\in k^{n\times n}$ and a diagonal matrix $D\in k^{n\times n}$ such that $A=U^TDU$, and Lemma 1 (b) shows that all entries of the matrix $D$ are nonnegative. Similarly, Lemma 1 (a) (applied to the matrix $B$ instead of $A$) yields the existence of an invertible matrix $V\in k^{n\times n}$ and a diagonal matrix $E\in k^{n\times n}$ such that $B=V^TEV$, and Lemma 1 (b) shows that all entries of the matrix $E$ are nonnegative. Thus, $A\otimes B=\left(U^TDU\right)\otimes\left(V^TEV\right)=\left(U\otimes V\right)^T\left(D\otimes E\right)\left(U\otimes V\right)$, so that the matrix $A\otimes B$ is nonnegative-definite (because the matrix $D\otimes E$ is a diagonal matrix all of whose entries are nonnegative, and therefore it is nonnegative-definite).
Now, let $v\in k^{n^2}$ be the vector given by $v_{\left(i,i'\right)}=\left[i=i'\right]$ for any pair $\left(i,i'\right)\in\left\lbrace 1,2,...,n\right\rbrace^2$. Here, for any assertion $\mathcal A$, we denote by $\left[\mathcal A\right]$ the truth value of $\mathcal A$, defined by $\left[\mathcal A\right]=1$ if $\mathcal A$ is true and $\left[\mathcal A\right]=0$ otherwise.
Now, an easy computation yields $v^T\left(A\otimes B\right)v=\operatorname{Tr}\left(AB^T\right)$. Since $B^T=B$, this becomes $v^T\left(A\otimes B\right)v=\operatorname{Tr}\left(AB\right)$. But $v^T\left(A\otimes B\right)v\geq 0$, since $A\otimes B$ is a nonnegative-definite matrix. Thus, $\operatorname{Tr}\left(AB\right)\geq 0$, proving Corollary 2.


text:
Q: Using custom Logging action in Play 2.2.x All examples I can find to use a custom Logger in Play Framework for play.Logger.debug(), play.Logger.info() etc (with the default static class Logger, not with any created instances) need to write a self-written class into conf/logger.xml. This does not work in development mode, I get an Exception
 Could not create an Appender of type [my.example.log.LoggerConnector].ch.qos.logback.core.util.DynamicClassLoadingException: Failed to instantiate type my.example
.log.LoggerConnector
        at ch.qos.logback.core.util.DynamicClassLoadingException: Failed to instantiate type my.example.log.LoggerConnector
        at      at ch.qos.logback.core.util.OptionHelper.instantiateByClassNameAndParameter(OptionHelper.java:73)

...
configuration looks like
<appender name="MYEXAMPLELOGGER" class="my.example.log.LoggerConnector">
  </appender>
and when I run the application via start, it works.
Does anybody know a way to register a Logger at runtime? The logger has to be instanciated after booting the application, since it should connect to some existing functionality.
Any hint, any help?


text:
Q: Stack trace showing ERB syntax error. Is the problem with app code or ERB library? I'm working through an ERB chapter from a Lynda.com course, Ruby Essential Training Part 3: Files, Formats, Templates, and keep getting a syntax error in what appears to be ERB itself. When I enter this code:
#!/usr/bin/env ruby

#### Mail Merge ####
#
# Launch this Ruby file from the command line
# to get started
#

require 'erb'
require 'csv'

APP_ROOT = File.expand_path(File.dirname(__FILE__))

# files in current dir
template_path = File.join(APP_ROOT, 'letter_template.txt')
csv_path = File.join(APP_ROOT, 'us_presidents.csv')

template = File.read(template_path)

i = 0
CSV.foreach(csv_path) do |row|
  next if row[0].start_with?('Number') # Header row
  i += 1

  @last_name = row[1]
  @first_name = row[2]
  state = row[6]
  end_date = row[4] || Time.now.year

  @title = "The History of #{state}"
  @due_date = end_date
  years = Time.now.year - @due_date.to_i
  @fee = "$#{years * 365}.00"

  letter = ERB.new(template).result(binding)

  num = i < 10 ? "0#{i}" : i
  filename = "letter_#{num}.txt"
  filepath = File.join('letters', filename)

  puts "-------"
  puts filepath
  puts letter

  File.write(filepath, letter)

end

I get this error message:
Traceback (most recent call last):
    15: from init.rb:20:in `<main>'
    14: from /Users/andrekibbe/.rvm/rubies/ruby-2.7.0/lib/ruby/2.7.0/csv.rb:510:in `foreach'
    13: from /Users/andrekibbe/.rvm/rubies/ruby-2.7.0/lib/ruby/2.7.0/csv.rb:658:in `open'
    12: from /Users/andrekibbe/.rvm/rubies/ruby-2.7.0/lib/ruby/2.7.0/csv.rb:511:in `block in foreach'
    11: from /Users/andrekibbe/.rvm/rubies/ruby-2.7.0/lib/ruby/2.7.0/csv.rb:1280:in `each'
    10: from /Users/andrekibbe/.rvm/rubies/ruby-2.7.0/lib/ruby/2.7.0/csv.rb:1280:in `each'
     9: from /Users/andrekibbe/.rvm/rubies/ruby-2.7.0/lib/ruby/2.7.0/csv/parser.rb:336:in `parse'
     8: from /Users/andrekibbe/.rvm/rubies/ruby-2.7.0/lib/ruby/2.7.0/csv/parser.rb:823:in `parse_quotable_loose'
     7: from /Users/andrekibbe/.rvm/rubies/ruby-2.7.0/lib/ruby/2.7.0/csv/parser.rb:49:in `each_line'
     6: from /Users/andrekibbe/.rvm/rubies/ruby-2.7.0/lib/ruby/2.7.0/csv/parser.rb:49:in `each_line'
     5: from /Users/andrekibbe/.rvm/rubies/ruby-2.7.0/lib/ruby/2.7.0/csv/parser.rb:52:in `block in each_line'
     4: from /Users/andrekibbe/.rvm/rubies/ruby-2.7.0/lib/ruby/2.7.0/csv/parser.rb:871:in `block in parse_quotable_loose'
     3: from /Users/andrekibbe/.rvm/rubies/ruby-2.7.0/lib/ruby/2.7.0/csv/parser.rb:1122:in `emit_row'
     2: from init.rb:34:in `block in <main>'
     1: from /Users/andrekibbe/.rvm/rubies/ruby-2.7.0/lib/ruby/2.7.0/erb.rb:905:in `result'
/Users/andrekibbe/.rvm/rubies/ruby-2.7.0/lib/ruby/2.7.0/erb.rb:905:in `eval': (erb):6: syntax error, unexpected '=', expecting end-of-input (SyntaxError)
;  = @due_date ; _erbout.<< "\\n\\n...**

Everything in the stack trace references CSV and ERB lines, so I can't see anything I can correct on my end. Am I missing something?
Update: letter_template.rb added:
Dear <%= @first_name %> <%= @last_name %>,

The following library book is overdue.

"<%= @title %>"
Due: <% = @due_date %>

Overdue fee: <%= @fee %>

Thank you for your prompt attention to this matter.

A: The stack trace shows lines from ERb because ERb code is the one that is executing.
While the issue could theoretically be in either ERb itself or your template, it is much more likely that the issue is in your template given that ERb is used by thousands of developers and applications daily.


text:
Q: регулярка для дробного числа, НЕ начинающегося с 0 если есть другие цифры в целой части Для WPF-контрола TextEdit из DevExpress15.2 мне нужна маска ввода для дробного числа (желательно заданной разрядности целой/дробной части), причём никогда не отображающая символ-разделитель дробной части, если пользователь сам её не пишет.
Стандартный вариант числовой Numeric маски наподобие n не устраивает тем, что даже если вводим целое число, всё равно отображается в конце символ разделитель дробной части.
Установка значений MaskUseAsDisplayFormat="False"  MaskSaveLiteral="False" такого результата не дала.
Решил реализовать это с помощью регулярных выражений как для дробного числа, таким образом:
[-+]?\d{1,32}[.,]?\d{0,6}

(спец.символы начала/конца строки не пишем, т.к. в DevExpress они уже подразумеваются; на случай ввода некорректного символа-разделителя дробной части у меня есть валидация значений)
Проблема в том, что она должна пропускать значения вроде (120,345, 102,345, 0,123) и при этом НЕ пропускать вроде 012,345 -- т.е. требуется маска для дробного числа, НЕ начинающегося с 0 если есть другие цифры в целой части.
Скажите как победить :) не обязательно регулярками.

A: ^[-+]?(0|[1-9]\d{0,31})([.,]\d{1,6})?$

Проверка:

input { box-sizing: border-box; width: 100%; border: 1px solid; outline: none; }
:valid { border-color: green; }
:invalid { border-color: red; }
<input pattern="^[-+]?(0|[1-9]\d{0,31})([.,]\d{1,6})?$" autofocus>


text:
Q: Filter large dataframe by two columns using second dataframe in R I have a dataframe which looks like the following:
library(tidyverse)

full.df<-tibble(x = c(1.5, 2.5, 3.5, 5.6, 7.4),
                y = c(4.5, 4.3, 2.6, 5.6, 7.6),
                a = c(1, 2, 3, 4, 5),
                b = c(5, 6, 7, 8, 9))

And a second dataframe that's essentially a subset of full.df but missing columns a & b:
subset.df<-tibble(x = c(1.5, 3.5, 7.4),
                  y = c(4.5, 2.6, 7.6))

How can I filter full.df on x & y using x & y from subset.df? I wish to return this:
# A tibble: 3 x 4
      x     y     a     b
  <dbl> <dbl> <dbl> <dbl>
1   1.5   4.5     1     5
2   3.5   2.6     3     7
3   7.4   7.6     5     9

I have tried full.df %>% filter(x == subset.df$x & y == subset.df$y) but this only returns the first row.

A: You're looking for
full.df %>% right_join(subset.df, by = c('x','y'))


text:
Q: Issue with Footer styling I am currently building a website and my code has been fine until now. I have added a footer to my webpage and it shows. However, when I add a height it doesn't change at all. Instead it changes the footer to the colour white. I have also tried using a div and a section (just for testing purposes) but it is still the same result. Any help would be appreciated! Here is the code:

St Philip Neri

Home

Contact

Welcome to our multicultural society.

Come worship with us.

    <button type="button">View the Sunday Bulletin</button>

body{
margin:0px;
}

header{
background-color:#080808;
display: flex;
align-items:center; /* align vertical */
padding-top:10px;
padding-bottom:10px;
position:fixed;
width:100%;
z-index:1000;
}

img{
display:inline-block;
width:35px;
margin-left:100px;
}

#textlogo{
margin:0px;
color:white;
font-family: 'Roboto', sans-serif;
font-weight:700;
display:inline-block;
margin:10px;
}

a{
color:white;
list-style-type:none;
text-decoration:none;
font-family:roboto,sans-serif;
font-weight:500;
font-size:15px;
}

nav{
margin-left:auto;
margin-right:100px;
}

nav li{
display:inline;
padding:5px;
}

#section1{
background-image:     url("http://i300.photobucket.com/albums/nn18/ojijimanuel/imageedit_4_6279316354_    zpsgbpfsvo1.jpg");
background-repeat:no-repeat;
background-size:100%;
background-position:center;
width:100%;
height:670px;
text-align:center;
display: flex;
align-items:center; /* align vertical */
justify-content:center;
flex-direction:column;

}

#section1heading{
color:white;
font-size:50px;
margin:0px;
font-family: 'Roboto', sans-serif;
font-weight:500;
display:block;
position:relative;
top:100px;

}

#section1paragraph{
color:white;
font-family:'Roboto', sans-serif;
font-weight:400;
font-size:20px;
position:relative;
top:100px;
}

#section2{
width:100%;
background-color:#cc1d00;
margin:0px;
padding-top:130px;
padding-bottom:130px;
text-align:center;
background-image:       url("http://i300.photobucket.com/albums/nn18/ojijimanuel/imageedit_7_2748546790_    zpsc1alysjl.jpg");
background-position:center;
background-size:100%;
display: flex;
align-items:center; /* align vertical */
justify-content:center;
height:50px;
}

button{
text-align:center;
border-color:white;
color:white;
background-color:transparent;
border-style:solid;
font-size:25px;
font-family: Roboto, sans-serif;
font-weight:500;
border-width:3.5px;
padding:10px;
}

button{
cursor: pointer;
cursor: hand;
}

#section3{
width:50%;
height:600px;
background-color:blue;
float:left;
}

#section4{
width:50%;
height:600px;
background-color:red;
float:right;
}

#footer{
width:100%;
background-color:orange;
margin:0px;
height:500px;
}

A: *

*wrong CSS selector, use footer { instead of #footer {

*add a clear fix to the footer style to avoid displaying it behind the sections
footer { clear: left; ...

A: To see your footer set it to float: left; and also define a height.
CSS
footer{
  background: white;
  float: left;
  height: 200px;
}

I hope this will help you.
EDIT
And remove this #footer to footer. The first one is when you declared a id named footer.

A: Firstly, Don't use an ID for the tag of the footer, instead of #footer, use footer.
Secondly, the footer seems to appear behind the sections, use a clear:both; to fix that.
Have a look at the snippet below :)

body{
margin:0px;
}

header{
background-color:#080808;
display: flex;
align-items:center; /* align vertical */
padding-top:10px;
padding-bottom:10px;
position:fixed;
width:100%;
z-index:1000;
}

img{
display:inline-block;
width:35px;
margin-left:100px;
}

#textlogo{
margin:0px;
color:white;
font-family: 'Roboto', sans-serif;
font-weight:700;
display:inline-block;
margin:10px;
}

a{
color:white;
list-style-type:none;
text-decoration:none;
font-family:roboto,sans-serif;
font-weight:500;
font-size:15px;
}

nav{
margin-left:auto;
margin-right:100px;
}

nav li{
display:inline;
padding:5px;
}

#section1{
background-image:     url("http://i300.photobucket.com/albums/nn18/ojijimanuel/imageedit_4_6279316354_    zpsgbpfsvo1.jpg");
background-repeat:no-repeat;
background-size:100%;
background-position:center;
width:100%;
height:670px;
text-align:center;
display: flex;
align-items:center; /* align vertical */
justify-content:center;
flex-direction:column;

}

#section1heading{
color:white;
font-size:50px;
margin:0px;
font-family: 'Roboto', sans-serif;
font-weight:500;
display:block;
position:relative;
top:100px;

}

#section1paragraph{
color:white;
font-family:'Roboto', sans-serif;
font-weight:400;
font-size:20px;
position:relative;
top:100px;
}

#section2{
width:100%;
background-color:#cc1d00;
margin:0px;
padding-top:130px;
padding-bottom:130px;
text-align:center;
background-image:       url("http://i300.photobucket.com/albums/nn18/ojijimanuel/imageedit_7_2748546790_    zpsc1alysjl.jpg");
background-position:center;
background-size:100%;
display: flex;
align-items:center; /* align vertical */
justify-content:center;
height:50px;
}

button{
text-align:center;
border-color:white;
color:white;
background-color:transparent;
border-style:solid;
font-size:25px;
font-family: Roboto, sans-serif;
font-weight:500;
border-width:3.5px;
padding:10px;
}

button{
cursor: pointer;
cursor: hand;
}

#section3{
width:50%;
height:600px;
background-color:blue;
float:left;
}

#section4{
width:50%;
height:600px;
background-color:red;
float:right;
}

footer{
width:100%;
background-color:orange;
margin:0px;
height:500px;
clear: both;

}

St Philip Neri

Home

Contact

Welcome to our multicultural society.

Come worship with us.

    <button type="button">View the Sunday Bulletin</button>


text:
Q: Max and Group by functions in SQL Server my sql got a bit rusty and I was wondering if there is a simple solution for my ask. I'm trying to get two unique UUIDs with with MAX ModifiedTime. Below is my code that I tried to simplify as much as possible. My goal is to get unique UUID with its MAX ModifiedDate along with other two associated columns- desired output 2 rows.
SELECT [UUID],[Description],IsHLVE,ModifiedTime
FROM tblConstructSecureIntelProjectIncidents
WHERE UUID in ('0b666564-38af-4cc2-9a58-58f9b57244b1','4b6080ea-5c13-4f03-8967-a6beb71e80c4')
ORDER BY UUID,ModifiedTime

I tried to group by all columns and do max which doesn't work properly since my "description" and "IsHLVE" have different values.
select [UUID],[Description],IsHLVE,MAX(ModifiedTime)
FROM tblConstructSecureIntelProjectIncidents
WHERE UUID in ('0b666564-38af-4cc2-9a58-58f9b57244b1','4b6080ea-5c13-4f03-8967-a6beb71e80c4')
GROUP BY [UUID],[Description],IsHLVE
ORDER BY UUID

I believe I need some kind of temporary table first and then join it back?
My desired output should have two unique UUIDs with its max date including all associated columns.

A: Perhaps something like this?
SELECT * FROM tblConstructSecureIntelProjectIncidents AS t
INNER JOIN (
 SELECT [UUID],MAX(ModifiedTime) AS LatestModifiedTime
 FROM tblConstructSecureIntelProjectIncidents
 WHERE UUID in ('0b666564-38af-4cc2-9a58-58f9b57244b1','4b6080ea-5c13-4f03-8967-a6beb71e80c4')
 GROUP BY [UUID]
) AS latest ON latest.UUID = t.UUID AND latest.LatestModifiedTime = t.ModifiedTime
ON latest.UUID

A: Sub-query and inner join takes care of this.
SELECT
    t1.uuid
    ,t1.Description
    ,t1.IsHLVE
    ,t1.modifiedtime
FROM tblConstructSecureIntelProjectIncidents as t1
INNER JOIN (
    SELECT
        MAX(modifiedtime) as modifiedtime
        ,uuid
    FROM tblConstructSecureIntelProjectIncidents
    GROUP BY uuid
) as s on t1.uuid = s.uuid and t1.modifiedtime = s.modifiedtime

A: This will get the max modification time per UUID:
select [UUID],MAX(ModifiedTime)
FROM tblConstructSecureIntelProjectIncidents
WHERE UUID in ('0b666564-38af-4cc2-9a58-58f9b57244b1','4b6080ea-5c13-4f03-8967-a6beb71e80c4')
GROUP BY [UUID]

Now you can get the data you want by selecting the values, and JOINing them:
select [UUID],[Description],IsHLVE,MAX(ModifiedTime)
FROM tblConstructSecureIntelProjectIncidents tCSPI
INNER JOIN (
   select [UUID],MAX(ModifiedTime) as MMT
   FROM tblConstructSecureIntelProjectIncidents
   WHERE UUID in ('0b666564-38af-4cc2-9a58-58f9b57244b1','4b6080ea-5c13-4f03-8967-a6beb71e80c4')
GROUP BY [UUID]
) sub ON sub.UUID = tCSPI.UUID AND sub.MMT = tCSPI.ModifiedTime


text:
Q: How can I have my listbox have columns? I want my ListBox to have columns, and one of those columns have to be a clickable URL.
How can I achieve this?

A: You can't do it in a ListBox.  You can create your own control, or settle for another existing one.  Based on the question, I'd guess you're not yet at the stage where you're creating your own controls.  That takes a pretty good understanding of existing controls and the way they work under the covers (but a google search for creating Winforms Controls should yield plenty of instructions.)  Edit added It looks like te 4th and 5th links in combination on that google search should get you what you need.  You can create your own user control and then do an array of them)
As far as for other possible alternatives, have you considered a DataGridView?  A DataGridView can have a hyperlink and it can have checkbox columns, so this would be one possible alternative.
Here's a link for having a Hyperlink column in a DataGridView.

A: Well, it is possible by using the CustomTabOffsets property (unreliable) or the DrawItem event.  And implementing the MouseDown event to find out if that particular 'column' was clicked.
But there's little point, a ListView control with View = Details gives you the same functionality.


text:
Q: how do you view subscriptions in discord desktop program? how do you view subscriptions in discord?
I subscribed a few months ago to a discord server.. I only have the one subscription
but I want to view all subscriptions so that that subscription shows up.

A: Do this :

*

*In the Discord desktop program, click the Settings gear icon at the bottom-left

*Switch to the Subscriptions tab on the left

*You will see the list under "Your Subscriptions".


text:
Q: Pandas - Make some headers row values I have what I assume might be a complexed ask.
I have a few columns in my dataframe, for each date column I want to store the date headers in the column called "Dates" and then I want to create 2 new columns to store the max and min values
DataFrame
DataFrame

ID
Item
DateMade_Min
DateMade_Max
DelDate_Min
DelDate_Max
ExpDate_Min
ExpDate_Max

1
2322
01/01/2020
01/01/2020
05/06/2020
07/06/2020
06/05/2022
09/09/2022

2
4454
03/04/2020
01/01/2021
07/08/2020
31/08/2020
15/12/2022
09/01/2023

Desired Output

ID
Item
Dates
Min
Max

1
2322
DateMade
01/01/2020
01/01/2020

1
2322
DelDate
05/06/2020
07/06/2020

1
2322
ExpDate
06/05/2022
09/09/2022

2
4454
DateMade
03/04/2020
01/01/2021

2
4454
DelDate
07/08/2020
31/08/2020

2
4454
ExpDate
15/12/2022
09/01/2023

A: You can reshape with an intermediate stacking and a MultiIndex:
out = (df
   .set_index(['ID', 'Item'])
   .pipe(lambda d: d.set_axis(d.columns.str.split('_', expand=True), axis=1))
   .stack(0)
   .reset_index().rename(columns={'level_2': 'Dates'})
)

output:
   ID  Item     Dates         Max         Min
0   1  2322  DateMade  01/01/2020  01/01/2020
1   1  2322   DelDate  07/06/2020  05/06/2020
2   1  2322   ExpDate  09/09/2022  06/05/2022
3   2  4454  DateMade  01/01/2021  03/04/2020
4   2  4454   DelDate  31/08/2020  07/08/2020
5   2  4454   ExpDate  09/01/2023  15/12/2022

alternative
Alternatively, you can use the janitor helper module and its pivot_longer function:
# pip install janitor
import janitor

out = df.pivot_longer(
    index=['ID', 'Item'],
    names_to=('Dates', '.value'),
    names_sep = '_',
    sort_by_appearance=True
)

A: here is one way to doit
# melt the DF
df2=df.melt(['ID','Item'])

# split the date field on '_' to form two columns

df2[['date','minmax']]=df2['variable'].str.split('_', expand=True)

# use pivot to reformat the resultset
df2.pivot(index=['ID','Item','date'], columns='minmax', values='value').reset_index()

minmax  ID  Item    date    Max     Min
0   1   2322    DateMade    01/01/2020  01/01/2020
1   1   2322    DelDate     07/06/2020  05/06/2020
2   1   2322    ExpDate     09/09/2022  06/05/2022
3   2   4454    DateMade    01/01/2021  03/04/2020
4   2   4454    DelDate     31/08/2020  07/08/2020
5   2   4454    ExpDate     09/01/2023  15/12/2022


text:
Q: Recursion into stack-form. Preserving a search path towards ends of recursion
A short form of question is: How do I convert a recursive search into a stack search? The trick is to be able to grab a branch that leads towards each of the recursion's endings.
This Article's suggestion won't work as the path to the ending cannot be traced. (Ultimately if we could save each step into array via the reference to trace later on)
I am using c#, and building a web of nodes.

Each node contains an information about its neighbors.
Also, each node contains 2 arrays. The 1st one is referencing all the nodes to which this node can communicate. The 2nd array holds lists, each of which contains "a path", consisting of ordered  node references.
If node A wishes to communicate to node B, he will look at the first array to see if B is even in his reach. If he finds it, he uses this index from a first array on a 2nd array to obtain "a path".
It's important for me to preserve this order.
As well as that, every node contains a list of direct neighbors (within a reach of 1).
Knowing its neighbors is actually the only thing each node knows before a Bake process occurs.
During the Bake, I recursively search through each neighbor of an inspected node, recording the "recursion branch" into a path-buffer list. As soon as there are  no more neighbors, I copy this buffer "path-list" into the 2nd Array + copy this dead-end node into a next cell of the 1st Array. of corse 1st and 2nd array belong to the node which we started from.
I then remove 1 dead -end node from the path list's last cell, rollback to a previous node to inspect another neighbor and the process repeats.
The problem is - huge recursions cause a stack overflow if the web gets too big. I need to translate it into a stack form.
I've looked over articles, such as this one, but there is obviously no way of accumulating this "path list", since every neighbor of every node on the way is pushed into a stack, anticipating a further inspection in future. There is no clear "trace" of the path we took to get to this dead-end node.
Here is a simplified version of the code (2 classes)
class Node{

    List neighbours;
    List accessNodes;
    List allPaths;
}

class Baker{

  List bakerBufferPaths;
  List bakerBanned;

   foreach particular node in scene{
        clear accessNodes;
        clear allPaths;
        clear bakerBufferPaths;
        }

        MainNodeList1 = particular node's list1 by reference. //those 2 variables will always  refer to the base node for which the search happens. They will be unchanged on all the levels of recursion
        MainNodeList2 = particular node's list2 by reference.

    void  function LookFurther(Node node){
          Node current;
          current = node;

          bakerBufferList(add current);

          foreach (not banned neighbor in current){

               LookFurther(current);
          }//end of foreach neighbor of current

          MainNodeList 1 (add current);
          MainNodeList 2 (add bakerBufferList);

          bakerBanned(add current);

         bakerBufferList(remove last);
     } //end of look further function

} //end of baker class

What to do?
Thank you

A: OK, this was an interesting question, so here's some example C# code I wrote up.
private static void SearchConnections(Node root)
{
    var path = new Stack<Node>();
    var progress = new Stack<int>();

    path.Push(root);        // start with root
    progress.Push(0);       // start with root's first neighbour

    while (path.Any())
    {
        var topnode = path.Peek();

        // continue the search until we get to a leaf
        int neighbourIx = progress.Pop();
        if (neighbourIx < topnode.Neighbours.Count())
        {
            // next time we are at this node, take the next neighbour
            progress.Push(neighbourIx + 1);
            // don't push cycles onto the stack!
            var nextNeighbour = topnode.Neighbours[neighbourIx];
            if (!path.Contains(nextNeighbour))
            {
                path.Push(nextNeighbour);
                // when we process the neighbour we just pushed,
                // start with its first neighbour
                progress.Push(0);
            }
        }
        else
        {
            // no more neighbours here - either a leaf, or we've searched all
            // neighbours. this is the last time we'll see this node, so
            // process it now. record the path to the top node unless
            // topnode is root - no path to self!
            if (topnode != root)
            {
                var trace = path.Reverse().ToList();
                root.Reachable.Add(topnode);
                root.Paths.Add(trace);
            }

            // remove the topnode from the stack
            path.Pop();
        }
    }
}

Here's a fiddle that shows it working: http://dotnetfiddle.net/6ijNzb
I've used two stacks - one to keep track of the nodes in the path, and one to keep track of which neighbour we picked at each branch in the path.


text:
Q: How to persistently store data in Next.js? I'm having trouble storing data persistently.
My case is when user logs in, I store JWT in web storage. However, I need to store user's information, such as user nickname or id.
I am trying to render user nickname in <header />.
I tried three different methods.
first one is using recoil, global state library. It didn't go well because whenever I refresh the page, every atoms were back to their initial value.
second one is using recoil-persist. I used recoil-persist or redux-persist in React. However, since recoil-persist works based on localStorage, I had a problem in hydration on Next.js. (localStorage doesn't exist in SSR, therefore hydration error occurs.)
last one I'm currently using is recoil and localStorage. Here's the code.
import { useRecoilValue } from 'recoil';
import { userNicknameAtom } from 'atoms/atom';
import { useEffect, useState } from 'react';
import styles from './header.module.scss';

function Header() {
  const [nick, setNick] = useState('');
  const user = useRecoilValue(userNicknameAtom);

  useEffect(() => {
    if (user) {
      localStorage.setItem('nickname', user);
    }
  });

  useEffect(() => {
    const id = localStorage.getItem('nickname');

    if (id) {
      setNick(id);
    } else {
      setNick('');
    }
  });

  return (
    <header className={styles.header}>
      {nick}
    </header>
  );
}

export default Header;

I am giving no dependency to useEffect to make sure codes inside useEffect runs every render. This works quite well.
However, I'm wondering whether this is the best approach to handle user info in Next.js If I can simply modify my code, I would like to know.

A: In a real app situation you would have a backend which would return your user data (automatically based on a token which is normally saved as a cookie). So each time your app is initialised you would make a request to get your user data and store it in your state management (redux, recoil, etc).
But in your case you want to make sure that you update your localStorage each time your user changes (I don't think there is any other case you want to update the localStorage). So your first useEffect should have user value in the dependency array like this:
  useEffect(() => {
    if (user) {
      localStorage.setItem('nickname', user);
    }
  }, [user]);

If the user value hasn't changed it doesn't make sense to update it with the same value.
Also I think you don't need second useEffect if you add the state setting to your first one (so in the end use just one useEffect which looks like this:
  useEffect(() => {
    if (user) {
      localStorage.setItem('nickname', user);
      setNick(user);
    }
  }, [user]);

)

A: Making a localStorage in Next.js persist is very frustrating, but it is possible, this is a link that I think would help one who wants to store some user preferences and settings, without setting or adding a modal and db to store the user's input. How to persist data in Next.js with localStorage and no libraries.
Here is a demo


text:
Q: jQuery (billy.carousel) - Carousel going nuts sometimes thanks in advance if you're willing to beam me up with a solution. I'm working on a site http://tecnointelcom.com/new/ -- and there is a carousel in the homepage. I'm using a jQuery Plugin "Billy the Carousel", from time to time it gets nuts and jumps from slide to another in less than 1 second (periodically, so about 5 slides in 3 seconds), but the indicator is still in the anchor of the a slide (it does not go nuts like the slider).
the jquery plugin is in (same route as prev link)/js/billy.carousel.jquery.js
the init file is in (same route as prev link)/js/init.js
Pls... could anyone see this and reply with something I must be missing in the code?
Thx, Alex

A: It looks like the plugin is queuing functions that contain animations with setInterval(). The latest modern browsers have begun to implement feature called requestAnimationFrame() to save resources. Essentially, your animation calls are being stacked up while your tab with the carousel in it is out of focus or hidden. When the tab regains focus, jQuery executes them all at the same time. jQuery advises you not to do this. From their .animate() documentation:

Because of the nature of requestAnimationFrame(), you should never queue animations using a setInterval or setTimeout loop. In order to preserve CPU resources, browsers that support requestAnimationFrame will not update animations when the window/tab is not displayed. If you continue to queue animations via setInterval or setTimeout while animation is paused, all of the queued animations will begin playing when the window/tab regains focus. To avoid this potential problem, use the callback of your last animation in the loop, or append a function to the elements .queue() to set the timeout to start the next animation.

You could also clear the object's fx queue with .clearQueue() right before the animation starts. At line 160 of billy.carousel.jquery.js:
object.clearQueue().animate({'marginLeft': "0"}, option.scrollSpeed);


text:
Q: Why do we add 4 to the desitnation when calculating the distance between two address? I am self-studying assembly and I've seen this in the coursehero when I was doing question.
when we are trying to calculate how far is address 2(Destination) from address 1(Starting point)
Lets say address 2 is 0x1FFFFFFF and address 1 is 0x1000FFFF.
the answer showed that we should do such : Ox1FFFFFFF + 4 - 0x1000FFFF.
Where does the 4 come from ? when do we need to add that when calculating the distance?


text:
Q: I can't get a Scheme function to recursively invoke f on a nested list for the correct result I didn't do too hot on a test I took recently in a class.  However, since everyone else bombed it as well, our professor is willing to give us some "make up" points by proving to her that we know Scheme (not so great at it...). She'd ask different questions from what was on the test, though.  So I'm working on the questions that were on the test to get better with Scheme, and I can't seem to get the following one to work.
Write a Scheme function reduce which takes two parameters: f, a function which takes a single parameter, and x, an arbitrary value.  The reduce function recursively invokes f using each nested list contained in x and then replaces the original nested list with the result of invoking f.
For example, invoking (reduce (lambda(x) (cons 'list x)) '(3 7 9 z s (3 (78 2 3)))) should return:
'(list 3 7 9 z s (list 3 (list 78 2 3)))
Also, invoking (reduce (lambda (x) (cdr x)) '(3 7 9 z s (3 (78 2 3)))) should return:
'(7 9 z s ((2 3))), where the first element is removed from each nested list.
This is the code I came up with:
(define reduce
  (lambda (f x)
    (if (null? x)'()
    (let ((var (car x)))
    (cond
      ((cons? var) (cons (f var) (reduce f (cdr x))))
      ((symbol? var) (cons var (reduce f (cdr x))))
      ((number? var) (cons var (reduce f (cdr x)))))))))

If I enter the example inputs, these are my results:

(reduce (lambda(x) (cons 'list x)) '(3 7 9 z s (3 (78 2 3))))

(list 3 7 9 'z 's (list 'list 3 (list 78 2 3)))
there's an extra 'list coming from who knows where
;

(reduce (lambda(x) (cdr x)) '(3 7 9 z s (3 (78 2 3))))

(list 3 7 9 'z 's (list (list 78 2 3)))
it only removes the 3 in the 2nd nested loop.  It should remove the 3 in the first one, 3 in the middle and the 78 in the 3rd.  It also shouldn't have the word "list" in it
;
I'm assuming the problem is in the line ((cons? var), but I can't seem to figure out how to fix it.
We didn't go too far into the Scheme language, so we haven't learned a whole lot of special methods; it's mainly all just recursion.
Any help would be much appreciated.
Thanks.

A: Here's my implementation:
(define (reduce f x)
  (define (inner x)
    (if (list? x)
        (f (map inner x))
        x))
  (inner x))

Examples:
> (reduce (lambda (x) `(list ,@x)) '(3 7 9 z s (3 (78 2 3))))
(list 3 7 9 z s (list 3 (list 78 2 3)))
> (reduce cdr '(3 7 9 z s (3 (78 2 3))))
(7 9 z s ((2 3)))

Here's a version that doesn't use map directly, but basically reimplements map (albeit using a hardcoded transformer):
(define (reduce f x)
  (define (transform lst)
    (if (null? lst)
        '()
        (cons (process (car lst)) (transform (cdr lst)))))
  (define (process x)
    (if (list? x)
        (f (transform x))
        x))
  (process x))


text:
Q: Нужен способ получения случайных английских слов. Как лучше это реализовать? Делаю игру, развивающую скорость печать(знаю, такие уже есть). Понимаю, что нужен файл либо база данных слов, как именно это лучше реализовать, и где можно скачать подобные словари?

A: Реализация:
Самое простое, что приходит в голову это хранить слова в txt файле.

*

*Загружаем строку из файла.

*Разбиваем ее в зависимости от разделителя для слов, который был использован.

*Складываем это все в массив и дальше пользуемся как угодно.

Скачать:
Есть частотные словари, вот например такой http://www.wordfrequency.info/100k.asp

A: Списки слов есть в интернете, и легко гуглятся. Поэтому вы можете подсчитать общее количество слов/строк в файле, и в нужный момент просто брать строку со случайным номером.
Небольшой трюк состоит в том, что обычно искать строку по номеру невозможно без предварительного чтения всех предыдущих строк. Чтобы обойти это, подсчитайте максимальную длину слова в вашем файле, и дополните все слова пробелами до этой максимальной ширины. Теперь ваши строки все одинакового размера (разумеется, если вы используете Encoding.Unicode, а не Encoding.UTF8: английские слова могут содержать символы вне ASCII), и вы можете просто найти смещение начала строки в файле.
Ну или если в вашем словаре несчастных 20 тысяч слов (размером со словарный запас Пушкина), можно не париться с оптимизацией хранения, и считать весь словарь в память один раз при старте программы.


text:
Q: Does the Square app have a custom URL scheme? In my iOS app, as part of the mobile payments options, I'd like to direct users who have the Square app installed on their device to use this as a payment option.
Is there a custom URL scheme that Square uses that would allow me to launch their app from within mine?

A: Yes, the Square app does have a custom URL schema you can call: square://
You can also see if the application is installed by the following method:
- (BOOL)isSquareInstalled
{
    return [[UIApplication sharedApplication] canOpenURL:[NSURL URLWithString:@"square://"]];
}

A: The Square Pay app uses the URL Scheme square-pay://