text:
Q: Is there a more efficient way to clean up my CCNodes? Is there a more efficient way to clean up my CCNodes? I'm calling this function (and others like it for different game objects), on a timer.
- (void)pulseBullets:(NSMutableArray *)bs targets:(NSArray *)targets {
    for (Bullet *b in bs) {
        for (QuantumPilot *p in targets) {
            if (p.active) {
                [p processBullet:b];
                if (!p.active) {
                    [self processKill:p];
                }
            }
        }
    }

    NSMutableArray *bulletsToErase = [NSMutableArray array];
    for (Bullet *b in bs) {
        [b pulse];
        if ([self bulletOutOfBounds:b]) {
            [bulletsToErase addObject:b];
        }
    }

    for (Bullet *b in bulletsToErase) {
        [b removeFromParentAndCleanup:YES];
    }

    [bs removeObjectsInArray:bulletsToErase];
}

A: Ok, but i make no 'statement' on performance, you will have to measure that for yourself. If you iterate a mutable array in reverse order, it is safe to delete an object during the iteration, because the iterator will not be invalidated by the deletion. So you could get rid altogther of the bullets to erase array like so :
for (Bullet *b in [bs reverseObjectEnumerator]) {  // *** do not change iteration order ***
    for (QuantumPilot *p in targets) {
        if (p.active) {
            [p processBullet:b];
            if (!p.active) {
                [self processKill:p];
            }
        }
    }

    [b pulse];
    if ([self bulletOutOfBounds:b]) {
        [b removeFromParentAndCleanup:YES];
        [bs removeObject:b];
    }
}

this is simpler , but obfuscates the inherent risk of altering an array content during iteration. You make the call as to whether it is 'cleaner'. Also, maybe the 'cost' of reversing the iterator is higher that what you save, as i said you would have to measure it.


text:
Q: How do I exclude my break statement from this list? Beginner coder here trying to get past a challenge. I'm trying to write a program that prompts the user for a list of numbers and then prints the maximum and minimum values from that list. I realize that there are built in functions to do this in Python but I have defined my own to try and better grasp the logic and how the language works. Here is what I have so far:
def find_largest_number(nums):
    largest_number = nums[0]
    for number in nums:
        if number > largest_number:
            largest_number = number
    return largest_number

def find_min_number(nums):
    min_number = nums[0]
    for number in nums:
        if number < min_number:
            min_number = number
    return min_number

nums = []
while True:
    num = input("> ")
    nums.append(num)
    if num == 'done':
        break
    try:
        value = int(num)
    except ValueError:
        print('Invalid input')
        continue

print(find_largest_number(nums))
print(find_min_number(nums))

If I run this code I can successfully get the minimum number, however the break statement 'done' is always returned as the largest number. Is there a way to exclude it from the functions or something else that I am missing? I have tried adding an int() before the num in both of the functions but this just causes the program to crash with the following error: TypeError: '>' not supported between instances of 'int' and 'str'
location:
def find_largest_number(nums):
    largest_number = nums[0]
    for number in nums:
        if int(number) > largest_number:
            largest_number = number
    return largest_number

A: You want to move the line nums.append(num) so that it goes right after the line value = int(num) and then edit it so that it reads nums.append(value) instead.
Currently, you are appending the input num to the list before checking to see if it is really the signal value "done".  You really want to wait until after verifying that it is not "done" before appending.
Secondly, you want to convert the num to an actual number (an int) which you are already doing when you say value = int(num).  Now, value is the integer (numeric) version of the input, and that is what you really want to append to your list.
The problem with not converting the num from a string to an int is that the comparison operators like < and > work differently on strings and ints.  Strings are compared using alphabetical order, and so, for example, 'b' goes after 'aa'.  But if these were numbers, we would want the opposite behavior, since 2 should come before 11.

redpajama_set_name: RedPajamaStackExchange


text:
Q: How to deep copy a map with initial capacity? Serialization and deserialization have been a preferred and accepted method of deep copying objects with complicated graphs (How do you make a deep copy of an object in Java? etc.) where the copy constructor/factory method approach is not well suited.
However, this approach does not work with maps that specified an initial capacity. My previous question on this (Why does specifying Map's initial capacity cause subsequent serializations to give different results?) shows that the resulting objects are not equal, and the answer shows that their byte representation is different: if serializing gives byte[] b1, then deserializing and serializing again will give byte[] b2 which is different from b1 (at least 1 element is different). This is in contrast to the usual behavior of de/serializing objects.
The readObject and writeObject methods that control the de/serialization process are private and so cannot be overriden - this was probably done on purpose (Hashmap slower after deserialization - Why?).
I am using the de/serialization deep copy approach on an object holding many other objects, including maps. I am also performing comparison and changes on their byte array representation. As long as the maps are not initialized with the initial capacity parameter, all works well. However, attempting to optimize the maps by specifying the initial capacity breaks this approach as mentioned above.
I would like to know if it's possible to circumvent this issue and if so how.

A: Ok, so, first of all, you're barking up the wrong tree by focusing on the fact that specifying an initial capacity leads to different serialized bytes. In fact, if you look at the difference:

pbA from your example:
: ac ed 00 05 73 72 00 0f 71 33 39 31 39 33 34 39   ....sr..q3919349
: 34 2e 53 74 61 74 65 00 00 00 00 00 00 00 01 02   4.State.........
: 00 01 4c 00 04 6d 61 70 73 74 00 10 4c 6a 61 76   ..L..mapst..Ljav
: 61 2f 75 74 69 6c 2f 4c 69 73 74 3b 78 70 73 72   a/util/List;xpsr
: 00 13 6a 61 76 61 2e 75 74 69 6c 2e 41 72 72 61   ..java.util.Arra
: 79 4c 69 73 74 78 81 d2 1d 99 c7 61 9d 03 00 01   yListx.....a....
: 49 00 04 73 69 7a 65 78 70 00 00 00 01 77 04 00   I..sizexp....w..
: 00 00 01 73 72 00 14 71 33 39 31 39 33 34 39 34   ...sr..q39193494
: 2e 4d 61 70 57 72 61 70 70 65 72 00 00 00 00 00   .MapWrapper.....
: 00 00 01 02 00 01 4c 00 03 6d 61 70 74 00 0f 4c   ......L..mapt..L
: 6a 61 76 61 2f 75 74 69 6c 2f 4d 61 70 3b 78 70   java/util/Map;xp
: 73 72 00 11 6a 61 76 61 2e 75 74 69 6c 2e 48 61   sr..java.util.Ha
: 73 68 4d 61 70 05 07 da c1 c3 16 60 d1 03 00 02   shMap......`....
: 46 00 0a 6c 6f 61 64 46 61 63 74 6f 72 49 00 09   F..loadFactorI..
: 74 68 72 65 73 68 6f 6c 64 78 70 3f 40 00 00 00   thresholdxp?@...
: 00 00 02 77 08 00 00 00 02 00 00 00 00 78 78      ...w.........xx

zero from your example:
: ac ed 00 05 73 72 00 0f 71 33 39 31 39 33 34 39   ....sr..q3919349
: 34 2e 53 74 61 74 65 00 00 00 00 00 00 00 01 02   4.State.........
: 00 01 4c 00 04 6d 61 70 73 74 00 10 4c 6a 61 76   ..L..mapst..Ljav
: 61 2f 75 74 69 6c 2f 4c 69 73 74 3b 78 70 73 72   a/util/List;xpsr
: 00 13 6a 61 76 61 2e 75 74 69 6c 2e 41 72 72 61   ..java.util.Arra
: 79 4c 69 73 74 78 81 d2 1d 99 c7 61 9d 03 00 01   yListx.....a....
: 49 00 04 73 69 7a 65 78 70 00 00 00 01 77 04 00   I..sizexp....w..
: 00 00 01 73 72 00 14 71 33 39 31 39 33 34 39 34   ...sr..q39193494
: 2e 4d 61 70 57 72 61 70 70 65 72 00 00 00 00 00   .MapWrapper.....
: 00 00 01 02 00 01 4c 00 03 6d 61 70 74 00 0f 4c   ......L..mapt..L
: 6a 61 76 61 2f 75 74 69 6c 2f 4d 61 70 3b 78 70   java/util/Map;xp
: 73 72 00 11 6a 61 76 61 2e 75 74 69 6c 2e 48 61   sr..java.util.Ha
: 73 68 4d 61 70 05 07 da c1 c3 16 60 d1 03 00 02   shMap......`....
: 46 00 0a 6c 6f 61 64 46 61 63 74 6f 72 49 00 09   F..loadFactorI..
: 74 68 72 65 73 68 6f 6c 64 78 70 3f 40 00 00 00   thresholdxp?@...
: 00 00 00 77 08 00 00 00 01 00 00 00 00 78 78      ...w.........xx

The only difference is the couple of bytes that specify load factor and such. Obviously, these bytes would be different - of course they would if you specify a different initial capacity that was ignored by the first deserialization. This is a red herring.
You are concerned about a corrupt deep copy, but this concern is misplaced. The only thing that matters, in terms of correctness, is the result of the deserialization. It just needs to be a correct, fully functional deep copy that doesn't violate any of your program's invariants. Focusing on the precise serialized bytes is a distraction: You don't care about them, in fact you only care that the result is correct.
Which brings us to the next point:
The only real issue you face here is a difference in long term performance (both speed and memory) characteristics from the fact that some Java versions ignore the initial map capacity when deserializing. This does not affect your data (that is, it will not break invariants), it only potentially affects performance.
So your very first step is to ensure that this is actually a problem. That is, it boils down to a potential premature optimization issue: Ignore the difference in the deserialized map's initial capacity for now. If your application runs with sufficient performance characteristics then you have nothing else to worry about. If it doesn't, and if you are able to narrow the bottlenecks down to decreased deserialized hash map performance due to a different initial capacity, only then should you approach this problem.
And so, the final part of this answer is, if you determine that the performance characteristics of the deserialized map actually are insufficient, there are a number of things you can do.
The simplest, most obvious one I can think of is to implement readResolve() on your object, and take that opportunity to:

*

*Construct a new map with the appropriate parameters (initial capacity, etc.)

*Copy all of the items from the old deserialized map to the new one.

*Then discard the old map and replace it with your new one.

Example (from your original code example, choosing the map that yielded the "false" result):
class MapWrapper implements Serializable {

    private static final long serialVersionUID = 1L;

    Map<String, Integer> map = new HashMap<>(2);

    private Object readResolve () throws ObjectStreamException {
        // Replace deserialized 'map' with one that has the desired
        // capacity parameters.
        Map<String, Integer> fixedMap = new HashMap<>(2);
        fixedMap.putAll(map);
        map = fixedMap;
        return this;
    }

}

But first question if this is really causing issues for you. I believe you are overthinking it, and that hyper-focusing on the byte-for-byte serialized data comparison is not productive for you.


text:
Q: How to add authentication to a Google apps script without it expiring? I have a Google apps script project which I use as a web application to save some data gathered from a web page (JavaScript only) to My Google sheets (think of it as a simple database for just me).
It's no need to use auth for anyone else other than my account, because, I don't use their accounts/data for anything at all. I just need to use my account only, so, when I deploy it, I make it execute as me, and accessible to anyone:

.
When I click deploy after previous screen, it asks for my permission (the consent dialogue) to access my account's data, which I grant it, and after that everything is good, and the HTTP requests to this script works just fine.

.
The problem is:
This authentication expires after maybe 7 days (I'm not sure) and the script stops working, I discover that when the HTTP requests to it return error 403
To fix that and make it work again, I need to run the script again from the Google apps script editor which asks for the permissions (consent) again:

.
I can't use it like that and the web page stop working when the authentication gets revoked!
I'm not publishing the script (I don't want/don't need to). Do I?
My question is, how can I add the authentication in a way that makes it lasts and stops asking me for it over and over again?

The script on Google apps script works like this:
function doPost(request) {
  return checkRequest(request);
}

function checkRequest(request) {
  //check the request & save the sent data to a google sheet here;
  //...

    return sendResponse({
      success: true,
      data: {result: 'Saved the data!' }
    });
}

function sendResponse(response) {
  return ContentService
    .createTextOutput(JSON.stringify(response))
    .setMimeType(ContentService.MimeType.JSON);
}

And I call it from the web page using Ajax HTTP POST request, like this:
jQuery.ajax({
    url: 'https://script.google.com/macros/s/{script-id}/exec',
    method: 'POST',
    dataType: "json",
    data: {key: 'value'},
    success: function (response) {
        console.log(response);
    },
    error: function (response) {
        console.error(response);
    }
});

And this is the response the script returns after few days when the authentication expires:

A: This has been reported to Google
There is already a report on Google's Issue Tracker which detail the same kind of behaviour:

*

*Random Deauthorizations for script since Editor Update with no changes to code
Google does seem to know about this issue. From the issue tracker link, a response was given:

[...] reviewing the documentation, it reads:

Authorizations by a test user will expire seven days from the time of consent.
Source

So I'm not sure we should expect anything different from these tests.
Also re-reading this thread, in your first comment you said that this was affecting projects that already published. Though I understand that you fixed the original projects that were having issues by un-linking the GCP projects.
A possible fix would be filling the scopes manually in the manifest for these types of issues. This is because Apps Script tries to infer the scopes needed at runtime, and sometimes this can result in Apps Script trying to gain more permissive scope than what is authorized.
See Setting Explicit Scopes
However, token expiry in around 7 days is to be expected for projects in "testing" state.

Which seems to be the case for the users in the report thread.
There are multiple reasons that this expiration may occur, as explained in the Using OAuth 2.0 to Access Google APIs page.
That being said, if it's causing problems you can file your own bug about it here in the Google Apps Script component.
References:

*

*Random Deauthorizations for script since Editor Update with no changes to code

*Using OAuth 2.0 to Access Google APIs | Google Identity

*Setting up your OAuth consent screen - Google Cloud Platform Console Help

*Authorization Scopes - Setting explicit scopes | Apps Script | Google Developers


text:
Q: Writing Truly Private Functions in Javascript I want to write a function that gives me control over what API's it can execute.
For example, how would I write an anonymous function that privately executes without jQuery after jQuery has been loaded into the page:
var app = (function(){
  $("body").append("should not append because it does not recognize jQuery");
})();

instead of
var app = (function(){
  $("body").append("should append because jQuery is recognized");
})(jQuery);

A: Expanding on what Nasser said, you can declare (locally) the things you want to disallow as undefined variables:
// allow jQuery
(function () { // don't overwrite $ or jQuery, so it's allowed, basically
    $("body").append("should append because jQuery is recognized");
}());

// disallow jQuery
(function ($, jQuery) { // declare $ and jQuery as undefined in the function scope
    // the line below will throw an error, though
    $("body").append("should not append because it does not recognize jQuery");
}());

You can further expand on this, but that's the general idea.


text:
Q: limit number file selections in a file input Is there a way to limit the number of files you can select using the input file plus the multiple attribute.
<input type="file" accept="image/*" multiple/>

I am aware of one approach that is to check the length of files after selection using the onChange event. While this works I would like to prevent user from selecting more than 5 image files in the file select dialog phase.
Is this possible?

A: Unfortunately there is no way if limiting the input field as specified in W3C. At least not without Javascript. The following would work but is probably not as nice as you would have liked:
<input type="file" onchange="checkFiles(this.files)">

function checkFiles(files) {
    if(files.length>5) {
        alert("length exceeded");
        files.slice(0,5);
        return false;
    }
}


text:
Q: extra closing bracket in xml I am using this example to save some variables to an xml file:
how do I set the current class to the return types results
This is my code for the settings file:
using System;
using System.IO;
using System.Xml.Serialization;

namespace ssscc.Settings
{
  public class AppSettings
  {
    public string ReceiptLine1 { set; get; }
    public string ReceiptLine2 { set; get; }
    public string ReceiptLine3 { set; get; }
    public string ReceiptLine4 { set; get; }
    public string ReceiptLine5 { set; get; }
    public string ReceiptLine6 { set; get; }
    public bool ReceiptLine1Enabled { set; get; }
    public bool ReceiptLine2Enabled { set; get; }
    public bool ReceiptLine3Enabled { set; get; }
    public bool ReceiptLine4Enabled { set; get; }
    public bool ReceiptLine5Enabled { set; get; }
    public bool ReceiptLine6Enabled { set; get; }

    public string GatewayUserName { set; get; }
    public string GatewayPassword { set; get; }
    public string GatewayId { set; get; }

    private static string GetSettingsFile()
    {
      var exePath = System.Windows.Forms.Application.StartupPath;
      var sharedDirectory = Path.Combine(exePath, "shared");
      var settingsDirectory = Path.Combine(sharedDirectory, "settings");
      var settingsFile = Path.Combine(settingsDirectory, "ssscc.xml");

      if (!Directory.Exists(sharedDirectory))
      {
        Directory.CreateDirectory(sharedDirectory);
      }

      if (!Directory.Exists(settingsDirectory))
      {
        Directory.CreateDirectory(settingsDirectory);
      }

      return settingsFile;
    }

    internal void SaveSettings()
    {
      var serializer = new XmlSerializer(typeof(AppSettings));
      using (var stream = File.OpenWrite(GetSettingsFile()))
        serializer.Serialize((Stream)stream, this);
    }

    internal static AppSettings GetInstance()
    {
      try
      {

      if (!File.Exists(GetSettingsFile()))
        return null;

      var serializer = new XmlSerializer(typeof(AppSettings));
      using (var stream = File.OpenRead(GetSettingsFile()))
      {
        return (AppSettings)serializer.Deserialize(stream);
      }

      }
      catch (Exception ex)
      {
        Console.WriteLine(ex.Message);
        throw;
      }
    }

  }
}

When I save the data the, the initial save goes fine and at the end of the file it shows:
<?xml version="1.0"?>
<AppSettings xmlns:xsi="http://www.w3.org/2001/XMLSchema-instance" xmlns:xsd="http://www.w3.org/2001/XMLSchema">
  <ReceiptLine1 />
  <ReceiptLine2 />
  <ReceiptLine3 />
  <ReceiptLine4 />
  <ReceiptLine5 />
  <ReceiptLine6 />
  <ReceiptLine1Enabled>false</ReceiptLine1Enabled>
  <ReceiptLine2Enabled>true</ReceiptLine2Enabled>
  <ReceiptLine3Enabled>false</ReceiptLine3Enabled>
  <ReceiptLine4Enabled>false</ReceiptLine4Enabled>
  <ReceiptLine5Enabled>false</ReceiptLine5Enabled>
  <ReceiptLine6Enabled>false</ReceiptLine6Enabled>
  <GatewayUserName>asdfasdf</GatewayUserName>
  <GatewayPassword>asdf</GatewayPassword>
  <GatewayId>sdf</GatewayId>
</AppSettings>

When I update the file and save it again, I end up with this:
<?xml version="1.0"?>
<AppSettings xmlns:xsi="http://www.w3.org/2001/XMLSchema-instance" xmlns:xsd="http://www.w3.org/2001/XMLSchema">
  <ReceiptLine1 />
  <ReceiptLine2 />
  <ReceiptLine3 />
  <ReceiptLine4 />
  <ReceiptLine5 />
  <ReceiptLine6 />
  <ReceiptLine1Enabled>false</ReceiptLine1Enabled>
  <ReceiptLine2Enabled>true</ReceiptLine2Enabled>
  <ReceiptLine3Enabled>false</ReceiptLine3Enabled>
  <ReceiptLine4Enabled>false</ReceiptLine4Enabled>
  <ReceiptLine5Enabled>false</ReceiptLine5Enabled>
  <ReceiptLine6Enabled>false</ReceiptLine6Enabled>
  <GatewayUserName>asdfasdf</GatewayUserName>
  <GatewayPassword>asdf</GatewayPassword>
  <GatewayId>sdf</GatewayId>
</AppSettings>>

Which it see two >> at the end.
Anyone see why it's saving two >> at the end of my xml file?
And my code errors out with:

A: It's because you're using File.OpenWrite:

For an existing file, it does not append the new text to the existing text. Instead, it overwrites the existing characters with the new characters. If you overwrite a longer string (such as "This is a test of the OpenWrite method") with a shorter string (such as "Second run"), the file will contain a mix of the strings ("Second runtest of the OpenWrite method").

While it's not clear from your example, I suspect the new contents are one byte shorter than the old contents, so you're seeing the closing angle bracket from the original file.
I suspect you should just use File.Create instead.


text:
Q: Woocommerce payment gateway webhook doesn't work I will be very grateful for any help. I'm trying to create a custom payment gateway for WooCommerce. The problem is in the callback function, I cannot process the response from the payment system. I set up payment, everything works fine, but I can't get a response from payment system and complete the order on my site. Please, help
<?php

        public function generate_form($order_id)
        {
            //GET MERCHANT ID FROM SETTINGS
            $merch_id = $this -> merchant_id;

            // GET ORDER
            $order = new WC_Order($order_id);

            // GET AMMOUNT
            $sum = $order->get_total();

            // format the amount
            $sum = number_format($sum, 0, '.', '');

            // GET CURRENCY
            $currency = $this->currency_type;

            // GET SECRET KEY FROM SETTINGS
            $secretKey = $this->merchant_secretkey;

            $description = sprintf(__('Payment for Order #%1$s', 'payme'), $order_id);

            $label_pay = __('Pay', 'payme');
            $label_cancel = __('Cancel payment and return back', 'payme');

            // Generating a digital signature in PHP (EXAMPLE FROM PAYMENT SYSTEM DOCS)
            function getFormSignature($merch_id, $currency, $sum, $order_id, $secretKey) {
             $hashStr = $merch_id.'{up}'.$currency.'{up}'.$sum.'{up}'.$order_id.'{up}'.$secretKey;
             return hash('sha256', $hashStr);
            }

            $signature = getFormSignature($merch_id, $currency, $sum, $order_id, $secretKey);

            $form = <<<FORM
<form action="{$this->checkout_url}" method="get">
    <input id="amount" name="amount" type="hidden" value="$sum" />
    <input id="act "name="act" type="hidden" value="request_payment" />
    <input id="test" name="test" type="hidden" value="{$this->test_mode}" />
    <input id="form" name="form" type="hidden" value="Y" />
    <input id="coin" name="coin" type="hidden" value="{$this->coin_type}" />
    <input id="id" name="id" type="hidden" value="$merch_id" />
    <input id="currency" name="currency" type="hidden" value="$currency" />
    <input id="external_invoice" name="external_invoice" type="hidden" value="$order_id" />
    <input id="message" name="message" type="hidden" value="$description" />
    <input id="signature" name="signature" type="hidden" value="$signature" />
    <input type="submit" class="button alt" id="submit_payme_form" value="$label_pay">
    get_cancel_order_url()}">$label_cancel
</form>
FORM;

            return $form;
        }

        public function process_payment($order_id)
        {
            $order = new WC_Order($order_id);

            return [
                'result' => 'success',
                'redirect' => add_query_arg(
                    'order_pay',
                    $order->get_id(),
                    add_query_arg('key', $order->get_order_key(), $order->get_checkout_payment_url(true))
                )
            ];

        }

        public function receipt_page($order_id)
        {
            echo '
' . __('Thank you for your order, press "Pay" button to continue.', 'payme') . '
';
            echo $this->generate_form($order_id);
        }

        /**
         * CALLBACK FUNCTION. THE REQUESTS SENT FROM PAYMENT SYSTEM TO MY CALLBACK URL https://example.com/?wc-api=wc_custom
         */
        public function custom_webhook()
        {

            $order = new WC_Order($order_id);

            $id = $this -> merchant_id;
            $currency = $this->currency_type;
            $secretKey = $this->merchant_secretkey;
            $amount_in_currency = $order->get_total();

            /**
            * INSTRUCTION FROM DOCS:
            * When we receive an invoice payment, we notify the merchant website of the payment status by sending a GET request to the handler URL (callback_url parameter).
            * In the payment processor, you must generate a digital signature using the received variables and check it against the received digital signature.
            */

            // CODE EXAMPLE FORM DOCS. An example of generating and verifying a digital signature in PHP

            function getSignature($id, $currency, $amount_in_currency, $order_id, $secretKey) {
             $hashStr = $id.'{up}'.$currency.'{up}'.$amount_in_currency.'{up}'.$order_id.'{up}'.$secretKey;
             return hash('sha256', $hashStr);
            }

            $signature = getSignature($_GET["id"], $_GET["currency"], $_GET["amount_in_currency"], $_GET["external_invoice"], $secretKey);

            if ($_GET["signature"] != $signature){
                $order->payment_complete();
                WC()->cart->empty_cart();
            }
                exit('Incorrect Digital Signature');

            // ERROR. WEBHOOK RESPONSE: Response - HTTP CODE: 400 DATA: -1
        }

?>

I am getting a 400 response error and cannot process the order on the site. What should I do please help!(


text:
Q: Eclipse long build time for java project EDIT: The solution was as follows: Disabling egit solved the building problem. For some reason, egit causes the build process to hang for many minutes.
I have a problem when I need to rebuild my java project. Our project takes 12 minutes to compile with "clean project" in eclipse. It will hang very long on a somewhat random percentage. There should in theory be no buildling cycles, and I have set "Max iterations when building with cycles" to 1 just in case.
I thought I had a nice solution to find out where it stopped: I wrote a small program to analyze the generated .class files too see which class-files it stops on for so long. So I wrote the attached program which sorts the generated .class -files by modifieddate
Guess if I was surprised with the results!
The build started around 12:20:40 and was finished 12:32:40
The first of the 4458 class-files was generated 12:20:42, and the last was generated 12:21:22
So the entire build took 40 seconds. So what the beep is eclipse doing those last 11 minutes??
import java.io.File;
import java.util.*;

public class AnalyzeBuildTime {

public static void main(String[] args) throws Exception{
    File dir = new File(path_to_project);
    Vector<File> v = new Vector<File>();
    parse(v,dir);
    System.out.println("Nr of files: "+v.size());
    Collections.sort(v,new Comparator<File>() {
        public int compare(File o1, File o2) {
            return new Long(o1.lastModified()).compareTo(o2.lastModified());
        }
    });
    System.out.println("Listing");
    for (File f : v) {
        System.out.println(f.getName()+"\t"+getTimeString(f.lastModified()));
    }
}

private static void parse(Vector<File> v, File f) throws Exception{
    if (f.isDirectory()) {
        for (File ff : f.listFiles()) {
            parse(v,ff);
        }
    }
    else if (f.getName().endsWith(".class")){
        v.addElement(f);
    }
}

public static String getTimeString(long l){
    Calendar c = Calendar.getInstance();
    c.setTimeInMillis(l);
    return zero(c.get(Calendar.HOUR_OF_DAY))+":"+zero(c.get(Calendar.MINUTE))+":"+zero(c.get(Calendar.SECOND));
}

private static String zero(int i) {
    if (i < 10) return "0"+i;
    return ""+i;
}
}

EDIT
Back from vacation, and have tried to understand this some more. I have now tried buildling my workspace via headless building ala:
eclipsec.exe -noSplash -application org.eclipse.jdt.apt.core.aptBuild -data c:\workspace

This seems to build fine for some time, displaying messages ala "(Found 4345 warnings) Compiling Diverse", then suddenly stops and hangs for about 4-5 minutes before continuing, continuing on "(Found 4346 warnings) Compiling Diverse" as if nothing has happened (and yes, it reaches a different warning count each time..)
Have tried profiling it with jvisualvm, but really does not know what I should be looking for. Some "Compiler Processing Task" threads are spawned in sequence, and the last "Compiler Processing Task" thread seems to be in wait mode when it hangs, with 0ms in "Running", and when the compiling eventually continues, this thread is stopped and a new "Compiler Processing Task" thread starts.
It should be noted that when compiling from command line, it compiles all my projects, and not only the big project that takes so much time from within eclipse, and it seems to be finished with the big 'Pos' project before it hangs on usually 'Diverse' or another project.
I just tried upgrading from eclipse neon to eclipse oxygen, but it seems to have the same behaviour.
EDIT2
Well, I've finally found a "solution", but I'm not that happy with it.
I'm using eclipse Neon (4.6.2), and have also tried switching to oxygen, but the problem persists.
I then tried building my project on my old computer running eclipse mars (4.5.2), and strangely enough did not experiance any build hangs. So I have copied my mars-eclipse from my old computer, and Clean on my big project now takes 55 seconds, and clean all takes 1:15. Still very interested in the reasons for the build hangs, so that I can use newer versions of eclipse.

A: Update: It turned out to be caused by the EGit plugin. The problem went away after disabling it.
(To see the path to debug this kind of performance problem, see the rest of the original answer)

There can be several reasons and I don't want to guess. But if you are interested to know what Eclipse is doing, there is a systematic approach to find it out, or at least bring you in a better position to solve the problem:

*

*Start Eclipse and attach VisualVM to the build process (in your case, Eclipse itself). VisualVM should be part of your JDK installation. If not, you it is freely available for download.

*Under Threads, there is the "Thread Dump" option, which will create a stack trace of all running threads

*Trigger the build and from time create thread dumps in VisualVM

*Analyze the stack traces and look for a pattern (i.e., a stack trace that shows up much more often)

From the stack-traces, you should hopefully see what Eclipse internally does. Statistically, even when you only look only at very few stack traces, it is very likely that it will reveal existing bottlenecks. For instance, I remember situations where it pointed me to specific plugins that I had installed (e.g. FindBugs). Removing them increased the performance again.
If it is still not clear what is going on, you can use the stack traces to add more details to your question, which would allow educated guesses. In the best case, you could even file a bug report. (Especially, when your code base is huge, it is not unlikely to run into bugs).
To show that the technique is effective for finding performance problems in IDEs, I want to mention that IntelliJ automatically dumps stack traces to disk whenever operations hang for a few seconds. They encourage users to file bug reports for performance issues, and ask them to attach the generated stack traces. It demonstrates that the information is very useful for someone who is familiar with the code base (or the code base of a plugin that shows up on top of the stack trace).
The technique is similar to conventional profiling, but it is often more effective in locating the bottleneck, especially if the bottleneck is obvious (which is likely the case in your scenario).
In addition, the stack trace of the slow path is highly useful when you need to ask for help. Analyzing a performance problem without having access to the machine is hard, but looking at a concrete example (given by the stack trace), can be a game changer.

Just to be sure, you should first rule out that the Java process is near the memory limit. VisualVM will list the GC activity in the Monitor tab. I don't think it is the problem in your case, but checking stack traces does not make sense if the application is more or less doing permanent garbage collects. In the worst case, it could even be misleading.

Update: Part of the thread dump, which drew attention to the problem and lead to the guess that EGit could be the problem (here, is the full thread dump):
"Worker-65" #196 prio=5 os_prio=0 tid=0x000000002a5d2800 nid=0x29534 runnable [0x0000000049f8e000]
   java.lang.Thread.State: RUNNABLE
    at sun.nio.fs.WindowsNativeDispatcher.GetFileAttributesEx0(Native Method)
    at sun.nio.fs.WindowsNativeDispatcher.GetFileAttributesEx(Unknown Source)
    at sun.nio.fs.WindowsFileAttributes.get(Unknown Source)
    at sun.nio.fs.WindowsFileAttributeViews$Basic.readAttributes(Unknown Source)
    at sun.nio.fs.WindowsFileAttributeViews$Basic.readAttributes(Unknown Source)
    at org.eclipse.jgit.util.FileUtils.getFileAttributesBasic(FileUtils.java:662)
    at org.eclipse.jgit.util.FS_Win32.getAttributes(FS_Win32.java:192)
    at org.eclipse.jgit.treewalk.FileTreeIterator$FileEntry.<init>(FileTreeIterator.java:365)
    at org.eclipse.jgit.treewalk.FileTreeIterator.entries(FileTreeIterator.java:242)
    at org.eclipse.jgit.treewalk.FileTreeIterator.<init>(FileTreeIterator.java:227)
    at org.eclipse.jgit.treewalk.FileTreeIterator.createSubtreeIterator(FileTreeIterator.java:233)
    at org.eclipse.jgit.treewalk.AbstractTreeIterator.createSubtreeIterator(AbstractTreeIterator.java:572)
    at org.eclipse.jgit.treewalk.TreeWalk.enterSubtree(TreeWalk.java:1210)
    at org.eclipse.egit.core.RepositoryUtil.canBeAutoIgnored(RepositoryUtil.java:720)
    at org.eclipse.egit.core.Activator$IgnoreDerivedResources$1.visit(Activator.java:646)
    at org.eclipse.core.internal.events.ResourceDelta.accept(ResourceDelta.java:64)
    at org.eclipse.core.internal.events.ResourceDelta.accept(ResourceDelta.java:75)
    at org.eclipse.core.internal.events.ResourceDelta.accept(ResourceDelta.java:75)
    at org.eclipse.core.internal.events.ResourceDelta.accept(ResourceDelta.java:75)
    at org.eclipse.core.internal.events.ResourceDelta.accept(ResourceDelta.java:48)
    at org.eclipse.egit.core.Activator$IgnoreDerivedResources.resourceChanged(Activator.java:622)
    at org.eclipse.core.internal.events.NotificationManager$1.run(NotificationManager.java:299)
    at org.eclipse.core.runtime.SafeRunner.run(SafeRunner.java:42)
    at org.eclipse.core.internal.events.NotificationManager.notify(NotificationManager.java:289)
    at org.eclipse.core.internal.events.NotificationManager.broadcastChanges(NotificationManager.java:152)
    at org.eclipse.core.internal.resources.Workspace.broadcastPostChange(Workspace.java:374)
    at org.eclipse.core.internal.resources.Workspace.endOperation(Workspace.java:1469)
    at org.eclipse.core.internal.events.AutoBuildJob.doBuild(AutoBuildJob.java:157)
    at org.eclipse.core.internal.events.AutoBuildJob.run(AutoBuildJob.java:235)
    at org.eclipse.core.internal.jobs.Worker.run(Worker.java:55)

"Worker-60" #191 prio=5 os_prio=0 tid=0x000000002a5d6800 nid=0x290c0 in Object.wait() [0x0000000049a8f000]
   java.lang.Thread.State: WAITING (on object monitor)
    at java.lang.Object.wait(Native Method)
    at java.lang.Object.wait(Unknown Source)
    at org.eclipse.core.internal.jobs.ThreadJob.waitForRun(ThreadJob.java:270)
    - locked <0x00000005c2362c50> (a java.lang.Object)
    at org.eclipse.core.internal.jobs.ThreadJob.joinRun(ThreadJob.java:197)
    at org.eclipse.core.internal.jobs.ImplicitJobs.begin(ImplicitJobs.java:92)
    at org.eclipse.core.internal.jobs.JobManager.beginRule(JobManager.java:307)
    at org.eclipse.egit.core.internal.indexdiff.IndexDiffCacheEntry.waitForWorkspaceLock(IndexDiffCacheEntry.java:466)
    at org.eclipse.egit.core.internal.indexdiff.IndexDiffCacheEntry.access$5(IndexDiffCacheEntry.java:458)
    at org.eclipse.egit.core.internal.indexdiff.IndexDiffCacheEntry$5.updateIndexDiff(IndexDiffCacheEntry.java:516)
    at org.eclipse.egit.core.internal.indexdiff.IndexDiffUpdateJob.run(IndexDiffUpdateJob.java:75)
    at org.eclipse.core.internal.jobs.Worker.run(Worker.java:55)

A: Why do you have 4346 warnings? That can't be good. I keep my projects 100% error and warning free. (Rootitootoot, yeah I know.) But that seems to me like it could be significant overhead, registering all those error messages and strings, especially if the code for doing so has a high "Big O" cost, e.g., if each warning checks previously generated warnings for duplicate elements. (I don't know if it does or not.) Might be worth investigating. Warnings could correlate with "stress" for the compilation process in ways that results in delays.
For better understanding the "Clean Project" process, and what the various stages are, I'd first check at the Eclipse community forums. I've found them to be very helpful. If you do so, posting here what you find out there would be helpful to others with the same problem, of course.

A: Try this:
Update "installed" java path in the eclipse.ini file with the given parameter.
-vm
C:/Program Files/Java/jdk1.8.0_131/bin/javaw.exe
Just try and tell me the difference if any found. :-)


text:
Q: How to handle 'Object': ambiguous symbol in Visual Studio I am creating a C++/CLI wrapper for native C code that has it's own Object typedef and am receiving the C2872 'Object': ambiguous symbol error when linking. The compiler output is:
1>C:\src\OS_kernel.h(27): error C2872: 'Object': ambiguous symbol
1>C:\src\OS_types.h(261): note: could be 'ObjectStruct *Object'
1>C:\src\OS_kernel.h(27): note: or       'System::Object'

It may be worth mentioning that I am mocking this native C code for the purposes of the C++/CLI wrapper; not sure if that opens up a potential solution that would otherwise not be available if no source code was available. I'm guessing there is a way to specify which definition I want the code to use, but I don't know how to specify that. Is that possible? I want to specify it to use the ObjectStruct *Object.
It would be great if I didn't have to modify the mock code since it could potentially be hundreds or thousands of individual places.
As an aside, I am also receiving this error for other types the native library is using, such as Buffer and Boolean.

A: OK, since you're getting the error in OS_kernel.h, I'm guessing that's part of the C code you're wrapping.
Obviously, one possible solution is to treat the name Object as a reserved word, and edit your C code to not use it. One could argue that this is the most correct solution, but it may not be possible to do that.
Depending on how you're referencing the C code, it may be reasonable to compile it as C++, and stick it entirely within a namespace. That way, when the C code (now C++ code) uses Object it will see the typedef within its namespace, and you'll have the option to reference either namespace in your code.
The fact that you're getting this error from your library's header file indicates to me that you've got a using namespace System; directive, and that the #include of your library's header files comes after that using directive. Consider removing the using namespace System;, or at least moving it after the #include. This way, you won't get that error in the library's headers, you'll just have to deal with it in your code.


text:
Q: Where is the redstone dust in the tools section? Where can I find the redstone dust in the creative inventory? I have Minecraft: Pocket Edition.

A: Second row, second column (under the sword tab):

Picture from the Pocket Edition Wiki

A: You can find it in the materials section of your inventory.


text:
Q: Calling a variable by a variable excel I wondering how I can use a variable to call another variable. For example Apple1, Apple2, Apple3, Apple4, Apple5, Apple6 and AppleNum.
Let us say AppleNum is 4. How can I use AppleNum to call for the code to use Apple4?
Also, What if Apple1, Apple2...ect are objects?
My first thought on how to solve this was by using some sort of Array?
Note: Using Select Case here will work but doesn't simply the code I have and would require each case to be written out individually (a lot of work)
Just out of interest, ts there a way to define AppleNum number of variables in the code?
If you can help, Thanks!

A: It is possible to have an array of variable size in VBA, using the following (for example):
Dim myArray() as Double
Dim AppleNum as Integer, arraySize as Integer
AppleNum = 4
arraySize = 6

ReDim myArray(1 to arraySize)

this would create an array myArray, and change its size to be 6 elements long (with index starting at 1).  You can declare the entire array in one statement (without redimensioning) with
myArray = Array(Apple1, Apple2, Apple3, Apple4, Apple5, Apple6)

Assuming that Apple1 etc. have been previously declared.
If you declare myArray as Variant rather than Integer (or don't give a type - defaults to Variant) then your array can contain anything you want.
You can also use
ReDim Preserve myArray(1 to arraySize * 2)

if at a later point you want the array to be twice as large, but you don't want to lose the first six elements you had assigned.
I hope these things will get you moving with your problem.


text:
Q: Jquery predefined textarea wont clear Prefilling a textarea with data pulled from a DB.
<textarea name="body" id="body" rows="5" cols="70"><? echo $body; ?></textarea>
I have a clear button to make it easier for the user to wipe a large chunk of text without having to highlight and delete.
The button uses an onclick="clear();" function call.
Here is the function...
function clear() {
    $('#body').val('');
}

The problem is it wont clear the predefined text. It will only clear text typed in addition to the predefined text. Or if I manually remove the predefined text it works fine.
I need the field to show the value from the DB. Is there a way to accomplish this without echoing the DB value in a <div> above the field and refraining from pre-defining the ext in the textarea?
Thanks.

A: Rename your function to be something other than clear() and the rest is good. See Why can't I call a function named clear from an onclick attribute?
Alternatively use .on('click', ...) as I've demonstrated below by attaching the event listener to the button using the class js-clear.

function myClear() {
  $('#body').val('');
}

$('.js-clear').on('click', function() {
  $('#body').val('');
});
<script src="https://cdnjs.cloudflare.com/ajax/libs/jquery/3.3.1/jquery.min.js"></script>

<textarea name="body" id="body" rows="5" cols="70">test content</textarea><br>

<button onclick="myClear()">myClear</button>
<button class="js-clear">.on('click')</button>


text:
Q: Execute command with sudo via PHP I have scripts in /etc/init.d/ that I use to control game servers and I would like to build a simple web interface to call those scripts. My sudoers file contains something like
www-data ALL=(ALL) NOPASSWD: /etc/init.d/starbound start stop

When I execute sudo /etc/init.d/starbound start within PHP, nothing happens. Am I missing something? Trying to access paths my PHP user is not allowed to usually gives me the appropriate warnings at least.

A: Seems the problem lies in the sudoers file. If I remove the start stop, it works.
So a correct sudoers could look like this:
Cmnd_Alias GAMES = /etc/init.d/ark_thecenter start, \
                   /etc/init.d/ark_thecenter stop, \
                   /etc/init.d/ark_theisland start, \
                   /etc/init.d/ark_theisland stop, \
                   /etc/init.d/starbound start, \
                   /etc/init.d/starbound stop

www-data ALL=(ALL) NOPASSWD: GAMES

A: Using sudo requires that you input your password when you run a command. By running sudo with exec() you aren't providing the password to sudo and cannot run the command with root level privileges.
Ubuntu.SE provides a way to pass the password to sudo in a single command, but the result is a little messy when implemented with PHP because the Password: prompt will be sent to STDOUT when the call is made, but that can be silenced by sending the output to /dev/null. The result of the command can still be stored in a variable as you might expect.
<?php
//Kill a sudo session if one exists.
exec('sudo -k');

//Run sudo without authenticating
$output = exec('sudo echo "foo"');
var_dump($output); //string(0) ""

//Provide the password and pipe it into sudo.
$output = exec('echo "password" | sudo -S echo "foo" 2> /dev/null');
var_dump($output); //string(3) "foo"
?>


text:
Q: Formal Definition/counter part in mathematics for "Objects" of Object Oriented Models I'm a newbie in both formal mathematics and theoretical computer science, so please bear with me if you find my question is not properly framed.
Object Oriented Modeling seems very useful in defining complex interactions when simulating real world. But it's mostly used in programming. I was wondering if we have a similar concept in mathematics.
When we're doing programming, we can understand the concept of "Objects" and "Object Oriented Programming" and just implement it. But do we have formal definition of "Objects" in terms of Set Theory? Or for that matter, any other formal mathematical theory?
Can we implement/ formally define three primary object orient modeling concepts-
1. Encapsulation
2. Inheritance
3. Polymorphism
I know question is too broad, but would really appreciate if you can provide some pointers as well so that I can understand these concepts better.

A: There is rich literature on mathematical modeling of programming languages, and object-oriented ones are no exception. I would recommend Benjamin Pierce's book "Types and programming languages" as a general introduction to the subject. Robert Harper's "Practical Foundations for Programming Languages" is also very good and available online.
You specifically ask about mathematical models for object-oriented languages. You could look at Abadi's and Cardelli's Theory of Objects and go on from there.
Lastly, you should have asked this question on the cstheory StackExchange.


text:
Q: How is the inequality constraint $\mbox{Tr}(W) \geq c$ convex? In one paper, I found that the following inequality constraint $$\mbox{Tr}(W) \geq c$$ where $W$ is a symmetric positive semidefinite matrix variable and $c$ is a constant, is convex.
In my understanding $\mbox{Tr}(W)$ is a convex function and, therefore, the above constraint should not define a convex set. Is there something wrong with my understanding?

A: $\text{Tr}(W)$ is a linear function, so the constraint is convex.

A: Suppose $$Tr(X) \ge c$$
and $$Tr(Y) \ge c$$
For $\alpha \in (0,1)$, we have $$Tr(\alpha X + (1-\alpha) Y)=\alpha Tr(X)+(1-\alpha)Tr(Y) \ge c$$
Hence it is convex.
Note that trace is a linear function.


text:
Q: joomla jce flash button is missing I have installed the jce 1.5 and mediabox to enable the admin to insert the flash videos by uploading the swf files or by browsing the url from the youtube
I have enabled the mediabox plugin
but I don't know where is the flash button is suppose to appear in JCE.
please help
thanks in advance

A: after searching on the net
I found SWFContent Pro & SWFContent Pro Module
this solved my problem :)


text:
Q: Delete rows from Cassandra DB using Apache Spark Java connector for Cassandra using key columns I am using Apache Spark 2.0, Apache Cassandra 3.7
and Apache Spark Java Connector for Cassandra 2.11 (2.0.0-M3)
I want to delete few rows from table in Cassandra based on key column values. How do I do that using Dataset and using Apache Spark Java Connector for Cassandra? I am using SparkSession in my code. Please suggest. If there is any other way to do this then let me know that. I want to do it using Java.
Thank you.

A: Functionality deleteFromCassandra() for deleting of Cassandra records is coming in new Cassandra Connector release. please check SPARKC-349 and SPARKC-392 for more details.
For deleting row from Cassandra using Cassandra Connector you can do something like below. Say for example I have columns like id UUID PRIMARY KEY, username TEXT in my table. Now I want to delete all the rows where username equals to "Mat". To do this get Session from Cassandra Connector and execute delete query.
dataset.where(dataset.col("username").equalTo("Mat")).foreachPartition(partition -> {
Session session = connector.openSession();
        while (partition.hasNext()) {
            Row row = partition.next();
            String id = (String) row.get(0);//UUID is at index 0
            String delete = "DELETE FROM mykeyspace.mytable where id=" + id + ";";
            session.execute(delete);
        }
        session.close();
    });


text:
Q: Change opacity of an area based on mouse position Is it possible to change the opacity of background but only underneath the cursor area (for example a white small circle)? I am thinking of it a bit like a basic heatmap but the heat doesn't stay - it just follows the cursor.
At the moment I have the following
HTML:
html {
  background-color: #000;
  width: 100%;
  height: 100%;
}

JS:
$(document).mousemove(function(event){
    var i = event.pageX.toPrecision(1) / 1000;
    $("html").css('opacity', i)
});

Sorry this is probably a very basic starting point. Would I need to use canvas?

A: You can do that using svg
What i did :-
I placed two same images with same co ordinates,height and width and gave a circular clip-path to the one on top (which has full opacity) when mouse moves the position of the circle also changes

$('svg').on('mousemove',function(e){
    $('.a').attr('cx',e.pageX).attr('cy',e.pageY)

})
.one{
    opacity:.5;
}
<script src="https://ajax.googleapis.com/ajax/libs/jquery/2.1.1/jquery.min.js"></script>
<svg width="500" height="500">
    <clippath id="clip" >
        <circle cx="50" cy="50" r="50" class="a"/>
    </clippath>

    <image xlink:href="https://images.unsplash.com/photo-1474575981580-1ec7944df3b2?dpr=1&auto=format&fit=crop&w=1500&h=934&q=80&cs=tinysrgb&crop=&bg=" width="500" height="500" x="0" y="0"   class="one"/>

   <image xlink:href="https://images.unsplash.com/photo-1474575981580-1ec7944df3b2?dpr=1&auto=format&fit=crop&w=1500&h=934&q=80&cs=tinysrgb&crop=&bg=" width="500" height="500" x="0" y="0" clip-path="url(#clip)"/>
  </svg>


text:
Q: Custom Title bar delay My app uses a custom titlebar created as a layout and is implemented using this format:
requestWindowFeature(Window.FEATURE_CUSTOM_TITLE);
setContentView(R.layout.my_layout);
getWindow().setFeatureInt(Window.FEATURE_CUSTOM_TITLE, R.layout.my_custom_title);
super.onCreate(savedInstanceState);

Now it did not work using the regular theme android:Theme.Light, neither did android:Theme.Light.NoTitleBar, they both resulted in a fatal exception when setContentView was called. So I created a custom style which looks like this:
<style name="MyWindowTitleBackground">
    <item name="android:background">#000000</item>
</style>

<style name="CustomTheme" parent="android:Theme.Light">
    <item name="android:windowTitleBackgroundStyle">@style/MyWindowTitleBackground</item>
    <item name="android:windowActionBar">false</item>
    <item name ="android:windowTitleSize">35dip</item>
</style>

However, every time the app is started there is a small delay in between the start and display of the actual layout with the custom titlebar, in this delay the default titlebar is shown with the appname in it. After about a second, when the Oncreate finishes, the custom title is loaded and shown.
Is there any way to fix this? What am I doing wrong?

A: Try putting
super.onCreate(savedInstanceState);

before the other lines and see if that works.
and putting
setContentView(R.layout.my_layout);

last.  I seemed to remember my app crashing because I had it in the wrong order.


text:
Q: How to access values displayed in a php dropdownlist populated from a mysql database Firstly, let me say that I've been searching the Internet, rewriting scripts and I still can't seem to find a solution to my problem or even one that could possibly help. I've even searched this site for similar questions and the focus seems to be on actually displaying the database values but what I want is to access those values. Or rather let me put it like this, I have a drop down that is generated through php and it contains data retrieved from mysql... all that works fine no errors.
My current problem is that when a user select an option from my dropdown, I want to use that value to do more operations based on the user's selection. Please help, I've been at it for a week with no avail. Thanks in advance. If you need samples of my code please tell me.

A: You could make a callback function on the onselect Event. This is the easiest with jQuery in my experience.
http://api.jquery.com/select/

A: Wrap your select in a form which had a post of type 'get'. This will post to the same page you are in and then you can use the get parameter on page refresh to load your second list

A: Your problem is not that easy since php only runs on the server and does not directly get any information about what a user is clicking and selecting in his browser.
One possible solution (and the most common one nowadays) is to load any further information asynchronously via AJAX as soon as the user selects something in your dropdown. jQuery is a neat framework that can help you with this.
An other method is to automatically submit the form as soon as something is selected and read the selected value with php ($_POST variable). With this you could then easily generate a more custom website according to the selection that was made. Code could look like this:
<form method="post" action="" name="myform">
<select name="myfield" onchange="this.form.submit()">
<option .... >
...
</select>
</form>

(Note that the form is submitted when the onchange event is triggered)
This method clearly has the disadvantage that the whole page has to be reloaded whenever a selection is made. With the AJAX approach the user does not even notice that some additional information was fetched form the server. (Except a small waiting time that may occur)
What you want to do depends on your own decisioin. However the first approach may need you to get into some javascript programming. But the result is certainly more comfortable for the user...


text:
Q: Class AB Amplifier help Im currently trying to desing a class AB amp. I have currently got so far as bellow. I have the base voltages set at around 0.7V to just allow forward conducting of the BE diodes, and reduce crossover distortion.
My question is how come for my design I do not have any voltage gain? Or is this stage purely for current gain? Also, in most designs I see for a class AB there is another transistor on the input to the pushpull pair. Is this for the voltage gain? Like in AB class amp, design considerations. If so how could I implement this stage into my design. I will finally add a differential pair on the input after I complete this stage.

A: You have no voltage gain because Q1 and Q2 are emitter followers, a circuit configuration with a nominal gain of 1.  You do have current gain, however, due to the current gain of Q1 and Q2 so the overall effect is power gain.  If you need voltage gain, you can add a voltage amplifier at the input.  This could be a differential pair but you could also use an operational amplifier. You should arrange to take overall feedback from the output,however, to reduce the distortion of the power stage.


text:
Q: How to use "OR" op for compositeFilter in Firestore REST API runQuery I am working on Firestore REST API runQuery
I would like to get all documents which fulfill this criteria:
college == 'CUHK' OR college == 'HKU'
I was looking for "OR" in the op of composite filter, unfortunately it doesn't exist
(Firestore Official Documentation)
Is there any alternative for the query below? (something I want but doesn't exist)
{
 "structuredQuery": {
  "from": [
   {
    "collectionId": "participants"
   }
  ],
  "where": {
   "compositeFilter": {
    "op": "OR", // <- what I want
    "filters": [
     {
      "fieldFilter": {
       "field": {
        "fieldPath": "college"
       },
       "op": "EQUAL",
       "value": {
        "stringValue": "CUHK"
       }
      }
     }, // OR
     {
      "fieldFilter": {
       "field": {
        "fieldPath": "college"
       },
       "op": "EQUAL",
       "value": {
        "stringValue": "HKU"
       }
      }
     }
    ]
   }
  }
 }
}


text:
Q: UIGraphicsGetImageFromCurrentImageContext memory leak for scaling image My iPhone application downloads image files from a server, stores it into NSTemporaryDirectory() and then loads the image in the UI asynchronously. Code flow is like this:

*

*Show view with loading activity indicator and run a image downloader in the background.

*Once the image is downloaded, it is written to a file.

*A timer in the loading view keep checking for the availability of file in the temp directory and once available, loads the image from file and adds the image to the UI.

*Before adding the image, it is scaled to required size.

Problem is, I use UIGraphicsGetImageFromCurrentImageContext to scale the image. Looks like the memory used by the image context is not getting cleaned. The app memory just keeps increasing as more files get downloaded.
Some code below:
Code to scale the image:

-(UIImage*)scaleToSize:(CGSize)size image:(UIImage *)imageref
{
 UIGraphicsBeginImageContext(size);
 [imageref drawInRect:CGRectMake(0, 0, size.width, size.height)];
 UIImage* scaledImage = UIGraphicsGetImageFromCurrentImageContext();
 UIGraphicsEndImageContext();
 return scaledImage;
}

Loading image from temp directory:

-(void)loadImageFromFile: (NSString *) path
{
 NSAutoreleasePool * pool = [[NSAutoreleasePool alloc] init];
 UIImage * imm = [[[UIImage alloc] initWithContentsOfFile:path] autorelease];
 [self performSelectorOnMainThread:@selector(insertImage:) withObject:imm waitUntilDone:YES];
 [pool release];
}

Adding image to view (subset of code):

 self.imageContainer = [[UIImageView alloc] initWithFrame:CGRectMake(0,80,320,250)];
 [self addSubview:self.imageContainer];
 self.imageContainer.image = [self scaleToSize:CGSizeMake(320.0f, 250.0f) image:imm];
 [imageContainer release];

What am I missing here ?

A: One way of avoiding the leak from UIGraphicsGetImageFromCurrentImageContext is to not call it at all by resizing the container instead of resizing image directly:
self.imageContainer.contentMode = UIViewContentModeScaleAspectFit;
self.imageContainer.frame = CGRectMake(self.imageContainer.frame.origin.x, self.imageContainer.frame.origin.y, 320.0f, 250.0f);


text:
Q: Matlab import of .dm3 image files broken after recent GMS update I'm trying to read in dm3 files with Sigworth's Matlab script (ReadDMFile.m to be found here)
The script attempts to extract these tags:

*

*'ImageList 2 ImageData Calibrations Dimension 1 Scale'

*'ImageList 2 ImageData Calibrations Dimension 1 Units'

*'ImageList 2 ImageData Dimensions 1'

*'ImageList 2 ImageData Dimensions 2'

*'ImageList 2 ImageData Dimensions 3'

*'ImageList 2 ImageData Data'

But the cell ('output') that should contain the results, comes up empty.
This same script has no problems reading dm3 files that were recorded by the same hardware and saved on the same machine shortly before GMS3 had gotten an update (new library installed). I therefore suspect the problem is with the installation rather than with the script.

A: This really sounds more like a Matlab question than a DM-scripting question. If the software version changed, and that changed the file-format, then there is nothing in DM-scripting which would fix the file for you.
However, you may consider going the opposite way and

*

*Have DM export the data in a matlab readable format

*Or have DM export the data in an intermediate format a matlab script could read.

Both options would be 'DM-scripts'. Possibly the easiest intermediate format would be a "data-only" format containing just the data values and no meta info. The meta info could be saved separately. The script to save an image in "data-only" is simply:
image img := GetFrontImage()
string path = "C:\\filename"
if ( !SaveAsDialog( NULL, "Please choose a saving location.", path, path ) ) exit(0)

img.SaveAsRawData( path )
Result( "\nFile saved as: " + path + ".dat" )

A: When looking into "how to fix" the Matlab script, it might be helpful to compare the two images (working/not working) loaded as a tag-structure.
A DM image is just a TagStructure like any TagGroup. Meta information is found "one hierachy layer up" to what you normaly get when you look at image tags.
The following script shows how to open a DM image as tagGroup:
string path = "C:\\test.dm3"
if ( !OpenDialog( NULL, "Please select the file.", path, path ) ) exit(0)

TagGroup tg = NewTagGroup()
if ( tg.TagGroupLoadFromFile( path ) )
    tg.TagGroupOpenBrowserWindow( path, 0 )

The data-only format stores the values in the data-type of the image with the data ordering:
Iterated over Z
   Iterated over Y
      Iterated over X

i.e. "line-by-line", then "plane-by-plane", and accordingly for higher dimensions.


text:
Q: Youtube embedded video with overlapping title Out of nowhere the title on my youtube video is overlapping the share and more info buttons within the video header. If you hover over the video the title compresses correctly.
Fiddle with the example:
http://jsfiddle.net/QpckF/
Here is my code:

Why Book with Rail Europe?

Is this a problem with youtube or my code?
Thanks

A: Trial and error testing seems to indicate that this is just an interface bug in the Youtube Flash player -- it doesn't truncate the title properly until a mouseover event has been triggered.
A few other interface issues I discovered; it appears that when a video is less than 350px in width, those 'share' and 'more info' buttons aren't even rendered by the flash player, so the problem will only occur if it is more than 350px but less than needed to have the full title visible.
Also, if the video is less than 201 pixels in height, the control bar at the bottom won't auto appear (to save space); but when there is no control bar, then a mouseover cannot trigger the title to be concatenated until the video starts playing.
Minor annoyances, but ones that only come up in a few cases so  don't know how big of a priority they are. You could try reporting the bugs (or see if someone else already has).

A: I was having the same problem.  You can also add "showinfo=0" to the url and it won't show the title at all.


text:
Q: Not only get duplicates from array, but need as well index of the duplicates I have the following array:
Driver[] predictions = new Driver[6];
predictions[0] = new Driver(10, "Michael Schumacher");
predictions[1] = new Driver(10, "Michael Schumacher");
predictions[2] = new Driver(9, "Fernando Alonso");
predictions[3] = new Driver(8, "Jensen Button");
predictions[4] = new Driver(7, "Felipe Massa");
predictions[5] = new Driver(6, "Giancarlo Fisichella");

I want to get all the duplicates - The name once, and then the positions (index) where the duplicates are. So, in this case I want to get "Michael Schumacher" and the positions 1 and 2 (index 0 and 1).
Can this be done in one go, or do I need to consider other options? I just read on DotNetPearls that IndexOf is pretty slow compared to having your own logic.
var driversSelectedMoreThanOnceAndTheirPositions = predictions.Select((driver, index) => new { driver, index })
.GroupBy(item => item.driver.Name)
.Where(grp => grp.Count() > 1)
.ToDictionary(g => g.Key, g => g.Select(a => (a.index + 1)).ToList());

A: To utilize linq for this, you could write something like the following, which uses an overload of Select that allows you to get the element index and then performs a GroupBy operation.
var query =
 predictions.Select((driver, index) => new { driver, index })
 .GroupBy(item => item.driver.Name)
 .Where(grp => grp.Count() > 1)
 .Select(grp => new { Name = grp.Key, Indexes = grp.Select(item => item.index) });

This will result in a sequence of anonymous-typed objects with the properties
class Anon
{
    public string Name;
    public IEnumerable<int> Indexes;
}

Which you could use as in
foreach (var item in query)
{
    Console.WriteLine(item.Name);
    foreach (int index in item.Indexes)
        Console.WriteLine(index);
}

You can, of course, change the way you group to get the entire driver object.

A: The code below will give you a dictionary keyed by driver's name, with a value of all their positions in the original array.  It will also give you a unique list (HashSet) containing only those driver names which occurred more than once in the orginal array.
      Driver[] predictions = new Driver[6];
      predictions[0] = new Driver(10, "Michael Schumacher");
      predictions[1] = new Driver(10, "Michael Schumacher");
      predictions[2] = new Driver(9, "Fernando Alonso");
      predictions[3] = new Driver(8, "Jensen Button");
      predictions[4] = new Driver(7, "Felipe Massa");
      predictions[5] = new Driver(6, "Giancarlo Fisichella");

      Dictionary<string, List<int>> indicies = new Dictionary<string, List<int>>();
      HashSet<string> driversWithDups = new HashSet<string>();
      for (int i=0; i<predictions.Length; i++)
      {
        Driver eachDriver = predictions[i];
        if (indicies.ContainsKey(eachDriver.Name))
        {
          indicies[eachDriver.Name].Add(i);
          driversWithDups.Add(eachDriver.Name);
        }
        else
        {
          indicies[eachDriver.Name] = new List<int>() {i};
        }
      }

A: Given the obvious definition of the Driver class, this should give you what you want:
        Driver[] predictions = new Driver[6];
        predictions[0] = new Driver(10, "Michael Schumacher");
        predictions[1] = new Driver(10, "Michael Schumacher");
        predictions[2] = new Driver(9, "Fernando Alonso");
        predictions[3] = new Driver(8, "Jensen Button");
        predictions[4] = new Driver(7, "Felipe Massa");
        predictions[5] = new Driver(6, "Giancarlo Fisichella");

        var ds = predictions.Select((driver, i) => new { Name = driver.Name, Index = i })
                            .GroupBy(a => a.Name, a => a.Index);


text:
Q: Opencart- Check if user is on category page I've a requirement where the product search and Login/Register links must be displayed only if the user is on Category Pages. That block should not be displayed while on the Static Footer pages as Contact Us or other static footer links.
Weird as it may be the client has very specific requirements regarding this thing.
I've worked on my own with the help in community as much as I can get. But so far I've been able to enable or disable the block completely.

A: One solution could be:
edit the template file catalog/view/template/your_theme/product/category.tpl and add the search input and login/register links directly to that template (somewhere) while positioning with CSS properly to meet Your needs.
Then edit the controller file catalog/controller/product/category.php and copy here the pieces of code from catalog/controller/common/header.php for the login/register links.
Of course edit catalog/view/template/your_theme/common/header.tpl and remove the search input and login/register links from here.
This should be enough...
Another solution:

*

*copy catalog/view/template/your_theme/common/header.tpl to catalog/view/template/your_theme/common/header_category.tpl

*copy catalog/controller/common/header.php to catalog/controller/common/header_category.php

*edit catalog/view/template/your_theme/common/header.tpl and remove the search input and register/login links...

*edit catalog/controller/product/category.php and find the piece code like $this->data['children'] = array(...); -> here replace the header with header_category
Never done this but it might work...

A: Finally I found this article that gave me exactly what I wanted...
http://craigmurray.me.uk/opencart-mods/how-to-highlight-the-current-category-in-the-header-in-opencart/
I made
if (isset($this->request->get['path'])) {

<<DISPLAY SECTION>>

}

But not sure if this would work if the links are made to be SEO friendly.
For now this is working.


text:
Q: Limit 3G traffic on Jailbroken iPad Is there any software for doing this?

A: There are indeed apps used to help you monitor and control your data usage over 3G. A quick Google search found this option: Data Usage for iPhone.


text:
Q: Paypal doesn't send IPN when counterparty status is Unverified or Unverified We build a web form for our client that enables payment using paypal in Singapore dollar ($) to a singapore paypal account. Now they're complaining that more than half of their client who had paid to them using paypal doesn't get the email notification that our system should send to them and the status of these clients in our system doesn't reflect the payment that these clients had made. It's clear here that on some cases, paypal doesn't send their IPN to our system.
From the transaction history csv file that our client gave to us (that they generated from their paypal account which is the receiving account in this case), most of the Status is Completed, but it seems our web site only receive IPN from paypal when the value for Counterparty Status is 'Non-US - Verified'. We won't receive IPN from paypal when the status is Completed but the counterparty status is either 'Non-US - Unregistered' or 'Non-US - Unverified'. So how do we solve this? How do we get those IPN from PayPal even if those payers are either unregistered or unverified? And actually what's the status of these payments?


text:
Q: Let $G$ be a disconnected graph of order $n \geq 6$ having three components. Prove that $\Delta(\overline G) \geq \frac{2n}{3}$ Let $G$ be a disconnected graph of order $n \geq 6$ having three components. Prove that $\Delta(\overline G) \geq \frac{2n}{3}$
This is what I got
let $u \in V(G)$, since $G$ have three components, there are at least 2 vertices of $G$ that are not adjacent to $u$, so $deg(u) \leq (n-3)$ in $G$. How can I connect this to $\overline G$?

A: I'm assuming that $\Delta$ is the maximum degree, and $\bar{G}$ is the complementary graph.
If $G$ has three connected components, then the (or one of the) smallest one has cardinality less or equal to $n/3$, so the sum of the number of nodes in the other two is $2n/3$ or greater.
That means that exists a node in the smallest component connected to at least $2n/3$ other nodes in $\bar{G}$, so $\Delta(\bar{G})\ge2n/3$.
 This holds for $n \ge 3$
In general, if you have $k$ connected components, then $\Delta(\bar{G})\ge(k-1)n/k$, with $n\ge k$


text:
Q: Fabric js: when button is clicked center canvas and zoom to object I'm trying to center the viewport on an object and zoom in/out when i click a button. I want to have an animation. To do this I'm using setInterval and moving the viewport in increments like so:
const objectCenterCoordenates = {
    x: Math.round(rect1.left + rect1.width / 2),
    y: Math.round(rect1.top + rect1.height / 2)
  };
  const centeredCanvasCoordenates = {
    x: objectCenterCoordenates.x - canvas.width / 2,
    y: objectCenterCoordenates.y - canvas.height / 2
  };

  let currentPoint = {
    x: Math.round(canvas.viewportTransform[4]) * -1,
    y: Math.round(canvas.viewportTransform[5]) * -1
  };

  console.log("Start animation");
  let animation = setInterval(() => {
    console.log("New frame");

    if (canvas.getZoom() !== 2) {
      let roundedZoom = Math.round(canvas.getZoom() * 100) / 100;
      let zoomStep = roundedZoom > 2 ? -0.01 : 0.01;
      let newZoom = roundedZoom + zoomStep;
      canvas.zoomToPoint(
        new fabric.Point(currentPoint.x, currentPoint.y),
        newZoom
      );
    }

    let step = 5;

    let vpCenter = {
      x: Math.round(canvas.getVpCenter().x),
      y: Math.round(canvas.getVpCenter().y)
    };
    if (
      vpCenter.x === objectCenterCoordenates.x &&
      vpCenter.y === objectCenterCoordenates.y
    ) {
      console.log("Animation Finish");
      clearInterval(animation);
    }

    let xDif = Math.abs(vpCenter.x - objectCenterCoordenates.x);
    let yDif = Math.abs(vpCenter.y - objectCenterCoordenates.y);

    let stepX =
      Math.round(vpCenter.x) > Math.round(objectCenterCoordenates.x)
        ? -step
        : step;
    if (Math.abs(xDif) < step)
      stepX =
        Math.round(vpCenter.x) > Math.round(objectCenterCoordenates.x)
          ? -xDif
          : xDif;
    let stepY =
      Math.round(vpCenter.y) > Math.round(objectCenterCoordenates.y)
        ? -step
        : step;
    if (Math.abs(yDif) < step)
      stepY =
        Math.round(vpCenter.y) > Math.round(objectCenterCoordenates.y)
          ? -yDif
          : yDif;

    currentPoint = {
      x: currentPoint.x + stepX,
      y: currentPoint.y + stepY
    };

    canvas.absolutePan(new fabric.Point(currentPoint.x, currentPoint.y));
  }, 4);

But sometimes, I haven't been able to determine why, it gets stuck in a loop moving a few pixels one way then going back the other. And the zoom is well implemented, since it's possible to get to the object before it finished zooming in/out.
Here is a codepen with my code: https://codepen.io/nilsilva/pen/vYpPrgq
I would appreciate any advice on making my algorithm better.

A: Looks like you have an exact match requirement for your clearInterval ...
    if (
      vpCenter.x === objectCenterCoordenates.x &&
      vpCenter.y === objectCenterCoordenates.y
    ) {
      console.log("Animation Finish");
      clearInterval(animation);
    }

The case that you describe stuck in a loop moving one way then going back the other is because the exact match it's never done, could be because the step you are taking or it could be a rounding issue
You can use Math.hypot to check if the two points are close enough, read more here:
https://developer.mozilla.org/en-US/docs/Web/JavaScript/Reference/Global_Objects/Math/hypot
The condition will look like:
    if (Math.hypot(
      vpCenter.x - objectCenterCoordenates.x,
      vpCenter.y - objectCenterCoordenates.y
    ) < step) {
      console.log("Animation Finish");
      clearInterval(animation);
    }


text:
Q: VBA Scripting.dictionary run-time error '13' type mismatch I have written code to go through two columns, one will be the key and the other item/items.  It goes through and finds the keys, if it finds a duplicate it adds it to the items along with the previous item.  The problem comes when I try to print out the items.  The keys print out fine but the items give me the run-time error '13' type mismatch.
Here is the code.
Sub All()
Worksheets("All").Activate
Dim Server As Variant
Dim Application As Variant
Dim colLength As Variant
Dim dict As Object
Dim element As Variant
Dim counter As Integer
Dim env As Variant
Dim envLength
Dim com As Variant
Dim comLength
Dim kw As Variant
Dim kwLength

'copies pair of columns
env = Range("A3:B" & WorksheetFunction.CountA(Columns(1)) + 1).Value
com = Range("D3:E" & WorksheetFunction.CountA(Columns(4)) + 1).Value
kw = Range("G3:H" & WorksheetFunction.CountA(Columns(7)) + 1).Value
'sets the start or end point of the pasted pair of columns
envLength = WorksheetFunction.CountA(Columns(1)) + 1
comLength = envLength + WorksheetFunction.CountA(Columns(4)) + 1
kwLength = comLength + WorksheetFunction.CountA(Columns(7)) + 1
'pastes the copies in two big columns
ActiveSheet.Range("I3:J" & envLength) = env
ActiveSheet.Range("I" & (envLength) & ":J" & comLength - 3) = com
ActiveSheet.Range("I" & (comLength - 3) & ":J" & kwLength - 6) = kw

Set dict = Nothing
Set dict = CreateObject("scripting.dictionary")
colLength = WorksheetFunction.CountA(Columns(9)) + 2
counter = 1
Application = Range("I3:I" & colLength).Value
Server = Range("J3:J" & colLength)
'Generate unique list and count
For Each element In Server
    If dict.Exists(element) Then
        dict.Item(element) = dict.Item(element) & ", " & Application(counter, 1)
    Else
        dict.Add element, Application(counter, 1)
    End If
    counter = counter + 1
Next
Worksheets("All2").Activate
ActiveSheet.Range("B2:B" & dict.Count + 1).Value = WorksheetFunction.Transpose(dict.keys)
ActiveSheet.Range("A2:A" & dict.Count + 1).Value = WorksheetFunction.Transpose(dict.items)
End Sub

Error is on line before End Sub

A: I found that when using Transpose you can only have maximum of 255 characters in the cell.
I solved this problem by creating a variable and setting it equal to the items and looping through each and copying to the sheet.
Sub Unique()
Worksheets("All").Activate
Dim Server As Variant
Dim App As Variant
Dim colLength As Variant
Dim dict As Object
Dim element As Variant
Dim counter As Integer
Dim env As Variant
Dim envLength
Dim com As Variant
Dim comLength
Dim kw As Variant
Dim kwLength
Dim dictItems As Variant

'copies pair of columns
env = Range("A3:B" & WorksheetFunction.CountA(Columns(1)) + 1).Value
com = Range("D3:E" & WorksheetFunction.CountA(Columns(4)) + 1).Value
kw = Range("G3:H" & WorksheetFunction.CountA(Columns(7)) + 1).Value
'sets the start or end point of the pasted pair of columns
envLength = WorksheetFunction.CountA(Columns(1)) + 1
comLength = envLength + WorksheetFunction.CountA(Columns(4)) + 1
kwLength = comLength + WorksheetFunction.CountA(Columns(7)) + 1
'pastes the copies in two big columns
ActiveSheet.Range("I3:J" & envLength) = env
ActiveSheet.Range("I" & (envLength) & ":J" & comLength - 3) = com
ActiveSheet.Range("I" & (comLength - 3) & ":J" & kwLength - 6) = kw

Set dict = Nothing
Set dict = CreateObject("scripting.dictionary")
colLength = WorksheetFunction.CountA(Columns(9)) + 2
counter = 1
App = Range("I3:I" & colLength).Value
Server = Range("J3:J" & colLength).Value

'Generate unique list of apps and servers
For Each element In Server
    If dict.Exists(element) Then
        If InStr(LCase(dict.item(element)), LCase(App(counter, 1))) = 0 Then
            dict.item(element) = dict.item(element) & vbLf & App(counter, 1)
        End If
    Else
        dict.Add element, App(counter, 1)
    End If
    counter = counter + 1
Next

Worksheets("All_Compare").Activate
ActiveSheet.Range("B2:B" & dict.Count + 1) = WorksheetFunction.Transpose(dict.keys)
dictItems = dict.items
For i = 0 To dict.Count - 1
    Cells(i + 2, 1) = dictItems(i)
Next

End Sub


text:
Q: Método de clase que manipula evento TextChange en c# mi consulta es la siguiente: Tengo un método de una clase que recibe un textbox como parámetro y le cambia algunas propiedades como Fondo y tamaño, pero no se como hacer para modificar el evento text_change
A)
public class CambiarColor
{

    public void CambiaTextbox( TextBox tx)
    {
        tx.Background = Brushes.Blue;

        //Ahora quiero que cuando el texto cambie cambie el color  de letras
        //Ej: azul,rojo,verde,azul,rojo... al teclear *texto destacado*
    }

}

O sea, normalmente lo hacia así
B)
 private void TxtEjemplo_TextChanged(object sender, TextChangedEventArgs e)
 {
     if (TxtEjemplo.Text.Length > 0) {/*cambio color*/ }
     else if (TxtEjemplo.Text.Length > 3) { /*cambio color*/}
 }

pero lo que quiero saber es si al pasarlo por parámetro dentro de ese método en esa clase en A) puede hacer lo mismo que hacia en B) y manipular ese evento .

A: no dices si estás usando WPF o windows forms, pero en las dos puedes suscribir el evento de cambio a un evento:
<TextBox  TextChanged="textChangedEventHandler">
</TextBox>

A: Lo que debes hacer es primero crear el manejador del evento de la siguiente manera:
private void Textboxes_TextChanged(object sender, TextChangedEventArgs e)
{
    TextBox t= (TextBox)sender;
    if (t.Text.Length > 0) {/*cambio color*/ }
    else if (t.Text.Length > 3) { /*cambio color*/}
}

Al manejador le llega el objeto que ha lanzado el evento en la variable sender, con lo que puedes usarlo para generalizar cualquier Textbox.
Luego lo único que debes hacer en tu método CambiarColor es suscribirte al evento:
public void CambiaTextbox(TextBox tx)
{
    tx.Background = Brushes.Blue;
    tx.TextChanged += Textboxes_TextChanged;
}

De esta manera cada vez que llamas a CambiarColor, te suscribes al evento. Debes tener cuidado ya que si llamas mas de una vez a CambiaTextbox para el mismo TextBox, te suscribiras varias veces al evento con lo que se llamaría varias veces a Textboxes_TextChanged cuando el texto cambie. Pero supongo que llamas a CambiaTextbox una vez nada mas cuando creas el TextBox, con lo que creo que no deberías tener problemas.


text:
Q: Uploading Images on Google Drive from IOS Application I am working with an IOS application ,in which I have to upload images on Google Drive .I am able to upload the images on GDrive,but first I want to create folder and then upload the selected images in that folder.
How could I create that album folder and then insert that images in that folder.
Please help I searched everywhere,but not getting the solution.
Please help me out.

A: Warning, none of the code below was not typed in any IDE. It is just to get you moving in the right direction :)
First, create the empty folder with something like this:
GTLDriveFile *folderObj = [GTLDriveFile object];
folderObj.title = folderName;
folderObj.mimeType = @"application/vnd.google-apps.folder";
GTLQueryDrive *query = [GTLQueryDrive queryForFilesInsertWithObject:folderObj uploadParameters:nil];

Then, when you are inserting the file, you will want to add the ID of this new folder to its parent references using something similar to:
GTLDriveParentReference *parentRef = [GTLDriveParentReference object];
parentRef.identifier = theFoldersId;
fileObj.parents = [NSArray arrayWithObject:parentRef];


text:
Q: Power BI How to extract month and year from a date I have a column containing dates in the following format: "28-SEP-2018 12.40.00", does anyone know how to extract the month and year from the date in a new column (i.e. Sep- 2018), via producing a measure.

A: @navee1990 the measure to extract the date and year is as follows
= MONTH([date] & YEAR([date])
Or the long way
CONCATENATE(MONTH([date]),YEAR([date]))

A: Assuming the type of the column is Text and you want the new values to be displayed as SEP-2018 rather than 09-2018:

You would need to create a new column with DAX as c1 = MID(Table2[Column1],4,8)
In case if the column is of type: DateTime ; then use the below DAX for new column :FORMAT(Table2[Column1],"MMM-YYYY")

A: New Date =FORMAT([date], "MMM") & "-" & YEAR([date])
This would give you a column with text data type. You can further create a column to sort the New Date column as per calendar chronology.


text:
Q: Some bars are black when trying to use individual colors I'm using dc.js to draw my charts, and trying to give different color to the bars.
Some bars are black instead of the colors I requested. How do I get the chart to use the color array?
This is the code
var keyColorCodes;
keyColorCodes = dc.config.defaultColors();

bar.colors(d3.scaleOrdinal().domain(d3.keys(keyColorCodes)).range(d3.values(keyColorCodes)));
bar.colorAccessor(function(d) {
  return d.key;
});

A: The domain of your scaleOrdinal should be an array containing the set of values which your colorAccessor will return. Right now you are pulling the set of indices of the dc.config.defaultColors().
One easy way to get the set of values is to map your group.all() through your colorAccessor:
.domain(speedSumGroup.all().map(d => d.key))

Also, d3.values is intended to be used with associative arrays, i.e. objects. It has no effect when applied to an ordinary array.
Here is a general way to do it, which should work in most cases:
  chart
    .colorAccessor(d => d.key)
    .colors(d3.scaleOrdinal()
              .domain(speedSumGroup.all().map(d => d.key))
              .range(dc.config.defaultColors()));

Example fiddle.


text:
Q: run loop to seven times for days in a week in scss I have days variable:
$days: M T W T F S S;

and static css as :
.bp3-control.bp3-checkbox input ~ .bp3-control-indicator::before {
background-image: unset;
content: "M";
padding: 7px 13px;
}

I want to set content Monday to Sunday in different checkboxes sequentially.
expected output :

A: $list: M T W T F S S;

  @each $day in $list{
    .bp3-control.bp3-checkbox input ~ .bp3-control-indicator::before {
      background-image: unset;
      content: "#{$day}";
      padding: 7px 13px;
    }
}

Hope this will help you

A: $days: (1 "M") (2 "T") (3 "W") (4 "T") (5 "F") (6 "S") (7 "S");

@each $i in $days {
    .bp3-control.bp3-checkbox:nth-child(#{nth($i, 1)}) input ~ .bp3-control-indicator::before {
        content: "#{nth($i,2)}";
    }
}

Checkout https://jsfiddle.net/moorthyrweb/3L1x5tva/


text:
Q: Aptana 3 Code Folding Ive started using Aptana 3 today and really like it,
However I'm struggling to find out if I can code fold to specific levels.
For example I can push Ctrl+Shift+Divide and will collapse EVERYTHING imaginable.
Including the class.
lets just say my doc is as follows:
class Kill_model extends Game_Model{

    function shoot(){
       //code
       //code
       //code
       //code
       //code
    }

    function respawn(){
       //code
       //code
       //code
       //code
       //code
    }

    function spectate(){
       //code
       //code
       //code
       //code
       //code
    }

}

The default will collapse to
class Kill_model extends Game_Model{}

I've been using PHPEdit in the past, and like to "Fold to Level 2"
This gives me the appearance of
class Kill_model extends Game_Model{

    function shoot(){}

    function respawn(){}

    function spectate(){}

}

I was wondering if its possible to just fold down to level 2, by level 2 I assume it means 2 levels deep. Level 1 = Class, level 2 = functions within.
Many thanks.

A: Ok, so level folding is available in Aptana, it just isn't built into PHP editing, only Source editing. To add it to PHP, you can go to Commands > Source > Edit this Bundle, and the Commands > PHP > Edit this Bundle and copy Source/commands/folding.rb to PHP/commands/folding.rb (this will be a new file). If you do not have Option and Command keys (Mac, I believe), you will want to change the keybindings in this file to something else, like Control and Alt. You will find the keybinding in the folding.rb file looking something like this:
with_defaults :input => :none, :output => :discard, :key_binding => "OPTION+COMMAND+0" do

and a second time like this:
cmd.key_binding = "CONTROL+ALT+" + level.to_s

Just change the OPTION to CONTROL and the COMMAND to ALT, and you will have a new Ctrl+Alt+ shortcut once you restart Aptana.

A: See my second answer for more direct info... I thought I'd leave this one in case it helps someone with a similar but not quite the same problem...
I can't speak for the keyboard shortcut because I don't know where numpad_divide is on my laptop (no numpad) - but if you look under Window > Preferences > Aptana Studio > Editors > PHP, you can choose to initially fold "these elements" - if you check "Functions" I think you may get the folding you are looking for. However, I do not think this preference will affect the behavior of Ctrl+Shift+Divide aka Collapse All.
There is also a command to collapse the current block (Ctrl+Numpad_minus) but I think this would be less useful to you.
You may also find the Quick Outline helpful, if you are looking for a short overview of the available classes and functions in your file. This can be accessed with Ctrl+O (or right click > Quick Outline).
Edit: Playing around with Aptana today I found, under Commands > Source > Folding > Toggle Foldings at Level > Level <x>. There appears to be a shortcut associated with each level, Alt+1, Alt+2, etc. but it doesn't work for me. I also don't see an option to configure a shortcut for these commands, but you can theoretically make your own.


text:
Q: How create a json object from POST data in Express.js? i have this form:
form(method="POST", action="/contato")
        .row
            .col-sm-4.form-group
                label NOME
                input(type="text",name="contato[nome]").form-control
            .col-sm-4.form-group
                label TELEFONE
                input(type="text",name="contato[telefone]").form-control
        .row
            .col-sm-4.form-group.btn-group
                input(type="submit", value="Salvar").btn.btn-success
                a(href="/contato").btn.btn-primary Voltar

but in my route:
router.post('/contato', (req, res) => {
    console.log('body', req.body);
});

output:

body { 'contato[nome]': 'Rafael', 'contato[telefone]': '0000' }

but i want:
body { contato : { nome : 'Rafael', telefone : '0000' }}

how do this?

A: Adding bodyParser middleware might help:
var bodyParser = require('body-parser');
....
....
app.use(bodyParser.urlencoded({ extended: true }));
app.use(bodyParser.json());

Make sure you have both!
I'm getting this request body:
body { contato: { nome: 'oleg', telefone: '123456' } }


text:
Q: python3-config --configdir shows older version of python I'm trying to compile vim with my python 3.7 but it seems it relys on either python 2.7 or 3.5.
While I installed python3 and python3 --version returns 3.7 but python3-config --configdir shows python 3.5
/usr/lib/python3.5/config-3.5m-x86_64-linux-gnu

How can I get rid of python 3.5 and its stuff.
Also:
python3.7-config --configdir

returns:
No command 'python3.7-config' found, did you mean:
 Command 'python3.5-config' from package 'python3.5-dev' (main)
 Command 'python2.7-config' from package 'python2.7-dev' (main)

A: I resolved this later problem by sudo apt install -y python3.7-dev. However, one should use python3.7-config