text:
Q: Acumatica Generic Inquiry Adding to Inquiries Menu (Automation Steps) Adding GIs to the report menu is easy enough but in this Technical Tuesday post Doug describes some additional steps that need to be followed with customization in order to add a GI to the INQUIRIES menu:

Anybody have any luck following his steps? I kept getting lots of validation errors with the code he shared and would appreciate a better explanation.
After the customization step, we just have to add it to the Automation Step.

A: Please use below customization code until we fix the issues with the Technical Tuesday post.
using System;
using System.Collections;
using PX.Data;
using PX.Objects.PO;

namespace PXDemoPkg
{
    public class POOrderEntry_Extension : PXGraphExtension<POOrderEntry>
    {

        public PXAction<POOrder> inquiry;

        [PXUIField(DisplayName = "Inquiries", MapEnableRights = PXCacheRights.Select)]
        [PXButton]
        protected virtual IEnumerable Inquiry(PXAdapter adapter,
            [PXInt] [PXIntList(new int[] { 1, 2, 3 },
                               new string[] { "Vendor Details", "Activities", "PO Prepayments" })] int? inquiryID)
        {
            if (inquiryID == 3)
            {
                POOrder order = Base.Document.Current;

                string giURL = PXGenericInqGrph.INQUIRY_URL;
                string gIName = "POprepayments";
                string sParameter1Name = "POnumber";
                string sParameter1Value = order.OrderNbr;

                string url = String.Format("{0}?Name={1}&{2}={3}", giURL, gIName, sParameter1Name, sParameter1Value);

                throw new PXRedirectToUrlException(url, PXBaseRedirectException.WindowMode.New, true, "POprepayments-GI");
            }
            else
                return Base.inquiry.Press(adapter);
        }
    }

}


text:
Q: Get all results from Google Place API I am using PHP curl to get Google Place API result. I am using below code for this :
$curl = curl_init();
curl_setopt_array($curl, array(
       CURLOPT_RETURNTRANSFER => 1,
       CURLOPT_URL => 'https://maps.googleapis.com/maps/api/place/textsearch/json?query=CITY&type=atm&next_page_token=40&key=KEY'
));
$resp = curl_exec($curl);
curl_close($curl);

From above request i got only 20 results but i want all result. To get all result i used "next_page_token" parameter like below :
https://maps.googleapis.com/maps/api/place/textsearch/json?query=CITY&type=atm&next_page_token=20&key=KEY

Above URL return only next 20 record but not all. So finally i have only 40 record but still i am not able to get all record.
Can anyone please help me out what should i do with url.

redpajama_set_name: RedPajamaStackExchange


text:
Q: Spring boot : Async request not returning anything Js :
$('#loaderImage').show();

$http.get('/utilities/longProcess')
    .success(function(data, status, headers, config) {
        console.log('Completed');
        $scope.sampleJSON = data.pmdStructureWrapper;
        $scope.sampleJSONDuplicates = data.pmdDuplicates;
        $scope.$watch('sampleJSON', setTimeout(function() {
            $('.panel-body li').each(function() {
                if ($.trim($(this).text()) === "") {
                    $(this).hide();
                }
            });
        }, 1000));
        $('#loaderImage').hide();
    })
    .error(function(data, status, header, config) {

    });

Controller :
@RequestMapping("/utilities/longProcess")
    public DeferredResult<String> async(HttpServletResponse response, HttpServletRequest request) {
        DeferredResult<String> dr = new DeferredResult<>();
        CompletableFuture.supplyAsync(() -> {
            return callURL(response, request);
        }, ex).thenAccept((String message) -> {
            dr.setResult(message);
        });
        return dr;
    }

private String callURL(HttpServletResponse response, HttpServletRequest request){
    PMDMainWrapper pmdMainWrapper = new PMDMainWrapper();
    Map<String, PMDStructureWrapper> codeReviewByClass = new HashMap<>();
    String partnerURL = this.partnerURL;
    String toolingURL = this.toolingURL;
    Cookie[] cookies = request.getCookies();
    List<PMDStructure> violationStructure = null;
    try {
        violationStructure = metadataLoginUtil.startReviewer(partnerURL, toolingURL, cookies);
    } catch (Exception e) {
        e.printStackTrace();
    }

    PMDStructureWrapper pmdStructureWrapper = null;
    List<PMDStructure> pmdStructureList = null;
    List<PMDStructure> pmdDuplicatesList = new ArrayList<>();
    int size = violationStructure.size();

    long start = System.currentTimeMillis();
    for (int i = 0; i < size; i++) {
        if (codeReviewByClass.containsKey(violationStructure.get(i).getName())) {
            PMDStructureWrapper pmdStructureWrapper1 = codeReviewByClass.get(violationStructure.get(i).getName());
            List<PMDStructure> pmdStructures = pmdStructureWrapper1.getPmdStructures();
            pmdStructures.add(violationStructure.get(i));
            pmdStructureWrapper1.setPmdStructures(pmdStructures);

        } else {
            pmdStructureList = new ArrayList<>();
            pmdStructureList.add(violationStructure.get(i));
            pmdStructureWrapper = new PMDStructureWrapper();
            pmdStructureWrapper.setPmdStructures(pmdStructureList);
            codeReviewByClass.put(violationStructure.get(i).getName(), pmdStructureWrapper);
        }
    }

    long stop = System.currentTimeMillis();

    LOGGER.info("Total Time Taken from PMDController "+  String.valueOf(stop-start));
    if (!codeReviewByClass.isEmpty()) {
        pmdMainWrapper.setPmdStructureWrapper(codeReviewByClass);
        pmdMainWrapper.setPmdDuplicates(pmdDuplicatesList);
        Gson gson = new GsonBuilder().create();
        return gson.toJson(pmdMainWrapper);
    }

    return "";
}

I am going with async process because when the app is hosted in heroku, it takes almost 120 seconds to return the result to the page, but as per heroku documentation the rest api should return within 30 seconds otherwise it terminates the process,
But still after implementing the above logic I am seeing the timeout error.
I have kept a console log in the javascript console.log('Completed'); but that gets printed only when it returns the result from callURL method which is taking more than 120 seconds to return.
What i wanted to implement is when the UI sends a request, it should keep receiving a message which says still loading, so that the request does not gets timeedout?

A: CompletableFuture.supplyAsync() runs the specified supplier in a different thread (one from the ForkJoinThreadPool for default). thenAccept() method only runs after the previous execution returns. So, it won't return fast in your case, you're just calling the long running call in a different thread.
Instead, define a common object, which acts as a cache (such as HttpSession), and make the CompletableFuture return the object stored there. And execute callURL()only when the cache is empty:
@RequestMapping("/utilities/longProcess")
public CompletableFuture<String> async(HttpServletResponse response, HttpServletRequest request) {
    HttpSession session = request.getSession();
    return CompletableFuture.supplyAsync(() -> session.getAttribute("CACHED_RESULT"))
            .thenComposeAsync(obj -> {
                if (obj == null) {
                    CompletableFuture.supplyAsync(() -> callUrl(request, response))
                            .thenAccept(result -> session.setAttribute("CACHED_RESULT", result));
                    return CompletableFuture.completedFuture("not ready yet");
                }
                return CompletableFuture.completedFuture(obj.toString());
            });

You can also add a timestamp to see when you did the last call to callUrl() and don't call callUrl() again when you've made a call but not received the answer yet.


text:
Q: ios - swift - read MDM config from UserDefaults I am trying to read the mdm config from UserDefaults but it keeps crashing.
The code is pretty straight forward:
 let defaults = UserDefaults.standard;
 let serverConfig = defaults.dictionary(forKey: Settings.SETTING_MANAGED_KCONFIGURATIONURL);

Whereas SETTING_MANAGED_KCONFIGURATIONURL is set to: "com.apple.configuration.managed"
Its crashing on the second line.
I am also using the UserDefaults.didChangeNotification Observer.
Here is my crashlog:
Exception Subtype: KERN_PROTECTION_FAILURE at 0x000000016f097e78
VM Region Info: 0x16f097e78 is in 0x16f094000-0x16f098000;  bytes after start: 15992  bytes before end: 391
      REGION TYPE                      START - END             [ VSIZE] PRT/MAX SHRMOD  REGION DETAIL
      MALLOC_TINY            0000000115800000-0000000115900000 [ 1024K] rw-/rwx SM=PRV
      GAP OF 0x59794000 BYTES
--->  STACK GUARD            000000016f094000-000000016f098000 [   16K] ---/rwx SM=NUL  ... for thread 0
      Stack                  000000016f098000-000000016f194000 [ 1008K] rw-/rwx SM=PRV  thread 0

Termination Signal: Segmentation fault: 11
Termination Reason: Namespace SIGNAL, Code 0xb
Terminating Process: exc handler [560]
Triggered by Thread:  0

Thread 0 name:  Dispatch queue: com.apple.main-thread
Thread 0 Crashed:
0   CoreFoundation                  0x00000001926ffee8 __CFStringAppendBytes + 188
1   CoreFoundation                  0x00000001926f2528 __CFStringAppendFormatCore + 10180
2   CoreFoundation                  0x00000001926f2528 __CFStringAppendFormatCore + 10180
3   CoreFoundation                  0x00000001926f35bc _CFStringCreateWithFormatAndArgumentsAux2 + 136
4   CoreFoundation                  0x00000001926f3664 CFStringCreateWithFormat + 44
5   CoreFoundation                  0x00000001926c047c -[CFPrefsSearchListSource copyOSLogDescription] + 116
6   CoreFoundation                  0x0000000192630eb8 -[CFPrefsSearchListSource alreadylocked_copyValueForKey:] + 260
7   CoreFoundation                  0x0000000192630d90 -[CFPrefsSource copyValueForKey:] + 60
8   CoreFoundation                  0x000000019277cae8 __76-[_CFXPreferences copyAppValueForKey:identifier:container:configurationURL:]_block_invoke + 40
9   CoreFoundation                  0x00000001926c0c54 __108-[_CFXPreferences+ 617556 (SearchListAdditions) withSearchListForIdentifier:container:cloudConfigurationURL:perform:]_block_invoke + 272
10  CoreFoundation                  0x00000001926c0698 normalizeQuintuplet + 340
11  CoreFoundation                  0x000000019262ed64 -[_CFXPreferences+ 19812 (SearchListAdditions) withSearchListForIdentifier:container:cloudConfigurationURL:perform:] + 108
12  CoreFoundation                  0x000000019262f5f0 -[_CFXPreferences copyAppValueForKey:identifier:container:configurationURL:] + 148
13  CoreFoundation                  0x000000019277ef30 _CFPreferencesCopyAppValueWithContainerAndConfiguration + 124
14  Foundation                      0x000000019309c8fc -[NSUserDefaults+ 26876 (NSUserDefaults) objectForKey:] + 52
15  MYAPP                       0x0000000100cd3bfc MISettingsManager.checkAndReadMDMSettings() + 424956 (MISettingsManager.swift:303)
16  MYAPP                       0x0000000100cda2b0 specialized closure #1 in static MISettingsManager.instance.getter + 451248 (<compiler-generated>:0)
17  MYAPP                       0x0000000100ccdb5c thunk for @escaping @callee_guaranteed (@in_guaranteed Notification) -> () + 400220 (<compiler-generated>:0)
18  Foundation                      0x00000001930c5ef0 -[__NSObserver _doit:] + 316
19  CoreFoundation                  0x00000001926b421c __CFNOTIFICATIONCENTER_IS_CALLING_OUT_TO_AN_OBSERVER__ + 20
20  CoreFoundation                  0x00000001926b41e8 ___CFXRegistrationPost_block_invoke + 64
21  CoreFoundation                  0x00000001926b36dc _CFXRegistrationPost + 392
22  CoreFoundation                  0x00000001926b3388 ___CFXNotificationPost_block_invoke + 96
23  CoreFoundation                  0x000000019262cc54 -[_CFXNotificationRegistrar find:object:observer:enumerator:] + 1496
24  CoreFoundation                  0x00000001926b2e38 _CFXNotificationPost + 696
25  Foundation                      0x000000019309c1a4 -[NSNotificationCenter postNotificationName:object:userInfo:] + 68
26  MYAPP                       0x0000000100cd2b64 MISettingsManager.setValueForSetting(_:_:) + 420708 (<compiler-generated>:0)
27  MYAPP                       0x0000000100cd4900 MISettingsManager.setSettingsValue(key:value:) + 428288 (MISettingsManager.swift:364)
28  MYAPP                       0x0000000100cd5990 MISettingsManager.validateMDMSettings(url:system:user:) + 432528 (MISettingsManager.swift:411)
29  MYAPP                       0x0000000100cd3fc4 MISettingsManager.checkAndReadMDMSettings() + 425924 (<compiler-generated>:0)
30  MYAPP                       0x0000000100cda2b0 specialized closure #1 in static MISettingsManager.instance.getter + 451248 (<compiler-generated>:0)
31  MYAPP                       0x0000000100ccdb5c thunk for @escaping @callee_guaranteed (@in_guaranteed Notification) -> () + 400220 (<compiler-generated>:0)
32  Foundation                      0x00000001930c5ef0 -[__NSObserver _doit:] + 316
33  CoreFoundation                  0x00000001926b421c __CFNOTIFICATIONCENTER_IS_CALLING_OUT_TO_AN_OBSERVER__ + 20
34  CoreFoundation                  0x00000001926b41e8 ___CFXRegistrationPost_block_invoke + 64
35  CoreFoundation                  0x00000001926b36dc _CFXRegistrationPost + 392
36  CoreFoundation                  0x00000001926b3388 ___CFXNotificationPost_block_invoke + 96
37  CoreFoundation                  0x000000019262cc54 -[_CFXNotificationRegistrar find:object:observer:enumerator:] + 1496
38  CoreFoundation                  0x00000001926b2e38 _CFXNotificationPost + 696
39  Foundation                      0x000000019309c1a4 -[NSNotificationCenter postNotificationName:object:userInfo:] + 68
40  MYAPP                       0x0000000100cd2b64 MISettingsManager.setValueForSetting(_:_:) + 420708 (<compiler-generated>:0)
41  MYAPP                       0x0000000100cd4900 MISettingsManager.setSettingsValue(key:value:) + 428288 (MISettingsManager.swift:364)
42  MYAPP                       0x0000000100cd5990 MISettingsManager.validateMDMSettings(url:system:user:) + 432528 (MISettingsManager.swift:411)
43  MYAPP                       0x0000000100cd3fc4 MISettingsManager.checkAndReadMDMSettings() + 425924 (<compiler-generated>:0)
44  MYAPP                       0x0000000100cda2b0 specialized closure #1 in static MISettingsManager.instance.getter + 451248 (<compiler-generated>:0)
45  MYAPP                       0x0000000100ccdb5c thunk for @escaping @callee_guaranteed (@in_guaranteed Notification) -> () + 400220 (<compiler-generated>:0)
46  Foundation                      0x00000001930c5ef0 -[__NSObserver _doit:] + 316
47  CoreFoundation                  0x00000001926b421c __CFNOTIFICATIONCENTER_IS_CALLING_OUT_TO_AN_OBSERVER__ + 20
48  CoreFoundation                  0x00000001926b41e8 ___CFXRegistrationPost_block_invoke + 64
49  CoreFoundation                  0x00000001926b36dc _CFXRegistrationPost + 392
50  CoreFoundation                  0x00000001926b3388 ___CFXNotificationPost_block_invoke + 96
51  CoreFoundation                  0x000000019262cc54 -[_CFXNotificationRegistrar find:object:observer:enumerator:] + 1496
52  CoreFoundation                  0x00000001926b2e38 _CFXNotificationPost + 696
53  Foundation                      0x000000019309c1a4 -[NSNotificationCenter postNotificationName:object:userInfo:] + 68
54  MYAPP                       0x0000000100cd2b64 MISettingsManager.setValueForSetting(_:_:) + 420708 (<compiler-generated>:0)
55  MYAPP                       0x0000000100cd4900 MISettingsManager.setSettingsValue(key:value:) + 428288 (MISettingsManager.swift:364)
56  MYAPP                       0x0000000100cd5990 MISettingsManager.validateMDMSettings(url:system:user:) + 432528 (MISettingsManager.swift:411)
57  MYAPP                       0x0000000100cd3fc4 MISettingsManager.checkAndReadMDMSettings() + 425924 (<compiler-generated>:0)
58  MYAPP                       0x0000000100cda2b0 specialized closure #1 in static MISettingsManager.instance.getter + 451248 (<compiler-generated>:0)
59  MYAPP                       0x0000000100ccdb5c thunk for @escaping @callee_guaranteed (@in_guaranteed Notification) -> () + 400220 (<compiler-generated>:0)
60  Foundation                      0x00000001930c5ef0 -[__NSObserver _doit:] + 316
61  CoreFoundation                  0x00000001926b421c __CFNOTIFICATIONCENTER_IS_CALLING_OUT_TO_AN_OBSERVER__ + 20
62  CoreFoundation                  0x00000001926b41e8 ___CFXRegistrationPost_block_invoke + 64
63  CoreFoundation                  0x00000001926b36dc _CFXRegistrationPost + 392
64  CoreFoundation                  0x00000001926b3388 ___CFXNotificationPost_block_invoke + 96
65  CoreFoundation                  0x000000019262cc54 -[_CFXNotificationRegistrar find:object:observer:enumerator:] + 1496
66  CoreFoundation                  0x00000001926b2e38 _CFXNotificationPost + 696
67  Foundation                      0x000000019309c1a4 -[NSNotificationCenter postNotificationName:object:userInfo:] + 68
68  MYAPP                       0x0000000100cd2b64 MISettingsManager.setValueForSetting(_:_:) + 420708 (<compiler-generated>:0)
69  MYAPP                       0x0000000100cd4900 MISettingsManager.setSettingsValue(key:value:) + 428288 (MISettingsManager.swift:364)
70  MYAPP                       0x0000000100cd5990 MISettingsManager.validateMDMSettings(url:system:user:) + 432528 (MISettingsManager.swift:411)
71  MYAPP                       0x0000000100cd3fc4 MISettingsManager.checkAndReadMDMSettings() + 425924 (<compiler-generated>:0)
72  MYAPP                       0x0000000100cda2b0 specialized closure #1 in static MISettingsManager.instance.getter + 451248 (<compiler-generated>:0)
73  MYAPP                       0x0000000100ccdb5c thunk for @escaping @callee_guaranteed (@in_guaranteed Notification) -> () + 400220 (<compiler-generated>:0)
74  Foundation                      0x00000001930c5ef0 -[__NSObserver _doit:] + 316
75  CoreFoundation                  0x00000001926b421c __CFNOTIFICATIONCENTER_IS_CALLING_OUT_TO_AN_OBSERVER__ + 20
76  CoreFoundation                  0x00000001926b41e8 ___CFXRegistrationPost_block_invoke + 64
77  CoreFoundation                  0x00000001926b36dc _CFXRegistrationPost + 392
78  CoreFoundation                  0x00000001926b3388 ___CFXNotificationPost_block_invoke + 96
79  CoreFoundation                  0x000000019262cc54 -[_CFXNotificationRegistrar find:object:observer:enumerator:] + 1496
80  CoreFoundation                  0x00000001926b2e38 _CFXNotificationPost + 696
81  Foundation                      0x000000019309c1a4 -[NSNotificationCenter postNotificationName:object:userInfo:] + 68
82  MYAPP                       0x0000000100cd2b64 MISettingsManager.setValueForSetting(_:_:) + 420708 (<compiler-generated>:0)
83  MYAPP                       0x0000000100cd4900 MISettingsManager.setSettingsValue(key:value:) + 428288 (MISettingsManager.swift:364)
84  MYAPP                       0x0000000100cd5990 MISettingsManager.validateMDMSettings(url:system:user:) + 432528 (MISettingsManager.swift:411)
85  MYAPP                       0x0000000100cd3fc4 MISettingsManager.checkAndReadMDMSettings() + 425924 (<compiler-generated>:0)
86  MYAPP                       0x0000000100cda2b0 specialized closure #1 in static MISettingsManager.instance.getter + 451248 (<compiler-generated>:0)
87  MYAPP                       0x0000000100ccdb5c thunk for @escaping @callee_guaranteed (@in_guaranteed Notification) -> () + 400220 (<compiler-generated>:0)
88  Foundation                      0x00000001930c5ef0 -[__NSObserver _doit:] + 316
89  CoreFoundation                  0x00000001926b421c __CFNOTIFICATIONCENTER_IS_CALLING_OUT_TO_AN_OBSERVER__ + 20
90  CoreFoundation                  0x00000001926b41e8 ___CFXRegistrationPost_block_invoke + 64
91  CoreFoundation                  0x00000001926b36dc _CFXRegistrationPost + 392
92  CoreFoundation                  0x00000001926b3388 ___CFXNotificationPost_block_invoke + 96
93  CoreFoundation                  0x000000019262cc54 -[_CFXNotificationRegistrar find:object:observer:enumerator:] + 1496
94  CoreFoundation                  0x00000001926b2e38 _CFXNotificationPost + 696
95  Foundation                      0x000000019309c1a4 -[NSNotificationCenter postNotificationName:object:userInfo:] + 68
[...]

Any help would be nice.
Thanks!
[UPDATE]
I changed my code slightly to see what is really returned. It's still crashing but on at a different spot. Which doesn't makes sense since I haven't changed the logic. The first 5 lines are just for testing purpose and can be ignored.
But I also added the PushNotification as mentioned here. Unfortunately there wasn't an explanation on why to add this.
let defaults = UserDefaults.standard;

let server = defaults.object(forKey: Settings.SETTING_MANAGED_KCONFIGURATIONURL);
print("[MISettingsManager] checkAndReadMDMSettings - server: \(server ?? "NULL")");
if let server = server as! [String:Any]? {
   print("[MISettingsManager] readManagedDefaultValues - \(server.description)");
}

let serverConfig = defaults.dictionary(forKey: Settings.SETTING_MANAGED_KCONFIGURATIONURL);
if(nil == serverConfig) {
   return;
}
print("[MISettingsManager] readManagedDefaultValues - \(serverConfig!.description)");

let url: String? = serverConfig![Settings.SETTING_SERVER_SERVICEURL] as? String;
if (!(url ?? "").isEmpty) {
   self.setSettingsValue(key: Settings.SETTING_SERVER_SERVICEURL, value: url);
}

setSettingsValue is written like this. Its also where its crashing. Null value check is done before this.
self.setValueForSetting(key!, value!);

This is the new crashlog:
Exception Type:  EXC_BAD_ACCESS (SIGSEGV)
Exception Subtype: KERN_PROTECTION_FAILURE at 0x000000016eeb3b10
VM Region Info: 0x16eeb3b10 is in 0x16eeb0000-0x16eeb4000;  bytes after start: 15120  bytes before end: 1263
      REGION TYPE                      START - END             [ VSIZE] PRT/MAX SHRMOD  REGION DETAIL
      mapped file            0000000104bf0000-0000000104d48000 [ 1376K] r--/rw- SM=COW
      GAP OF 0x6a168000 BYTES
--->  STACK GUARD            000000016eeb0000-000000016eeb4000 [   16K] ---/rwx SM=NUL  ... for thread 0
      Stack                  000000016eeb4000-000000016efb0000 [ 1008K] rw-/rwx SM=PRV  thread 0

Termination Signal: Segmentation fault: 11
Termination Reason: Namespace SIGNAL, Code 0xb
Terminating Process: exc handler [607]
Triggered by Thread:  0

Thread 0 name:  Dispatch queue: com.apple.main-thread
Thread 0 Crashed:
0   CoreFoundation                  0x00000001927711c4 CFBasicHashCreateCopy + 4
1   CoreFoundation                  0x00000001926a1664 CFDictionaryCreateMutableCopy + 180
2   CoreFoundation                  0x00000001926308a4 -[_CFXNotificationNameWildcardObjectRegistration find:matching:] + 308
3   CoreFoundation                  0x000000019262cbdc -[_CFXNotificationRegistrar find:object:observer:enumerator:] + 1376
4   CoreFoundation                  0x00000001926b2e38 _CFXNotificationPost + 696
5   Foundation                      0x000000019309c1a4 -[NSNotificationCenter postNotificationName:object:userInfo:] + 68
6   MYAPP                       0x0000000100eb693c MISettingsManager.setValueForSetting(_:_:) + 420156 (<compiler-generated>:0)
7   MYAPP                       0x0000000100eb8920 MISettingsManager.setSettingsValue(key:value:) + 428320 (MISettingsManager.swift:375)
8   MYAPP                       0x0000000100eb99b0 MISettingsManager.validateMDMSettings(url:system:user:) + 432560 (MISettingsManager.swift:422)
9   MYAPP                       0x0000000100eb7fe4 MISettingsManager.checkAndReadMDMSettings() + 425956 (<compiler-generated>:0)
10  MYAPP                       0x0000000100ebe2d0 specialized closure #1 in static MISettingsManager.instance.getter + 451280 (<compiler-generated>:0)
11  MYAPP                       0x0000000100eb1b24 thunk for @escaping @callee_guaranteed (@in_guaranteed Notification) -> () + 400164 (<compiler-generated>:0)
12  Foundation                      0x00000001930c5ef0 -[__NSObserver _doit:] + 316
13  CoreFoundation                  0x00000001926b421c __CFNOTIFICATIONCENTER_IS_CALLING_OUT_TO_AN_OBSERVER__ + 20
14  CoreFoundation                  0x00000001926b41e8 ___CFXRegistrationPost_block_invoke + 64
15  CoreFoundation                  0x00000001926b36dc _CFXRegistrationPost + 392
16  CoreFoundation                  0x00000001926b3388 ___CFXNotificationPost_block_invoke + 96
17  CoreFoundation                  0x000000019262cc54 -[_CFXNotificationRegistrar find:object:observer:enumerator:] + 1496
18  CoreFoundation                  0x00000001926b2e38 _CFXNotificationPost + 696
19  Foundation                      0x000000019309c1a4 -[NSNotificationCenter postNotificationName:object:userInfo:] + 68
20  MYAPP                       0x0000000100eb693c MISettingsManager.setValueForSetting(_:_:) + 420156 (<compiler-generated>:0)
21  MYAPP                       0x0000000100eb8920 MISettingsManager.setSettingsValue(key:value:) + 428320 (MISettingsManager.swift:375)
22  MYAPP                       0x0000000100eb99b0 MISettingsManager.validateMDMSettings(url:system:user:) + 432560 (MISettingsManager.swift:422)
23  MYAPP                       0x0000000100eb7fe4 MISettingsManager.checkAndReadMDMSettings() + 425956 (<compiler-generated>:0)
24  MYAPP                       0x0000000100ebe2d0 specialized closure #1 in static MISettingsManager.instance.getter + 451280 (<compiler-generated>:0)
25  MYAPP                       0x0000000100eb1b24 thunk for @escaping @callee_guaranteed (@in_guaranteed Notification) -> () + 400164 (<compiler-generated>:0)
26  Foundation                      0x00000001930c5ef0 -[__NSObserver _doit:] + 316

```

A: Infinite loop. You are writing to UserDefaults in the same method that fires as a result of the observer that fires whenever UserDefaults is modified.
Fix: don't write to UserDefaults as a side-effect of a method that is the target of an observer that fires whenever UserDefaults is written to.


text:
Q: Fluent API e Migration Tenho o seguinte cenário:
public abstract class Pessoa
{

   /* Propriedades do Pessoa*/
   public Guid IdPessoa { get; set; }
}

public class Cliente : Pessoa
{
    public Cliente()
    {
       IdPessoa = Guid.NewGuid();
       Enderecos = new List<Endereco>()
    }
    /* Propriedades do Cliente */
    public virtual string CPF {get; private set; }
    public virtual ICollection<Endereco> Enderecos { get; set; }
}

public class Fornecedor : Pessoa
{
    public Fornecedor()
    {
       IdPessoa = Guid.NewGuid();
       Enderecos = new List<Endereco>()
    }

    public virtual string CNPJ {get; private set; }
    public virtual ICollection<Endereco> Enderecos { get; set; }
}

O que eu gostaria de fazer:
1º - Usar o migration para criar a base, mas no meu teste ele gera a tabela pessoa com todos os atributos e as classes que estendem Pessoa apenas com o IdPessoa e a propriedade particular de cada uma. Gostaria de saber se posso usar ou se tenho que mapear na unha?
2º - Na entidade Endereco ele vai possuir apenas número, complemento, CEP e o IdPessoa. Porem não sei se isso é possível. Se não for eu posso ter na mesma entidade (endereco) atributos como IdCliente, IdFornecedor ... Id .... conforme for precisando e somente preenchendo de acordo com a entidade persistida (na minha visão, tenho quase certeza que isso seria uma gambiarra), qual seria a alternativa: uma tabela pra cada entidade tipo ClienteEndereco, FornecedorEndereco e se for isso como ficaria minhas classes e o mapeamento?
Obrigado.

A: Quando falamos em mapear classes que utilizam hierarquias para tabelas, independentemente de ORM, temos 3 padrões conhecidos:
Tabela por Hierarquia (TPH)
Ocorre a desnormalização total das tabelas, ou seja, a transformação de todos os campos definidos em todas as classes em uma mesma tabela.
Quando isso acontece, todas as propriedades próprias de classes filhas viram campos NULL e o Entity Framework cria um campo "Discriminator" para saber a qual entidade filha aquele registro pertence.
Tabela por Tipo (TPT)
O tipo pai e todos os seus filhos ganham uma tabela própria cada, onde a classe abstrata possui a chave primária e cada filho possui como chave primária apenas a chave estrangeira do tipo pai.
Quando isso acontece, temos um cenário plenamente normalizado, pois nenhum campo se repete.
Tabela por Tipo Concreto (TPC)
Quando seu objetivo é ter uma tabela separada para cada classe filha, não importando a repetição de campos na classe abstrata, esse é o tipo desejado.
Implementar esse tipo de modelo geralmente dá um trabalho a mais, pois cada entidade deve gerar um Id próprio, ao mesmo tempo em que na modelagem de classes, eles possuem o mesmo campo de identidade na classe abstrata.

1º - Usar o migration para criar a base, mas no meu teste ele gera a tabela pessoa com todos os atributos e as classes que estendem Pessoa apenas com o IdPessoa e a propriedade particular de cada uma. Gostaria de saber se posso usar ou se tenho que mapear na unha ?

Pela forma que você descreveu na questão, parece que está ocorrendo o padrão TPT para o Pessoa mas você quer um TPC. No seu caso, como Pessoa não possui campos próprios e o IdPessoa que cada filho carrega é um Guid independente um do outro, o TPC parece ser a melhor solução para a sua abstração.
Considerando as suas classes acima, temos a seguinte configuração para as classes de Pessoa, independentemente do padrão:
public DbSet<Pessoa> Pessoas { get; set; }

protected override void OnModelCreating(DbModelBuilder modelBuilder)
{
    // mapeamento específico conforme o padrão

    // mapeamento comum das classes
    modelBuilder.Entity<Pessoa>().HasKey(x => x.IdPessoa);
    modelBuilder.Entity<Pessoa>().Property(x => x.IdPessoa)
                                 .IsRequired()
                                 .HasDatabaseGeneratedOption(DatabaseGeneratedOption.Identity);

    modelBuilder.Entity<Cliente>().Property(x => x.CPF)
                                  .IsRequired()
                                  .IsFixedLength()
                                  .IsUnicode(false)
                                  .HasColumnType("char")
                                  .HasMaxLength(11);

    modelBuilder.Entity<Fornecedor>().Property(x => x.CNPJ)
                                     .IsRequired()
                                     .IsFixedLength()
                                     .IsUnicode(false)
                                     .HasColumnType("char")
                                     .HasMaxLength(14);

    base.OnModelCreating(modelBuilder);
}

Um exemplo de criação de base e registros para cada tipo de pessoa:
Database.SetInitializer<Contexto>(new DropCreateDatabaseAlways<Contexto>());

using (var contexto = new Contexto())
{
    var cliente = new Cliente { CPF = "74182476808" }; // gerado aleatoriamente
    contexto.Pessoas.Add(cliente);

    var fornecedor = new Fornecedor { CNPJ = "89205398000106" }; // gerado aleatoriamente
    contexto.Pessoas.Add(fornecedor);

    contexto.SaveChanges();
}

Considerando que parece que você possui um caso de TPT, seu mapeamento específico deve possuir algo como:
modelBuilder.Entity<Cliente>().ToTable("Cliente");
modelBuilder.Entity<Fornecedor>().ToTable("Fornecedor");

E consequentemente, suas tabelas devem estar sendo criadas como:

Pela sua questão, você precisaria de um mapeamento como o abaixo para ter um TPC:
modelBuilder.Entity<Cliente>().Map(m =>
{
    m.MapInheritedProperties(); // necessário para indicar que Pessoas deve estar contido em Cliente
    m.ToTable("Cliente");
});

modelBuilder.Entity<Fornecedor>().Map(m =>
{
    m.MapInheritedProperties(); // necessário para indicar que Pessoas deve estar contido em Fornecedor
    m.ToTable("Fornecedor");
});

Dessa forma, suas tabelas seriam criadas como:

Nesse caso, como para o Entity Framework temos apenas o tipo Pessoa, para pegar apenas Clientes você precisaria fazer algo como:
var clientes = contexto.Pessoas.OfType<Cliente>().ToList();

O que deve ser considerado também é que, pela natureza do seu mapeamento entre classes, fazer um comando contexto.Pessoas.ToList() geraria sempre uma query com UNION ALL entre todas as tabelas de tipos filhos. Por conta disso, o recomendado é que seja verificado muito bem o tipo de querys que você pretende fazer para esse tipo de mapeamento.

2º - Na entidade Endereco ele vai possuir apenas numero, complemento, cep e o IdPessoa. Porem não sei se isso é possivel. Se não for eu posso ter na mesma entidade ( endereco ) atributos como IdCliente, IdFornecedor ... Id .... conforme for precisando e somente preenchendo de acordo com a entidade persistida ( Na minha visao , tenho quase certeza que isso seria uma gambiarra ), qual seria a alternativa uma tabela pra cada entidade tipo ClienteEndereco, FornecedorEndereco e se for isso como ficaria minhas classes e o mapeamento ?

Se na sua entidade de Endereço os campos forem sempre iguais, ela se relacioná com Pessoa e terá apenas o PessoaId que você definiu na classe abstrata.
As entidades ficariam algo como:
public abstract class Pessoa
{
    public Guid IdPessoa { get; set; }
    public virtual ICollection<Endereco> Enderecos { get; set; }
}

public class Cliente : Pessoa
{
    public Cliente()
    {
        IdPessoa = Guid.NewGuid();
        //Enderecos = new List<Endereco>();
    }

    public string CPF { get; set; }
}

public class Fornecedor : Pessoa
{
    public Fornecedor()
    {
        IdPessoa = Guid.NewGuid();
        //Enderecos = new List<Endereco>();
    }

    public string CNPJ { get; set; }
}

public class Endereco
{
    public int IdEndereco { get; set; }
    public string Numero { get; set; }
    public string Complemento { get; set; }
    public string Cep { get; set; }

    public Guid IdPessoa { get; set; }
    public virtual Pessoa Pessoa { get; set; }
}

E o mapeamento de Endereco ficaria:
modelBuilder.Entity<Endereco>().HasKey(x => x.IdEndereco);
modelBuilder.Entity<Endereco>().Property(x => x.IdEndereco)
                               .IsRequired()
                               .HasDatabaseGeneratedOption(DatabaseGeneratedOption.Identity);

modelBuilder.Entity<Endereco>().Property(x => x.Numero)
                               .IsRequired()
                               .IsUnicode(false)
                               .HasColumnType("varchar")
                               .HasMaxLength(5);

modelBuilder.Entity<Endereco>().Property(x => x.Complemento)
                               .IsRequired()
                               .IsUnicode(false)
                               .HasColumnType("varchar")
                               .HasMaxLength(100);

modelBuilder.Entity<Endereco>().Property(x => x.Cep)
                               .IsRequired()
                               .IsFixedLength()
                               .IsUnicode(false)
                               .HasColumnType("char")
                               .HasMaxLength(8);

modelBuilder.Entity<Endereco>().Property(x => x.IdPessoa)
                               .IsRequired();

modelBuilder.Entity<Pessoa>().HasMany<Endereco>(pessoa => pessoa.Enderecos)
                             .WithRequired(endereco => endereco.Pessoa)
                             .HasForeignKey(endereco => endereco.IdPessoa);

Considerando que estamos adicionando 3 endereços como abaixo:
using (var contexto = new Contexto())
{
    var cliente = new Cliente { CPF = "74182476808" }; // gerado aleatoriamente
    contexto.Pessoas.Add(cliente);

    var fornecedor = new Fornecedor { CNPJ = "89205398000106" }; // gerado aleatoriamente
    contexto.Pessoas.Add(fornecedor);

    var enderecoCliente1 = new Endereco { Numero = "1", Cep = "00000000", Complemento = "Teste endereço cliente 1", Pessoa = cliente };
    contexto.Enderecos.Add(enderecoCliente1);

    var enderecoCliente2 = new Endereco { Numero = "2", Cep = "00000000", Complemento = "Teste endereço cliente 2 ", Pessoa = cliente };
    contexto.Enderecos.Add(enderecoCliente2);

    var enderecoFornecedor = new Endereco { Numero = "3", Cep = "00000000", Complemento = "Teste endereço fornecedor", Pessoa = fornecedor };
    contexto.Enderecos.Add(enderecoFornecedor);

    contexto.SaveChanges();
}

Dessa forma, independentemente se você estiver usando TPT ou TPC e você quiser, por exemplo, apenas os clientes e seus respectivos endereços, você faria:
var clientes = contexto.Pessoas.Include("Enderecos").OfType<Cliente>().ToList();

Isso geraria uma query como:
SELECT
    [Project1].[C2] AS [C1],
    [Project1].[C1] AS [C2],
    [Project1].[IdPessoa] AS [IdPessoa],
    [Project1].[CPF] AS [CPF],
    [Project1].[C3] AS [C3],
    [Project1].[IdEndereco] AS [IdEndereco],
    [Project1].[Numero] AS [Numero],
    [Project1].[Complemento] AS [Complemento],
    [Project1].[Cep] AS [Cep],
    [Project1].[IdPessoa1] AS [IdPessoa1]
    FROM ( SELECT
        [Extent1].[IdPessoa] AS [IdPessoa],
        [Extent1].[CPF] AS [CPF],
        '0X0X' AS [C1],
        1 AS [C2],
        [Extent2].[IdEndereco] AS [IdEndereco],
        [Extent2].[Numero] AS [Numero],
        [Extent2].[Complemento] AS [Complemento],
        [Extent2].[Cep] AS [Cep],
        [Extent2].[IdPessoa] AS [IdPessoa1],
        CASE WHEN ([Extent2].[IdEndereco] IS NULL) THEN CAST(NULL AS int) ELSE 1 END AS [C3]
        FROM  [dbo].[Cliente] AS [Extent1]
        LEFT OUTER JOIN [dbo].[Enderecoes] AS [Extent2] ON [Extent1].[IdPessoa] = [Extent2].[IdPessoa]
    )  AS [Project1]
    ORDER BY [Project1].[IdPessoa] ASC, [Project1].[C3] ASC

E finalmente, o resultado seria:

Importante: como estamos falando de Cliente e Fornecedor como tabelas diferentes e sem relação, o campo "IdPessoa" da tabela Endereco nunca terá uma FK.
Se essa chave é crucial para seu caso, é recomendado o uso de TPT para Pessoa ou, no pior caso, deixe a lista de Endereços em cada Pessoa e fique com N campos NULL na tabela Endereco para lidar com cada um dos filhos de Pessoa.

A:
1º - Usar o migration para criar a base, mas no meu teste ele gera a tabela pessoa com todos os atributos e as classes que estendem Pessoa apenas com o IdPessoa e a propriedade particular de cada uma. Gostaria de saber se posso usar ou se tenho que mapear na unha?

Isso ocorre porque você mapeou Pessoa com um DbSet correspondente no contexto. Neste caso, o Entity Framework entende que Cliente e Fornecedor estendem Pessoa e colocam todos os campos na mesma tabela, o que é correto, já que você pode usar assim:
var pessoas = db.Pessoas.ToList();

Essa consulta traz todas as pessoas, independentes de serem clientes ou fornecedores. Se você deseja manter clientes e fornecedores separados, remova o DbSet de Pessoa e gere o banco de dados novamente.

2º - Na entidade Endereco ele vai possuir apenas numero, complemento, cep e o IdPessoa. Porem não sei se isso é possivel. Se não for eu posso ter na mesma entidade ( endereco ) atributos como IdCliente, IdFornecedor ... Id .... conforme for precisando e somente preenchendo de acordo com a entidade persistida ( Na minha visao , tenho quase certeza que isso seria uma gambiarra ), qual seria a alternativa uma tabela pra cada entidade tipo ClienteEndereco, FornecedorEndereco e se for isso como ficaria minhas classes e o mapeamento?

Resolvendo o ponto 1 resolve-se automaticamente por design o ponto 2, ou seja, não precisará existir ClienteEndereco e FornecedorEndereco se você usar a estrutura unificada de tabelas com a herança. Apenas Endereco já resolve bem o que você precisa.
Agora, se a intenção é deixar Cliente e Fornecedor em tabelas separadas, você terá que realizar o mapeamento de ClienteEndereco e FornecedorEndereco, respectivamente, e poderá usar não necessariamente IdPessoa. Pode usar IdCliente ou IdFornecedor, apenas indicando ao Entity Framework as propriedades de navegação corretas, ou seja, para ClienteEndereco:
public int ClienteId { get; set; }
public virtual Cliente Cliente { get; set; }

E para Fornecedor:
public int FornecedorId { get; set; }
public virtual Fornecedor Fornecedor { get; set; }

Como disse em comentário, se você quer unificar os endereços, mas especializando por Cliente e Fornecedor, terá também que colocar a herança em Endereco:
public abstract class Endereco { ... }
public class ClienteEndereco : Endereco { ... }
public class FornecedorEndereco { ... }


text:
Q: Python, sum returned MySQL data 'm fetching some data from MySQL database using:
cur.execute("SELECT memory FROM vm WHERE hv_id=5")
for row in cur.fetchall() :
print row[0]

This prints something like this:
512
1024
4096
4096
2048
4096
1024
6144
1024
1024
4096

I need sum the above and set it as a variable for further calculations.

A: Why don't use SUM() in the query itself:
cur.execute("SELECT SUM(memory) FROM vm WHERE hv_id=5")
result = cur.fetchone()[0]

A: another answer if you are finding something Pythonista
cur.execute("SELECT memory FROM vm WHERE hv_id=5")
result = sum(int(x) for x in cur.fetchall())
print result

or
result = sum(map(int, cur.fetchall()))


text:
Q: Create button onclick function to act as arrow keys do I have this Java script function that acts as a back space.  This works fine but now I want to create a button that goes back, and one that goes forward without deleting the text ( like the behavior of your arrow keys ) .  Any help with this is greatly appreciated.

 function setBack() {
     document.getElementById('user').value =
     document.getElementById('user').value.substring(0,
     document.getElementById('user').value.length - 1);
 }
 <input id="user" type="text">
 <button type="button" onclick="setBack();">backspace</button>
 <button type="button" onclick="">back</button>
 <button type="button" onclick="">forward</button>

No jQuery please Native Javascript only.

A: Give this a try:

            let input = document.getElementById('Test');
            input.focus();

            let index = 0;

            document.getElementById('Prev').addEventListener('click', function(){

                index -= 1;

                if(index <= 0) {
                    index = input.value.length;
                }

                input.focus();
                input.selectionEnd = index;
                input.selectionStart = index;
            });

            document.getElementById('Next').addEventListener('click', function(){
                console.log(index);

                index += 1;

                if(index > input.value.length) {
                    index = 0;
                }

                input.focus();
                input.selectionEnd = index;
                input.selectionStart = index;
            });
        <input id="Test" type="text" value="helloooo">
        <button id="Prev">Prev</button>
        <button id="Next">Next</button>

A: You can do that by obtaining the cursor location which is possible with selectionStart. Here is the sample code. You can add more features to this as per the requirement.
function back(){

                console.log(user.selectionStart-1)
                if(user.selectionStart !== 0 ){
                user.focus();
                user.selectionEnd = user.selectionStart
                user.selectionStart = user.selectionStart-1
                }

            }
function forward(){

                console.log(user.selectionStart)
                user.focus()
                user.selectionEnd = user.selectionStart+1
                user.selectionStart = user.selectionStart+1

            }

A: You can store caret position inside var say caretPosition . And pass caret position after back and forward. Just increment pos on forward and decrement pos on back. here is how i have tried.

var caretPosition = 0;
function updateLength(){
  caretPosition =  document.getElementById('user').value.length
}
function setBack(e) {
     var str= document.getElementById('user').value;
     var position =document.getElementById('user').selectionStart;
     caretPosition = position-1;
     document.getElementById('user').value =
     str.substring(0,position - 1) + str.substring(position, str.length)
     resetCaretPosition('user',caretPosition);

 }
 function back(){
   caretPosition =(caretPosition>1)?caretPosition-1:caretPosition ;
   resetCaretPosition('user',caretPosition);
}

 function forward(){
   caretPosition =caretPosition+1 ;
   resetCaretPosition('user',caretPosition);
 }
 function resetCaretPosition(elemId, caretPos){
    var elem = document.getElementById(elemId);
    if(elem != null) {
        if(elem.createTextRange) {
            var range = elem.createTextRange();
            range.move('character', caretPos);
            range.select();
        }
        else {
            if(elem.selectionStart) {
                elem.focus();
                elem.setSelectionRange(caretPos, caretPos);
            }
            else
                elem.focus();
        }
    }
}
<input id="user" oninput="updateLength()"  type="text">
 <button type="button" onclick="setBack(event);">backspace</button>
 <button type="button" onclick="back()">back</button>
 <button type="button" onclick="forward()">forward</button>


text:
Q: WinDev - Using a variable in a Looper Content Query I am hoping someone will be able to point me in the right direction.  I have a Looper control within WinDev and am filling the Content using a Query.
How do I utilise a global variable within the query?  It seems that it must be passed in as a parameter to the query, however there is no opportunity to set the parameter unless executing the query from code.  It all seems a little contradictory and I am sure I'm missing something obvious.
UPDATE
Having read about MySource but also read that MySource cannot be utilised in an Initialization block; I have moved the query to independent.  Thereby allowing me to set the parameter with
Query name.Parameter = Value

However, although the Query is specified in the Content table of the Looper control, it does not seem to return anything.
Have tried calling HExecuteQuery() and LooperDisplay(), neither of which seem to do anything.
The query is a simple select and works when tested in the query editor.
Any help would be greatly appreciated,

A: It turns out that I had to go into the Description of each field and re-click the Link entry.  Nothing changed as I clicked them but the data now appears.
Not a great solution but it resolved the issue  :-(

A: Changing from embedded to independent is the best thing you could do and it's the best practice as well. Once the source has changed though you do have to rebind all the data to the attributes since it loses it's references.
You better execute the query at the window's Global Declarations section if you don't want to eat up resources and I/Os for nothing by using the Window's End of Initialization section like I've seen people doing .
This way you don't need to call LooperDisplay() and your independent Query will only be called once by your HExecuteQuery().


text: Q: Is it possible to implement "Evernote" Apps shortcut creation using phonegap? Is it possible to implement the shortcut creation technique used in "Evernote" app using phonegap plugin.I am trying to do the same using phonegap  and android but unfortunately I am unable to do so.I could easily do that with a native app with android but is it possible in cross platform as well?It would be really helpful if anybody can help me out with this.Thanks!!


text:
Q: NoSuchMethodException with PageFactory in Appium While using some code like the following:
PageFactory.initElements(AppiumFieldDecorator(driver, Duration.ofSeconds(3)), this)

I receive this error:
java.lang.RuntimeException: java.lang.NoSuchMethodException: jdk.proxy2.$Proxy9.proxyClassLookup()

You can read the complete error log here.
I found someone else who had this problem, and the only answer is to use JDK 15 instead of JDK 16. I tried, with JDK 15.0.2 and JDK 1.8, but it doesn't solve the problem for me. In addition I would like to continue using JDK 16.
I'm currently using OpenJDK 16.0.2 and Appium 7.5.1.
Do you know how can I solve it?

A: I tried again with JDK 15.0.2, and it works now: unfortunately I don't know exactly why.
The following is the init I used in my class:
PageFactory.initElements(AppiumFieldDecorator(driver), this)

A: I fixed this situation by changing from Java SE 17.0.1 to Java SE 11.0.12
screenshot from Eclipse IDE


text:
Q: Search (SQLite3) database using multiple words (If you can think of a better title please say)
So I have a database with tables which I want to be able to search. Search as in I have the input intel core i5 and I want to get any row which column Name has intel, core and i5 in it in any arrangement, characters surrounding these words or any other words anywhere.
So far I am doing:
search = "intel core i5" # This is taken from an entry field.
words = []
for word in search.split()
    words.append("%" + word.strip() + "%")
results = db_handler.query("""SELECT Table1.ID
                              FROM Table1
                                  JOIN Table2
                                  ON Table1.ID2 = Table2.ID
                              WHERE Table2.Name LIKE({0}) AND
                                  Active=1""".format(", ".join("?" for _ in self.words)), self.words)
# db_handler.query is a method which queries and returns results. Plus some other stuff.
# In Table1 there is some columns like ID, ID2, Active, eta
# ID2 matches ID in Table2 which also contains Name
# So I want ID from Table1 searched by Name from Table2

But that does not work as LIKE does not take more than one arg. (There is probably a better way of doing it than splitting the input up but I did this as this was what made sense, is there?) I have seen some people with a bit different questions be suggested REGEXP but I have look at it but did not really get it for my use. If this is the best, can you explain how thanks. How should I do this?
Thanks

A: LIKE takes one pattern, but you can include multiple keywords in it, for example:
... LIKE '%intel%core%i5%' ...

This will match values containing intel followed by core followed by i5, with arbitrary strings before, after, and in between.
To find records containing any arrangements,
you need to use multiple LIKE clauses of all permutations (there are 6 of them in this example), and OR them together, for example:
... (Table2.Name LIKE '%intel%core%i5%' OR Table2.Name LIKE '%intel%i5%core%' OR ...) ...

In context:
from itertools import permutations

search = "intel core i5"
words = [word.strip() for word in search.split()]
combinations = ["%" + "%".join(order) + "%" for order in list(permutations(words)]
sql = """SELECT <Columns> FROM <Table>
         WHERE [Other ...]
             (<Col> LIKE {0})""".format(" OR <Col> LIKE ".join("?" for _ in combinations))
values = combinations # sql and values/combinations to be sent to a query function.

A: Let's suppose (to consider the general problem) that you want to be able to find rows with any or all of the words in list or set words in column col. Let's also further suppose that you are fully aware of the risks of SQL injection attacks, and so you are fully sanitising any user input before including it in words.
The query condition you want for a single word w can be expressed in Python as
"{0} LIKE '%{}%'".format(col, w)

The individual field queries need to be joined with "OR" to find any term or "AND" to find all terms. So you can set joiner to be either ' AND ' or ' OR ' and then the whole query search condition will be
joiner.join(["{0} LIKE '%{1}%'".format(col, w) for w in words])

If you set
words = "intel core i5".split()
joiner = " AND "
col = "Table2.name"

this evaluates to
Table2.name LIKE '%intel%' AND Table2.name LIKE '%core%' AND Table2.name LIKE '%i5%'

You clearly already know enough Python to be able to do what you want with that.


text:
Q: Creating a Triangulation for use in Matplotlib's plot_trisurf with matplotlib.tri.Triangulation I am a trying to use matplotlib.tri.Triangulation to generate the triangles for a matplotlibs plot_trisurf. I want to specify the triangles rather than letting the Delaunay triangulation which matplotlib.tri.Triangulation uses because it does not work for some cases such as triangles in in the xz or yz plane. I am not sure if this specifying the triangles myself will solve the problem but I seems like a good thing to try.
The issue is that the triangulation requires a (n,3) array with n being the number of triangles. To quote the page on matplotlib.org "For each triangle, the indices of the three points that make up the triangle, ordered in an anticlockwise manner." https://matplotlib.org/api/tri_api.html#matplotlib.tri.Triangulation
. I cannot discern how to create the array in the right form and that is were I would like help. I appreciate any help.
I have tried a few things so far but here is what my last try looks like:
import matplotlib.pyplot as plt
import numpy as np
import matplotlib.tri as mtri

fig = plt.figure()
ax = fig.gca(projection='3d')

x1=0
x2=1
x3=1
x4=0

y1=0
y2=0
y3=2
y4=2

x=[]
y=[]
x.append(x1)
x.append(x2)
x.append(x3)
x.append(x4)
y.append(y1)
y.append(y2)
y.append(y3)
y.append(y4)
z=np.zeros(8)

triang = mtri.Triangulation(x, y, triangles=[[[x1,y1],[x2,y2],[x3,y3]],[[x3,y3],[x4,y4],[x2,y2]]])

ax.plot_trisurf(triang, z, linewidth=0.2, antialiased=True)

ax.view_init(45,-90)
ax.set_xlabel("X")
ax.set_ylabel("Y")
ax.set_zlabel("Z")
ax.set_aspect("equal")

fig.set_size_inches(8,8)

plt.show()

A: There is an example on the matplotlib page that shows how to use points and triangles to create a matplotlib.tri.Triangulation. As this may be unnecessarily complicated, we may simplify even further.
Let's take 4 points, which should create 2 triangles. The triangles argument would specify the corners of the triangles in form of the indices of the points. As the documentation says,

triangles : integer array_like of shape (ntri, 3), optional
  For each triangle, the indices of the three points that make up the triangle, ordered in an anticlockwise manner. [..]

Consider this code, where we have a (4,2) array, specifying the point coordinates, having the x and y coordinates for each point in a row. We then create triangles from them by using the indizes of the points that should constitute the triangle in an anti-clockwise manner.
import numpy as np
import matplotlib.pyplot as plt
import matplotlib.tri as mtri

xy = [[0.3,0.5],
      [0.6,0.8],
      [0.5,0.1],
      [0.1,0.2]]
xy = np.array(xy)

triangles = [[0,2,1],
             [2,0,3]]

triang = mtri.Triangulation(xy[:,0], xy[:,1], triangles=triangles)
plt.triplot(triang, marker="o")

plt.show()

The first triangle is made up of points 0, 2, 1  and the second of 2,0,3. The following graphics shows visualizes that code.

We may then create a list of z values and plot the same in 3D.
import numpy as np
import matplotlib.pyplot as plt
import matplotlib.tri as mtri
from mpl_toolkits.mplot3d import Axes3D

xy = [[0.3,0.5],
      [0.6,0.8],
      [0.5,0.1],
      [0.1,0.2]]
xy = np.array(xy)

triangles = [[0,2,1],
             [2,0,3]]

triang = mtri.Triangulation(xy[:,0], xy[:,1], triangles=triangles)

z = [0.1,0.2,0.3,0.4]

fig, ax = plt.subplots(subplot_kw =dict(projection="3d"))
ax.plot_trisurf(triang, z)

plt.show()


text:
Q: React doesn't rerender component when props change I have a problem with React components not re-rendering when their props change. GroupLabel takes counter as a prop.
export const GroupLabel = (props) => {
    const change = () => {
        props.setCurrent(props.group);
        let newCounter = props.counter;
        newCounter[props.group.ID] = 0;
        props.setCounter(newCounter);
    };

    return (

                <img src="..."

                {props.group.name}

            {props.counter[props.group.ID]>0?{props.counter[props.group.ID]}:null}

    );
}

GroupLabel is invoked by its parent component for every group it has in groups (groups is a list of objects and a state).
{groups.length!==0?groups.map(item => {return <GroupLabel counter={counter} setCounter={setCounter} key={item.ID} setCurrent={setCurrent} group={item}/>}):null}

In parent component counter is an object mapping groupID to number of messages this group received via websocket. It is changed like this:
let newCounter = counter; // counter is a current state
newCounter[msgJSON.group]++; // msgJSON.group is id of group to which message is directed
setCounter(newCounter);

And it all works correctly but React still doesn't re-render. From what I read React should re-render its components whenever:

*

*their state changes

*their props change

*parent component is re-rendered
In this situation both GroupLabel props change and parent state is changing (since counter it passes is his state). I can see in React Dev Tools that counter prop has changed (initially its zero for every group).

I don't give the whole code for the parent component because it is too long.

A: The problem is that you are mutating state, not creating a new one. When you set state in a function component, react will do a === between the old state and the new state. If they're equal, the component does not render.
To fix this, change this:
let newCounter = props.counter;
newCounter[props.group.ID] = 0;
props.setCounter(newCounter);

To this:
let newCounter = {
  ...props.counter
};
newCounter[props.group.ID] = 0;
props.setCounter(newCounter);

And this:
let newCounter = counter;
newCounter[msgJSON.group]++;
setCounter(newCounter);

To this:
let newCounter = {
  ...counter;
}
newCounter[msgJSON.group]++;
setCounter(newCounter);


text:
Q: Seeking on a http progressive download I am trying to implement the progressive download of audio files in my android project. I am able to progressively play the audio by reading chunks of data and passing on to the media player. So, the media player does play the audio with simultaneous buffering, but the problem lies with seeking.
When I seek to a position where the buffering has not yet completed, then the client requests the server for a range of bytes. Once I receive the range of data, I store it in a file and  pass the file descriptor to the mediaplayer, but the mediaplayer is unable to play the audio since the header information is missing.
Is there any better way to do this? Any queue buffering so that the header information is still retained while loading the content at a particular position? Or any other way to handle seeking on a progressive download?
Note that I cannot pass the uri of the audio files to the media player for security reasons.


text:
Q: jQuery Animate Button Background Shape I am trying to duplicate the button hover effect as seen on this website: http://www.dewitt.ch/
They are using a css styled triangle and animating it across on hover.
jQuery(".btn")
 .mouseover(function () {
  jQuery(this).find(".triangle").animate({
    right: "-50px"
  }, 100);
 })
.mouseout(function () {
 jQuery(this).find(".triangle").animate({
    right: "-500px"
 }, 100,

 function () {
    jQuery(this).find(".triangle").css(
        "right", "100%"
    )
 });
});

I have created a code snippet to show my current efforts here:

jQuery(".btn")
  .mouseover(function() {
    jQuery(this).find(".triangle").animate({
      right: "0px"
    });
  })
  .mouseout(function() {
    jQuery(this).find(".triangle").animate({
      right: "100%"
    });
  });
.btn {
  -webkit-backface-visibility: hidden;
  -moz-backface-visibility: hidden;
  -ms-backface-visibility: hidden;
  -o-backface-visibility: hidden;
  backface-visibility: hidden;
  display: inline-block;
  border: 1px solid #d5b7a0;
  color: #d5b7a0;
  font: 400 1.2em/1em Arial, Helvetica, sans-serif;
  height: 48px;
  line-height: 48px;
  margin-top: 20px;
  overflow: hidden;
  padding: 0 50px;
  position: relative;
  text-transform: uppercase;
  letter-spacing: 2px;
  background: 0 0;
  cursor: pointer;
  transform: translate3d(0px, 0px, 0px);
}

.btn .triangle {
  width: 100%;
  position: absolute;
  top: 0;
  border-left: 52px solid transparent;
  border-right: 52px solid transparent;
  border-top: 52px solid #d5b7a0;
  display: block;
  right: 100%;
}

  Button

I am close to getting it to work properly but the triangle shape is "bouncing", also I'm struggling to get it to come in from the left and exit to the right.
I am using jQuery .mouseover and .mouseout to trigger .animate which may not be the best method?

A: Why not use css:
.btn .triangle {
  -webkit-transition:all 0.4s ease;
  right:100%;
}

.btn:hover .triangle {
  right:0;
}

P.s: your jquery animate is missing the timing;

A: Try this:
$( ".btn" )
  .mouseenter(function() {
    $( ".triangle" ).animate({right:"0px"}, 50);
  })
  .mouseleave(function() {
    $( ".triangle" ).animate({right:"100%"}, 50);
  });

Or pure css:
.btn .triangle {
  -webkit-transition: right 0.4s ease;
  transition: right 0.4s ease;
  right:100%;
}

.btn:hover .triangle {
  right:0;
}

A: No need for jQuery animate on this one, CSS animation does the trick. Just remember to add css transition on the .triangle
.btn:hover .triangle {
    right: 0;
}

.btn{
 -webkit-backface-visibility: hidden;
 -moz-backface-visibility: hidden;
 -ms-backface-visibility: hidden;
 -o-backface-visibility: hidden;
 backface-visibility: hidden;
 display: inline-block;
 border: 1px solid #d5b7a0;
 color: #d5b7a0;
 font: 400 1.2em/1em Arial,Helvetica,sans-serif;
 height: 48px;
 line-height: 48px;
 margin-top: 20px;
 overflow: hidden;
 padding: 0 50px;
 position: relative;
 text-transform: uppercase;
 letter-spacing: 2px;
 background: 0 0;
 cursor: pointer;
 transform: translate3d(0px, 0px, 0px);
}
.btn .triangle{
 width: 100%;
 position: absolute;
 top: 0;
 border-left: 52px solid transparent;
 border-right: 52px solid transparent;
 border-top: 52px solid #d5b7a0;
 display: block;
    right:100%;
    -webkit-transition: right 0.5s ease-in-out;
    transition: right 0.5s ease-in-out;
}
.btn:hover .triangle {
    right: 0;
}

 Button

A: I added the timing element that was mentioned, but what was causing the triangle element to jump around was .mouseover and .mouseout.
.mouseenter and .mouseleave work much better.
jQuery(".btn")
   .mouseenter(function () {
     jQuery(this).find(".triangle").animate({
        right: "-50px"
     }, 500);
   })
   .mouseleave(function () {
     jQuery(this).find(".triangle").animate({
        right: "-500px"
     }, 500,
        function () {
           jQuery(".triangle").css(
             "right", "200%"
           );
        });
});

Here's the code snippet:

jQuery(".btn")
  .mouseenter(function() {
    jQuery(this).find(".triangle").animate({
      right: "-50px"
    }, 500);
  })
  .mouseleave(function() {
    jQuery(this).find(".triangle").animate({
        right: "-500px"
      }, 500,
      function() {
        jQuery(".triangle").css(
          "right", "200%"
        );
      });
  });
.btn {
  -webkit-backface-visibility: hidden;
  -moz-backface-visibility: hidden;
  -ms-backface-visibility: hidden;
  -o-backface-visibility: hidden;
  backface-visibility: hidden;
  display: inline-block;
  border: 1px solid #d5b7a0;
  color: #d5b7a0;
  font: 400 1.2em/1em Arial, Helvetica, sans-serif;
  height: 48px;
  line-height: 48px;
  margin-top: 20px;
  overflow: hidden;
  padding: 0 50px;
  position: relative;
  text-transform: uppercase;
  letter-spacing: 2px;
  background: 0 0;
  cursor: pointer;
  transform: translate3d(0px, 0px, 0px);
}

.btn .triangle {
  width: 100%;
  position: absolute;
  top: 0;
  border-left: 52px solid transparent;
  border-right: 52px solid transparent;
  border-top: 52px solid #d5b7a0;
  display: block;
  right: 100%;
}

  Button


text:
Q: sort array in php, merging two values together I have the following array from a while($x = mysql_fetch_assoc...):
Array ( [item_id] => 1 [item_name] => name [foo] => bar )

How would I modify the array so it returns me:
Array ( [item_id] => 1 [item_name] => name - bar )

A: $array['item_name'] = "{$array['item_name']} - {$array['foo']}";
unset($array['foo']);

or alternatively
$array = array(
  'item_id' => $array['item_id'],
  'item_name' => "{$array['item_name']} - {$array['foo']}"
);

A: If you always want to merge [item_name] and [foo] values, then it's pretty easy:
$result = array_map(function($item) {
    return array(
        'item_id' => $item['item_id'],
        'item_name' => $item['item_name'] . ' - ' . $item['foo'],
    );
}, $input);


text:
Q: CouchDB Index Error using ORDER BY in queries from Hyperledger Composer v0.18.0 to v0.19.0 I have an issue with CouchDB Index on a query with the ORDER BY statement while moving from Hyperledger Composer v0.18.0 to v0.19.0.

Context:

A Simple Asset called Event:
asset Event identified by id {
    o String id
    o String name
    o EventType eventType
    o DateTime scheduledTime
    o EventStatus status
}

A Query with an ORDER BY statement:
query getScheduledEvents {
    description: "Select all the SCHEDULED Events"
    statement:
        SELECT event.network.assets.Event
            WHERE (status == 'SCHEDULED')
                ORDER BY [scheduledTime ASC]
}

HL Composer v0.18.0

Using Composer v0.18.0 everything works fine. I can query the Events from the REST API simply creating this Index on CouchDB:
{
    "type": "json",
    "def": {
    "fields": [
            {
                "scheduledTime": "asc"
            }
        ],
        "partial_filter_selector": {}
     }
}

HL Composer v0.19.0

From Composer v0.19.0 (And Fabric 1.1.0) the Index will be automatically generated on the deployment, and the new index looks like this:
{
    "type": "json",
    "def": {
        "fields": [
            {
                "\\$class": "asc"
            },
            {
                "\\$registryType": "asc"
            },
            {
                "\\$registryId": "asc"
            },
            {
                "status": "asc"
            },
            {
                "scheduledTime": "asc"
            }
        ],
        "partial_filter_selector": {}
    }
}

And now, using Composer v0.19.0, querying the same endpoint I get the following error :
{
"error": {
    "statusCode": 500,
    "name": "Error",
    "message": "2 UNKNOWN: error executing chaincode: transaction returned with failure: Error: Couch DB Error:no_usable_index,  Status Code:400,  Reason:No index exists for this sort, try indexing by the sort fields.",
    "code": 2,
    "metadata": {
        "_internal_repr": {}
    },
    "details": "error executing chaincode: transaction returned with failure: Error: Couch DB Error:no_usable_index,  Status Code:400,  Reason:No index exists for this sort, try indexing by the sort fields.",
"stack": "Error: 2 UNKNOWN: error executing chaincode: transaction returned with failure: Error: Couch DB Error:no_usable_index,  Status Code:400,  Reason:No index exists for this sort, try indexing by the sort fields.\n    at new createStatusError (/home/user/.nvm/versions/node/v8.11.1/lib/node_modules/composer-rest-server/node_modules/grpc/src/client.js:64:15)\n    at /home/user/.nvm/versions/node/v8.11.1/lib/node_modules/composer-rest-server/node_modules/grpc/src/client.js:583:15"
    }
}

Removing the generated index and creating the old one won't solve the issue, as I still receive the same error.
Any thoughts?
Thank you!

A: I was able to recreate this with a similar query, and found that I could get it working by rearranging the fields in the index document.  In your case it would be arranged as follows:
{
    "type": "json",
    "def": {
        "fields": [
            {
                "\\$class": "asc"
            },
            {
                "\\$registryType": "asc"
            },
            {
                "\\$registryId": "asc"
            },
            {
                "scheduledTime": "asc"
            },
            {
                "status": "asc"
            }
        ],
        "partial_filter_selector": {}
    }
}

I think this is related to the explanation in bullet 3 of this post


text:
Q: Best way to query the log files, with Spark or caseesndra I have log files in different servers(5 servers connect through LAN) and I need to process and get the result

*

*Each node has 4TB log files and I'm using HDFS to load all log files into Spark

*Every time, when request come, the Spark load all files (5 * 4TB) then query with Spark SQL

What if I load all the log files into caseesndra and then query (it can be preloaded ) ? which is the fast way ..?

A: HDFS and Cassandra has each their own advantages.
If you need to process all log files entirely, HDFS is a better choice because it is a file system and has been designed to store a massive amount of data and process them by batch.
Now, if you only need to process a portion of the log files, a datastore like Cassandra is a better choice because you can filter data by primary key and have faster access and skip scanning through all the files.
Cassandra is designed for OLTP workload whereas HDFS and the kind are designed for OLAP workload


text:
Q: I would like to be able to get this integral evaluation to show up in terms of variables this is very much a beginner question; I was hoping that someone may be able to take a look at this code and tell me why it outputs all of these crazy numbers instead of just the variables specified in the limits. Any help is very much appreciated, thank you.

A: I suspect that you may have accidental defined some parameters such as Γ and ω0 earlier, because they don't appear in the Out[64] line in your image. To clear all definitions, it is sometimes helpful to simply quit the kernel. You can find this option under the "Evaluation" menu.
You also don't need the Evaluate[] line. You can simply call n[ω, ω0, Γ].
The following worked for me on a fresh kernel:
k[ω_, ω0_, Γ_] := 1/(2 π)* Γ^2/((ω - ω0)^2 + Γ^2)
n[ω_, ω0_, Γ_] := 1 + 2/π Integrate[a k[a, ω0, Γ]/(a^2 - ω^2), {a, 0, ∞}, Assumptions -> 0 < ω && 0 < ω0 && 0 < Γ, PrincipalValue -> True]
n[ω, ω0, Γ]

This returned the following analytical result:
(*1 + (Γ (ω0 (Γ^2 - ω^2 + ω0^2) (π + 2 ArcTan[ω0/Γ]) - Γ (Γ^2 + ω^2 + ω0^2) Log[ω^2/(Γ^2 + ω0^2)]))/(2 π^2 ((Γ^2 + ω^2)^2 + 2 (Γ - ω) (Γ + ω) ω0^2 + ω0^4))*)


text:
Q: We have a linear operator T. Show $T^2=Id$ implies $T=T^*$ We have a linear operator $T:V\rightarrow V $. V is a finite-dimension inner product space over the field of the complex numbers. Show $T^2=Id$ implies $T=T^*$.
I've tried working with the inner product, trying to get $(Tx,x)=(x,Tx)$ with no luck. Maybe it has something to do with a basis for T (and thus diagonalizability?)

A: You can't prove it, since it is not true. Take$$\begin{array}{rccc}T\colon&\mathbb{R}^2&\longrightarrow&\mathbb{R}\\&(x,y)&\mapsto&\left(2y,\frac x2\right).\end{array}$$Then $T^2=\operatorname{Id}$, but $T^*(x,y)=\left(\frac y2,2x\right)$.

A: $(Tx, y)=(Tx, T^2 y)=(T x, T (Ty))=(x,T y)$
if $T$ is an isometric operator

A: I will build a basis on which $T$ is diagonal.
Given a non-zero vector $u$, consider $v=Tu$. We then have $Tu=v$. Let the first two vectors in our basis be $u+v,u-v$. These are eigenvectors of $T$ with eigenvalues $\pm1$ (if either of those two vectors is $0$, then don't include that in the basis).
Repeat the process by picking a $w$ not in the span of $u,v$, look at $Tw$, add $w\pm Tw$ to the basis, and so on.
We get a basis of eigenvectors with real eigenvalues, meaning $T$ is diagonalizable.


text:
Q: Express Middleware - call cycle module.exports = errorHandler;

function errorHandler(err, req, res, next) {
    if (typeof (err) === 'string') {
        // custom application error
        return res.status(400).json({ error: err });
    }

    if(err.name === 'Unauthorized') {
        return res.status(401).json({ error: err.message })
    }

    // default to 500 server error
    return res.status(500).json({ error: err.message });
}

// register routes
app.use('', require('./controllers/view.controller'))
app.use('/api/auth', require('./controllers/auth.controller'))
app.use('/api/games', require('./controllers/game.controller'))
app.use('/api/bets', require('./controllers/bet.controller'))
app.use('/api/coupons', require('./controllers/coupon.controller'))
app.use('/api/users', require('./controllers/user.controller'))

// global error handler
app.use(errorHandler);

Is this error handler considered express middleware or an express route?
Is express middleware called before or after the request cycle? Or does it depend on when in the cycle its called? For example this errorHandler is registered after the routes, therefore its called after the request cycle?

A: Such errorHandler is a special type of Express middleware which is only called when an error happened (typically by a middleware calling next(err) with a non-null parameter). You can tell it's an error middleware by the number of arguments declared: 4 instead of usual 2 or 3.
So it does not matter where you add it, before or after the normal route handlers (though they are usually defined last). But in relation to each other, on every request cycle, error middlewares do follow the order they are added; the first one added is always called first by Express in the error handling chain.


text:
Q: Existence of free abelian subgroup and isomorphism I am trying to prove the following question:
Given is $G$ an abelian group and $F$ a free abelian group. Let $\varphi: G \rightarrow F$ an epimorphism. Show that there exsit a free abelian subgroup $F'\subset G$ with $ker\varphi \oplus F'=G$ such that $\varphi \mid _ {F'} :F'\rightarrow F$ is a group isomorphism.
How do we prove the existence of $F'$? I know that the subgroups of free abelian groups are free. The epimorphism induces a bijection between the set of subgroups of $F$ and the set of the subgroups of $G$ which contain $ker \varphi$.
Can anybody help me with this question, please? I appreciate any hints and comments. Thank you in advance!

A: Hint: Show that it is sufficient to find a map $\psi:F \to G$ such that $\phi \circ \psi =Id_F$ (consider $Im(\psi)$). Now if $S$ is a basis of $F$, a map from $F$ to $G$ is determined by a function (of sets) $f:S \to G$. Moreover, you want $\phi \circ f=Id_S$, so you don't have a lot of choices left for $f$.
Can you take it from here ?


text: Q: Get timestamp cross two docker containers using kubernetes I got two Docker pods running on Kubernetes, say A and B. I got a flow of events from A to B. I need to find a way to measure the time it takes for an event passes from a point in A until it passes a point in the B. Old fashion Java System.currentTimeMillis() I guess would be working fine if it was within the same pod. But now we cross pod barriers. How do I get proper timestamps?


text:
Q: Fixed JSON reference loop errors not I'm getting too much data I added this line to resolve circular errors in my JSON:
        services.AddMvc()
                .AddJsonOptions(
                    options => options.SerializerSettings.ReferenceLoopHandling = Newtonsoft.Json.ReferenceLoopHandling.Ignore
                );

But now, I find that some of my controllers return too much information.
I found this similiar question, but reading through it, I couldn't really figure out how to apply it to my code:
Avoiding Circular referencing providing too much data
For example, this simple controller returns data that I don't want:
    [HttpGet("{id}")]
    public async Task<ActionResult<BookList>> GetBookList(string id)
    {
        var bookList = await _context.BookList.FindAsync(id);

        return bookList;
    }

Here is the model for that data:
public partial class BookList
{
    public BookList()
    {
        BookLinks = new HashSet<BookLinks>();
    }

    public string BookId { get; set; }
    public Guid LibraryId { get; set; }
    public string BookTitle { get; set; }
    public string BookText { get; set; }
    public byte? BookType { get; set; }

    public virtual LibraryList Library { get; set; }
    public virtual ICollection<BookLinks> BookLinks { get; set; }
}

}
So when I hit the controller above, I am getting all the unwanted data for BookLinks in addition to the data from BookList.
I just want the data from BookList based on a particular BookId.
I was under the impression, that if I wanted all data returned(including the BookLinks data), I'd have to do something like this:
        var bookList = await _context.BookList
            .Include(i => i.BookLinks)
            .Where(b => b.BookId == id)
            .ToListAsync();

That said, is there way to limit or exclude data that I don't want?
Thanks!

A: Your navigation props are virtual, so I'm assuming you have lazy-loading enabled. When the serializer walks the object, it will trigger the get for each of these properties, which will in turn issue queries one by one to backfill the data, which will then get serialized as well. Assuming that it doesn't encounter a circular reference, it will continue to walk down the related entities, loading and serializing each relationship.
This is a perfect illustration of why you should never serialize entities. Entities are for working with the database. They are not for and should not be used for returning responses, rendering views, etc.
Instead, create a view model/DTO/whatever you want to call it. Map your entity class(es) on to that, and then return the view model instead. That way, you can control exactly what the response is.


text:
Q: Setting text in a fragment in Android I've got a method that resets a text field in a fragment to "  ". This worked fine when everything was in MainActivity. The problem is, ((EditText)v.findViewById(R.id.edAreaxml)).setText("");.
Fragment code is:
public class DataEdit extends Fragment implements OnClickListener {

    public View onCreateView(LayoutInflater inflater, ViewGroup container, Bundle savedInstanceState) {
        View v = inflater.inflate(R.layout.dataedit, container, false);
        Button btnResetForm = (Button) v.findViewById(R.id.btnResetFormxml);
        btnResetForm.setOnClickListener(this);
        return v;
    }

    @Override
    public void onClick(View v) {
        switch (v.getId()) {
        case R.id.btnResetFormxml:
            resetForm(v);
            break;
        }
    }
    public void resetForm(View v) {
        ((EditText) v.findViewById(R.id.edAreaxml)).setText(""); //THIS IS THE PROBLEM
    }

XML:
<TableRow>
        <TextView
            android:layout_width="fill_parent"
            android:layout_height="wrap_content"
            android:text="Area">
        </TextView>
        <EditText
            android:layout_width="fill_parent"
            android:layout_height="wrap_content"
            android:id="@+id/edAreaxml">
        </EditText>
</TableRow>

UPDATE: Per answers 1 and 3, the following adjustments have been made. There is still a problem. LogCat output is at bottom.
public class DataEdit extends Fragment implements OnClickListener {
public View onCreateView(LayoutInflater inflater, ViewGroup container, Bundle savedInstanceState) {
        View v = inflater.inflate(R.layout.dataedit, container, false);
    Button btnResetForm = (Button)v.findViewById(R.id.btnResetFormxml);
    btnResetForm.setOnClickListener(this);
    //EditText edArea=(EditText)v.findViewById(R.id.edAreaxml);
    return v;
    }@Override
public void onClick(View v) {
        switch (v.getId()) {
    case R.id.btnResetFormxml:
            resetForm(v);
            break;
       }
    }
public void resetForm(View v) {
        EditText edArea=(EditText)v.findViewById(R.id.edAreaxml);
        edArea.setText(" ");//PROBLEM IS HERE
    }
}

Logcat is:
03-21 09:35:20.735: E/Trace(1013): error opening trace file: No such file or directory (2)
03-21 09:35:21.795: D/gralloc_goldfish(1013): Emulator without GPU emulation detected.
03-21 09:35:22.425: I/Choreographer(1013): Skipped 48 frames!  The application may be doing too much work on its main thread.
03-21 09:35:25.805: I/Choreographer(1013): Skipped 71 frames!  The application may be doing too much work on its main thread.
03-21 09:35:28.254: D/AndroidRuntime(1013): Shutting down VM
03-21 09:35:28.254: W/dalvikvm(1013): threadid=1: thread exiting with uncaught exception (group=0x40a13300)
03-21 09:35:28.294: E/AndroidRuntime(1013): FATAL EXCEPTION: main
03-21 09:35:28.294: E/AndroidRuntime(1013): java.lang.NullPointerException
03-21 09:35:28.294: E/AndroidRuntime(1013):     at net.JonesInc.streamwalker.DataEdit.resetForm(DataEdit.java:139)
03-21 09:35:28.294: E/AndroidRuntime(1013):     at net.JonesInc.streamwalker.DataEdit.onClick(DataEdit.java:74)
03-21 09:35:28.294: E/AndroidRuntime(1013):     at android.view.View.performClick(View.java:4084)
03-21 09:35:28.294: E/AndroidRuntime(1013):     at android.view.View$PerformClick.run(View.java:16966)
03-21 09:35:28.294: E/AndroidRuntime(1013):     at android.os.Handler.handleCallback(Handler.java:615)
03-21 09:35:28.294: E/AndroidRuntime(1013):     at android.os.Handler.dispatchMessage(Handler.java:92)
03-21 09:35:28.294: E/AndroidRuntime(1013):     at android.os.Looper.loop(Looper.java:137)
03-21 09:35:28.294: E/AndroidRuntime(1013):     at android.app.ActivityThread.main(ActivityThread.java:4745)
03-21 09:35:28.294: E/AndroidRuntime(1013):     at java.lang.reflect.Method.invokeNative(Native Method)
03-21 09:35:28.294: E/AndroidRuntime(1013):     at java.lang.reflect.Method.invoke(Method.java:511)
03-21 09:35:28.294: E/AndroidRuntime(1013):     at com.android.internal.os.ZygoteInit$MethodAndArgsCaller.run(ZygoteInit.java:786)
03-21 09:35:28.294: E/AndroidRuntime(1013):     at com.android.internal.os.ZygoteInit.main(ZygoteInit.java:553)
03-21 09:35:28.294: E/AndroidRuntime(1013):     at dalvik.system.NativeStart.main(Native Method)
03-21 09:35:32.204: I/Process(1013): Sending signal. PID: 1013 SIG: 9

A: Try to initialize local variables as:
EditText editText;

@Override
public View onCreateView(LayoutInflater inflater, ViewGroup container, Bundle savedInstanceState) {
    View v = inflater.inflate(R.layout.dataedit, container, false);
    Button btnResetForm = (Button) v.findViewById(R.id.btnResetFormxml);
    btnResetForm.setOnClickListener(this);
    editText = (EditText) v.findViewById(R.id.edArea);
    return v;
}

@Override
public void onClick(View v) {
    switch (v.getId()) {
        case R.id.btnResetFormxml:
            resetForm();
            break;
    }
}

public void resetForm() {
    editText.setText("");
}

With this, your resetForm method have no need the View param.

A: Initialze EditText as below assuming it belongs to dataedit.xml.
EditText ed;
public View onCreateView(LayoutInflater inflater, ViewGroup container, Bundle savedInstanceState) {
    View v = inflater.inflate(R.layout.dataedit, container, false);
    ed =(EditText)v.findViewById(R.id.edArea);
    Button btnResetForm = (Button) v.findViewById(R.id.btnResetFormxml);
    btnResetForm.setOnClickListener(this);
    return v;
}

Then
@Override
public void onClick(View v) {
    switch (v.getId()) {
    case R.id.btnResetFormxml:
        resetForm(); // no need to pass v as a param
        // you could just have  ed.setText(""); here itself. no need for resetForm

        break;
    }
}

Then
public void resetForm() {
    ed.setText("");
}

A: The problem is
 public void onClick(View v)
where v is the button.
Try to put
Button btnResetForm = (Button) v.findViewById(R.id.btnResetFormxml);
et = (EditText)v.findViewById(R.id.edArea);

and define
EditText et;

as a property of your fragment.
After that you can use
public void resetForm(View v) {
    et.setText("");
}


text:
Q: Game Development - Array with pointers to array elements I am currently developing a game for the iPhone/iPod/iPad.  To store the board data, which is 12 columns by 8 rows, I have an array that stores pointers to one of the game items, a block.  It is declared as follows:
BlockData* mBoard[kNumberOfColumns][kNumberOfRows];

I also have another array declared like this:
BlockData* mCenterSquare[16];

This I want to store pointers to specific locations on the board, for example,
mCenterSquare[0] = mBoard[4][5];

Is this the right way of doing it?  What I want to accomplish using the above line of code is for mCenterSquare[0] to store a pointer to a position on the board - 4th column and 5th row.  How would I go about doing this?
Thanks in advance.

A: Why not only use the mCenterSquare array to store data:
function BlockData* getBlockData(int row, int col) {
     return mCenterSquare[row * kNumberOfCols + col]
}

A: I can't help but think this is a trick question.  Yes, that is the way you would do it. :)


text:
Q: Azure Project Publish Profile Corrupt After Uploading to VSO When we create a Publish Profile (azurepubxml) for our Azure Projects (ccproj) and commit to VSO, we tend to get this error in VSO when viewing the file:
VSO Error when Viewing in Browser

This file contains non-printable characters and no other viewer was found for file extension "azurePubxml".
Click to download file to your computer.

Viewing AzurePubXML withinin VSO

A: After further review - there seems to be something in the TFS/VS IDE Tooling that corrupts the file during upload.
The fix is to perform the following steps:

*

*Download the original publish profile locally

*Delete the publish profile from VSO

*Upload the downloaded file directly using VSO in the browser.

Not sure why this is occurring, but hopefully this helps someone else and short circuit time to resolve.


text:
Q: Google related bar - how to keep from showing up on my website A new "google related" bar shows up at the bottom of my website.  It displays links to my competitors and other things like maps, etc.  It is tied in with users using the google toolbar.  If anyone has any ideas on how I can disable from displaying on my web side I would sure appreciate it.

A: Taken from http://harrybailey.com/2011/08/hide-google-related-bar-on-your-website-with-css/
Google inserts an iframe into your html with the class .grelated-iframe
So hiding it is as simple as including the following css:
iframe.grelated-iframe {
    display: none;
}

A: Google removed div and frame names and put everything to important so original answer no longer works on my site. We need to wait for the iframe to be created and then hide it by classname.  Couldn't get .delay to work, but this does...today anyway.
$(document).ready(function() {
setTimeout(function(){
$('.notranslate').hide();},1000);
});

A: Following javascript code tries to find the google related iframe as soon as the window finishes loading. If found, it is made hidden, else an interval of one second is initialized, which checks for the specified iframe and makes it hidden as soon as it is found on page.
$(window).load(function (){
var giframe = null;
var giframecnt = 0;
var giframetmr = -1;

giframe = $("body > iframe.notranslate")[0];
if(giframe != null)
    $(giframe).css("display", "none");
else
    giframetmr = setInterval(function(){
        giframe = $("body > iframe.notranslate")[0];
        if(giframe != null) {
            clearInterval(giframetmr);
            $(giframe).css("display", "none");
        } else if(giframecnt >= 20)
            clearInterval(giframetmr);
        else
            giframecnt++;
    }, 1000);});

A: Find the parent DIV element that contains the stuff in the bar. If it has an id or name attribute, and you can control the page CSS then simply add a rule for the element, i.e. if you see something like
<div id="footer-bar-div".....

then add a CSS rule
#footer-bar-div {display:none ! important}
This will not work if the bar is inside an iframe element, but even in that case you should be able to hide it using javascript, but you will need to find the name/id of the frame, i.e.:
var badFrame = document.getElementById('badFrameId').contentWindow;
badFrame.getElementById('footer-bar-div').style.display='none';

if the frame has a name, then instead you should access it with:
var badFrame = window.frames['badFrameName']

There is also a chance that the bar is generated on-the-fly using javascript. If it is added to the end of the page you can simply add a <noscript> tag at the end of your content - this will prevent the javascript from executing. This is an old trick so it might not always work.


text:
Q: How to let my VBA code skip the Application.Intersect function when there are no cells for the filter criteria? How do I let my my code skip the Application.Intersect function when there are no data points for the filter criteria? The error occurs at line 3 and 4 stating:

I tried the (on line 3):
If IsError(Intersect(filterRange, filterRange.Offset(1, 0)).SpecialCells(xlCellTypeVisible)) = False Then
But it does not work.
I also tried:
If Not IsError(Intersect(filterRange, filterRange.Offset(1, 0)).SpecialCells(xlCellTypeVisible)) Then
Set filterRange = Worksheets("JO_Pickups (Test)").Range("$A$1:$E$" & Total_rows_JOPickTest) 'filter for less computations
filterRange.AutoFilter Field:=2, Criteria1:=JO_id(i)
If IsError(Intersect(filterRange, filterRange.Offset(1, 0)).SpecialCells(xlCellTypeVisible)) = False Then
    Set filteredRange = Intersect(filterRange, filterRange.Offset(1, 0)).SpecialCells(xlCellTypeVisible) 'remove headers
    If Not filteredRange Is Nothing Then
        For Each Area In filteredRange.Areas
            Worksheets("JO_Pickups (Test)").Range(Area.Address).Copy _
            Destination:=Worksheets("Help Worksheet").Cells(2, 1)
        Next Area
    End If
End If

A: You can't trap a runtime error using IsError(), so you need something like:
Dim visRng As Range

On Error Resume Next
Set visRng = filterRange.Offset(1, 0)).SpecialCells(xlCellTypeVisible)
On Error Goto 0

If Not visRng is Nothing Then
    'do stuff...
End If


text:
Q: nested brace-enclosed initializer lists My code generates a syntax error with GCC :

src/main.cpp: In function 'int main()': src/main.cpp:95:4: error:
could not convert '{{"enum", E_PRINT}, {"string", "setup"}, {"object",
{{"double", 3.1415926535897931e+0}, {"long", 1235813l}}}}' from
'<brace-enclosed initializer list>' to 'Object'
};

#include <cmath>
#include <initializer_list>
#include <iostream>
#include <memory>
#include <sstream>
#include <string>
#include <vector>

#include <stdlib.h>

struct NamedValueBase {

   NamedValueBase( const std::string & name ) :
      name( name )
   {}

   virtual ~ NamedValueBase( void ) {}

   std::string name;
};

template<class T>
struct NamedValue : public NamedValueBase {

   NamedValue( const std::string & name, const T & value ) :
      NamedValueBase( name ),
      value( value )
   {}

   T value;
};

typedef std::shared_ptr<NamedValueBase> sharedPair;

struct Object {

   Object( void ) {}

   Object( std::initializer_list<sharedPair > attributes ) :
      pairs( std::vector<sharedPair >(
         attributes.begin(), attributes.end() ))
   {}

   template<class T>
   void add( const std::string & name, const T & value ) {
      pairs.push_back(
         sharedPair(
            new NamedValue<T>( name, value )));
   }

   void add( sharedPair nvb ) {
      pairs.push_back( nvb );
   }

   std::vector<sharedPair > pairs;
};

template<class T>
sharedPair create( const std::string & name, T value ) {
   return sharedPair( new NamedValue<T>( name, value ));
}

inline sharedPair create(
   const std::string &                name,
   std::initializer_list<sharedPair > attributes )
{
   return sharedPair(
      new NamedValue<Object>( name, Object( attributes )));
}

enum e {
   E_PRINT
};

int main() {
   // First form: OK
   Object msg = {
      create( "enum"  , E_PRINT ),
      create( "string", "setup" ),
      create( "object", {
         create(  "double", M_PI ),
         create(  "long"  , 1235813L )}
      )
   };
   std::cout << msg.pairs.size() << std::endl;

   // Second form: error: could not convert '{{"enum"...5813l}}}}' from
   // '<brace-enclosed initializer list>' to 'Object'
   Object msg2 = {
      { "enum"  , E_PRINT },
      { "string", "setup" },
      { "object", {
         {  "double", M_PI     },
         {  "long"  , 1235813L }}
      }
   };
   std::cout << msg2.pairs.size() << std::endl;
   return EXIT_SUCCESS;
}
// g++ -std=c++11 src/main.cpp -o object

Compilation and execution of the first form works well but I wish to enable the second form using parameter pack syntax i.e.
template<T...Args>

A: It can't be implemented with a template parameter pack because a nested initializer list is a non-deduced context.
The trick is to implement an intermediate "builder" class using a templated constructor and a constructor accepting a list of itself to handle the nested case:
struct pairBuilder {
    sharedPair ptr;

    template<typename T>
    pairBuilder(const std::string & name, const T & value) : ptr(create(name, value))
    {}

    pairBuilder(const std::string & name, std::initializer_list<pairBuilder> values) :
        ptr(create(name, values))
    {}
};

And then accept a list of them inside Object:
struct Object {

    Object(std::initializer_list<pairBuilder> values) {
        for (auto& t : values)
            add(t.ptr);
    }

    // . . .

This works because in this case the normal deduction from a type happens during overload resolution, essentially "unwrapping" each braced-init-list.
Complete example:
#include <cmath>
#include <initializer_list>
#include <iostream>
#include <memory>
#include <sstream>
#include <string>
#include <vector>

struct NamedValueBase {

    NamedValueBase(const std::string & name) :
        name(name)
    {}

    virtual ~NamedValueBase(void) {}

    std::string name;
};

typedef std::shared_ptr<NamedValueBase> sharedPair;

template<class T>
sharedPair create(const std::string & name, T value);

struct pairBuilder {
    sharedPair ptr;

    template<typename T>
    pairBuilder(const std::string & name, const T & value) : ptr(create(name, value)) {
    }

    pairBuilder(const std::string & name, std::initializer_list<pairBuilder> values) : ptr(create(name, values)) {
    }
};

template<class T>
struct NamedValue : public NamedValueBase {

    NamedValue(const std::string & name, const T & value) :
        NamedValueBase(name),
        value(value)
    {}

    T value;
};

struct Object {

    Object(void) {}

    Object(std::initializer_list<sharedPair> attributes) :
        pairs(std::vector<sharedPair >(
            attributes.begin(), attributes.end()))
    {}

    Object(std::initializer_list<pairBuilder> values) {
        for (auto& t : values)
            add(t.ptr);
    }

    template<class T>
    void add(const std::string & name, const T & value) {
        pairs.push_back(
            sharedPair(
                new NamedValue<T>(name, value)));
    }

    void add(sharedPair nvb) {
        pairs.push_back(nvb);
    }

    std::vector<sharedPair> pairs;
};

template<class T>
sharedPair create(const std::string & name, T value) {
    return sharedPair(new NamedValue<T>(name, value));
}

inline sharedPair create(
    const std::string &                name,
    std::initializer_list<pairBuilder> values)
{
    return sharedPair(
        new NamedValue<Object>(name, Object(values)));
}

enum e {
    E_PRINT
};

int main() {
    Object msg2 = {
      { "enum"  , E_PRINT },
      { "string", 2.0 },
        { "object", {
          {  "double", 3.14     },
          {  "long"  , 1235813L }}
        }
    };
    std::cout << msg2.pairs.size() << std::endl;
    return EXIT_SUCCESS;
}


text:
Q: What's wrong with this simple CREATE TABLE? What's wrong with this query ? MySQL doesn't like longblob anymore ??
mysql> CREATE TABLE WGS(1 longblob);
ERROR 1064 (42000): You have an error in your SQL syntax; check the manual that corresponds to your MySQL server version for the right syntax to use near '1 longblob)' at line 1

Edit: I changed the column for a Letter it doesn't work as well. Mysql seems to allow only at least 3 characters for column's name..

A: -- EDIT from my original answer, it was completely wrong, sorry about that --
MySQL requires you to quote your table column if it's solely digits:
http://dev.mysql.com/doc/refman/5.0/en/identifiers.html

Identifiers may begin with a digit but unless quoted may not consist solely of digits

I'd suggest changing the naming though, it's quite irritating having to quote your identifier everytime
`1` longblob

A: CREATE TABLE `test`.`WGS` (
`1` LONGBLOB NOT NULL
) ENGINE = InnoDB;

this is correct syntax.

A: Try this it should work:
 CREATE TABLE WGS(`1` LONGBLOB);

A: CREATE TABLE "table_name"
("column_name" "data_type_for_column_name") and instead you have 1 for column_name. It must be alphanumeric with a letter as a first symbol.