text:
Q: SMTP connect() failed PHPMailer Using MailGun I was trying to connect my MailGun SMTP details with PHP Mailer and it doesn't work at all it throws error like below
2020-10-16 09:58:34 SERVER -> CLIENT: 220-server2.dnsboost.com ESMTP Exim 4.93 #2 Fri, 16 Oct 2020 15:28:34 +0530 220-We do not authorize the use of this system to transport unsolicited, 220 and/or bulk e-mail.
2020-10-16 09:58:34 CLIENT -> SERVER: EHLO website.com
2020-10-16 09:58:34 SERVER -> CLIENT: 250-server2.dnsboost.com Hello website.com [192.154.231.187]250-SIZE 52428800250-8BITMIME250-PIPELINING250-AUTH PLAIN LOGIN250-STARTTLS250 HELP
2020-10-16 09:58:34 CLIENT -> SERVER: STARTTLS
2020-10-16 09:58:34 SERVER -> CLIENT: 220 TLS go ahead
SMTP Error: Could not connect to SMTP host.
2020-10-16 09:58:34 CLIENT -> SERVER: QUIT
2020-10-16 09:58:34
2020-10-16 09:58:34
SMTP connect() failed. https://github.com/PHPMailer/PHPMailer/wiki/Troubleshooting
failed

I've tried all the suggested methods to fix this but none worked!
I tested the credentials with SMTP tester sites and they work just perfectly fine and send test message to my inbox but it doesn't work when I try to use it with PHPMailer...

A: This exact error is described in the troubleshooting guide that's linked from the error message!

In an SMTP transcript this will typically be shown as trying to send a STARTTLS command immediately followed by a QUIT command.

It's nothing to do with credentials, everything to do with the TLS configuration on your server. Try setting $mail->SMTPDebug = 3;, and you'll then need to check your CA certificate bundle, as described in the guide.


text:
Q: Nearly all internet traffic blocked aside from http/https So today I noticed several network-based programs not functioning, such as Valve's Steam platform.  After disabling the windows firewall, and even booting in safe mode with networking, I am unable to get a response from www.google.com using the "ping" or "tracert" commands.  Connecting through the browser works fine however.  I have also tried on another laptop and have the same results.
This is using a wired internet connection in a multi-unit dwelling, so there must be one or more routers involved, but I cannot bypass them.  It appears to be a blockage at the router/ISP, but cannot believe someone would be so bold as to shut off ALL internet traffic aside from port 80/443.  Is there anything else I can do to test the network?
The ISP is comcast.  Should also mention that Skype is working fine.
Tracing route to www.google.com [74.125.239.49]
over a maximum of 30 hops:

1     1 ms     1 ms     1 ms  TEW-731BR [192.168.10.1]
2     1 ms     1 ms     1 ms  10.0.0.1
3     *        *        *     Request timed out.
4     *        *        *     Request timed out.
5     *        *        *     Request timed out.
6     *        *        *     Request timed out.

redpajama_set_name: RedPajamaStackExchange


text:
Q: Kafka 0.10.2 consumers getting massive number of duplicates I have a fairly simple Kafka setup - 1 producer, 1 topic, 10 partitions, 10 KafkaConsumers all with the same group ID, all running on a single machine. When I process a file, the producer quickly creates 3269 messages, which the consumers happily start consuming. Everything runs fine for a while, but at a certain point the consumers start consuming duplicates - LOTS  of duplicates. In fact, it looks like they just start consuming the message queue over again. If I let it run for a long time, the database will start receiving the same data entries 6 or more times. After doing some tests with logging, it looks like the consumers are re-consuming the same messages with the same unique message names.
As far as I can tell, no re-balancing is happening. Consumers are not dying or being added. It's the same 10 consumers, consuming the same 3269 messages over and over until I kill the process. If I just let it go, the consumers will write dozens of thousands of records, massively increasing the amount of data that really should be going into the database.
I'm fairly new to Kafka, but I'm kind of at a loss for why this is happening. I know Kafka doesn't guarantee exactly-once processing, and I'm ok with a couple duplicates here and there. I have code to prevent persisting the same records again. However, I'm not sure why the consumers would re-consume the queue over and over. I know that Kafka messages aren't deleted after they are consumed, but if all the consumers are in the same group, the offsets should prevent this, right? I understand a little bit about how offsets work, but as far as I know, they shouldn't be getting reset if there is no re-balancing, right? And the messages aren't timing out as far as I can tell. Is there a way for me to get my consumers to consume everything in the queue once-ish and then wait for more messages without re-consuming the same stuff forever?
Here are the proprties I pass in to the producer and consumers:
Properties props = new Properties();
        props.put("bootstrap.servers", "localhost:9092");
        props.put("acks", "all");
        props.put("retries", 0);
        props.put("batch.size", 16384);
        props.put("linger.ms", 1);
        props.put("buffer.memory", 33554432);
        props.put("group.id", "MyGroup");
        props.put("num.partitions", 10);
        props.put("key.serializer", "org.apache.kafka.common.serialization.StringSerializer");
        props.put("value.serializer", "org.apache.kafka.common.serialization.StringSerializer");
        props.put("key.deserializer", "org.apache.kafka.common.serialization.StringDeserializer");
        props.put("value.deserializer", "org.apache.kafka.common.serialization.StringDeserializer");

        MyIngester ingester = new MyIngester(args[0], props);

A: To me this seems to be an issue with acknowledging the receipt.
Try the following properties
    props.put("enable.auto.commit", "true");
    props.put("auto.commit.interval.ms", "100");


text:
Q: Select second minimum value in a table I have a table like the following, and originally I wanted to return the earliest update date for different statuses.
However, since the project was cancelled and recreated, I want to ignore the first planning date and only return the second planning date.

+------------+------------+------------+-----------+
| Project ID |  UpdateDT  |  Audit ID  | SubStatus |
+------------+------------+------------+-----------+
|   11111    | 2017-12-20 |   10123    | Planning  |
|   11111    | 2017-05-25 |   10135    | Planning  |
|   11111    | 2017-10-11 |   10254    | Cancelled |
+------------+------------+------------+-----------+

My query is like the following, but it can only return the earliest planning date rather the second earliest one. I added a CASE expression but the result is still the same. Can anyone please shed some lights? Thank you.
SELECT DISTINCT sub.Request_ID
    ,sub.UpdateDT
    ,a.reqStatus
FROM [RptChange].[dbo].[tRequestsAudit] a
JOIN (
    SELECT [reqID] [Request_ID]
        ,CASE
            WHEN [reqStatus] IN ('Cancelled')
                THEN MAX([reqUpdateDt])
            ELSE MIN([reqUpdateDt])
            END AS [UpdateDT]
        ,MIN([AuditID]) AS EarliestAuditID
        ,[reqStatus] SubStatus
    FROM [RptChange].[dbo].[tRequestsAudit]
    WHERE [reqID] = 11111
    GROUP BY [reqStatus]
        ,[reqID]
    ) sub ON sub.[EarliestAuditID] = a.AuditID

+------------+------------+------------+-----------+
| Project ID |  UpdateDT  |  Audit ID  | SubStatus |
+------------+------------+------------+-----------+
|   11111    | 2017-05-25 |   10135    | Planning  |
|   11111    | 2017-10-11 |   10254    | Cancelled |
+------------+------------+------------+-----------+

The result I want:

+------------+------------+------------+-----------+
| Project ID |  UpdateDT  |  Audit ID  | SubStatus |
+------------+------------+------------+-----------+
|   11111    | 2017-12-20 |   10123    | Planning  |
|   11111    | 2017-10-11 |   10254    | Cancelled |
+------------+------------+------------+-----------+

A: Here is one way to tackle this using ROW_NUMBER.
declare @tRequestsAudit table
(
    ProjectID int
    , UpdateDT date
    , AuditID int
    , SubStatus varchar(10)
)

insert @tRequestsAudit values
(11111, '2017-12-20', 10123, 'Planning')
, (11111, '2017-05-25', 10135, 'Planning')
, (11111, '2017-10-11', 10254, 'Cancelled')
;

select ProjectID
    , UpdateDT
    , AuditID
    , SubStatus
from
(
    select *
        , RowNum = ROW_NUMBER()over(partition by ProjectID, SubStatus order by UpdateDT desc)
    from @tRequestsAudit
) x
where x.SubStatus <> 'Planning'
OR
(
    x.SubStatus = 'Planning'
    AND
    x.RowNum = 2
)

A: If you are using SQL 2012 and above, you can use the lead function to remove the Planning records which were cancelled later. This query assumes that there is going to be a sequential order of Planning and Cancelling:
select a.*
from
(select *,lead(Substatus,1) Over(Partition by [Project ID] Order by UpdateDt) as lead_status
from [RptChange].[dbo].[tRequestsAudit])a
where a.lead_status!='Cancelled'


text:
Q: How can I import specific Swift classes/modules hosted on a particular webpage? I am currently building an application which will allow mini-plugins to aid the use of my application. It is a lot like Slack, allowing user-contributed, custom plugins to aid the user. These plugins will be Swift classes. I will be setting up a system where users can submit their custom plugins to be hosted on a webpage. Users in my application will be able to select a few of these plugins that they need, and the application would import those plugins only, and add the classes containing the plugins to a top-level file so that everything in my application can use these plugin classes. How can I import these selected modules into my application files?
For example, if I have a variable webpageURLContainingPlugin, then is there anything that will allow me to import the class/module at that link?
Also, I wouldn't want to download all those plugins when creating my XCode project, as I feel it would take too much unnecessary space to store all of the possible plugins, whereas a user may only choose upto five of those to use.
If it is not possible to import a file from the internet containing these modules, please can you suggest a workaround to this issue?
Edit: I am not looking for a way to create the plugin architecture, and I have an idea of how I'd like to do that, my question is more about accessing Plugins hosted online on a webpage and putting it onto my top level files so I can access them. However, if there is a specific plugin architecture that I must follow to be able to do this, then please suggest it.

A: You can't. IAPs might be an option worth exploring.

AppStore review guidelines
2. Performance > 2.5 Software Requirements
2.5.2 Apps should be self-contained in their bundles, and may not read or write data outside the designated container area, nor may they download, install, or execute code, including other apps. Apps designed to teach, develop, or test executable code may, in limited circumstances, download code provided that such code is not used for other purposes. Such apps must make the source code provided by the Application completely viewable and editable by the user.


text:
Q: Show jQuery UI validation in tooltip As soon I've started using MVC I couldn't realize how to display correct error validation in a tooltip.
For an instance:
$(document).tooltip({
     items: ".input-validation-error",
     content: function() {
           return $(this).attr('data-val-required');
     }
});

It shows just "data-val-required" message. How can I make it dynamically to show the correct error that has occured? There's any libray/framework in JS to implement it?

A: How we set up our validation is to put attributes on the fields that have validation (in the model)
[Required]
public string Field { get; set; }

then on the view use the validation helpers.  At the top
@Html.ValidationSummary()

and generally below each field
@Html.ValidationMessageFor(x => x.Field, "*")

we like to use asterisk next to the field and have the message show in the summary at the top.  you can replace that with a message if you would like.  To trigger server side do a post back and in the post action check
ModelState.IsValid()

if not then send it back and the messages will show.  From your code it looks like you are wanting something fired with Jquery which you can do with
if($('form').valid()){
    //something here,  ajax call maybe when all forms are valid
}

this will trigger the validation for you on the client side.  It will highlight the fields red and a summary of all of the invalid fields will show at the top.  Hopefully this helps.


text:
Q: Retrieve IMSI by using CodenameOne, Cordova and AngularJS I use Cordova Hybrid Apps in Codename One and I would like retrieve the IMSI of the SIM card. Someone can help me please?
Thanks

A: iOS doesn't provide access to IMSI natively to protect users privacy. We provide Display.getMsisdn() but it won't work on most modern platforms.
I'm guessing what you are really asking is this Codenameone:How to get the mobile number of current sim card in real device?


text:
Q: How to displaying categories in the cart Woocommerce? Question on Woocommerce. In the cart need to divide the products into categories. For example...
Category 1
product 1 - $10.
product 2 - $20.
Category 2
product 1 - $10.
product 2 - $20.
There is a variant <? Php echo $ _product-> get_categories (); ?>
But the problem is that categories are displayed before each product:
Category 1
product 1 - $10.
Category 1
product 2 - $20.
Help solve this problem. Thanks!
Code cart.php:
<?php do_action( 'woocommerce_before_cart_contents' ); ?>

        <?php
        foreach ( WC()->cart->get_cart() as $cart_item_key => $cart_item ) {
            $_product   = apply_filters( 'woocommerce_cart_item_product', $cart_item['data'], $cart_item, $cart_item_key );
            $product_id = apply_filters( 'woocommerce_cart_item_product_id', $cart_item['product_id'], $cart_item, $cart_item_key );

            if ( $_product && $_product->exists() && $cart_item['quantity'] > 0 && apply_filters( 'woocommerce_cart_item_visible', true, $cart_item, $cart_item_key ) ) {
                $product_permalink = apply_filters( 'woocommerce_cart_item_permalink', $_product->is_visible() ? $_product->get_permalink( $cart_item ) : '', $cart_item, $cart_item_key );
                ?>

                            <?php echo $_product-> get_categories (); ?>

                <tr class="woocommerce-cart-form__cart-item <?php echo esc_attr( apply_filters( 'woocommerce_cart_item_class', 'cart_item', $cart_item, $cart_item_key ) ); ?>">

                        <?php
                            echo apply_filters( 'woocommerce_cart_item_remove_link', sprintf(
                                '×',
                                esc_url( WC()->cart->get_remove_url( $cart_item_key ) ),
                                __( 'Remove this item', 'woocommerce' ),
                                esc_attr( $product_id ),
                                esc_attr( $_product->get_sku() )
                            ), $cart_item_key );
                        ?>

                        <?php
                            $thumbnail = apply_filters( 'woocommerce_cart_item_thumbnail', $_product->get_image(), $cart_item, $cart_item_key );

                            if ( ! $product_permalink ) {
                                echo $thumbnail;
                            } else {
                                printf( '%s', esc_url( $product_permalink ), $thumbnail );
                            }
                        ?>

                    <td class="product-name" data-title="<?php esc_attr_e( 'Product', 'woocommerce' ); ?>">

<?php
                            if ( ! $product_permalink ) {
                                echo apply_filters( 'woocommerce_cart_item_name', $_product->get_name(), $cart_item, $cart_item_key ) . ' ';
                            } else {
                                echo apply_filters( 'woocommerce_cart_item_name', sprintf( '%s', esc_url( $product_permalink ), $_product->get_name() ), $cart_item, $cart_item_key );
                            }

                            // Meta data
                            echo WC()->cart->get_item_data( $cart_item );

                            // Backorder notification
                            if ( $_product->backorders_require_notification() && $_product->is_on_backorder( $cart_item['quantity'] ) ) {
                                echo '
' . esc_html__( 'Available on backorder', 'woocommerce' ) . '
';
                            }
                        ?>

<?php  the_field('weight',$product_id); ?>

                    <td class="product-price" data-title="<?php esc_attr_e( 'Price', 'woocommerce' ); ?>">
                        <?php
                            echo apply_filters( 'woocommerce_cart_item_price', WC()->cart->get_product_price( $_product ), $cart_item, $cart_item_key );
                        ?>

                    <td class="product-quantity" data-title="<?php esc_attr_e( 'Quantity', 'woocommerce' ); ?>">
                        <?php
                            if ( $_product->is_sold_individually() ) {
                                $product_quantity = sprintf( '1 <input type="hidden" name="cart[%s][qty]" value="1" />', $cart_item_key );
                            } else {
                                $product_quantity = woocommerce_quantity_input( array(
                                    'input_name'  => "cart[{$cart_item_key}][qty]",
                                    'input_value' => $cart_item['quantity'],
                                    'max_value'   => $_product->get_max_purchase_quantity(),
                                    'min_value'   => '0',
                                ), $_product, false );
                            }

                            echo apply_filters( 'woocommerce_cart_item_quantity', $product_quantity, $cart_item_key, $cart_item );
                        ?>

                    <td class="product-subtotal" data-title="<?php esc_attr_e( 'Total', 'woocommerce' ); ?>">
                        <?php
                            echo apply_filters( 'woocommerce_cart_item_subtotal', WC()->cart->get_product_subtotal( $_product, $cart_item['quantity'] ), $cart_item, $cart_item_key );
                        ?>

                <?php
            }
        }
        ?>

        <?php do_action( 'woocommerce_cart_contents' ); ?>


text:
Q: Facing issue while retrieving the document from MongoDB based on Date field Actually my date field in mongodb looks like this "Date" : ISODate("2015-03-01T00:00:00.000+0000").
Based on this field I'm trying to retrieve the document using java.
But, I'm getting null while retrieving the document.
Regarding conversion of String to Java Date Object I'm facing issue.
Can anyone please help me out?
MongoDatabase db = mongoclient.getDatabase("myDB");
MongoCollection<Document> col = db.getCollection("myCol");

SimpleDateFormat format = new SimpleDateFormat("yyyy-MM-dd'T'HH:mm:ss.SSS+SSSS") ;
String oldDate = "2015-03-01T00:00:00.000+0000";
Date date = format.parse(oldDate);

Document doc = new Document();
doc.put("Date" , date);
System.out.println(col.find(doc).first());


text:
Q: X-axis date label wrong we are binding data to chart date rage from 30/10/2018 to 30/01/2019, but the first labels on the x-axis are showing as 29/10/2018.
can anyone let us know what are the settings to change?


text:
Q: Bug in isodata?: German short date with horizontal spaces after periods Is there a bug in the isodate package? When I switch to \shortdate with the option german, horizontal spaces occur after the periods:
\documentclass{article}
\setlength{\parindent}{0pt}
\usepackage[german]{isodate}
    \shortdate
\begin{document}
30.04.17 (manual)\\\today\,(isodate)
\end{document}

Is this known/wanted? I certainly would rather not have the spaces after the periods. Would it be better to use datetime2?

A: It is wanted, see the documenentation. You can change it like this:
\documentclass{article}
\setlength{\parindent}{0pt}
\usepackage[german]{isodate}
    \shortdate
\daymonthsepgerman{}\monthyearsepgerman{}{}
\begin{document}
30.04.17 (manual)\\\today\,(isodate)
\end{document}


text:
Q: How to obtain sum of records in a key,value fashion using nativeQuery in CrudRepository? I am getting an array-list as a return type with 0th index as an array. What i want is a key value pair segregation, where column name is the key and its value is the corresponding sum i obtained.
@Query(value = "
SELECT SUM(revenue_amount) AS revenue_amount
     , SUM(service_charge_amount) AS service_charge_amount
  FROM event_stats
 WHERE event_id = :event_id
", nativeQuery = true)
public ? findTicketTotalForAnEvent(@Param("event_id") String event_id);

What should be the return type ? And how to filter it further ?

A: If you're open to use Projections, something like below would give you desired result.
Declare a static interface like below:
static interface TotalTicketsForEvent {
    public Long getRevenueAmount();
    public Long getServiceChargeAmount();
}

Now your query should be:
@Query(value="SELECT SUM(revenue_amount) AS revenueAmount, SUM(service_charge_amount) AS serviceChargeAmount FROM event_stats WHERE event_id = :event_id", nativeQuery = true)
public List<TotalTicketsForEvent> findTicketTotalForAnEvent(@Param("event_id") String event_id);

You can use the interface methods to process the list further.


text:
Q: Cannot update a post I am trying to update an answer I just provided with some resource links - but it constantly keeps crashing on me and the kitty seems awfully busy by now :-)
Here's the question I answered:
Is there a library to use Linq to directly query databases, dynamically?
I tried several times to add one or two links to relevant articles / blog posts, but no matter what I do (links inside the text or at the end of the paragraph), when I click on "save", the kitty comes up and the changes aren't saved.....

A: Fixed. The problem should be taken care of now.

A: I successfully edited your comment. Is it only links that cause problems?
EDIT
Ok I see this now. I tried to edit this answer and include a link to google and I get the error message consistently

A: I'm running into this as well on a question I created: Can I recursively create a path in Zookeeper?
It already has a link in it, and didn't give me a problem when I first created it. Going back to fix a typo in the code, however, gives me busykitteh.

A: I'm having the same problem. I've tried editing some of my older answers, and I can't, if they have links and I keep the links in.
If I remove all links from the post, I can edit it.
Kitten kaboodles!

A: Confirmed that this happens on ServerFault as well, not just SO


text:
Q: Run program on AWS server from browser I am not sure this can be done but I have installed a Winforms application on an AWS server. I want to allow users to run the program but not by going through the rigmarole of using RDC and then running the program when connected that way. I looked at this article:
https://learn.microsoft.com/en-us/windows-server-essentials/use/use-remote-web-access-in-windows-server-essentials#BKMK_Connect
But when I tried connecting in the browser I got an error "this web page can't be found". Ultimately I want the user to have an icon on their desktop that they click on, it connects to the server, runs the program for them to then use. Is that even possible?

A: This sounds like a potential use case for Amazon AppStream where the desktop applications run on a remote, managed server and you interact with them from your browser.
You can try out sample applications like FreeCAD or Eclipse.


text:
Q: Beautiful problem about polyhedrons A regular tetrahedron has this property:
For any two of its vertices exists a third vertex, which forms a regular triangle with these 2 vertices. (But it doesn't mean any 3 vertices form a regular triangle)
Are there any other polyhedrons that have the same property?
I think there isn't such a polyhedron. But not sure how to prove it. I've tried proving that there isn't an irregular tetrahedron with this property, assuming that there is a pair of unequal sides.


text:
Q: I need to change database from mysql to postgres for a JSP project which is using hibernate. How should I do it? I have to change DB from Mysql to Postgres. What changes should I make to my hibernate.cfg.xml
<?xml version="1.0" encoding="UTF-8"?>
<!DOCTYPE hibernate-configuration PUBLIC
        "-//Hibernate/Hibernate Configuration DTD 3.0//EN"
        "http://hibernate.sourceforge.net/hibernate-configuration-3.0.dtd">
<hibernate-configuration>
    <session-factory>
        <property name="hibernate.connection.driver_class">com.mysql.jdbc.Driver</property>
        <property name="hibernate.connection.url">jdbc:mysql://localhost:3306/courier</property>
        <property name="hibernate.connection.username">root</property>
        <property name="hibernate.dialect">org.hibernate.dialect.MySQLDialect</property>
        <mapping resource="com/pojo/Adminlogin.hbm.xml" />
        <mapping resource="com/pojo/Contactus.hbm.xml" />
        <mapping resource="com/pojo/Couriercompany.hbm.xml" />

        <mapping resource="com/pojo/Deliveryaddress.hbm.xml" />
        <mapping resource="com/pojo/Domestic.hbm.xml" />

        <mapping resource="com/pojo/Pickupaddress.hbm.xml" />
        <mapping resource="com/pojo/Pincode.hbm.xml" />

        <mapping resource="com/pojo/Userregistration.hbm.xml" />
        <mapping resource="com/pojo/Placecourier.hbm.xml" />
    </session-factory>
</hibernate-configuration>

Will I need to make further changes in my java files for the postgres queries to work. Do I need to add anything to my webcontent files which mainly have frontend JSP pages??

A: Mainly you have to change driver and dialect and of course the credentials and url.
If you did not use native queries everything should work just fine.

A: This is a hibernate.cfg.xml for posgresql and it will help you with basic hibernate configurations for posgresql.
<!DOCTYPE hibernate-configuration PUBLIC
        "-//Hibernate/Hibernate Configuration DTD 3.0//EN"
        "http://www.hibernate.org/dtd/hibernate-configuration-3.0.dtd">

<hibernate-configuration>
    <session-factory>
        <property name="hibernate.dialect">org.hibernate.dialect.PostgreSQLDialect</property>
        <property name="hibernate.connection.driver_class">org.postgresql.Driver</property>
        <property name="hibernate.connection.username">postgres</property>
        <property name="hibernate.connection.password">password</property>
        <property name="hibernate.connection.url">jdbc:postgresql://localhost:5432/hibernatedb</property>

        <property name="connection_pool_size">1</property>

        <property name="hbm2ddl.auto">create</property>

        <property name="show_sql">true</property>

       <mapping class="org.javabrains.sanjaya.dto.UserDetails"/>

    </session-factory>
</hibernate-configuration>


text:
Q: Inserting LilyPond files into ShareLatex I've created a couple LilyPond .ly files, with some music I want to insert into a Latex document I have on ShareLatex, but I don't know which packages to use etc.
Does anyone know how I can get this done?

A: I ended up going with just creating individual images (.pdf, with the highest quality option, as @Richard suggested) and inserting them into the .tex with \includegraphics. It's not a perfect solution, but it was definitely good enough for my purposes.
As an aside, using ShareLaTeX (now Overleaf) is a good solution when you're relatively new to LaTeX, but situations like this where it forces you to use suboptimal workarounds do arise quite often. I now use TeXStudio and don't think I'll ever need another LaTeX editor again.


text:
Q: $http.get() in controller not working for my API I am working on Application which uses Angularjs.I want to call api and get data using $http.get().My problem is when I use my api in url its not working whereas I use url which I found on w3schools tutorial is working fine.
here is my code :
 var url = "/api/v1/policycategory/get";
 $http.get(url).then(function (response) {
    $scope.myString= response.statusText;
 });

Using my api I am getting my response in browser as below :
[{"id":1,"name":"Dependants only","displayName":"Dependants Only","dateTimeCreated":"2016-05-12T11:58:19.35"},{"id":2,"name":"One adult","displayName":"Single","dateTimeCreated":"2016-05-12T11:58:19.357"},{"id":3,"name":"One adult & dependant(s)","displayName":"Sole Parent","dateTimeCreated":"2016-05-12T11:58:19.363"},{"id":4,"name":"One adult & any dependants","displayName":"Sole Parent Plus","dateTimeCreated":"2016-05-12T11:58:19.367"},{"id":5,"name":"Two adults","displayName":"Couple","dateTimeCreated":"2016-05-12T11:58:19.367"},{"id":6,"name":"Two adults & dependant(s)","displayName":"Family","dateTimeCreated":"2016-05-12T11:58:19.37"},{"id":7,"name":"Two adults & any dependants","displayName":"Family Plus","dateTimeCreated":"2016-05-12T11:58:19.37"}]
When I use my api,it does not run that part inside function.

A: You are assigning $scope.myString= response.statusText; but your response does not have a field called statusText.

A: yes you are getting the data but you are not accessing it correctly. If you write $scope.myString = response[0].id; the you will see that it has some value. You are trying to access response.statusText but the key statusText does not exist in your response

A: you should return data not statusText
var url = "/api/v1/policycategory/get";
 $http.get(url).then(function (response) {
    $scope.myString= response.data;
 });


text:
Q: Get image size from existing image by location angularjs I want to validate existing images size which have been saved before. Value stored in database is just image name.
Here is my html code

Is there any way to get image size (in KB/MB not height and width) from image path in angularjs? or should do something in java controller?

A: No this will not be possible with Angular as the only was with javascript to do this is to execute an AJAX request for the image then read the
getResponseHeader('Content-Length')

Header property. Angular JS is not intended for these kinds of operations.

function httpGetFileSize(theUrl){
 //FETCH Data From Server
 xmlhttp=new XMLHttpRequest();
 xmlhttp.open("HEAD", theUrl , false );
 xmlhttp.send();
 return xmlhttp.getResponseHeader('Content-Length');
}

That is the javascript answer to this problem. You could also do this server side with PHP or ASP


text:
Q: Eclipse RCP IPageLayout woes I have an Eclipse RCP application with a sort of three column layout:

The editor area is at the extreme right. Now, when you get an IPageLayout to work with, the editor area is already added in. That's fine: we add area B to the left of the editor, and area A to the left of B, and the layout is exactly what we need.
The issue is that when you move the sash between A and B, views A and B change without resizing the editor area (good;) but when you move the other sash between B and the editor area, all three views are resized; the layout manager acts to maintain the ratio of the widths of A and B, and that's not what we want. We want the user to be able to move each sash independently, and have it influence only the two views it touches.
It seems like the root cause of this is that the editor is in place when you get your IPageView, and therefore you have to position the IFolderLayouts relative to it. If you could position the editor relative to B, instead, then resize would do the right thing.
So my questions:

*

*Is there any way to tell the IPageView to position the editor relative to a view, instead of the other way around?

*Barring that, is there any other way to influence the layout algorithm, like writing some kind of layout manager?

A: I know of no way to alter the layout tree of IPageLayout in Eclipse 3.x. In Eclipse 4.2, however, the Application Model can be changed dynamically at runtime.
So, if you would consider migrating your application to Eclipse 4, this solution could be an option. To keep the original application and UI code as untouched as possible, this solution will

*

*take full advantage of the compatibility layer of Eclipse 4 to create an Application Model from the Eclipse 3 based RCP application. There is no need to create an Application Model or alter the UI code of the application.

*rearrange the editor area's layout after the application is active. This is done by creating an addon class in a separate plugin.

*allow easy migration to more Eclipse 4 functionality in the future: Should you decide to build an own Application Model, you can just unhook the addon plugin.

I started with the regular RCP Mail template of Eclipse 3 and altered the perspective to recreate the problem. This is the Perspective class I used in my test application:
import org.eclipse.ui.IPageLayout;
import org.eclipse.ui.IPerspectiveFactory;

public class Perspective implements IPerspectiveFactory {

  public static final String ID = "wag.perspective";

  public void createInitialLayout(IPageLayout layout) {
    String editorArea = layout.getEditorArea();
    layout.setEditorAreaVisible(true);

    layout.addStandaloneView(AView.ID, false, IPageLayout.LEFT,
                             0.25f, editorArea);
    layout.addStandaloneView(BView.ID, false, IPageLayout.LEFT,
                             0.25f, editorArea);

    layout.getViewLayout(AView.ID).setCloseable(false);
    layout.getViewLayout(BView.ID).setCloseable(false);
  }
}

It basically creates the scenario you described: a three column layout where one sash effects all three parts and the other one only two.
I then proceeded to migrate the application and alter the Application Model.
Migrate the Eclipse 3 based RCP application to Eclipse 4
There are online tutorials available for this process. I found Eclipse 4.1: Run your 3.x RCP in 4.1 and Eclipse 4 and the Compatibility Layer - Tutorial to be very helpful.
I recommend including the org.eclipse.e4.tools.emf.liveeditor and its required plug-ins in your product dependencies. With the live editor, you can take a look at the Application Model that is created by the compatibility layer.
Once the application starts, thet sashes will still behave the same way. Open the live editor on your application window and take a look at your model.

You can see that the PartSashContainer including the placeholder for the AView contains another PartSashContainer. Moving the sash between AView and that container will update the rest of the layout tree, while moving the sash between BView and the editor does not effect other parts of the layout.
You could now drag the placeholder for the AView to the container where the BView and the editor are located. This would instantly create the effect you desire: The sashes will only affect their direct neighbours. But these changes will only be saved in one's own runtime workspace. Something else is needed to alter the layout structure automatically.
Altering the Application Model at runtime
Since I didn't want to touch the original code if possible, I created another plugin to make a contribution to the Application Model.
Create a Plug-In Project without an Activator without using a template.
Add an Addon class: select New->Other->Eclipse 4->Classes->New Addon Class
Add a Model Fragment: select New->Other-Eclipse 4->Model->New Model Fragment. Open the created fragment.e4xmi file and add a Model Fragment. For the Element Id, put org.eclipse.e4.legacy.ide.application (this is the standard id of legacy applications) and for the Featurename addons. Add an Addon to the Model Fragment. Enter an ID and set the Class URI to your addon class.
Now add your fragment.e4xmi to your org.eclipse.e4.workbench.model extension point:
<extension
  id="id1"
  point="org.eclipse.e4.workbench.model">
  <fragment
    uri="fragment.e4xmi">
  </fragment>
</extension>

Add your contribution plugin to the dependencies of your application product. When you start your application and look at the model with the live editor, you should see your Addon listed in the model.
Now we can implement the Addon. This is the code of my Addon class:
package wag.contribution.addons;

import java.util.ArrayList;
import java.util.Arrays;
import java.util.List;

import javax.annotation.PostConstruct;
import javax.annotation.PreDestroy;
import javax.inject.Inject;

import org.eclipse.e4.core.services.events.IEventBroker;
import org.eclipse.e4.ui.model.application.MApplication;
import org.eclipse.e4.ui.model.application.ui.MElementContainer;
import org.eclipse.e4.ui.model.application.ui.MUIElement;
import org.eclipse.e4.ui.model.application.ui.advanced.MPlaceholder;
import org.eclipse.e4.ui.workbench.modeling.EModelService;
import org.osgi.service.event.Event;
import org.osgi.service.event.EventHandler;

public class LayoutSorter {

  @Inject private IEventBroker broker;

  private EventHandler handler;

  // The part IDs we are interested in, sorted in the sequence they should be
  // shown
  private static List<String> PART_IDS = Arrays.asList(new String[] {
              "wag.aView", "wag.bView", "org.eclipse.ui.editorss" });

  // Listen to the e4 core service's event broker to find the magical time
  // when the application is created and try to sort the layout.
  @PostConstruct
  void hookListeners(final MApplication application,
                     final EModelService service) {

    if (handler == null) {
      handler = new EventHandler() {
        // Try to sort the layout. Unsubscribe from event broker if
        // successful.
        @Override
        public void handleEvent(Event event) {
          try {
            sort(application, service);
            // sort did finish: stop listening to the broker.
            broker.unsubscribe(handler);
          } catch (Exception e) {
            // Something went wrong, the application model was not ready yet.
            // Keep on listening.
          }
        }
      };

      // Subscribe "ServiceEvent.MODIFIED" to grab the application.STARTED
      // event. Does anybody know how to do this in a better way?
      broker.subscribe("org/osgi/framework/ServiceEvent/MODIFIED",
                       handler);
    }
  }

  private void sort(MApplication application, EModelService service) {

    // find all placeholders
    List<MPlaceholder> placeholders = service.findElements(application,
              null, MPlaceholder.class, null);

    // only keep the ones we are interested in
    for (int i = placeholders.size() - 1; i > -1; i--) {
      if (!PART_IDS.contains(placeholders.get(i).getElementId())) {
        placeholders.remove(i);
      }
    }

    // find the parents of the placeholders
    List<MElementContainer<MUIElement>> parents = new ArrayList<>(
             placeholders.size());
    for (MPlaceholder placeholder : placeholders) {
      parents.add(placeholder.getParent());
    }

    // find the parent that is "deepest down" in the tree
    MElementContainer<MUIElement> targetParent = null;
    for (MElementContainer<MUIElement> parent : parents) {
      for (MUIElement child : parent.getChildren()) {
        if (parents.contains(child)) {
          continue;
        }
        targetParent = parent;
      }
    }

    // move all parts to the target parent
    if (targetParent != null) {
      for (int i = 0; i < placeholders.size(); i++) {
        if (targetParent != placeholders.get(i).getParent()) {
          service.move(placeholders.get(i), targetParent, i);
        }
      }
    }
  }

  @PreDestroy
  void unhookListeners() {
    if (handler != null) {
      // in case it wasn't unhooked earlier
      broker.unsubscribe(handler);
    }
  }
}

(Please note that the code above is a bit of a hack because it is only really suited for this specific problem.)
After a restart, the application should now behave in the desired way. Take a look at the Application Model to see your changes.
One thing to be aware of is that local changes are saved in the runtime workspace in the file .metadata\.plugins\org.eclipse.e4.workbench\workbench.xmi if saving is switched on, so for recreating the unaltered model for testing this file has to be deleted.

A: I don't think, it's possible to achieve exactly what you want (so the answers to your questions would be 1. no, 2. no). But there it a 3rd alternative, which IMO behaves quite nicely.
When trying in Eclipse: Start with viewA on left and Editor on right. Then when you drag viewB to the right side of viewA, you get the (wrong) setup you describe. But then you drag it to the left part of the Editor, then you get different configuration, where dragging right sash behaves as you want. Dragging of left sash resizes viewA and Editor and MOVES viewB.
I would say that the code to achieve this would be:
IFolderLayout areaA = layout.createFolder("A", IPageLayout.LEFT, 0.33f, editorArea);
IFolderLayout areaB = layout.createFolder("B", IPageLayout.LEFT, 0.5f, editorArea);


text:
Q: Why is my program writing  to my file? def convert(score):
    if score >= '90':
        msg = "Congratulations! You earned an A!"
        (msg)

    elif score >= '80':
        msg = "You earned a B; good job!"
        (msg)

    elif score >= '70':
        msg = "You earned a C; looks like you need to study a little harder."
        (msg)

    elif score >= '60':
        msg = "You earned a D; maybe you should consider tutoring"
        (msg)

    else:
        score < '60'
        msg = "I'm sorry; you failed."
        (msg)

    return convert

def main():
    infilename = input("Please enter the name of the input file: ")
    outfilename = input("Please enter the name of the output file: ")

    infile = open(infilename,"r")
    outfile = open(outfilename,"w")

    for line in infile:
        msg = convert(line)
        print(msg,file=outfile)

    infile.close()
    outfile.close()

main()

The grades are supposed to print to a file, but when I open the file, all it says is: <function convert at 0x02DE8C00>. If I run the code, and don't try to print it to a file, it works fine.
OK, they want me to add more details, but I can't really think of anything else to add, I think you get it.
What have I done wrong this time?

A: Your function returns itself (return convert) instead of msg.


text:
Q: Add Applet in project I understood from people my error and thanx for them. I have to add and extends Applet file to my ready project. Should I start from begining or it is possible just add Applet to the project and make it work? I have to add my programm to HTML.
Here is pictures of my error and my project:
Jar file and puctures

A: hht_7.HHT_7 needs to extends Applet


text:
Q: Typo3 Solr -failed to execute page indexer request I have a question related to the Typo3 v10 Solr extension. For some reasons some pages can not be indexed properly. In the logs I see these errors:
Failed to execute Page Indexer Request. See log for details. Request ID:
In the logs it looks like some requests contain empty raw body. Rest pages with same type have been indexed properly. Maybe someone has encountered similar issues with solr indexer? What cause the issue in this case?


text:
Q: ¿Como agregar caracteres a una palabra contenida en un texto? Necesitaba saber como colocar caracteres especiales a una palabra que seleccione dentro de un textarea. Por ejemplo, si tengo el siguiente texto:
La palabra que deseo seleccionar es [esta] con corchete.
Es decir, al seleccionar la palabra esta, se le agregue los [] en sus extremos.
Esto intentando algo así:
<form id="miform">
  <textarea id="texto" rows="20" cols="100">La palabra que deseo seleccionar es [esta] con corchete.</textarea>
</form>

 <button class="btn btn-lg" type="submit" id="seleccione">Seleccionar</button>

 $("#seleccione").on("click", function (ev) {
  selectedText = document.getSelection();
  $("#texto").html("[ " + selectedText +"]");
});

Lógicamente se me va a reemplazar todo el texto por la palabra selecciona con corchetes, pero eso no es lo que quiero, sino lo que le había explicado.

A: Esta sería una forma de hacerlo, solo faltaría ponerle los corchetes a la palabra elegida y no a todas las que sean iguales.

$("#seleccione").on("click", function(ev) {
  let selectedText = window.getSelection().toString()
  let regexp = new RegExp(selectedText, 'g');
  selectedText=$("#texto").html().replace(regexp, "[" + selectedText + "]")
  $("#texto").html(selectedText);
});
<script src="https://cdnjs.cloudflare.com/ajax/libs/jquery/3.3.1/jquery.min.js"></script>
<form id="miform">
  <textarea id="texto" rows="20" cols="100">La palabra que deseo seleccionar es esta con corchete.</textarea>
</form>

<button class="btn btn-lg" type="submit" id="seleccione">Seleccionar</button>

A: Buenas esta forma sería afectando solo a el texto seleccionado. Espero que te sirva

function markSelection(el) {
  const {
    selectionStart,
    selectionEnd,
    value
  } = el;
  const to = selectionEnd - selectionStart;
  const selectedText = '[' + value.substr(selectionStart, to) + ']';
  const prevToSelection = value.substring(0, selectionStart);
  const nextToSelection = value.substring(selectionEnd);
  el.value = prevToSelection + selectedText + nextToSelection;
}
#text {
  width: 100%;
  height: 100px;
}
<textarea id="text">Lorem ipsum dolor sit amet consectetur, adipiscing elit mattis nisi nunc, vehicula tristique proin commodo. Fermentum ante sociosqu torquent posuere montes cursus tincidunt massa pellentesque donec arcu, etiam convallis varius lobortis mollis cras pharetra scelerisque nullam mus leo fames, tempor vel elementum odio porta nisl lectus nisi parturient a. Nam iaculis felis vehicula massa auctor sodales lacinia, sagittis a augue malesuada natoque netus penatibus phasellus, at ut vulputate rutrum diam quis.

Praesent erat tempus aenean porta laoreet hac, facilisi ultricies litora inceptos sed etiam maecenas, senectus ornare torquent penatibus viverra. Maecenas leo condimentum rutrum cubilia ac sociosqu habitasse aliquet, urna lacinia tristique rhoncus morbi curabitur praesent, felis dapibus accumsan sagittis sem auctor fusce. Taciti hendrerit tincidunt urna tristique aenean mauris tempus metus, convallis massa neque platea semper aptent sem, felis id odio conubia molestie in erat.</textarea>
<button onclick="markSelection(text)">Marcar seleccion</button>


text:
Q: How to get new hash value of URL without page reload I setup this script to capture clicks to  elements and grab the location.hash value:
$('a').on('click', function(){
    filenamehash=location.hash;
    console.log(filename);
    console.log(filenamehash);
});

The problem is, the value of the hash doesn't seem to change until after the function completes. So if I click a new hash value in my page, the above script doesn't catch it. If I click it a second time, it does.
Do I need a delay of some kind? Or perhaps "on click finish" event (if there is such a thing?).
Thanks.

A: Why not just listen for the hash change instead
$(window).on('hashchange', function() {
    console.log( window.location.hash );
});

or if the hash is the anchors href, just get that
$('a').on('click', function(){
    var filenamehash = $(this).attr('href');

    console.log(filenamehash);
});


text:
Q: How to activate device admin on google glasses? I want to disable camera on my google glasses. Is there any way to activate device admin and call DevicePolicyManager.setCameraDisabled(admin, disabled) method.

A: Android stack on Google glass doesn't support admin feature.


text:
Q: Setting font in share intent android I am looking for the solution since quite a while now. I want to set the font of the text shared from my app to other apps.
I don't know how I can achieve this, the font is in .ttf file. The below code I am using but it is for the plain text.
Intent intent = new Intent(Intent.ACTION_SEND);
        intent.setType("text/plain");
        intent.putExtra(Intent.EXTRA_TEXT, "This is a message for you
Hello");

        mShareActionProvider.setShareIntent(intent);

Please let me know the possible options I have.
Thanks,
Amandeep

A:
I want to set the font of the text shared from my app to other apps.

That is not possible, sorry.

The below code I am using but it is for the plain text.

You may wish to use text/html, not text/plain, given that you are passing HTML tags.


text:
Q: Add two Pandas Series or DataFrame objects in-place? I have a dataset where we record the electrical power demand from each individual appliance in the home.  The dataset is quite large (2 years or data; 1 sample every 6 seconds; 50 appliances).  The data is in a compressed HDF file.
We need to add the power demand for every appliance to get the total aggregate power demand over time.  Each individual meter might have a different start and end time.
The naive approach (using a simple model of our data) is to do something like this:
LENGHT = 2**25
N = 30
cumulator = pd.Series()

for i in range(N):
    # change the index for each new_entry to mimick the fact
    # that out appliance meters have different start and end time.
    new_entry = pd.Series(1, index=np.arange(i, LENGTH+i))
    cumulator = cumulator.add(new_entry, fill_value=0)

This works fine for small amounts of data.  It also works OK with large amounts of data as long as every new_entry has exactly the same index.
But, with large amounts of data, where each new_entry has a different start and end index, Python quickly gobbles up all the available RAM.  I suspect this is a memory fragmentation issue.  If I use multiprocessing to fire up a new process for each meter (to load the meter's data from disk, load the cumulator from disk, do the addition in memory, then save the cumulator back to disk, and exit the process) then we have fine memory behaviour but, of course, all that disk IO slows us down a lot.
So, I think what I want is an in-place Pandas add function.  The plan would be to initialise cumulator to have an index which is the union of all the meters' indicies.  Then allocate memory once for that cumulator.  Hence no more fragmentation issues.
I have tried two approaches but neither is satisfactory.
I tried using numpy.add to allow me to set the out argument:
# Allocate enough space for the cumulator
cumulator = pd.Series(0, index=np.arange(0, LENGTH+N))

for i in range(N):
    new_entry = pd.Series(1, index=np.arange(i, LENGTH+i))
    cumulator, aligned_new_entry = cumulator.align(new_entry, copy=False, fill_value=0)
    del new_entry
    np.add(cumulator.values, aligned_new_entry.values, out=cumulator.values)
    del aligned_new_entry

But this gobbles up all my RAM too and doesn't seem to do the addition.  If I change the penaultiate line to cumulator.values = np.add(cumulator.values, aligned_new_entry.values, out=cumulator.values) then I get an error about not being able to assign to cumulator.values.
This second approach appears to have the correct memory behaviour but is far too slow to run:
for i in range(N):
    new_entry = pd.Series(1, index=np.arange(i, LENGTH+i))
    for index in cumulator.index:
        try:
            cumulator[index] += new_entry[index]
        except KeyError:
            pass

I suppose I could write this function in Cython.  But I'd rather not have to do that.
So: is there any way to do an 'inplace add' in Pandas?
Update
In response to comments below, here is a toy example of our meter data and the sum we want.  All values are watts.
 time     meter1  meter2  meter3  sum
09:00:00   10                      10
09:00:06   10       20             30
09:00:12   10       20             30
09:00:18   10       20      30     50
09:00:24   10       20      30     50
09:00:30   10               30     40

If you want to see more details then here's the file format description of our data logger, and here's the 4TByte archive of our entire dataset.

A: After messing around a lot with multiprocessing, I think I've found a fairly simple and efficient way to do an in-place add without using multiprocessing:
import numpy as np
import pandas as pd

LENGTH = 2**26
N = 10
DTYPE = np.int

# Allocate memory *once* for a Series which will hold our cumulator
cumulator = pd.Series(0, index=np.arange(0, N+LENGTH), dtype=DTYPE)

# Get a numpy array from the Series' buffer
cumulator_arr = np.frombuffer(cumulator.data, dtype=DTYPE)

# Create lots of dummy data. Each new_entry has a different start
# and end index.
for i in range(N):
    new_entry = pd.Series(1, index=np.arange(i, LENGTH+i), dtype=DTYPE)
    aligned_new_entry = np.pad(new_entry.values, pad_width=((i, N-i)),
                               mode='constant', constant_values=((0, 0)))
    # np.pad could be replaced by new_entry.reindex(index, fill_value=0)
    # but np.pad is faster and more memory efficient than reindex

    del new_entry
    np.add(cumulator_arr, aligned_new_entry, out=cumulator_arr)
    del aligned_new_entry

del cumulator_arr

print cumulator.head(N*2)

which prints:
0      1
1      2
2      3
3      4
4      5
5      6
6      7
7      8
8      9
9     10
10    10
11    10
12    10
13    10
14    10
15    10
16    10
17    10
18    10
19    10

A: assuming that your dataframe looks something like:
df.index.names == ['time']
df.columns == ['meter1', 'meter2', ..., 'meterN']

then all you need to do is:
df['total'] = df.fillna(0, inplace=True).sum(1)


text:
Q: Get class file name in trait I have traitA in traitA.php and classA in classA.php which uses that trait.
I need to get classA file name inside of that trait. Can I do it somehow? __FILE__ returns  traitA.php

A: SOLVED.
I used
$reflection = new ReflectionClass('ClassA');
$classFileName = $reflection->getFileName();


text:
Q: Corporate Sales C++ Me and a friend are having difficulty with this program challenge that our professor assigned us. What we are having with is are int main(). Are tutors keep pointing us to it but won't explain what is wrong. So, if you could explain and show us what we are doing wrong then it would be greatly appreciated.
Here is the question:
A corporation has six divisions, each responsible for sales to different geographic locations. Design a Divsales class that keeps sales data for a division, with the following members:

*

*An array with four elements for holding four quarters of sales figures for the division

*A private static variable for holding the total corporate sales for all divisions for the entire year.

*A member function that takes four arguments, each assumed to be the sales for a quarter. The value of the arguments should be copied into the array that holds the sales data. The total of the four arguments should be added to the static variable that holds the total yearly corporate sales.

*A function that takes an integer argument within the range of 0-3 the argument is to be used as a subscript into the division quarterly sales array. The function should return the value of the array element with that subscript.

Write a program that creates an array of six DivSales objects. The program should ask the user to enter the sales for four quarters for each division. After the data is entered, the program should display a table showing the division sales for each quarter. The program should then display the total corporate sales for the year.
#include <iostream>
#include <cstdlib>
#include  <cctype>

using namespace std;

class DivSales
{
private:
    double quarter [4];
    static double DivCorp;

public:
    double display(int);
    void qutrSale();
}

void DivSales::qutrSale()
{
    int number;

    for (number = 0; number < 4; number++)
    {
        cout << "The sales for the quarter"<< number+1<< ": ";
        cin>> quarter [number];

        DivCorp += quarter[number];

        while (quarter[number] < 0)
        {
            cout<< "Error, please enter a positive sale amount: $";
            cin >> quarter [number];
        }
    }
}

double DivSales::display(int input)
{
    return quarter [input];
}

int main ()
{
    int count;
    DivSales div[5];

    for (count=0; count<5; count++)
    {
        div [count].qutrSale();
    }
    return 0;
}

Some of the errors are

*

*Error    1   error C2628: 'DivSales' followed by 'void' is illegal (did you forget a ';'?)   h:\school\cosc 1337.01\chapter 11 program challenge 7\chapter 11 program challenge 7\corporate sales.cpp    23

*Error    2   error C2556: 'DivSales DivSales::qutrSale(void)' : overloaded function differs only by return type from 'void DivSales::qutrSale(void)' h:\school\cosc 1337.01\chapter 11 program challenge 7\chapter 11 program challenge 7\corporate sales.cpp    24

*Error    3   error C2371: 'DivSales::qutrSale' : redefinition; different basic types h:\school\cosc 1337.01\chapter 11 program challenge 7\chapter 11 program challenge 7\corporate sales.cpp    24

*Error    4   error C2264: 'DivSales::qutrSale' : error in function definition or declaration; function not called    h:\school\cosc 1337.01\chapter 11 program challenge 7\chapter 11 program challenge 7\corporate sales.cpp    54

A: That code doesn't compile even if we knew what it's supposed to be doing. I did some slight changes anyway for it to compile and run, I hope you can inspect this to some help:
#include <iostream>
#include <cstdlib>
#include  <cctype>

using namespace std;

class DivSales

{

private:

double quarter [4];
        static double DivCorp;

    public:
        double display(int);
        void qutrSale();

};
double DivSales::DivCorp = 0;
void DivSales::qutrSale()
{

 int number;

       for (number = 0; number < 4; number++)
        {
            cout << "The sales for the quarter"<< number+1<< ": ";
            cin>> quarter [number];

            DivCorp += quarter[number];

            while (quarter[number] < 0)
            {
                 cout<< "Error, please enter a positive sale amount: $";
                cin >> quarter [number];
            }
        }
}

double DivSales::display(int input)

{
        return quarter [input];
}

int main ()

{

int count;

DivSales div[5];

    for (count=0; count<5; count++)
    {
        div [count].qutrSale();
    }
    return 0;
}

Test run
$ g++ -o test test.c
$ ./test
The sales for the quarter1: 1
The sales for the quarter2: 1
The sales for the quarter3: 1
The sales for the quarter4: 1
The sales for the quarter1: 2
The sales for the quarter2: 2
The sales for the quarter3: 2
The sales for the quarter4: 2
The sales for the quarter1: 3
The sales for the quarter2: 3
The sales for the quarter3: 3
The sales for the quarter4: 3
The sales for the quarter1: 4
The sales for the quarter2: 4
The sales for the quarter3: 4
The sales for the quarter4: 4
The sales for the quarter1: 5
The sales for the quarter2: 5
The sales for the quarter3: 5
The sales for the quarter4: 5
$


text: Q: Is it possible to generate an x509 certificate in Javascript? I have been assigned some JavaScript tasks at work to help me gain exposure with that language. So I'm writing a unit test for a JavaScript implementation someone else has written. I have some tests working but I still need to use an x509 cert for testing. Since placing a file on a CI server is not an option, how can I create an x509 cert for unit testing?


text:
Q: Laravel filter a value in all columns public function getBooks($input)
{
    $books= Book::where('book_name', 'LIKE', '%' . $input . '%')->get();
    return Response::json($books);
}

I know how to filter a column by a given value. But how do I filter ALL columns by a given value. For example, I have a column called 'category' where user should be able to use the same search bar to filter the category.
Something like:
$books = Book::where('all_columns', 'LIKE', '%' . $input . '%')->get();

Thanks!

A: You have to add a where clause for each column like @JoelHinz suggests. To simplify things a bit you can use an array and a loop:
$query = Book::query();
$columns = ['book_name', 'foo', 'bar'];
foreach($columns as $column){
    $query->orWhere($column, 'LIKE', '%' . $input . '%');
}
$books = $query->get();

Or even use the schema builder to retrieve all column names from your table:
$columns = Schema::getColumnListing('books');

A: Most databases do not support searching all columns simultaneously. I'm afraid you'll likely have to chain all of the columns together:
$books = Book::where('book_name', 'LIKE', '%' . $input . '%')
    ->orWhere('another_column', 'LIKE', '%' . $input . '%')
    // etc
    ->get();

A: You can also use this override function to apply condition to all rows.
public function newQuery($excludeDeleted = true) {
        return parent::newQuery()
            ->where('another_column', 'LIKE', '%' . $input . '%');
    }

Now Book Model will provide only result who match your requirement.


text:
Q: Display an image - Popup ArcGIS API for Javascript I'm trying to display an image in a popup, I've read the documentation, I've seen the code of some samples (and also made some attempts using ImageValue and ImageContent), but when I click on the map element with the popup, the image doesn't show. I can't figure out what I'm doing wrong.
Here is my code now and here is my popup when I click on a point:
            var attr = {
                Lat: arr[i][0], //latitude
                Lng: arr[i][1], //longitude
                Image: "localimage.jpg" //image in same folder
            };

            var template = new PopupTemplate({
              title: "Lat: {Lat} Lng: {Lng}",
              mediaInfos: [{
                "title": "",
                "caption": "",
                "type": "image",
                "value": {
                  "sourceURL": "{Image}"
                }
              }]
            });

           //when I click on this point after I've added it to the map,
           //the image doesn't show
             var pointGraphic = new Graphic({
                    geometry: point,
                    symbol: pictureMarkerSymbol, //custom marker
                    attributes: attr,
                    popupTemplate: template
             });

EDIT: I've re-read some samples, trying to understand what I was missing and keeping in mind the answer given here, in the end the solution was that I've missed some parenthesis:
var template = new PopupTemplate({
              title: "Lat: {Lat} Lng: {Lng}",
            content: [{ //Missed [ here
                type: "media",
                mediaInfos: [{
                title: "",
                caption: "",
                value: {
                   sourceURL: "{Image}"
                }
        }]
    }] //Missed ] here
});

Thanks for the reply, hope this helps someone in the future

A: mediaInfos is a property of class MediaContent, that is a type of a possible content of PopupTemplate. So you need to move the media to the content and also indicate the type of the content, by passing a media object or an object to autocast. Something like this,
const template = new PopupTemplate({
  title: "Lat: {Lat} Lng: {Lng}",
  content: [{ // <- media goes in the content
    type: "media", // <- autocast to media
    mediaInfos: [{
      "title": "",
      "caption": "",
      "type": "image",
      "value": {
        "sourceURL": "{Image}"
      }
    }]
  }]
});

UPDATE:
Here you have a working example I made for you,

  <meta charset="utf-8">
  <meta name="viewport" content="initial-scale=1, maximum-scale=1, user-scalable=no">
  <title>ArcGIS API for JavaScript Hello World App</title>

  <link rel="stylesheet" href="https://js.arcgis.com/4.15/esri/css/main.css">


text:
Q: iPython/Jupyter notebooks following deprecation of GoogleDrive "host" For several years, I've been storing iPython/Jupyter notebooks in public folders on my GoogleDrive and then copying a path like this
https://www.googledrive.com/host/folder_id/file_name.ipynb

into the Jupyter nbViewer. This gives me a link to my notebook that I can share with colleagues.
A few days ago all my links stopped working, and after a bit of searching it seems as though Google have discontinued the hosting feature.
I don't want to host a website from my GoogleDrive, but I do need to be able to share iPython notebooks via nbViewer. Are there any alternative ways to continue to do this via my GoogleDrive account, or do I need to look into moving my files elsewhere?
Thanks!

A: Github support ipyton notebook format. So you can upload your file there.
For example, like this file.


text:
Q: Why do we use "congruent to" instead of equal to? I'm more familiar with the notation $a \equiv b \pmod c$, but I think this is equivalent to $a \bmod c = b \bmod c $, which makes it clear that we should put a $=$ instead of $\equiv$.
What's the reason for the change of sign? If it's to emphasize that modular equivalence is a congruence relation, why don't we use the $\equiv$ sign in both notations?

A: The difference between the two is as follows:
Note that (in its usual usage) $a \mod c$ is a function that gives a particular answer, and has nothing to do with equivalence relations per se.  For example, we might note that
$$
\renewcommand{\mod}{\operatorname{mod}}
7 \mod 2 = 1
$$
That is, $7$ has a remainder of $1$ upon division by $2$.
What we cannot say is that
$$
7 \mod 2 = 3
$$
because $1$ and $3$ are distinct values.  We can say, however, that
$$
7 \equiv 3 \pmod 2
$$
Since both $7$ and $3$ have the same remainder upon division by $2$.

Why is it important?  Well, we often make "substitutions" of equivalent values, and writing "mod" every time you make a substitution becomes unwieldy.  For example, we can compute:
$$
5*7*9 - 2*3 + 5 + 3 \equiv 1*1*1 - 0*1 + 1 + 1 \equiv 3 \equiv 1 \pmod 2
$$
If we were to write this with mod as an operator, we'd have
$$
[5*7*9 - 2*3 + 5 + 3] \mod 2 =\\
[(5 \mod 2)(7 \mod 2)(9 \mod 2) - (2 \mod 2)(3 \mod 2) + (5 \mod 2) + 3 \mod 2] \mod 2 = \\
[(1)(1)(1) - (0)(1) + (1) + 1 ]\mod 2 =\\
3 \mod 2 = 1
$$

A:

*

*I am a human being.

*You are a human being.

Therefore, I am you: right ? Well, as it turns out, the answer is no. It simply means that we belong to the same class. Likewise, $3\neq7$, but $3\equiv7\bmod4$.

A: Equal to means that they are the (exact) same thing. Congruent to means that they have some important property in common, in this case the same remainder when divided by the modulus. The relation, however, must be reflexive, symmetric, and transitive.

A: I (like most people, I believe) move freely between $=$ and $\equiv$ in the following sense.
Saying $a \equiv b \pmod{n}$ is the same as saying $a = b$ as elements of $ \mathbb Z / n\mathbb Z$. At least this is what I say to my students to keep in mind in case I jump around in my notation.

A: "Why" questions about notation can range into non-mathematical territory: Notation is not always perfectly logical or consistent.
This isn't an explanatory answer, but an extended comment about writing
$$
a \equiv b \pmod{c}
\tag{1}
$$
versus
$$
a \bmod{c} = b \bmod{c}.
\tag{2}
$$
In (1), mod $c$ is grammatically an adverb, modifying the binary relation "is equivalent to". Consistency dictates writing something like
$$
a \equiv_{\bmod{c}} b\qquad\text{or}\qquad a \equiv_{c} b.
$$
I'm not a historian, but believe the widespread use of the notation (1) at the school level arose in the New Math era of the 1950s. (It's easy to imagine how this "afterthought" notation (mod $c$) would work psychologically for students raised on arithmetic drills involving integers. I haven't a shred of evidence, however, and will keep my speculations private.)
In (2), by contrast, mod $c$ functions grammatically as an adjective, modifying the symbols $a$ and $b$. This is a more sophisticated viewpoint: Instead of relating integers $a$ and $b$ (which are familiar to young students), (2) equates residue classes mod $c$. That's already one reason to avoid (2) in an introductory setting.
To give a completely different reason, writing "$a \bmod{c}$" to denote a residue class is clumsy. The generic equivalence class notation $[a]_{c}$ would be preferable, or even $[a]$ if the modulus $c$ were fixed during the discussion/computation. One does in fact see $[a] = [b]$ in introductory algebra at the university level.
Honestly, even square brackets are cumbersome. (They can also cause perplexing LaTeX errors when Cayley tables are typeset as arrays. Exercise: Why?) Between friends and in private, you might as well denote the residue class simply as "$a$" if the modulus is fixed, so that mod $7$ you have, e.g.,
$$
5^{2015} \equiv -(2^{2015})
  \equiv -(2^{3 \cdot 671 + 2})
  \equiv -4
  \equiv 3.
$$
Ideally: Mathematical notation conveys concepts concisely, precisely, and consistently across fields and disciplines.
In practice: Changing historical perspectives and notational habits, field-specific conventions and emphases, and computer typesetting capabilities influence the ways we express mathematics in writing. Even sub-specialities of pure mathematics may use mutually-incompatible notation, to say nothing of discussions between pure mathematicians and engineers (say).
The answer to the question at hand may be as banal as "(1) is more compact than (2)" or "that's just the way everyone writes it (in 2015)". The take-away message is: "Mathematical notation is not always logical or consistent, and making notation consistent is much harder than it might first appear."
Answer to Exercise:

 If a square-bracketed expression follows a newline command \\ with only white space in between, LaTeX reads the expression as an optional argument, expecting a length.

A: We could have $-1 \bmod 2=-1$ and $1\bmod 2=1$, so $1\neq -1$, but nevertheless we have $1\equiv -1 \bmod 2$. So the equality $a\bmod c=b\bmod c$ is not clear, because it depends of the choice of a residue system.

A: The $a$ in the expression
$$a \equiv b \pmod c$$
and the thing you intuitively write as $a \mod c$ in the expression
$$a \bmod c = b \bmod c$$
are different kinds of things.
The symbol $a$ denotes an integer—a variable of type $\mathbb{Z}$, as a programmer might say, or an element of the ring $\mathbb{Z}$, as a mathematician might say.
The thing you denote by $a \bmod c$ is an integer modulo $c$—a variable of type $\mathbb{Z}/c\mathbb{Z}$, or an element of the ring $\mathbb{Z}/c\mathbb{Z}$. You can think of an integer modulo $c$ as an "hour" on a "$c$-hour clock," as described at the link above.
There's a natural way to turn an integer $n$ into an integer modulo $c$: you put the clock hand at noon, and then tick it forward $n$ hours. The hour you end up at is the one you call $n \mod c$. A more common notation for it is $[n]_c$, which can be abbreviated to just $[n]$ if it's clear that you're working on a $c$-hour clock.
Saying that the integers $a$ and $b$ are congruent modulo $c$, written
$$a \equiv b \pmod c,$$
is the same as saying that the hours $[a]_c$ and $[b]_c$ are equal, written
$$[a]_c = [b]_c.$$
In fact, this is how many people define congruence. You should be able to convince yourself, if you think about it long enough, that the hours $[a]_c$ and $[b]_c$ are equal if and only if the integers $a$ and $b$ have the same remainder when divided by $c$, which is another common definition of congruence modulo $c$.

A: I prefer to use the congruence exclusively (I view the remainder operation as a source of headache even though I realize that it is a necessary evil in computing).
But I use both equal ($=$) and congruent to ($\equiv$) signs together when processing a lengthy calculation in modular arithmetic. My freshman algebra students quickly catch on with my calculations like
$$
12^{3004}\equiv5^{3004}=5^{3000}\cdot 5^4=(5^6)^{500}\cdot 5^4\equiv 1^{500}\cdot5^4=25^2\equiv4^2=16\equiv2\pmod7.
$$
IOW, I use $=$ when there is an equality of integers between the steps, and $\equiv$ when I mean a congruence. The power of laws obeyed by congruences is apparent. Checking/following the progress of the calculation is easier this way. Of course, using $\equiv$ all the way is correct also. The $\equiv$ is there as a reminder that in this step we do something that only results in a congruence.
As the students become acquainted with the language of residue class rings, I gradually stop making the distinction between $=$ and $\equiv$ as well as, clarity of context permitting, the distinction between $n$ and $\overline{n}$.
Thinking about what that would look like when done by somebody who is only familiar with binary mod makes me shudder.

A: It depends on how you define your notation. The standard definition of congruence is $a \equiv b \pmod c$ if and only if $c \mid (b-a)$. The standalone expression $b \pmod c$ is undefined, hence not equal to anything.
On the other hand, some people like to write "$b \bmod c$" to stand for the least nonnegative number $d$ that satisfies $d \equiv b \pmod c$. If you adopt this notation then it is true that $a \equiv b \pmod c$ if and only if $(a \bmod c) = (b \bmod c)$.

A: Typically $=$ is used to denote that two objects are equivalent in every single context.  It is usually a primitive in logic, defined by textual replacement.
Other symbols, for example $\equiv$, are used for context sensitive equivalence.  $9$ is equal to $4$ in the context of $\pmod 5$.  Two binary trees may be equivalent in terms of their shape, but not where they are located in memory.  A husband and wife may be equivalent for the sake of tax purposes, but not for their respective expectations of each other.

A: In more advanced math, you will find number systems where it is not possible (or possible, but not wise) to define $a\mod c$ in an obvious way, while you will be able to write it as $a\equiv b\pmod{c}$.
There is an additional problem with $a\mod c = b\mod c$, which is that it allows for $a\mod c = b\mod d$. But this is hardly ever useful.
There are ways to write it as equality, but it is pedagogically useful to become comfortable with congruence as an instance equivalence relation.

A: I don't see any problem in writing $a\bmod n = b\bmod n$ as long as one is familiar what it means.
Even "worse" is when dealing with decimal system, we write, for example, $1=0.\dot9$ even though they are not the same series - they merely converge to the same real number.
Now, to the point. We start with ring $\mathbb Z$ (i.e. a structure consisting of integers with familiar addition and multiplication) and fix some natural $n$. Then we define equivalence relation $\equiv$ such that $$ a\equiv b \iff n|b-a$$ Having the fact that one can form quotient set of equivalence classes with respect to $\equiv$, using the properties of $\mathbb Z$ (namely that multiples of $n$ form an ideal) it follows that the quotient set $\mathbb Z/\equiv$ is actually a ring itself and then we use more familiar notation $\mathbb Z/n\mathbb Z$. Very importantly, we get a surjective function $\pi:\mathbb Z\to\mathbb Z/n\mathbb Z$ that sends any $a$ to it's equivalence class $[a]$
satisfying $$\pi(a+b) = \pi(a) + \pi(b),\ \pi(ab) = \pi(a)\pi(b)\quad \text{(i.e. $\pi$ is a ring homomorphism)}$$ So, when we write $a \equiv b\ \pmod n$ we mean that $a$ and $b$ belong to the same equivalence class (which just means that they give the same residue when divided by $n$ in this context) and consequently $\pi(a) = \pi(b)$. We might as well write $\operatorname{mod} n$ instead of $\pi$ and apply convention $a\bmod n = (\operatorname{mod}\ n)(a)$.
Why don't we do it? Because it is tedious to write down calculations that way.
One usual way of writing down calculations is to write $\overline 1,\ \overline 2,\ldots$ for congruence classes when having fixed $n$. For example $\overline 1 = \overline 3$ in $\mathbb Z/2\mathbb Z$, instead of $1\equiv 3\pmod 2$. I wouldn't have problem even if one would write $1=3$ as long as it is clear that these merely represent same elements of the ring $\mathbb Z/2\mathbb Z$, and not equality of integers, just as $1 = 0.\dot 9$ as real numbers, but not as series.
Long story short, how you write depends on the context and most important thing is that it is not ambiguous to the reader.

A: Relating to @Omnomnomnom's answer, I think there is a subtle difference in the mathematical and computer science perspectives to this.
From a computer science perspective, a mod b looks a lot like a % b, which is a distinct operation with a single answer (try typing 7 % 3 into your Python interpreter, and you will always get the same answer).
I generally think of congruency in the following manner:

*

*Congruency: small mod medium ≡ big if and only if small ≡ big mod medium

*Equality: big mod medium = small (or in Python, big % medium == small), but the opposite direction does not hold (small mod medium ≠ big).
My experience with this topic is limited to single dimensional modular integer arithmetic used in cryptography, so I cannot speak to any subtleties that may arise in other contexts.


text:
Q: Run npm update in docker without using the cache on that specific update Background:

*

*I'm writing code in node.js, using npm and docker. I'm trying to get my docker file to use cache when I build it so it doesn't take too long.

*We have a "common" repo that we use to keep logic that is used in a variety of repositories and this gets propagated is npm packages.

The problem:
I want the docker file NOT use the cache on my "common" package.
Docker file:
FROM node:12-alpine as X

RUN npm i npm@latest -g
RUN mkdir /app && chown node:node /app
WORKDIR /app

RUN apk add --no-cache python3 make g++ tini \
    && apk add --update tzdata

USER node
COPY package*.json ./
COPY .npmrc .npmrc
RUN npm install --no-optional && npm cache clean --force
ENV PATH /app/node_modules/.bin:$PATH
COPY . .

package.json has this line:
"dependencies": {
  "@myorg/myorg-common-repo": "~1.0.13",

I have tried adding these lines in a variety of places and nothing seems to work:

*

*RUN npm uninstall @myorg/myorg-common-repo && npm install @myorg/myorg-common-repo

*RUN npm update @myorg/myorg-common-repo --force

Any ideas on how I can get docker to build and not use the cache on @myorg/myorg-common-repo ?

A: So I finally managed to solve this using this answer:
What we want to do is invalidate the cache for a specific block in the Docker file and then run our update command. This is done by adding a build argument to the command (CLI or Makefile) like so:
docker-compose -f docker-compose-dev.yml build --build-arg CACHEBUST=0

And then Adding this additional block to the Docker file:
ARG CACHEBUST=1
USER node
RUN npm update @myorg/myorg-common-repo

This does what we want.
The ARG CACHEBUST=1 invalidates the cache and the npm update command runs without it.


text:
Q: Sencha ExtJS - Display combo picker always on top of the control So I have this specific combo that I need to display its picker always on top (just as it behaves when it is too near to the bottom of the page). As shown here:

I tried with the pickerAlign config but I wasn't able to put it on top of my control. Thanks!

A: Found the answer, this will do:
pickerAlign : 'b-t'

Anyway, it displays the same amount of items it would as if there was the same space on top of it that the amount beneath it.


text:
Q: Unable to start mongodb-org 5 on ubuntu server in virtualbox after installation - Core dump I followed the instructions from the official documentation, but when checking the status of the process it gives me the following error:
imperium@imperium:~$ sudo systemctl status mongod.service
● mongod.service - MongoDB Database Server
     Loaded: loaded (/lib/systemd/system/mongod.service; disabled; vendor preset: enabled)
     Active: failed (Result: core-dump) since Wed 2021-11-03 18:58:22 UTC; 16min ago
       Docs: https://docs.mongodb.org/manual
    Process: 2405 ExecStart=/usr/bin/mongod --config /etc/mongod.conf (code=dumped, signal=ILL)
   Main PID: 2405 (code=dumped, signal=ILL)

nov 03 18:58:22 imperium systemd[1]: Started MongoDB Database Server.
nov 03 18:58:22 imperium systemd[1]: mongod.service: Main process exited, code=dumped, status=4/ILL
nov 03 18:58:22 imperium systemd[1]: mongod.service: Failed with result 'core-dump'.
imperium@imperium:~$

It is a clean install of ubuntu server. How can I fix this?
What i tried
sudo chown -R mongodb:mongodg /var/log/mongodb
sudo chown -R mongodb:mongodg /var/lib/mongodb
sudo chmod -R 755 /var/lib/mongodb
sudo chmod -R 755 /var/log/mongodb

sudo systemctl restart mongod.service

Same result.

sudo mongod --repair --dbpath /var/lib/mongod
> Illegal instruction

imperium@imperium:~$ dmesg | grep mong
[   31.638118] traps: mongod[627] trap invalid opcode ip:565454367a9a sp:7ffc8668ba80 error:0 in mongod[565450400000+5090000]

A: I found this answer:

MongoDB 5.0 requires a Sandy Bridge or newer CPU. Get a newer processor or use an older version of MongoDB.
https://jira.mongodb.org/browse/SERVER-54407

Restored my VM to a snapshot prior to a Mongo 5 installation and install mongodb 4.4 and it now works.


text:
Q: terminating the password prompt during scp in perl after certain amount of time I am trying exit the password input prompt  during a scp command in the perl script after certain amount time for the server which do not have the ssh public key. In this script, I am using the back-tick for copying of file from one server to another, but the script get stuck on the password prompt and do not exit out even after the assigned timeout.
my $test       = '';
my $exit_value = '';
eval {
          my $timeout = 2;
          local $SIG{ALRM} = sub { die "timeout\n" };
          alarm($timeout);
          $test       = `scp foo.txt bar@baz:/`;
          $exit_value = $? >> 8;
          alarm(0);
     }

if ($@) {
    print "Time out";
}

Is there any way handle the above scenario ?

A: You should set BatchMode when calling from an non interactive session to disable the password prompt altogether.
$test = `scp -o BatchMode=yes foo.txt bar@baz:/`;

See below
 BatchMode
         If set to ``yes'', passphrase/password querying will be disabled.
         This option is useful in scripts and other batch jobs where no
         user is present to supply the password.  The argument must be
         ``yes'' or ``no''.  The default is ``no''.

A: Also you can use the following parameter to disable the host_key checking using:-

$test = scp -o BatchMode=yes -o StrictHostKeyChecking=no foo.txt bar@baz:/;

A: I made the use of IPC::Run module to achieve the above object, to terminate the password prompt after certain time.
So my current code looks like this
my $in  = '';
my $out = '';
my $err = '';
my @cmd = ('scp' , 'foo.txt' , 'bar@baz:/');

eval {
        run \@cmd, \$in, \$out, \$err,IPC::Run::timeout(5)
            or die "SSH Error: $? $err\n";
    };
if ($@) {
   print "TimeOut";
}


text:
Q: Geometric realization of simplicial sets I wonder if we can construct some different geometric realizations?
In the current construction, $n$-cells of geometric realization are in one-to-one correspondence with non-degenerate simplices in $X_n$, which is due to the equivalence relation given by $$(f^*(x), t)\sim (x, f_*(t)), x\in X_n, t\in \Delta^m$$ for every
morphism $f : [m]\to [n]$ in $\Delta$
(Recall the geometric realization is defined by $|X_*|= (\bigsqcup_{n\ge0} X_n\times \Delta^n)/\sim$).
I think if we drop the equivalence relation, we can get a new CW-complex, where $n$-cells of construction are in one-to-one correspondence with simplices in $X_n$.(Am I right? I am not very sure, but it seems that works)
Also, is there a specific reason/motivation for the current construction of the geometric realization? Why do we require $n$-cells of geometric realization are in one-to-one correspondence with non-degenerate simplices in $X_n$?

A: The geometric realization of a simplicial set is only unique up to (topological) isomorphism. There is no overriding reason to define as you do above. The definition of geometric realization you give is chosen firstly so that
1) It is functorial in simplicial maps $X_\bullet\rightarrow Y_\bullet$.
2) It defines a left adjoint to the singular set functor $Top\xrightarrow{S}sSet$ definedby $SY_n=Map(\Delta^n,Y)$.
and also so that
3) For 'nice' classes of simplicial sets it will take values in 'nice' classes of topological spaces.
In particular the geometric realisation $|-|$ depends on the choice of the standard topological simplices $\Delta^n$, the definition of the singular set functor $S$ and how we want it to interact with certain classes of simplicial sets and spaces. It is "defined" as above by many texts simply because it is the most convenient possible definition.
Indeed a similar definition is that of the fat geometric realization, given by
$||X_\bullet||=\bigsqcup_{n\geq 0} X_n\times \Delta^n /\left[(d_ix,t)\sim (x,d^it)\right]$
In particular the fat geometric realization does not throw away the degenerate simplices. There is a natural map
$\alpha:||X_\bullet||\rightarrow |X_\bullet|$,
and if $X_\bullet$ is good, that is, if each degeneracy map $s_i:X_{n-1}\rightarrow  X_n$ for each $n$ is a closed cofibration, then $\alpha$ is a homotopy equivalence. It has other nice properties. If $f_\bullet:X_\bullet\rightarrow Y_\bullet$ is a levelwise homotopy equivalence then $||f_\bullet||$ is a homotopy equivalence whilse $|f|$ need not be. See for example Segal's paper 'Categories and Cohomology theories'.


text:
Q: Debugging pre-processed code I am trying to step through a C project (fossil-scm) that has a 2-phase pre-processing stage.
First there is a custom built pre-processing program, that goes through the files and fixes certain project-specific macros, creates the include headers, and a few other things. It creates a bunch of .c and .h files. The result is then compiled as usual, passing through the "regular" pre-processor.
I took the result from the first part and created a visual-studio project from it. When I tried to debug it, it was skipping my breakpoints. I found that every file begins with a
#line 1 "src/original_filename.c"

I can comment out this line and get debugging to work, but I would rather use this line to get debugging in the original context.
So...
How can I set it up so that it compiles the processed files, but uses the #line directives to give me debugging capabilities in the original files?
I tried just placing the src directory next to the files, and it works if I start the program by pressing F10, but I don't know how to get the original files into the project explorer so that I can easily open them and place breakpoints without the compiler trying to compile them.

A: From my experiments with Visual Studio 2012 (2010 might behave similarly), setting breakpoints in the "original" source files (source files referenced by #line directives in the "real" source files) only works correctly if:
1) I add the "original" source files to the project. (E.g. Add -> Existing Item...)
2) I exclude the "original" source files from build. (E.g. Right-Click -> Properties -> Exclude from Build = Yes)
A bit of a late answer, but I hope this helps someone.


text:
Q: how to quit omxplayer without using terminal? I have made an application launcher using Tkinter for the raspberry pi.I made the application launcher to start automatically after x loads by placing
@/usr/bin/sudo /home/pi/myscript.py inside /etc/xdg/lxsession/LXDE-pi/autostart.
And for launching applications from within the python script i'm using the subprocess module.The code for the same is:
subprocess.Popen('python /home/pi/script.py')
subprocess.Popen('scratch')
subprocess.Popen('omxplayer -o local /home/pi/video.mp4',shell=True)

Now what is happening is that all the processes are running fine i.e all the applications gets launched perfectly and when i'm closing the apps(using the close button or alt+f4) that is also working fine.
But the omxplayer seems to be in full screen mode(though its not covering my entire screen).There is no close button there.Some of the documentations say that there are shortcut keys like q for quit but that also doesn't work.The alt+f4 is also not working and moreover since i'm launching it from within my python script(application launcher) I cannot use the terminal to quit the same.
But when I launch the same video from within the terminal both q and alt+f4 is working (i.e I can use both of them to quit omxplayer).
So can anyone explain why this is happening and how can enable the quit thing for the omxplayer while launching it from within the python script?

A: omxPlayer doesn't run on your Xwindows. it uses GPU to render itself onto directly in your display. as it doesn't run on Xwindows, it doesn't need or have any close button. moreover, when you start this player it becomes the active window of that application from where you launched it.
currently i am using another parallel application that executes command and run this

ps -ef | grep /usr/bin/omxplayer | grep -v grep | awk '{print $2}' | xargs kill -9

command to quit this. i am now working for some better solutions.

A: I have the same problem, omxplayer tends to stay alive after playing a sound file. I found out omxplayer tends to have problems with certain TTYs. There is the option --no-keys which seems to make omxplayer quit after playing the file. Example:
omxplayer --no-keys your_sound_file.mp3


text:
Q: Formating display for a Document/Form library I created a SharePoint Forms Library. Every entry is saved as an XML file.
The form contains around 200 columns in the form library. The requirement is, when a user changes any column value in the from the info-path form that value should change color in the document library so that it can be highlighted.
I can change the full row using conditional formatting (SharePoint Designer) but I need to change that value cell or the string color itself.

A: The first thing that you must do is to turn on version tracking, see; http://office.microsoft.com/en-us/access-help/track-and-view-version-information-for-sharepoint-list-items-HA010209305.aspx
This will allow you to know when something has changed.
The next bit is a bit more difficult, you need to write some client side script, that gets the version information, checks what was changed last, and then highlights it. This may not be possible.
It is easier just to ask the users to select "view versions" if they are interested in what has changed.


text:
Q: NoMethodError:undefined method `symbolize_keys' in rspec test Here is the error for update in rspec:
  4) CustomersController GET customer page 'update' should be successful
     Failure/Error: post 'update', customer
     NoMethodError:
       undefined method `symbolize_keys' for "1":String
     # ./spec/controllers/customers_controller_spec.rb:38:in `block (3 levels) in <top (required)>'

The rspec code:
it "'update' should be successful" do

  customer = Factory(:customer)
  post 'update', customer
  response.should be_success
end

The update in customers controller:
  def update
    @customer = Customer.find(params[:id])
    if @customer.update_attributes(params[:customer], :as => :roles_new_update)
      if @customer.changed
        @message = 'The following info have been changed\n' + @customer.changes.to_s
        @subject ='Customer info was changed BY' + session[:user_name]
        notify_all_in_sales_eng(@message,@subject)
      end

      redirect_to session[('page'+session[:page_step].to_s).to_sym], :notice => 'Customer was updated successfaully!'
    else
      render 'edit', :notice => 'Customer was not updated!'
    end
  end

Any thoughts about the error? Thanks.

A: I will not enter into details on RSpec, but I just met the same error and this is how I would correct it for your code:
it "'update' should be successful" do
  customer = Factory(:customer)
  post 'update', :id => customer.id
  response.should be_success
end

I think you can't provide your object directly to the post method, you must pass it's id as in a Hash instead.
(Please note too that this code assumes your customer exists in the test database, so your Factory must create it.)


text:
Q: Jupyter notebook not showing output on vs code mac I installed the Jupyter Notebook to VS Code, but when I try to run anything it does not show me an output. Does anyone know why? And how I can fix this?

A: It looks like you aren't connected to any Jupyter servers, so the cells are actually waiting to be run. Please see Visual Studio Docs on how to set up:

Setting up your environment
To work with Python in Jupyter Notebooks, you must activate an Anaconda environment in VS Code, or another Python environment in which you've installed the Jupyter package. To select an environment, use the Python: Select Interpreter command from the Command Palette (Ctrl+Shift+P).
Once the appropriate environment is activated, you can create and open a Jupyter Notebook, connect to a remote Jupyter server for running code cells, and export a Jupyter Notebook as a Python file.

Once a cell is ran properly, there should be a green tick under the cell like below:

A: If you configured a virtual environment, you have to select it again with (Ctrl+Shift+P) after your reboot your machine.


text:
Q: Can I access two different dropboxes from one computer? We have a situation where a worker is using a Dropbox shared with many people in different companies to work on a collaborative project. She cannot figure out how to use our company's Dropbox now, to work on a different project. She needs access to both Dropboxes, at different times. We're using Windows 7. Thank you for any help.

A: The steps to setup two Dropbox accounts on the same machine are as follows:

*

*Sign up, and setup dropbox for your business account

*Create an Automator app and add: bash
HOME=$HOME/Dropbox-personal /Applications/Dropbox.app/Contents/MacOS/Dropbox &

*

*Where Dropbox-personal is the location of your personal Dropbox folder

*Save the script into your personal dropbox folder (for future use)

*OpenSystem Preferences > User Accounts, go to your login, and select Login Items

*

*Add your application to the list of programs to launch at login

You can also change the app icons in your menu bar so that you can differentiate between the two accounts.
For more detailed instructions see the original post

A: you can make use of the runas feature of windows.
for example you have 2 users on your windows, user1 and user2, user1 is the user you work with.
here's what you do.
1. login to user1, install dropbox
2. login to user2, install dropbox
3. back to user1, create a bat file with the following content: runas /user:user2 C:\Users\User2\AppData\Roaming\Dropbox\bin\Dropbox.exe
4. run dropbox on user1 as usual. then run this bat file, you'll be asked to type password of user2. then you have a second dropbox!

A: Here is a tool that you can use.
http://www.bustatech.com/run-multiple-dropbox-on-your-pc-at-the-same-time/


text:
Q: Is there a way to modify a class in a class method in Python? I wanted to do something like setattr to a class in class method in Python, but the class doesn't exist so I basically get:
NameError: global name 'ClassName' is not defined

Is there a way for a class method to modify the class? Something like this but that actually works:
class ClassName(object):
    def HocusPocus(name):
        setattr(ClassName, name, name)

    HocusPocus("blah")
    HocusPocus("bleh")

A: Class methods get the class passed as the first argument:
class Bla(object):
    @classmethod
    def cm(cls,value):
        cls.storedValue = value

Bla.cm("Hello")

print Bla.storedValue # prints "Hello"

Edit: I think I understand your problem now. If I get it correctly, all you want to do is this:
class Bla(object):
    storedValue = "Hello again"

print Bla.storedValue # prints "Hello again"

Class creation in Python (pretty much) simply means:

*

*Create a fresh namespace.

*Run the code that you find inside the class body using this namespace

*Put everything that's left in the namespace into the class as class attributes.

Since storedValue is in the namespace after step 2, it's turned into a class attribute in step 3.

A: Another way you could do this would be to use a class decorator, though these are only available from Python 2.6 onwards IIRC.
Something like this:
def addattributes(cls):
    cls.foobar = 10
    return cls

@addattributes
class MyClass(object):
    pass

print MyClass.foobar

This kind of this most useful when you want to "decorate" a number of classes with some specific functionality / properties.  In your case, if you only want to do this once, you might just want to use class methods as previously shown.

A: While many good suggestions have been advanced, the closest one can get to the originally requested code, that is:
class ClassName(object):
    def HocusPocus(name):
        setattr(ClassName, name, property(fget=..., fset=...))

    HocusPocus("blah")
    HocusPocus("bleh")

is this:
class ClassName(object):

    def HocusPocus(name):
        return property(fget=..., fset=...)

    blah = HocusPocus("blah")
    bleh = HocusPocus("bleh")

I'm assuming the mysterious ... redacted parts need access to name too (otherwise it's not necessary to pass it as an argument).
The point is that, within the class body, HocusPocus is still just a function (since the class object doesn't exist yet until the class body finishes executing, the body is essentially like a function body that's running in its local dict [without the namespace optimizations typically performed by the Python compiler on locals of a real function, but that only makes the semantics simpler!]) and in particular it can be called within that body, can return a value, that value can be assigned (to a local variable of the class body, which will become a class attribute at the end of the body's execution), etc.
If you don't want ClassName.HocusPocus hanging around later, when you're done executing it within the class body just add a del statement (e.g. as the last statement in the class body):
    del HocusPocus


text:
Q: JPARepository's findAll query on baseclass of @MappedSuperClass just returns entries of baseclass I have a JPA MappedSuperClass like this:
@MappedSuperclass
public abstract class Foo extends AbstractPersistable<Long> {
private Status status;
@ManyToOne(cascade=CascadeType.ALL)
private User owner;

And two subclasses inheriting from Foo, namely defined as follows:
@Entity
@Table(name="BARFOO")
@EqualsAndHashCode(callSuper=true)
@PrimaryKeyJoinColumn(name="id", referencedColumnName="id")
public @Data class Bar extends Foo {
  private String beer;

and
@Entity
@Table(name="BLUBFOO")
@EqualsAndHashCode(callSuper=true)
@PrimaryKeyJoinColumn(name="id", referencedColumnName="id")
public @Data class Blub extends Foo {
private String cider;

Now when I save some data in an Object of type Bar or Blub I expect a myRepository.findAll to actually return cider or beer AND both status and owner from the MappedSuperClass. Instead, it just returns cider or beer - the properties of the subclass.
Is there just an error in my reasoning or am I missing on anything completely?
This is my BarRepository:
public interface BarRepository extends JpaRepository<Bar, Long> {
}

And this is how findAll() in my BarService is "implemented":
@Inject
private BarRepository barRepository;
public Iterable<Bar> findAll() {
  return barRepository.findAll();
}

I also have both for my Blub subclass. Any hint is appreciated and when I missed on any best practice, I'd be glad if you put me on the right track again.