text:
Q: Did the Rebels know or suspect Vader himself would board the blockade runner? Episode IV begins with the Star Destroyer Devastator (Vader's flagship at the time) pursuing the Rebel blockade runner Tantive IV. The blockade runner is soon captured and boarded by Imperial stormtroopers and Vader himself.
Did the Rebels know or suspect Vader was on the Star Destroyer before he boarded the blockade runner? In other words, did they have any idea ahead of time that Vader would step through the breached door?

I'm not suggesting that the Rebels should have surrendered rather than stalled for time by resisting the Imperial boarding attempt. I'm just curious if they knew or suspected that they would have to resist Vader in addition to stormtroopers as the Imperials attempted to board the blockade runner.

A: Leia knew (and possibly the Tantive IV's command crew). It seems unlikely that rank and file soldiers would have been told.

And Leia knew, the moment the ship identified itself as the Devastator, there would be no escape.
It was Darth Vader's ship.
A New Hope: The Princess, the Scoundrel, and the Farm Boy


text: Q: snmp version 3 client android studio I want to use simple snmp get in android.I found the code for java and try to use it in android.I also attach snmp4j.jar file for android.But I got the NullPointer Exception and I don't get the output.If anybody have any idea or code for how to use snmp in android then please suggest me..

redpajama_set_name: RedPajamaStackExchange


text:
Q: Decoding passwords or some more sophisticated way to send passwords for users? I have a group of users. Everyone of them has the same username-password combination. There is the data encrypted (see code below) in my db. The question is, what is the best and the most secure way to handle the whole use case? I just want to send username - password combo in an email, same email to every user. Should I just decode the password or save the text password for that period than user has sent the email and delete textual password after that or have you any ideas for that?
There is not so priceless data in my software but still...
private Users hashPasswordBase64(Users currentUser) {

    try {
        MessageDigest md = MessageDigest.getInstance("SHA-256");
        String text = currentUser.getPassword();
        md.update(text.getBytes("UTF-8"));
        byte[] digest = md.digest();

        currentUser.setPassword(Base64.encode(digest));
    } catch (NoSuchAlgorithmException ex) {
        Logger.getLogger(UsersController.class.getName()).log(Level.SEVERE, null, ex);
    } catch (UnsupportedEncodingException ex) {
        Logger.getLogger(UsersController.class.getName()).log(Level.SEVERE, null, ex);
    }

A: Betaminos pretty much laid the guidlines.
What I recommend is storing the password server-side in an encoded format, and only decoding it whenever someone tries to log in as the person.
another option (assumming that it is a small-scale thing) would be to send an obfuscated password, with lots of spammed characters (example here: http://pastebin.com/hT1AVMUp) (and here: http://pastebin.com/9He1sk2m) and have them decode it client-side. it won't beat any humans, but it should make it harder on decoding programs.

A: I would recommend to decode the password on-the-fly, send the eMail, and dispose of the variable.
Storing the password only makes it easier for a trojan to retrieve it.
Besides that I would suggest to provide a password that needs to be changed by the user after the very first login. This way, the user would be able to choose password that is easy to memorize for him and you won't have any problems sending out the clear-text passwords because this become invalid after a single use.


text:
Q: NSMutableArray empty array error I am doing some operations in for loop with nsmutablearray' s data. But sometimes it work sometimes it gives me an error like 'array index 3 empty array' at this line :
else if (min>[[enyakinarray objectAtIndex:i] floatValue])

full code :
for (int i=0; i<[ws3.CustomerID count]; i++) {

    //radian hesaplaması
    float total = [first floatValue];
    float theta = total * M_PI/180;
    float total2 = [second floatValue];
    float theta2 = total2 * M_PI/180;
    float total3 = [[ws3.Latitude objectAtIndex: i]  floatValue];
    float theta3 = total3 * M_PI/180;
    float total4 = [[ws3.Longitude objectAtIndex: i] floatValue];
    float theta4 = total4 * M_PI/180;

     distance = 6371 * acos(cos(theta) * cos(theta3)
                           * cos(theta4 - theta2)
                           + sin(theta) * sin( theta3)) ;

    NSLog(@"xxxxx %f",distance);

    num = [NSNumber numberWithFloat:distance];
    [enyakinarray  addObject:num];
    NSLog(@"asasasas %@",enyakinarray);

}

float min;
NSString *s;
for (int i=0; i<[enyakinarray count]; i++) {
   if(i==0)
   {
    min = [[enyakinarray objectAtIndex:i] floatValue];
    s= [ws3.CustomerName objectAtIndex:i];
   }
   else if (min>[[enyakinarray objectAtIndex:i] floatValue])
            {
            min= [[enyakinarray objectAtIndex:i] floatValue];
            s = [ws3.CustomerName objectAtIndex:i];
            }
    enyakinfirma.text=s;
   }

How can I solve this?

A: This is strange but should be really easy to debug. Just write
NSLog("First array: %@", enyakinarray)
NSLog(@"Second array: %@", ws3.CustomerName)
NSLog(@"Second array: %@", ws3.CustomerID)

before your for and you should see the problem very quickly. Maybe you are changing the array contents somewhere between its creation and usage?
However, I see a design problem there. Your code uses several separate arrays CustomerName, CustomerID and enyakinarray Latitude and Longitude which contain values of a single entity Customer (name, id, latitude, longitude and distance). Maybe you could create an object Customer with these properties and mantain only one array of customers? Good OOP design helps you prevent this type of errors :)
And you can merge the two cycles into one:

float minDistance = FLT_MAX;
NSUInteger customerIndex = 0;

for (NSUInteger i = 0; i < [ws3.CustomerID count]; i++) {
    /* distance calculation code ... */

    float distance = 6371 * acos(cos(theta) * cos(theta3)
                           * cos(theta4 - theta2)
                           + sin(theta) * sin(theta3));

    if (distance < minDistance) {
        minDistance = distance;
        customerIndex = i;
    }
}

enyakinfirma.text = [ws3.CustomerName objectAtIndex:customerIndex];


text:
Q: PHP - recording errors What is the best way to record errors experienced by the user?
My initial thought was to make a function that recorded the error with a unique number and maybe a dump of the variables into a record on the database.
Is there a better approach? Should I use a text file log instead?

A: How about overriding the default PHP errorhandler?
This site should give some basic information: http://www.php.net/manual/en/function.set-error-handler.php and the first comment on http://www.php.net/manual/en/function.set-exception-handler.php
You might also want to store database errors, perhaps some kind of custom function that allows you to use code like:
<?php
$objQueryResult = mysql_query("query here") or some_kind_of_function_here();
?>

You might want to store the recorded errors in a file, which is outside your public html root folder, to make sure people can't access it by accident.
I would also assume, you'd want to store a complete stacktrace in such a file, because then you can actually debug the problem.
When overriding the default errorhandlers, please note you don't forget to send a nice message to the user (and exit the script, when needed).
I would recommend storing:

*

*$_POST

*$_GET

*A complete dump of
debug_print_backtrace()

*Possibly the SQL that triggered this?

I would suggest you to use debug_print_backtrace() to make sure you get a summary of data. The debug_backtrace() function gives about the same information, but it can sometimes just give you too much information.
The code you could use to catch backtraces:
<?php
ob_start();
debug_print_backtrace();
$trace = ob_get_contents();
ob_end_clean();
?>

To store this, you could use a plain text output, if you don't get too much errors, otherwise perhaps use something like sqlite? - Just don't use the same SQL connection to store the errors, as that might trigger more problems, if you're having webserver to SQL connection errors.

A: Well, at least writing to text files on the local system should be less error prone, thus allowing you to catch DB errors too :)
I would prefer to write a decent dump of the current state to a simple log file. In addition to your "own" state (i.e. your application's variables and objects), you might consider doing a phpinfo() to get inspiration as to which environment and request variables to include.

A: PEAR::Log is handy for this kind of logging. e.g.

$logger->alert("your message");
$logger->warning("your message");
$logger->notice("your message");

etc.
You can log to a file or to a database, I wrote a PDO enabled sqlite extension , pretty simple.
These are handy to put into exception handling code too.
PEAR::Log
Records: id, logtime, identity, severity 1-7( ie "Alert"), and your message.

A: I think @Icheb's answer covers it all.
I have tried something new this year in a project that I thought I'd share.
For a PHP based content aggregation / distribution service, an application that runs quietly in the background on some server and you tend to forget, we needed an error reporting system that makes sure we notice errors.
Every error that occurs has an Error ID that is specified in the code:
$success = mysql_query(this_and_that);
if (!$success) log_error ("Failed Query: ".mysql_error(), "MYSQL_123");

Errors get logged in a file, but more importantly sent out by mail to the administrator, together with a full backtrace and variable dump.
To avoid flooding with mails - the service has tens of thousands of users on a good day - error mails  get sent out only once every x hours for each error code. When an error of the same code occurs twice within that timespan, no additional mail will be sent. It means that every kind of error gets recorded, but you don't get killed by error messages when it's something that happens to hundreds or thousands of users.
This is fairly easy to implement; the art is getting the error IDs right. You can, for example, give every failed mySQL query in your system the same generic "MYSQL" Error ID. In most cases, that will be too generic and block too much. If you give each mySQL query a unique error ID, you might get flowed with mails and the filtering effect is gone. But wWhen grouped intelligently, this can be a very good setup.

A: From the usability point of view, the user should not Ever experience errors.
Depending on the error you should make different strategies:

*

*non catchable errors or difficult to catch from PHP, read the logs for each application

*

*Apache

*MySQL and DB errors, transactions

*prepare php with "site being updated" or error controllers for emergencies.

*PHP errors

*

*these should be detected through Exceptions

*silenced but not forgotten, don't try to fix them on the fly

*log them and treat them

*interface errors

*

*an advice: allow user to submit suggestions or bugs

I know this does't cover all, is only an addendum to the others have suggested.


text:
Q: Difference between ER diagram and Class diagram I have been given a description and need to draw ER diagram and Class diagram for the description.
Now I am having issue with understanding the differences between these 2 diagrams.
When I draw the diagrams entities of ER diagram becomes classes. I am not sure whether I am in right track.
Please explain me what is the difference and similarities of these two?

A: ER diagram:

*

*what is contained in the database like the table, relationship, primary key, foreign key, what is a weak entity,

Class diagram:

*

*what is contained in class like attributes, types of attributes, method, the return type of methods, method's parameter, a relationship of a class(inheritance, aggregation etc.). plus there are also about an interface, abstract class.

ORM(object relation mapping):

*

*there are ORM tools available in any language.

*where you have to create only an ER diagram from that we have to create only class any based on a class it will automatically create a database.

*so we don't need to create a class diagram.

A: When you think of Class Diagrams, you are thinking about the organization of behaviors or simply functions. In example, calculate costs function using state tax information. Then you may have different classes representing different calculation functions (See strategy pattern from GoF design patterns).
When you think about an ER diagram, you are thinking about the rules around the existence and relationship of data that will be stored. A user account must have a username and a bank account can have only one primary user account.
To sum up, with class diagrams you think about the organization of behaviors/functions, while with ER diagrams you think about the organization of data assets. The two definitely relate when building an entire application, but have two different perspectives in the design of the application being built.
Hope that explanation helps!

A: There are many ways to tell the difference between ERD and Class diagram.
For instance, ERD, otherwise known as Entity Relationship Diagram, only portrays systemic features.
On the other hand, Class Diagram displays the most vital sections of a system, the systemic and behavioural features.
In Unified Modelling Language, UML, features are shown as unencrypted text in 'the class rectangle box'.
However, in an Entity Relationship Diagram, the features are 'oval linked to the entity type'.
ER Diagram has relationships which are more complex than Class diagram and are more complicated to be deciphered by humans.
ER Diagram contrasts to Class diagram since it 'maps into tables in database' whereas Class diagram maps into actual objects.
Another distinction is that Class diagram has some relationships which are not implied and modelled in Entity Relationship Diagram.
The main segments of Entity Relationship Diagrams consist of entities, relationships and attributes whilst classes, relationships and attributes are the segments of Class Diagrams.
Hope this helps anyone!

A: From DifferenceBetween.com:

ER diagrams represent the abstract representation of the data model,
  while class diagrams represent the static structure and behavior of
  the proposed system. Main building blocks of ER diagrams are entities,
  relationships and attributes but the main building blocks of class
  diagrams are classes, relationships and attributes. Class diagram are
  more likely to map in to real-world objects, while ER diagrams most
  often map in to the tables in the database. Usually, relationships
  found in ER diagrams are more difficult to understand for humans than
  relationships in class diagrams.

A: one of the differences between ERD and class diagram is
in ERD we can define an intermediate entity, for example, we want to define a "book shopping" website.
(like the below image)

See we should define "Warehouse_Book" for the "ERD diagram" and implement the DB structure but in "class diagram we don't have any class like this.


text:
Q: SQL Server : query with incorrect SUM result My SQL Server query is supposed to get a count of each customer's number of orders, and the SUM of their reward points. For most customers the result is accurate (most people only have one or two orders). For a few people, the result is wildly off.
Here's the original query:
SELECT
    c.email,
    c.lastlogindate,
    c.custenabled,
    c.maillist,
    d.GroupName,
    COUNT(o.orderid) AS orders,
    SUM(r.points) AS total_points
FROM
    ((customers c
      LEFT JOIN orders o ON (c.contactid = o.ocustomerid AND o.ostep = 'step 5')
     )
     LEFT JOIN discount_group d ON c.discount = d.id
    )
LEFT JOIN
    customer_rewards r ON r.contactid = c.contactid
WHERE
    c.last_update > '2014-02-01'
OR c.lastlogindate > '2014-02-01'
GROUP BY
    c.email, c.custenabled, c.maillist, c.lastlogindate, d.GroupName;

For one example, customerid 1234 has placed 21 orders, totaling 2724 points. This will report that he has placed 441 orders (21 * 21) valued at 57204 points (2724 * 21). The raw data is fine, but each order row is being duplicated by the amount of orders they placed (but not for most customers...)
If I change the query to this:
SELECT
    o.orderid,
    c.email,
    COUNT(o.orderid) AS orders,
    SUM(r.points) AS total_points
FROM
    ((customers c
      INNER JOIN orders o ON (c.contactid = o.ocustomerid AND o.ostep = 'step 5')
     )
    )
INNER JOIN
    customer_rewards r ON r.contactid = c.contactid
WHERE
    c.last_update > '2014-02-01'
OR c.lastlogindate > '2014-02-01'
GROUP BY
    c.email, o.orderid;

The aggregate functions are calculated properly, but it will display one result for each order placed. So it will show "Customer 1234/21 orders/2724 points", 21 times.
I did remove the 'discount_group' join in the second query, but that was just to make it easier to read and change. That hasn't had any effect on results.

A: Here is a solution using common table expressions to aggregate your results.
Note: this will not show customers that have 0 orders or 0 rewards points.  If you would like to show these, change the INNER JOINs to LEFT JOINs
WITH cteOrders AS
(
    SELECT o.ocustomerid, orderCount = count(*)
    FROM orders o
    WHERE o.ostep = 'step 5'
    GROUP BY o.ocustomerid
)
, cteRewards as
(
    SELECT cr.contactid, total_points = SUM(cr.points)
    FROM customer_rewards cr
    GROUP BY cr.contactid
)
SELECT
    c.email,
    o.orderCount as orders,
    r.total_points
FROM
    customers c
    INNER JOIN cteOrders o ON c.contactid = o.ocustomerid
    INNER JOIN cteRewards r ON r.contactid = c.contactid
WHERE
    c.last_update > '2014-02-01'
OR c.lastlogindate > '2014-02-01'
;

Or using subqueries:
SELECT
    c.email,
    o.orderCount as orders,
    r.total_points
FROM
    customers c
    INNER JOIN
    (
    SELECT o.ocustomerid, orderCount = count(*)
    FROM orders o
    WHERE o.ostep = 'step 5'
    GROUP BY o.ocustomerid
    ) o ON c.contactid = o.ocustomerid
    INNER JOIN
    (
    SELECT cr.contactid, total_points = SUM(cr.points)
    FROM customer_rewards cr
    GROUP BY cr.contactid
    ) r ON r.contactid = c.contactid
WHERE
    c.last_update > '2014-02-01'
OR c.lastlogindate > '2014-02-01'
;


text:
Q: Scala 2.8 handles Boolean and java.lang.Boolean properly? Consider the following:
scala> val a:java.lang.Boolean = true
a: java.lang.Boolean = true

scala> val b = true
b: Boolean = true

scala> a == b
res4: Boolean = true

scala> b == a
<console>:8: warning: comparing values of types Boolean
and java.lang.Boolean using `==' will always yield false
       b == a
         ^
res5: Boolean = true

The warning says that it will yield false but it yields true.
Scala 2.8.

A: A bit of source code control archaeology shows that handling of those warnings were improved after 2.8.1. Here is the annotated revisions to the unit tests for those warnings.
https://lampsvn.epfl.ch/trac/scala/browser/scala/trunk/test/files/neg/checksensible.scala?annotate=blame&rev=25638
This is compared to rev 19169 in 2.8.1 final that is a lot more basic:
https://lampsvn.epfl.ch/trac/scala/browser/scala/tags/R_2_8_1_final/test/files/neg/checksensible.scala
I think this gives a sense that more attention was provided to this after 2.8.1.
Looking at some bug reports, it seems the warning are really just that - hopefully helping identify errors. If you know what you're doing (such as comparing java Boolean and scala Boolean), then you can ignore.

A: Interestingly, this has regressed.  In recent warning enhancements I must be excluding numerics and missing boolean.  The error message in trunk for comparing java.lang.Boolean and Boolean is impressively confusing.


text:
Q: MySQL Shell Scripting to create Procedures I'm working on an install script for Mac OSX and am using a shell script to create a database and all the tables I need for the program to use. The problem that I am facing is the creating of the procedure we need. I have tried multiple way of implementing and wondered if anyone knows of an example or if it is possible. Below is what I have as far as the procedure goes. I would appreciate any help.
The Procedure:
DELIMITER //
CREATE PROCEDURE Hours_Procedure()
BEGIN
DECLARE avg_usage FLOAT;
DECLARE max_time TIMESTAMP;
DECLARE counter INTEGER;
DECLARE NumOfNodes INTEGER;
DECLARE Num_Hour_Records INTEGER;

SET counter = 0;
SELECT MAX(Node_Num) INTO NumOfNodes FROM Minutes;

loop1 : LOOP SET avg_usage = 0.0;
 SET counter = counter + 1;
 IF counter = (NumOfNodes + 1) THEN LEAVE loop1;
 ELSE SELECT AVG(x.Power_Usage), MAX(x.Record_Time) INTO avg_usage, max_time FROM(
  SELECT M.Power_Usage, M.Record_Time FROM Minutes M
  WHERE M.Node_Num = counter ORDER BY RID DESC LIMIT 60) x;
  INSERT INTO Hours(Node_Num, Record_Time, Power_Usage) VALUES (counter, max_time, avg_usage);
  DELETE FROM Minutes WHERE Node_Num = counter ORDER BY RID ASC LIMIT 60;
 END IF;
END LOOP loop1;

DROP INDEX Hours_Index ON Hours;
CREATE INDEX Hours_Index ON Hours(RID, Node_Num);
END// DELIMITER ;

What I tried:
$mysql -u $_adminuser -h $_host -Bse "USE $_hostdb; $createProc;"

Where $createProc is the code to create the procedure.

A: With your procedure stored in the file procedure.sql, try the following. It eliminates the USE statement by specifying the database on the command line:
$mysql --batch --silent -u $_adminuser -h $_host $_hostdb < procedure.sql


text:
Q: How can I resolve the schemaLocation attribute of an .XSD when all of my .XSD's are stored as resources? I am working on a project where I need to generate XML files based on nested XSD's.  e.g. ORDER has a reference to PERSON, PERSON has a reference to ADDRESS, etc.
I am creating an `XmlReaderSettings' instance to validate the XSD's, as well as validate the XML after it is generated.
I have added the XSD's as Resources to my assembly.  I then create an XmlSchema instance for each resource, from lowest to highest, and add it to the XmlReaderSettings.Schemas collection.
However, this fails attempting to add a schema that references another schema.  I get an XmlSchemaException: "For element declaration, either the name or the ref attribute must be present."
I have included sample XSD's and source code below:
ADDRESS.xsd - referenced by PERSON.xsd
<?xml version="1.0" encoding="utf-8"?>
<xs:schema id="ADDRESS.xsd" attributeFormDefault="unqualified" elementFormDefault="qualified" xmlns:xs="http://www.w3.org/2001/XMLSchema">
  <xs:element name="ADDRESS" >
    <xs:complexType>
      <xs:sequence>
        <xs:element name="ADDRESS1" type="xs:string"/>
        <xs:element name="ADDRESS2" type="xs:string"/>
        <xs:element name="CITY" type="xs:string"/>
        <xs:element name="STATE" type="xs:string"/>
        <xs:element name="ZIP" type="xs:string"/>
      </xs:sequence>
    </xs:complexType>
  </xs:element>
</xs:schema>

PERSON.xsd
<?xml version="1.0" encoding="utf-8"?>
<xs:schema id="PERSON.xsd" attributeFormDefault="unqualified" elementFormDefault="qualified" xmlns:xs="http://www.w3.org/2001/XMLSchema">
  <xs:include schemaLocation="ADDRESS.xsd"/>
  <xs:element name="PERSON" >
    <xs:complexType>
      <xs:sequence>
        <xs:element name="L_NAME" type="xs:string"/>
        <xs:element name="F_NAME" type="xs:string"/>
        <xs:element name="Addresses">
          <xs:complexType>
            <xs:sequence>
              <xs:element ref="ADDRESS" minOccurs="0" maxOccurs="unbounded"/>
            </xs:sequence>
          </xs:complexType>
        </xs:element>
      </xs:sequence>
    </xs:complexType>
  </xs:element>
</xs:schema>

Sample Code - Load and validate XSD's
using System;
using System.IO;
using System.Text;
using System.Xml;
using System.Xml.Schema;
using SchemaTest.Properties;

namespace SchemaTest
{
    class Program
    {
        static void Main(string[] args)
        {
            // create validation settings instance
            var xmlReaderSettings = new XmlReaderSettings
            {
                ValidationType = ValidationType.Schema,
                ValidationFlags = XmlSchemaValidationFlags.ProcessInlineSchema |
                                  XmlSchemaValidationFlags.ProcessSchemaLocation |
                                  XmlSchemaValidationFlags.ReportValidationWarnings
            };

            xmlReaderSettings.ValidationEventHandler += SchemaValidationEventHandler;

            // added XmlResourceResolver, per the accepted answer below
            xMLReaderSettings.Schemas.XmlResolver = new XmlResourceResolver();

            // load schemas into validation settings instance
            LoadSchema(xmlReaderSettings, Resources.PERSON);

            // validate schemas
            xmlReaderSettings.Schemas.Compile();

            Console.WriteLine("Press any key to continue...");
            Console.ReadKey();
        }

        private static void LoadSchema(XmlReaderSettings xmlReaderSettings, string schemaString)
        {
            using (var schemaStream = new MemoryStream(Encoding.Default.GetBytes(schemaString)))
            {
                var schema = XmlSchema.Read(schemaStream, null);

                try
                {
                    xmlReaderSettings.Schemas.Add(schema);
                }
                catch (Exception ex)
                {
                    Console.WriteLine("EXCEPTION: {0}", ex.Message);
                }
            }
        }

        private static void SchemaValidationEventHandler(object sender, ValidationEventArgs e)
        {
            Console.WriteLine("{0}: {1}", e.Severity, e.Message);
        }
    }
}

I am not sure if this has anything to do with the ValidationFlags, but I tried removing XmlSchemaValidationFlags.ProcessSchemaLocation and still received the same error.  I have also tried passing SchemaValidationEventHandler to the XmlSchema.Read method (instead of null in sample code), and the schema seems to be created OK, but it still throws the exception when attemtping to add it to the XmlReaderSettings.Schemas collection.
EDIT - 2011.11.03
I resolved this issue (pun intended) by creating my own XmlUrlResolver descendent called XmlResourceResolver, based on the XmlResolver class example in accepted answer below.

A: To get rid of the error, change type="Addresses" to name="Addresses" in your PERSON.xsd file.
It is better to go with the code below to get schemas compiled. The important things are to make sure you establish a base uri (since you're reading from a stream), to use an XmlSchemaSet instead, and a custom resolver (to read files as embedded resources).
using System;
using System.IO;
using System.Text;
using System.Xml;
using System.Xml.Schema;

namespace ConsoleApplication3
{
    class Program
    {
        class XmlResolver : XmlUrlResolver
        {
            internal const string BaseUri = "schema://";

            public override object GetEntity(Uri absoluteUri, string role, Type ofObjectToReturn)
            {
                if (absoluteUri.Scheme == "schema")
                {
                    switch (absoluteUri.LocalPath)
                    {
                        case "/ADDRESS.xsd":
                            return new MemoryStream(Encoding.UTF8.GetBytes(Resource.ADDRESS));
                        case "/PERSON.xsd":
                            return new MemoryStream(Encoding.UTF8.GetBytes(Resource.PERSON));
                    }
                }
                return base.GetEntity(absoluteUri, role, ofObjectToReturn);
            }
        }

        static void Main(string[] args)
        {
            using (XmlReader reader = XmlReader.Create(new StringReader(Resource.PERSON), new XmlReaderSettings(), XmlResolver.BaseUri))
            {
                XmlSchemaSet xset = RetrieveSchemaSet(reader);
                Console.WriteLine(xset.IsCompiled);
            }
        }

        private static XmlSchemaSet RetrieveSchemaSet(XmlReader reader)
        {
            XmlSchemaSet xset = new XmlSchemaSet() { XmlResolver = new XmlResolver() };
            xset.Add(XmlSchema.Read(reader, null));
            xset.Compile();
            return xset;
        }
    }
}


text:
Q: Scala ordered priority queue that always has the lowest number as the head, ascending order I'd like to get a code sample that accomplishes ascending ordering of items in a priority queue.
I'd like to store Tuple2(Int, String) inside a priority queue so that it is ordered by the first element of the tuple in ascending order.
If my priority queue is called pq and I call pq.head I'd like to get the tuple with the lowest number, same thing with calling pq.dequeue.
scala> val pq = scala.collection.mutable.PriorityQueue[(Int, String)]()
pq: scala.collection.mutable.PriorityQueue[(Int, String)] = PriorityQueue()

scala> pq += Tuple2(8, "eight")
res60: pq.type = PriorityQueue((8,eight))

scala> pq += Tuple2(4, "four")
res61: pq.type = PriorityQueue((8,eight), (4,four))

scala> pq += Tuple2(7, "seven")
res62: pq.type = PriorityQueue((8,eight), (4,four), (7,seven))

How to apply ascending ordering by first element at time of insertion to the above?
Thanks

A: If all you need is reversing the implicit ordering, you could just reverse the queue right away:
val pq = PriorityQueue.empty[(Int, String)].reverse

A: All you need to do is to mention ordering of the queue items. The following code will serve the purpose.
  def ascendingOrder(tuple2: (Int, String)) = -tuple2._1
  val pq = PriorityQueue[(Int, String)]()(Ordering.by(ascendingOrder))
  pq += Tuple2(8, "eight")
  pq += Tuple2(4, "four")
  pq += Tuple2(7, "seven")
  for (i <- 1 to 3) (println(pq.dequeue()))

Avoid using reverse as it will create unnecessary overheads.

A: PriorityQueue.apply and PriorityQueue.empty both take an implicit Ordering instance that will be used to order the contents—the head will be the "largest" value according to that ordering. You're getting the default one for tuples, which is a lexicographic ordering on the elements of the tuple, which isn't what you want, since it'll make the tuple with the largest first element the head.
There are a couple of ways you can solve this issue. The easiest is just to call .reverse on your queue, which will give you a new queue with the same contents but the opposite ordering, which means the tuple with the lowest value will be the head.
You can also provide your own ordering when creating the queue:
import scala.collection.mutable.PriorityQueue

val pq = PriorityQueue.empty[(Int, String)](
  implicitly[Ordering[(Int, String)]].reverse
)

Or if you explicitly don't want the second element to be consulted:
val pq = PriorityQueue.empty[(Int, String)](
  Ordering.by((_: (Int, String))._1).reverse
)

This is possibly a little more efficient than reversing the queue, but probably not enough to worry about, so you should just choose the approach that you find most elegant.

A: From the scaladoc:

Only the dequeue and dequeueAll methods will return methods in priority order (while removing elements from the heap).  Standard collection methods including drop and iterator will remove or traverse the heap in whichever order seems most convenient.

That caveat seems to also apply to .head, but .dequeue returns elements in order.
The default ordering is descending (since the highest priority comes out first), but you can explicitly pass a reversed order when constructing:
val normalOrder = implicitly[Ordering[(Int, String)]]
val reversedOrder = Ordering.reverse(normalOrder)
val pq = scala.collection.mutable.PriorityQueue[(Int, String)](reversedOrder)


text:
Q: "No such module 'LocalAuthentication'" when trying to import in Xcode 6 using Swift I wanted to build a simple demo app using the new LocalAuthentication framework and Swift. I made a new Single View project, and added one line to the top of the ViewController.swift file:
import LocalAuthentication

Whereupon Xcode tells me there is no such module. Obviously very new to Swift, what am I doing wrong?

A: Same problem occurs with Objective-C code.
Seems like it is an issue of beta 1. If you run your project on an iOS 8 device (tested on a 5s iPhone), it will work. But it doesn't with the Simulator (Framework can't be found).

A: Yes,Same Problem Occurs in Xcode 6.
But It worked fine when I use an iPhone Device,
change "Deployment target" on settings to iOS 7.0, build and run in Iphone device.
But Touch ID not Supported in my ipod Device and Simulator..
Its works only in iPhone 5s Device.


text:
Q: Регулярные выражения Python - значение из середины текста Как с помощью регулярных выражений (желательно в Python) извлечь значение "3", используя только "А" в выражении. Каждое значение находится на новой строке.
Пробую следующим образом, но не работает:
text = """

A

ab

1

2

bc

3

4

B

ab

5

6

bc

7

8

"""

re_result = re.search('A.*bc\n+(\d)', text, re.S)
print(re_result.group(1))

Выдает 7, а не 3.

A: Используйте ленивый поиск, добавив ?:
re_result = re.search('A.*?bc\n+(\d)', text, re.S)

Т.к. у вас несколько bc и жадный поиск, то регулярка дошла до последнего bc и честно вытащила последующее число – 7.
Пример:

*

*.* – это жадный. Он попробует найти как можно больше.

*.*? – это ленивый. Он остановится на первом совпадении.


text:
Q: Error Getting Cassini to work on Local Machine I get the following error when attempted to get cassini to work on a local machine:
The current identity (NT AUTHORITY\LOCAL SERVICE) does not have write access to 'C:\Windows\Microsoft.NET\Framework\v2.0.50727\Temporary ASP.NET Files

I actually created a BAT file to do the following
cd\
cd C:\WINDOWS\Microsoft.NET\Framework\v2.0.50727\
aspnet_regiis -ga "NT AUTHORITY\LOCAL SERVICE"

and was wondering if there was a way to accomplish this same thing programatically in C#. The goal is to have the installer do this without having to rely on a BAT file.

A: If all else fails, you could invoke aspnet_regiis with System.Diagnostics.Process.


text:
Q: RabbitMQ, requeing a rejected message in a pub sub model written in node I am creating a simple chat app where

*

*There can be multiple users and multiple chat rooms.

*Each chat room can hold multiple users.

*A rabbitMQ connection is established when the server starts.

*When a user connects to the server, a socket connection is opened in a rabbitMQ channel.

*On sending a message through socket from the client (user), rabbitmq channel pushes it to the exchange using a specific routing key.

*On consuming, if the socket is active then send through it & acknowledge it. If not don't acknowledge it and re queue it.

{
//Creating a new connection
amqp.connect('amqp://localhost', (err, conn) => {

conn.createChannel(function(err, ch) {

ch.assertExchange(exchangeName, 'direct', { durable: false });
const routingKey = // some routing key;

wss.on('connection', (ws, req) => {
  // Creating a new queue for the user
  ch.assertQueue('', { exclusive: true, persist: true, durable: true }, (err, q) => {
    // Binds with the routing key
    ch.bindQueue(q.queue, exchangeName, routingKey);

    ch.consume(q.queue, (msg) => {
      if (ws.readyState === 1) {
        ch.ack(msg);
        ws.send(` [-] Received ${msg.content.toString()}`);
      } else {
        // What will come here so that it will be requeued to a new queue with the same routing id?
      }
    }, { noAck: false });
  });

  ws.on('message', (message) => {
    ch.publish(exchangeName, routingKey, new Buffer(message));
    console.log(`[x] Sent ${message} to the exchange with routingKey ${routingKey}`);
  });
})

This works correctly when all the users are in socket connected with the server. What I want to implement is when the socket connection dies for an user and if he misses a message based on the routing key (specific to the user), he should be able to receive those messages again whenever he reconnects back with a different queue. I feel this is possible since the messages can be kept in exchange if it is not acknowledged in any queue. But not sure how to implement it.

A: Let me address several misconceptions ...

What I want to implement is when the socket connection dies for an
  user and if he misses a message based on the routing key (specific to
  the user), he should be able to receive those messages again whenever
  he reconnects back with a different queue

You are using exclusive queues. By definition, these queues are deleted when their associated connection and channel goes away. The messages in those queues are lost when the queue is deleted.

I feel this is possible since the messages can be kept in exchange if
  it is not acknowledged in any queue.

That's not how RabbitMQ works. Exchanges are used to route messages, and queues are what store them.
The following comment is incorrect:

If user1 and user2 on different host, clearly they should establish
  different channels. 'channel' is just something like connection, if
  two channels consume same queue, they can receive same message.

Being on different hosts and probably running in different processes, user1 and user2 will each establish their own connections and channels. Two consumers will never receive the same message from the same queue.
Getting back to your original problem, you need to declare your queues as not-exclusive and durable, and name them in such a way that when your application re-connections the app connects to the same queue. That way, the app can consume the messages that remain on the queue.
There are various ways to have RabbitMQ delete unused queues for you that are documented.

NOTE: the RabbitMQ team monitors the rabbitmq-users mailing list and only sometimes answers questions on StackOverflow.

A: Consumer should consume message with Acknowledgement, If a message is delivered to a consumer and not acknowledged before the consumer connection dropped, then RabbitMQ will redeliver it. You can get more detail from RabbitMQ doc.
In your situation, when the socket connection broken, you should force close the channel, then the RabbitMQ will know these message should redeliver.
To ensure that messages do survive when server restarts, set exchange 'durable':
 ch.assertExchange(exchangeName, 'direct', { durable: false });


text:
Q: In Java, why does (unsorted) Set implement Iterable, but SortedMap does not? There are two aspects to this question that I felt were too closely related to ask as separate questions.

*

*Why doesn't SortedMap implement Iterable<Map.Entry<K,V>>?

If you need to perform an action on every key-value pair in a map, iterating over the entrySet() seems like the way to go.  So why not provide a direct iterator() method on SortedMap?  Unless you are worried about iteration order being inconsistent in a HashMap.  Which leads me to:

*Does implementing Iterable imply a stable ordering?

Iterating over an ordered collection (List, SortedMap, SortedSet) is a great way to reliably implement equals() (see Note 1) and do other things that have to produce the same result every time.  Iterating over an unsorted set or map could yield different ordering if you call it multiple times, so is unsuitable for these purposes.  Especially if you are comparing HashSets or HashMaps - two of them could contain the same objects, but the order of their iterators would be different.
I guess there are 2 aspects to those questions:

*

*What are the historical reasons for these design decisions?

*If doing it again today, are there correct answers to these questions?  Maybe OrderedIterable should extend Iterable to guarantee order?
Notes:

*

*I had originally suggested that you needed a reliable ordering to implement hashCode(), but if you sum all the hashcodes, it turns out that you don't need a reliable ordering if your hashing algorithm is commutative.  Addition is commonly used for hashCodes and it is commutative: a + b = b + a and B. even with overflow, addition is still commutative so that a + Integer.MAX_VALUE = Integer.MAX_VALUE + a.  You do still need a reliable ordering to implement equals() so that you can compare the first item of one to the first item of the other, etc.

P.S.
This question is about the interfaces Iterable, Set, SortedSet, Map, and SortedMap.  It's fine to bring up other interfaces as examples, but
I do not think the Collection interface is relevant to this question.  It's quirky and has the potential to be a distraction.

A: Although it is correct from a narrowly technical point of view to say that Set implements Iterable, but SortedMap does not, it is not a very useful question to ask.  A more useful question to ask is whether both classes offer the Iterable interface, and they certainly both do.
As you know, there are three ways to offer an interface:

*

*By explicitly implementing it using the implements keyword.

*By implementing an interface which extends the interface in question.

*By exposing a function which returns the interface in question.

Set is declared as follows: public interface Set<E> extends Collection<E> {... so, as you can see, Set does not directly implement Iterable, it only implements it indirectly, by virtue of implementing Collection, which extends Iterable.
Now, SortedMap would also be implementing Iterable indirectly, just as Set does, if it was implementing Collection, but it does not even do that.  Instead, it exposes an entrySet() function, which returns a Collection, which extends Iterable.
So, you can have your much desired Iterable in both cases.
If you would like to insist on the narrowly technical question of why Set (indirectly) implements Iterable, but SortedMap offers it via a function instead, the answer is that the designers of the java language runtime made the decision a long time ago to refrain from making extensive use of  interfaces extending other interfaces. That's why Map<K,V> does not extend Collection<Map.Entry<K,V>>, offering an entrySet() method instead.
They could have done the opposite, and as a matter of fact the designers of the C# language runtime did choose to go the other way, so IDictionary<K,V> extends ICollection<KeyValuePair<K,V>>.
I have experimented with both ways, and I still have not arrived at a conclusive decision as to which one is better.  They simply appear to be two different ways of accomplishing the same thing.
The implementation of Iterator does not imply a stable ordering, as you seem to understand (and therefore it is not clear to me where your question is in that respect.)  You may iterate over an unsorted map, in which case nobody can tell what the order of the items will be, and you may insert an element to the map and re-iterate, in which case the order of the items may be completely different from the previous time.  (Not just different by one item: all items may appear to be re-arranged.)
There is no need for an OrderedIterable interface because its signature would be identical to Iterable.  (And don't get me started on the choice of the java people to introduce a Set besides Collection.)  You can just invoke OrderedMap.entrySet(), which the documentation promises will return an ordered set, which means that the Iterator of that set will always yield items in order.


text:
Q: DataList inside PanelGrid Primefaces I'm trying to display dynamic grid panel using DataList but the problem is that the grid panel considers the columns of the datalist as one colomn and displays them in one column.
I want just to dispay panelgrid like in static data.
thank to help me.
this is my code
  <h:panelGrid columnClasses="align-top, align-top" columns="2">
                    <h:form>
                        <p:dataList id="parameters" value="#{scriptManagerForm.params}" var="conf" >
                            <p:column>
                            <h:outputText value="#{conf.name}"></h:outputText>
              </p:column> <p:column>
                            <p:inputText value="#{conf.value}" required="true" rendered="#{scriptManagerForm.isText(conf.type)}"></p:inputText>
                    </p:column>
                        </p:dataList>
                        <p:commandButton action="#{scriptManagerForm.validateParams()}" value ="Configure"  />
                    </h:form>
                </h:panelGrid>

and this is the style css applied on the panel grid
 .align-top {
                vertical-align: top;
            }


text:
Q: Connecting a 1280x720 Laptop to a high resolution screen I have connected my laptop (which has 1280x720 resolution) to my Samsung's 4k screen.
I chose my Samsung's screen as the Main display. I am not mirroring/extending the displays.
The windows-7 suggested to choose the 1920x1080 resolution but with that resolution, the whole screen/desktop/windows are not visible.
What should I do so that I can see properly sized windows on my Samsung's screen?
PS: I am running windows 7


text:
Q: Select jComboBox item only once for adding row to jTable I'm adding jCombobox selected item to jTable but I want to add item only once and change that specific cells values .
For example: I've added item for sale so when I'm selecting same item once again it must increase quantity and price accordingly calculation than adding new row.
I've tried using following code :
private void jComboBoxActionPerformed(java.awt.event.ActionEvent evt) {
    DefaultTableModel df = (DefaultTableModel) jTable.getModel();
    String actionCommand = "comboBoxEdited";
    if (evt.getActionCommand().equals(actionCommand)) {
        Object items = jComboBox.getSelectedItem();
        String name = (String) items;
        String[] part = name.split("\t");
        String item = (part[0]);
        int qty = Integer.valueOf((part[1]));
        double price = Double.parseDouble((part[2]));
        int ids = Integer.valueOf(part[3]);

        int rows = df.getRowCount();
        df.addRow(new Object[]{part[0], part[1], part[2], part[3]});
        for (int i = 0; i < rows; i++) {
            String id = (String) jTable.getValueAt(i, 2);
            if (ids == Integer.valueOf((String) jTable.getValueAt(i, 3))) {
                int qt = qty+1;
                jTable.setValueAt(item, i, 0);
                jTable.setValueAt(qt, i, 1);
                jTable.setValueAt(price * qt, i, 2);
                jTable.setValueAt(ids, i, 3);
            } else {
                df.addRow(new Object[]{part[0], part[1], part[2], part[3]});
            }
        }
    }
}

So with that code I can add only first row and when adding one more I can not get behavior I want.
Here is my complete code can check in IDE directly.
Thank you so much.

A: See whether below program works similar to what is in your mind. Notice how I have used found flag to build the logic.
(I have used " _ " in place of the tab character because it is more visible in the combo box.)
Here, I have assumed the "price" in the combo box is not the unit price. It is the price of full quantity in that combo box item.
import javax.swing.*;
import javax.swing.table.DefaultTableModel;
import java.awt.BorderLayout;
import java.awt.event.*;

public class AddToTable {

  public static void main(String[] args) {

    JTable jTable = new JTable(new DefaultTableModel(
        new Object[][] {},
        new String[] {"Item", "Qty", "Price", "ID"}));

    JComboBox<String> jComboBox = new JComboBox<>();
    jComboBox.addItem("Item1 _ 2 _ 2.5 _ 101");
    jComboBox.addItem("Item2 _ 5 _ 6 _ 201");
    jComboBox.addItem("Item3 _ 3 _ 1.5 _ 301");

    jComboBox.addActionListener(new ActionListener()
    {
      @Override
      public void actionPerformed(ActionEvent e)
      {
        Object items = jComboBox.getSelectedItem();
        String name = (String) items;
        String[] part = name.split(" _ ");
        String item = (part[0]);
        Integer qty = Integer.valueOf((part[1]));
        Double price = Double.parseDouble((part[2]));
        Integer ids = Integer.valueOf(part[3]);

        DefaultTableModel df = (DefaultTableModel) jTable.getModel();
        int rows = df.getRowCount();
        boolean found = false;
        for (int i = 0; i < rows; i++) {
          if (ids.equals(jTable.getValueAt(i, 3))) {
            Integer newQty = qty + (Integer) jTable.getValueAt(i, 1);
            Double newPrice = price + (Double) jTable.getValueAt(i, 2);
            jTable.setValueAt(newQty, i, 1);
            jTable.setValueAt(newPrice , i, 2);
            found = true;
            break;
          }
        }
        if (!found) {
          df.addRow(new Object[]{item, qty, price, ids});
        }
      }
    });

    JFrame f = new JFrame();
    f.setDefaultCloseOperation(JFrame.EXIT_ON_CLOSE);
    f.getContentPane().add(jComboBox, BorderLayout.NORTH);
    f.getContentPane().add(new JScrollPane(jTable), BorderLayout.CENTER);
    f.setBounds(300, 200, 400, 300);
    f.setVisible(true);
  }
}


text:
Q: has worked / worked I have been wondering what I should use between PP and PS in this particular context.
The last year, my friend bleached his teeth by a doctor, and today I want to do the same but I am puzzled and he tell me
" It will work because it worked for me" or "It will work because it has worked for me"
Indeed, even though the action is past, there is a relevance in the present. But to me the past simple version is better.

A: I would go with the first example. It is a little bit more natural sounding from a native speaker-perspective, and the second version with "has worked" suggests that the bleaching process is an ongoing thing rather than a one-time occurrence. Additionally, the sentence as a whole is a bit awkward because of what it implies. Just because the tooth bleaching worked for one person, this doesn't mean that it will automatically work for you. A better way to convey the same meaning might be

I've had my teeth bleached and it worked for me. Therefore, it might be worth giving it a shot.

or

Bleaching my teeth worked for me. It might work for you as well.


text:
Q: How can I escape backslashes in MySQL with JDBC? I want to insert something like \mytext into a MySQL database using JDBC. I tried to use the Java String replace method to find all backslashes and turn them into double-backslashes. In Java itself, I have to escape each backslash by a double-backslash, so in my understanding this should be it:
String sqlProcessed = sqlString.replace("\\", "\\\\")

The resulting string I send to the database using an insert statement, surrounded by 'single quotes' like this:
String query = "INSERT INTO table VALUES ('" + sqlProcessed + "')";

However, instead of showing the expected result, I get a double-backslash in the database, i.e., \\mytext. On the other hand, without the processing, the backslash is just omitted, i.e., I get mytext in the database.
What am I doing wrong?

A: Don't concatenate values into the query string (the only valid exception is if you need to dynamically determine table and columnnames).
Instead you should use parameterized (or prepared) statements:
For example
try (PreparedStatement preparedStatement = connection.prepareStatement(
        "insert into myTable (column1, column2, column3) values (?, ?, ?)")) {
    preparedStatement.setString(1, "value1");
    preparedStatement.setInt(2, 2);
    preparedStatement.setString(3, "value3");
    preparedStatement.executeUpdate();
}

Using prepared statements will remove the need to escape for the database (either the driver takes care of this, or the parameter values are sent to the server in a way that doesn't need escaping), you only need to take care of the normal Java String escaping.
As an added bonus you can get a reusable statement that you can execute multiple times with different values. And on most database systems (but IIRC not on MySQL with the default settings of the Connector/J driver), using prepared statements can (and usually will) have a performance benefit when reused.

A: I suggest you to use query parameters instead of making a query with parameters texted.
The driver will help you to feed the \.


text:
Q: Please report this issue to the mongodb/brew - PR to fix it? brew upgrade:
Warning: Calling plist_options is deprecated! Use service.require_root instead.
Please report this issue to the mongodb/brew tap (not Homebrew/brew or Homebrew/core), or even better, submit a PR to fix it:
  /usr/local/Homebrew/Library/Taps/mongodb/homebrew-brew/Formula/mongodb-community.rb:55

brew doctor:
Please note that these warnings are just used to help the Homebrew maintainers
with debugging if you file an issue. If everything you use Homebrew for is
working fine: please don't worry or file an issue; just ignore this. Thanks!

Warning: No Cask quarantine support available: unknown reason.
Warning: Calling plist_options is deprecated! Use service.require_root instead.
Please report this issue to the mongodb/brew tap (not Homebrew/brew or Homebrew/core), or even better, submit a PR to fix it:
  /usr/local/Homebrew/Library/Taps/mongodb/homebrew-brew/Formula/mongodb-community.rb:55

mongodb-community:
brew list mongodb-community
/usr/local/Cellar/mongodb-community/6.0.4/bin/install_compass
/usr/local/Cellar/mongodb-community/6.0.4/bin/mongod
/usr/local/Cellar/mongodb-community/6.0.4/bin/mongos
/usr/local/Cellar/mongodb-community/6.0.4/homebrew.mxcl.mongodb-community.plist
/usr/local/Cellar/mongodb-community/6.0.4/MPL-2
/usr/local/Cellar/mongodb-community/6.0.4/THIRD-PARTY-NOTICES

What causes this 'report'? Does it need "a PR to fix it"?

A: The issue has now been fixed in the Mongo's homebrew package.
See following pull requests:
https://github.com/mongodb/homebrew-brew/pull/176
and
https://github.com/mongodb/homebrew-brew/pull/174


text:
Q: Node.js: Viewing string variable in my browser So lets say I have a file called string.js, it might look something like this:
var hello = "Hello World!";

And lets say I have a file called hello.html.
How do I now view that string upon opening hello.html in my browser?

A: Your task can be divided into two parts:
1.add javascript codes to html and control then content
2.use node.js server to serve the html file up
The first task is pretty straightforward. You just have to include the .js file in your html. This is basic html-javascript application. You can find a lot of resource to learn it. W3schools is a very good site for beginners.
You have several ways to do task 2. Your objective is serve static contents. Let's use Hapi framework as an example.
'use strict';

const Hapi = require('hapi');

const server = new Hapi.Server();
server.connection({ port: 3000, host: 'localhost' });
server.register(require('inert'), (err) => {

    if (err) {
        throw err;
    }

    server.route({
        method: 'GET',
        path: '/sample',
        handler: function (request, reply) {
            reply.file('/your html file');
        }
    });
});
server.start((err) => {

    if (err) {
        throw err;
    }
console.log(`Server running at: ${server.info.uri}`);
});

Now, once you enter localhost:3000/sample in your browser, you will be able to see the result.
In the code, what you did is creating a Hapi server and setting a route. The route replies you a html file once it is called.

A: Node.js runs server side. To be able to display Hello world, you would need to do something like:
const http = require('http');

http.createServer((req, res) => {
  res.end('Hello World');
}).listen(3000);


text:
Q: Optimal value for applying gaussian filter in Difference of Gaussian? I have implemented Difference of Gaussian using OpenCV java.
import org.opencv.core.Core;
import org.opencv.core.Mat;
import org.opencv.core.Size;
import org.opencv.highgui.Highgui;
import org.opencv.imgproc.Imgproc;

import com.atul.JavaOpenCV.Imshow;

public class demodog

{
public static void main(String args[])
{
System.loadLibrary(Core.NATIVE_LIBRARY_NAME);

Mat img=Highgui.imread("C:\\testdatabase\\illumination1.jpg");

Mat g1=new Mat();
Mat g2=new Mat();
Mat g3=new Mat();
Mat g4=new Mat();
Mat g5=new Mat();

Mat r1=new Mat();
Mat r2=new Mat();
Mat r3=new Mat();
Mat r4=new Mat();

Imgproc.GaussianBlur(img, g1, new Size(1,1), 0);
Imgproc.GaussianBlur(img, g2, new Size(3,3), 20);
Imgproc.GaussianBlur(img, g3, new Size(5,5), 40);
Imgproc.GaussianBlur(img, g4, new Size(7,7), 50);
Imgproc.GaussianBlur(img, g5, new Size(11,11),70);

Core.subtract(g2, g1, r1);
Core.subtract(g3, g2, r2);
Core.subtract(g4, g3, r3);
Core.subtract(g5, g4, r4);

Imshow im9 = new Imshow("DOG4");
im9.showImage(r4);

Imshow im8 = new Imshow("DOG3");
im8.showImage(r3);

Imshow im7 = new Imshow("DOG2");
im7.showImage(r2);

Imshow im6 = new Imshow("DOG1");
im6.showImage(r1);

Imshow im = new Imshow("Input Image");
im.showImage(img);
}
}

The results are shown below

Question :
I have used kernel size of 1,3,5,7,11 with sigma values 20,40,50,70 to obtain the result.Did i use the suitable values or can i improve the result by changing the values..??

A: I'm looking here:
http://docs.opencv.org/modules/imgproc/doc/filtering.html?highlight=gaussianblur#gaussianblur
It seems you're OK.
Just keep the rule of the radius of the Gaussian Kernel to be 4-5 times the STD.
If you set the STD to 4, use Kernel of size [33, 33] to the least.
In order to have a better look of the "high Pass" image, usually it is added to a DC of level 128 (For [0,255] images).


text:
Q: Why loss function always return zero after first epoch? Why the loss function is always printing zero after the first epoch?
I suspect it's because of loss = loss_fn(outputs, torch.max(labels, 1)[1]).
But if I use loss = loss_fn(outputs, labels), I will get the error
RuntimeError: 0D or 1D target tensor expected, multi-target not supported

.
nepochs = 5

losses = np.zeros(nepochs)

loss_fn = nn.CrossEntropyLoss()

optimizer = optim.Adam(modell.parameters(), lr = 0.001)

for epoch in range(nepochs):

    running_loss = 0.0
    n = 0

    for data in train_loader:

        #single batch
        if(n == 1):
            break;

        inputs, labels = data

        optimizer.zero_grad()

        outputs = modell(inputs)

        #loss = loss_fn(outputs, labels)
        loss = loss_fn(outputs, torch.max(labels, 1)[1])
        loss.backward()
        optimizer.step()

        running_loss += loss.item()
        n += 1

    losses[epoch] = running_loss / n
    print(f"epoch: {epoch+1} loss: {losses[epoch] : .3f}")

The model is:
def __init__(self, labels=10):
    super(Classifier, self).__init__()
    self.fc = nn.Linear(3 * 64 * 64, labels)

def forward(self, x):
    out = x.reshape(x.size(0), -1)
    out = self.fc (out)
    return out

Any idea?
The labels are a 64 elements tensor like this:
tensor([[7],[1],[ 2],[3],[ 2],[9],[9],[8],[9],[8],[ 1],[7],[9],[2],[ 5],[1],[3],[3],[8],[3],[7],[1],[7],[9],[8],[ 8],[3],[7],[ 5],[ 1],[7],[3],[2],[1],[ 3],[3],[2],[0],[3],[4],[0],[7],[1],[ 8],[4],[1],[ 5],[ 3],[4],[3],[ 4],[8],[4],[1],[ 9],[7],[3],[ 2],[ 6],[4],[ 8],[3],[ 7],[3]])

A: Usually loss calculation is loss = loss_fn(outputs, labels) and here outputs is as following:
_ , outputs = torch.max(model(input), 1)
or
outputs = torch.max(predictions, 1)[0]

Common practice is modifying outputs instead of labels:

torch.max() returns a namedtuple (values, indices) where values is
the maximum value of each row of the input tensor in the given
dimension dim. And indices is the index location of each maximum value found (argmax).

In your code snippet the labels is not indices of the labels, so when you calculate the loss, the function should look like this:
loss = loss_fn(torch.max(outputs, 1)[0], labels)


text:
Q: Location based data in azure table storage I am designing an app which has a feature that allows a user to store geolocation based data, then later on allow other users to query for those data that falls within a given radius of their current geolocation.
The question is what is the best approach to design the table to be scalable and has great performance? I was thinking of having a table containing latitude as the partition key (pk), longitude as the row key (rk), then an dataid column that maps to another table that uses that dataid as its partition key.
My thinking is that using the 2-way lookup it's going to boost up my performance since both lookup would be instant. Is this the right way of thinking? I was reading somewhere that looking for partition keys that falls into some range is bad. If that is the case how should I approach this? How does Google maps, Apple map kit typically implement those feature?

A: This is difficult to answer completely without knowing your access patterns and scenarios fully. You can use the recently published Azure Storage Table design guide to help come up with a good design for your problem
http://azure.microsoft.com/en-us/documentation/articles/storage-table-design-guide/
For reads, Azure Table Storage is designed for fast point queries where client knows the partition key and row key so you need to factor that in your data model. For writes, you want uniform distribution and avoid append/prepend pattern to achieve high scale.


text:
Q: C99:I need someone with a good seeding algorithm for Windows 10 The code shown below is for a program that generates a random password. The password char makeup itself is fine, but the issue comes with the password length. It is supposed to be a random number between 12 and 20(upper and lower). However it always sets to 1 value per device. I'm aware that this is a seeding issue but I do not know what seed to use. If anyone has suggestions, please comment them below.
#include <stdio.h>
#include <stdlib.h>
#include <time.h>

int main()
{
    int lower = 12, upper = 20, count = 1;
    int i;
    for (i = 0; i < count; i++) {
    int num = (rand() %
    (upper - lower + 1)) + lower;
    int N = ("%d", num);
    **srand(time(0));**
    randomPasswordGeneration(N);
    return 0;
}

}
void randomPasswordGeneration(int N)
{
    int i = 0;
    int randomizer = 0;
    char numbers[] = "0123456789";
    char letter[] = "abcdefghijklmnoqprstuvwyzx";
    char LETTER[] = "ABCDEFGHIJKLMNOQPRSTUYWVZX";
    char symbols[] = "!@#$^&*? -_/";
    char password[N];
    randomizer = rand() % 4;
    for (i = 0; i < N; i++) {

        if (randomizer == 1) {
            password[i] = numbers[rand() % 10];
            randomizer = rand() % 4;
            printf("%c", password[i]);
        }
        else if (randomizer == 2) {
            password[i] = symbols[rand() % 8];
            randomizer = rand() % 4;
            printf("%c", password[i]);
        }
        else if (randomizer == 3) {
            password[i] = LETTER[rand() % 26];
            randomizer = rand() % 4;
            printf("%c", password[i]);
        }
        else {
            password[i] = letter[rand() % 26];
            randomizer = rand() % 4;
            printf("%c", password[i]);
        }
    }
}

A: Answer to my own question:
I accidentally put rand above srand. So it was not actually pseuo-random number generation
Broken Code:
int main()
{
    int lower = 12, upper = 20, count = 1;
    int i;
    for (i = 0; i < count; i++) {
    int num = (rand() %
    (upper - lower + 1)) + lower;
    int N = ("%d", num);
    srand(time(0));
    randomPasswordGeneration(N);
    return 0;
}

**Working Code:**

int main()
{
    srand(time(0));
    int lower = 12, upper = 2Oh0, count = 1;
    int i;
    for (i = 0; i < count; i++) {
    int num = (rand() % (upper - lower + 1)) + lower;
    int N = ("%d", num);
    randomPasswordGeneration(N);
    return 0;
}


text:
Q: C# + Code Contracts - Throw exception UPDATE - Due to lack of explanation from my side, I've rewritten the post.
What do you think about using Code Contracts to throw exceptions on invalid input?
(I'm coding against a contract for my Service which requires the UserName not to be null or contain whitespaces)
MembershipServiceContracts.cs - Located in the service layer in a subfolder
[ContractClassFor(typeof (IMemberShipService))]
internal abstract class MemberShipServiceContracts : IMemberShipService
{
    #region IMemberShipService Members

    public MembershipCreateStatus CreateUser(string userName, string password, string email)
    {
        Contract.Requires(!String.IsNullOrWhiteSpace(userName), "Test");
        Contract.Requires(!String.IsNullOrWhiteSpace(password));
        Contract.Requires(!String.IsNullOrWhiteSpace(email));

        return default(MembershipCreateStatus);
    }

    #endregion

}

MembershipService.cs - Located in my service layer
[ContractClass(typeof (MemberShipServiceContracts))]
public interface IMemberShipService
{
    MembershipCreateStatus CreateUser(string userName, string password, string email);
}

public class MemberShipService : IMemberShipService
{
    private readonly MembershipProvider _provider;

    public MemberShipService()
        : this(null)
    { }

    public MemberShipService(MembershipProvider provider)
    {
        _provider = provider ?? Membership.Provider;
    }

    #region IMemberShipService Members

    public MembershipCreateStatus CreateUser(string userName, string password, string email)
    {
        MembershipCreateStatus status;
        _provider.CreateUser(userName, password, email, null, null, true, null, out status);

        return status;
    }

    #endregion
}

AccountController.cs - located at the UI layer
Now this is the interesting part...
Should I use:
    [Authorize(Roles = "Developer")]
    [HttpPost]
    public ActionResult Create(CreateUserViewModel model)
    {
        if (!String.IsNullOrEmpty(model.UserName))
        {
            throw new ArgumentException("UserName May not be null or contain only white spaces.", model.UserName);
        }

        if (!String.IsNullOrEmpty(model.Password))
        {
            throw new ArgumentException("Password May not be null or contain only white spaces", model.Password);
        }

        if (!String.IsNullOrEmpty(model.Email))
        {
            throw new ArgumentException("Email May not be null or contain only white spaces", model.Email);
        }

        if (!ModelState.IsValid)
        {
            return Json("Model validation failed");
        }

        MembershipCreateStatus newUser = _memberShipService.CreateUser(model.UserName, model.Password,
                model.Email);

        return Json(newUser != MembershipCreateStatus.Success ? "Failed" : "Success");
    }

or:
[Authorize(Roles = "Developer")]
[HttpPost]
public ActionResult Create(CreateUserViewModel model)
{
    Contract.Requires<ArgumentException>(!String.IsNullOrWhiteSpace(model.UserName),
            "UserName May not be null or contain only white spaces.");

    Contract.Requires<ArgumentException>(!String.IsNullOrWhiteSpace(model.Password),
            "Password May not be null or contain only white spaces");

    Contract.Requires<ArgumentException>(!String.IsNullOrWhiteSpace(model.Email),
            "Email May not be null or contain only white spaces");

    if (!ModelState.IsValid)
    {
        return Json("Model validation failed");
    }

    MembershipCreateStatus newUser = _memberShipService.CreateUser(model.UserName, model.Password,
            model.Email);

    return Json(newUser != MembershipCreateStatus.Success ? "Failed" : "Success");
}

to throw the an exception if the code contracts for the CreateUser() method isnt fulfilled?
Thanks in advance.

A: A failure in a Code Contract indicates that your code has a serious bug that should be fixed. It doesn't replace validation of user input. Rather, you would first validate your user input, then attempt to process the data if determined to be valid (otherwise prompt the user to re-enter). If you then don't satisfy the target contract with your valid data, then an uncatchable exception will be thrown as you pretty obviously have a bug.
I hoped it would be a silver bullet but quickly realised I still needed my validation. After that, I grew to really love the way code contracts will replace all of my usual guard code.
Think of all the times you would get a NullReferenceException (too many for me!). Code Contracts can take that pain all away.
R.
P.s. Also, don't use contracts to validate security-sensitive data as code contracts can be turned off at runtime...

A: I'm afraid to say: it depends on how you want to use code contracts.
You'd better look at the user manual, section "Usage Guidelines". Here's a small excerpt:

The easiest use of the contract tools
is if you decide that you don't need
to perform argument validation at
runtime in release builds (Usage 1).
In that case, you use the contract
tools during development, but not on
the shipped bits. Remember, you can
ship a contract reference assembly
along with your release bits so 18
clients can get runtime checking of
your parameter validations on their
debug builds via call-site requires
checking. The second easiest approach
if you need argument validation in
your release build is to turn on
contract checking in all builds (Usage
2). You therefore take advantage of
the tools to produce the runtime
strings of your conditions and to
perform contract inheritance for you.
You can choose to produce specic
exceptions for your parameter
validations, or have the default
ContractException.

I'd suggest you read the whole section before making any big decisions.

A: Both of the approaches are fine .
The 3 ways that one has for checking pre conditions are

*

*Contract.Requires -> a particular condition must be true upon entry to the method.

*Contract.Requires -> Same as above but throw exception if condition not met
Requires is always compiled, so use of this method entails a hard dependency on    the tools. You should decide if you want that before using this method.

*Your first approach --> The benefit of this type of precondition is that it is always there to perform the runtime check.
In the first approach you might want to add Contract.EndContractBlock();
I am exploring this feature myself but I think you can throw exception in your service layer and it is ok.
HTH


text:
Q: I can upload files to root of the Google Disk, but can't upload file to subdirectory I am trying to upload a file to Google Disk using the HTTP based protocol of the Google Drive API.
Request:
POST /upload/drive/v3/files?uploadType=multipart HTTP/1.1
Host: www.googleapis.com
Content-length: 317
Content-type: multipart/related; boundary="===============1113791900570109977=="
Authorization: Bearer ...

--===============1113791900570109977==
Content-type: application/json

{
  "mimeType": "text/plain",
  "parentID": "[\'16zJngsKtpLtlFe-WTo8LOCCQ2k-uqkZI\']",
  "folder": "test",
  "name": "test1.txt"
}
--===============6521522044179315692==
Content-type: text/plain

test1

--===============6521522044179315692==--

Response:
HTTP/1.1 200 OK
Content-length: 119
Expires: Mon, 01 Jan 1990 00:00:00 GMT
Vary: Origin, X-Origin
Server: UploadServer
Date: Sun, 06 Jun 2021 11:18:11 GMT
Pragma: no-cache
Cache-control: no-cache, no-store, max-age=0, must-revalidate
X-guploader-uploadid: ABg5-UxJxPPfItZVlcOjWSM74dRtuNGFN-S88K_BU9lYi9Bjz-JgU9GzUPp2ghHP83ynJKklgVtsOPaLonv1KkISPg
Alt-svc: h3-29=":443"; ma=2592000,h3-T051=":443"; ma=2592000,h3-Q050=":443"; ma=2592000,h3-Q046=":443"; ma=2592000,h3-Q043=":443"; ma=2592000,quic=":443"; ma=2592000; v="46,43"
Content-type: application/json; charset=UTF-8
{
  "mimeType": "text/plain",
  "kind": "drive#file",
  "id": "1d_ZC7slHvidXAu774SOE_nkBuO-Bblsk",
  "name": "test1.txt"
}

I  add to the metadata object, parents: ['16zJngsKtpLtlFe-WTo8LOCCQ2k-uqkZI'] where that string is the id of the folder I wanted to upload it into. But file always upload in root directory.
What I doing wrong?

A: In your request body, I think that "parentID": "[\'16zJngsKtpLtlFe-WTo8LOCCQ2k-uqkZI\']", is required to be modified. And, there is no property of folder. So, how about the following modification?
From:
{
  "mimeType": "text/plain",
  "parentID": "[\'16zJngsKtpLtlFe-WTo8LOCCQ2k-uqkZI\']",
  "folder": "test",
  "name": "test1.txt"
}

To:
{
  "mimeType": "text/plain",
  "parents": ["16zJngsKtpLtlFe-WTo8LOCCQ2k-uqkZI"],
  "name": "test1.txt"
}

*

*In this request body, the file of test1.txt is created in the folder of 16zJngsKtpLtlFe-WTo8LOCCQ2k-uqkZI.

References:

*

*Files: create

*Files


text:
Q: Selective iteration in arbitrary number of lists Let's say I have an arbitrary number of lists (so list of lists). All lists are of same size,
An example of this might be
say, k lists of length 4 (k=2)
[
[A, B, C, D] # length 4
[A, F, G, D] # length 4
]

Now given a query_list
[A, B, C, E]

This should return [A, B, C, D] which is the longest chain as in [A,F,G,D], the second character "F" and "B" in query_list mismatches..

A: x=[ ["a","b","c"],["a","b","z"],["a","z","c"] ]
z=["a","b","c"]

arr = []
for i in x:
    cnt = sum(z == y for z, y in zip(i, z))
    arr.append(cnt)

index = arr.index(max(arr))

print(x[index],"matched the most")


text:
Q: Nonetype is not iterable when updating dictionary? I am pretty new to python and as a project to push myself, I decided to create a simple framework with an updatable user:password dictionary. This is still a work in progress! The problem exists when creating a new user id and then trying to access that user id. I am using python 3.7.
Here is the error:
Traceback (most recent call last):
  line 37, in
    if account in accounts:
TypeError: argument of type 'NoneType' is not iterable
import sys
accounts = {'Trace': 'Jollyrancher5', 'Brian': 'Kitties82', 'Taylor': 'Flower15'}

while True:
    print('Please select an option.\n1. Create new account.\n2. Enter existing account.')
    choice = input()
    if choice == '1':
        print('Please enter an account name')
        new_account = input()
        if new_account not in accounts.keys():
            print('Please enter a password.')
            new_pass = input()
            accounts = accounts.update({new_account: new_pass})
            print('Your new User ID is: ' + new_account + '.')
            print('Your new password is: ' + new_pass + '.')
            print('Please store this information for safe keeping.')
            print('Type OK to continue.')
            while True:
                next = input()
                if next == 'OK' or next == 'ok':
                    break
                else:
                    print('Invalid entry. Please type OK.')
        else:
            print('Account name taken. Please enter a different account name.')
    elif choice == '2':
        break
    else:
        print('Not a valid entry.')

account = ''
password = ''
denial = 0
while True:
    print('Please enter User ID.')
    account = input()
    if account in accounts:
        break
    else:
        print('User ID not recognized.')

while True:
    print('Please enter password.')
    password = input()
    if password == accounts[account]:
        break
    else:
        password != accounts[account]
        denial += 1
        if denial == 3:
            print('Account locked.')
            input()
            sys.exit()
print('Access Granted.\nYour account balance is $1,000,000.00.')
input()

A: The issue is in line no 13:
accounts = accounts.update({new_account: new_pass})

This returns None as the update is done in place. [see docs] Instead use:
accounts.update({new_account: new_pass})

It will perform the update no need to reassign the value.

A: Remove this line:-
`accounts = accounts.update({new_account: new_pass})`

add this line:-
`while True:
      print('Please enter User ID.')
      account = input()
      accounts.update({new_account:new_pass})
      if account in accounts:`

this error is caused because your dictionary was not getting updated, and that's why the first value it was recieving was None hence a NoneType error was generated.
Upvote if you understand my answer.


text:
Q: JavaScript Object Function Access Variable in setTimeout I am a newbie in OOP in JS. Right now I am trying to call variable in the instance, but how can I call it in the function?
var foo = function() {

    this.a = 1;    // how can I call 'a' in the setTimeout() function

    this.start = function(i) {
        if (i<3){
            window.setTimeout(function() {

                console.log(a);    // this line shows undefined
                console.log(this.a);      // this line indicates 'this' is window

                i++;
                start(i);    // this one does not work as well

            }, 2000);
        }
    };
};

var bar = new foo();
bar.start(0);

A: Just store this in a variable before the function:
var foo = function() {

    this.a = 1;    // how can I call 'a' in the setTimeout() function

    this.start = function(i) {
        var that = this;
        if (i<3){
            window.setTimeout(function() {

                console.log(that.a);

                i++;
                that.start(i);    // this one does not work as well

            }, 2000);
        }
    };
};

var bar = new foo();
bar.start(0);

Alternatively, you can use ES6's new arrow functions depending on your project requirements:
window.setTimeout(() => {

    console.log(this.a);

    i++;
    this.start(i);    // this one does not work as well
}, 2000);


text:
Q: How to find the iteration in which the continue-sattement takes place in python I have a for loop and a continue statement in it in python. I want to know the number of iteration in which the continue statement took place. I mean:
count=0
for i in range (5):
    if i == 3:
        count+=1
        continue
    print (i)

The count value tells me that 1 time I have faced the continue in my for loop. But I want to know in which iteration was it, which obviously is the fourth iteration (after printing 0, 1 and 2). In reality I may get into continue several time and this is only a simple example to clarify my proble. I do appreciate if anyone let me know how to find it out. In advance, thanks for any help.

A: Two ways to go about this.

*

*Modifying your code slightly:

>>> count = 0
>>> for i in range(5):
...     count += 1
...     if i == 3:
...             print(f"Loop continued at iteration {count}")
...             continue
...     print(i)
...
0
1
2
Loop continued at iteration 4
4

*Using enumerate, for a more 'pythonic' solution:

>>> for iter, i in enumerate(range(5), start=1):
...     if i == 3:
...             print(f"Loop continued at iteration {iter}")
...             continue
...     print(i)
...
0
1
2
Loop continued at iteration 4
4

A: count=0
for i in range (5):
    if i/3 == 0:
        count+=1
        continue
    print (i)

Your code should like this but in this code for-loop continues forever
if you want write i to screen each times use the code below
count=0
for i in range (5):
    if i/3 == 0:
        count+=1
        print (i)
        continue

A: Use class to store the values.
class info():
    def __init__(self):
        self.counter = 0
        self.iter = []

    def increment(self):
        self.counter += 1

a = info()
for i in range(5):
    a.increment()
    if i%2:
        if i!=5:
            a.iter.append(i+1)
        continue
print(a.counter, a.iter)

5 [2, 4]

see: https://ide.geeksforgeeks.org/3WrtCiH2PD

A: Each time continue  is run, add the current index to count. At the end the count list will contain all the indexes in which continue has been executed. The length of count will tell you how many times continue has been run.
 if __name__ == '__main__':
        count = []
        for i in range(5):
            if i == 3:
                count.append(i+1) #because iter starts with 0
                continue
            print(i)
    print(count)
    print(len(count))

Clarification
You can change i+1 with i, it depends on how you want to interpret it. In general it depends on whether you want to take into account that the iteration started from 0 or not.


text:
Q: 3-d integration over space and complex time argument of quantum mechanical propagator This is a chemically inspired problem, but basically all it consists of is computing integrals.
I have an integral like this.
$$f=\int\int{\int{K_0(x_a,x_b,\frac{it}{\hbar}-\frac{\beta}{2})K_1(x_b,x_a,\frac{-it}{\hbar}-\frac{\beta}{2})}}dx_adx_bdt$$
My kernels $K$'s are:
$$K_0=\sqrt{\frac{m}{2\pi t_0}}\exp{(-S_0)}$$
$$K_1=\sqrt{\frac{m}{2\pi t_1}}\exp{(-S_1)}$$
$S's$ correspond to action (in the sense of physics) which is:
$$S_n(x_a,x_b,t_n)=\frac{m(x_a-x_b)^2}{2 t_n}-\frac{(x_a+x_b)k_nt_n}{2}-\frac{k_n^2t_n^3}{24m}$$
Where $n$ is either 0 or 1. The problem is the integral above doesn't seem to be converging with the imaginary argument for $t$'s.I am trying to integrate with respect to: $x_a$, $x_b$ and $t$ from -Inf to +Inf. My final answer for integral should look something like this:
$$\exp{\frac{k_0^2k_1^2\hbar^2\beta^3}{24m(k_0-k_1)^2}}$$
One can set $\hbar$ to 1. Is it a gaussian integral with respect to $x_a$ and $x_b$? One has to be careful because there are also imaginary parts in the exponent. How does one reach at the-above final answer for the integral? Really confused! Any help is appreciated since the integral doesn't look gaussian to me.


text:
Q: Computed field - extension method, ViewModel, Viewbag variable? I have the following classes.
public class Header
{
    public int HeaderId { get; set}
    public virtual List<Detail> Details { get; set; }
    ....
}

public class Detail
{
    [Required, ForeignKey("Header")]
    public int HeaderId { get; set; }
    public virtual Header Header { get; set; }
    public int Quantity { get; set; }
    ....
}

And I've built a page show the list of Header. I didn't use any ViewModel.
Index.cshtml
@model IEnumerable<App1.Models.Header>
@foreach (var i in Model) {
    ....
    // TODO: Add Sum of Detail.Quantity for each Header item
}

Now, I have a requirement of adding the sum of Quantity in the Detail class for each Header item in the Index.cshtml page.
What's the best and quickest way to refactor the code? Is an extension method on Header good approach?
P.S. I just use summing as an example, the actual computing is much more complex.

A: You should try to keep the logic in the Model and not in the View. Since it's an aggregation of the Detail objects in the Header, I suggest you add the logic into the Header object.
public class Header
{
    public int HeaderId { get; set; }
    public virtual List<Detail> Details { get; set; }

    public int SumOfDetailQuantities
    {
        get { return Details.Sum(x => x.Quantity); }
    }
}

I would not suggest that you add an extension method to the Header since you've already got full control over the Model, an extension method would only obfuscate the code. There is nothing wrong with having this type of aggregation logic in the Model, but if you have some religious reasons for not doing it, then set the value from the ViewModelBuilder.

A: create a class
public class HeaderWithSum {
    public Header Header {get; set;}
    public int Sum {get; set;}
}

then in your Action Method :
public ActionResult Index() {
    var hs as headerWithSum;
    List<HeaderWithSum> headerWithSum;
    List<Header> headers = headerRepository.GetAll();
    int sum = 0;
    foreach(var h in headers) {
        sum = h.GetSumOfDetails();
        hs = new HeaderWithSum()
             {
                 Header = h , Sum = sum
             };
        headerWithSum.Add(hs);
    }
    return View(headerWithSum);
}

for simplifying i omitted some code such as DI and Implementation of GetSumOfDetails method

A: Finally I just create a function and put it in ViewBag.
ViewBag.SumFunc = new Func<Header, int>(....);

Then call it in the view.


text:
Q: Bloomberglp.Blpapi.RequestQueueOverflowException: Queue Size: 128 I can't figure out what the problem is with Bloomberg API.
Everytime when I try to download historical finance data, that means to create a DataRequest for 5000 instruments for 3 days once for euro currency and once for local currency, I get this queue exception.
What's really confusing is, the program still goes on for the first request which contains euro prices for instruments but not for the second.
Thanks for the help.

A: Well since you are not getting a slow consumer warning, I'd bet you are just requesting to much data on one request.
Try Splitting your request into several chunks.

A: Queue Size of each request is 1024, if the size > 1024, it will throw BloombergOverFolowException


text:
Q: How can I get the size in bytes allocated on data memory segment? Is there any way to get the number of bytes allocated in the data memory segment by a C++ program during debug-time? I know how to track general memory consumption and heap allocation, but this is something I have never done before.
I am looking for either a code solution or some form of Visual Studio analyzing utility.


text:
Q: How to find the deviation using Java I would like to find out the deviation between two drawing lines using the following code but for some reason it just feels wrong.
import java.awt.*;
import java.awt.event.ActionEvent;
import java.awt.event.ActionListener;
import java.awt.event.MouseEvent;
import java.awt.event.MouseListener;
import java.awt.event.MouseMotionListener;
import java.util.ArrayList;

import javax.swing.*;

public class DrawLine extends JPanel {

  private static final long serialVersionUID = 1L;

  LinePoint[] lineA = new LinePoint[5];
  LinePoint[] lineB = new LinePoint[5];

  public void paintComponent(Graphics g) {

     for(int i = 0; i < lineA.length; i++) {
         lineA[i] =  new LinePoint();
         lineB[i] =  new LinePoint();

     }

     int initialLocationPoint = 10;
     for(int i = 0; i<lineA.length; i++) {
         lineA[i].x = initialLocationPoint;
         lineA[i].y = 100;
         lineB[i].x = initialLocationPoint;
         lineB[i].y = 100;
         g.drawOval((int)lineA[i].x, (int)lineA[i].y, 1, 1);
         g.drawOval((int)lineB[i].x, (int)lineB[i].y, 1, 1);
         initialLocationPoint +=1;
     }

     System.out.println("DEVIATION: " + this.calculateDifference());

  }

  public double calculateDifference() {
      double deviation = 0.0;
      double deviationPerCordinate = 0.0;
      for (int i = 0; i < lineA.length; i++) {
          deviationPerCordinate = Math.sqrt( Math.pow(2, (lineB[i].x - lineA[i].x))  + Math.pow(2,(lineB[i].y - lineA[i].y)));
          System.out.println("deviationPerCordinate " + i + ": " + deviationPerCordinate);
          deviation = deviation + deviationPerCordinate;
      }
      return deviation;
  }

  public static void main(String[] args) {
    JFrame.setDefaultLookAndFeelDecorated(true);

    JFrame frame = new JFrame("Draw Line");
    frame.setDefaultCloseOperation(JFrame.EXIT_ON_CLOSE);
    frame.setBackground(Color.white);
    frame.setSize(400, 400);

    DrawLine panel = new DrawLine();

    frame.add(panel);

    frame.setVisible(true);
  }

RESULT:
deviationPerCordinate 0: 1.4142135623730951
deviationPerCordinate 1: 1.4142135623730951
deviationPerCordinate 2: 1.4142135623730951
deviationPerCordinate 3: 1.4142135623730951
deviationPerCordinate 4: 1.4142135623730951
DEVIATION: 7.0710678118654755
EXPTECTED RESULT:
Shouldn't this return 0? as there is no difference at all since both drawings are at the same positions/cords.
Anyone knows what Am I doing wrong here? Is it the formula?

A: Asuming that you are using the Euclidean distance to calculate the deviation, you formula is wrong. The correct way to square a value in Java using Math library is Math.pow(x, 2). That being said, this Math.pow(2, (lineB[i].x - lineA[i].x)) should be Math.pow((lineB[i].x - lineA[i].x), 2) and same for the y coordinate.


text:
Q: Which sheaves on a projective bundle are flat over the base scheme? Assume $X$ is a noetherian scheme over $\mathbb{C}$ and $E$ a locally free sheaf of finite rank on $X$. Denote the the associated projective bundle by $f: \mathbb{P}(E)\rightarrow X$.
Are there any coherent sheaves on $\mathbb{P}(E)$ that are flat over $X$ except locally free ones?
I'm especially interested in such $G\in Coh(\mathbb{P}(E))$ with the property that the canonical morphism $f^{*}f_{*}G\rightarrow G$ is an isomorphism. For these $G$ we have $G_{|\mathbb{P}(E(x))}=\mathcal{O}_{\mathbb{P}(E(x))}^{r_x}$ for all closed points $x\in X$ and some $r_x\geq 1$. So we have $H^i(\mathbb{P}(E(x)),G_{|\mathbb{P}(E(x))})=\{0\}$ for all $i\geq 1$.
I'm trying to see that this implies $R^if_{*}G=0$ for all $i\geq 1$, for which flatness of $G$ over $X$ is needed.

A: **Question: "I'm especially interested in such G∈Coh(P(E)) with the property that the canonical morphism $f^∗f_∗(G)\rightarrow G$ is an isomorphism."
Answer: If $S:=Spec(k)$ with $k$ the complex number field and $V:=k\{e_0,..,e_n\}$ it follows $\mathbb{P}(V^*) \cong \mathbb{P}^n_k$ is complex projective $n$-space. Let
$$\pi: \mathbb{P}^n_k \rightarrow S$$
be the projection morphism and let $G$ be a coherent sheaf on $\mathbb{P}^n_k$. It follows
$$\pi_*(G) \cong H^0(\mathbb{P}^n_k,G)$$
is the $k$-vector space of global sections of $G$ - let this vector space have basis $B:=\{u_i\}_{i \in I}$. It follows $\pi_*(G)$ is a free $\mathcal{O}_S$-module on the basis $u_i$.
Since the pull back of a free module is a free module, it follows there is an isomorphism
$$\pi^*\pi_*(G) \cong \oplus_{i\in I}\mathcal{O}_{\mathbb{P}^n_k}u_i$$
hence the $\mathcal{O}_{\mathbb{P}^n_k}$-module $\pi^*\pi_*(G)$ is free on the set $I$.
If you require $G$ to have an isomorphism
$$\pi^*\pi_*(G) \cong G$$
it follows $G$ is a free $\mathcal{O}_{\mathbb{P}^n_k}$-module on $I$.
Question: "I'm trying to see that this implies Rif∗G=0 for all i≥1, for which flatness of G over X is needed."
Answer: In Hartshorne, Ex.III.8.4 they compute the higher direct images
$$R^n\pi_*(\mathcal{O}(l))$$
for any projective bundle $\mathbb{P}(E^*)$ and any locally trivial sheaf $E$.
In particular they calculate it for the example above with $E:=V$, $l=0$ and $\mathcal{O}_{\mathbb{P}^n_k}$. Note that if $f:X\rightarrow Y$ is a morphism of schemes and if $E,F$ are $\mathcal{O}_X$-modules it follows
$$f_*(E\oplus F)\cong f_*E \oplus f_*F.$$


text:
Q: Deleting more than 20 columns in excel vba I wrote a macro to do multiple things and in the end want to delete more than 20 columns.
I used the below statement to execute it but it gives me a run time error. It looks like there is a limit on how many columns you can delete at a time.
I recorded a macro to delete all the below columns and it seems that excel is splitting the range statement into multiple but when i use it, it does not seem to work.  pls let me know what's the easiest way to delete so many columns. thanks
Range("A:A,C:C,D:D,E:E,F:F,J:J,L:L,M:M,O:O,Q:Q,R:R,T:T,U:U,V:V,W:W,X:X,Z:Z,AA:AA,AB:AB,AC:AC,AD:AD,AE:AE,AG:AG,AI:AI,AK:AK,AL:AL,AN:AN,AO:AO,AP:AP,AQ:AQ,AR:AR,AT:AT,AU:AU, AV: AV , AW: AW , AX: AX , AY: AY , AZ: AZ , BA: BA , BB: BB , BC: BC , BD: BD , BE: BE , BF: BF , BG: BG , BH: BH, BI:     BI , BJ: BJ , BK: BK , BM: BM , BN: BN , BP: BP , BQ: BQ , BR: BR , BS: BS , BU: BU , BV: BV , BW: BW , BX: BX , BY: BY , CA: CA, CB:     CB , CC: CC , CE: CE ").Select
Range("CE1").Activate
Selection.Delete Shift:=xlToLeft

A: With Sheets(shtname)
        .Columns(Range("A").Select).EntireColumn.Delete
        .Columns(Range("C:F,J,L,M,O").Select).EntireColumn.Delete
        .Columns(Range("Q:R, T:X").Select).EntireColumn.Delete
        .Columns(Range("Z:AE,AI,AK:AL,AN:AR,AT:BK").EntireColumn.Delete
' complete your range in the same way and you should be sorted
End With

Seems like it should work for your purpose, if not, do leave a comment clarifying your question.

A: The address string you pass to the range property can't exceed 255 characters. You can shorten yours because some of the columns are adjacent -eg use T:X rather than T:T,U:U,V:V,W:W,X:X. If the string is still too long you will need to create separate ranges and union them, or perform the delete in a couple of steps.


text:
Q: fdisk prints nothing and devices are not mounted I am quite new to Linux, and I need to mount some devices, using the lsblk command and more.
lsblk presents the devices (internal, I don't have external ones) the output is:
# lsblk
NAME                    MAJ:MIN RM   SIZE RO TYPE MOUNTPOINT
sda                       8:0    0   120G  0 disk
|_sda1                    8:1    0     2G  0 part
|_sda2                    8:2    0   118G  0 part
  |_centos-root (dm-0)  253:0    0   110G  0 lvm  /opt/loglevels
  |_centos-swap (dm-1)  253:1    0     8G  0 lvm
sr0                      11:0    1  1024M  0 rom

I saw in many tutorials that the devices are mounted to /dev directory, i.e to get the sda1 device I'd type lsblk /dev/sda1 etc. but this command returns lsblk: /dev/sda1: not a block device
when I type fdisk -l that brings the mounted devices- it prints nothing:
# fdisk -l
#

where is my mistake? what am I missing? I saw in this link that there might be some problem in mounting the files, how can I see it?
Thaks a lot!

A: For lsblk consider doing this
alias lsblk2='lsblk -o type,name,label,partlabel,size,fstype,model,serial,wwn,uuid'

That sets up an alias so when you type lsblk2 it will give what i consider the most useful printout of what lsblk can do, and show all devices connected that you can easily reference and know what is what.
And doing lsblk -h will give you the help printout, showing all the options you can use like I did with the lsblk2 alias, and you can tweak to your liking.


text:
Q: Update en laravel Soy nuevo utilizando laravel y quisiera saber como pasar la siguiente consulta a laravel
UPDATE users
INNER JOIN tm_employee ON users.id = tm_employee.UserId
SET users.groupId = ''
WHERE tm_employee.id = ''

A: Mira si te sirve así:
 DB::table('users')
   ->join('employee', 'users.id', '=', 'employee.UserId')
   ->where('employee.id','')
   ->update([ 'employee' => '' ]);

A:
Si estas trabajando cada una de tus tablas por medio de los modelos de
  Laravel, deberías hacer lo siguiente

En el controlador
Aquí puedes invocar al modelo User de este modo
use App\User;

Después de eso, tu consulta debería verse así
$data = User::join('employee', 'users.id', '=', 'employee.UserId')
   ->where('employee.id','')
   ->update([ 'employee' => '' ]);

Finalmente para que esto funcione, te debes dirigir al modelo User y declarar lo siguiente
public $timestamps = false;

LO QUE HCIE FUE

*

*lo anterior se hace para que con esto no intente actualizar tu columna updated_at es decir esa la ignore

*Las columnas y sus valores que se usarán en la actualización se mandan dentro del método update bajo el formato de clave=>valor