text:
Q: Using base64 images in pdfsharp html to pdf conversion I am trying to embed base64 images in HTML which will then be converted to PNG, normal images work fine but if I set the src to a base64 string is shows the broken image in my pdf:
https://gyazo.com/7c86e05373b165840225e931cf5975c9
Here is an example of an image string I would send, works fine in the html, broken after converting to pdf.
<img id="fmacttcChartPNG-PullUps" src="data:image/png;base64,iVBORw0KGgoAAAANSUhEUgAAAAkAAAAJAgMAAACd/+6DAAAAAXNSR0IArs4c6QAAAAlQTFRF7QA07QA0////wRtPhQAAAAF0Uk5TAEDm2GYAAAABYktHRAJmC3xkAAAACW9GRnMAAAORAAAJpwDTb3gUAAAACXBIWXMAAAsSAAALEgHS3X78AAAAB3RJTUUH4AoEBBQC2OsgcQAAABBJREFUCNdjYIAC1lDsGAgAIgICHfAWayEAAAAldEVYdGRhdGU6Y3JlYXRlADIwMTYtMTAtMDRUMDQ6MjA6MDIrMDI6MDAcnXh7AAAAJXRFWHRkYXRlOm1vZGlmeQAyMDE2LTEwLTA0VDA0OjIwOjAyKzAyOjAwbcDAxwAAACl0RVh0ZGM6Zm9ybWF0AGFwcGxpY2F0aW9uL3ZuZC5hZG9iZS5waG90b3Nob3DkrZ9UAAAAOHRFWHRpY2M6Y29weXJpZ2h0AENvcHlyaWdodCAoYykgMTk5OCBIZXdsZXR0LVBhY2thcmQgQ29tcGFueflXeTcAAAAhdEVYdGljYzpkZXNjcmlwdGlvbgBzUkdCIElFQzYxOTY2LTIuMVet2kcAAAAmdEVYdGljYzptYW51ZmFjdHVyZXIASUVDIGh0dHA6Ly93d3cuaWVjLmNoHH8ATAAAADd0RVh0aWNjOm1vZGVsAElFQyA2MTk2Ni0yLjEgRGVmYXVsdCBSR0IgY29sb3VyIHNwYWNlIC0gc1JHQkRTSKkAAAAYdEVYdGxhYmVsAFJlY3RhbmdsZSA4IGNvcHkgMsSFowcAAAAVdEVYdHBob3Rvc2hvcDpDb2xvck1vZGUAM1YCs0AAAAAmdEVYdHBob3Rvc2hvcDpJQ0NQcm9maWxlAHNSR0IgSUVDNjE5NjYtMi4xHC9sCwAAABN0RVh0dGlmZjpYUmVzb2x1dGlvbgA3Mg5QcYUAAAATdEVYdHRpZmY6WVJlc29sdXRpb24ANzKTX5DzAAAAKHRFWHR4bXA6Q3JlYXRlRGF0ZQAyMDE2LTA5LTIwVDIyOjEyOjEwKzA1OjAwdPNMtwAAADF0RVh0eG1wOkNyZWF0b3JUb29sAEFkb2JlIFBob3Rvc2hvcCBDQyAyMDE0IChXaW5kb3dzKTJLJSkAAAAqdEVYdHhtcDpNZXRhZGF0YURhdGUAMjAxNi0wOS0yOFQyMzo0OTo0OSswNTowMAbjefgAAAAodEVYdHhtcDpNb2RpZnlEYXRlADIwMTYtMDktMjhUMjM6NDk6NDkrMDU6MDA6RypGAAAAS3RFWHR4bXBNTTpEb2N1bWVudElEAGFkb2JlOmRvY2lkOnBob3Rvc2hvcDozNjQ2ZDY3ZC03ZjVkLTExZTYtYmMwYS1jMjA1ZmMxYjZiNmKXgewtAAAAPXRFWHR4bXBNTTpJbnN0YW5jZUlEAHhtcC5paWQ6ZWI5ZTBjYzQtOTVlMy05NjQ3LWI5Y2QtNDcyOGVjMzBhNTc0GfVhRwAAAEV0RVh0eG1wTU06T3JpZ2luYWxEb2N1bWVudElEAHhtcC5kaWQ6OGM1NTVkNDMtNDM2MC1hZTQ5LWJkMGMtZjkyY2E0MWY5MzUxLlI9uAAAAABJRU5ErkJggg==">

Does anyone know if this is supported or have any ideas on the correct direction to proceed on this?
Thanks,
Sam


text:
Q: Free two dimensional array Having the following piece of code:
 int (*fd)[2];
 int memory = n * sizeof(int);
 fd = malloc(memory);

How should I correctly free the allocated memory?

A: Use free(fd) to free the memory allocated by malloc to fd.
NOTE: free() only marks the memory chunk as free - there is no enforcement of this freeing operation.
For detailed explanation read: Heap Management With malloc() and free().

redpajama_set_name: RedPajamaStackExchange


text:
Q: Installing Semicode OS on VirtualBox Has anyone installed SemiCode OS on VirtualBox? Can you please share how you did it?

A: *

*Open Virtualbox and click "New"

*Enter Name (SemicodeOS or anything else you want)

*Choose Type - Linux and version - Ubuntu (32-bit)  -> Continue (The 64-bit -  version hasn't yet been released.)

*Allocate 512MB+ memory (preferably 1024MB+) -> Continue

*Check "Create a virtual hard disk now" -> Continue

*VDI (VirtualBox Disk Image) -> Continue

*Check "Dynamically allocated" -> Continue
Allocate Disk size -> Create.

*Now Choose SemicodeOS (or whatever name you picked) from the list of virtual  machines (Left pane) and Start.

*Click the browse icon (small folder icon to the right of the select menu) on the Popup window that appears when the VM runs.

*Browse to where you downloaded/stored the SemicodeOS-dist.iso file, Open and Start

*Enjoy!


text:
Q: Mockito set private property I have a small problem with Mockito. Let's say I have this code :
MyObject object = mock(MyObject.class);
System.out.println("PROPERTY 1 BRUT VALUE : " + property1Value);
object.setProperty1(property1Value);
System.out.println("PROPERTY 1 VALUE BEFORE STUB : " + object.getProperty1());
when(object.getProperty1()).thenReturn(property1Value);
System.out.println("PROPERTY 1 VALUE AFTER STUB : " + object.getProperty1());

PROPERTY 1 BRUT VALUE : 150.0
PROPERTY 1 VALUE BEFORE STUB : 0.0
PROPERTY 1 VALUE AFTER STUB : 150.0

The problem is that my object property is not set directly. I have a method in MyObject that uses it and it always return 0. It is not possible to set directly an object property if it is mocked ?
Found nothing on the documentation on this point.
Thanks.
EDIT 1 : Here is the method in MyObject that uses the property set by Mockito
public Double getProperty1X2() {
    return 2 * property1;
}

This method returns 0 in my tests, even if I set the property value. Maybe because it is using the field directly and not the getter ?

A: You can check my answer on this discussion:-
Is it possible to invoke mocked object's method?
The key point for you is:-
when(object.getProperty1()).thenCallRealMethod();


text:
Q: Can someone please explain me what exactly is Node in this below piece of code in java? class Node
 {
 Node l, r;
 int val;
 int h;

 public Node()
 {
     l = null;
     r = null;
     val = 0;
     h = 0;
 }

What are we doing in the line? :
Node l,r;
This only a part of a program that I did not include here.
Thanks.

A: We can't tell you exactly what it is, because how would we know.
But, we can make educated guesses, based on the badly named fields1:

*

*l should really be named left

*r should really be named right

*val should really be named value
That would make the class appear to be a binary search tree node.
Don't know what h is, but it could be a height value, representing the height of the sub-tree.
1 Badly named fields:

Variable names should be short yet meaningful. The choice of a variable name should be mnemonic- that is, designed to indicate to the casual observer the intent of its use. One-character variable names should be avoided, except for temporary "throwaway" variables.

A: Node is the name of the class that you're defining.
Node l, r; defines two variables of the Node type inside of each instance of Node but does not initialize them (each node has the possibility of containing two nodes, the left and right).


text:
Q: Selecting Distinct Values from sorted Table I have data query in my excel workbook to load data from a CSV-file. I want to use the Power Query-Editor to transform the data before working with them actually.
The simplified structure of the CSV-file are as shown in the html-table snippet below:

    Response-ID
    Task-ID
    Executed Action
    Status
    Date

    1
    A
    Some Task to be done
    Open
    20.01.2020

    2
    A
    Another Action done today
    Open
    25.01.2020

    3
    B
    New Task
    Open
    25.01.2020

    4
    A
    More actions in this matter
    Done
    26.01.2020

    5
    C
    Another Task
    Open
    27.02.2020

    6
    B
    Whatever
    Done
    29.02.2020

    7
    D
    Now what?
    Open
    02.03.2020

    8
    C
    Almost done...
    Open
    02.03.2020

What I want to achieve is a Power Query M code to display only the latest entry from each unfinished Task-ID.
Here is what I have so far:
let
    Source = ResponseData //a copy of my actual data query "ResponseData" to work with in this case
    #"Transformed Table" = Table.Distinct(Table.Buffer(Table.Sort(Source, {{"Date", Order.Descending}})), "Task-ID"),
    #"Remove Finished Tasks" = Table.SelectRows(#"Transformed Table", each ([Status] <> "Done" and [Status] <> "Canceled"))
in
    #"Remove Finished Tasks"

This code actually returns a list of all open tasks. But against my expectation it only contains the oldest response-ID of each task instead of the newest one. Changing the sort-order in the #"Transformed Table"-line returns the very same result in a reversed order. So basically sorting the table has no influence on the resulting data at all...
EDITED the code above according to the answer by Ron Rosenfeld -> Buffering the sorted table does the trick.

A: For reasons I don't fully understand (seems to have something to do with query folding), Power Query Remove Duplicates when run on a certain data sources, apparently does not respect the sorting order.  But if you use Table.Buffer, then it ensures that folding will not take place and that the Remove Duplicates will take place after the sorting/filtering.
Not sure which would be faster on large datasets, though -- Table.Buffer versus Table.Group
CSV File
Response-ID,Task-ID,Executed Action,Status,Date
1,A,Some Task to be done,Open,20.01.2020
2,A,Another Action done today,Open,25.01.2020
3,B,New Task,Open,25.01.2020
4,A,More actions in this matter,Done,26.01.2020
5,C,Another Task,Open,27.02.2020
6,B,Whatever,Done,29.02.2020
7,D,Now what?,Open,02.03.2020
8,C,Almost done...,Open,02.03.2020

First few lines of MCode is a bit different, but this should give you the gist:
let
    Source = Csv.Document(File.Contents("C:\Users\ron\Desktop\test.csv"),[Delimiter=",", Columns=5, Encoding=1252, QuoteStyle=QuoteStyle.None]),
    #"Promoted Headers" = Table.PromoteHeaders(Source, [PromoteAllScalars=true]),
    #"Changed Type" = Table.TransformColumnTypes(#"Promoted Headers",{{"Response-ID", Int64.Type}, {"Task-ID", type text}, {"Executed Action", type text}, {"Status", type text}, {"Date", type text}}),
    #"Changed Type with Locale" = Table.TransformColumnTypes(#"Changed Type", {{"Date", type date}}, "en-150"),
    #"Filtered Rows" = Table.SelectRows(#"Changed Type with Locale", each ([Status] = "Open")),
    #"Sorted Rows" = Table.Sort(#"Filtered Rows",{{"Date", Order.Descending}}),
    #"Buffered Table" = Table.Buffer(#"Sorted Rows"),
    #"Removed Duplicates" = Table.Distinct(#"Buffered Table", {"Task-ID"}),
    #"Sorted Rows1" = Table.Sort(#"Removed Duplicates",{{"Task-ID", Order.Ascending}})
in
    #"Sorted Rows1"

Results


text:
Q: Как открыть стороннее приложение из своего приложения? Мне нужно использовать стороннее приложение в своем проекте(просмотр 3d моделей). Можно ли как то допустим при нажатии на кнопку в своем приложении открывать нужное мне приложение? Может как то программно запускать его исполняющий файл?

A: самостоятельно Вы приложение пользователя не запустите, это должен сделать он сам,но реализовать диалог выбора приложений, которые могут обработать Ваш запрос вы можете при помощи неявного intent. Таким образом, сделать запрос на запуск стороннего приложения Вы сможете. Но важно, чтобы приложение,которое Вы хотите запустить явно уведомляло Андроид , посредством своего манифеста,о том, что его можно запускать из вне.

A: В итоге я сделал это так
public void reeee(View view) {
    String path = "/storage/emulated/0/Android/data/com.example.android.camera2basic.demo/files/default/AvatarModelDir/Anna.dae";
    File file = new File(path);

    //checking if the File exists
    if(file.exists()) {
        Intent intent = new Intent();
        intent.setAction(Intent.ACTION_VIEW);
        intent.setDataAndType(Uri.fromFile(file), "application/octet-stream");

        boolean result = isIntentAvailable(getApplicationContext(), intent);

        if (result){
            startActivity(intent);
        }
    }
}

public static boolean isIntentAvailable(Context context, Intent intent) {
    List<ResolveInfo> list = context.getPackageManager().queryIntentActivities(intent,
            PackageManager.MATCH_DEFAULT_ONLY);
    return !list.isEmpty();
}

Указывая путь к файлу который нужно открыть и правильный тип MIME (в моем случае это application/octet-stream) у меня все работает

A: Запустить чужой пакет из своего приложения просто
Intent intent = getContext().getPackageManager().getLaunchIntentForPackage("имя пакета");
startActivity(intent);


text: Q: How to add a Bootstrap4 template in Angular6 project? I tried to split bootstrap components to Angular way. But after ng build in port 4200 it's not showing anything but a white screen. There are lot of js, json,images, css ,scss. How do I add it all to the angular project?


text:
Q: What is best practice for C++ Public API? What is best practice for C++ Public API?
I am working on a C++ project that has multiple namespaces, each with multiple objects. Some objects have the same names, but are in different namespaces. Currently, each object has its own .cpp file and .h file. I am not sure how to word this... Would it be appropriate to create a second .h file to expose only the public API? Should their be a .h file per namespace or per object or some other scope? What might be a best practice for creating Public APIs for C++ libraries?
Thanks For Any Help,
Chenz

A: It is sometimes convenient to have a single class in every .cpp and .h pair of files and to have the namespace hierarchy as the directory hierarchy.
For instance if you have this class:
namespace stuff {
  namespace important {
    class SecretPassword
    {
       ...
    };
  }
}

then it will be in two files:
/stuff/important/SecretPassword.cpp
/stuff/important/SecretPassword.h

another possible layout might be:
/src/stuff/important/SecretPassword.cpp
/include/stuff/important/SecretPassword.h

A: G'day,
One suggestion is to take a look at the C++ idiom of Handle-Body, sometimes known as Cheshire Cat. Here's James Coplien's original paper containing the idiom.
This is a well known method for decoupling public API's from implementations.
HTH

A: I'd say it's best decided by you, and the type of 'library' this is.
Is your API provides one "Action"? or handles only one abstract "Data type"? examples for this would be zlib and libpng. Both have only one header that gives everything that is needed to perform what the libraries are for.
If your library is a collection of unrelated (or even related) classes that do, or not, the same goal, then provide each subset with it's own header. Major example for this will be boost.

A: Here is what I'm used to do:
"Some objects have the same names, but are in different namespaces"
That's why namespaces exist.
"Would it be appropriate to create a second .h file to expose only the public API? "
You always should expose only the public API. But what means to expose public API? If it would be only to headers then, since public API relies on private API, the private API would be included by public API anyway. To expose a public API mark public functions/classes with a macro (which in case of Windows exports public functions to the symbol table; and probably it will be soon adopted by Unix systems). So you should define a macro like MYLIB_API or MYLIB_DECLSPEC, just check some existing libraries and MS declspec documentation. It is sufficient, usually non-public API will be kept in subdirectories so it doesn't attend library's user.
"Should their be a .h file per namespace or per object or some other scope?"
I prefer Java-style, one public class per header. I found that libs written in this way are far more clean and readable than those which are mixing file and structure names. But there are cases when I brake this rule, especially when it comes to templates. In such cases I give #warning message to not include header directly and carefully explain in comments what is going on.

A: Great response LiraNuna.
Are you providing an API to an application or a library?
An application API will generally only provide methods that either query the state of an application or attempt to alter that state.  In this case you'd generally have separate interface declarations in a separate header file.  Your objects would then implement this interface to handle API requests.
A library will generally expose objects that can be re-used.  In this case, generally speaking, your API is simply the public methods in the header file.

A: I agree with what doc said - one class per file. 99.9% of the time!
Also, consider what filenames to use. It's generally a bad idea to have multiple headers of the same name in different directories, even though the classes they contain may well be in different namespaces.
Especially if this is a public API, you probably cannot control what include paths are defined by the user of your library, so a build may find the wrong one. Tweaking the order of include paths would definitely not be a solution I'd recommend!
We use a naming convention of Namespace-Class.h to explicitly identify classes in files.


text:
Q: Trigger for multiplying two columns from different tables with a functions in mysql I have been endelessly trying to get a trigger to work, with many different variations and all ending in errors.
I have finally just decided to ask for help, since im still a beginner at this.
So say I have a many-to-many table that contains pk's of o.orderId and p.productId, and within this table I have two columns called amount and totalPrice
I have then created a function, that returns the price of products based on their productiD.
CREATE FUNCTION func_getProductPrice($pId varchar(45)) RETURNS int(11)
    DETERMINISTIC
BEGIN
DECLARE origPrice int(11);
SET origPrice = (select o.productPrice from (productId_has_orderId
inner join productId on productId = $pId);
RETURN origPrice;
END

And a before insert trigger that is meant to call on this function to get the price, multiply the returned value based on new entry and then update the price field of this new entry.
delimiter |
CREATE TRIGGER `vet`.`calcProdutctPrice` before INSERT ON `productId_has_orderId`
FOR EACH ROW
IF NEW.amount <> 1 THEN
BEGIN
DECLARE newPrice int(11);
set newPrice = ((SELECT SUM((new.amount) * (select func_getProductprice(new.p.productId))) AS total from productId_has_orderId));
    begin
        update productId_has_orderId
        set price = newPrice
        where orderId = new.orderId;
        end;
    END;
end if
|
delimiter ;

Which gives this error when inserting data
Cant't update table 'productId_has_orderId' in stored function/trigger because it is already used by statement which invoked this stored function/trigger
An another variation of the trigger which essentially works the same, but the price is not a declared variable and is instead just updated to the new price
delimiter |
CREATE TRIGGER `vet`.`calcProdutctPrice` before INSERT ON `productId_has_orderId`
FOR EACH ROW
IF NEW.amount <> 1 THEN
BEGIN
        update productId_has_orderId
        set price = ((SELECT SUM((new.amount) * (select func_getProductprice(new.p.productId))) AS total from productId_has_orderId));
        where orderId = new.orderId;
    END;
end if
|
delimiter ;

Which then instead gives this error when inserting values
insert into productId_has_orderId (orderId, productId, amount) values (5100002, 3100002, 3)
Error Code: 1093. You can't specify target table 'productId_has_orderId' for update in FROM clause 0.000 sec
I am not sure what else I can do by now, I was thinking about creating a trigger calling a stored procedure, but I don't know if I can pass values from a trigger to a procedure.
Any help is appreciated, thank you

A: Assume we have (schematically):

*

*Products table
CREATE TABLE products (productID INT,
                       price DECIMAL);

*Orders table
CREATE TABLE orders (orderID INT,
                     total_price DECIMAL);

*Joining table
CREATE TABLE joining (productID INT,
                      orderID INT,
                      amount DECIMAL,
                      separate_price DECIMAL);

There is a lot of records in products table. We form new order and add new record into orders table. Now we begin to insert records into joining table, and we want to calculate both separate_price (for each separate product) and total (for whole order).

The trigger for to calculate separate price will be:
CREATE TRIGGER calculate_separate
BEFORE INSERT
ON joining
FOR EACH ROW
SET NEW.separate_price := (SELECT NEW.amount * products.price
                           FROM products
                           WHERE products.productID = NEW.productID);

The trigger for to calculate total price will be:
CREATE TRIGGER calculate_separate
AFTER INSERT
ON joining
FOR EACH ROW
UPDATE orders
    SET total_price = total_price + NEW.separate_price
    WHERE orderID = NEW.orderID;

If there is no separate_price field in joining table (and there is no trigger which calculates the value for that field) we will use
CREATE TRIGGER calculate_separate
AFTER INSERT
ON joining
FOR EACH ROW
UPDATE orders
    SET total_price = total_price + (SELECT NEW.amount * products.price
                                     FROM products
                                     WHERE products.productID = NEW.productID)
    WHERE orderID = NEW.orderID;

Pay attention: we calculate separate value (which is stored in the same table, in the record which creation fires a trigger) in BEFORE trigger (so the calculated value then will be inserted), whereas we re-calculate total value in AFTER trigger (and update a record in another table, and only in case when new record successfully inserted).
PS. Function mentioned in a question is not used - we do not need in it. We can use it, of course, but its usage is excess.
PPS. Each trigger above contains one single statement. So we do not need in BEGIN..END blocks ade DELIMITER reassign.


text:
Q: Combine two or more columns into one in a table I have an existing database with a table that I need to alter. Due to some recent changes requested, I need to take two columns out of a table and put the data from those two columns into an existing column in the table. Thankfully, they are all Varchar type so the data doesn't have to be transformed.
Here's what the table looks like now:

And here's what I want it to be:

I'm not exactly sure where to even start with this. So what's the best way to do this without breaking the table or losing any data?
NOTE: This is NOT for querying. I want to change the structure of the table itself to remove these two columns but take their data and dump it into an existing column.

A: This can be done by a simple update statement:
Update table
Set colC = colC + char(13) + char(10) + colD +char(13) + char(10) + colE

Note that char(13) + char(10) is a line break.
After you verify that the data was copied, use alter table to drop colD and colE.
The question is are you sure this move is wise?
This move seem to contredict a basic rule of relational databases design. If these columns stores different data entities I would strongly recommend against such a move.
Unless these values actually needs to be merged into a single value (on the logical level) then this is the wrong thing to do.


text:
Q: How to trigger a task on completion of two other tasks in Airflow DAG in python? I have a scenario like the one below. Task 3 should be triggered on successful completion of Task1 and Task2. I have shared my code below, can you let me know what is missing in it for the scenario?

My code
from airflow import DAG

from airflow.contrib.sensors.aws_glue_catalog_partition_sensor import AwsGlueCatalogPartitionSensor
from datetime import datetime, timedelta

from airflow.operators.postgres_operator import PostgresOperator
from utils import FAILURE_EMAILS

yesterday = datetime.combine(datetime.today() - timedelta(1), datetime.min.time())

default_args = {
    'owner': 'airflow',
    'depends_on_past': False,
    'start_date': yesterday,
    'email': FAILURE_EMAILS,
    'email_on_failure': False,
    'email_on_retry': False,
    'retries': 1,
    'retry_delay': timedelta(minutes=5)
}

dag = DAG('trigger_job', default_args=default_args, schedule_interval='@daily')

wait_for_task1 = AwsGlueCatalogPartitionSensor(
    task_id='Task1',
    database_name='db',
    table_name='table1',
    expression='load_date={{ ds_nodash }}',
    timeout=60,
    dag=dag)

wait_for_task2 = AwsGlueCatalogPartitionSensor(
    task_id='Task2',
    database_name='db',
    table_name='table2',
    expression='load_date={{ ds_nodash }}',
    timeout=60,
    dag=dag)

execute_sql = PostgresOperator(
    task_id='Task3',
    postgres_conn_id='REDSHIFT_CONN',
    sql="schema_do_lines.sql",
    params={'limit': '50'},
    dag=dag
)

execute_sql.set_upstream(wait_for_task1)

How can this be done in airflow using python?

A: You need two one simple thing:

*

*Set the dependencies right. For now you have coded that execute_sql depends on wait_for_task1. You have to specify that execute_sql also depends on wait_for_task2 by adding the line execute_sql.set_upstream(wait_for_task2) at the end of your code.

*BONUS: You may have to set the trigger_rule parameter in your task definition. You can read more about it in this documentation. In your specific case there is no need to set it explicitly because by default it is set on all_success (i.e. execute task only if all the parents have succeeded), and thus execute_sql will only trigger when both tasks it depends on have succeeded.


text:
Q: Apple Push APNS Sometimes not arriving I have an app which is already on the app store,
I also have a server that sends push notification to the iphone.
My problem is that sometimes, the notification does not arrive to the iphone,
and this only happened after there was no apns communication to the apple push server after 2 or 3 hours, but after timeout, it would start working again. it was really random.
At first i though the problem was a timeout, then i tried to print out the return value of my ssl_wrap.send() functions, and it did return the length of the strings that was supposed to be sent, meaning, Apple APNS received all my json strings. it is just not broadcasting them to the client phone.
I need to keep firing the apns server until it timeouts before making the push notification work again, this is not right.
Any ideas?
class PushSender:
def __init__(self):
    _sock = socket.socket( socket.AF_INET, socket.SOCK_STREAM )
    _sock.settimeout(2)
    self.ssl_sock = ssl.wrap_socket( _sock, certfile = theCertfile )
    self.ssl_sock.settimeout(1)
    self.ssl_sock.connect( theHost )
    self.counter = 0
    self.lastPush = time()

def reset(self):
    Log("Reset APNS");
    self.ssl_sock.close()
    _sock = socket.socket( socket.AF_INET, socket.SOCK_STREAM )
    _sock.settimeout(2)
    self.ssl_sock = ssl.wrap_socket( _sock, certfile = theCertfile )
    self.ssl_sock.settimeout(1)
    self.ssl_sock.connect( theHost )
    self.counter = self.counter + 1;
    self.lastPush = time()

def send(self,token, message, badge, sound):
    #Log("INIT APNS")
    payload = {}
    aps = {}
    aps["alert"] = str(message)
    aps["badge"] = badge
    aps["sound"] = str(sound)

    payload["aps"] = aps

    if time() - self.lastPush> 60*30 : # 30 minutes idle reconnect
        self.reset()
    try:
        #Log("Making Message APNS")
        tokenh = binascii.unhexlify(token)
        payloadstr = json.dumps(payload, separators=(',',':'))
        payloadLen = len(payloadstr)
        fmt = "!cH32sH%ds" % payloadLen
        command = '\x00'
        msg = struct.pack(fmt, command, 32, tokenh, payloadLen, payloadstr)
    except:
        Log("APNS Data Error " +token+" " +message);
        return;
    try:
        #Log(msg)
        sent = 0;
        while sent < len(msg):
            msg2 = msg[sent:];
            justSent = self.ssl_sock.write( msg2 )
            #Log(str(len(msg)) + " " + str(justSent))
            sent += justSent
            if justSent==0 :
                raise socket.error(0,"Send failed")
    except socket.error, err:
        Log( "APNS Error: "+str(self.counter)+" "+ str(err) )
        self.reset()
        if self.counter<=2 : self.send(token,message,badge,sound)
    Log( "APNS DONE"+ str(self.counter))
    self.counter = 0;
    self.lastPush = time()


text:
Q: iOS 7.1.2 RESideMenu crash on +[UIView appearanceWhenContainedInInstancesOfClasses:]: unrecognized selector sent to class I have added RESideMenu library in my iOS project from https://github.com/romaonthego/RESideMenu . It works fine on iOS 8,9 but crashing on iOS 7.1.2.
The issue is :
+[UIView appearanceWhenContainedInInstancesOfClasses:]: unrecognized selector sent to class 0x3c265a78
Sep 21 14:48:37 iPhone HafiziQuran[476] <Error>: *** Terminating app due to uncaught exception 'NSInvalidArgumentException', reason: '+[UIView appearanceWhenContainedInInstancesOfClasses:]: unrecognized selector sent to class 0x3c265a78'
    *** First throw call stack:
    (0x30e6af83 0x3b61bccf 0x30e6e823 0x30e6d203 0x30dbc768 0xa0eb1 0xa5e93 0x336f7587 0x336f6edb 0x336f156b 0x3368d6e9 0x3368c851 0x336f0ca9 0x35ca5aed 0x35ca56d7 0x30e35a67 0x30e35a03 0x30e341d7 0x30d9eebf 0x30d9eca3 0x336efed1 0x336eb14d 0x782a1 0x3bb28ab7)

My implementation on appdelegate is :
self.dmVC=[[DEMOFirstViewController alloc] init];
self.navigationController = [[UINavigationController alloc] initWithRootViewController:self.dmVC];//[[DEMOFirstViewController alloc] init]

self.leftMenuViewController = [[DEMOLeftMenuViewController alloc] init];
self.rightMenuViewController = [[DEMORightMenuViewController alloc] init];

self.sideMenuViewController = [[RESideMenu alloc] initWithContentViewController:self.navigationController
                                                                leftMenuViewController:self.leftMenuViewController
                                                               rightMenuViewController:self.rightMenuViewController];

self.sideMenuViewController.menuPreferredStatusBarStyle = 1; // UIStatusBarStyleLightContent
self.sideMenuViewController.delegate = self;
self.sideMenuViewController.contentViewShadowColor = [UIColor blackColor];
self.sideMenuViewController.contentViewShadowOffset = CGSizeMake(0, 0);
self.sideMenuViewController.contentViewShadowOpacity = 0.6;
self.sideMenuViewController.contentViewShadowRadius = 12;
self.sideMenuViewController.contentViewShadowEnabled = YES;
self.window.rootViewController = self.sideMenuViewController;
self.window.backgroundColor = [UIColor whiteColor];
[self.window makeKeyAndVisible];


text:
Q: Python match/case by dictionary key/values I would like to clean my code from excessive if/else and translate to match/case. However, I am unable to access the value by key. I get the error called match pattern must be a type.
My code:
match message.channel.id: #int type 123123
    case channels.get("EventID") | channels.get("AnnouncmentsID"): #list of values int types {"EventID" : 123213} | {"PetsID : 234234}
        #some code

    case channels.get("DeathID"): #value int type {"DeathID" :123123}
        if message.attachments:
           #some code
    ###Same cases
    case _:
        pass

I tried explicitly changing int/string types, use the dict[key] and dict.get('key') keys directly. Nothing comes out.

A: You're comparing int to list. Use | for matching multiple literals in match statement:
case channels.get("EventID") | channels.get("AnnouncmentsID") | channels.get("PetsID") | channels.get("Guild MomentsID"):

Described in documentation


text:
Q: How do I clear recent emoji in iOS 8.3? Before 8.3, I was able to clear recently used emoji by clicking on Settings->Reset->Reset Keyboard Dictionary.  Now, that does not work.
My recent emoji screen is littered with accidentally typed ones and such. It seems though that you can place your favorites on the first column by re-selecting them from their original lists (screens), but that does not seem to work well, and it is not as useful as being able to clear the entire list of recently used emojis.

A: So I figured out in iOS 8.3 when you reset your keyboard it doesn't clear your recently used emojis. But it replaces them with random emojis.
Then try typing an emoji. Now it should be first in your recently used. So just pretend the default emojis aren't there.


text:
Q: How to hide button on the Jquery UI dialog box I have been using JQuery UI dialog box.The following code I am using.Can any one please let me know how to hide the Export button after click
$( "#dialog-confirm1" ).dialog({
            resizable: false,
            height:350,
            width:650,
            modal: false,
            autoOpen:false,
            buttons: {
                "Export": function() {
                    exportCSV(2);

                },
                Cancel: function() {
                    $( this ).dialog( "close" );
                }
            }
        });

A: You could use $('.ui-button:contains(Export)').hide(): (the following code hides the export button when you click it)
$( "#dialog-confirm1" ).dialog({
            resizable: false,
            height:350,
            width:650,
            modal: false,
            autoOpen:false,
            buttons: {
                "Export": function() {
                    exportCSV(2);
                    $(event.target).hide();

                },
                Cancel: function() {
                    $( this ).dialog( "close" );
                }
            }
        });

A: The documentation for the buttons option says:

The context of the callback is the dialog element; if you need access
  to the button, it is available as the target of the event object.

Therefore, you can use event.target to refer to the button element:
buttons: {
    "Export": function(event) {
        $(event.target).hide();
        exportCSV(2);
    },
    "Cancel": function() {
        $(this).dialog("close");
    }
}

A: buttons: [{
    "Export": function() { exportCSV(2); },
    click: $( this ).hide()

}]


text:
Q: backbone.js newcomer - error creating collection in app namespace initialize method I'm following the the book, Backbone.js on Rails and am creating the basic todo application alongside reading it but I am getting the following javascript error trying to initialize a collection inside the applications namespace:
Error: TodoApp.Collections.Notes is not a constructor
Source File: localhost:3000/assets/todo_app.js?body=1
Line: 13
todo_app.js
var TodoApp = {
  Models: {},
  Collections: {},
  Views: {},
  Routers: {},
  initialize: function(data) {
    console.log("INITIALIZE");
    var notes = new TodoApp.Collections.Notes(data.notes);
    new TodoApp.Routers.Notes({ notes: notes });
    Backbone.history.start();
  }
};

I've followed the instructions so far and created a Note model, Notes collection and router and this is how the initialize method is called on index.html.erb:
<%= javascript_tag do %>
  TodoApp.initialize({ notes: <%== @notes.to_json %> });
<% end %>

This is the order I'm including all of the files:
//= require jquery
//= require jquery_ujs
//= require underscore
//= require json2
//= require backbone
//= require backbone-support
//
//= require todo_app
//
//= require_tree ./models
//= require_tree ./collections
//= require_tree ./views
//= require_tree ./routers
//= require_tree ../templates
//= require_tree .

Can anyone help with this? What have I missed out here?
Thanks

A: TodoApp.initialize({ notes: <%== @notes.to_json %> }); seems like a typo. It should be TodoApp.initialize({ notes: <%= @notes.to_json %> }); instead.

A: Javascript is evaluated in the order it is loaded, so I guess your app is trying to initialize before the files containing the collection is loaded (you're including todo_app before the other files).
Either include todo_app last or listen to the document onload event and initialize the app after the page has been fully loaded.

A: try using:
TodoApp.initialize({ notes: <%= @notes.to_json.html_safe -%> });

A: You could try to instantiate the new collection and then fill it up using the reset method.
In your example it should be something like this:
initialize: function(data){
  var notes = new TodoApp.Collections.Notes()
  notes.reset(data.notes)

}
The "reset" method accepts either a list of models or a hash. See the backbone documentation for more information.
Another good way to use this method is preloading the information on the webpage and then having our collection filling itself with the stored data. You can insert is on a div using a data tag like this:
<%= content_tag "div", "Can be blank", id: "container-id", data: { notes: Notes.all } %>

And then call:
notes.reset($('#container-id').data 'notes')

You can check Ryan Bates Screencasts on Backbone if you'll like to get more information. Beware that to watch those videos you have to subscribe to his site.
PS: If the location of yout todo_app.js is on your javascript asset folder you don't have to add it using the asset pipeline because it will be automatically picked up by rails by the //= require_tree . line.


text:
Q: git push heroku master error I'm encountering a problem deploying heroku. The online instructions suggest I follow these steps: https://devcenter.heroku.com/articles/django#deploy-to-heroku
However, when I get to "git push heroku master" I get the following error:
Counting objects: 12, done.
Delta compression using up to 8 threads.
Compressing objects: 100% (10/10), done.
Writing objects: 100% (12/12), 3.44 KiB, done.
Total 12 (delta 1), reused 0 (delta 0)
! Heroku push rejected, no Cedar-supported app detected

To git@heroku.com:mysterious-peak-4781.git
! [remote rejected] master -> master (pre-receive hook declined)
error: failed to push some refs to 'git@heroku.com:mysterious-peak-4781.git'

Can someone tell me whats wrong?

A: Rename the app as soon as you create it. It is a must in heroku i guess.
use this command
heroku apps:rename NAME

NAME = what ever name you want to put.
If the above  does not work,
type
cd .git
vi config

you will get something like this.
[remote "heroku"]
url = git@heroku.com:NAME.git

This is also a method. Change the name and try.


text:
Q: How to stop all threads in the tree? If I execute ExecutorService.shutdownNow() in Main thread  it does not stop all threads but If I execute ExecutorService.shutdownNow() in Thread1 or Thread2 it kills its sub child threads
How to cascade shutdown command to the lowest level?
       Main thread
        /      \
       /        \
Thread 1   Thread 2
|   |  |     |  |
A   B  C     D   E

How to kill all threads from main thread?
using below snippet to craete thread
CompletionService<Object> completionService = new ExecutorCompletionService<Object>(threadExecutor);
                        List<Future<Object>> futures = new ArrayList<Future<Object>>();
                        for(MultiThread mt : threadList)
                        {
                         futures.add(completionService.submit(mt));
                        }

                        while (futures.size() > 0) {
                            Future f = completionService.take();
                            futures.remove(f);
                            try {
                              Object result = f.get();
                              System.out.println(result);
                            } catch (Exception e) {
                              System.out.println("Caught exception from one task: " + e.getCause().getMessage() + ". shutdown now!");
                              threadExecutor.shutdownNow();
                              break;
                            }
                        }

How to handle interruption in child thread?

A: shutdownNow
List shutdownNow()
Based on Javadoc:
Attempts to stop all actively executing tasks, halts the processing of waiting tasks, and returns a list of the tasks that were awaiting execution.
This method does not wait for actively executing tasks to terminate. Use awaitTermination to do that.
There are no guarantees beyond best-effort attempts to stop processing actively executing tasks. For example, typical implementations will cancel via Thread.interrupt(), so any task that fails to respond to interrupts may never terminate.

A: You could use a ThreadPoolExecutor and pass an instance of a ThreadFactory.  The ThreadFactory will use a unique ThreadGroup that is associated with each new thread that is created.  If you need to interrupt all of the threads then you can just use the ThreadGroup interrupt method and all of the threads will be interrupted.
public class GroupThreadFactory implements ThreadFactory {
    private ThreadGroup group;

    public GroupThreadFactory(ThreadGroup group) {
         this.group = group;
    }

    public Thread newThread(Runnable r) {
         return new Thread(group, r);
    }
}


text:
Q: How do I get the compact/minified form of pretty-printed JSON in Java? How do I make Jackson's build() method pretty-print its JSON output? is an example that pretty-prints the JSON string.
I need to take the pretty-printed version of JSON string and then convert it to the compact/minified form. How can it be done?
I need to convert this:
{
  "one" : "AAA",
  "two" : [ "B B", "CCC" ],
  "three" : {
    "four" : "D D",
    "five" : [ "EEE", "FFF" ]
  }
}

to this:
{"one":"AAA","two":["B B","CCC"],"three":{"four":"D D","five":["EEE","FFF"]}}

I tried to remove '\n', '\t', and ' ' characters; but there may be some of these characters in values so I can't do that.
What else can be done?

A: With the streaming API, you can use JsonGenerator.copyCurrentEvent() to easily re-output the token stream with whatever pretty-printing applied you want, including the default of no whitespace; this avoids buffering the entire document in memory and building a tree for the document.
// source and out can be streams, readers/writers, etc.
String source = "   { \"hello\" : \" world \"  }  ";
StringWriter out = new StringWriter();

JsonFactory factory = new JsonFactory();
JsonParser parser = factory.createParser(source);
try (JsonGenerator gen = factory.createGenerator(out)) {
    while (parser.nextToken() != null) {
        gen.copyCurrentEvent(parser);
    }
}

System.out.println(out.getBuffer().toString()); // {"hello":" world "}

You can use the same approach to pretty-print a JSON document in a streaming fashion:
// reindent
gen.setPrettyPrinter(new DefaultPrettyPrinter());

A: Jackosn-core is one way of pretty printing json. You can read the answer here https://stackoverflow.com/a/12174201/432903
You can also use org.json library, which is a very simple but standard json lib for java. Open source code here -> stleary/JSON-java.
maven dependency
<dependency>
    <groupId>org.json</groupId>
    <artifactId>json</artifactId>
    <version>20160810</version>
</dependency>

usage
        String payload = "{\n" +
            "  \"fact1\": \"Java is verbose.\", \n" +
            "  \"fact2\" : \"C has pointers\"\n" +
            "}";
        System.out.println(new JSONObject(payload));

You'll get compact json {"fact2":"C has pointers","fact1":"Java is verbose."} in one line.

A: The safe way is to read the data using the JsonNode API and just write it out again without enabling the pretty printer.
ObjectMapper m = new ObjectMapper();
JsonNode rootNode = m.readTree(payload);
String compressed = rootNode.toString();

If the object is huge, the Streaming API can help.
Using a regexp does also work if you use this pattern: \s*\n\s*
This doesn't create the most compact form (i.e. you will still have some spaces between elements) but it's a cheap solution if you already have the JSON as a String. The reason why this pattern is safe is that new lines are invalid in String values (they must be escaped using \n) so you can safely remove whitespace around them.

A: Jackson allows you to read from a JSON string, so read the pretty-printed string back into Jackson and then output it again with pretty-print disabled.
See converting a String to JSON
Simple Example
    String prettyJsonString = "{ \"Hello\" : \"world\"}";
    ObjectMapper objectMapper = new ObjectMapper();
    JsonNode jsonNode = objectMapper.readValue(prettyJsonString, JsonNode.class);
    System.out.println(jsonNode.toString());

Requires
<dependency>
    <groupId>com.fasterxml.jackson.core</groupId>
    <artifactId>jackson-core</artifactId>
    <version>2.5.3</version>
</dependency>
<dependency>
    <groupId>com.fasterxml.jackson.core</groupId>
    <artifactId>jackson-databind</artifactId>
    <version>2.5.3</version>
</dependency>


text:
Q: Como posso calcular os elementos em Javascript Preciso pegar o valor id="valorPorcentagem" que é o valor da porcentagem com o (id="valor_vendedor") e somar automaticamente no id="comissao".
Sendo que:
valorPorcentagem / 100 x valor_vendedor = comissao
20 / 100 x 800,00 = 160,00
45 / 100 x 700,00 = 315,00

O valor total da comissão = R$ 475,00

html

Comissão do Vendedor:
<input type="text" name="total" id="comissao" readonly>

<select id="valorPorcentagem">
  <option value="20">20</option>
    <option value="45">45</option>
</select>

<input id="valor_vendedor" onkeyup="calcular()">

javascript
function calcular() {
    var soma = $('.calcular').get().reduce(function(soma, el) {
        return (parseFloat(el.value.replace(/\./g, "").replace(",", "."), 10) || 0) + soma;
    }, 0);

    soma = soma.toFixed(2);

    document.getElementById('comissao').value = soma;
    mascara(document.getElementById('comissao'), mreais);
}

O botão (Adicionar Plano) em HTML
<input type="text" name="usuarios[0][comissao_vendedor]" id="valor_vendedor" class="calcular form-control" placeholder="R$" onkeypress="mascara(this,mreais)" onkeyup="calcular()">

$ js
var AddTableRow = function(el) {
        var tbody = $(el).closest('table').find('tbody');
        var row = tbody.find('tr:last').clone();
        var name = row.find('.calcular').attr('name');
        var index = parseInt(name.match(/informacao\[(\d+)\]\[porcentagem\]/)[1], 10) + 1;
        row.find('[name^="informacao["]').each(function() {
            if (this.name) {
                this.name = this.name.replace(/^informacao\[\d+\]/, "informacao[" + index + "]");
            }
        });
        tbody.append(row);
    };

Segue o código

A: Mudei algumas coisas no código que você disponibilizou. Não entendi o uso do reduce e de uma função de máscara que não existe. Mas para efetuar esse cálculo, você pode simplesmente obter os valores usando val() e realizar a operação:

function calcular() {
  var comissao = (parseFloat($("#valorPorcentagem").val())/100) * parseFloat($("#valor_vendedor").val());
  $("#comissao").val(comissao);
}

<select id="valorPorcentagem">
  <option value="20">20</option>
  <option value="45">45</option>
</select>

<input id="valor_vendedor" onkeyup="calcular()">
Comissão do Vendedor:

<input type="text" name="total" id="comissao" readonly>

A: Sei que não foi o enfoque principal da pergunta, mas vi que ira trabalhar com mais de um campo input, portanto vai uma versão de como você poderia trabalhar:
Cabem adaptações.

function calcular() {
  contador = 1;
  elementos = [];
  // Procuro todos elementos que possuem o pseudo-metodo "fazparte" e que estao visiveis no formulario
  jQuery('input[fazparte]:visible').each(function() {
    // Teoricamente os campos adicionados dinamicamente devem possuir id
    // diferenciado, por um contador talvez? enfim, uso esse contador para
    // adicionar em um array que irei usar futuramente para fazer o calculo
    if (jQuery(this)[0].value != "") {
      elementos.push(contador);
    }
    contador++;
  });
  var valorFinal = 0;
  for (var i in elementos) {
    // Para cada input que possui valor, faco uma somatória das porcentagens
    //dos elementos que possuem um valor setado, e jogo no valor final da comissão
    valorFinal += ((document.getElementById("porcentagem"+elementos[i]).value)/100)*(document.getElementById("valor"+elementos[i]).value)
  }
  document.getElementById("comissao").value = valorFinal;
}

Comissão do Vendedor:
<input type="text" name="total" id="comissao" readonly>

<select id="porcentagem1" onchange="calcular()">
  <option value="20">20</option>
  <option value="40">40</option>
</select>

<input id="valor1" onblur="calcular()" fazparte>

<select id="porcentagem2" onchange="calcular()">
  <option value="10">10</option>
  <option value="45">45</option>
</select>

<input id="valor2" onblur="calcular()" fazparte>

Para adicionar elementos dinamicamente:

function calcular() {
  contador = 1;
  elementos = [];
  jQuery('input[fazparte]:visible').each(function() {
    if (jQuery(this)[0].value != "") {
      elementos.push(contador);
    }
    contador++;
  });
  var valorFinal = 0;
  for (var i in elementos) {
    valorFinal += ((document.getElementById("porcentagem" + elementos[i]).value) / 100) * (document.getElementById("valor" + elementos[i]).value)
  }
  document.getElementById("comissao").value = valorFinal;
}

function adicionarElemento() {
  var contador = 0;
  jQuery('input[fazparte]:visible').each(function() {
    contador++;
  });
  // Aqui a logica de adicionar um proximo elemento para
  // funcionar na logica acima so sera necessario criar o proximo id corretamente,
  // desse modo mesmo que o input
  // existir, se ele nao for setado, nao vai alterar em nada o valor da comissao
  var elemento = '
<select id="porcentagem' + (contador + 1) + '" onchange="calcular()"><option value="10">10</option><option value="45">45</option></select><input id="valor' + (contador + 1) + '" onblur="calcular()" fazparte>';
  $("#valor" + (contador)).after(elemento);
}

Comissão do Vendedor:
<input type="text" name="total" id="comissao" readonly>
<button onclick="adicionarElemento()">Adicionar plano</button>

<select id="porcentagem1" onchange="calcular()">
  <option value="20">20</option>
  <option value="40">40</option>
</select>

<input id="valor1" onblur="calcular()" fazparte>

<select id="porcentagem2" onchange="calcular()">
  <option value="10">10</option>
  <option value="45">45</option>
</select>

<input id="valor2" onblur="calcular()" fazparte>

A: Se vale mudar o HTML, podes sempre fazer um selector que selecione todos os elementos quando um desses é mudado, calcular a percentagem do mesmo, reduzir a lista à soma dos mesmos e apresentar o resultado num input:

$.fn.reduce = [].reduce;

$('body').on('change', 'calc-comissao input' ,function(event, something) {
var total = $('calc-comissao input')
  .map(function(index, ele) {
   return (ele.parentNode.querySelector('select').value / 100) * ele.value;
  })
  .reduce(function(last, value) { return parseFloat(last) + parseFloat(value)});
  $('comissao input').val(total.toFixed(2));
});

Comissão do Vendedor:
<comissao><input type=text/></comissao>

<calc-comissao>
  <select>
<option value="20">20</option>
<option value="40">40</option>
  </select>
  <input type="number" value=0/>
</calc-comissao>

<calc-comissao>
  <select>
<option value="10">10</option>
<option value="70">70</option>
  </select>
  <input type="number" value=0/>
</calc-comissao>


text:
Q: What is wrong with my xpath? Why is a different element receiving the click? Steps to recreate:

*

*Go to http://practice.automationtesting.in/

*Click on add to basket

*Then view basket

*Change the quantity to 2

*Click on Update Basket

*Click on remove item'X'

*Or use coupon code "krishnasakinala"

*Click on Apply Coupon button

The error I am getting is:
selenium.common.exceptions.ElementClickInterceptedException: Message: element click intercepted: Element ... is not clickable at point (216, 220). Other element would receive the click:

I have tried different locators but getting the same error.
Read more: https://softwaretestingboard.com/q2a/4041/exceptions-elementclickinterceptedexception-intercepted#ixzz6iUxRC97y
My code:
url = "http://practice.automationtesting.in"
driver.get(url)
wait_timeout = 5
wait_variable = W(driver, wait_timeout)

driver.find_element_by_xpath("//a[@data-product_id='160']").click()
wait_variable.until(E.presence_of_element_located((By.XPATH, "//a[@class ='added_to_cart wc-forward']"))).click()

wait_variable.until(E.presence_of_element_located((By.XPATH, "//input[@type='number']"))).clear()
wait_variable.until(E.presence_of_element_located((By.XPATH, "//input[@type='number']"))).send_keys(2)

wait_variable.until(E.element_to_be_clickable((By.NAME, "update_cart"))).click()
wait_variable.until(E.presence_of_element_located((By.XPATH, "//a[@title='Remove this item']"))).click()

A: There are multiple ways to solve this problem like making the driver wait, using a different element identifier (CSS/class/etc.) but the most effective one is to use the method execute_script()
element = driver.find_element_by_xpath('the xpath of the element')
driver.execute_script("arguments[0].click();", element)

A: wait_variable.until(E.element_to_be_clickable(
    (By.NAME, "update_cart"))).click()

wait_variable.until(E.presence_of_element_located(
    (By.CSS_SELECTOR,'[class="blockUI blockOverlay"]')))

wait_variable.until(E.staleness_of(
    driver.find_element_by_css_selector('[class="blockUI blockOverlay"]')))

wait_variable.until(E.presence_of_element_located(
    (By.XPATH, "//a[@title='Remove this item']"))).click()

The error is due to the overlay loader use this code , using javascript to click an element is not a right way it will bypass the UI rendering and direcly trigger click event on the element.
This should be avoided if you are using selenium for testing
How to find locator for overlay loader:
what is overlay loader :

This spinner is a UI element used to block user interaction with UI while ajax components are being loaded in the background.
What are the challenges:?
The spinner load so fast that it is hard to locate the element from dev tool
How to find the locator?
open element tab , right click the html and seelct break on sub tree modification

now click play button:
click update cart and click the blue play button till the loader is present in the UI.

This will freeze UI with the spiner in screen , now you can easily find the locator


text:
Q: css: exclude (hide) specific area from element With CSS3 clip-path option I can easily clip element so that only specified area will be visible. It's cool, but is there a way to exclude an area so that everything except specified path will be visible?
Here is an example of what I want to do. I need to cut a circle out:

Placing a circle over is not an option because I need the underlying background to be visible.
AFAIK one way to do it is by using canvas, but is it possible with pure CSS?
Thanks!

A: Sure it's possible.  Use clip-path!  Imagine your div is piece of paper and clip-path is a pair of scissors.  If you wanted to cut out a circle in the middle, you'd cut around the edges, along a line into the middle, around a circle, and back to the edge along the same line.
I hacked together a python script that outputs the CSS.  Apologies for the style...
import math

# radius in percent of width
radius = 0.25
# xy pos in percent
xPos = 0.5
yPos = 0.5
# number of points around the circle
# size of css is approx proportional to this
smooth = 50

# from here, just go around the outline of the shape

x = []
y = []

x.append(0)
y.append(0)

x.append(0)
y.append(1)

x.append(xPos - radius)
y.append(1)

x.append(xPos - radius)
y.append(yPos)

angleZero = math.pi
increment = 2 * math.pi / smooth

numDigits = 3

for k in range(0, smooth):
 angle = angleZero - k * increment
 x.append( round( xPos + radius * math.cos(angle), numDigits ) )
 y.append( round( yPos - radius * math.sin(angle), numDigits ) )

x.append(xPos - radius)
y.append(yPos)

x.append(xPos - radius)
y.append(1)

x.append(1)
y.append(1)

x.append(1)
y.append(0)

cssValue = "polygon(";
for k in range(0, len(x) - 1):
  cssValue += str( abs(x[k]*100) ) + "% " + str( abs(y[k]*100) ) + "%, "
cssValue += str( abs(x[len(x) - 1]*100) ) + "% " + str(abs( y[len(x) - 1]*100) ) + "%);"

property = "clip-path: "
spaces = "    "
print(".excludeCircle{");
print(spaces + "-webkit-"+property + cssValue)
print(spaces + property + cssValue)
print("}")

Here's what it looks like:

.excludeCircle{
    -webkit-clip-path: polygon(0% 0%, 0% 100%, 25.0% 100%, 25.0% 50.0%, 25.0% 50.0%, 25.2% 46.9%, 25.8% 43.8%, 26.8% 40.8%, 28.1% 38.0%, 29.8% 35.3%, 31.8% 32.9%, 34.1% 30.7%, 36.6% 28.9%, 39.4% 27.4%, 42.3% 26.2%, 45.3% 25.4%, 48.4% 25.0%, 51.6% 25.0%, 54.7% 25.4%, 57.7% 26.2%, 60.6% 27.4%, 63.4% 28.9%, 65.9% 30.7%, 68.2% 32.9%, 70.2% 35.3%, 71.9% 38.0%, 73.2% 40.8%, 74.2% 43.8%, 74.8% 46.9%, 75.0% 50.0%, 74.8% 53.1%, 74.2% 56.2%, 73.2% 59.2%, 71.9% 62.0%, 70.2% 64.7%, 68.2% 67.1%, 65.9% 69.3%, 63.4% 71.1%, 60.6% 72.6%, 57.7% 73.8%, 54.7% 74.6%, 51.6% 75.0%, 48.4% 75.0%, 45.3% 74.6%, 42.3% 73.8%, 39.4% 72.6%, 36.6% 71.1%, 34.1% 69.3%, 31.8% 67.1%, 29.8% 64.7%, 28.1% 62.0%, 26.8% 59.2%, 25.8% 56.2%, 25.2% 53.1%, 25.0% 50.0%, 25.0% 100%, 100% 100%, 100% 0%);
    clip-path: polygon(0% 0%, 0% 100%, 25.0% 100%, 25.0% 50.0%, 25.0% 50.0%, 25.2% 46.9%, 25.8% 43.8%, 26.8% 40.8%, 28.1% 38.0%, 29.8% 35.3%, 31.8% 32.9%, 34.1% 30.7%, 36.6% 28.9%, 39.4% 27.4%, 42.3% 26.2%, 45.3% 25.4%, 48.4% 25.0%, 51.6% 25.0%, 54.7% 25.4%, 57.7% 26.2%, 60.6% 27.4%, 63.4% 28.9%, 65.9% 30.7%, 68.2% 32.9%, 70.2% 35.3%, 71.9% 38.0%, 73.2% 40.8%, 74.2% 43.8%, 74.8% 46.9%, 75.0% 50.0%, 74.8% 53.1%, 74.2% 56.2%, 73.2% 59.2%, 71.9% 62.0%, 70.2% 64.7%, 68.2% 67.1%, 65.9% 69.3%, 63.4% 71.1%, 60.6% 72.6%, 57.7% 73.8%, 54.7% 74.6%, 51.6% 75.0%, 48.4% 75.0%, 45.3% 74.6%, 42.3% 73.8%, 39.4% 72.6%, 36.6% 71.1%, 34.1% 69.3%, 31.8% 67.1%, 29.8% 64.7%, 28.1% 62.0%, 26.8% 59.2%, 25.8% 56.2%, 25.2% 53.1%, 25.0% 50.0%, 25.0% 100%, 100% 100%, 100% 0%);
}

img{
  width: 300px;
  height: 200px;
}

body{
  background-color: green;
}

  This is text in the background. This is text in the background. This is text in the background. This is text in the background. This is text in the background. This is text in the background. This is text in the background. This is text in the background. This is text in the background. This is text in the background. This is text in the background. This is text in the background. This is text in the background. This is text in the background. This is text in the background. This is text in the background. This is text in the background. This is text in the background. This is text in the background. This is text in the background. This is text in the background. This is text in the background. This is text in the background. This is text in the background. This is text in the background. This is text in the background. This is text in the background. This is text in the background. This is text in the background. This is text in the background. This is text in the background. This is text in the background. This is text in the background. This is text in the background. This is text in the background.

Edit: One issue with this method is that it really makes an oval.  You could fix this by using px in the circle (if you know the min-size of the element) or by having an x radius and a y radius (if you know the relative sizes).  If you know nothing, you'll need some js...

A: It's a bit of a fiddle, but this might help if the background is an image.  Place a circle over, and treat the background as a sprite.  Comment out the content div to see the full background image:

#container {
  width: 400px;
  height: 200px;
  background: url('http://lorempixel.com/400/200');
  text-align:center;
}
#content {
  width: 80%;
  height: 100%;
  background: silver;
  text-align: center;
  display:inline-block;
}
#circle {
  width: 100px;
  height: 100px;
  border-radius: 50%;
  background: url('http://lorempixel.com/400/200') 150px 50px;
  background-position: center;
  position: fixed;
  top: 58px;
  left: 158px;
}

      Lorem ipsum amet sint dolor etc.

This is your main content area


text:
Q: Display queryset count sitewide? What is the best way to display a query set count site wide? instead of calling users in every view.
Example:
views.py
def index(request):
    users = Profile.objects.all().count()
    return render(request, 'layout.html', {'users': users})

layout.html

Total Users: ({{users}})

A: This looks like you need a custom context_processor. Then you have users in the context for every request/view.

A: You want a custom template tag. The documentation is clear enough so that there's no need for an example here.


text:
Q: Getting "`let` is not available from within an example" in Rails 4 and Rspec I have been working to use the proper Rspec syntax for setting variables for example let(:order_created) { load_json_fixture('order_created') } which calls this support method inside rspec/support:
Support Method
module LoadJsonFixtureHelper
  def load_json_fixture(name)
    data = nil
    Dir["#{Rails.root}/{test,spec}"].each do |dir|
      Dir["#{dir}/fixtures/**/*.json"].map do |filename|
        data = JSON.parse(File.read(filename)) if File.basename(filename,File.extname(filename)) == name
      end
    end
    data
  end
end

However, wherever I try to call this I get the following error message:
Error
test - (#<RSpec::ExampleGroups::Provider::FromAFactory:0x007fe8d2213c58>):0 > let(:order_created) { load_json_fixture('order_created') }
RSpec::Core::ExampleGroup::WrongScopeError: `let` is not available from within an example (e.g. an `it` block) or from constructs that run in the scope of an example (e.g. `before`, `let`, etc). It is only available on an example group (e.g. a `describe` or `context` block).
from /Users/chrishough/.rbenv/versions/2.3.1/lib/ruby/gems/2.3.0/gems/rspec-core-3.4.4/lib/rspec/core/example_group.rb:683:in `method_missing'
test - (#<RSpec::ExampleGroups::Provider::FromAFactory:0x007fe8d2213c58>):0 >

Partial Spec Example
RSpec.describe Provider, type: :model do
  describe 'from a factory' do

    before(:all) do
      binding.pry
    end

    it 'can be built' do

      binding.pry

      expect((build :provider)).to be_valid.and be_instance_of(Provider)
    end

    it 'can be created' do
      expect((create :provider)).to be_valid.and be_persisted
    end
  end

I can get around this by using instance variables but I am trying to follow Rspec correctly. How can I fix this?

A: Try it this way:
describe 'from a factory' do
  let(:order_created) { load_json_fixture('order_created') }

  it 'can parse json' do
    # try typing 'order_created` now when pry trigger
    binding.pry

  end
end


text:
Q: crossrider extension installed on all browsers but working only in chrome I have successfully installed the my crossrider extension on Chrome, Firefox and IE (all up to date) but the browser button (although enabled on all) only works for Chrome.
Background code seems to work, since I can trigger alerts.
My background.js looks like this:
appAPI.ready(function() {
var popupDims = {
    CH: {height: 400, width: 400},
    FF: {height: 400, width: 400},
    IE: {height: 400, width: 400},
    SF: {height: 400, width: 400}
};

if ("CHFFIESF".indexOf(appAPI.platform) !== -1) {
    appAPI.browserAction.setPopup({
        resourcePath:'popup.html',
        height:popupDims[appAPI.platform].height,
        width:popupDims[appAPI.platform].width
    });
}
else {
    alert('This extension is not supported on your browser');
}});

In my popup.html I have some javascript:
function crossriderMain($) {
// load libraries
eval(appAPI.resources.get('select2.js'));

$('[as-trigger]').click(function () {
    // retrieves the information for the active tab
    appAPI.tabs.getActive(function(tabInfo) {
        activeUrl = tabInfo.tabUrl;

        appAPI.request.get({
            url: 'http://...',
            onSuccess: function(response, additionalInfo) {
                // show message
            },
            onFailure: function(httpCode) {
                console.log('GET:: Request failed. HTTP Code: ' + httpCode);
            }
        });

    });

})

$('[as-project-dropdown]').select2().on('select2-selecting', function (e) {
    // some jquery code
});

appAPI.request.get({
    url: 'http://...',
    onSuccess: function(response, additionalInfo) {
        var dataObject = JSON.parse(response);

        $.each(dataObject.data, function(key, value) {
            $('[as-project-list]').append('some html...');
        });

        $('[as-companyname]').html(dataObject.company);
    },
    onFailure: function(httpCode) {
        console.log('GET:: Request failed. HTTP Code: ' + httpCode);
    }
});}

And in my firefox console I can see an error thrown by my extension:
MyExtension <Warning: document.getElementById(...) is null Function-name: appAPI.request.get User callback>

@Crossrider support: my app id is 65982

A: Looking at your code I can see that you did not set the browser action's icon. Per the Browser Action docs, on some browsers this is essential for the button to properly initialize. I created an extension with your code and added the icon using appAPI.browserAction.setResourceIcon and the button worked fine.
So taking the snippet from your background.js, add the icon as follows:
appAPI.ready(function() {
var popupDims = {
    CH: {height: 400, width: 400},
    FF: {height: 400, width: 400},
    IE: {height: 400, width: 400},
    SF: {height: 400, width: 400}
};

if ("CHFFIESF".indexOf(appAPI.platform) !== -1) {
    appAPI.browserAction.setResourceIcon('logo.jpg');
    appAPI.browserAction.setPopup({
        resourcePath:'popup.html',
        height:popupDims[appAPI.platform].height,
        width:popupDims[appAPI.platform].width
    });
}
else {
    alert('This extension is not supported on your browser');
}});

[Disclosure: I am a Crossrider empployee]


text:
Q: How to get text at specific value in XML using XSLT I have an XML file with the following content:
<option>
      <test attr="a">text1</test>
      <test attr="b">text2</test>
      <test attr="c">text3</test>
</option>

How can I now extract text2 using xslt?
Everything I try gives me text1.
For example:
<xsl:if test="option/test/@attr='a'">
<xsl:value-of select="option/test"/>
</xsl:if>

A: This XPath should get you the text2 value:
option/test[@attr='b']

It effectively says "select the test element that has an attr attribute with a value of 'b'".
So you could use it like this:
<xsl:value-of select="option/test[@attr='b']"/>

without the need for the xsl:if.

A: You need to use a predicate to specify "the test whose attr has the value 'a'".
 option/test[@attr='a']

You also need to be aware of the difference between relative and absolute xpaths, and know what context you're invoking the path from -- you are using relative paths which will work only if your current node is the option's parent.


text:
Q: Одновременное изменение разных переменных одним методом путём асинхронности class Program
    {
        static int x, y, z;

        static int Factorial(int num)
        {
            Console.WriteLine("Start of method");
            int result = 1;

            for(int i = 1; i <= num; ++i)
            {
                result *= i;
            }

            Thread.Sleep(4000);
            Console.WriteLine("End of method");
            num = result;
            return result;
        }

        static async void FactorialAsync(int num_1, int num_2, int num_3)
        {
            Task _x = Task.Run(() => Factorial(num_1));
            Task _y = Task.Run(() => Factorial(num_2));
            Task _z = Task.Run(() => Factorial(num_3));

            Task[] tasks = new Task[3] { _x, _y, _z };
            await Task.WhenAll(tasks);
        }

        static void Main(string[] args)
        {
            Console.WriteLine("Start Main");

            x = 4; y = 2; z = 3;

            FactorialAsync(x, y, z);

            Console.WriteLine($"x: {x}, y: {y}, z: {z}");
            Console.WriteLine("End Main");
            Console.ReadKey();
            Console.WriteLine($"x: {x}, y: {y}, z: {z}");
        }
    }

Ф-ция Factorial(int) имитирует сложную задачу, которая занимает некоторое время и в итоге она изменяет входящий параметр на результат и возвращает сам же результат.
В методе FactorialAsync(int, int, int) реализуется включение нескольких потоков одновременно, которые выполняют метод  Factorial(int).
Цель программы вообще - изменить 3 переменных одновременно одним и тем же методом путём асинхронизации. Но в итоге этого не происходит. В методе Factorial(int) изменял модификации параметров кл.словом ref, но результатов не дало.
P.S. Вот только начал знакомиться с асинхронизацией, суть вроде как понял. Просто вот пришла такая идея для практики, но всё как всегда идёт не по плану). И вообще возможно ли такая реализация или вообще бред?)
ЗЫ ах да, вывод проги такой, если что:

A: Ваш метод Factorial возвращает результат. Этот результат нужно использовать.
Изменим метод FactorialAsync следующим образом:
static async Task<int[]> FactorialAsync(int num_1, int num_2, int num_3)
{
    Task<int> _x = Task.Run(() => Factorial(num_1));
    Task<int> _y = Task.Run(() => Factorial(num_2));
    Task<int> _z = Task.Run(() => Factorial(num_3));

    Task[] tasks = new Task[3] { _x, _y, _z };
    await Task.WhenAll(tasks);

    return new int[] { _x.Result, _y.Result, _z.Result };
}

Задачи теперь имеют тип Task<int>, то есть у них есть результат. Возвращаем их результаты в виде массива. Можно создать отдельную структуру или использовать кортеж (tuple).
И, соответственно, используем значения, возвращаемые методом FactorialAsync:
private static async Task Main(string[] args)
{
    x = 4; y = 2; z = 3;
    Console.WriteLine($"x: {x}, y: {y}, z: {z}");

    var result = await FactorialAsync(x, y, z);

    Console.WriteLine($"x: {result[0]}, y: {result[1]}, z: {result[2]}");
}

Метод Factorial оставлен без изменений.

Использовать ref/out при работе с асинхронными методами невозможно.

Я бы переписал метод так:
static async Task<int[]> FactorialAsync(params int[] input)
{
    var tasks = input
        .Select(n => Task.Run(() => Factorial(n)))
        .ToArray();

    await Task.WhenAll(tasks);

    return tasks
        .Select(t => t.Result)
        .ToArray();
}

Чтобы убедиться в одновременности выполнения нескольких задач, можно добавить вывод текущего Id таски.
static int Factorial(int num)
{
    Console.WriteLine("Start of method");
    int result = 1;

    for (int i = 1; i <= num; ++i)
    {
        result *= i;
        Console.WriteLine("Task Id: " + Task.CurrentId);
        Thread.Sleep(400);
    }

    Console.WriteLine("End of method");
    return result;
}

Вообще, запуск и выполнение задач/потоков зависит от множества факторов: наличие свободный потоков в пуле, количество ядер в процессоре, Debug/Release и многое другое. Если идентификаторы задач будут выводиться не вразнобой, как должно быть, то можно попробовать увеличить значения факториалов, скажем, на порядок.

A: Получилось решить таким способом:
 class Program
    {
        static int _x, _y, _z;

        static int Foo(int x)
        {
            Console.WriteLine("Start Foo");
            int result = 1;
            for(int i = 1; i <= x; ++i)
            {
                result *= i;
            }

            Thread.Sleep(2000);
            Console.WriteLine("End Foo");
            return result;
        }

        static async Task<int> FooAsyncHandle(int x)
        {
            return await Task<int>.Run(() => Foo(x));
        }

        static async void SmthAsync(int x, int y, int z)
        {
            Task<int> task_1 = FooAsyncHandle(x);
            Task<int> task_2 = FooAsyncHandle(y);
            Task<int> task_3 = FooAsyncHandle(z);

            await Task.WhenAll(task_1, task_2, task_3);

            _x = task_1.Result;
            _y = task_2.Result;
            _z = task_3.Result;
        }

        static void Main(string[] args)
        {
            _x = 0; _y = 0; _z = 0;
            Console.WriteLine("Start Main");
            Console.WriteLine($"x: {_x}, y: {_y}, z: {_z}");

            SmthAsync(5, 2, 3);

            Console.WriteLine("EndMain");
            Console.ReadKey();
            Console.WriteLine($"x: {_x}, y: {_y}, z: {  _z}");
        }
    }

В методе Main() запускается асинхронный поток SmthAsync(int, int, int), который в свою очередь инициализирует 3 разные задачи, которые выполняют один и тот же асинхронный метод, который запускает Foo.
        static async void SmthAsync(int x, int y, int z)
        {
            Task<int> task_1 = FooAsyncHandle(x);
            Task<int> task_2 = FooAsyncHandle(y);
            Task<int> task_3 = FooAsyncHandle(z);

            await Task.WhenAll(task_1, task_2, task_3);

            _x = task_1.Result;
            _y = task_2.Result;
            _z = task_3.Result;
        }

После выполнения этих "сложных" задач в асинхронном режиме (await Task.WhenAll(task_1, task_2, task_3)), объекты task_1, task_2, task_3 просто возвращают значения для моих переменных _x,_y,_z. Таким образом, не нужно указывать ф-цию Main как асинхронную, следовательно, основной поток не останавливается, а изменение 3ех переменных происходит как бы в "фоновом" режиме, как я и задумал)


text:
Q: puppet: "applying configuration version ", what does it refer to? When I run
sudo puppet agent -t

after a long phase of catalog loading, I get a message:
info: Applying configuration version '1403590182'
What is that number 1403590182 referring to?
In fact I have noticed that if I run twice in a row sudo puppet agent -t, I get different configuration version numbers even if the modules have not changed!
How can I determine which version of each module is being applied to the node?

A: from the documentation config_version

How to determine the configuration version. By default, it will be the
time that the configuration is parsed, but you can provide a shell
script to override how the version is determined. The output of this
script will be added to every log message in the reports, allowing you
to correlate changes on your hosts to the source version on the
server.
Setting a global value for config_version in puppet.conf is not
allowed (but it can be overridden from the commandline). Please set a
per-environment value in environment.conf instead. For more info, see
https://puppet.com/docs/puppet/latest/environments_about.html

The time is represented as a unix time stamp as such yours indicates "06/24/2014 @ 6:09am" (and i just realised how old this Q was)

A: If the manifests are git controlled the administrator can let the Puppet master know how to describe the version with the statement below in /etc/puppet/puppet.conf (on the Puppet master). One such statement goes in each environment section with the path adjusted to where the environment looks for manifests.
  config_version = git --git-dir $confdir/modules/production/.git describe --all --long

If you use some other version control system i'm sure there's some equivalent command to get an indication of the revision.


text:
Q: Adding custom fields to RadScheduler Appointments I have a RadScheduler. It is now displaying  all appointments in the database. I need to display only current loggedin  customer's appointment details. I got a field in my database for the customerId. How i will add it to the Appointments in RadScheduler.
Many Thanks

A: Imo the RadScheduler itself is architectural not the right place to filter your appointments. Rather filter your bound DataSource for the correct appointments. Easy one with Linq, could be something like datasource.all(appointment => appointment.customerId == context.loginId)


text:
Q: Calculate nearest point in space, python3 I have two datasets with different sets of coordinates. I am trying to find the indices's of the points that are the shortest distance apart. To do this I have attempted to write two functions:
 def distance(a, b):
     """
     Calculates the distance between two GPS points (decimal)
     @param a: 2-tuple of point A
     @param b: 2-tuple of point B
     @return: distance in m
     """
     from numpy import sin, cos, sqrt, arctan2, radians, add, subtract, multiply
     r = 6371000             # average earth radius in m
     dLat = radians(subtract(a[0],b[0]))
     dLon = radians(subtract(a[1],b[1]))

     x1 = add(sin(dLat/2) ** 2, cos(radians(a[0])))
     x2 = multiply(cos(radians(b[0])),sin(dLon/2))

     x = multiply(x1,x2) **2

    y = 2 * arctan2(sqrt(x), sqrt(1-x))
    d = r * y
    return d

and
 def findNearest(ilon,ilat,lon,lat):
     """
     i,j = findNearest(ilon,ilat,lon,lat):
     find indices of closest point within lat and lon data
     Input:
     ilon, ilat (input longitude and latitude to match)
     lon, lat = longitude and latitude in which to look
     lon and lat must have same dimension
     return:
     i,j =  row and colum index of match in lon, lat
     lon = ravel(lon)
     """
     from numpy import where, ravel, shape, meshgrid, array

     d=[]
     if len(shape(lon))==1:
        lon,lat = meshgrid(lon,lat)
     a = ravel(lon)
     b = ravel(lat)
     for x, y in zip(a,b):
        d.append(distance([ilon,ilat],[x,y]))
     i, = where(d==min(array(d)))
     i=i[-1]
     j,i = where((a[i]==lon) & (b[i]==lat))
     return int(i),int(j)

Please can you help me make these more efficient and help identify any bugs.
The two datasets I'm currently working with are 2874 x 1 and 4346 x 1.
Here is some example data:
 dataset 1:
 longitude,      latitude
-29.12777024,   31.97120842
-29.12931210,   31.97415242
-29.1305217,    31.97645816
-29.13207462,   31.97936922
-29.13390954,   31.98294568
-29.1358673,    31.98642314
-29.1379327,    31.99051119
-29.1402072,    31.99354618
-29.14214358,   31.99680022
-29.14373422,   31.9999497
-29.1456006,    32.00320652
-29.1477001,    32.00602422
-29.14998566,   32.0084005
-29.1536702,    32.01045613

Dataset 2:
Lon_1,   Lat_1
25.0,   -34.0
25.1,   -34.0
25.2,   -34.0
25.3,   -34.0
25.4,   -34.0
25.5,   -34.0
25.6,   -34.0
25.7,   -34.0
25.8,   -34.0
25.9,   -34.0
26.0,   -34.0
26.1,   -34.0

Many Thanks

A: There is no need to ravel your lon and lat arrays: broadcasting and universal functions saves your life here:
dist = distance(ilon, ilat, lon, lat)

generates a 2D-array containing the distance between (ilon,ilat) and all items in (lon, lat). Then
index = np.argmin(dist)

gets the index of the min distance in the (raveled) matrix of distances, and finally
minlon, minlat = lon.ravel()[index], lat.ravel()[index]

provides the final answer


text:
Q: How to filter results simultaneously using Solr and Google Places API? I want to filter content using Apache Solr and then filter results using the Google places API or vice versa. Actually I want to use this API from Google places.
So I want to filter both, Locations (using the Google Places API) with some features (using Apache Solr). Is that possible?If so how? thanks!

A: This is a wide open question so I'm not sure what languages, platform, etc. you are requiring. Also, have you started this yet? If so please post your code so that we can add on to it.
If no code, the only way I can think of answering this question is conceptually:
To call Solr and Google Places- you simply need to use an HTTP URL Request.
For Google Places this can be:
https://maps.googleapis.com/maps/api/place/nearbysearch/output?Key&lat&long&radius

Where Key, Lat, Long, and Radius are just some of the parameters you can/should use.
For Solr this can be:
http://localhost:8983/solr/select?q=*:*&wt=json

Where *:* means ask Solr for everything in json format. Clearly you would want to add parameters to this as well to call specific features, but the point is to answer question you can query both of these using HTTP URL Requests and then add the necessary arguments to the end of each URL.
Depending on the language you choose, the code calling these URL's will look different, but the effect will be the same.
It may also be a good idea to keep wt=json as a Solr parameter because the Google Places will also return its result in json format- so it may be easier and faster to work with json in both results.
I hope this helps. Please feel free to post comments or follow up questions if it helps.


text:
Q: Misinterpreting a Phrase
Let $R$ be the collection of sequences $(a_1,a_2,...)$ of integers $a_1$, $a_2$,..., where all but finitely many of the $a_i$ are $0$. Prove that $R$ is a ring under componentwise addition and multiplication which does not have an identity.

I construed this phrase as, "$a_i \neq 0$ for finitely many $i \in \mathbb{N}$. If this is the case, how does $R$ form a ring? It doesn't seem to be closed under multiplication, for consider $(1,0,0,...)$ and $(0,1,0,...)$. Clearly their product does not contain any nonzero integers; i.e., the condition $a_i \neq 0$ for finitely many $i$" is not satisfied.
So, what is the correct interpretation of the phrase?

A: Zero is a finite cardinal, so $(0,0,\ldots) \in R$.
That is, all but a finite number of $a_i$ in that collection are $0$; that finite number happens, in fact, to be zero.


text:
Q: Root object Alfresco "session.getTicket()" "sessionticket.getTicket()" I'm trying to use session.getTicket() to obtain the authentication ticket of alfresco. But I get

"session is not defined"

I try too sessionticket.getTicket() and gives me the same error.
Any help?

A: Since you are working on share, you are most probably authenticated.
If it is the case, you can access your alfresco repo through the proxy endpoint in share and all requests will have authentication ticket attached to them before getting forwarded to your repo !
In other terms, use this endpoint :
/share/proxy/alfresco/api/upload

Instead of :
/alfresco/service/api/upload

and You won't even have to attach a ticket to your requests !


text:
Q: "Re-parenting" GIT feature branch based on another I am hoping someone knows the git-fu required to untangle a branch mess.
I have a feature branch - FB2 - whose parent is FB1, which in turn originated from master.
Bad news: I need to retarget FB2 on top of master as it needs to ship before FB1, without any of the commits from FB1.
Good news: There are few code changes in FB2 that directly interact with changesets from FB1. However, there are dozens and dozens of commits from pull requests over many tickets (~75) from both FB1 and FB2.
I'm looking for the least painful way to find and incorporate only the commits which were committed directly to FB2. Alternatively, a way to alter the existing FB2 branch to retarget master and remove all the commits that originated from FB1.
brute force cherry picking or rebasing will take forever and be error prone.
"git rebase --onto master FB1" didn't seem to work in a test. The changes from FB1 were still present in FB2.
Thanks!
Similar to the diagram here:
# CURRENT
A--B--C--D // master
          \
           E--F--G // FB1
                  \
                   H--I--J // FB2
# DESIRED

          H--I--J // FB2
         /       \
A--B--C--D        M // merged
          \
           E--F--G // FB1

A: Have you had any re-merges between FB1 and FB2 ? Or you just branched of fb1 and fb2 then had its own history? if so :
you may try creating the patch between commits G and J:
git diff #G..#J > mypatch.patch

then create a new branch where you actually want to start from and apply the patch:
git apply mypatch.patch

However, if files do not exist on the new target branch, the patch fill not apply cleanly.
for that you may first want to do :
 git diff --name-status #G..#J

to identify what actual files changed.


text:
Q: List of string to use in labels c# First. I create a group of 5 labels using a for
for (byte fila = 0; fila < 5; fila++)
        {
            Label letras = new Label();

            letras.Height = alto;
            letras.Width = ancho;
            letras.BackColor = Color.Blue;
            letras.ForeColor = Color.AntiqueWhite;
            letras.Font = new Font("Arial", 60);
            letras.TextAlign = ContentAlignment.MiddleCenter;
            letras.BorderStyle = BorderStyle.FixedSingle;
            letras.Left = 200 + (ancho + 20) * fila;
            letras.Top = 60;
            letras.Text = null;
            letras.Visible = false;
            letras.MouseMove += new
            System.Windows.Forms.MouseEventHandler(this.letras_MouseMove);

            this.Controls.Add(letras)

Second. I have a list of words declared as list of strings of 5 characters.
List <string> palabras = new List <string> { "limón", "bufón", "leche", "video",
"guiso",
            "dulce", "gusto", "audaz", "vacío", "huevo", "avena", "guapo", "ozono",
"audio",
            "zanja", "pausa", "freno", "débil", "hurto", "otoño", "libro", "pluma",
"disco",
            "fruta", "melón", "papel", "mapeo", "nuevo", "banco", "tigre", "mundo",
"hueco",
            "cable", "funda", "lápiz", "botón", "tonto", "regla", "tipas", "canal" };

I need to call one of them (words) and put each of the characters in a label of the group of labels I created first, in an altered order (5, 3, 1, 2, 4). I ´ve tried with substrings function but I always have errors. ¿Any suggestions?

A: string is basically an array of char, so you can access specific chars by their index, e.g.
string text = "Hello world!";

// this will write 'H'

Console.WriteLine(text[0]);


text:
Q: Ruby - Calling all methods without arguments for a class object Is it possible to call all parameterless methods for a given class object by using reflection in Ruby?

A: def call_paramater_less_methods(instance)
   instance.class.instance_methods(false).each do |m|
     instance.public_send(m) if instance.method(m).arity.zero?
   end
end

class C
  def a()  puts "a says hi"   end
  def b()  puts "b says ho"   end
  def c(s) puts "c says #{s}" end
end

call_paramater_less_methods(C.new)
  # b says ho
  # a says hi

Optionally,
instance.public_send(m) if instance.method(m).arity.zero?

can be replaced with
instance.method(m).call if instance.method(m).arity.zero?


text:
Q: Find the order of zeros The given function is $f(z)=\frac{\sin z}{z}$, so to find the order of zeros first we have to find the zeros, in this case $f(z)=0$ iff $z=(2n+1)\pi, n\in\Bbb Z$. Those are a lot of zeros and I'm not sure what to do next, I figure maybe pick one, say $z=\pi$, so
$$f'(z)=\frac{z\cos(z)-\sin(z)}{z^2}=\frac{\pi\cos\pi-\sin\pi}{\pi^2}\not=0$$
That way we get that $\pi$ is a zero of order $1$, that means all of the othet zeros are too of order $1$? how do I find the order of zeros?

A: If $f(z) = g(z)/h(z)$ where $g$ and $h$ are analytic and $g$ has a zero of order $k$ at $z=p$ while $h(z) \ne 0$, then $f$ has a zero of order $k$ there as well.


text:
Q: Need a sample step function to orchestrate multiple API gateway calls I need a step function example for orchestrate few flows in my functions.
Sync all credit/debit using API call --> Update account balance API call -->send notification in case of debit with updated balance

A: What you're looking for is a step function that can invoke a Lambda function. This Lambda function would call your API Gateway endpoint.
There is a tutorial here that should help to demonstarte how to build a workflow using Lambda functions.
You can also find many sample projects here.


text:
Q: How to change QTableView text color using QItemDelegate? I have created subclassed QItemDelegate and redefined the paint method.  I have tried
painter.setPen(QtGui.QColor('#FFFFFF'))

which doesnt work. How do I change the text color?
As a side note I tried to color the background by calling painter.setBackground(color) which also doesnt work. How are these methods intended to be used?
class ItemDelegate(QtWidgets.QItemDelegate):
    def __init__(self, parent):
        QtWidgets.QItemDelegate.__init__(self, parent)
        self.parent = parent

    def paint(self, painter, option, index):
        item = index.data(QtCore.Qt.DisplayRole)
        #print(item)
        print(dir(painter))
        if index.column() == 1:
            color = QtGui.QColor('#34ebc6')
        elif index.column() == 2:
            color = QtGui.QColor('#FFFFFF')
        elif index.column() == 3:
            color = QtGui.QColor('#9546c7')
        else:
            color = QtGui.QColor('#FFFFFF')
        painter.fillRect(option.rect, color)
        super(ItemDelegate, self).paint(painter, option, index)

A: You have to override the drawDisplay method where you have to change the values of the QPalette::Text and QPalette::HighlightedText roles of the palette:
class ItemDelegate(QtWidgets.QItemDelegate):
    def paint(self, painter, option, index):
        color = QtGui.QColor("#FFFFFF")
        if index.column() == 1:
            color = QtGui.QColor("#34ebc6")
        elif index.column() == 2:
            color = QtGui.QColor("#FFFFFF")
        elif index.column() == 3:
            color = QtGui.QColor("#9546c7")
        painter._color = color

        super(ItemDelegate, self).paint(painter, option, index)

    def drawDisplay(self, painter, option, rect, text):
        color = painter._color
        opt = QtWidgets.QStyleOptionViewItem(option)
        cg = (
            QtGui.QPalette.Normal
            if opt.state & QtWidgets.QStyle.State_Enabled
            else QtGui.QPalette.Disabled
        )
        if opt.state & QtWidgets.QStyle.State_Selected:
            opt.palette.setColor(cg, QtGui.QPalette.HighlightedText, color)
        opt.palette.setColor(cg, QtGui.QPalette.Text, color)
        super(ItemDelegate, self).drawDisplay(painter, opt, rect, text)

With QStyledItemDelegate it is easier since you only need to override the initStyleOption method:
class ItemDelegate(QtWidgets.QStyledItemDelegate):
    def initStyleOption(self, option, index):
        super(ItemDelegate, self).initStyleOption(option, index)

        color = QtGui.QColor("#FFFFFF")

        if index.column() == 1:
            color = QtGui.QColor("#34ebc6")
        elif index.column() == 2:
            color = QtGui.QColor("#FFFFFF")
        elif index.column() == 3:
            color = QtGui.QColor("#9546c7")

        cg = (
            QtGui.QPalette.Normal
            if option.state & QtWidgets.QStyle.State_Enabled
            else QtGui.QPalette.Disabled
        )
        if option.state & QtWidgets.QStyle.State_Selected:
            option.palette.setColor(cg, QtGui.QPalette.HighlightedText, color)

        option.palette.setBrush(QtGui.QPalette.Text, color)


text:
Q: JSONArray.length() returns wrong length in Android Studio I am parsing a JSON string that has an array of 5 JSON objects. Though, when I call the JSONArray .length() method, it returns 6 instead of 5. Any clue why this is so? Thanks.
Here is the JSON string:
String jsonStr =
   "["
                + "{"
                + " \"deptNbr\": 1, "
                + " \"catgNbr\": 120,"
                + " \"catgDesc\": \"COLD CEREAL\","
                + " \"modSect\": 13,"
                + " \"locationId\": \"0001\","
                + " \"upc\": \"2200001654\","
                + " \"primeItemNbr\": 553279324,"
                + " \"itemNbr\": \"1\","
                + " \"itemDesc\": \"LIFE CINN\","
                + " \"price\": 1.98,"
                + " \"horizontalFacings\": 1,"
                + " \"verticalFacings\": 1,"
                + " \"capacity\": 35,"
                + " \"shelf\": 2,"
                + " \"productHeight\": 10.43,"
                + " \"productWidth\": 7.5,"
                + " \"productDepth\": 2.5,"
                + " \"xCoord\": 0"
                + " },"
                + " {"
                + " \"deptNbr\": 1,"
                + " \"catgNbr\": 120,"
                + " \"catgDesc\": \"COLD CEREAL\","
                + "\"modSect\": 13,"
                + "\"locationId\": \"0002\","
                + "\"upc\": \"4000032968\","
                + "\"primeItemNbr\": 130958,"
                + "\"itemNbr\": \"130958\","
                + "\"itemDesc\": \"HONEY NUT CHERRIOS\","
                + "\"price\": 1.98,"
                + "\"horizontalFacings\": 2,"
                + "\"verticalFacings\": 1,"
                + "\"capacity\": 20,"
                + "\"shelf\": 2,"
                + "\"productHeight\": 11.25,"
                + "\"productWidth\": 7.67,"
                + "\"productDepth\": 2,"
                + "\"xCoord\": 8.5"
                + "},"
                + "{"
                + "\"deptNbr\": 1,"
                + "\"catgNbr\": 120,"
                + "\"catgDesc\": \"COLD CEREAL\","
                + "\"modSect\": 13,"
                + "\"locationId\": \"0007\","
                + "\"upc\": \"79051314000\","
                + "\"primeItemNbr\": 137063,"
                + "\"itemNbr\": \"4\","
                + "\"itemDesc\": \"CINN TOAST CRUNCH\","
                + "\"price\": 3.32,"
                + "\"horizontalFacings\": 1,"
                + "\"verticalFacings\": 1,"
                + "\"capacity\": 24,"
                + "\"shelf\": 1,"
                + "\"productHeight\": 10.25,"
                + "\"productWidth\": 7.67,"
                + "\"productDepth\": 2,"
                + "\"xCoord\": 0"
                + " },"
                + " {"
                + "\"deptNbr\": 1,"
                + "\"catgNbr\": 120,"
                + "\"catgDesc\": \"COLD CEREAL\","
                + "\"modSect\": 13,"
                + "\"locationId\": \"0008\","
                + "\"upc\": \"2800078552\","
                + "\"primeItemNbr\": 138779,"
                + "\"itemNbr\": \"5\","
                + "\"itemDesc\": \"STAR WARS\","
                + "\"price\": 4.28,"
                + "\"horizontalFacings\": 1,"
                + "\"verticalFacings\": 1,"
                + "\"capacity\": 21,"
                + "\"shelf\": 1,"
                + "\"productHeight\": 10.5,"
                + "\"productWidth\": 7.67,"
                + "\"productDepth\": 2,"
                + "\"xCoord\": 8.5"
                + "},"
                + "{"
                + "\"deptNbr\": 1,"
                + "\"catgNbr\": 120,"
                + "\"catgDesc\": \"COLD CEREAL\","
                + "\"modSect\": 13,"
                + "\"locationId\": \"0009\","
                + "\"upc\": \"7339000459\","
                + "\"primeItemNbr\": 194231,"
                + "\"itemNbr\": \"6\",  "
                + "\"itemDesc\": \"LUCKY CHARMS\", "
                + "\"price\": 2.28, "
                + "\"horizontalFacings\": 1, "
                + "\"verticalFacings\": 1, "
                + "\"capacity\": 24, "
                + "\"shelf\": 1, "
                + "\"productHeight\": 11.25, "
                + "\"productWidth\": 7.67, "
                + "\"productDepth\": 2, "
                + "\"xCoord\": 17 "
                + " }," +
 "]";

Here is where I create the JSONArray object and call the length() method:
try{
   JSONArray cerealArray = new JSONArray(jsonStr);
   Log.d(LOGTAG,"cerealArray.length(): " + cerealArray.length());
}catch(JSONException e){
   Log.e("JSONException: ", "failed to read jsonString");
}

In my logcat:
D/ImageTargetRenderer: planogramArray.length(): 6

A: That's because of the last ',' in your JSON
                + " }," +

remove that and it should be ok