text:
Q: Dynamically reference variables/objects/arrays etc This seems such an easy task, at least it is in VB.net.  I simply need to reference an array based on a string that is passed to a method.  When a view controller loads a method is called and a string is passed.  A URL will be created based on this string and JSON will be fetched from it.  What I want is for the method to populate an appropriate array based on this passed string.
Here we see the method "goGetData" being called in class "getData" with one of three string parameters "workshop/speaker/exhibitor":
- (void)viewDidLoad
{

[getData goGetData:@"workshop"];
[getData goGetData:@"speaker"];
[getData goGetData:@"exhibitor"];

getData *getDataInstance = [[getData alloc] init];

NSArray *newTablesArray = getDataInstance.jsonAllTables;
NSLog(@"Json currently = %@", newTablesArray);

[super viewDidLoad];

[[self myTableView]setDelegate:self];
[[self myTableView]setDataSource:self];
arrayTable =[[NSMutableArray alloc]init];
}

For example if "goGetDate" is fired with "speaker" I would need the speaker data to be fetched and then the "_jsonSpeaker" array to be populated.  Here is my attempt so far to reference and populate the arrays based on what string was passed in the method call:
#import "getData.h"

@implementation getData

+(void)goGetData:(NSString *)requestedTable
{

getData *getDataInstance = [[getData alloc] init];

[getDataInstance buildArray];
[getDataInstance fetchData:requestedTable];

}

-(void)buildArray{
// I tried putting the arrays in an array but still do no know how to reference them
_jsonAllTables = [[NSMutableArray alloc] initWithObjects:_jsonExhibitor, _jsonSpeaker, _jsonWorkshop, nil];

}

-(void)fetchData:(NSString *)requestedTable{
NSString *varCurrentTable;
varCurrentTable = [NSString stringWithFormat:@"_json%@", requestedTable];
NSString *requestedURL;
requestedURL = [NSString stringWithFormat:@"http://testapi.website.com/api/%@", requestedTable];

NSURLRequest *request = [NSURLRequest requestWithURL:[NSURL URLWithString:requestedURL]];
[NSURLConnection sendAsynchronousRequest:request queue:[[NSOperationQueue alloc] init] completionHandler:^(NSURLResponse *response, NSData *data, NSError *error)
 {
     if (response){
         NSHTTPURLResponse *newResp = (NSHTTPURLResponse*)response;

         if (newResp.statusCode == 200) {

             // STUFF FOR TESTING NSLog(@"Response to request: %@ is: %i GOOD", requestedURL, newResp.statusCode);

             if ([data length] >0 && error == nil)
             {
                 // STUFF FOR TESTING NSUInteger indexOfArray = [_jsonAllTables indexOfObject:varCurrentTable];
                 // STUFF FOR TESTING NSString *objectAtIndexOfArray = [_jsonAllTables objectAtIndex:indexOfArray];

             //    This is the part I think I am stuck on:
             //    "CURRENT TABLE TO BE POPULATED" = [NSJSONSerialization JSONObjectWithData:data options:kNilOptions error:&error];

             }
             else if ([data length] == 0 && error == nil)
             {
                 NSLog(@"Nothing was downloaded");
             }
             else if (error != nil)
             {
                 NSLog(@"Error: %@", error);
             }

         } else if (newResp.statusCode == 404){
              NSLog(@"Response to request: %@ is: %i BAD - URL incorrect", requestedURL, newResp.statusCode);
         } else {
             // add more returned status error handling here
         }

     }else{
         NSLog(@"No response received");
     }

 }];
}

@end

Thanks,
Added for clarification on what I am trying to achieve:  To save a LOT of writing out the same thing over and over is the following possibly in Obj-c (please excuse the mish-mash of languages)
NSArray *ListOfTables = [NSArray arrayWithObjects:@"Speaker", @"Exhibitor", @"Workshop", nil];

For i as int = 0 to ListOfTables.count{

 [self fetchData:(ListOfTables.objectAtIndex = i) withCompletion:^(NSArray* objects, NSError*error){
    dispatch_async(dispatch_get_main_queue(), ^{
        if (objects) {
            self.(ListOfTables.objectAtIndex = i) = objects;
        }
        else {
            NSLog(@"Error: %error", error);
        }
    });
}];
i++;
Next
};

Notice i don't call a separate method for each table, instead I call the same method but with different table name parameter each time.  I can't seem to find a working example with such placeholders in Xcode.

A: You probably want a method which is asynchronous and returns the result via a completion handler:
typedef void(^completion_t)(NSArray* objects, NSError*error);

-(void)fetchData:(NSString *)tableName
  withCompletion:(completion_t)completionHandler;

Usage:
- (void) foo {

    [self fetchData:tableName1 withCompletion:^(NSArray* objects, NSError*error){
        dispatch_async(dispatch_get_main_queue(), ^{
            if (objects) {
                self.table1 = objects;
            }
            else {
                NSLog(@"Error: %error", error);
            }
        });
    }];

    [self fetchData:tableName2 withCompletion:^(NSArray* objects, NSError*error){
        dispatch_async(dispatch_get_main_queue(), ^{
            if (objects) {
                self.table2 = objects;
            }
            else {
                NSLog(@"Error: %error", error);
            }
        });
    }];

    [self fetchData:tableName3 withCompletion:^(NSArray* objects, NSError*error){
        dispatch_async(dispatch_get_main_queue(), ^{
            if (objects) {
                self.table3 = objects;
            }
            else {
                NSLog(@"Error: %error", error);
            }
        });
    }];
}

Implementation:
typedef void(^completion_t)(NSArray* objects, NSError* error);

-(void)fetchData:(NSString *)tableName
  withCompletion:(completion_t)completionHandler
{
    NSURLRequest *request = [NSURLRequest requestWithURL:[NSURL URLWithString:tableName]];
    // Setup HTTP headers, e.g. "Accept: application/json", etc.
    ...
    [NSURLConnection sendAsynchronousRequest:request
                                       queue:[[NSOperationQueue alloc] init]
                           completionHandler:^(NSURLResponse *response, NSData *data, NSError *error)
    {
         NSError* err = error;
         NSArray* objects; // final result array as a representation of JSON Array
         if (response) {
             NSHTTPURLResponse *newResp = (NSHTTPURLResponse*)response;
             if (newResp.statusCode == 200) {
                 if ([data length] >0 && error == nil)
                 {
                     NSError* localError;
                     objects = ... // Use NSJSONSerialization to obtain a representation
                     if (objects) {
                         if (completionHandler) {
                             completionHandler(object, nil);
                         }
                         return;
                     }
                     else {
                         err = localError;
                     }
                 }
                 else {
                     err = ...
                 }
             }
         }
         if (objects == nil) {
             assert(err);
             if (completionHandler) {
                 completionHandler(nil, err);
             }
         }
    }];
}

Asynchronous Loop
Another example, for loading a bunch of data:
First, implemented a method which is an "asynchronous loop":
typedef void(^completion_t)(id result, NSError* error);

- (void) fetchObjectsWithTableNames:(NSMutableArray*)tableNames
         completion:(completion_t)completionHandler;

This method is, itself asynchronous, thus the completion handler.
Usage:
- (void) foo
{
    NSArray* tableNames =  @[@"A", @"B", @"C"]; // possibly 1000

    [self fetchObjectsWithTableNames:[tableNames mutableCopy]:^(id result, NSError*error){
        if (error) {
            NSLog(@"Error: %@", error);
        }
        else {
            // finished fetching a bunch of datas with result:
            NSLog(@"Result: %@", result);
        }
    }];
}

Implementation
- (void) fetchObjectsWithTableNames:(NSMutableArray*)tableNames
         completion:(completion_t)completionHandler;
{
    if ([tableNames count] > 0) {
        NSString* name = [tableNames firstObject];
        [tableNames removeObjectAtIndex:0];
        [self fetchData:name withCompletion:^(NSArray* objects, NSError*error){
            if (objects) {
                [self.tables addObject:objects];
                [self fetchObjectsWithTableNames:tableNames completion:completionHandler];
            }
            else  {
               // handle error
            }
        }];
    }
    else {
        // finished
        if (completionHandler) {
            completionHandler(@"finished", nil);
        }
    }
}


text:
Q: Should the methods of the interfaces throw exceptions? I mean, in the definition. If I have a method of a class that implements an interface and I want to throw an exception, how can I do that if the interface don't have a throws declaration.
Thanks

A: You simply don't or throw a RuntimeException.

A: How is the code relying on your class implementing the interface going to know that it has to handle the new exception? You have two options:

*

*Handle it in the interface method.

*Throw an exception that inherits from RuntimeException, which doesn't need to be in the throws clause. However, any code calling this method does not have to catch this exception nor does it know that it can be thrown. So be careful when using this option. Document them where possible, but you'll still face a problem when passing an object to an existing method such as a library or one that is built-in.

A: If you cannot touch the interface, then your only choice is to throw a RuntimeException. There are some standard RuntimeExceptions that you can use directly : IllegalStateException, IllegalArgumentException, UsupportedOperationException, etc.
Use these standard exceptions if they suit your needs, or create your own by extending the class RuntimeException. Consider documenting the thrown exceptions by using the @throws doclet in the javadoc.

A: The methods in your interface can declare to throw checked exceptions only if it makes sense for all the possible implementations to force the client to handle that exception.
Think of java.sql.Connection (an interface with all the methods throwing SQLException). Otherwise, if only one particular implementation has to deal with some checked exception, handle it there and either wrap it in some RuntimeException and rethrow or recover from that state if it makes sense.

redpajama_set_name: RedPajamaStackExchange


text:
Q: Material Design Textfield Custom Class Not Showing Up in Xcode I have installed the MaterialComponents/TextFields pod, and I am trying to add a new text field into the storyboard editor.  I add a textfield, and when I go to add a Material textfield custom class from the dropdown in the identity inspector, none of the material textfields that come with the pod show up. Is there something that I'm missing that needs to be done before I can use these custom classes?

A: Try this instead - reinstalling the pod or restart Xcode or import Material components in swift file. Hope it works


text:
Q: When creating entity with keyValue options, Orion auto data type detection does not infer location attribute correctly When creating an entity you could do it like this :
curl --location --request POST 'https://my.api/v2/entities/?options=keyValues' --header 'Content-Type: application/json' --data-raw '{
   "id":"vehicle:WasteManagement:1",
   "type":"WasteManagement",
   "vehicleType":"lorry"
}'

Or without the options=KeyValues parameter :
curl --location --request POST 'https://my.api/v2/entities/' --header 'Content-Type: application/json' --data-raw '{
   "id":"vehicle:WasteManagement:2",
   "type":"WasteManagement",
   "vehicleType":{
        "value": "lorry"
    }
}'

And in both case the entity is the same.
But I don't manage to create an entity with a options=keyValues parameter with an entity that has a 'location' attribute : when doing
curl --location --request POST 'https://my.api/v2/entities/' --header 'Content-Type: application/json' --data-raw '{
   "id":"vehicle:WasteManagement:3",
   "type":"WasteManagement",
   "vehicleType":"lorry",
    "location": {
        "type": "Point",
        "coordinates": [
            -0.56832066,
            47.49576
        ]
    }
}'

In this case, the result from curl --location --request GET https://my.api/v2/entities/vehicle:WasteManagement:2'
Would be
"location": {
    "type": "StructuredValue",
    "value": {
        "type": "Point",
        "coordinates": [
            -3.164485592,
            40.627851337
        ]
    },
    "metadata": {}
},

And the type of location is StructuredValue
My expectation would be geo:point or other geo:XXX depending of the type of the GeoJSON which allow the entity to be geolocalized and filter by location.

A: According to the NGSIv2 specification section "Partial Representations":

Attribute/metadata type may be omitted in requests. When omitted in attribute/metadata creation or in update operations, a default is used for the type depending on the value:

*

*...

*If value is an object or array, then StructuredValue is used.

In the case of request
curl --location --request POST 'https://my.api/v2/entities/?options=keyValue' --header 'Content-Type: application/json' --data-raw '{
   "id":"vehicle:WasteManagement:3",
   "type":"WasteManagement",
   "vehicleType":"lorry",
    "location": {
        "type": "Point",
        "coordinates": [
            -0.56832066,
            47.49576
        ]
    }
}'

the location attribute fulfills with the "when [attribute type] omitted in attribute/metadata creation or in update operations" of the NGSIv2 spec. In addition, value is an object so "If value is an object or array, then StructuredValue is used"  applys. Thus, it is correct that the attribute is created/updated with type StructuredValue.
The workaround is pretty easy: don't use the keyValues mode if you need attributes with a special type (as the ones for a location or DateTime) and use the normalized mode instead.
Note that the keyValues mode has been designed as a helper  not as a replacement of the normalized mode. The keyValues mode covers a great degree of the normalized mode functionality, but not fully.


text:
Q: Cypress verify API request I want to verify if the API request contains what it needs to contain, but not sure what I am doing wrong as I have always this error:
cy.wait() timed out waiting 5000ms for the 1st request to the route: apiCheck. No request ever occurred.

I have a link in the main menu, after clicking that link the new page opens and API call is iniciated immediately http://localhost:8081/currencies
So in Cypress I have this:
 cy.get('ul li[title="Menu item"]>a').click();

  cy.intercept({
        method: 'GET',
        url: '/currencies',
      }).as('apiCheck')

      cy.wait('@apiCheck').then((interception) => {
      expect(interception.response.statusCode).to.equal(200);
expect(interception.response.body[0]).to.have.property('geographyName', 'EMEA')
      })

As you can see from Cypress test runner screenshot, the request is there and has status 200, but still it says no request ever occurred.

A: ah, well, seems I need to call cy.intercept before the link is clicked, then it seems working.


text:
Q: Issue Sending Post Data To PhP The Library Im Using: https://github.com/Code-Building/requests
PHP
if (register($_GET['username'], $_GET['password'], $_GET['hwid'])) { ... }
```

C++
    http::request* result = http::post("https://xxx/api/handle.php?t=", data);

    printf("%s", result->text.c_str());

I would like to add running this on a local server works just fine, having issues with livenet since thats what our teacher wants.
Also the issue is sending the post data. Manually entering post data / sending with fiddler work just fine. Any Ideas?
(Ive also used $_POST didnt work aswell)


text:
Q: does checkstyle for java propose modifications? I'm using checkstyle within eclipse and when I activate it, the tool shows message about naming conventions and doesn't make proposals which should be very practical.
does this functionality exist ? how could I use it ?
thanks

A: Java naming conventions are pretty easy to detect, to remember and to apply. A validator can detect violations but can't propose the correct name (in general) as this may depend on semantics. And: once you know the conventions, you immediatly realise the problem and see a "correct" alternative.
Examples:
int Person = null;  // should be person

class my_mouse_listener {   // should be MyMouseListener

private static int red = 1;  // should be RED

private String SUPERUSERPASSWORD = "secret";  // could be superuserPassword
                                              // -> good proposal impossible as
                                              // sUPERUSERPASSWORD would be
                                              // valid too

A: Checkstyle does not propose the 'correct' name. The configuration for checkstyle is just a regular expression, so you can't say 'how do I transform the name so that it it will fit in with the regular expression'.
You can however add a personalised message for each type of error raised, so that you can suggest a better name, or give examples. Look in Window->Preferences->Checkstyle.


text:
Q: Write the equation of the image of the parabola $y=x^2-2x+1$ under a translation $\vec{p}=\hat{i}+3\hat{j}$ Write the equation of the image of the parabola $y=x^2-2x+1$ under a translation $\vec{p}=\hat{i}+3\hat{j}$

$y=(x-1)^2$ is a parabola whose vertex is $(1,0)$ and focus is $(1,\frac{1}{4})$.I dont know how to solve further.

A:
Write the equation of the image of the parabola $y=x^2-2x+1$ under a translation $\vec{p}=\hat{i}+3\hat{j}$

Translating $y=f(x)$ over $\vec{p}=\color{blue}{a}\hat{i}+\color{red}{b}\hat{j}$ corresponds to the equation $y-\color{red}{b}=f(x-\color{blue}{a})$ in the same coordinate system; so with $y=x^2-2x+1$ and $\vec{p}=\color{blue}{1}\hat{i}+\color{red}{3}\hat{j}$, you get:
$$y-\color{red}{3}=(x-\color{blue}{1})^2-2(x-\color{blue}{1})+1 \iff y=x^2 - 4 x + 7 \tag{$*$}$$

$y=(x-1)^2$ is a parabola whose vertex is $(1,0)$

After rewriting the parabola in this standard form, you could also simply shift the vertex towards $(1+\color{blue}{1},0+\color{red}{3})=\color{purple}{(2,3)}$, so the equation becomes:
$$y=(x-\color{purple}{2})^2+\color{purple}{3}\iff y=x^2 - 4 x + 7 \tag{$\star$}$$
Note that $(*)$ and $(\star)$ match.

A: $p(x,y)=(x,y)+(1,3)=(x+1,y+3), \quad p(x,y)^t=(x+1,y+3)^t$ so $p$ can be seen as a matrix
$\pmatrix{1 & 0 & 1\\ 0 & 1 & 3 \\ 0 & 0 & 1}$ which is $\pmatrix{1 & 0 & 1\\ 0 & 1 & 3 \\ 0 & 0 & 1}\pmatrix{x \\ y \\ 1}=\pmatrix{x+1 \\ y+3 \\ 1}$
so for $y=(x-1)^2$ it is
$\pmatrix{1 & 0 & 1\\ 0 & 1 & 3 \\ 0 & 0 & 1}\pmatrix{x \\ (x-1)^2 \\ 1}=\pmatrix{x+1 \\ (x-1)^2+3 \\ 1}$
so $y'=(x-1)^2+3=x^2-2x+4=(x'-1)^2-2(x'-1)+4=x'^2-4x'+7$


text:
Q: How to hide all divs in jquery of particular div? I have HTML like below

      //code

         //code

           //code

      //code

         //code

           //code

So I want to hide all inner P divs of particular L. I have tried below code but it is not working.
$('#L0 div[id^=P]').hide();

A: $('#L0 div[id^=P], #L0 div[id^=p]').hide();

A: Last div id p is small char and in selector used CAPITAL P char

change

A: This worked for me. Two of them are not hiding because they are small letter p

$('div[id^="P"]').hide();
$('div[id^="p"]').hide();

      //code

         //code

           //code

      //code

         //code

           //code

A: just hide your L0 div and all inner P will hide automatically for particular Div
try following code
$('#L0').hide();

A: Add a class to your top level DIV's for example:

1

2

3

4

5

6

Now you can easily select all DIV's with the class top-div and hide their children, In this case the inner divs:
$('div.top-div').children().hide();

If you want to hide the inner divs of only one outer (L) div use the code below:
$('div#L0').children().hide();// for your first div L0
$('div#L1').children().hide();// for your second div L1


text:
Q: Rails 3: Get Count of Models via Relationship In Ruby on Rails (3) with PostgreSQL and given the following three hierarchical models:
class Category
    has_many :posts
end

class Post
    belongs_to :category
    has_many :comments
end

class Comment
    belongs_to :post
end

Is there a way to get the total comment count for each category without having to iterate over each of the posts?
Any help would be appreciated, thank you!

A: Yes, there is. All you need to do is group the relation by the column you want:
counts_hash =
  Comment.
  joins(post: :category).
  group("#{Category.table_name}.id").
  count

That should return a hash with structure category_id => comments_count
However, that will exclude any categories that have 0 comments since inner-joins will be performed.
If you want to include all category IDs, for whatever reason, you'd have to include a few extra steps:
counts_hash.tap do |hash|
  Category.pluck(:id).each do |category_id|
    hash[category_id] = 0
  end
end

Alternatively:
# the following will return 0 as the value of any missing key
Hash.new(0).merge(counts_hash)hash


text:
Q: Sort with threads I have an assignment and i need working code. Before i start i want to understand the problem but i cant figure out how to write it.
I have an array of data, take this for example
var arr = new byte[] {5,3,1,7,8,5,3,2,6,7,9,3,2,4,2,1}

I need to split this array in half, throw it into a thread pool and do that recursively until i have <=2 elements. If i have 2 elements i need to check which is less and put it on the left side then return the array.
What i don't understand is how do i merge the array? am i suppose to split the array, throw a thread into the pool and block until its ready? How do i get the results of the thread? I'm going to assume its not possible to merge the arrays without blocking?
Heres what i have so far.
    static void Main(string[] args)
    {
        var arr = new byte[] { 5, 3, 1, 7, 8, 5, 3, 2, 6, 7, 9, 3, 2, 4, 2, 1 };
        var newarr = Sort(arr);
        Console.Write(BitConverter.ToString(newarr));
    }
    static byte[] Sort(byte[] arr)
    {
        if (arr.Length <= 2)
            return arr;
        if (arr.Length == 2)
        {
            if (arr[0] > arr[1])
            {
                var t = arr[0];
                arr[0] = arr[1];
                arr[1] = t;
            }
            return arr;
        }

        var arr1 = arr.Take(arr.Length / 2).ToArray();
        var arr2 = arr.Skip(arr1.Count()).ToArray();
        //??
        return arr;
    }

Note: The prof did say we can ask others for help. I think i can solve this without asking but i want to get the best answer. Threading is my weakness (i dont everything else, db, binary io, web interface, just never complex threads)

A: This appears to be a parallel version of merge sort. You should essential make it work like the recursive sequential version, but apparently run each recursive sort as a separate task.
In your task API, there should be some way to wait for completion, and perhaps to also pass results. With that, you can copy the traditional mergesort fairly well: for each sub-sort, put a task into the pool, and wait for completion of the two subtasks. Then perform the merge, and pass back your own result to your calling tasking.
If you have a regular thread API only (i.e. no real task library), then I suggest you provide the output in a third array: each thread will have two input arrays, and one output array. If you are allowed to create fresh threads for each task, you can wait for task completion by joining the two subthreads.

A: To add onto Martin's answer, I would not create smaller copies of the array.  Instead, I would have each thread work on a subset of the original array.

A: More than happy to oblige: Any multi-core sorting implementation in .NET?


text:
Q: pip install apache-airflow then airflow initdb on a fresh virtual environment: SyntaxError $ virtualenv --version
16.3.0
$ pip --version
pip 19.0.1

I created a fresh environment. And run the
pip install apache-airflow

It is successful installed
apache-airflow   1.10.2

But then I run the
 airflow initdb

I got the error
ERROR [airflow.models.DagBag] Failed to import: /Users/admin/workshops/apache/airflow/lib/python3.7/site-packages/airflow/example_dags/example_http_operator.py
    Traceback (most recent call last):
      File "/Users/admin/workshops/apache/airflow/lib/python3.7/site-packages/airflow/models.py", line 374, in process_file
        m = imp.load_source(mod_name, filepath)
      File "/Users/admin/workshops/apache/airflow/lib/python3.7/imp.py", line 171, in load_source
        module = _load(spec)
      File "<frozen importlib._bootstrap>", line 696, in _load
      File "<frozen importlib._bootstrap>", line 677, in _load_unlocked
      File "<frozen importlib._bootstrap_external>", line 728, in exec_module
      File "<frozen importlib._bootstrap>", line 219, in _call_with_frames_removed
      File "/Users/admin/workshops/apache/airflow/lib/python3.7/site-packages/airflow/example_dags/example_http_operator.py", line 27, in <module>
        from airflow.operators.http_operator import SimpleHttpOperator
      File "/Users/admin/workshops/apache/airflow/lib/python3.7/site-packages/airflow/operators/http_operator.py", line 21, in <module>
        from airflow.hooks.http_hook import HttpHook
      File "/Users/admin/workshops/apache/airflow/lib/python3.7/site-packages/airflow/hooks/http_hook.py", line 23, in <module>
        import tenacity
      File "/Users/admin/workshops/apache/airflow/lib/python3.7/site-packages/tenacity/__init__.py", line 352
        from tenacity.async import AsyncRetrying
                          ^
    SyntaxError: invalid syntax

It is a fresh virtual environment. I did not install anything else.

A: As can be found here, async has become a keyword since Python 3.7. You could  create a virtual environment with Python < 3.7 and install Airflow. And perhaps you could also try and upgrade tenacity to >=4.10.0 as the issue in tenacity is resolved in that version.


text:
Q: n-dimensional vector space isomorphic to the n-th product of a field as abelian groups Let $V$ be a finite dimensional vector space (of dimension n) over a field $F$. I need to show that $V$ is isomorphic to $F^n$ as abelian groups. However, I don't really understand what does "isomorphic as abelian groups" mean, my (poor) attempt to solve this was:
Let $f:V\to F^n$, $f((v_1,v_2,\ldots,v_n)):=v_1+\ldots+v_n$, clearly $f$ is a group homomorphism, but it is not biyective since, for example, in the case where $dim(V)=2$ and $F=\mathbb{R}$ we have $f((2,-2))=0=f((3,-3))$, I've also tried it by defining $f$ to be the product of a vector's entries but obviously it didn't work so I'm stuck!
I think this should be an easy problem but since I don't quite understand it, it's giving me problems. Thank you for your help.

A: First, pick a basis $\{w_i\}$ for $V$. Note that all elements of $V$ can be written as $\sum^n c_iw_i$ for some $c_i \in F$. This gives a natural function $f(\sum^n c_iw_i) = (c_1, ... c_n)$. Show that it is a bijection and that it is a homomorphism as far as $+$ is concerned.


text:
Q: Create new drop downs on change event using jQuery I have drop down menu with some random values. When I select the value onchange event triggers and I want to add new drop down under it, but the new one should have all values except selected one in first drop down. Now when I change value of second one, I need third one that has only non selected values from previous two drop downs and so on until there is no more option to select.
What I have for now is mechanism for adding new drop downs, but it is not working correctly. If I for example select first value it will do the job, new drop down is shown and it has all options except selected one. But then if I go back and try to change option for first drop down third drop down is created. This should not be a case, if drop down already created another drop down it should not do it again. Is it even possible to avoid triggering of new onchange event for drop down that already triggered one? Or maybe some other kind of event is more suitable for this case?
This is my function that does described job:
createNewDropDonws : function() {
    var selectWrapper = $('#select-boxes');
    $(document).on('change', '.dynamic-select', function() {
        var element = $(this);
        var optionsLength = (element.find('option').length) - 1;

        if(optionsLength === 1) {
        return true;
        }

        var newSelect = $(this).clone();
        newSelect.find("option[value='" + element.val() + "']").remove();
        newSelect.appendTo(selectWrapper)
    });
}

This is my HTML for drop down:

    <select class="dynamic-select" id="ddlTest">
      <option value=""></option>
      <option value="Belbin">Belbin</option>
      <option value="Raven">Raven</option>
      <option value="PPA">PPA</option>
      <option value="PPA+">PPA+</option>
      <option value="Basic Knowledge">Basic Knowledge</option>
      <option value="PCT">PCT</option>
    </select>

And this is simple CSS class:
.dynamic-select{
  display: block;
  margin: 10px;
  }

Does anybody has any idea how this can be implemented correctly by using jQuery?

A: We can do it in following way:
We are just adding some class like executed once it add another dropdown. And in event handler we are checking if current dropdwon has that class or not. If it is already there then it means we are already done with that dropdown as follows:

$(document).ready(function() {
  var selectWrapper = $('#select-boxes');
  $(document).on('change', '.dynamic-select', function() {
    var element = $(this);
    if(element.hasClass("executed"))
      return;

    var optionsLength = (element.find('option').length) - 1;

    if (optionsLength === 1) {
      return true;
    }

    var newSelect = $(this).clone();
    newSelect.find("option[value='" + element.val() + "']").remove();
    newSelect.appendTo(selectWrapper)

    $(this).addClass("executed");

  });
});
.dynamic-select {
  display: block;
  margin: 10px;
}

  <select class="dynamic-select" id="ddlTest">
    <option value=""></option>
    <option value="Belbin">Belbin</option>
    <option value="Raven">Raven</option>
    <option value="PPA">PPA</option>
    <option value="PPA+">PPA+</option>
    <option value="Basic Knowledge">Basic Knowledge</option>
    <option value="PCT">PCT</option>
  </select>


text:
Q: php script gets two ajax requests, only returns one? I'll start from the beginning.
I'm building a wordpress plugin that does double duty, in that it can be inserted in to a post via a shortcode, or added as a sidebar widget. All it does is output some js to make jquery.post requests to a local php file. The local php file makes a request to a webservice for some data. (I had to do it this way instead of directly querying the web service with jquery.ajax because the url contains a license key that would be public if put in the js).
Anyway, When I am viewing a page in the wordpress blog that has both the sidebar widget and the plugin output via shortcode only one of the requests work. I mean it works in that it gets a response back from the php script. Once the page is loaded they both work normally when manually told to.
Webpage view -> send 2 post requests to my php script -> both elements should be filed in, but only one is.
My php script is just:
<?php
    if(isset($_POST["zip"])) {
         // build a curl object, execute the request,
         // and basically just echo what the curl request returns.
    }
?>

Pretty basic.
here is some js some people wanted to see:
function widget_getActivities( zip ){
    jQuery("#widget_active_list").text("");
    jQuery.post("http://localhost/wordpress/wp-content/ActiveAjax.php", { zip: zip},
        function(text) {
            jQuery(text).find("asset").each(function(j, aval){
                var html = "";
                html += " " +  jQuery(aval).find("assetName").text() + " at ";

                jQuery("location", aval).each(function(i, val){
                    html += jQuery("locationName", val).text() + "  on ";
                });

                jQuery("date", aval).each(function(){
                    html += jQuery("startDate", aval).text();

                jQuery("#widget_active_list")
                    .append(jQuery("
")
                        .addClass("widget_ActivityEntry")
                        .html(html)
                        .bind("mouseenter", function(){
                            jQuery(this).animate({ fontSize: "20px", lineHeight: "1.2em" }, 50);
                        })
                        .bind("mouseleave", function(){
                            jQuery(this).animate({ fontSize: "10px", lineHeight: "1.2em" }, 50);
                    })
                    );

                });
            });
        });
}

Now imagine there is another function identical to this one except everything that is prepended with 'widget_' isn't prepended. These two functions get called separately via:
jQuery(document).ready(function(){
    w_zip = jQuery("#widget_zip").val();
    widget_getActivities( w_zip );
    jQuery("#widget_updateZipLink").click(function() { //start function when any update link is clicked
        widget_c_zip = jQuery("#widget_zip").val();
        if (undefined == widget_c_zip || widget_c_zip == "" || widget_c_zip.length != 5)
            jQuery("#widget_zipError").text("Bad zip code");
        else
            widget_getActivities( widget_c_zip );

    });
})

I can see in my apache logs that both requests are being made.
I'm guessing it is some sort of race condition but that doesn't make ANY sense.
I'm new to all this, any ideas?
EDIT: I've come up with a sub-optimal solution. I have my widget detect if the plugin is also being used on the page, and if so it waits for 3 seconds before performing the request. But I have a feeling this same thing is going to happen if multiple clients perform a page request at the same time that triggers one of the requests to my php script, because I believe the problem is in the php script, which is scary.

A: Not really enough information for me to really figure anything out...
However one thing to try is to get firebug and see what the response is for each of the requests.
Another question might be...are you filling in by id?  If so, then it may be due to the fact that you have the same id twice in one page, and that is messing things up.  If you have it online it would be much easier to help you out.

Edit:
A few comments...I'm not sure if anything will be solved by this...however...

As far as I know the type of comment you use there is only effective when used in html and might be screwing up your Javascript.  Replace it with //
jQuery("#widget_active_list").append(jQuery("
")
                                     .addClass("widget_ActivityEntry")
                                     .html(html)
                                     .bind("mouseenter", function(){
                                          jQuery(this).animate({ fontSize: "20px", lineHeight: "1.2em" }, 50);
                                     })
                                     .bind("mouseleave", function(){
                                          jQuery(this).animate({ fontSize: "10px", lineHeight: "1.2em" }, 50);
                                     })
                             );

Second of all...that whole block is nested in the last .each which doesn't seem to be having an effect however, it is not impossible that it messing with it.
Last of all, while it might not actually be making a difference, you should probably be setting the type of the response to xml.  Using both the http headers in php and using the last argument of the function. i.e.
header("Content-Type: application/xml");

and
jQuery.post("http://localhost/wordpress/wp-content/ActiveAjax.php", { zip: zip}, thefunctionhere, xml);

If this doesn't help, my suggestion for a sub-optimal solution, is to use a get request instead, and add a random parameter that isn't taken into account to both requests, however make it the same for each request, but different every time you go to the page.  That way the browser will cache the request for the first one, and not query the server a second time, but it won't cache it for when the person comes to the page again.


text:
Q: Multiline shell script comments - how does this work? Recently, I stumbled upon a multiline comment type I have never seen before - here is a script example:
echo a
#
: aaa
: ddd
#
echo b

This seems to work, even vim syntax-highlights it. What is this style of commenting called and how to I find more info about it?

A: It's not any style of commenting. the : built-in command does absolutely nothing; it's being abused for commenting here.
$ help :
:: :
    Null command.

    No effect; the command does nothing.

    Exit Status:
    Always succeeds.

A: In early shells, the colon was the only way to create comments.
However, it is not a true comment, because the line is parsed in exactly the
same way as any other command is parsed, and that may have side effects. For
example:
: ${a:=x} # assigns the value 'x' to the variable, 'a'

: $(command) # executes 'command'

(Sometimes the colon is use solely for the purpose of invoking those side
effects, but then it's not being used as a comment.)
It is sometimes convenient to use the colon to comment out a section of a
script:
: '
while [ "$n" -ne "$x" ]
do
  : whatever
done
'

This is a great timesaver over preceding each line with #, particularly if the
commenting out is only temporary.

A: If your comment is at the end of the script, you can do it like this:
#!/bin/sh
echo 'hello world'
exec true
we can put whatever we want here
\'\"\$\`!#%&()*+,-./0123456789:;<=>?@ABCDEFGHIJKLMNOPQRSTUVWXYZ[\]^_
abcdefghijklmnopqrstuvwxyz{|}~

A: That is not a multi-line comment.  # is a single line comment.
: (colon) is not a comment at all, but rather a shell built-in command that is basically a NOP, a null operation that does nothing except return true, like true (and thus setting $? to 0 as a side effect).  However since it is a command, it can accept arguments, and since it ignores its arguments, in most cases it superficially acts like a comment.  The main problem with this kludge is the arguments are still expanded, leading to a host of unintended consequences.  The arguments are still affected by syntax errors, redirections are still performed so : > file will truncate file, and : $(dangerous command) substitutions will still run.
The least surprising completely safe way to insert comments in shell scripts is with #.  Stick to that even for multi-line comments.  Never attempt to (ab)use : for comments.  There is no dedicated multi-line comment mechanism in shell that is analogous to the slash-star /* */ form in C-like languages.

For the sake of completeness, but not because it is recommended practice, I will mention that it is possible to use here-documents to do multi-line "comments":
: <<'end_long_comment'
This is an abuse of the null command ':' and the here-document syntax
to achieve a "multi-line comment".  According to the POSIX spec linked
above, if any character in the delimiter word ("end_long_comment" in
this case) above is quoted, the here-document will not be expanded in
any way.  This is **critical**, as failing to quote the "end_long_comment"
will result in the problems with unintended expansions described above.
All of this text in this here-doc goes to the standard input of :, which
does nothing with it, hence the effect is like a comment.  There is very
little point to doing this besides throwing people off.  Just use '#'.
end_long_comment


text:
Q: How to select the correct id for the specific button pressed in dynamic table I'm relatively new to jquery and cannot for the life of me get this to return the proper youtube id it just always returns the first one in the table.
php.
I load the youtube id from my database then display it in the table.
require_once 'library/Zend/Loader.php';
Zend_Loader::loadClass('Zend_Gdata_YouTube');
echo '
';
echo '
';

while ($row = mysqli_fetch_assoc($videoquery))
{
$vidid = ($row['id']);
$vidtitle = ($row['title']);
$vidip = ($row['ip']);
$page2 = ($row['page']);
$q = ($row['youtubeid']);

$yt = new Zend_Gdata_YouTube();
$yt->setMajorProtocolVersion(2);
$videoEntry = $yt->getVideoEntry($q);
$thumbnail = 'mediaGroup->thumbnail[0]->url . '" width="100" height="92"';

echo '

 '.$thumbnail.'
 ' .$vidtitle. '

 <form method="post">
 <input name="parse" type="hidden" value="playvid" /><input name="youtubeid" id="youtubeid" type="hidden" value="'.$q.'" />;
 <input type="button" name="play" id="play" value="Play Video" />
 </form>

 <form method="post" action="">
 <input type="hidden" name="page2" value="'.$_SERVER['REQUEST_URI'].'">
 <input name="parse" type="hidden" value="deletepost2" />
 <input name="postid2" type="hidden" value="'.$vidid.'"/>';
if ($topuserid == $_GET['id']){
 echo '<input type="submit" name="deletepost2" id="deletepost2" value="Delete Video" /';>
}
echo  '</form>
';
}
echo   '
';
}

Jquery code

A: Nathan had the right idea but had some errors in his code. Try this:

A: you need to give your selector some context.  implementing no changes in your html you could change your js to
$(document).ready(function(){
var $tr = $(this).closest('tr')
$('#play').live('click', function() {
tr.find('#video').empty()
var vidid = tr.find('#youtubeid').val();
alert(vidid);
var playvid = '<object width="300" height="193">'+
'<param name="movie" value="http://www.youtube.com/v/'+vidid+'&hl=en_US&fs=1"></param>'+
'<param name="allowFullScreen" value="true"></param>'+
'<param name="allowscriptaccess" value="always"></param>'+
'<embed src="http://www.youtube.com/v/'+vidid+'&hl=en_US&fs=1" type="application/x-shockwave-flash" allowscriptaccess="always" allowfullscreen="true" width="300" height="193"></embed>'+
'</object>';
tr.find('#video').append(playvid);    });
});


text:
Q: How to make API requests with loop in SAS I'm trying to geocode entities (company) through the Brazilian zip code respectively, using a public API called BrasilAPI.
This is a fictional sample of the data:
data AMOSTRA_ENTIDADE;
infile datalines delimiter=',';
length  CODEMPRESA 3.
        NOMEEMPRESA $9
        CEP $8;

input   CODEMPRESA
        NOMEEMPRESA $
        CEP;
datalines;
1,EMPRESA A,71577090
2,EMPRESA B,01026010
10,EMPRESA C,01000000
100,EMPRESA D,92300000
110,EMPRESA E,29010580
;
run;

fictional sample of the data
I recently discovered the http SAS proc for this task, I don't know if there is another one. With that I tried to make the following code snippet to perform the request in the API following these examples I found:

*

*example_1

*example_2

*example_3
%macro get_lat_long(cep);
  %let site="https://brasilapi.com.br/api/cep/v2/&cep.";
  %put NOTE: &site.;
  filename resp temp;

  proc http
     url = &site
     method = get
     out = resp;

     debug level=1;
  run;

  libname resp json;

  data _null_;
     infile resp;
     input;
     put _infile_;
  run;

%mend get_lat_long;

data COORDENADAS_ENTIDADE;
   set AMOSTRA_ENTIDADE;
   length macro_call $200;

   macro_call  = cats('%consulta_lat_long(',CEP,')');
   call execute(macro_call);
   rc = dosubl(macro_call);
run;

return from the code above:

My question is, how to make these requests in SAS to return the JSON and other information coming from the request in the API?
What I have input:

What I'm looking for in the output:

Please, if possible, I would like examples to run on both SAS Enterprise Guide and SAS Viya. Thank you in advance for your help!

A: Good start but you weren't reading in the JSON at all. This should give you a better idea of how to loop this, but it currently does not handle the case of a CEP not being found - I'll leave you to figure out that logic. Otherwise it does work to create a table with CEP + Coordinates you can merge. Rather than the JSON text, I suggest storing the ALLDATA from the JSON and reformat that to the required structured.
data AMOSTRA_ENTIDADE;
infile datalines delimiter=',';
length  CODEMPRESA 3.
        NOMEEMPRESA $9
        CEP $8;

input   CODEMPRESA
        NOMEEMPRESA $
        CEP;
datalines;
1,EMPRESA A,71577090
2,EMPRESA B,01026010
10,EMPRESA C,01000000
100,EMPRESA D,92300000
110,EMPRESA E,29010580
;
run;

proc sql;
drop table master_locations;
drop table master_allData;
quit;

%macro get_lat_long(cep);
  %let site="https://brasilapi.com.br/api/cep/v2/&CEP";
  %put NOTE: &site.;
  filename resp temp;

  proc http
     url = &site
     method = "get"
     out = resp;
  run;

  libname resp json;

  *keep all data if desired;
  data fullResponse;
      length Value $200.;
      set resp.allData;

  run;

  *get location coordinates from RESP library;
  data location;
      set resp.location_coordinates;
      CEP=&CEP.;
  run;

  *append to master file;
  proc append base= master_locations data=location;
  run;

  proc append base=master_allData data=fullResponse;
  run;

  *remove temporary tables so you do not get wrong data between loops;
  proc sql;
  drop table location;
  drop table fullresponse;
  quit;

  %mend get_lat_long;

  data COORDENADAS_ENTIDADE;
   set AMOSTRA_ENTIDADE;
   length macro_call $200;

   macro_call  = cats('%get_lat_long(',CEP,')');
   call execute(macro_call);
run;


text:
Q: How to prevent hotlinking of streaming content? I have a directory with my media files and I need no to display them on other sites.
Server doesn't support .htaccess, because it uses nginx.
How can I enable hotlink protection for my files??
Thank you.

A: Easiest way would be to check for the Referer header in HTTP request. Basically if that header does not have URL from your site, then this could be hot linking.
This has following problems:

*

*Referrer header can be forged -> hot linking works

*All user agents do not necessarily send the Referrer header -> legitimate user might not get the content.

You could also set a cookie when user is browsing your site, and check for existence of that cookie when user is accessing the streaming content.

A: The details may be dated, but Igor gives an example of referrer mapping for image hotlink protection that might be useful here: http://nginx.org/pipermail/nginx/2007-June/001082.html
If you decide to go the referrer route.
If you are using memcached you could also store store client IP addresses for a time and only serve up your streaming media if an unexpired client IP is found in the cache. The client IP gets cached during normal browsing ensuring that the person viewing your streaming content has also recently been visiting your site.

A: On my hostgator site, they used nginx as a proxy to Apache(nginx+apache). maybe that will help you. Also if you have access to the logs, if you see a lot of traffic that way from a ip I would investigate, and if it points to a site, then block the other web server. Php's file_get_contents doesn't get stopped by htaccess or anything else I know besides blocking the ip.


text:
Q: Rspec for Detecting devises This is my task
1) Create a new route localhost:3000/device
2) Consider if this url is hit from the mobile phones or desktop browsers, then
3) Track the system/device (iOS, android, web) from which the URL is hit
4) Based on the device from which the request has come, we need to redirect to some other URL (e.g., iOS ——> "iOS app store", android ——> "Android play store", web ——> "google page")
5) Find what are the different approaches that are available to track the system from which the request has come and what would be the best one to implement and why?
Here I found a solution, but in rspec it causes error.
This is my route
get :devise, to: 'topics#devise'

And this is my controller
class TopicsController < ApplicationController
  def devise
    if request.env['HTTP_USER_AGENT'].downcase.match(/mac/i)
      redirect_to 'https://itunes.apple.com/us/app/apple-store/id375380948?mt=8'
    elsif request.env['HTTP_USER_AGENT'].downcase.match(/windows/i)
      redirect_to 'https://www.microsoft.com/en-in/store/apps/windows'
    elsif request.env['HTTP_USER_AGENT'].downcase.match(/android/i)
      redirect_to 'https://play.google.com/store?hl=en'
    else
      redirect_to root_path
    end
  end
end

When I hit url lvh.me:3000/devise it redirects to the respective app store.
This is my controller spec
context 'devise' do
  it 'should detect the device' do
    get :devise
    response.should redirect_to '/https://www.microsoft.com/en-in/store/apps/windows'
  end
end

and this caused the error:

Expected response to be a redirect to http://test.host/https://www.microsoft.com/en-in/store/apps/windows but was a redirect to http://test.host/.
   Expected "http://test.host/https://www.microsoft.com/en-in/store/apps/windows" to be === "http://test.host/".

If I did it in a wrong way, tell some suggestion for doing rspec

A: If your rails version is not too ancient in controller you can use request.user_agent (it will look into env anyway, but this makes code cleaner)
Browsers pass user agent in header User-agent (which in turn ends up in rack env), so you need to simulate this in your tests.
For testing this I'd recommend using request  specs instead of controller ones (which are deprecated in rails 5):
 RSpec.describe 'Topics...', type: :request do
   it "redirects for ios" do
     get '/your/topcis/path/here', headers: { 'HTTP_USER_AGENT' => 'iPhone' }
     expect(response).to redirect_to(/\.apple\.com/)
   end
 end

(above uses rails 5, for older rails headers will be just hash, not a keyword argument)
Also you can write your method with case statement:
def devise
  redirect_to case request.user_agent.downcase
              when /mac/i     then 'https://itunes.apple.com/us/app/apple-store/id375380948?mt=8'
              when /windows/i then 'https://www.microsoft.com/en-in/store/apps/windows'
              when /android/i then 'https://play.google.com/store?hl=en'
              else
                root_path
              end
end


text:
Q: Group objects with matching properties into Lists I have a List of objects in C#.  All the objects contain properties code1 and code2 (among other properties).
Example:
List -> object = id, name, code1, code2, hours, amount.

There are 31 possible code1 values.
There are 10 possible code2 values.
I need to group together all objects having the same code1 and code2 values (the unique combination) into their own Lists which would be saved within a parent list (so that each individual list could be iterated over later.)

A: Enumerable extensions is your friend (are* your friends? :)
var groups = lists.GroupBy(item => new { item.code1, item.code2 });

And....the legendary Skeet hit post before I did, the SHAME!
Time to one up Skeet (ha, right). You could also group your common items in a dictionary.
var mapping = list
  .GroupBy(item => new { item.code1, item.code2 })
  .ToDictionary(g => g.Key, g => g.ToList());

Now mapping is a Dictionary<anon{code1, code2}, List<YourObject>>. Of course you could leave off the ToList for the value, and the value type of the dictionary would be an IGrouping, which is an IEnumerable.
You could also use ToLookup
var lookup = list.ToLookup(item => new { item.code1, item.code2 });

The result is an ILookup which has a key of the key Type given, and is an IEnumerable of the list type used. It's not a dictionary, but can be used similarly.

A: Sounds like you want something like:
var groups = list.GroupBy(x => new { x.code1, x.code2 });

// Example of iterating...
foreach (var group in groups)
{
    Console.WriteLine("{0} / {1}:", group.Key.code1, group.Key.code2);
    foreach (var item in group)
    {
        Console.WriteLine("  {0} ({1})", item.id, item.name);
    }
}


text:
Q: System.Windows.Forms.Keys - Lower or Uppercase? I have been searching around for an answer to this but I can't seem to find anything. Does anyone know if you can determine the letter casing in Keys?
For example:
if (System.Windows.Forms.Keys.A.ToString() == "A")
{
    // Upper or Lower?
}

Thanks.

A: There is no casing, it represents a physical key on your keyboard.  Do you see an 'a' and an 'A' on your keyboard?
You can check and see if a Shift key is depressed.

A: System.Windows.Forms.Keys.A represents the physical key A on your keyboard. It does not have a case. Thus, your question does not make sense.
If you want to check whether the user holds the Shift key on the keybord, there's also System.Windows.Forms.Keys.Shift.

A: There is no simple mapping between keys and characters. Keyboard layouts can work differently. One example are dead keys. And once you get to IMEs it gets even more complicated. Do not try to duplicate a keyboard layout manually in your application.
If you want to get what character a user entered, handle WM_CHAR, not WM_KEY_DOWN/UP. It's exposed as Control.KeyPress event in winforms.


text:
Q: AJAX Event Handlers - beforeSend, fail and done I am trying to attach an "on begin" handler to an AJAX call but I am getting
TypeError: request.beforeSend is not a function
As far as what I read on the JQuery docs site, the following should work, but alas, something is amuck. Thanks for looking
(Using JQuery 1.10.2)
  //Init the AJAX request and send
            var request = $.ajax({
                type: "POST",
                traditional: true,
                dataType: "html",
                url: "/NewClubOpeningTool/DeleteSelectedEmails/",
                data: { delete : checkedValues,clubId:"@Model.NewClub_Id" },
                cache: true
            });

            request.beforeSend(function() {

                $("#loading-area").show();

            });

            request.done(function (payload) {

            $("#loading-area").hide();
                //Do stuff ...

            });

            request.fail(function (jqXHR, textStatus) {

                 $("#loading-area").hide();
                //Do stuff...
            });

A: Try
var request = $.ajax({
                type: "POST",
                traditional: true,
                dataType: "html",
                url: "/NewClubOpeningTool/DeleteSelectedEmails/",
                data: { delete : checkedValues,clubId:"@Model.NewClub_Id" },
                cache: true,
                beforeSend : function() {
                              $("#loading-area").show()
                             }
                });


text:
Q: AJAX loop not finishing first request before starting next I am trying to create a simple script that loops through all the inputs in a table, and submits an AJAX GET request for each one whose value is greater than one. For some reason, it seems that my script never manages to successfully complete all AJAX requests. I know if I set async: false on the AJAX request, it will succeed, but it is not best practice and also slows down the browser.
Any ideas how to fix this? I searched all over, found many relevant answers, but could not manage to achieve a fix for the script.
$('#OrderSubmit').click(function() {
    $('.OrderForm').find('.pid-input').each(function(j, element) {
        qty = $(element).val();
        if (qty > 0) {
            pid = $(element).data("pid");
            $.ajax({
                url: "/cart.php?action=add&product_id=" + pid + "&qty=" + qty
            });
        }
    });
});

A: Your code seems fine.
May be you are sending request in a loop. From server side there might be restriction for subsequent request from one client.
Its possible because one can crash the server or reduce the service quality by simply sending requests continuously.
Try giving  timeout of few milliseconds if this satisfies the server.
$('#OrderSubmit').click(function() {
var i=0;
$('.OrderForm').find('.pid-input').each(function(j, element) {
    qty = $(element).val();
    if (qty > 0) {

        i++;
        pid = $(element).data("pid");
        setTimeout(function(pid,qty)
          {
      $.ajax({
            url: "/cart.php?action=add&product_id=" + pid + "&qty=" + qty
        });
          }.bind({},pid,qty),i*1000);

    }
});
});


text:
Q: No response from AJAX call I am not getting any response from my AJAX call to the API.
Few days back it was working fine and I was getting response JSON but now I am not able to get any JSON object.
Mozilla does not give response JSON but shows no error but in Chrome I am getting net::ERR_INSECURE_RESPONSE
AngularJS code:
app.controller("LoginCtrl",
        function($scope, $http,$location,$rootScope) {
    $scope.login = function(user){
        $http({
            method: "POST",
            url: "https://aadvq11nwbv01.staples.com/wcs/resources/v1/member/login?storeId=10101&responseFormat=json",
            /*header: "Access-Control-Allow-Origin:*",*/
            header: "Content-Type: application/json",
            header: "Accept: application/json",
            data:{
                companyID: $scope.user.customerid,
                userID: $scope.user.userid,
                password: $scope.user.password
            }
        })
        .success(function (response){
            $rootScope.profile="xxx";
            userDetails = response;
            console.log(userDetails);
            $location.url("/profile")
        })
        .error(function (err){
            $scope.logerr="err";
            console.log(err);
        });
    }
});

A: The reason could be you have specified in wrong way. header should be an object then define its properties in it.
Code
    $http({
        method: "POST",
        url: "https://aadvq11nwbv01.staples.com/wcs/resources/v1/member/login?storeId=10101&responseFormat=json",
        header: {
            "Content-Type: application/json",
            "Accept: application/json"
        },
        data:{
            companyID: $scope.user.customerid,
            userID: $scope.user.userid,
            password: $scope.user.password
        }
    })

A: The reason you get the error is that the SSL certificate provided by the webserver is not recognised and therefore not trusted. If you are using a self-signed certificate on your webserver this will explain it. Otherwise there is an issue with the setup of your certificate.


text:
Q: Python: get secure cookies using Selenium Let me explain what is the issue in my case:

*

*Go to site: "https://example.com"

*Choose login using Google account;

*You will be redirected to google login page;

*Fill username and password and click on "Next";

*Login with success;

*Open Developers Tools and > Application, in Cookies it will be possible to find some secure cookies like: "access_token" and "USERAUTH"

*When I'm trying to retrieve this values using Selenium - with no luck. However, in browser I'm able to see required values in Developer Tools.

So, How is it possible to retrieve all cookies from the site?
Below example of my code:
def main():
    main_window_handle = None
    session = requests.Session()
    driver = webdriver.Chrome('C:/chromedriver.exe')
    driver.delete_all_cookies() # clean up the prior login sessions
    driver.get('https://example.com/') # change the url to your website
    while not main_window_handle:
        main_window_handle = driver.current_window_handle
    time.sleep(2)
    driver.find_element_by_xpath("//*[@id=\"sign-in-container__social-services\"]/button").click()
    signin_window_handle = None
    while not signin_window_handle:
        for handle in driver.window_handles:
            if handle != main_window_handle:
                signin_window_handle = handle
                break
    driver.switch_to.window(signin_window_handle)
    driver.find_element_by_xpath("//*[@id=\"identifierId\"]").send_keys("")
    driver.find_element_by_xpath("//*[@id=\"identifierNext\"]/span/span").click()
    time.sleep(2)
    driver.find_element_by_xpath("//*[@id=\"password\"]/div[1]/div/div[1]/input").send_keys("")
    driver.find_element_by_xpath("//*[@id=\"passwordNext\"]/span/span").click()
    time.sleep(5)
    driver.switch_to.window(main_window_handle)
    time.sleep(5)
    driver.delete_all_cookies()
    driver.refresh()
    time.sleep(10)
    cookies_list = driver.get_cookies()
    print(driver.get_cookies())
    response = session.get('https://example.com/')
    print(session.cookies.get_dict())
    cookies_dict = {}
    for cookie in cookies_list:
        cookies_dict[cookie['name']] = cookie['value']
    access_token = cookies_dict.get('access_token') # getting None on this step
    print(access_token)
    time.sleep(60)

if __name__ == "__main__":
    main()


text:
Q: Can I listen to the clientWidth/clientHeight properties on a div? As the title says, can I add a listener to a div to get when the clientWidth and clientHeight values change?

A: Not directly no. If the width of the div is determined by the window width however you can attach a resize event to the window and when that fires you can grab the size of your div directly.


text:
Q: c++ syncing of cin and cout with iostream need some help here;
  look at this code:
#include<bits/stdc++.h>
 using namespace std;
 int main()
{   ios::sync_with_stdio(false);
    cin.tie(false);
    while(true)
    {
        int x;
        cin>>x;
        cout<<x<<"\n";

        if(x==42){
            break;
        }

    }
    return 0;
}

and now this:
#include<bits/stdc++.h>
using namespace std;
int main()
{
    while(true)
    {
        int x;
        cin>>x;
        cout<<x<<"\n";

            if(x==42){
            break;
        }

    }
    return 0;
}

when i run both the codes,the first one accepts all the inputs first and then shows output; But with same code the second one reads and prints simultaneously
what's the problem here, i cant understand;

A: The difference is cin.tie(false); (which should really be cin.tie(nullptr);). It removes the tie between cin and cout.
By default the streams are buffered, so the text written to cout is not displayed until the buffer is full or the stream is flushed, whichever happens first.
But, also by default, cin is "tied" to cout and flushes the buffer before each input. That makes any prompts written to cout visible before the input.


text:
Q: Android context outside of Activity class I am trying to handle exceptions in my application. I am trying to log the exception, then use Toast to alert the user that there was a problem. I have this working find in all my class's that extend Activity.
However, in any class that does not extended activity I can not use the toast method as I can't get the current context. Is there a simple way to get around this or should all my class's extend Activity?

A: You just pass Context
When You call Non-Activity  class from Activity class call Like
YourNonActivtyClass obj = new YourNonActivtyClass(Activity.this);

A: I came up with a solution using RXJava and Kotlin. It should be easy enough to recreate it in Java though. This is a singleton class that simply has a getter and setter. The getter creates an observable instance of context, which is set by an Activity via setContext(context: Context)
object AndroidContextObservable { // needs to be singleton.

    private lateinit var context: Context

    fun context(): Observable<Context> {
        return Observable.create { subscriber ->
            subscriber.onNext(this.context)
            subscriber.onComplete()
        }
    }

    fun setContext(context: Context) {
        this.context = context
    }
}

Say I have a service that uses GoogleCalendars: I'd first set it in my activity:
class ViewMeetingRoomDataActivity : AppCompatActivity() {
    @Inject lateinit var googleCalendarsService: GoogleCalendarService // abstraction over the GoogleCalendarAPI Class (Below)

    private var subscriptions: Disposable = Disposable.empty()
    private lateinit var meetingRoomBundleData: ParcelableMeetingRoomData

    override fun onCreate(savedInstanceState: Bundle?) {
        super.onCreate(savedInstanceState)
        AndroidContextObservable.setContext(this) // set the context here
        DaggerServiceModuleComponent.create().inject(this)

        setContentView(R.layout.activity_view_meeting_room_data)
    }

    override fun onPause() {
        super.onPause()

        this.subscriptions.dispose()
    }

}

And then because the observable comes from a singleton, we can subscribe to it in the init lifecycle hook.
@Module
class GoogleCalendarsApiServiceModule @Inject constructor(): IGoogleCalendarsApiServiceModule {

    private lateinit var googleCredential: Credential
    private lateinit var googleCalendarService: Calendar

    private val httpTransport: NetHttpTransport = NetHttpTransport()
    private val subscriptions: Disposable = Disposable.empty()

    init {
    // Subscribe to the context
        this.subscriptions.apply {
            AndroidContextObservable.context()
                .subscribe { context ->
                    googleCredential = GoogleCredentialsBuilder.getCredentials(httpTransport, context)
                    googleCalendarService = ServiceBuilder.buildGoogleCalendarService(googleCredential, httpTransport)
                }
        }
    }

    fun finalize() {
        this.subscriptions.dispose() // <-- Don't forget to discard Observables :)
    }
}

I like this solution because it's testable and the context now comes from a single source of truth. It was the cleanest way I could think of getting context outside of an Activity.
Hoped I've helped.

A: Toast messages should work within the application context, i.e.
Toast.makeText(getApplicationContext(), ...);


text:
Q: Zend Framework - tinyMCE - plugin folders are mistaken to be controllers? Help Hi guys I'm trying to integrate the tinymce plugin however I'm running into problems such that almost every feature which requires a plugin to be rendered i.e the add url popup or add image pop up - it opens an empty pop up window. Even if I try to open it inline I get the same blank popup window.. I noticed that whenever I click on lets say url button in tinymCE it opens with reference to my localhost and because of that I'm assuming my application is mistaking the containing javascript folder to be some controller or action.
How can I fix this please - I've set up mod rewrite to allow clean urls as well as ignore the javascript folder but this is a different issue altogether :(
what should I be looking at here.. I can't notice any error sin firebug..

A: Try putting .htaccess with following contents into your MCE directory:
RewriteEngine Off

A: OUCH sorry - I figured it out ... apparently I had set up my htaccess file to ignore file extensions of images but the templates loaded had a file extension of .htm... just added the new extensions to the htaccess and got it fixed.. sorry for panicking  thanks anyway!


text:
Q: Is it possible to express a vector using cross product with another vector? I was wondering if it was possible to find $\overrightarrow{a}$ when it is given that:
$$ \overrightarrow{a} \times \overrightarrow{b} = \overrightarrow{c}$$
Vectors $\overrightarrow{b}$ and $\overrightarrow{c}$ are known. How can I express vector $\overrightarrow{a}$ using $\overrightarrow{b}$ and $\overrightarrow{c}$??

A: $\underline{a}$ would have to be a vector perpendicular to $\underline{c}$ but not parallel to $\underline{b}.$
You would therefore have to find parameters $\lambda$ and $\mu$ so that, for example $$\underline {a}=\lambda\underline{b}+\mu\underline{b}\times\underline{c}$$ where $\mu\neq0.$
We then have $$\underline{a}\times\underline{b}=(\lambda\underline{b}+\mu\underline{b}\times\underline{c})\times\underline{b}$$
$$=0+\mu(\underline{c}(b\cdot b)-\underline{b}(b\cdot c))$$
But $b\cdot c=0$ since they are perpendicular, so $\mu$ is predetermined and has value $\frac{1}{(b\cdot b)}$ and $\lambda$ is arbitrary.
So while $\underline{a}$ is not unique, it can be found for specific non parallel vectors $\underline{b}$ and $\underline{c}$

A: As mentioned elsewhere, only the components of $\vec{a}$ perpendicular to $\vec{b}$ can be found.
Use $$ \vec{a}_\perp = \frac{\vec{b}\times\vec{c}}{\| \vec{b} \|^2} $$
Proof
Vector $\vec{a}$ is assumed to contain both perpendicular and parallel components to $\vec{b}$ such that $\vec{a} = \vec{a}_\parallel + \vec{a}_\perp$.
Now form $\vec{c} = \vec{a} \times \vec{b}$
$$ \vec{c} = (\vec{a}_\parallel + \vec{a}_\perp) \times \vec{b} $$
and use the formula above
$$ \vec{c} = \left(\vec{a}_\parallel + \frac{\vec{b}\times\vec{c}}{\| \vec{b} \|^2}\right) \times \vec{b} $$
Since $\vec{a}_\parallel$ is parallel to $\vec{b}$, it stands that  $\vec{a}_\parallel \times \vec{b} =0 $
$$ \vec{c} = \frac{ (\vec{b}\times\vec{c})\times \vec{b} }{\vec{b} \cdot \vec{b}} = \frac{\vec{b} \times (\vec{c} \times \vec{b} )}{\vec{b} \cdot \vec{b}} = \frac{\vec{c} (\vec{b} \cdot \vec{b}) - \vec{b} (\vec{c}\cdot\vec{b}))}{\vec{b} \cdot \vec{b}} = \vec{c}$$
which is an application of the vector triple product. The above is true since $\vec{c}\cdot\vec{b}=0$ with them being perpendicular to each other.

A: Generally this is not possible. If you have the equation
$$
\overrightarrow{a} \times \overrightarrow{b} = \overrightarrow{c} \tag{1}
$$
for arbitrary $\overrightarrow{b},\overrightarrow{c}\in \mathbb{R}^3$ it is not always possible to find a proper $\overrightarrow{a}$, simply because it might not exist.
As it was already pointed out in the answer of @DavidQuinn, the resulting vector  $\overrightarrow{c}$ is perpendicular to $\overrightarrow{a},\overrightarrow{b}$ and therefore to the $\operatorname{span}(\overrightarrow{a},\overrightarrow{b})$.
So for example if we choose $\overrightarrow{b}=\overrightarrow{c}$, then
$$
\overrightarrow{a} \times \overrightarrow{b} = \overrightarrow{c}=\overrightarrow{b}
$$
is not even well defined (and we don't need to speak of a solution for  $\overrightarrow{a} $ of any kind).
So let's now assume $(1)$ is well defined - which seems to be your intention - then if we find a solution, it is for sure not unique (as @Arthur already pointed out). This is because the following holds
$$
\overrightarrow{a} \times (\overrightarrow{b}+\overrightarrow{c}) = (\overrightarrow{a} \times \overrightarrow{b})+(\overrightarrow{a} \times \overrightarrow{c})
$$
So assume we've found $\overrightarrow{a}$ which solves $(1)$, then we can simply add any to $\overrightarrow{b}$ parallel vector $\overrightarrow{d}$   and $(1)$ would still hold, because
$$
(\overrightarrow{a}+\overrightarrow{d}) \times \overrightarrow{b} = (\overrightarrow{a} \times \overrightarrow{b})+(\overrightarrow{d} \times \overrightarrow{b})=(\overrightarrow{a} \times \overrightarrow{b})+\overrightarrow{0}=\overrightarrow{c}
$$
Unfortunately, I am not aware of an algorithm which would gives us a solution $\overrightarrow{a}$ in the first place.

A: Assume $b, c\not = 0$. Note first that we must have $(a, c), (b, c) = 0$. Choose some vector $b'$ orthogonal to both $b$ and $c$, and write $a = \alpha b + \alpha' b'$. Then $a\times b = \alpha' (b\times b')$; and since $b, b', c$ are pairwise orthogonal, we have $b'\times b = \beta c$ for some constant $c\not = 0$. Thus $\beta$ determines $\alpha'$, and $\alpha$ is arbitrary. Specifically, for $b' = b\times c$, we have $b'\times b = |b|^2 c$ and thus $\alpha' = |b|^{-2}$.

A: Why is everybody assuming 3-dimensional vectors? There is a very intersting cross product in seven dimensions as well; it is anti-commutative, therefore $\mathbf a\times \mathbf b= -\mathbf b \times \mathbf a= \mathbf c$ and can be written in a matrix form:
$$    T_{\mathbf x} = \begin{bmatrix} 0 & -x_4 & -x_7 & x_2 & -x_6 & x_5 & x_3 \\ x_4 & 0 & -x_5 & -x_1 & x_3 & -x_7 & x_6 \\ x_7 & x_5 & 0 & -x_6 & -x_2 & x_4 & -x_1 \\ -x_2 & x_1 & x_6 & 0 & -x_7 & -x_3 & x_5 \\ x_6 & -x_3 & x_2 & x_7 & 0 & -x_1 & -x_4 \\ -x_5 & x_7 & -x_4 & x_3 & x_1 & 0 & -x_2 \\ -x_3 & -x_6 & x_1 & -x_5 & x_4 & x_2 & 0 \end{bmatrix}.
$$
The cross product is then given by
$    -\mathbf{b} \times \mathbf{a} = -T_{\mathbf{b}}\cdot \mathbf{a}=\mathbf{c}$. Calculate $-T_{\mathbf{b}}^{-1}\mathbf{c}$ (if possible!) and you're done...

A: The question is easy to answer using geometric algebra (GA). Let me first state the answer (which is of course the same as reached in the answer by ja72) to pique your interest:
$$
a = \frac{1}{|b|^2}(\alpha b - c \times b)
$$
where $\alpha$ is an arbitrary real number, and $b$ must be orthogonal to $c$ in order for the problem to be well-posed. This is easy to check using the vector triple product, as ja72's answer shows.
Now, how does one get this using geometric algebra? There are several good introductions to GA online, so I won't write a new one here, but I'll provide some links in the end of the post. Now, assuming the basics are understood, we can immediately translate the problem in terms of the wedge product and the dual, using the relation
$$
a\times b  = a\wedge b I^{-1},
$$
where $I$ is the pseudoscalar in 3D space, and $I^{-1} = -I$ is its inverse with respect to the geometric product. This gives:
$$
a \wedge b = c I.
$$
The inner product product of $a$ and $b$ is some real number, say $a \cdot b = \alpha$. Let us add this to the wedge product to get
$$
a\cdot b + a\wedge b = ab = \alpha + cI,
$$
where the first identity is a fundamental formula in GA concerning the products of vectors.
Since vectors in GA have an inverse with respect to the geometric product, we can multiply from the right with $b^{-1} = \frac{b}{b^2}$ to get
$$
a = \left(\alpha + c I\right)b^{-1} = \frac{1}{b^2}\left(\alpha b + cb I\right).
$$
The fact that $b$ and $c$ must be orthogonal appears here in the form that if they are not, then $cb$ will have a three-vector component, and $a$ won't be a vector. It was of course also apparent in the first equation we wrote, since the dual of a vector in three dimensions is always a bivector orthogonal to the vector itself.
The previous formula is already the answer, but let us translate it back to the cross product form to get
$$
a = \frac{1}{b^2}\left(\alpha b + c\wedge b I^{-1} I I\right) = \frac{1}{b^2}\left(\alpha b - c\times b\right),
$$
where we inserted $I^{-1} I  = 1$ to the second term to get the cross product to appear, and used $I^2 = -1$.
If this got you interested in learning GA, the wikipedia article is not a bad place to start. Here some more links, though which of them are most useful depend on what's your mathematical background:

*

*Imaginary numbers are not real

*Lecture notes for a course on GA

*A slightly more mathematical, but thorough, introduction

*Geometric algebra for physicists
Google will find a lot more sources, which of them are best for you depends on your starting level, as I mentioned.


text:
Q: What is the correct way of retrieving ParseUser using include.() I'm fairly new to Parse and I have 2 classes. The User class and another class that I called "Group". The Group class has a field called "users" where I keep ParseUser objects.
 ParseQuery<ParseObject> query = ParseQuery.getQuery("Group");
    query.include("users");
    query.findInBackground(new FindCallback<ParseObject>() {
        @Override
        public void done(List<ParseObject> parseObjects, ParseException e) {
            Log.v(TAG, ""+parseObjects);
        }
    });

The parseObjects returned null, and I'm not sure where I went wrong. Any help?


text:
Q: Hyperledger Fabric on AWS ECS not instantiate chaincode I'm working on setting Hyperledger Fabric network on AWS ECS. Here's my network network and bootstrap scenarios.
Network

*

*ca-org0, ca-org1, ca-org2

*orderer-org0

*peer1-org1, peer1-org2

Bootstrap sceanrios

*

*All nodes are successfully started, create crypto materials, peers and orderers are registered and enrolled to CA ...

*create 'mychannel' channel

*join peer1-org1, peer1-org2 to 'mychannel'

*update both peers as anchor peer

*both peers install 'abac' sample chaincode

*peer1-org1 instantiate 'abac' chaincode to 'mychannel'

*test invoke and query

ECS
each node is ECS service with 1 task with networkMode awsvpc. and every service is created with AWS Service Discovery so each service can be look up with DNS. In my case peer1-org1 can be look up in vpc using peer1-org1.ns-t2c, orderer1-org0 as orderer1-org0.ns-t2c ...
ECS cluster diagram
Problem
I have been successfully done installing chaincode (step 5 in 'Bootstrap sceanrios') and chaincode container is created in EC2
peer1-org1:$ peer chaincode instantiate -C mychannel -n mycc -v 1.0 -c '{"Args":["init","a","100","b","200"]}' -P "OR('org1MSP.member','org2MSP.member')" -o orderer1-org0.ns-test

And this instantiate command successfully done w/o error and chaincode container is created on peer1-org1's EC2
peer1-org1's EC2:$ docker ps
CONTAINER ID        IMAGE                              COMMAND                  CREATED             STATUS              PORTS              NAMES
3f7a488475cb        dev-peer1-org1.ns-t2c-mycc-1.0    "chaincode -peer.add…"   17 seconds ago      Up 16 seconds                         dev-peer1-org1.ns-t2c-mycc-1.0
<below is peer1-org1 container info>

But when I execute peer chaincode list --instantiated -C mychannel, No chaincode listed
peer1-org1:$ peer chaincode list --instantiated -C mychannel
Get instantiated chaincodes on channel mychannel:
peer1-org1:$

When queried 'abac' chaincode
peer1-org1$: peer chaincode query -C mychannel -n mycc -c '{"Args":["query","a"]}'
Error: endorsement failure during query. response: status:500 message:"make sure the chaincode mycc has been successfully instantiated and try again: getccdata mychannel/mycc responded with error: could not find chaincode with name 'mycc'"

And here's peer task definition
{
  "family": "peer1-org1",
  "networkMode": "awsvpc",
  "containerDefinitions" : [
    {
      "name": "peer1-org1",
      "image": "hyperledger/fabric-ca-peer:1.2.0",
      "essential": true,
      "memory": 128,
      "command": ["/bin/bash", "-c", "'/scripts/ecs_start-peer.sh'"],
      "environment": [
        {"name": "FABRIC_CA_CLIENT_HOME", "value": "/data/peers/peer1-org1.ns-t2c"},
        {"name": "FABRIC_CA_CLIENT_TLS_CERTFILES", "value": "/data/org1-ca-chain.pem"},
        {"name": "ENROLLMENT_URL", "value": "http://peer1-org1.ns-t2c:peer1-org1.ns-t2cpw@ica-org1.ns-t2c:7054"},
        {"name": "PEER_NAME", "value": "peer1-org1.ns-t2c"},
        {"name": "PEER_HOME", "value": "/data/peers/peer1-org1.ns-t2c"},
        {"name": "PEER_HOST", "value": "peer1-org1.ns-t2c"},
        {"name": "PEER_NAME_PASS", "value": "peer1-org1.ns-t2c:peer1-org1.ns-t2cpw"},
        {"name": "CORE_PEER_ID", "value": "peer1-org1.ns-t2c"},
        {"name": "CORE_PEER_ADDRESS", "value": "peer1-org1.ns-t2c:7051"},
        {"name": "CORE_PEER_LOCALMSPID", "value": "org1MSP"},
        {"name": "CORE_PEER_MSPCONFIGPATH", "value": "/data/peers/peer1-org1.ns-t2c/msp"},
        {"name": "CORE_VM_ENDPOINT", "value": "unix:///host/var/run/docker.sock"},
        {"name": "CORE_LOGGING_LEVEL", "value": "DEBUG"},
        {"name": "CORE_PEER_TLS_ENABLED", "value": "true"},
        {"name": "CORE_PEER_TLS_CERT_FILE", "value": "/data/peers/peer1-org1.ns-t2c/tls/server.crt"},
        {"name": "CORE_PEER_TLS_KEY_FILE", "value": "/data/peers/peer1-org1.ns-t2c/tls/server.key"},
        {"name": "CORE_PEER_TLS_ROOTCERT_FILE", "value": "/data/org1-ca-chain.pem"},
        {"name": "CORE_PEER_TLS_CLIENTAUTHREQUIRED", "value": "true"},
        {"name": "CORE_PEER_TLS_CLIENTROOTCAS_FILES", "value": "/data/org1-ca-chain.pem"},
        {"name": "CORE_PEER_TLS_CLIENTCERT_FILE", "value": "/data/tls/peer1-org1.ns-t2c-client.crt"},
        {"name": "CORE_PEER_TLS_CLIENTKEY_FILE", "value": "/data/tls/peer1-org1.ns-t2c-client.key"},
        {"name": "CORE_PEER_GOSSIP_USELEADERELECTION", "value": "true"},
        {"name": "CORE_PEER_GOSSIP_ORGLEADER", "value": "false"},
        {"name": "CORE_PEER_GOSSIP_EXTERNALENDPOINT", "value": "peer1-org1.ns-t2c:7051"},
        {"name": "CORE_PEER_GOSSIP_SKIPHANDSHAKE", "value": "true"},
        {"name": "ORG", "value": "org1"},
        {"name": "ORG_ADMIN_CERT", "value": "/data/orgs/org1/msp/admincerts/cert.pem"},
        {"name": "CORE_PEER_ADDRESSAUTODETECT", "value": "true"},
        {"name": "CORE_PEER_CHAINCODELISTENADDRESS", "value": "0.0.0.0:7052"},
        {"name": "CORE_VM_DOCKER_ATTACHSTDOUT", "value": "true"}
      ],
      "mountPoints": [
        {
          "containerPath": "/scripts",
          "sourceVolume": "scripts"
        },
        {
          "containerPath": "/data",
          "sourceVolume" : "data"
        },
        {
          "containerPath": "/host/var/run",
          "sourceVolume": "run"
        }
      ],
      "portMappings": [
        {
          "containerPort": 7051
        },
        {
          "containerPort": 7053
        }
      ]
    }
  ],
  "volumes": [
    {
      "name": "scripts",
      "host": {
        "sourcePath":"/efs/scripts"
      }
    },
    {
      "name": "data",
      "host": {
        "sourcePath": "/efs/data"
      }
    },
    {
      "name": "run",
      "host": {
        "sourcePath": "/var/run"
      }
    }
  ]
}

I've referenced here and here to reference peer ENV variables but no worked..

A: I had the same problem: my chaincode was successfully installed and instantiated, but I also got the error: "could not find chaincode with name 'mycc'"
The cause in my situation was: The anchor peers had a incorrect hostname configured in configtx.yaml (example: Organizations > &Org > AnchorPeers > Host)
The solution for me was to set the hostname to the correct value.
Hope this helps anyone.


text:
Q: Java - Using Recursion to Find Palindrome I am designing a util class that takes a string as a parameter and returns true if it is a palindrome(ex: input: radar ---> output: true) and returns false if it is not. For this class, I am using a linkedlist, however I don't know why there seems to be an error. Here is the stack trace:
Exception in thread "main" java.lang.IndexOutOfBoundsException: Index: 4, Size: 4
    at java.util.LinkedList.checkElementIndex(LinkedList.java:555)
    at java.util.LinkedList.remove(LinkedList.java:525)
    at com.run.FindPalindromes.FindMain(FindPalindromes.java:20)
    at com.run.FindPalindromes.FindMain(FindPalindromes.java:16)
    at com.run.Test.main(Test.java:7)

And Here is the source code:
public boolean FindMain(String in){
    if(times == 0){
    search = new LinkedList(cc.convertStringToArraylist(in));
    times ++;
    FindMain(null);
    } else {
        if(search.get(search.size()-1).equals(search.get(0))){
            search.remove(0);
            search.remove(search.size());
            FindMain(null);
        } else {
            System.out.println("Not Palindrome");
            return false;
        }
    }

    return true;

}

A: search.remove(search.size()) should be search.remove(search.size() - 1) since lists are zero-based. If you have four elements your list indices run from 0 to 3, and so there is nothing at location 4.
Also your code as it stands won't handle empty lists very well, so that's something you need to check.


text:
Q: What is the fastest and most accurate way to check if a website/URL exists.. Curl or PHP? What is the most accurate and fastest way to check if a URL exists? Example: Google.com.  I have been reading that I can use curl or I can use php file_exists() to locate the index file. I used this curl function...
function url_exists($url) {
    $ch = @curl_init($url);
    @curl_setopt($ch, CURLOPT_HEADER, TRUE);
    @curl_setopt($ch, CURLOPT_NOBODY, TRUE);
    @curl_setopt($ch, CURLOPT_FOLLOWLOCATION, FALSE);
    @curl_setopt($ch, CURLOPT_RETURNTRANSFER, TRUE);
    $status = array();
    preg_match('/HTTP\/.* ([0-9]+) .*/', @curl_exec($ch) , $status);
    return ($status[1] == 200);
}

for example google.com but it returns false for google and true for other sites. I guess I am looking for the best solution to this question.

A: If your looking for just a connection rather than a status code you can just use fopen...
if (!fopen($url, "r")) {
 // cannot connect
}

If you want to check the HTTP code then curl is probably the best way.


text:
Q: What is wrong in this ajax call? I'm trying to save some data to my database, using an Ajax-call, like i did hundrets of times before:
function saveNewGraphic() {
var svgString = drawObject.node().outerHTML;
if (logLevel >= 10) {
    console.log("svgEditor - saveNewGraphic");
    console.log("SVG-Grafik: " + svgString);
}

$.ajax({
    type: "POST",
    url: appBaseUrl + 'Symbols/SaveNewGraphic',
    data: {
        svgString: svgString,
        pageId: pageId
    },
    error: function () {
        alert("Fehler beim Speichern der neuen Grafik auf Seite (ID) " + pageId);
    },
    success: function (result) {
        if (logLevel >= 10) console.log("Grafik mit ID: " + result.data.ID + " gespeichert");
        //  svg.attr("id", result.data.ID);
    },
    async: false
});
}

svgString is ok and pageId also.
I tried same without error, success and async but it even doesn't hit the Controller-Action.
Only Message:
HTTP500: SERVERFEHLER: Es ist ein unerwarteter Zustand aufgetreten, sodass der Server die Anforderung nicht erfüllen kann.
(XHR)POST - http://localhost:52771/Symbols/SaveNewGraphic

This is the Action that should be hit:
    [HttpPost]
    [Authorize(Roles = RoleName.AdminOrEngineerOrSales)]
    public ActionResult SaveNewGraphic(string svgString, int pageId)
    {
        string message="ID fehlerhaft";
        //if (pageId == 0) message = "Neue Grafik wurde nicht gespeichert, Page-ID nicht lesbar" ;

        int id = 1;// SymbolDataProvider.SaveNewProjectGraphic(svgString, pageId, User.Identity.Name);
        //if(id >= 0) message = "Grafik erfolgreich gespeichert";

        var data = new { ID = id, Message = message };
        return Json(new { data, JsonRequestBehavior.AllowGet });
    }

It is strange that this Action would be hit (of Course if I Change the url).
    [HttpPost]
    [Authorize(Roles = RoleName.AdminOrEngineerOrSales)]
    public ActionResult SaveNewPosition(string positionData, int pageId, int id = 0, int symbolId = 0)
    {
        string message;
        if (id == 0)
            message = "Position nicht gespeichert, Id nicht lesbar";
        else if (SymbolDataProvider.SaveSymbolPosition(id, positionData, symbolId, pageId, User.Identity.Name))
            message = "Position gespeichert.";
        else
            message = "Position nicht gespeichert, Probleme beim Datenbankaufruf!";
        return Json(new { Message = message, JsonRequestBehavior.AllowGet });
    }

But I could not see the difference between them.


text:
Q: Can PostGIS use spatial indexes on foreign tables? I'm attempting to perform a query on some foreign spatial tables which is taking several orders of magnitude longer than running on the normal spatial table because the index is not used.
Indexes seem to be working on non-spatial queries.
Is this something that should work or is this not supported?

A: Assuming at least Postgres 9.6 for local and remote server, and the same version of PostGIS installed, running this on the local server should do the trick:
ALTER SERVER your_foreign_server_name OPTIONS (ADD extensions 'postgis');

Postgres can use indexes on a remote Postgres server. You may have to do more than for local tables, autovacuum does not run ANALYZE for remote tables automatically. Start by reading the chapter "Remote Query Optimization" in the manual.
Related answer with more details:

*

*Postgres 9.5 foreign table inheritance not using indexes

*Related blog post by Michael Paquier
Since PostGIS is an extension, this new feature of Postgres 9.6 is particularly relevant:

Allow extension-provided operators and functions to be sent for remote
execution, if the extension is whitelisted in the foreign server's
options (Paul Ramsey)
Users can enable this feature when the extension is known to exist in
a compatible version in the remote database. It allows more efficient
execution of queries involving extension operators.

Bold emphasis mine.
The use of indexes is bound to operators. Various PostGIS spatial functions are transformed to use operators internally when the query is planned. This related answer on SO has more explanation:

*

*Can PostgreSQL index array columns?


text:
Q: How to give to the strategy matrix a dynamic object based on the current filenames in the folder my goal is to have some job steps (docker build and push) to run on every Dockerfile I add in a specific folder.
This is the main structure I'm trying:
...

stages:
- stage: Get_DF_Stage
  displayName: Get_Dockerfiles
  jobs:
    - job: Get_DF_Job
      steps:
        - task: bash@3
          inputs:
            filePath: 'helpers/from_files_to_yaml_object.sh'
          displayName: Get_Dockerfiles
          name: Get_DF_Task

# --- Take the latest image on the private repo and retags it with the current date
- stage: Docker_Image_Patch
  displayName: Docker_Image_Patch
  dependsOn:
    - Get_DF_Stage
  jobs:
  - job: docker_login
    displayName: Login to COMPANY CR

    steps:
    - task: Docker@2
      displayName: Login to COMPANY Container Registry
      inputs:
        command: login
        containerRegistry: COMPANY-cr

  - job: docker_patch
    displayName: Build and push Docker images

    strategy:
      # $[ stageDependencies.Get_DF_Stage.Get_DF_Job.outputs['Get_DF_Task.dockerfile_list'] ]
      matrix:
        nginx:
          dockerfile: 'nginx'
        nginx-alpine:
          dockerfile: 'nginx-alpine'

    steps:
    - task: Docker@2
      displayName: Build Docker image
      inputs:
        command: build
        containerRegistry: COMPANY-cr
        Dockerfile: dockerfiles/$(dockerfile)
        repository: $(dockerfile)
        buildContext: .
        arguments: --no-cache --pull
        tags: latest

    - task: Docker@2
      displayName: Push Docker image
      inputs:
        command: push
        containerRegistry: COMPANY-cr
        repository: $(dockerfile)
        tags: latest

My idea is to generate the YAML executing a bash task, that will have this output:
nginx:
  dockerfile: 'nginx'
nginx-alpine:
  dockerfile: 'nginx-alpine'

For two files in the folder, named: 'nginx' and 'nginx-alpine'.
Then I would load that variable in the matrix through the stageDependencies command.
Is there a way to insert a YAML object from a bash script?
Or is there a simpler way to iterate jobs on files?

A: Yes this is possible in following way:
jobs:
- job: JobA
  steps:
  - pwsh: |
      $json="{'nginx': {'dockerfile': 'nginx'}, 'nginx-alpine': {'dockerfile': 'nginx-alpine'}}"
      Write-Host "##vso[task.setvariable variable=targets;isOutput=true]$json"
    name: setTargets
  - script: echo $(setTargets.targets)
    name: echovar

- job: buildSrc
  dependsOn: JobA
  displayName: Build source
  strategy:
    matrix: $[ dependencies.JobA.outputs['setTargets.targets'] ]
  variables:
    targets: $[ dependencies.JobA.outputs['setTargets.targets'] ]
  steps:
  - pwsh: Write-Host "${{ convertToJson(variables) }}"
    displayName: 'Print all variables via expression'

You can also check my answer to similar question here

A: In the end I've found out my solution wasn't working because I was trying to generate a YAML or a JSON Array, instead of a JSON MAP.
So I've modified my bash task to generate a JSON map based on the files in a specific folder:
#!/bin/bash
filenames_list="$(ls -1 dockerfiles/ |tr '\n' ' ' )"
filenames_list=($filenames_list)

filenames_tmp=""
for (( i=0; i<${#filenames_list[@]}; i++ ))
do
    echo "> Found '${filenames_list[$i]}'"
    filenames_tmp="${filenames_tmp}, \"${filenames_list[$i]}\":{\"dockerfile\":\"${filenames_list[$i]}\"}"
done

# Remove first void comma
filenames_tmp="${filenames_tmp[0]:2}"
# Create JSON
filenames_list="{ ${filenames_tmp[*]} }"

## --- Output: { "nginx": { "dockerfile": "nginx" }, "nginx-alpine": { "dockerfile": "nginx-alpine" }}
echo "> Result <${filenames_list}>"
echo "##vso[task.setvariable variable=dockerfile_list;isOutput=true]`echo "${filenames_list}"`"

Then I call the dockerfile variable from the second stage like this
- stage: Docker_Image_Patch
  displayName: Docker_Image_Patch
  dependsOn:
    - Get_DF_Stage
  jobs:
  - job: docker_patch
  displayName: Build and push Docker images
  strategy:
    matrix: $[ stageDependencies.Get_DF_Stage.Get_DF_Job.outputs['Get_DF_Task.dockerfile_list'] ]

  steps:
    - pwsh: Write-Output "$(dockerfile)"
      displayName: Show current Dockerfile

    - script: echo "##vso[task.setvariable variable=CURRENT_DATE]`date +"%Y%m%d"`"

    - task: Docker@2
      displayName: Build Docker image
      inputs:
        command: build
        containerRegistry: company-cr
        Dockerfile: dockerfiles/$(dockerfile)
        repository: devops/$(dockerfile)
        buildContext: .
        arguments: --no-cache --pull
        tags: |
          $(CURRENT_DATE)
          latest

    - task: Docker@2
      displayName: Push Docker image
      inputs:
        command: push
        containerRegistry: company-cr
        repository: devops/$(dockerfile)
        tags: |
          $(CURRENT_DATE)
          latest


text:
Q: Jupyterlabs Notebook and command line Python have different system path? Question:
What's the best way to set a Jupyterlab's notebook to have the same sys.path as Python when it's run from the Mac terminal?
Background:
I can use a python module (Beautiful Soup) successfully by starting Python from the Mac terminal (within a virtual environment named VENV). It installs, imports and works fine. But the Jupyterlabs notebook using the same VENV environment, won't import the very same module. I confirmed they are both using the same Python instance using the "Which Python" command, but terminal and notebook have a different sys.path, which appears to be restricting what the notebook can see.
What's the best way to handle this path inconsistency?

A: I found a workaround to make it work.
Thanks to Peter Bakke.
https://www.peterbakke.com/data-analysis/set-system-path-python-jupyter-notebooks/
I also installed BeautifulSoup4, rather than bs4.


text:
Q: Why http://www. goes to /index.php and https://www. does not? I'm running into a strange error causing poor SEO results.
Everything works expect when using http://www. it shows /index.php
but, https://www. or http:// or https:// does not show index.php
This is my rewrite conf

RewriteCond %{HTTP_HOST} ^www\.domain\.com$
RewriteRule ^/?$ "https\:\/\/domain\.com\" [R=301,L]

A: If you have search console you could check what is wrong with your domain.If you couldn`t find any problem my advice is to find good SEO agency. http://www.asknatewang.com/ There is a chance your ranking to be affected because of the discrepancy.
Greetings!