text:
Q: CakePHP 2.0 migration XML Helper Almost finished a CakePHP migration (on a very big project which I didn't write) from 1.3.14 to 2.0.5  One of the remaining issues is with the deprecation of the XML Helper.
The new XML class in 2.0.5 fails for me where it previously worked.  The migration guide states "Now this class does not manipulate data anymore, and it is a wrapper to SimpleXMLElement"
http://book.cakephp.org/2.0/en/appendices/2-0-migration-guide.html#xml
Previously I was using:
file_put_contents($xml_file, $this->Xml->serialize($quote, array('encoding' => 'UTF-8')));

I have tried replacing the above with:
$xml =  Xml::build($quote, array(
    'encoding' => 'UTF-8',
    'format' => 'attributes'));

However all I get is an exception 'XmlException' with message 'Invalid input.'  I've included a sample array below.
Basically the new XML class does not like the array input.  There are several parts of the application that all generate complex XML and they have the same issue.
Has anyone run into this problem?  It will take me forever to debug this.
I guess a potential workaround would be to copy the old Xml.php and helper and maybe make a plugin, but I'd prefer to get this all working if possible.
Sample array:
Array
(
    [Quote] => Array
        (
            [id] => 1
            [quote_template_id] => 1
            [project_id] => 1
            [quote_status_id] => 1
            [client_id] => 1
            [date_added] => 2011-05-11
            [is_archived] => 0
            [comment] => Revision 2.
        )

    [Project] => Array
        (
            [id] => 1
            [project_status_id] => 2
            [user_id] => 5
            [salesperson_id] => 5
            [site_id] => 1
            [name] => Test Project
            [description] =>
            [is_archived] => 0
            [date_added] => 2011-05-11
            [expected_start] => 2011-05-11
            [Actual_start] =>
            [expected_finish] => 2011-05-11
            [actual_finish] =>
            [special_clearance] => 1
            [ProjectStatus] => Array
                (
                    [id] => 2
                    [name] => Tendering
                )

            [User] => Array
                (
                    [id] => 5
                    [user_group_id] => 5
                    [username] => operations
                    [password] => 7de1e823411aec881a96475e614d6286b944e92b
                    [first_name] => Operations
                    [last_name] => Person
                    [contact_phone] => 0400 000 000
                    [contact_number] => 0400 000 000
                    [emerg_contact_name] => 123
                    [emerg_contact_phone] => 0400 000 000
                    [is_active] => 1
                    [is_reset_required] => 0
                    [address] => 123
                    [state] => VIC
                    [suburb] => 123
                    [postcode] => 3000
                    [full_name] => Operations Person
                )

            [Site] => Array
                (
                    [id] => 1
                    [site_type_id] => 1
                    [zone_id] => 1
                    [name] => Highpoint Test Site
                    [address] => 200 Rosamond Road
                    [suburb] => Maribyrnong
                    [postcode] => 3032
                    [state] => VIC
                    [melway_ref] => -
                    [date_added] => 2011-02-25 11:19:00
                    [comment] => This is just a test site
                    [is_active] => 1
                )

            [Salesperson] => Array
                (
                    [id] => 5
                    [user_group_id] => 5
                    [username] => operations
                    [password] => 7de1e823411aec881a96475e614d6286b944e92b
                    [first_name] => Operations
                    [last_name] => Person
                    [contact_phone] => 0400 000 000
                    [contact_number] => 0400 000 000
                    [emerg_contact_name] => 123
                    [emerg_contact_phone] => 0400 000 000
                    [is_active] => 1
                    [is_reset_required] => 0
                    [address] => 123
                    [state] => VIC
                    [suburb] => 123
                    [postcode] => 3000
                    [full_name] => Operations Person
                )

            [ProjectStatusChange] => Array
                (
                    [0] => Array
                        (
                            [id] => 1
                            [project_id] => 1
                            [project_status_id] => 1
                            [created] => 2011-05-11 17:27:14
                        )

                    [1] => Array
                        (
                            [id] => 2
                            [project_id] => 1
                            [project_status_id] => 2
                            [created] => 2011-05-11 17:27:23
                        )

                )

            [EquipType] => Array
                (
                    [0] => Array
                        (
                            [id] => 2
                            [category_id] => 3
                            [name] => 1-3.5 Tonne Excavator
                            [description] => this is just a test excavator
                            [is_usable_for_cartage] => 0
                            [EquipTypesProject] => Array
                                (
                                    [id] => 1
                                    [equip_type_id] => 2
                                    [project_id] => 1
                                )

                        )

                    [1] => Array
                        (
                            [id] => 4
                            [category_id] => 3
                            [name] => Float to Site
                            [description] =>
                            [is_usable_for_cartage] => 0
                            [EquipTypesProject] => Array
                                (
                                    [id] => 2
                                    [equip_type_id] => 4
                                    [project_id] => 1
                                )

                        )

                )

            [MaterialType] => Array
                (
                    [0] => Array
                        (
                            [id] => 6
                            [code] => IB
                            [name] => Clean Brick
                            [is_active] => 1
                            [MaterialTypesProject] => Array
                                (
                                    [id] => 4
                                    [material_type_id] => 6
                                    [project_id] => 1
                                    [is_importable] => 0
                                    [is_exportable] => 0
                                )

                        )

                    [1] => Array
                        (
                            [id] => 28
                            [code] => C
                            [name] => General Clay
                            [is_active] => 1
                            [MaterialTypesProject] => Array
                                (
                                    [id] => 5
                                    [material_type_id] => 28
                                    [project_id] => 1
                                    [is_importable] => 0
                                    [is_exportable] => 0
                                )

                        )

                    [2] => Array
                        (
                            [id] => 38
                            [code] => S
                            [name] => Sand
                            [is_active] => 1
                            [MaterialTypesProject] => Array
                                (
                                    [id] => 6
                                    [material_type_id] => 38
                                    [project_id] => 1
                                    [is_importable] => 0
                                    [is_exportable] => 0
                                )

                        )

                )

        )

    [QuoteStatus] => Array
        (
            [id] => 1
            [name] => Tendering
            [Quote] => Array
                (
                    [0] => Array
                        (
                            [id] => 1
                            [quote_template_id] => 1
                            [project_id] => 1
                            [quote_status_id] => 1
                            [client_id] => 1
                            [date_added] => 2011-05-11
                            [is_archived] => 0
                        )

                )

        )

    [Revision] => Array
        (
            [0] => Array
                (
                    [Revision] => Array
                        (
                            [id] => 3
                            [quote_id] => 1
                            [name] => Q-1-3
                            [comment] => Revision 2.
                            [user_id] => 5
                            [revision_time] => 2011-05-11 17:32:55
                            [quote_status_id] => 1
                        )
                )

        )

    [QuoteContact] => Array
        (
            [0] => Array
                (
                    [id] => 1
                    [contact_id] => 18
                    [quote_id] => 1
                    [Contact] => Array
                        (
                            [SEQNO] => 18
                            [SALUTATION] => Mr
                            [FIRSTNAME] => Bob
                            [LASTNAME] => Test
                            [TITLE] => Sales
                            [MOBILE] =>
                            [DIRECTPHONE] => 612-9999 9999
                            [DIRECTFAX] => 612-9999 9999
                            [HOMEPHONE] =>
                            [EMAIL] => asdf@asdf.com.au
                            [NOTES] =>
                            [ADDRESS1] => PO BOX 1111
                            [ADDRESS2] => PENRITH
                            [ADDRESS3] => NSW AUSTRALIA
                            [ADDRESS4] =>
                            [DELADDR5] =>
                            [DELADDR6] =>
                            [POST_CODE] =>
                            [DELADDR1] => 1 CLARKE ST
                            [DELADDR2] => PENRITH
                            [DELADDR3] => SYDNEY
                            [DELADDR4] => AUSTRALIA
                            [ISACTIVE] => Y
                            [ADVERTSOURCE] => 0
                            [SALESNO] => 1
                            [FULLNAME] => Bob Chancellor
                            [COMPANY_ACCNO] =>
                            [COMPANY_ACCTYPE] =>
                            [MSN_ID] =>
                            [YAHOO_ID] =>
                            [SKYPE_ID] =>
                            [ADDRESS5] =>
                            [LAST_UPDATED] => 2010-05-19 16:39:42
                            [id] => 18
                            [name] => Bob Test
                            [email] => asdf@asdf.com.au
                        )

                    [Quote] => Array
                        (
                            [id] => 1
                            [quote_template_id] => 1
                            [project_id] => 1
                            [quote_status_id] => 1
                            [client_id] => 1
                            [date_added] => 2011-05-11
                            [is_archived] => 0
                        )

                )

        )

)

A: XML documents must have only one root element, and CakePHP enforces this, ie your array must look something like this:
Array
(
    [Root] => Array
        (
            [Quote] => Array
                (
                    ...
                )

            [Project] => Array
                (
                    ...
                )

            ...
        )
)

The following should work:
$xml = Xml::build(array('root' => $quote), array(
    'encoding' => 'UTF-8',
    'format' => 'attributes'
));

See also http://book.cakephp.org/2.0/en/core-utility-libraries/xml.html#transforming-an-array-into-a-string-of-xml


text:
Q: Display Database entry as option in a Django Form I am trying to create an inventory app and one reservation app.
I am trying to take entries from the inventory model and one can reserve it with the help of reservation app.
What I am trying to achieve  :

*

*The reservation app should take the entry of serial number from the inventory app serial number.
It should either with the help of a drop down , which will show only the entry of specific serial number, so that random serial number should not be entered. ( I tried the concept of foreign key and many to many but I was unable to achieve it on the html page UI , but I achieved it on admin panel) Can you suggest what changes will be required ?

For now, I am creating a form like this :

But it is very poor method, because form is not getting validated, I am redirecting user to other web page where there are serial numbers present.
I am trying to see how can we make the serial numbers available there itself as a drop down so that user can select which serial number to select.

*I am trying to add the slot field as unique entry. I tried to add the slot as unique = True in reservation_app/models.py but it is only working in admin panel. When I try to give the duplicate entry on html page, it is accepting the duplicate value and it is also getting stored in database.

I am trying to find its solution from very long via all over the internet, but it seems very difficult to me.
If anyone knows how it can be done. That will be extremely grateful. I am providing almost everything of the necessary code which can be required below:
inventory_app/models.py
from django.db import models
#from django.utils import timezone
# Create your models here.
class Form1(models.Model):
    item = models.CharField(max_length=125)
    quantity = models.IntegerField(default=0)
    vendor = models.CharField(max_length=125)
    inward = models.IntegerField(default=1234)
    sno = models.CharField(max_length=100)
    date = models.DateField()
    date_received = models.DateField()
    def __str__(self):
      return self.item

reservation_app/models.py
from django.db import models

# Create your models here.
class Reserve(models.Model):
   team = models.CharField(max_length=125 , default="DevOps" )
   rsno = models.CharField(max_length=125, default="ABCD12345")
   mac_address = models.CharField(max_length=125 , default="AA-00-04-00-XX-YY")
   hostname = models.CharField(max_length=125, default="gitlab.altiostar.com")
   ue = models.CharField(max_length=125 , null=True)
   slot = models.DateField(null=True)
   def __str__(self):
    return self.team

reservation_app/views.py
from django.shortcuts import render, HttpResponse
from .models import Reserve
#from reservation_app.models import Reserve

# Create your views here.
def reserve(request):
    if request.method == "POST":
        team = request.POST.get('team')
        rsno = request.POST.get('rsno')
        mac_address = request.POST.get('mac_address')
        hostname = request.POST.get('hostname')
        ue = request.POST.get('ue')
        slot = request.POST.get('slot')
        reserve = Reserve( team=team , rsno=rsno, slot=slot , mac_address = mac_address , hostname = hostname , ue = ue ) #security_stamp_date=security_stamp_date
        reserve.save()
    return render(request, 'home.html')

inventory_app/views.py
from django.shortcuts import render, HttpResponse
from inventory_app.models import Form1
import datetime
from .models import Form1
import csv
from .filters import ItemFilter

def form1(request):
    if request.method == "POST":
        item = request.POST.get('item')
        quantity = request.POST.get('quantity')
        sno = request.POST.get('sno')
        inward = request.POST.get('inward')
        vendor = request.POST.get('vendor')
        date_received = request.POST.get('date_received')
     #   security_stamp_date = request.POST.get('security_stamp_date')
        form1 = Form1(item=item, quantity=quantity , inward=inward , sno=sno , vendor=vendor, date=datetime.datetime.now() , date_received=date_received ) #security_stamp_date=security_stamp_date
        form1.save()

    return render(request, 'form1.html')

home.html page of reservation_app

          Radio Serial Number
          <input type="text" class="form-control" id="exampleFormControlInput1" name= "rsno" placeholder="S/N123ABC123" required >

         Check Available Serial Numbers

        Book your slot for Date
        <input type="datetime-local" class="form-control" id="exampleFormControlInput1" name= "slot" >

      <button type="submit" class="btn btn-primary"> Submit </button>

form1.html of inventory_app

      Serial Number
      <input type="text" class="form-control" id="exampleFormControlInput1" name= "serial_number" placeholder="S/N123ABC123" required >

      <button type="submit" class="btn btn-primary"> Submit </button>

Thanks for your time :)

A: *

*What you want to do is to create a dynamic form where you generate a choice field. Check out this article about creating a dynamic form: https://www.caktusgroup.com/blog/2018/05/07/creating-dynamic-forms-django/

redpajama_set_name: RedPajamaStackExchange


text:
Q: The constraint reference 'string' could not be resolved to a type. type with 'Microsoft.AspNetCore.Routing.RouteOptions.ConstraintMap' Do you know why this error on C# /.NET 6 Web API project? It came suddenly today. Please let me know if you'll need any more info here.
System.InvalidOperationException: The constraint reference 'string' could not be resolved to a type. Register the constraint type with 'Microsoft.AspNetCore.Routing.RouteOptions.ConstraintMap'.
   at Microsoft.AspNetCore.Routing.DefaultParameterPolicyFactory.Create(RoutePatternParameterPart parameter, String inlineText)
   at Microsoft.AspNetCore.Routing.ParameterPolicyFactory.Create(RoutePatternParameterPart parameter, RoutePatternParameterPolicyReference reference)
   at Microsoft.AspNetCore.Routing.Matching.DfaMatcherBuilder.DfaBuilderWorker.AddParentsWithMatchingLiteralConstraints(List`1 nextParents, DfaNode parent, RoutePatternParameterPart parameterPart, IReadOnlyList`1 parameterPolicyReferences)
   at Microsoft.AspNetCore.Routing.Matching.DfaMatcherBuilder.DfaBuilderWorker.ProcessSegment(RouteEndpoint endpoint, List`1 parents, List`1 nextParents, RoutePatternPathSegment segment)
   at Microsoft.AspNetCore.Routing.Matching.DfaMatcherBuilder.DfaBuilderWorker.ProcessLevel(Int32 depth)
   at Microsoft.AspNetCore.Routing.Matching.DfaMatcherBuilder.BuildDfaTree(Boolean includeLabel)
   at Microsoft.AspNetCore.Routing.Matching.DfaMatcherBuilder.Build()
   at Microsoft.AspNetCore.Routing.Matching.DataSourceDependentMatcher.CreateMatcher(IReadOnlyList`1 endpoints)
   at Microsoft.AspNetCore.Routing.DataSourceDependentCache`1.Initialize()
   at System.Threading.LazyInitializer.EnsureInitializedCore[T](T& target, Boolean& initialized, Object& syncLock, Func`1 valueFactory)
   at System.Threading.LazyInitializer.EnsureInitialized[T](T& target, Boolean& initialized, Object& syncLock, Func`1 valueFactory)
   at Microsoft.AspNetCore.Routing.Matching.DataSourceDependentMatcher..ctor(EndpointDataSource dataSource, Lifetime lifetime, Func`1 matcherBuilderFactory)
   at Microsoft.AspNetCore.Routing.Matching.DfaMatcherFactory.CreateMatcher(EndpointDataSource dataSource)
   at Microsoft.AspNetCore.Routing.EndpointRoutingMiddleware.InitializeCoreAsync()
--- End of stack trace from previous location ---
   at Microsoft.AspNetCore.Routing.EndpointRoutingMiddleware.<Invoke>g__AwaitMatcher|8_0(EndpointRoutingMiddleware middleware, HttpContext httpContext, Task`1 matcherTask)
   at Microsoft.AspNetCore.Diagnostics.DeveloperExceptionPageMiddleware.Invoke(HttpContext context)

A: If you are using params in your controller something like this:
[HttpGet("update/{id:string}")] then remove :string.
change it to [HttpGet("update/{id}")].

A: i solved this issue,
constraint type 'string' has not been registered with the RouteOptions.ConstraintMap, which is a dictionary that maps constraint names to constraint types in the application.
Create a class like this:
public class StringRouteConstraint : IRouteConstraint
{
    public bool Match(HttpContext httpContext, IRouter route, string routeKey, RouteValueDictionary values, RouteDirection routeDirection)
    {
        object value;
        if (values.TryGetValue(routeKey, out value) && value is string)
        {
            // Validate the value of the route parameter here and return true if it is valid
            return true;
        }

        return false;
    }
}

after that, go in to ur program.cs and paste this,
   services.Configure<RouteOptions>(options =>
    {
        options.ConstraintMap.Add("string", typeof(StringRouteConstraint));
    });

And your problem should go away :) ,  i named my controller method,
[HttpGet("[action]/{id:string}")]


text:
Q: Mockito mock() and recording of invocation I'm using Mockito in order to do some mocks/testing. My scenario is simple : I have a class mocked using mock() and I'm invoking this class (indirectly) for a large number of times (i.e. ~100k)
Mockito seems to hold some data for every invocation, and so I run out of memory at a certain point.
I'd like to tell mockito not to hold any data (I don't intend to call verify(), etc, I just don't care, for this specific tests, what reaches to that mock). I don't want to create new mocks with every invocation.

A: You can use Mockito.reset(mock), just be aware that after you call it, your mock will forget all stubbing as well as all interactions, so you would need to set it up again. Mockito's documentation on the method has these usage instructions:
List mock = mock(List.class);
when(mock.size()).thenReturn(10);
mock.add(1);

reset(mock);
//at this point the mock forgot any interactions & stubbing

They do also discourage use of this method, like the comments on your question do. Usually it means you could refactor your test to be more focused:

Instead of reset() please consider writing simple, small and focused test methods over lengthy, over-specified tests. First potential code smell is reset() in the middle of the test method. This probably means you're testing too much. Follow the whisper of your test methods: "Please keep us small & focused on single behavior". There are several threads about it on mockito mailing list.


text:
Q: Why Dojo grid.refresh is making another server call? We are using dojo JsonRest. Whenever we need to refresh the grid with new data, dojo is firing two server calls.
Below is the code.
var MyJsonRest = declare(JsonRest, {
   get: function(id, options) {
       return this.inherited(
           arguments,
           [id, lang.mixin(this.headers, options)]);
   }
});

myDataStore = MyJsonRest({
    target: someurl,
   headers: {
      'moduleUName': somemodulename
   },
   idAttribute: "id",
       query: function(query, options) {
          // some other code
      }

});

myDataStore.get("", { paramName: paramValue }).then(function(result) { // this fires a request to server
  gridObj.refresh(); // this fires same request 2nd time to the server
  // if the gridObj.refresh() is commented out, then the grid does not displayes the new data.
});

A: In order for the Grid to detect changes in the store without triggering the refresh, you should wrap your JsonRest store with the dojo.store.Observable.  Any updates to the store will then be auto updated in the grid.
myCacheDataStore = new Cache(myDataStore, new Memory({});
myObservableDataStore = new Observable(myCacheDataStore)

You should be able to pass myObservableDataStore in place of myDataStore.
To update or refresh the grid you can change the target url or update the headers in myDataStore directly and call grid.refresh.  I have not tested with the updating of headers, but my example changes the target url from
/rest/users/

to
/rest/users/?username=jdoe

and the grid updates fine.
myDataStore.target = '/rest/users/?username=jdoe'

or maybe
myDataStore.headers[paramName] = paramValue

since your MyJsonRest store mixin the options provided into "get" into the headers as well.

A: This question seems to have a far more straightforward answer than the accepted answer (as evidenced by a comment near the end of it).
You're calling get on your store, then calling grid.refresh() inside the success handler for that call.  Since you're using a server-based store, get is going to fire one request itself.  The grid is going to fire another request (via the store's query method) to get a list of items to populate itself with.
It's unclear from your example if there's another reason why you're initially calling get, but calling store methods directly will not populate widgets like the grid - widgets access the store directly themselves.


text:
Q: Zend Framework dom problem I want to get website shortcut icon(favicon) and stylesheet path with zend_dom query
$dom = new Zend_Dom_Query($html);
$stylesheet = $dom->query('link[rel="stylesheet"]');
$shortcut = $dom->query('link[rel="shortcut icon"]');

Stylesheet query is work but shortcut icon query not work. How i do?
Thanks.

A: This appears to be an issue with Zend's css style query implementation. In Zend/Dom/Query.php, the query function calls a conversion function to convert the query into proper xpath format:
public function query($query)
{
    $xpathQuery = Zend_Dom_Query_Css2Xpath::transform($query);
    return $this->queryXpath($xpathQuery, $query);
}

However within the transform() method, they seem to be using some pretty basic regex to split up the string by spaces:
$segments = preg_split('/\s+/', $path);

Which basically means your link[rel="shortcut icon"] query now becomes two queries: link[rel="shortcut and icon"]
To get around this, you can use the method Zend_Dom_Query::queryXpath() and provide it with a proper xPath query. Like this:
$dom->queryXpath('//link[@rel="shortcut icon"]');


text:
Q: Not showing RSVP buttons in email - ical-generator Not getting RSVP buttons in the email. I'm using "ical-generator" NPM to generate ics file.
This is code to generate ics file
let eventObj = {
    method: 'request',
    start: new Date(startTime),
    end: new Date(endTime),
    summary: "testing meeting",
    uid: uid,
    sequence: 0,
    description: description,
    organizer: {
        name: fullname,
        email: email
    },
    attendees:[
        {
            mailto : 'user@gmail.com',
            email : 'user@gmail.com',
            name : 'john',
            status : 'needs-action',
            rsvp : true,
            type : 'individual'
        }
    ],
    status: 'confirmed'
}
let cal = ical();
cal.domain(url).name('My ical invite');
cal.createEvent(eventObj);

my ics file will look like below
BEGIN:VCALENDAR
VERSION:2.0
PRODID:-//sebbo.net//ical-generator//EN
NAME:My ical invite
X-WR-CALNAME:My ical invite
BEGIN:VEVENT
UID:5f44e98484341386e4523ba1@dominname
SEQUENCE:0
DTSTAMP:20200825T103548Z
DTSTART:20200826T183000Z
DTEND:20200826T190000Z
SUMMARY:testing meeting
DESCRIPTION:meeting Description : testing
ORGANIZER;CN="peter":mailto:user1@gmail.com
ATTENDEE;ROLE=REQ-PARTICIPANT;CUTYPE=INDIVIDUAL;PARTSTAT=NEEDS-ACTION;RSVP
 =TRUE;CN="john";EMAIL=user@gmail.com:MAILTO:user@gmail.com
STATUS:CONFIRMED
END:VEVENT
END:VCALENDAR

in my mail, I'm getting ics like below (I'm using gmail)

Here I'm not getting RSVP buttons and also in my ics file 'METHOD:REQUEST' is missing.
could you please help me out of this
thank you

A: I place 'method' in the wrong place
it should be here
let cal = ical()
cal.method('REQUEST')
cal.domain(url).name('My ical invite')

Now I'm able to get RSVP button on email


text:
Q: subscribing to system blogs I have a 8.0.2SP1 site with a system blog.  The client wants to know what the subscribe button does but I can't find a description in the documentation.  Right now when someone clicks to subscribe, they get an option for all posts or all comments -- that part makes sense but it seems to do nothing. The client is expecting an email if a new post is added.  I can see in the documentation how community blogs work (by default it updates activity feed).  I can find in the  profile settings where you can specify delivery method for Group blogs and Colleague blogs.  But no settings for system blogs.
Q: What does subscribing to a system blog do?
Q: Are there profile-level settings for how the system handles notifications for system blogs?

A: Subscribing to a blog will alert someone when a new post has been made. Subscribing to a specific post will allow the user to be notified if comments have been posted. These settings assume that you have setup an smtp server (relay) in your web.config. Under the hood there's no major differences between a blog you create under a regular folder, or a group/user. For setting the alerts on the root level blogs you should see a "web alerts" tab under the blog's properties


text:
Q: Avoiding Content-Length in HEAD response The Content-Length response header is often expensive to generate for a just HEAD request (e.g. when dealing with dynamically generated resources), but may be essentially "free" after doing the work needed to generate a GET response body.
When it is reasonable to provide a Content-Length (instead of a chunked response) when responding to a GET request, yet unreasonable or slow to calculate the Content-Length for the corresponding HEAD request, is it permissible for the HEAD response to:

*

*Omit the Content-Length header altogether?

*Respond with Transfer-Encoding: chunked even though GET response would have a Content-Length?

The relevant W3C specification indicates that a HEAD request "SHOULD" (not "MUST") respond with identical headers; is the cleanliness and, admittedly often minor, total transfer size savings of using Content-Length in the GET response worth violating the aforementioned "SHOULD" in the case of HEAD, or is the only reasonable choice to have both responses send a Transfer-Encoding: chunked header?

A: Thanks to a tip from @julian-reschke, rfc-7231 indicates that:

The server SHOULD send the same header fields in response to a HEAD request as it would have sent if the request had been a GET, except that the payload header fields (Section 3.3) MAY be omitted.

Per section 3.3 of that same document, the payload header fields consist of:

*

*Content-Length

*Content-Range

*Trailer

*Transfer-Encoding


text:
Q: How to ignore NaN in colorbar? I have a 3d surface, accompanied by a color bar, being generated by
surf = ax.plot_surface(xv, yv, zv, ...)
cb = fig.colorbar(surf)

When it works, it looks like this:

The problem is that some of the values may be NaN, in which case the colorbar fails to generate, like this:

C:\Users\Sam\Anaconda\lib\site-packages\matplotlib\colorbar.py:581: RuntimeWarning: invalid value encountered in greater
  inrange = (ticks > -0.001) & (ticks < 1.001)
C:\Users\Sam\Anaconda\lib\site-packages\matplotlib\colorbar.py:581: RuntimeWarning: invalid value encountered in less
  inrange = (ticks > -0.001) & (ticks < 1.001)
C:\Users\Sam\Anaconda\lib\site-packages\matplotlib\colors.py:576: RuntimeWarning: invalid value encountered in less
  cbook._putmask(xa, xa < 0.0, -1)

I could try to replace the NaN values of zv with 0 (zv[isnan(zv)] = 0), but then the resulting graph has vertical cliffs, which are confusing and obscure some of the features, and it skews the color bar.

What I want is a way for the color bar to ignore NaN values. To do this I could manually set the color bar (to amin(zv[~isnan(zv)]) and amax(zv[~isnan(zv)])) after it is created, but I don't know how to do this.
Any suggestions on how to ignore NaNs when computing the colorbar and when coloring a 3d surface?

A: Set the vmin and vmax parameters in the call to plot_surface. These values affect the minimum and maximum values mapped by the colorbar.
import numpy as np
import matplotlib.pyplot as plt
import mpl_toolkits.mplot3d.axes3d as axes3d

def peaks(x, y):
    return x*np.sin(y)

fig = plt.figure()
ax = fig.add_subplot(1, 1, 1, projection='3d')
X, Y = np.meshgrid(np.linspace(-3, 3, 100), np.linspace(-3, 3, 100))

Z = peaks(X, Y)
Z[X+Y>3] = np.nan

surf = ax.plot_surface(X, Y, Z, alpha=0.3, cmap=plt.cm.jet,
                       vmin=np.nanmin(Z), vmax=np.nanmax(Z))
cbar = plt.colorbar(surf)

plt.show()

A: You should be able to exclude NaN from zv before the surf, like so:
surf = ax.plot_surface(xv, yv, zv[~isnan(zv)], ...)
cb = fig.colorbar(surf)

This should side-step the problem entirely, if I understand it correctly. Of course, I may be confused. Good Luck.


text:
Q: Tool for editing and manipulation JSON? JSON is very popular among social network sites.
I have been searching tools for analyzing JSON and found some good tools for viewing but they do not meet my needs. (like http://jsonviewer.codeplex.com/)
I need to search and filter the data by specific a field and then get some value from another specific field.
Can you suggest a tool or a way to view my JSON data easily?
sample data:
{
  "data": [
    {
      "id": "141816652602643",
      "from": {
        "name": "Deval Agrifarman",
        "id": "896085636"
      },
      "message": "yang belum bisa berhenti ngerokok silahkan dilihat... kalo ga bisa donlot mampir aja ke rumah bawa camilan :D",
      "picture": "http://external.ak.fbcdn.net/safe_image.php?d=AQC3wb7_yd8fdv64&w=130&h=130&url=http\u00253A\u00252F\u00252Fi1.ytimg.com\u00252Fvi\u00252FDiyWK3fzTpA\u00252Fhqdefault.jpg",
      "link": "http://www.youtube.com/watch?v=DiyWK3fzTpA",
      "name": "Sex, Lies & Cigarettes': Vanguard Sneak Peek (Indonesia Subtitle-Full)",
      "description": "Fakta mengenai Industri dan bisnis Rokok diIndonesia, Penetrasi Rokok dalam masyarakat Indonesia.. Dalam Konferensi Dunia untuk Tembakau 2010 Koresponden Chr...",
      "icon": "http://static.ak.fbcdn.net/rsrc.php/v1/yD/r/aS8ecmYRys0.gif",
      "created_time": "2012-01-26T15:03:21+0000"
    },
    {
      "id": "109379672518544",
      "from": {
        "name": "Deval Agrifarman",
        "id": "896085636"
      },
      "message": "kesannya kok kayak aku yang minta ke monyet nya yah wkwkwkwk...",
      "link": "http://www.facebook.com/photo.php?fbid=107424555941677&set=a.101882006495932.4636.100000224005368&type=1",
      "name": "~KeBaB~",
      "icon": "http://static.ak.fbcdn.net/rsrc.php/v1/yD/r/aS8ecmYRys0.gif",
      "created_time": "2012-01-23T15:33:45+0000",
      "comments": {
        "data": [
          {
            "id": "109379672518544_32659",
            "from": {
              "name": "Dhanank Perdhana",
              "id": "1243815675"
            },
            "message": "Deval: \"Mbah, tolong diramal dong garis tangan saya...\"\nMbak Nyemot: \"Hooo.. kamu ini ngga' cocok jadi pejabat.. Nanti kamu pasti pengen cepet2 beli Bentley.. \"\n\n...huehuehue... :P",
            "can_remove": true,
            "created_time": "2012-01-23T15:39:34+0000",
            "likes": 3,
            "user_likes": true
          },
          {
            "id": "109379672518544_32663",
            "from": {
              "name": "Alex Zar",
              "id": "1378608838"
            },
            "message": "klo sodara mmg harus saling berbagi...",
            "can_remove": true,
            "created_time": "2012-01-23T15:42:19+0000"
          },
          {
            "id": "109379672518544_32682",
            "from": {
              "name": "Deval Agrifarman",
              "id": "896085636"
            },
            "message": "Dhanank Perdhana baiklah mbah aku akan jadi pejabat saja... biar punya jaguar... xixixi...\n\nAlex Zar weleh... sodara mu toh? kirain syapa :D xixixi...",
            "message_tags": [
              {
                "id": "1243815675",
                "name": "Dhanank Perdhana",
                "offset": 0,
                "length": 16
              },
              {
                "id": "1378608838",
                "name": "Alex Zar",
                "offset": 92,
                "length": 8
              }
            ],
            "can_remove": true,
            "created_time": "2012-01-23T15:46:13+0000"
          },
          {
            "id": "109379672518544_33010",
            "from": {
              "name": "Ali M. Fauzi",
              "id": "1248947710"
            },
            "message": "\"Seharusnya tangan diatas lebih baik dari tangan dibawah.\" Kira2 klo kondisinya kayak gitu gmn ya? :-) :)",
            "can_remove": true,
            "created_time": "2012-01-23T17:11:03+0000"
          },
          {
            "id": "109379672518544_33012",
            "from": {
              "name": "Ali M. Fauzi",
              "id": "1248947710"
            },
            "message": "\"Seharusnya tangan diatas lebih baik dari tangan dibawah.\" Kira2 klo kondisinya kayak gitu gmn ya? :-) :)",
            "can_remove": true,
            "created_time": "2012-01-23T17:11:17+0000"
          },
          {
            "id": "109379672518544_34880",
            "from": {
              "name": "Deval Agrifarman",
              "id": "896085636"
            },
            "message": "kesannya kayak DPR sekarang... tangannya di atas tapi nyolong dari yang ada di bawah... :D wkwkwkwk...",
            "can_remove": true,
            "created_time": "2012-01-24T03:07:16+0000"
          },
          {
            "id": "109379672518544_35753",
            "from": {
              "name": "Maruko Chan",
              "id": "100001798922313"
            },
            "message": "LOL! iya.. hahaha",
            "can_remove": true,
            "created_time": "2012-01-24T09:14:24+0000"
          },
          {
            "id": "109379672518544_38576",
            "from": {
              "name": "Y.i. Kusumawati",
              "id": "1334087290"
            },
            "message": "sbenernya monyetnya yang mana",
            "can_remove": true,
            "created_time": "2012-01-25T00:01:56+0000"
          },
          {
            "id": "109379672518544_39568",
            "from": {
              "name": "Ali M. Fauzi",
              "id": "1248947710"
            },
            "message": "Nah.... Loh... pertanyaan bagus tuh....",
            "can_remove": true,
            "created_time": "2012-01-25T06:10:11+0000"
          },
          {
            "id": "109379672518544_39665",
            "from": {
              "name": "Ajungo Toriyama",
              "id": "1266357019"
            },
            "message": "Deval Agrifarman : salim dulu....sama kakak.....",
            "message_tags": [
              {
                "id": "896085636",
                "name": "Deval Agrifarman",
                "offset": 0,
                "length": 16
              }
            ],
            "can_remove": true,
            "created_time": "2012-01-25T07:13:39+0000"
          }
        ],
        "paging": {
          "next": "https://graph.facebook.com/109379672518544/comments?limit=25&method=GET&metadata=true&format=json&callback=___GraphExplorerAsyncCallback___&access_token=AAACEdEose0cBAKn8Nfv307rHgjdP9l9usbDj1KbQlzotoQDs6zuQEcxioPm73R3h1ZABBiNQyPG9iukYZAxjnxwmd6ZCNuYdkkKQ7KA4QZDZD&offset=25&__after_id=109379672518544_39665"
        }
      }
    },
    {
      "id": "335701516450154",
      "from": {
        "name": "Deval Agrifarman",
        "id": "896085636"
      },
      "message": "selamat tahun baru lagi yah :D sori nggak sempet bikin kartu ucapan :)",
      "link": "http://www.facebook.com/photo.php?fbid=10150484907061432&set=a.170757796431.134250.152798801431&type=1",
      "name": "Wall Photos",
      "icon": "http://static.ak.fbcdn.net/rsrc.php/v1/yD/r/aS8ecmYRys0.gif",
      "created_time": "2012-01-23T11:36:19+0000"
    }
  ],
  "paging": {
    "previous": "https://graph.facebook.com/896085636/links?limit=3&format=json&since=1327590201&__paging_token=141816652602643&__previous=1",
    "next": "https://graph.facebook.com/896085636/links?limit=3&format=json&until=1327318579&__paging_token=335701516450154"
  }
}

what i need is for example:

*

*getting values of 'link' from 'created_time' in january

*getting values of 'message' and 'picture' plus all 'name' and 'message' inside 'comments' if there are any

A: I mostly use this tool http://codedestine.com/json-editor.html It has feature to add date and its drag and drop UI makes it easy to construct json. It will show you json in object view, then you can select any node and get its data and even can modify it.

A: If Java tools are OK, look at JSONPath, article http://goessner.net/articles/JsonPath/

Data may be interactively found and extracted out of JSON structures on the client without special scripting.

A: There is also JSONselect http://jsonselect.org/#tryit I have found today.
JSONSelect is an experimental selector language for JSON.

It makes it easy to access data in complex JSON documents.

It feels like CSS.

Code on GitHub https://github.com/lloyd/JSONSelect
Last updated    a year ago


text:
Q: Can I change the location of the ImageIcon that I put on a JLabel in my code? I tried using, "label.setBounds(100,100,250,250)" and "label.setLocation(100,100)" but the image does not move from the top and center of the JLabel.
import java.awt.Dimension;
import javax.swing.ImageIcon;
import javax.swing.JFrame;
import javax.swing.JLabel;
import javax.swing.JPanel;

public class Machine extends JPanel
{
    public Machine()
    {
         ImageIcon imageIcon = new ImageIcon("res/robot.png");
         JLabel label = new JLabel(imageIcon);
         add(label);
    }

     public static void main(String[] args)
     {
         JFrame frame = new JFrame();
         frame.add(new Machine());
         frame.setVisible(true);
         frame.setSize(new Dimension(1080, 720));
     }
}

A: What are you trying to do?
The default layout of a JPanel is a FlowLayout with center alignment and the label is displayed at its preferred size. So the label is displayed in the center.
You have a couple of options:

*

*Change the alignment of the FlowLayout to be either LEFT or RIGHT

*Don't add the label to the panel. Just add it directly to the frame which uses a BorderLayout.
Then you can do something like:
 label.setHorizontalAlignment(JLabel.LEFT);
 label.setVerticalAlignment(JLabel.CENTER);

Edit:

was just trying to get the image to be in the middle of the frame

Then post your actual requirement when you ask a question. We don't know what "can I change the location" means to you.
So you would either use the BorderLayout and adjust the horizontal/vertical alignment as already demonstrated.
Or, you could set the layout manager of the frame to be a GridBagLayout and then add the label directly to the frame and use:
frame.add(label, new GridBagConstraints());

Now the label will move dynamically as the frame is resized.

A: If you want to place an image in a certain location, perhaps best is to draw it directly in your JPanel in a paintComponent method override, using one of Graphics drawImage(...) methods, one that allows placement of the image.
import java.awt.Dimension;
import java.awt.Graphics;
import java.awt.image.BufferedImage;
import java.io.IOException;
import java.net.URL;

import javax.imageio.ImageIO;
import javax.swing.*;

@SuppressWarnings("serial")
public class Machine extends JPanel {
    private static final String IMG_PATH = "https://upload.wikimedia.org/wikipedia/commons/"
            + "thumb/f/f2/Abraham_Lincoln_O-55%2C_1861-crop.jpg/"
            + "250px-Abraham_Lincoln_O-55%2C_1861-crop.jpg";
    private BufferedImage img;
    private int x;
    private int y;

    public Machine() {
        setPreferredSize(new Dimension(1080, 720));
        x = 100; // or wherever you want to draw the image
        y = 100;

        try {
            URL imgUrl = new URL(IMG_PATH);
            img = ImageIO.read(imgUrl);
        } catch (IOException e) {
            e.printStackTrace();
            System.exit(-1);
        }
    }

    @Override
    protected void paintComponent(Graphics g) {
        super.paintComponent(g);
        if (img != null) {
            g.drawImage(img, x, y, this);
        }
    }

    public static void main(String[] args) {
        SwingUtilities.invokeLater(() -> {
            JFrame frame = new JFrame();
            frame.setDefaultCloseOperation(JFrame.EXIT_ON_CLOSE);
            frame.add(new Machine());
            frame.pack();
            frame.setLocationRelativeTo(null);
            frame.setVisible(true);
        });
    }
}

Version 2: MouseListener / MouseMotionListener so that the image can be moved
import java.awt.Dimension;
import java.awt.Graphics;
import java.awt.Point;
import java.awt.Rectangle;
import java.awt.event.MouseAdapter;
import java.awt.event.MouseEvent;
import java.awt.image.BufferedImage;
import java.io.IOException;
import java.net.URL;

import javax.imageio.ImageIO;
import javax.swing.*;

@SuppressWarnings("serial")
public class Machine extends JPanel {
    private static final String IMG_PATH = "https://upload.wikimedia.org/"
            + "wikipedia/commons/thumb/f/f2/"
            + "Abraham_Lincoln_O-55%2C_1861-crop.jpg/"
            + "250px-Abraham_Lincoln_O-55%2C_1861-crop.jpg";
    private BufferedImage img;
    private int x;
    private int y;

    public Machine() {
        setPreferredSize(new Dimension(1080, 720));
        x = 100; // or wherever you want to draw the image
        y = 100;

        MyMouse mouse = new MyMouse();
        addMouseListener(mouse);
        addMouseMotionListener(mouse);

        try {
            URL imgUrl = new URL(IMG_PATH);
            img = ImageIO.read(imgUrl);
        } catch (IOException e) {
            e.printStackTrace();
            System.exit(-1);
        }
    }

    @Override
    protected void paintComponent(Graphics g) {
        super.paintComponent(g);
        if (img != null) {
            g.drawImage(img, x, y, this);
        }
    }

    private class MyMouse extends MouseAdapter {
        private Point offset;

        @Override
        public void mousePressed(MouseEvent e) {
            // check if left mouse button pushed
            if (e.getButton() != MouseEvent.BUTTON1) {
                return;
            }

            // get bounds of the image and see if mouse press within bounds
            Rectangle r = new Rectangle(x, y, img.getWidth(), img.getHeight());
            if (r.contains(e.getPoint())) {
                // set the offset of the mouse from the left upper
                // edge of the image
                offset = new Point(e.getX() - x, e.getY() - y);
            }
        }

        @Override
        public void mouseDragged(MouseEvent e) {
            if (offset != null) {
                moveImg(e);
            }
        }

        @Override
        public void mouseReleased(MouseEvent e) {
            if (offset != null) {
                moveImg(e);
            }
            offset = null;
        }

        private void moveImg(MouseEvent e) {
            x = e.getX() - offset.x;
            y = e.getY() - offset.y;
            repaint();
        }
    }

    public static void main(String[] args) {
        SwingUtilities.invokeLater(() -> {
            JFrame frame = new JFrame();
            frame.setDefaultCloseOperation(JFrame.EXIT_ON_CLOSE);
            frame.add(new Machine());
            frame.pack();
            frame.setLocationRelativeTo(null);
            frame.setVisible(true);
        });
    }
}


text:
Q: Drop top row of dataframe and make the second row variable names I have list clean_data_2009 containing 12 monthly data frames named wireless_YY_mmm each, where YY represents year 2009 abbreviated as 09 and mmm abbreviates the calendar months.
I want to drop the first row in each of the 12 dataframes, and then convert the first row to variables name row.  The command below works, but I want to write a loop instead.
clean_data_2009$wireless_jan_09 <- clean_data_2009$wireless_jan_09[-1,] %>% row_to_names(row_number = 1)

I have written the loop command to print the text that R should accept to manipulate the data frames using paste command, but R tries to read the paste command and thus gives me an error.  I try to fix it with the get command, but still run into the error shown below -

month <- c("jan", "feb", "mar", "april", "may", "june", "july", "aug", "sep", "oct", "nov", "dec")
year <- c("09") # "2010", "2011"
list_dt <- c("clean_data_2009$wireless")
rows2del <- c("[-1, ]")

for (y in year) {
  for (m in month) {

    print(paste(y,m,sep = "_") )
    print(paste(list_dt,m,y,sep = "_"))
    print(paste(paste(list_dt,m,y,sep = "_"),rows2del, sep=""))

    get(paste(list_dt,m,y,sep = "_")) <- get(paste(paste(list_dt,m,y,sep = "_"),rows2del, sep="")) %>% row_to_names(row_number = 1)
  }
}

Error:
[1] "09_jan"
[1] "clean_data_2009$wireless_jan_09"
[1] "clean_data_2009$wireless_jan_09[-1, ]"
Error in get(paste(paste(list_dt, m, y, sep = "_"), rows2del, sep = "")) :
  object 'clean_data_2009$wireless_jan_09[-1, ]' not found

A: This alternative approach might help. If you already have your frames in a list, you can just loop through them, and using indexing to drop the first row, and set the names in a single setNames() call for each frame
lapply(clean_data_2009, \(d) setNames(d[-1,],d[1,]))


text:
Q: Mysql two select statements into one mark differences with column value OK I have two select statements
What i want to do is do this in one select statement with
where im.alias_title =(in_image_alias_title OR a.user_id = user_id)AND a.approved = in_album_approved AND a.visible = in_album_visible;
I need to identify between the two results sets- is there a way to create another column value on the query for say it is a users album or it is an album that belongs to an image. An image can have multiple albums. Or it best to keep seperate
/* Select all albums associated with an image */
SELECT a.alias_title, a.title, a.hits, a.created_on, a.updated_on, a.updated_by
FROM album a
INNER JOIN album_image ai ON a.id = ai.album_id
INNER JOIN image im ON ai.image_id = im.id
WHERE im.alias_title =in_image_alias_title AND a.approved = in_album_approved AND a.visible = in_album_visible;

/* Select a users albums */
SELECT a.alias_title, a.title, a.hits, a.created_on, a.updated_on, a.updated_by
FROM album a
INNER JOIN album_image ai ON a.id = ai.album_id
INNER JOIN image im ON ai.image_id = im.id
WHERE a.approved = in_album_approved AND a.visible = in_album_visible AND a.user_id = user_id;

A: You can specify the filter criteria as you describe and use the result of boolean expressions to indicate which of the original query/queries the record was in:
SELECT a.alias_title, a.title, a.hits, a.created_on, a.updated_on, a.updated_by,
       im.alias_title = in_image_alias_title AS q1,  -- was included in 1st query
       a.user_id      = user_id              AS q2   -- was included in 2nd query
FROM   album       a
  JOIN album_image ai ON a.id        = ai.album_id
  JOIN image       im ON ai.image_id = im.id
WHERE  (im.alias_title = in_image_alias_title OR a.user_id = user_id)
   AND a.approved = in_album_approved
   AND a.visible  = in_album_visible


text:
Q: How much should a unit test know about the function it is testing? I'm writing a test for a caching mechanism. The mechanism has two cache layers, the request cache and redis. The request cache uses Flask.g, an object that stores values for the duration of the request. It does this by creating a dictionary, on the Flask.g._cache attribute.
However, I think that the exact attribute is an implementation detail that my unit test shouldn't care about. I want to make sure it stores its values on Flask.g, but I don't care about how it does that. What would be a good way to test this?
I'm using the Python mock module, so I know I can mock out `Flask.g, but I'm not sure if there's a way to test whether there has been any property access on it, without caring about which property it is.
Is this even the right approach for tests like this?

A: Personally you shouldn't be mocking Flask.g if you are testing endpoints. since you would be creating a self.app (I may be unsure about this portion)
Secondly you will need to mock the redis client with something like this being the returned structure.
class RedisTestCase(object):
    saved_dictionary = {}
    def keys(self, pattern):
        found_keys = []
        for key in RedisTestCase.saved_dictionary: #loop keys for pattern
            if pattern:
                found_keys.append(key)
        return found_keys

    def delete(self, keys):
        for key in keys:
            if key in RedisTestCase.saved_dictionary:
                del RedisTestCase.saved_dictionary[key]

    def mset(self, items):
        RedisTestCase.saved_dictionary.update(items)

    def pipeline(self):
        return RedisTestCase()


text:
Q: phone number verification using parse server , swift and Twilio Im trying to use phone number verification in my app. During sign up the user will be asked for their phone number and be sent a verification code and they will enter the code and if it matches they can proceed. I have the cloud code ready but I'm not sure how exactly to call this from the app. Any help would be appreciated
What I want to be able to do is when they enter their phone number and press continue, first check that the phone number is a valid phone number, then send the sms code. finally segue to a verification view where they enter the code, if it doesn't match display an alert, if it does, log the user in
Cloud code:
// Require and initialize the Twilio module with your credentials
var twilio = require("twilio")("twilioAccountSid","twilioAuthToken");

Parse.Cloud.define("sendVerificationCode", function(request, response) {
    var verificationCode = Math.floor(Math.random()*999999);
    var user = Parse.User.current();
    user.set("phoneVerificationCode", verificationCode);
    user.save();

    twilio.sendSms({
        from: '+14123854839',
        To: request.params.phoneNumber,
        Body: "Your verification code is " + verificationCode + "."
    }, function(err, responseData) {
        if (err) {
          response.error(err);
        } else {
          response.success("Success");
        }
    });
});

Parse.Cloud.define("verifyPhoneNumber", function(request, response) {
    var user = Parse.User.current();
    var verificationCode = user.get("phoneVerificationCode");
    if (verificationCode == request.params.phoneVerificationCode) {
        user.set("phoneNumber", request.params.phoneNumber);
        user.save();
        response.success("Success");
    } else {
        response.error("Invalid verification code.");
    }
});

swift code send code :
  @IBAction func send(_ sender: Any) {

        PFCloud.callFunction(inBackground: "sendVerificationCode", withParameters:  ["phoneNumber" : phoneNumber], block: { (results, error) in
            if error == nil {
                let aVC = self.storyboard?.instantiateViewController(withIdentifier: "VerificationCode") as! VerificationCode
                self.present(aVC, animated: true, completion: nil)
                print("sent")
            } else {
                print ("\(error!.localizedDescription)")
            }
        })

    }


text:
Q: Projecting $facet output to an object I created an aggregation ending with a facet operation, producing the following result:
[
    {
        "all": [
            {
                "all": 6948
            }
        ],
        "none": [
            {
                "none": 207
            }
        ]
    }
]

What I need is an output like below:
{
    all: 6948,
    none: 207
}

I tried some $projections but couldn't get rid of the arrays outside and inside of the result. Is this possible with $project or should I try something else?

A: try this code
db.collection.aggregate([
  {
    $unwind: "$all"
  },
  {
    $unwind: "$none"
  },
  {
    $project: {
      _id: 0,
      all: "$all.all",
      none: "$none.none"
    }
  }
])

check in mongo playground

A: Try this:
{
    $project: {
      all: {
        $arrayElemAt: [
          "$all",
          0
        ]
      },
      none: {
        $arrayElemAt: [
          "$none",
          0
        ]
      }
    }
  },
  {
    $project: {
      all: "$all.all",
      none: "$none.none"
    }
  }

A: Use project stage after facet as
{$project:{
   all:{$arrayElemAt:["$all.all",0]},
   none:{$arrayElemAt:["$none.none",0]},
}}


text:
Q: error: deleteItem function is not defined in my script I wrote a to do list in javascript but this code dose not work and show a deleteItem() is not defined error. I test it in codepen and it works correctly.
window.onload = function () {
let ourForm = document.getElementById("ourform");
let ourField = document.getElementById("todo");
let ourList = document.getElementById("list");

ourForm.addEventListener("submit", e => {
    e.preventDefault();
    createItem(ourField.value);
});

function createItem(x) {
    let ourHtml = `<li>${x}<button onclick="deleteItem(this)">Delete</button></li>`;
    ourList.insertAdjacentHTML("beforeend", ourHtml);
    ourField.value = "";
    ourField.focus();
}

function deleteItem(elementToDelete) {
    elementToDelete.parentElement.remove();
}

}

NEED-TO-DO APP

<form id="ourform">
    <input id="todo" type="text" autocomplete="off">
    <button>Create Item</button>
</form>

Need To Do

whats wrong with my script ..

A: Try copying the deleteItem function outside window.onload function as the scope is not accessible right now.
  window.onload = function () {
    let ourForm = document.getElementById("ourform");
    let ourField = document.getElementById("todo");
    let ourList = document.getElementById("list");

    ourForm.addEventListener("submit", e => {
      e.preventDefault();
      createItem(ourField.value);
    });

    function createItem(x) {
      let ourHtml = `<li>${x}<button onclick="deleteItem(this)">Delete</button></li>`;
      ourList.insertAdjacentHTML("beforeend", ourHtml);
      ourField.value = "";
      ourField.focus();
    }

  }
  function deleteItem(elementToDelete) {
    elementToDelete.parentElement.remove();
  }

A: Your code is correct
you can delete this line given under below
window.onload = function () {

then you code will work perfect
thank you


text:
Q: Refresh to Car Position Correct Way Unity I created car game. I have 3 checkpoint. Car refresh when I press R key
but car wrong position.
My Code;
Checkpoint.js;
#pragma strict

var SpawnPoint : Transform;

function OnTriggerEnter(col: Collider)
{
    if(col.tag =="Player")
    {
        SpawnPoint.position = Vector3(transform.position.x, transform.position.y,   transform.position.z);
    }
}

ReSpawn.js;
#pragma strict
var SpawnPoint : Transform;
var player : GameObject;
var target : Transform;

function Update()
{

if(Input.GetKeyDown(KeyCode.R))
    {
        player.transform.position  = SpawnPoint.position;
    }
}

How to force correct position?

A: you should use getcomponent to get a var in another script assign your checkpoint script to var script via inspector.
#pragma strict
var script : Checkpoint;
var player : GameObject;
var target : Transform;

function Update()
{

if(Input.GetKeyDown(KeyCode.R))
    {
        player.transform.position  = script.GetComponent(Checkpoint).SpawnPoint.position;
    }
}


text:
Q: How do i output text to a printer in c++ I am new to programming and seem to be having trouble figuring out how to direct output to a printer.
cout directs to monitor, is there a command to direct to the print queue?
I have a simple console program and am using code blocks for my ide.

A: A problem like this is dependent on your operating system.  Assuming you use windows, you may need to look at the 'Windows API' which may or may not have a method of doing this.  Alternatively, you can output to a text file, then use a script to open the file, run through the print menu, and close the file which is less eloquent but will work.


text:
Q: Promises and Async/Await don't seem to do anything in Express/node I'm learning node and express and I'm trying to implement a function that retrieves data from a csv file uploaded by the user.
The data should be processed first and then outputted to the console, but it instead outputs an empty array before processing it.
I followed examples of async/await from tutorials I found online but the issue persists and I'm not sure how to proceed.
app.on("event:file_uploaded", async(userDataPath)=>{
    let result = await retrieveDataFromCsvFile(userDataPath);
    console.log(result); //should be completed after retrieving data
});

function retrieveDataFromCsvFile(path){
    return new Promise((resolve)=>{
        console.log(`RETRIEVING DATA FROM: ${path}`);
        const stream = fs.createReadStream(path);
        const rl = readline.createInterface({input: stream});
        let data = [];
        rl.on("line", (row)=>{
            data.push(row.split(","));
        })
        rl.on("close", ()=>{
            console.log("Data Processed"); //should be completed first
        })
        resolve(data);

    })
}

Outputs:
RETRIEVING DATA FROM: <filepath>
[]
Data Processed

A: You need to call resolve when you have the data you want.
At the moment you are:

*

*Registering a line event handler

*Registering a close event handler

*Calling resolve
Some time later you will get line and close events that trigger their respective event handler functions … but by then you've already resolved the promise.
You need to determine what condition means your data is ready. At a guess, I'd expect that to be "When the callback to close is run" and call resolve then.

A: As you can see your console logs are in the wrong order so that should tell you that the promise is resolved first and the file is processed later.
You should change the close event to
    rl.on("close", ()=>{
        console.log("Data Processed"); //should be completed first
    resolve(data);
    })

this would ensure that your promise is resolved after the function is done processing the file.


text:
Q: высота grid элементов по высоте контента самого элемента Есть верстка элементов на grid. Мне необходимо высоту каждого элемента grid подогнать под размер его контента, но я уже все перепробовал. Т.е. что бы все блоки grid были прижаты друг к другу. У меня это пока не получается сделать. Подскажите пожалуйста, как эти можно сделать. Спасибо.

.internet_connectedhouses_content_blocks_symbolhouses {
  display: grid;
  grid-template-columns: repeat(2, 1fr);
  grid-template-rows: repeat(10, auto);
  grid-auto-flow: column;
  grid-row-gap: 30px;
  grid-column-gap: 50px;
}

.internet_connectedhouses_content_blocks_symbolhouses_block {
  display: grid;
  grid-gap: 10px;
  height: fit-content;
  height: -moz-fit-content;
  height: -webkit-fit-content;
}

.internet_connectedhouses_content_blocks_symbolhouses_block p:first-child {
  font-style: normal;
  font-weight: bold;
  font-size: 24px;
  line-height: 31px;
  color: #000000;
}

.internet_connectedhouses_content_blocks_symbolhouses_block p:not(:first-child) {
  font-style: normal;
  font-weight: normal;
  font-size: 16px;
  line-height: 21px;
  color: #000000;
}

А

Автозаводская, ул.: 1, 2, 3, 4, 4/1, 4/3, 4/2, 5

Агрогородок, ул.: 4а, 7, 18, 19, 20, 32, 100, 101, 102

Адмирала Горшкова, ул.: 7, 11, 15, 17, 19

Адмирала Кузнецова, ул.: 1, 2, 3, 4, 5, 6, 7

Адмирала Макарова, ул.: 8

Адмирала Нахимова, ул.: 2, 3, 4, 5, 6, 7, 8, 10, 11, 12, 14, 15, 16, 17

Аллейная, ул.: 7

Андрея Белого, ул.: 2, 3, 4, 5, 6, 8

Б

Береговая, ул.: 1, 2, 3, 4, 5, 6, 7, 8, 8б, 69

Брагина, ул.: 1, 3, 5

Г

Героев, просп.: 1, 2, 3, 4, 5, 6, 7, 8, 9, 10

Гидрогородок, ул.: Б, В, А, 3а, 4, 9

Главная, ул.: 1, 2, 3, 4, 5, 7/1, 7, 9, 11/1, 11, 12, 15, 15а, 20, 22/1, 22, 24, 26, 32/23

Граничная, ул.: 5, 7, 9/1, 9, 10, 10а, 11, 11/1, 12, 14, 16, 18, 20, 22, 24, 28, 30, 32, 34, 36а, 36, 38а, 38, 40, 42

Д

Детская, ул.: 9, 11/3, 11/2, 11/1, 11

Ж

Железнодорожный, пр-д.: 29

Жилгородок, ул.: 1, 2, 4к1, 5а, 6, 7а, 9а, 41, 52, 54, 55, 63

Жуковского, просп.: 1, 2, 3, 4/1, 4, 5, 7, 9, 11, 13

З

Заводская, ул.: 4, 6, 10, 12, 14, 18, 29, 33, 39, 41а, 43, 45

Западная, ул.: 2, 21

И

Интернациональная, ул.: 20, 22, 23

К

Калинина, ул.: 1, 2а, 3, 5, 6, 7, 8, 10, 12, 14, 16, 18, 20, 22, 24

Керамическая, ул.: 13, 15, 20, 23/1, 24, 28, 30, 32, 66

Колхозная, ул.: 1, 2, 3, 4, 5, 6, 7, 8, 11, 12/1, 12/2, 12/3

Комсомольский, пр-д.: 2

Красный Текстильщик, ул.: 2

Л

Ленина, ул.: 1/5, 2, 4а, 5, 6б, 6, 6а

Лесные Поляны, ул.: 3, 4, 5, 6, 19

Лесопарковая, ул.: 2, 3, 4, 11, 12, 16, 17, 18

Луговая, ул.: 2, 2/1, 9, 9/2, 12, 14, 16

Ляхова, ул.: 3, 5

М

Маяковского, ул.: 1, 2, 4а, 4, 5, 5/1, 5/2, 9/1, 9, 11, 12, 13, 14а, 14, 18, 19, 20, 21, 22, 24, 26, 28, 30, 36, 42

Морская, ул.: 1, 2, 3

Московская, ул.: 1, 3, 5/1, 5/2, 8, 10

Н

Некрасова, ул.: 3а, 4, 5, 6а, 6, 7, 8, 10, 13, 15

Новая, ул.: 5, 6б, 7, 9, 9а, 11, 13, 15, 18, 18а, 20, 20б, 20а, 22а, 23, 24, 27, 28, 29, 30, 31, 32, 33, 36, 37, 38, 39, 40, 41, 42, 43, 49

Носовихинское, ш.: 1, 2, 3, 4, 5, 6, 7, 8, 9, 10, 11, 12, 13к1, 13, 15, 21, 22

О

Октябрьская, ул.: 1, 3, 5, 7, 9, 11, 13, 15, 17, 19, 21, 23, 25, 25/3, 25/1, 25/2, 27, 29, 31, 33, 35

П

Павлино, мкр.: 1, 2, 3, 4, 5, 6, 10, 11, 12, 14, 15, 15/1, 16, 17, 18/1, 18, 19, 20, 21, 22, 25, 26, 27, 34, 36, 37, 38, 39а, 39, 67, 69

Пионерская, ул.: 1, 2, 3, 4, 5/1, 5/2, 5, 6, 7а, 7, 8, 9а, 9, 10, 11, 12а, 12, 12б, 14, 14б, 15, 17, 18а, 19/2, 19/1, 19, 21, 23, 25, 26, 27, 29, 31, 33

Поликахина, ул.: 1, 3, 5

Почтовая, ул.: А, 2а, 2/1, 3, 4, 4/1, 5/1, 6а, 7, 8, 10

Пролетарская, ул.: 1/2к2, 1/2к1, 2/2, 2/1, 2, 3, 4, 5а, 5, 7, 8, 10, 12, 27, 47, 49, 50

Пушкина, ул.: 2, 4, 6, 6б, 8, 10, 12

Пушкинская, ул.: 30, 49

Р

Рождественская, ул.: 4, 5, 6, 7, 8, 10

С

Саввинская, ул.: 1/1, 2а, 3, 5а, 9б, 10, 12, 13, 17, 17а, 17б

Саввинское, ш.: 2, 4/2, 4/1, 4, 6, 10, 13, 15, 17, 19, 21, 23, 23а

Свободы, ул.: 1а, 1, 2, 3, 5, 7а, 8/1, 8, 9а

Смельчак, ул.: 3, 5, 7, 8, 9, 10, 12

Советская, ул.: 2, 4, 5, 6, 8, 10, 14, 16, 18, 20, 22, 26, 28, 34, 40, 42, 46, 57, 59, 61

Соловьева, ул.: 1, 2, 3, 4, 5/1, 5

Спасский, бул.: 4, 6

Струве, ул.: 3/1, 3, 5, 7, 7/1, 9, 9/1

Т

Транспортная, ул.: 2, 3а, 4, 6, 6а, 19

Троицкая, ул.: 1, 2, 3, 4, 5

Ц

Центральная, ул.: 1, 4, 6, 8, 10, 26, 35, 40, 41, 43, 45, 47, 68/1

Ч

Чаплыгина, ул.: 1, 3, 5, 7

Ш

Шестая, ул.: 3, 5, 7, 11, 13, 15, 17

Школьная, ул.: 2, 3/1, 4, 5

Ю

Юбилейная, ул.: 1а, 1, 2/1, 2, 2/2, 3, 4а, 4/3, 4/1, 4/5, 4/4, 4, 5, 6/1, 6, 7а, 7, 8, 8/2, 8/1, 9, 11/3, 11/2, 11/1, 12, 13, 14, 16, 18, 18/1, 20, 20/1, 22/1, 22

Южная, ул.: 3, 5, 7

Южное Кучино, мкр.: 1, 2, 3, 5, 6, 7

A: Судя по тому, что видно в инспекторе, высота ячейки и так занимает ровно столько, сколько занимает контент. Есть два нюанса: у вас задан grid-gap, который добавляет расстояние между ячейками; параграфы имеют стандартный margin, что также раздвигает ячейку - добавление стиля p { margin: 0 } решает проблему.


text:
Q: Bash Shell Scripting: what simple logic am I missing This may be too generic a question as is but...
I am stumped by trying to move through the directories from within a shell script. I'm not a *nix power user, but I am comfortable working through the command line for most tasks. I'd like to call a script that can move 'me' to a directory instead of just the script process similar to the following:
prompt:> goto lit

where  goto is an alias -> goto='./goscript'
and
goscript has some simple code in such as:
cd /path to work dirs/lit/user dir

(assuming each user has a directory inside /lit)
I've avoided this issue myself by setting my personal alias' to move to the desired directory, run a script, then return to the original directory. This question was brought to me by a co-worker who uses a similar method, but wanted to make the process more generic so we don't need to create every single alias we need.
I thought this would be an easy problem to solve, but I'm stumped as I don't really have a great deal of shell scripting experience ...as of yet.

A: Even better than using an alias as others have described, check out the CDPATH variable!  It's basically equivalent of the PATH functionality, but applied to the cd command.
For example, if I define my CDPATH as $CDPATH:${HOME}/subdir, and ~/subdir contains another directory, subsubdir, then I can simply execute:
cd subsubdir

from any directory, and navigate the the path as expected.
Here's some more specifics:
http://www.caliban.org/bash/#bashtips
To set the CDPATH variable, add a line to your .bashrc, such as
export CDPATH=$CDPATH:${HOME}/subdir

A: You can create a function that is called goto (or whatever) and make sure it is defined in your .bashrc (or you can "source" it from your current shell):
function goto {
    #  the "$USER" part will expand to the current username
    # the "$1" will expand to the first argument to the function ("goto xyz" => $1 is "xyz")
    cd /some-path/lit/$USER/$1
}

Put this in ~/.bashrc or in a separate file and call "source the-file" from your prompt then you can call the function just like any other program:
prompt> goto folder
 cd /some-path/lit/your-user/folder

A: To execute a script in the same environment of your prompt you have to invoke it with .
Say you have the script named up:
cd ..

if you invoke it with . you get:
$> pwd
$> /home/users/rd/proj
$> . up
$> pwd
$> /home/users/rd

A: You can't.  The script has its own copy of the environment, and so it can't change the login shell's environment.

A: I wasn't a member when I asked this (ironically my anonymous login question has higher flair than my official login questions combined), so I can't close it now - But- The Remo D. et al. answer would be the one that led to the working solution we needed. If anyone with mod powers can close this & select that as the accepted answer, i'd apprediate it.

A: You can't use cd in a bash script. You could alias the cd and path though.
alias goto='cd /path_to_work/usr/dir'

UPDATE: you would put that line in your .bashrc file and then do
source ~/.bashrc

to create the alias.

A: You can accomplish some simple stuff like this using an alias.  For example, I have some aliases that put me into a workspace environment and configure variables for our Makefile system.  Here's a real alias I am using as an example.  The '&&' will continue executing the commands until one of them fails--in simple scenarios like this, no clean-up is needed, since failure isn't likely.
alias main1='cd ~/code/main1 && export TOP=`pwd` && export DEBUG=1'

If you want to develop a shared library of aliases amongst your co-workers, you can share them over NFS and source the file to be included.

A: Each script has its own idea of the current working directory. "cd" is not a process but a shell build-in.
The way to do what you want is to create an alias. In csh it will be something like:
alias goto 'cd /path_to_work/\!*/user_dir'

sh/bash have similar alias facilities

A: I tend to have a couple dozen aliases in my .rc that look like this:
alias work='cd /home/foo/work'
alias rails='cd /home/foo/rails'
alias assets='cd /home/foo/rails/assets'

etc.
If that isn't going to work for you, you might be able to use the debug hooks in bash to replace the command line in-place before it is executed - if the 'goto' keyword is the first thing on the line.  This will involve googling around for 'trap' in bash, but be forewarned, such incantations do not behave the same on all systems.  I wrote up one such experience a few months ago, and you're welcome to the results.


text:
Q: SOQL: Is it possible to order result based on Child field I want to build a query to order result based on Child field like this:
select id, name, other_field, (select id, name, other_field from Child__r) from Parent order by Child__r.name

But, I am getting an error message. I've searched Salesforce documentations, but did not find anything.
Edit: ERROR message added below:

INVALID_FIELD:  order by Child__r.name ^ ERROR at Row:1:Column:254
Didn't understand relationship 'Child__r' in field path. If you are
attempting to use a custom relationship, be sure to append the '__r'
after the custom relationship name. Please reference your WSDL or the
describe call for the appropriate names.

A: You can query the child object instead and pull in the parent fields using a Right Inner Join:
SELECT Id, Name, SomeField__c, Parent__c, Parent__r.Name, Parent__r.OtherField__c
FROM Child__c ORDER BY Name

But no, you cannot sort the parent records by child values, due to the nature of a many-to-one relationship. If you have one parent with children Alice and David, and another with children Bob and Charlie, you need a way to determine which would come first. With number fields you might order by Max, Min, Avg, etc. But that doesn't make sense with text fields.


text:
Q: How to pass CSV data as a string in a web method? I am trying to pass in a string representation of CSV data into a web method and then re-read into a CSV.
I do not know how to properly split the data for each row. It works if I have one line in my CSV, but if I have multiple rows it reads it all as one line.
Is there a way to convert my string back to a CSV? I know that each row should have a fixed amount of records if that helps.
Edit: Can CsvReader interpret new line returns like \r\n?
Edit 2: The web method is accessed via an API.
Sample CSV

A, B, C, D
E, F, G, H

This is being read by csvReader as A, B, C, D E, F, G, H as one row.

Web Method
public string Import(string csvData)
{
   //Other code

   byte[] byteArray = Encoding.UTF8.GetBytes(csvData);
   MemoryStream csvMemoryStream = new MemoryStream(byteArray);
   StreamReader csvStreamReader = new StreamReader(csvMemoryStream);

   //Pass in the StreamReader to my other function
   return ImportData(csvStreamReader);
}

Import Function
public static string ImportData(StreamReader reader)
{
   using (var csvReader = new CsvReader(reader))
   {
      csvReader.Configuration.HasHeaderRecord = false;
      csvReader.Configuration.DetectColumnCountChanges = true;

      while (csvReader.Read())
      {
         //Other code
      }
}

A: You just need to read line by line instead of grabbing all the text.
using(StreamReader reader = new StreamReader("C:/path/filename.csv")
{
    string currentline;
    while( currentline = reader.ReadLine() != null)
    {
        //Do something with currentline
    }
}


text:
Q: MySQL keyring component (not plugin) not loading on server startup Problem:

*

*There is no indication mysqld is actually reading the server manifest and/or the keyring component configuration file. Any help would be greatly appreciated.

System Info:

*

*Ubuntu 20.04

*MySQL 8.0.29

Details:

*

*All files are in the default locations where "sudo apt-get install mysql-server" puts them.

*mysql-server package came from Ubuntu repos.

What I've tried:

*

*Per the MySQL docs, I created "a global manifest file named mysqld.my in the mysqld installation directory", and tried placing it in the following locations without success:
(NOTE: Owner:group:perms == root:mysql:640)

*

*/usr ('basedir' location)

*/usr/sbin/ (mysqld binary location) [file is currently here]

*/var/lib/mysql ('datadir' location) [ASIDE: If I were using a global and a local manifest, the local manifest goes here according to the mysql docs.]

*/usr/lib/mysql/plugin/ ('plugin_dir' location)

*Per the MySQL docs, I created "a global configuration file named component_keyring_file.cnf in the directory where the component_keyring_file library file is installed" in the following location:
(NOTE: Owner:group:perms == root:mysql:640)

*

*/usr/lib/mysql/plugin/ ('plugin_dir' location. File 'component_keyring_file.so' does exist here.)

*I used the following test with an initial condition that mysqld was not running:

*

*Place the global manifest in one of the folders listed.

*Start mysqld. ("sudo service mysql start")

*Verify mysqld started. ("sudo service mysql status")

*Check keyring component status: mysql -v -v -v -uREDACTED -pREDACTED -e "SELECT * FROM performance_schema.keyring_component_status;"

*Stop mysqld. ("sudo service mysql stop")

*Verify mysqld stopped. ("sudo service mysql status")

*Repeat at step #1 for next file location.

In all cases the SELECT query returned "Empty set".

*Finally, I tried changing the permissions on the global manifest to 660 in the hope that I would see a warning in the MySQL error.log, but there is still nothing in the error.log that indicates the keyring component loaded before InnoDB is initialized.
(Reason: The MySQL docs stated "server access to a manifest file
should be read only. For example, a mysqld.my server manifest file
may be owned by root and be read/write to root, but should be read
only to the account used to run the MySQL server. If the manifest
file is found during startup to be read/write to that account, the
server writes a warning to the error log suggesting that the file be
made read only.")
End Result: I'm running out of ideas, and I'm hoping one of you can point me in the right direction.
Other info:

*

*I'm aware there is plenty of info on how to configure the keyring plugin, but apparently the component is newer and offers more features/flexibility which is why I was attempting to use it.

*If it helps, here's where I started from on the MySQL docs: https://dev.mysql.com/doc/refman/8.0/en/innodb-data-encryption.html#innodb-data-encryption-about

A: Looks like you've been through the documentation very thoroughly. It looks to me like it should be working.
Things you might check:

*

*Is the plugin directory configured? What is the output of show variables like 'plugin_dir';

*Are you using AppArmor? Run sudo aa-status. If you are, and mysql is in one of the enforce profiles then you can either put it into a complain profile (sudo aa-complain /usr/sbin/mysqld) or use the mysql profile in appArmor, e.g. cat /etc/apparmor.d/usr.sbin.mysqld | sudo apparmor_parser -a. Note that you might need to update the profile with your specific paths for the encryption keyring file.
Let me know how you get on.

A: I have exactly the same problem that you described here. I am using Ubuntu 22.04 and mysql 8.031. I went through the exact same steps that you did with the component keyring file and the query "SELECT * FROM performance_schema.keyring_component_status;" returns "Empty set". Let me know if anyone has updates on this.


text:
Q: Browse disk usage of git staging area I want to version control my home directory in git.
I've used ncdu to find the largest sub-directories and from there built a .gitignore which I hope excludes the largest and most useless parts of my home directory (eg .gem/, .cache/, .cabal/, tmp/).
After doing a git add $HOME, how can I browse the index / cache / staging area with respect to disk usage?
Ideally, I'm after something interactive like ncdu where I can drill down into sub-directories.

A: Stash data store in git-dir.
Default the git store data in folder .git (git-dir).

The latest stash you created is stored in refs/stash; older stashes
  are found in the reflog of this reference and can be named using the
  usual reflog syntax (e.g. stash@{0} is the most recently created
  stash, stash@{1} is the one before it, stash@{2.hours.ago} is also
  possible).

A: The size of the index itself won't be relevant, since I detail in "What does the git index contain EXACTLY?":

The state is "virtual" in the sense that it does not necessarily have to, and often does not, match the files in the working tree.

What you can do is... make a commit (you can always git reset @~ to cancel the commit and redo it later)
Then, as mentioned in "git find fat commit":
git diff-tree -r -c -M -C --no-commit-id @     # get new blobs for HEAD commit
git cat-file --batch-check << blob ids         # get size of each blob

That will use git cat-file bach output to print information about them, including objectsize:disk.
If no format is specified, the default format is %(objectname) %(objecttype) %(objectsize).


text:
Q: Accessing documentDB on host in docker contains
*

*I have an docker ASP.Net core webapi in a docker container running.

*I Have on the Host machine installed the local documentDB emulator

So when I try to use http://localhost:8081 to access the emulator, it won't work. I think that is "correct" because localhost is not the host system. So what I want is to access the http://localhost:8081 from the parent host.
I tried to use the ip from the parent host and the hostname from the parent host with the same error that the host / emulator cannot be reached, but I can ping the host from the container.
The emulator is up and running and I Disabled all firewalls (in the host).
My dockerfile (very basic):
FROM microsoft/aspnetcore:1.0.1
ARG source
WORKDIR /app
EXPOSE 80
COPY ${source:-bin/Release/PublishOutput} .
ENTRYPOINT ["dotnet", "Portal.UserProfile.dll"]

So what do I wrong? Or is it possible to run documentDb emulator in a docker host?


text:
Q: Where is workflow task info stored? I have looked through dozens of table information and schema info but I can't find the "Workflow Task Detail" table and the connections to the "Rules Using This Task".
I'm trying to add a trigger which will modify a date based on the "Unique Name" naming convention my client uses.

Thank you.

A: The object you would be looking for is the ActionTask object (key prefix 01V). Unfortunately, you cannot query this table, because it is not exposed in any API, nor can you directly modify these items, because it requires the metadata API. As a workaround, you could use a formula field to determine which date to set. Unfortunately, this is the best that you can do under the current situation with the API.


text:
Q: Cant Get Proper Output To This Program I'm trying to print numbers if they are not divisible by three or five and if they are divisible by three or five they should not be printed.
This is my code:
i = int(input())
if (i == i/3) | (i == i/5):
    print('this number is divisible by 3 or 5')
else:
    print('i')

Im new to stackoverflow does not the properly how it works!!!!:(

A: If i = 5, then your if statement becomes
if (5 == 5/3) or (5 == 1):
    # do stuff

You're looking for the modulus %, which gives you the remainder of a division. Change the if statement to
if (i % 3 == 0) or (i % 5 == 0):

and it should work. For i = 5 this will give
if (2 == 0) or (0 == 0):
    # do stuff


text:
Q: Is it possible to create a column in Microsoft SQL Server that limits what can be added to column? For example, I want to specify that an 'Email' column must contain an @ symbol in order to be valid. Is it possible to do this?

A: You do this using a check constraint:
alter table t add constraint chk_t_email check (email like '%@%' and email is not null);

Of course, this is just an illustration.  An email has many other rules as well.  However, more comprehensive validation could be asked in another question.


text:
Q: Tour view does not have React internal Fiber I want implementation app-tour in my project , I installed react-native-app-tour  .I have a View that I want assign app-tour to it and I use ref in view that it dispatch AppTourView to inputreducer and finally in useEffect I run appTour but when I run app I encountered Error that error is Tour view does not have React internal Fiber, please can help me
import React, {
  useState,
  useEffect,
  useCallback,
  useReducer,
  useRef,
} from 'react';
import {AppTour, AppTourSequence, AppTourView} from 'react-native-app-tour';

const inputReducer = (state, action) => {
  if (action.type == 'SET_APPTOUR') {
    return [...state.appTour, action.data];
  }
};
export default function HomeScreen(props) {
const [forsat, setForSat] = useState(null);
  const [appTourTargets, dispatchAppTour] = useReducer(inputReducer, {
    appTour: [],
  });
 useEffect(() => {

    setTimeout(() => {
      console.log(appTourTargets);
      let appTourSequence = new AppTourSequence();
      appTourTargets.appTour.forEach(appTourTarget => {
        appTourSequence.add(appTourTarget);
      });
      AppTour.ShowSequence(appTourSequence);
    }, 1000);
  }, [appTourTargets]);

return(
<view style={styles.container}>
             <View
        ref={useCallback(ref => {
          if (!ref) return;

          setForSat(ref);
          let prop = {
            order: 12,
            title: 'This is a target View',
            description: 'We have the best targets, believe me',
            outerCircleColor: '#3f52ae',
            cancelable: false,
          };
          dispatchAppTour({type:'SET_APPTOUR', data:AppTourView.for(ref, {...prop})});
        }, [])}
        style={styles.rankContainer}>
        <BText font="_Light" size={15} color={color.firstColor}>
          فرصت{' '}
          <BText font="_Bold" color={color.secondColor} size={15}>
            {FormatHelper.toPersianString(daysToGo.toString())}
          </BText>{' '}
          روز تا کنکور
        </BText>
      </View>

     </view>
   )
}


text:
Q: List of US government free GIS data online The US government publishes a plethora of useful, high-quality GIS data sources online.
The data includes:

*

*Municipal and international boundaries

*Classified points of interest

*Geographic maps

*Climate charts

*Air transportation maps

*...and so much more, in the US and outside it.

Unfortunately, the data is located in dozens of different web sites, each belonging to a separate agency. This community wiki aims to list all the known official US data sources available on the web.
Answers should probably include:

*

*Site name & link

*Agency name and description

*Coverage (US \ International)

*Short description of available data

*Update date (if applicable\relevant)

*Comments about quality or experience with the data

*One data source per answer

A:
Tiger - the US Census Bureau GIS data. Covers the US only.

*

*Municipal and state boundaries

*Cartographic maps

*Street maps

From my personal experience, the data is comprehensive, accurate and well-formed.
Last update - 2011.

A: The National Map
This is sponsored by the USGS.

*

*Topographic Map Products

*Transportation

*Hydrography

*Land Cover

A:
USGS Earth Explorer
Products available for download include:

*

*Aerial Photography

*AVHRR

*Cal/Val Reference Sites

*Commercial

*Declassified Data

*Digital Elevation

*DLGs

*EO-1

*Forest Carbon Sites

*Global Fiducials

*Global Land Surveys

*HCMM

*JECAM Sites

*Land Cover

*Landsat Archive

*Landsat Legacy

*Landsat MRLC

*NASA LPDAAC Collections

*Orbview-3

*Radar

*Vegetation Monitoring

A:
The National Geophysical Data Center (NGDC) of the National Oceanic and Atmospheric Administration (NOAA) provides data, products and services relating to several disciplines of geophysical science:

*

*Bathymetry & Global Relief

*Earth Observations from Space

*Geomagnetic Data & Models

*Marine Geology & Geophysics

*Natural Hazards

*Space Weather & Solar Events

A:
The National GAP Analysis Program ecological data from USGS:

*

*National Land Cover Dataset (NLCD)

*

*Ecological Systems based on NatureServe classifications

*Protected Areas Dataset (Federal, State, Local, NGO, Tribal lands) Highly Recommended

*Species geographic range

*Species distribution models (ongoing)

A:
Data.gov, the US government's open data warehouse, whose self-described purpose is to "increase public access to high value, machine readable datasets generated by the Executive Branch of the Federal Government" is celebrating its 3rd year of service.
The main area of the website contains some spatially-enabled data as well as links to external datasets, some of which are shapefiles or links to other websites.
There is also a Geodata Catalog which houses spatial data exclusively.
Types of data available are various and range from records of visitors to the White House to realtime earthquake data, TIGER data, elevation data, and more (like, a LOT more, 440,000+ datasets).

A:
The National Geospatial-Intelligence Agency offers an impressive POI list called "Complete Files of Geographic Names for Geopolitical Areas", which seems to comprehensively cover every spot of the world.
I had a brief, but good, experience with the POI list of Isreal.
The data is updated as to 18 July 2002.

A:
A plug for my own agency!  USFWS provides National datasets (including WMS in many cases) for the following:

*

*Critical Habitat (as mandated by the Endangered Species Act)

*National Wetlands Inventory

*Project locations and Focus areas for Partners for Fish and Wildlife & Coastal Programs (ECOS)

*Cadastral data (and refuge road system) for the National Wildlife Refuge System

*Coastal Barrier Resources Systems (determines Fed funding / flood insurance)

*Landscape Conservation Cooperatives (Large scale eco-units for conservation developed by FWS & USGS)

*Migratory Bird Conservation dataset


text:
Q: Java Regular Expression check I have the code as
  String s = "The loading is completed, TB62 is bound for Chongqing, and trains 11-13 are expected";

    boolean matcher = Pattern.matches(".*11-13.*", s);
    System.out.println(matcher);

I am only checking for string containing 11-13 and above workds but if the regular expression is
.*1-13.*

that also works for the above string. How do I change regular expression that it will won't match .*1-13.* but only .*11-13.* should match
Updating and adding more info so people can answer
I have two regular expressions
.*11-13.*
.*1-1.*

But the issue is even
.*1-1.*  also matches to the string

String s = "The loading is completed, TB62 is bound for Chongqing, and trains 11-13 are expected";

It should not match because I want to regular expression .*11-13.* to match only. I think I need to modify regular expression

A: For that use word boundary \b:
Pattern.matches(".*\\b11-13\\b.*", s);

Take a look at the javadoc of Pattern.
For instance if you could have line breaks in the text, either use DOT_ALL (dot is also newline) with compile, or simply use find instead of match.

A: Instead of Pattern#matches, which matches the whole string, you can use Matcher#find as shown below:
import java.util.regex.MatchResult;
import java.util.regex.Matcher;
import java.util.regex.Pattern;

class Main {
    public static void main(String[] args) {
        String s = "The loading is completed, TB62 is bound for Chongqing, and trains 11-13 are expected";
        Matcher matcher = Pattern.compile("\\b11-13\\b").matcher(s);
        while (matcher.find()) {
            System.out.println(matcher.group());
        }

        // Alternatively
        Pattern.compile("11-13").matcher(s).results().map(MatchResult::group).forEach(System.out::println);
    }
}

Output:
11-13
11-13

Note: \b is a boundary matcher. If you need a regex for any pair of hyphen-separeted integers consisting of two digits, you can use \b\d{2}-\d{2}\b as the regex.


text:
Q: mongodb avoid inconsistencies Given the following scenario:
Collection Products with a document Product(id, owner), and a document p1(1, "bob")

*

*Request1:  read p1

*Request2:  read p1

*Request2:  update p1 name="karen" (if owner was "bob" during previous read)

*Request1:  update p1 name="laura" (if owner was "bob" during previous read)

Both updates will succeed, correct? And the result will be "laura" as far as I understand MongoDB. However, can I simply resolve this by adding a where clause name="bob" because the changes are in one document, or do I need more advanced features such as transactions? Or is this only for multi document updates?

A:
Both updates will succeed, correct?

Yes.
Assuming that the update method is like this: db.collection.updateOne( { id: 1 }, { owner: name } ), where the id is a unique product id field and the "name" value is either "laura" or "karen" depending upon the request. Both updates will succeed.
But, the final result could be "laura" or "karen". You don't know which update will reach the database first. So, there is no guarantee that what will be the value of owner in the document, after the update.
Note that read and update are two separate operations (as in CRUD). Having read a document doesn't mean a request owns the document in any way. The documentation says "In MongoDB, an operation on a single document is atomic"; this applies to update operations too.

And the result will be "laura" as far as I understand MongoDB.

May be.
Unless somehow you are controlling the order in which the updates are happening in the database, there is no guarantee what  the final result will be.

However, can I simply resolve this by adding a where clause name="bob"
  because the changes are in one document, or do I need more advanced
  features such as transactions? Or is this only for multi document
  updates?

Adding a where clause like this db.collection.updateOne( { id: 1, owner: "bob"}, { owner: name } ) will make sure that only one update operation will take place. Again, which update happens is not guaranteed.

Transactions?

Transactions can be used with replica-sets (MongoDB version 4.0+) and shard clusters (MongoDB version 4.2+) only; not available with standalone MongoDB installations.
Does your application with the above scenario require a transaction? No. The update is a single operation and MongoDB guarantees it as an atomic operation. Generally, transactions are useful when there are multiple CRUD operations to be performed as a single unit (e.g., an invoice generation may create an invoice document and update the inventory and accounts collections - all operations happen as a unit or not happen at all).


text:
Q: How to get the screen position of `QMainWindow` and print it? I'm trying to get the screen position of QMainWindow and print the position (x,y) values. I have tried both self.pos() and self.mapToGlobal(self.pos()) and both of these return 0.
import sys
from PyQt5.QtWidgets import QApplication, QMainWindow

class MainWindow(QMainWindow):

    def __init__(self):
        QMainWindow.__init__(self)
        self.resize(400, 200)

        # PRINTS 0 0
        print(self.pos().x(), self.pos().y())

        # PRINTS 0 0
        print(self.mapToGlobal(self.pos()).x(), self.mapToGlobal(self.pos()).y())

app = QApplication(sys.argv)
window = MainWindow()
window.show()
sys.exit(app.exec_())

I'm using Python 3.7 and PyQt 5.11, how can I achieve this?

A: The position of a widget is with respect to the parent if it has it, and if it does not have it is with respect to the screen, so in the case of MainWindow, since it is a window, pos() should be used, if it were a widget that has a parent you must use self.mapToGlobal(QtCore.QPoint(0, 0)) since it is the top-left position.
On the other hand the initial position of every widget is QPoint(0, 0), and if it is a window the OS manipulates its position and moves it, so you get the value of (0, 0), so in your case you must track the change of position, for example using moveEvent:
import sys
from PyQt5 import QtCore, QtWidgets

class MainWindow(QtWidgets.QMainWindow):
    def __init__(self):
        super(MainWindow, self).__init__()
        self.resize(400, 200)

    def moveEvent(self, e):
        print(self.pos())
        super(MainWindow, self).moveEvent(e)

if __name__ == '__main__':
    app = QtWidgets.QApplication(sys.argv)
    window = MainWindow()
    window.show()
    sys.exit(app.exec_())

A: I'll add the link http://doc.qt.io/qt-5/application-windows.html#window-geometry and an example:
import sys
from PyQt5.QtWidgets import (QApplication, QMainWindow, QWidget,
                             QVBoxLayout, QTextEdit, QPushButton)

class MainWindow(QMainWindow):

    def __init__(self):
        QMainWindow.__init__(self)
        self.resize(400, 200)

        centralWidget = QWidget()
        self.setCentralWidget(centralWidget)

        self.textEdit = QTextEdit()
        self.btn = QPushButton("get the screen position of `QMainWindow`")
        self.btn.clicked.connect(self.btnClicked)

        layoutV = QVBoxLayout(centralWidget)
        layoutV.addWidget(self.textEdit)
        layoutV.addWidget(self.btn)

        self.textEdit.append("Start:")
        self.textEdit.append("pos.x=`{}`, pos.y=`{}`"
                             "".format(self.pos().x(), self.pos().y()))
        self.textEdit.append("geometry.x=`{}`, geometry.y=`{}`"
                             "".format(self.geometry().x(), self.geometry().y()))
        self.textEdit.append("--------------------------------------")

    def btnClicked(self):
        self.textEdit.append("pos.x=`{}`, pos.y=`{}`"
                             "".format(self.pos().x(), self.pos().y()))
        self.textEdit.append("geometry.x=`{}`, geometry.y=`{}`"
                             "".format(self.geometry().x(), self.geometry().y()))

    def moveEvent(self, event):    # QMoveEvent
        print("x=`{}`, y=`{}`".format(event.pos().x(), event.pos().y()))
        super(MainWindow, self).moveEvent(event)

    def resizeEvent(self, event):  # QResizeEvent
        print("w=`{}`, h=`{}`".format(event.size().width(), event.size().height()))
        super(MainWindow, self).resizeEvent(event)

app = QApplication(sys.argv)
window = MainWindow()
window.show()
sys.exit(app.exec_())

A: I thought I'd chime in as I've been working on the same thing.  Storing and restoring the window position between sessions.  Here's what worked for me with python 2.717 and  Qute 1.3.2
from Qt import QtWidgets
from Qt import QtCore

class MainUI(QtWidgets.QMainWindow):
    def __init__(self):
        self.installEventFilter(self)
        self._nLastEvent = None

    def resizeEvent(self, event):
        super(MainWindow, self).resizeEvent(event)
        s = self.size()
        print(s.width())
        print(s.height())

    def eventFilter(self, obj, event):
        if self._nLastEvent == QtCore.QEvent.Move and event.type() == QtCore.QEvent.WindowActivate:
            pos = self.pos()
            print(pos.x())
            print(pos.y())
        self._nLastEvent = event.type()
        return super(MainUI, self).eventFilter(obj, event)