text:
Q: How to check if two instances are of the same class Python So in my pygame game, I have created a list of objects to make things like updating them all and collision checking easier. So when I'm collision checking, I have to check if the current object is the same as the object we are collision checking with. Here is my current code:
def placeMeeting(self, object1, object2):

    # Define positioning variables
    object1Rect = pygame.Rect(object1.x, object1.y, object1.width, object1.height)

    # Weather or not they collided
    coll = False

    # Loop through all walls to check for possible collision
    for i in range(len(self.instances)):

        # First check if it's the right object
        if (self.instances[i] == object2):
            print "yep"
            object2Rect = pygame.Rect(self.instances[i].x, self.instances[i].y, self.instances[i].width, self.instances[i].height)

            # Check for collision with current wall -- Horizontal
            if (object1Rect.colliderect(object2Rect)):
                coll = True

    # Return the final collision result
    return coll

(All objects in the list/array are a child to the su)

A: Apart from type way in previous answer, I think you can use isinstance. https://docs.python.org/2/library/functions.html#isinstance
Operator is can be used for object checking such as a is b if a and b are same objects. Remember is checks only objects and not their values. Or, I havenot seen anyone do this, I guess id(obj1) == id(obj) would work as well when you need to check if two objects are same.

A: You can check to see the type of a variable using the type() function. So your code would read as below:
if(type(self.instances[i]) is MyCustomType):

This would check to see if instance[i] is of type MyCustomType. You can replace this with inbuilt types such as dict, list, int, str etc. or it can be custom types/objects you have declared.
It is important to note that it will only check the object type and not the object's values. So it will not see if two objects hold identical values.
It is also a bit tricky when we come to inheritance, so there are more examples in this answer Determine the type of an object?
Also take note from the comments to this answer, as if you are using Python 2.x and not inheriting from object when declaring custom Classes this solution may not work.

If you want to know if two instances of a class hold the same value you will have to implement the __eq__ function/method into the class definition. See SO answer Is there a way to check if two object contain the same values in each of their variables in python? for more details.

A: Simple, yet powerful =>  type(a) is type(b)
>>> class A:
...     pass
...
>>> a = A()
>>> b = A()
>>> a is b
False
>>> a == b
False
>>> type(a)
<class '__main__.A'>
>>> type(b)
<class '__main__.A'>
>>> type(a) is type(b)
True
>>> type(a) == type(b)
True
>>>


text:
Q: Trouble with converting an array of strings into an array of objects-JSON.parse I know this is not horribly difficult based on what I've been reading, but I keep getting an error msg. Generally something along the lines of an unexpected identifier.
https://gist.github.com/2869105
The gist shows all relevant info but I'll add the main js here.
- content_for :javascripts do
  - cache('search_autocomplete') do
    :javascript
      $(function(){
      var products = #{auto_complete_products.to_json};
        $("#keywords").autocomplete(products,{
        appendToElement: ".autocomplete"
          });
      });

This is how it is currently set up. I want to convert this array of strings to an array of objects, as I will be adding an image along with the current name when autocomplete occurs.
Rails 3.0.7
Mac OS X Lion
HAML/SASS
Note the second file in the gist is what I tried, but did not work.
Any help is greatly appreciated. Thanks!

A: I use the autocomplete feature this way: $('#keywords').autocomplete({source: array_or_hash_or_path}).
So I guess you need something like this:
$("#keywords").autocomplete({source: #{auto_complete_products.to_json}})

redpajama_set_name: RedPajamaStackExchange


text:
Q: Sieve of Eratosthenes, array is too large that memory out of bounds I want to get all prime numbers between 2 and pow(2, 32), but, since pow(2, 32) is to large that I can not declare that large array. The following are my codes
struct prims_n
{
    long long *prim;
    long long  size;
};

struct prims_n get_prim_number(long long number)
{
    long long count = 0;
    struct prims_n result;
    bool* a = new bool[number+1];
    memset(a, 1, number+1);
    for(long long i = 2; i <= sqrt(number); i ++)
    {
        if(a[i])
        {
            for(long long j = 2; j <= number/i; j ++)
            {
                a[i*j] = 0;
            }
        }
    }
    for (long long i = 2; i <= number; i++)
    {
        if (a[i]) count ++;
    }
    result.size = count;
    long long k = 0;
    result.prim = new long long[count];
    for (long long i = 2; i <= number; i++)
    {

        if (a[i] && k < count)
        {
            result.prim[k] = i;
            k ++;
        }
    }
    return result;
}

int main(int argc, char* argv[])
{

    struct  prims_n result = get_prim_number(pow(2, 26));
    cout << "prim numbers:" << result.size
        << " pow(2, 32)=" <<  pow(2, 32) << endl;
    return 0;
}

My OS is Windows and IDE is Visual Studio 2012.
The number pow(2, 32) is too large and the Sieve of Eratosthenes is not computational efficient. So, what should I do?

A: Easy way: build for 64 bit target and install a lot of RAM.
Or you could reduce the needed memory by not storing an int for each number but a bit only. std::vector<bool> or std::bitset<N> would be good containers to use. bitset requires the size to be known at compile time, vector allows it to change. BTW, vector<bool> is specialized for optimized memory usage.
Of course you do not really need to store all numbers 1..N because you know that the even numbers cannot be prime numbers. So you could use an array where for example the element at index i represents the information if 2*i+1 is a prime number.
Other option: only store the prime numbers, then for each new number to test try to divide it by the prime numbers you already calculated and stored (not all, only up to sqrt()).
Or work with windowed views into the sieve: store the known prime numbers in one container and allocate space for part of the complete buffer. If you are done with the buffer, then move to the next window.

A: Prime numbers are on the form (6K + 1) or (6K - 1),
Loop over k and check if 6K+1 or 6K-1 is not divisible by 2,3,5,7 to be prime


text: Q: Is it possible for any double integral in rectangular coordinate to be transformed into double integral in polar? For Example, I want to calculate the volume of solid within the region bounded by the x-axis, y=sinx and x = pi? In rectangular coordinate this double integral can be set up as $$\int_0^\pi\biggl({\int_0^{sin(x)}f(x,y)dy}\biggr)dx$$ How about in polar form?


text:
Q: Why Are My Images in the Three-Columns Row Not Lining Up Horiztonally? Trying to build up my first actual email template and I'm having some issues with the three-columns images lining up vertically above and below each other, not horizontally with each taking up 200px of 600px like I'm aiming for. I've combed through the code 3x now and have not found the issue, as at this point I'm following along with a tutorial and watching his work perfectly. What obvious thing am I missing? I apologize for the sloppy CSS formatting in advance, I'm trying to reduce the line count a bit since every line will need quotes around it for Yogmail. Thank you!
Edit: Just added the entire template so you can see that it's not till three-columns that the email template breaks, and from there even the footer or copy and pasted borders are stuck in the center. I seem to be having a similar problem with anything I build into this document after the three-columns section, but not before. I'm guessing maybe they're pulling CSS from a class I'm not intending it to? Everything above the section I posted works as intended, while everything below it is stuck in the center without the ability to display horizontally.
CSS:

Your Next Steps:

Your transaction is now live.

          Click Here

Ensure Another Transaction

Click here to ensure another crypto transaction as a buyer or seller with Crypto Ensure

Update Transaction

Click here to update an existing transaction

Contact Us

Click here to get in contact with our team if you have any questions or comments

Thank You!

Ending Message Goes Here

For more information regarding our service, see our documents page or reach out to us directly.

                               Documentation

Email Address

123 Chris Address, Louisville, KY 15222

A: Here's something you can try??

h1 {
  font-size:18px;
  padding:10px;
  }

.featured {
  max-width:200px;
  max-height:600px;
  box-shadow:0px 4px 12px 0px;
}

.featured-container {
  display:grid;
  grid-template-columns:auto auto auto;
  grid-gap:20px;

}

.featured > img {
  object-fit:cover;
  width:200px;
  height:200px;

}

.featured-info  {
  display:grid;
  grid-template-columns:auto auto;
  padding:5px;
  grid-gap:5px;
}

.featured-description {
  padding:5px;
  line-height:1;
}

#241 Blk 24 Mooncute, Cats California 95534

$1,000

Single Family Home

Beds:2

Bath:1

Description

This cat are the most beautiful animals on earth They are so cute please don't hurt them Because cats..

#241 Blk 24 Mooncute, Cats California 95534

$1,000

Single Family Home

 Beds:2

Bath:1

Description

This cat are the most beautiful animals on earth They are so cute please

#241 Blk 24 Mooncute, Cats California 95534

$1,000

Single Family Home

 Beds:2

Bath:1

Description

This cat are the most beautiful animals on earth They are so cute please don't


text:
Q: Project boolean value in aggregation framework Is it possible to project the boolean value of an operation with MongoDB's aggregation framework?
For example, given an input document like so:
{
  "id": 123,
  "data": [
    {
      "val": 1
    },
    {
      "val": 2
    },
    {
      "val": 3
    },
    {
      "val": 4
    },
    {
      "val": 5
    }
  ]
}

And the operation being $data.val > 3 I'd like to return:
{
  "result": [
    {
      "bool_val": 0
    },
    {
      "bool_val": 0
    },
    {
      "bool_val": 0
    },
    {
      "bool_val": 1
    },
    {
      "bool_val": 1
    }
  ],
  "ok": 1
}

This is what I came up with:
db.test.aggregate([{$match: {id: 123}},
                   {$unwind: "$data"},
                   {$project: {"bool_val": {"$data.val": {$gt: 3}}, _id: 0}}
                  ])

Which produces the following error:
aggregate failed: {
  "errmsg": "exception: invalid operator '$data.val'",
  "code": 15999,
  "ok": 0
}

A: You have to use $cond:
db.test.aggregate([
    {
        $match: {id: 123}
    },
    {
        $unwind: "$data"
    },
    {
        $project: {
            "bool_val": {
                $cond: [ {$gt: [ "$data.val", 3] }, 1, 0 ]
            },
            _id: 0
        }
    }
])

A: As a reference, the syntax for multiple conditions is:
db.test.aggregate([
    {
        $match: {id: 123}
    },
    {
        $unwind: "$data"
    },
    {
        $project: {
            "bool_val": { $cond: [ {$and: [{$gt: ["$data.val", 3]},
                                            {$lte: ["$data.val", 5]} ]
                        }, 1, 0]},
            _id: 0
        }
    }
])


text:
Q: matplotlib pylot Exception has occurred: ValueError When I used matplotlib to draw a picture, pylot's scatter method showed an exception.The exception information is as follows:
 Exception has occurred: ValueError
 'c' argument has 797 elements, which is not acceptable for use with 'x'
  with size 797, 'y' with size 797.
  File "D:\legao\xiaowy\plot.py", line 74, in <module>
  plt.scatter(x, y, c=color)

python verison is 3.6, matplotlib is 3.0.2.
I read the help documentation and found no specific errors. Please help me find out, thank you.
My code is as follows:
import math
import matplotlib.pyplot as plt

# data
traces = {
    'A': [(112, 36), (112, 45), (112, 52), (112, 54), (112, 63), (111, 73),
          (111, 86), (111, 91), (111, 97), (110, 105)],
    'B': [(119, 37), (120, 42), (121, 54), (121, 55), (123, 64), (124, 74),
          (125, 87), (127, 94), (125, 100), (126, 108)],
    'C': [(93, 23), (91, 27), (89, 31), (87, 36), (85, 42), (82, 49), (79,
          59), (74, 71), (70, 82), (62, 86), (61, 92), (55, 101)],
    'D': [(118, 30), (124, 83), (125, 90), (116, 101), (122, 100)],
    'E': [(77, 27), (75, 30), (73, 33), (70, 37), (67, 42), (63, 47), (59,
          53), (55, 59), (49, 67), (43, 75), (36, 85), (27, 92), (24, 97),
          (20, 102)],
    'F': [(119, 30), (120, 34), (120, 39), (122, 59), (123, 60), (124, 70),
          (125, 82), (127, 91), (126, 97), (128, 104)],
    'G': [(88, 37), (87, 41), (85, 48), (82, 55), (79, 63), (76, 74), (72,
          87), (67, 92), (65, 98), (60, 106)],
    'H': [(124, 35), (123, 40), (125, 45), (127, 59), (126, 59), (128, 67),
          (130, 78), (132, 88), (134, 93), (135, 99), (135, 107)],
    'I': [(98, 26), (97, 30), (96, 34), (94, 40), (92, 47), (90, 55), (87,
          64), (84, 77), (79, 87), (74, 93), (73, 102)],
    'J': [(123, 60), (125, 63), (125, 81), (127, 93), (126, 98), (125, 100)]
}

def get_vector(a, b):
    """Calculate vector (distance, angle in degrees) from point a to point
       b.

      Angle ranges from -180 to 180 degrees.
      Vector with angle 0 points straight down on the image.
      Values increase in clockwise direction.
    """
    dx = float(b[0] - a[0])
    dy = float(b[1] - a[1])

    distance = math.sqrt(dx**2 + dy**2)

    if dy > 0:
        angle = math.degrees(math.atan(-dx/dy))
    elif dy == 0:
        if dx < 0:
            angle = 90.0
        elif dx > 0:
            angle = -90.0
        else:
            angle = 0.0
    else:
        if dx < 0:
            angle = 180 - math.degrees(math.atan(dx/dy))
        elif dx > 0:
            angle = -180 - math.degrees(math.atan(dx/dy))
        else:
            angle = 180.0

    return distance, angle

def count_distance():
    '''Loop through the point data and calculate the result and color
    values'''

    x = []
    y = []
    c = []
    red_c = (255, 0, 0)
    blue_c = (0, 0, 255)
    for group1 in traces.keys():
        for index1, point1 in enumerate(traces[group1]):
            for group2 in traces.keys():
                for index2, point2 in enumerate(traces[group2]):
                    if point1 != point2 and index2 - index1 == 1:
                        t1, t2 = get_vector(point1, point2)
                        x.append(t2)
                        y.append(t1)
                        if group1 == group2:
                            c.append(blue_c)
                        else:
                            c.append(red_c)
    return x, y, c

if __name__ == '__main__':
    x, y, color = count_distance()
    # print(len(x))
    # exception here
    plt.scatter(x, y, c=color)
    plt.xlabel('Angle')
    plt.ylabel('Distance')
    plt.show()

First, I initialized a batch of motion data (traces), and then designed a function (get_vector) to calculate the distance between two points. The function count_distance statistics the distance of all points in the traces and the color that should be displayed. The code error is mainly caused by the color data.

A: Matplotlib expects RGB(A) colors to be specified in the range between 0.0 and 1.0, see more here. The fix below changes the colors within (0, 1). Additionally, it uses the set_color method on the artist object. Not entireley sure why your code shouldn't work. I'll have a look at it.
EDIT: it actually works out of the box without the set line, but the colorrs have to be within 0, 1!

import math
import matplotlib.pyplot as plt

# data
traces = {
    'A': [(112, 36), (112, 45), (112, 52), (112, 54), (112, 63), (111, 73),
          (111, 86), (111, 91), (111, 97), (110, 105)],
    'B': [(119, 37), (120, 42), (121, 54), (121, 55), (123, 64), (124, 74),
          (125, 87), (127, 94), (125, 100), (126, 108)],
    'C': [(93, 23), (91, 27), (89, 31), (87, 36), (85, 42), (82, 49), (79,
          59), (74, 71), (70, 82), (62, 86), (61, 92), (55, 101)],
    'D': [(118, 30), (124, 83), (125, 90), (116, 101), (122, 100)],
    'E': [(77, 27), (75, 30), (73, 33), (70, 37), (67, 42), (63, 47), (59,
          53), (55, 59), (49, 67), (43, 75), (36, 85), (27, 92), (24, 97),
          (20, 102)],
    'F': [(119, 30), (120, 34), (120, 39), (122, 59), (123, 60), (124, 70),
          (125, 82), (127, 91), (126, 97), (128, 104)],
    'G': [(88, 37), (87, 41), (85, 48), (82, 55), (79, 63), (76, 74), (72,
          87), (67, 92), (65, 98), (60, 106)],
    'H': [(124, 35), (123, 40), (125, 45), (127, 59), (126, 59), (128, 67),
          (130, 78), (132, 88), (134, 93), (135, 99), (135, 107)],
    'I': [(98, 26), (97, 30), (96, 34), (94, 40), (92, 47), (90, 55), (87,
          64), (84, 77), (79, 87), (74, 93), (73, 102)],
    'J': [(123, 60), (125, 63), (125, 81), (127, 93), (126, 98), (125, 100)]
}

def get_vector(a, b):
    """Calculate vector (distance, angle in degrees) from point a to point
       b.

      Angle ranges from -180 to 180 degrees.
      Vector with angle 0 points straight down on the image.
      Values increase in clockwise direction.
    """
    dx = float(b[0] - a[0])
    dy = float(b[1] - a[1])

    distance = math.sqrt(dx**2 + dy**2)

    if dy > 0:
        angle = math.degrees(math.atan(-dx/dy))
    elif dy == 0:
        if dx < 0:
            angle = 90.0
        elif dx > 0:
            angle = -90.0
        else:
            angle = 0.0
    else:
        if dx < 0:
            angle = 180 - math.degrees(math.atan(dx/dy))
        elif dx > 0:
            angle = -180 - math.degrees(math.atan(dx/dy))
        else:
            angle = 180.0

    return distance, angle

def count_distance():
    '''Loop through the point data and calculate the result and color
    values'''

    x = []
    y = []
    c = []
    red_c = (1, 0, 0)
    blue_c = (0, 0, 1)
    for group1 in traces.keys():
        for index1, point1 in enumerate(traces[group1]):
            for group2 in traces.keys():
                for index2, point2 in enumerate(traces[group2]):
                    if point1 != point2 and index2 - index1 == 1:
                        t1, t2 = get_vector(point1, point2)
                        x.append(t2)
                        y.append(t1)
                        if group1 == group2:
                            c.append(blue_c)
                        else:
                            c.append(red_c)
    return x, y, c

if __name__ == '__main__':
    x, y, color = count_distance()
    # print(len(x))
    # exception here
    h = plt.scatter(x, y, c = color)

    plt.xlabel('Angle')
    plt.ylabel('Distance')
    plt.show()

A: plt.scatter(x, y, c=color)

since you are using c=color, it is expecting a factor (categorical variable with certain levels only). The error says it all, Exception has occurred: ValueError
 'c' argument has 797 elements, which is not acceptable for use with 'x'
  with size 797, 'y' with size 797.
This means matplotlib will not allow to use a variable with equal level of x and y.
Just remove c= colors and try to plot it, it should work.


text:
Q: Selenium: unknown error: session deleted because of page crash I get the below error when I run my selenium code on chrome, but it works fine on firefox.
org.openqa.selenium.WebDriverException: unknown error: session deleted because of page crash
from unknown error: cannot determine loading status
from tab crashed
  (Session info: chrome=51.0.2704.84)
  (Driver info: chromedriver=2.20.353124 (035346203162d32c80f1dce587c8154a1efa0c3b),platform=Mac OS X 90.11.4 x86_64) (WARNING: The server did not provide any stacktrace information)
Command duration or timeout: 55.19 seconds
Build info: version: '2.53.0', revision: '35ae25b', time: '2016-03-15 17:00:58'
System info: host: 'mm-MacBook-Pro.local', ip: '90.0.0.5', os.name: 'Mac OS X', os.arch: 'x86_64', os.version: '10.11.4', java.version: '1.7.0_60'
Session ID: 2618f9cc58558217216fee85102d9a15
Driver info: org.openqa.selenium.chrome.ChromeDriver
Capabilities [{platform=MAC, acceptSslCerts=true, javascriptEnabled=true, browserName=chrome, chrome={userDataDir=/var/folders/qg/dycb2gvn04g715_18wlclrrw0000gn/T/.org.chromium.Chromium.CWvi9E}, rotatable=false, locationContextEnabled=true, mobileEmulationEnabled=false, version=51.0.2704.84, takesHeapSnapshot=true, cssSelectorsEnabled=true, databaseEnabled=false, handlesAlerts=true, browserConnectionEnabled=false, webStorageEnabled=true, nativeEvents=true, hasTouchScreen=false, applicationCacheEnabled=false, takesScreenshot=true}]

A: I had the same issue which was caused by a larger background image. Mounting /dev/shm to host system solved the issue.
Docker Compose
  chrome:
    image: selenium/node-chrome:3.14.0
    depends_on:
      - selenium-hub
    environment:
      - HUB_HOST=selenium-hub
      - HUB_PORT=4444
    volumes:
      - /dev/shm:/dev/shm

A: Are you running this using Docker? If so, you may have to increase your shared memory size e.g. shm_size: 1g


text:
Q: sql bulk insert never completes for 10 million records when using df.bulkCopyToSqlDB on databricks I am reading 1 GB of CSV file ( record count : 10 million, columns : 13 ) and trying to dump it into the SQL server. Below are the infra details :

*

*CSV file location : azure blob storage

*Code : Spark + Scala

*Cluster : Databricks
Size :

*Code Used to read the file and dump it :
val df = spark.read.format(fileparser_config("fileFormat").as[String]).option("header", fileparser_config("IsFirstRowHeader").toString).load(fileparser_config("FileName").as[String]).withColumn("_ID", monotonically_increasing_id)
val bulkCopyConfig = Config(Map(
        "url" -> connConfig("dataSource").as[String],
        "databaseName" -> connConfig("dbName").as[String],
        "user" -> connConfig("userName").as[String],
        "password" -> connConfig("password").as[String],
        "dbTable" -> tableName,
        "bulkCopyBatchSize" -> "500000",
        "bulkCopyTableLock" -> "true",
        "bulkCopyTimeout" -> "600"))
println(s" ${LocalDateTime.now()} ************ sql bulk insert start ************")
df.bulkCopyToSqlDB(bulkCopyConfig)
println(s" ${LocalDateTime.now()} ************ sql bulk insert end ************")

*Problem :
the cluster goes into a limbo and my job never completes. One time when it ran long enough it threw an error :
org.apache.spark.SparkException: Job aborted due to stage failure: Task 13 in stage 38.0 failed 4 times, most recent failure: Lost task 13.3 in stage 38.0 (TID 1532, 10.0.6.6, executor 4): com.microsoft.sqlserver.jdbc.SQLServerException: The connection is closed.\n\tat com.microsoft.sqlserver.jdbc.SQLServerException.makeFromDriverError(SQLServerException.java:227)\n\tat com.microsoft.sqlserver.jdbc.SQLServerConnection.checkClosed(SQLServerConnection.java:796)\n\tat com.microsoft.sqlserver.jdbc.SQLServ

*

*Cluster Event logs :

*

*Other observations :

*

*While the job runs for a very long time, the cluster is not completely unresponsive. I tried this by submitting more jobs in that same window. The job ran but took comparatively more time than usual( around 10x time)

*I tried increasing the worker nodes and the node type ( even chose 128 GB nodes ) but still the outcome was same.

*While the job was running, I tried checking the SQL table row count with nolock query. I ran this after 3-4 minutes while the job was running, it gave me around 2 million records in the table. But when I ran it again after 10 minutes, the query kept running forever and never returned any records.

*I have tried tweaking the bulkCopyBatchSize property but it hasnt helped much.

*I have tried to remove the sqlinsertion code and used an aggregation operation on the dataframe that i create from 1 GB file and the entire thing takes only 40-50 seconds, so the problem is only with sql driver/sql server.

A: I was facing the same issue.
Azure SQL Server - Standard S7: 800 DTUs
HDInsight - 6 node (2 D13V2 Head and 4 D13V2 Worker)
Data Size - 100GB Parquet with 1.7 billion rows.
Initially I was using "bulkCopyTimeout" as 600 seconds and I observed the loading was restarting after the timeout passed. Then I changed the timeout to a very large value and it worked fine.
For performance improvement:
Create columnstore Index in the target table and use
"bulkCopyBatchSize" = 1048576 (Load whole batch into row-groups maximum capacity and compresses them directly into the column-store rather than loading into delta store and compressing later)
"bulkCopyTableLock" = "false" (in order to allow parallelism)


text:
Q: ArcPy space in textfield I got a tiny script:
def calc(value):
 if value is '123':
    return 'ok'
 elif value is '12 3':
    return 'not_ok'
 else:
    return value

if the value is without spaces it works perfectly, but if there is a space in it, it just returns the value.
Where is my error? :)

A: Rather than use is try the == operator.


text:
Q: Wordpress: Permalinks for pages broken I'm using Wordpress 3.1.1 and recently reorganized my page (deleted and moved a lot of pages). Now I get 404-errors when accessing some pages (all posts and tags work fine).
I can disable the permalinks and then access all pages without problems. I can also rename the pages (e.g. contact --> contact1) and all links work again for the new names. However, if I rename them back, I get the same 404 error again. It seems like some kind of caching-problem. Any ideas how to fix it? Thanks!
My .htaccess for the root directory:
# BEGIN WordPress
<IfModule mod_rewrite.c>
RewriteEngine On
RewriteBase /
RewriteRule ^index\.php$ - [L]
RewriteCond %{REQUEST_FILENAME} !-f
RewriteCond %{REQUEST_FILENAME} !-d
RewriteRule . /index.php [L]
</IfModule>

# END WordPress

A: Try clearing your 'trash' can in Wordpress, annoyingly items in the trash area still use a permalink, and when accessing those links you'd get 404 message.
Also delete your htaccess file (if it has no additional settings in it), and the reset your permalink settings.
Ian.

A: I finally solved it. I realized, that there were some page names, that produced a server 404 and some, that don't. Then I took a closer look at my directory structure:
I access my blog from the root path (not the worpdrpess-directory which is located in it). So I can enter

www.myurl.com

instead of

www.myurl.com/wordpress

So far, so good. However, I had some files in my root directory, that had the same name as the page I was trying to access.
Eg. if there is a contact.abc (the extension doesn't matter) in the root folder, then getting

www.myurl.com/contact

will produce a 404-error. If I rename the file everything works fine. Hopefully, that will help others as well.


text:
Q: Script to periodically move files older than x to different drive? Background: My media center PC records TV programs to an external Drobo unit. Recording and watching two HD programs pushes the limit of the USB throughput though and playback stutters if there's any additional hard disk activity. Since FW800 seems to be impossible to get working reliably under Windows 7, I'm looking into recording TV unto the internal hard disk and moving the files periodically onto the Drobo. Which brings me to my question:
Can somebody give me a script or other method that will move files created more than a day ago and/or which aren't currently in use to a different drive/folder?

A: Windows 7 include a command line utility named robocopy for bulk file operations. You need to create a .cmd file using something like this:
robocopy "c:\Internal folder" "e:\External folder" /S /MOV /MINAGE:1 /IS /R:1 /W:1

and then create a scheduled task that runs that file every few hours.

A: Use find to find them and move to move them.

A: "You can try setting it as a scheduled task
Start>all programs>accessories>system tools>scheduled tasks"
http://www.computing.net/answers/windows-xp/how-do-i-auto-run-batch-file-every-60-minute/179011.html


text:
Q: VB.NET - Accumulating Numbers and Calculating Average I have started over and everything is working as intended except for 2 of the accumulating totals, the calculation is not working the way I need it to. Instead of adding previous sales to the total it tacks the new sale on the end...
for example: I input 1 Snowboard and 1 Snowboard with Boots, this works, 1 is shown in the summary for both Snowboards and Snowboards with Boots. However when I try to input again in order to keep a running total of sales I have a problem, I enter 1 Snowboard and 1 Snowboard with Boots, and the summaries show 11 rather than 2. Why does this happen?
   ' Declare module-level variables and constants.
Private SnowBoardsSold, BootsSold, SaleCount As Integer
Private ItemsSold As Integer
Private TotalSales As Decimal
Const SNOWBOARD_RATE As Decimal = 20D
Const BOOTS_RATE As Decimal = 30D

Private Sub CalculateButton_Click(ByVal sender As System.Object, ByVal e As System.EventArgs) Handles CalculateButton.Click
    ' Calculate the prices
    Dim SnowBoards, Boots As Integer
    Dim SnowBoardSale, BootsSale, ThisSale, AverageSalesEver As Decimal

    Try
        ' Convert the Snowboard input to numeric variable.
        SnowBoards = Integer.Parse(SnowboardsTextBox.Text)

        Try
            ' Convert Boots if Snowboard was successful.
            Boots = Integer.Parse(WithBootsTextBox.Text)
            ' Calculate values for sale.
            SnowBoardSale = SnowBoards * SNOWBOARD_RATE
            BootsSale = Boots * BOOTS_RATE
            ThisSale = SnowBoardSale + BootsSale

            ' Calculate summary values.
            TotalSales += ThisSale
            BootsSold += BootsSale
            SnowBoardsSold += SnowBoardSale
            SaleCount += 1
            AverageSalesEver = TotalSales / SaleCount

            ' Format and display prices for the sale.
            SnowBoardsPriceTextBox.Text = SnowBoardSale.ToString("c")
            BootsPriceTextBox.Text = BootsSale.ToString("c")
            TotalPriceTextBox.Text = ThisSale.ToString("c")

            ' Format and display values for the summary.
            SnowBoardRentalTextBox.Text += SnowBoards.ToString()
            BootsRentalTextBox.Text += Boots.ToString()
            TotalChargesTextBox.Text = TotalSales.ToString("c")
            AverageChargeTextBox.Text = AverageSalesEver.ToString("c")

        Catch BootsException As FormatException
            ' Handle a Boots exception.
            MessageBox.Show("Please enter numbers.", "Data Entry Error",
                            MessageBoxButtons.OK, MessageBoxIcon.Error)
            With WithBootsTextBox
                .Focus()
                .SelectAll()
            End With
        End Try

    Catch SnowBoardsException As FormatException
        ' Handle a SnowBoard exception.
        MessageBox.Show("Please enter numbers.", "Data Entry Error",
                        MessageBoxButtons.OK, MessageBoxIcon.Error)
        With SnowboardsTextBox
            .Focus()
            .SelectAll()
        End With

    Catch AnException As Exception
        'Handle any other exception.
        MessageBox.Show("Error: " & AnException.Message)
    End Try
End Sub

A: First, you might want to change the way you grab the numbers:
'Convert snowboard input value to numeric variable.
SnowboardInteger = Integer.Parse(SnowboardsTextBox.Text)

to:
Dim SnowboardInteger As Integer
If TryParse.Integer(SnowboardsTextBox.Text, SnowboardInteger) = False then
 ' if it parses, SnowboardInteger will have the value,
 'else the function returns false
     MessageBox.Show("Please enter numbers")
End if

Also, you are parsing the textboxes twice.  Once in the declaration then right after. This doesnt look right:
SnowboardSaleCountInteger += 1
WithBootsSaleCountInteger += 1
TotalSaleCountInteger += TotalChargesSumInteger   ' ?????
AverageChargeInteger = TotalChargesSumInteger / TotalSaleCountInteger

Adding 'charges' to a 'counter' doesnt seem right. If you want the avg shouldnt it be:
TotalSaleCountInteger = SnowboardSaleCountInteger + WithBootsSaleCountInteger

If you want fractions such as 'xx.yy' in the result, AverageChargeInteger should be a Double or Decimal, unless whole dollars are ok for the assignment.
If you need to accumulate from previous clicks, then you need to move some declarations out of the procedure up by SnowboardSumInteger, WithBootsSumInteger so they can accumulate.  As it is, WithBootsSaleCountInteger, TotalSaleCountInteger dont do anything and are always 1.  I wonder if as a 'SaleCounter' they shouldnt increase by the value in the textbox rather than just 1 (dont have the assignment in front of me).
One more thing you might need to do is here:
SnowboardPriceInteger = SnowboardInteger * SNOWBOARD_RENTAL_RATE
WithBootsPriceInteger = WithBootsInteger * WITH_BOOTS_RENTAL_RATE
TotalPriceInteger = SnowboardPriceInteger + WithBootsPriceInteger

Your constants are Decimal (SNOWBOARD_RENTAL_RATE) so, the result of the calc has to go into a Decimal var, but SnowboardPriceInteger and the other are not.  An integer cannot store a fractional result from the multiplication or division.
something like:
' sales accumulators
 Private TotalSales As Decimal = 0
 Private ItemsSold As Integer = 0

Click Event:
' this sale:
Dim Snowboards As Integer
Dim Boots As Integer

' get the values from the text boxes, then:
Dim SnowBoardSale As Decimal = (SnowBoards * SnowBoardRate)
Dim BootsSale As Decimal = (Boots * BootsRate)
Dim ThisSale As Decimal =  SnowBoardSale  + BootsSale

 ' update accumulators
TotalSales += ThisSale
ItemsSold += (Boots + Snowboards)

' calc the average
Dim AverageSalesEver AS Decimal = TotalSales  / ItemsSold

' Display results in textboxes
'(this exercise is left to the student  ;)  )

HTH
I think you just confused yourself with too many variables and ones left over from old attempts.


text:
Q: How do I layout an app that shifts between different "modes" programmatically? I'd like to make an app with different views for different "modes" with some shared code (there's some elements I want always the same, and the background will be changing between different views). I'm going to manage the shifts between those views based off of time. What's the best way to layout the views?
I looked at doing a tab view, but it seems a bit unnatural since the tabbar doesn't easily hide. I can also do a custom container (my original thought), but it seems like it would be good to stay within the "standard" iOS views if possible.
Does doing a custom view seem sound / is there a better way that I missed?

A: I would have 2 versions of -layoutSubviews of the parent view. Something like:
-(void)layoutSubviews
{
    if ( self.mode == 0 )
    {
        [ self layoutMode0 ] ;
    }
    else if ( self.mode == 1 )
    {
        [ self layoutMode1 ] ;
    }
}

Your layout code can also show/hide certain views or set background images etc. In your code to switch modes, call -setNeedsLayout... something like this:
-(void)setMode:(enum Modes)newMode
{
    _mode = newMode ;
    [ self setNeedsLayout ] ;
}

If you want the mode switch to animate, you can do something more like this:
-(void)setMode:(enum Mode)newMode animated:(BOOL)animated
{
    _mode = newMode ;
    if ( animated )
    {
        [ UIView animateWithDuration:0.25 animations:^{
            [ self layoutSubviews ] ;
        } ]
    }
    else
    {
        [ self setNeedsLayout ] ;
    }
}

with your ordinary setter -setMode: looking like this:
-(void)setMode:(enum Mode)newMode
{
    [ self setMode:newMode animated:NO ] ;
}

A: You could also consider using UINavigationController if your modes are stack based. The navigation bar can be hidden easily (set hidesNavigationBar to YES). When you push or pop controllers corresponding to modes you might want to set animated to NO, unless the slide in/slide out animation suits you.


text:
Q: How to create a list with routable items with React-router? I'd like create a details view inside a list element
For example:

*

*Items: /items

item 1

item 2

item 3

*ItemPreview: /list/2

item 1

<ItemPreview>more details for item 2</ItemPreview>

item 3

My idea is to pass the childrens coming from router down to the Item component ... but there is too much of hassle passing all the item specific values.
But is there a nice common way of doing it?

A: I've written a JsFiddle that demonstrates a list with routable items. It uses the Navigation router instead of the React Router but I hope you're open to that. You can see that I pass the list of items into the Items component and the selected Item down to the Item component. The Item component is a Hyperlink, built using the router's RefreshLink. Clicking the Hyperlink passes the selected item number down and the Item component changes the selected item's display. If you've got any questions about the code, please let me know.
var {StateNavigator} = Navigation;
var {RefreshLink} = NavigationReact;

var Items = ({items, id, stateNavigator}) => (

    {items.map((item, i) => (
      <Item
        item={item}
        id={i}
        selected={i === id}
        key={i}
        stateNavigator={stateNavigator} />
    ))}

);

var Item = ({item, id, selected, stateNavigator}) => (

    <RefreshLink
      navigationData={{id: id}}
      disableActive={true}
      stateNavigator={stateNavigator}>
      {!selected ? item : 'more details for ' + item}
    </RefreshLink>

);

var stateNavigator = new StateNavigator([
  {key: 'items', route: '{id?}'}
]);

stateNavigator.states.items.navigated = (data) => {
  ReactDOM.render(
    <Items
      items={['item 1', 'item 2', 'item 3']}
      id={data.id}
      stateNavigator={stateNavigator} />,
    document.getElementById('container')
  );
};

stateNavigator.start();


text:
Q: How to convert WebLogicJtaTransactionManager to tomcat supported TransactionManager As of now we are using weblogic server. So we are using webLogicJtaTransactionManager as shown below.
<bean id="transaction manager" class="org.springframework.transaction.jta.WebLogicJtaTransactionManager" >
<parameter="transactionManagerName" value="javax.transaction.TransactionManger" />
</bean>

Now i want to change above XML to tomcat supported transactionManger. Can you please help how to change this. I tried to deployee in tomcat server with out changing this i am getting below error.
org.springframework.beans.factory.BeanCreationException: Error creating bean with name 'transactionManager' defined in class path resource [applicationContext.xml]: Invocation of init method failed; nested exception is org.springframework.transaction.TransactionSystemException: Could not initialize WebLogicJtaTransactionManager because WebLogic API classes are not available; nested exception is java.lang.ClassNotFoundException: weblogic.transaction.TransactionHelper

A: For example DataSourceTransactionManager is platform agnostic.
In java config:
import org.springframework.transaction.PlatformTransactionManager;
import org.springframework.jdbc.datasource.DataSourceTransactionManager;
import javax.sql.DataSource;

// snip other stuff

@Bean
public PlatformTransactionManager transactionManager() {
    return new DataSourceTransactionManager(dataSource());
}
@Bean
public DataSource dataSource() {
    // create and return a new JDBC DataSource ...
}

in xml config:
<bean id="transactionManager"
    class="org.springframework.jdbc.datasource.DataSourceTransactionManager">
    <property name="dataSource" ref="datasource" />
</bean>

Your weblogic example has JTA-enabled transaction manager, so it supports distributed transactions, and there is a cross-platform JTA transaction manager in Spring as well, JtaTransactionManager. However since Tomcat doesn't support JTA out of the box, you couldn't use that - using the example above you'll get transactions for your datasource only.


text:
Q: type mapping between cbor (javascript) and c++ I don't know to which C++ types to map the following cbor (javascript) types:

*

*null

*undefined
The other way around, I have not idea to which cbor (javascript) type to map the C++ void type.

A: I think undefined should be mapped to void, because:
function a() {}
console.log(a())

results in:
undefined

This leaves ::std::nullptr_t for the null type.

A: It's not uncommon in C++ to define empty structs for this purpose, e.g. struct null_type{} and struct undefined_type{}.


text:
Q: Groovy Attribute should have type 'java.lang.Integer', but found type 'java.lang.Object' I have the following JUnit test:
public class JavaTest {

    final int value = 2;

    @Test
    @Repeat(times = value)
    public void test() {
        fail("Not yet implemented");
    }
}

The @Repeat annotation comes from easytest-core, and the exact definition is here.
When I compile this as java source everything builds (and runs) fine. When I compile the exact same thing as groovy source, I get:

Groovy:Attribute 'times' should have type 'java.lang.Integer'; but found type 'java.lang.Object' in @org.easetech.easytest.annotation.Repeat  GroovyTest.groovy

After searching the internets, I found a few similar discussions on SO and jira.codehaus, but those deal with String - GString problems, so the solutions do not work for me.
How can I fix this?
Updates:

*

*java.version=1.7.0_76

*groovy.version=2.3.7

A: Think you're bumping into the fact groovyc doesn't treat final variables as inline constants like javac does
I tried changing your int variable like this:
final Integer value = Integer.valueOf(2).intValue()

which prevents the variable from being treated as an inline constant. After that change I get a compile error from the @Repeat annotation:

Expected Integer.valueOf(2).intValue() to be an inline constant

It looks like there's some acknowledgement of the inconsistency here in a Groovy JIRA: https://issues.apache.org/jira/browse/GROOVY-1628
There's also some further discussion here in this SO thread:
Does it make sense to mark variable as final in groovy?
It doesn't look like you're going to be able to get groovy to match the Java behavior for this scenario.


text:
Q: How to implement non-blocking infinite loop in Python I have an infinite loop that reads video frames from webcam and each frame will go through a complex function that requires high computing power. So when displaying the frames the program will feel kinda laggy because of the blocking code.
What I intend to do now is,

*

*only collect the first few frames when target object appears

*Put them into a separate thread to avoid code blocking.

I've measure the number of frames captured by webcam every second, that is ~28 frames. So every second the while loop will only collect the first 5 frame and process all of them in another thread, and return the result after all 5 functions are completed.
I've tried to use 'Pool' and 'Queue' but couldn't get it to work, the loop still gets blocked. The code below vaguely represents how my program look like now, will edit it when I get home, using phone to post now.
def detect(frame):
    # detect target object from images
    pass

def nn(frame):
    # some heavy processing code
    pass

count = 0
stack = []

while True:
    frame = cv2.imread(0)

    detected = detect(frame)

    # stop collecting images when collected 5
    if detected and count <= 5:
        stack.append(frame)
        count += 1

    # start processing
    if len(stack) == 5:
        p = Pool(4)
        results = p.map(nn, frame)
        p.close()
        p.join()

        # reset
        stack = []
        count = 0

Am I getting the concept right? Or I need to do something else like coroutine?

A: I solved this using rq.
A simple message queue for python.
First, the implementation of the method you need to run asynchronously.
It will run your nn function, in this case,
then, set a simple configuration for the message queue,
I use connectionPool from the redis package.
Basically, you send out the whole task to a parallel process executed by a rq worker.
def nn(frame):
    # some heavy processing code
    pass

def asynch_call(frame):
   p = Pool(4)
   results = p.map(nn, frame)
   p.close()
   p.join()

pool = redis.ConnectionPool(
  host=HOST,
  port=PORT,
  password=PASS,
  db=0)

r = redis.Redis(connection_pool=pool)
q = Queue('nn_queue', connection=r)

count = 0
stack = []

while True:
    frame = cv2.imread(0)

    detected = detect(frame)

    # stop collecting images when collected 5
    if detected and count <= 5:
        stack.append(frame)
        count += 1

    # start processing
    if len(stack) == 5:

        job = q.enqueue(asynch_call, frame, timeout=any_long_timeout )

        if job.status=='queued':
            print("Job submission ok")

            # reset
            stack = []
            count = 0

In order to start a worker which will handle the asynchronous calls, you have a couple of options, create your own code for a Worker or just run the following command in a separate terminal:
rq worker nn_queue

See the command with the queue name used above to send the job.
I hope it helps.


text:
Q: R: rollapplyr and lm factor error: Does rollapplyr change variable class? This question builds upon a previous one which was nicely answered for me here.
R: Grouped rolling window linear regression with rollapply and ddply
Wouldn't you know that the code doesn't quite work when extended to the real data rather than the example data?
I have a somewhat large dataset with the following characteristics.
str(T0_satData_reduced)
'data.frame':   45537 obs. of  5 variables:
 $ date   : POSIXct, format: "2014-11-17 08:47:35" "2014-11-17 08:47:36" "2014-11-17 08:47:37" ...
 $ trial  : Factor w/ 5 levels "1","2","3","4",..: 1 1 1 1 1 1 1 1 1 1 ...
 $ vial   : Factor w/ 4 levels "1","2","3","4": 1 1 1 1 1 1 1 1 1 1 ...
 $ O2sat  : num  95.1 95.1 95.1 95.1 95 95.1 95.1 95.2 95.1 95 ...
 $ elapsed: num  20 20 20.1 20.1 20.1 ...

The previous question dealt with the desire to apply a rolling regression of O2sat as a function of elapsed, but grouping the regressions by the factors trial and vial.
The following code is drawn from the answer to my previous question (simply modified for the complete dataset rather than the practice one)
rolled <- function(df) {
   rollapplyr(df, width = 600, function(m) {
   coef(lm(formula = O2sat ~ elapsed, data = as.data.frame(m)))
   }, by = 60, by.column = FALSE)
 }

T0_slopes <- ddply(T0_satData_reduced, .(trial,vial), function(d) rolled(d))

However, when I run this code I get a series of errors or warnings (first two here).
Warning messages:
1: In model.response(mf, "numeric") :
using type = "numeric" with a factor response will be ignored
2: In Ops.factor(y, z$residuals) : - not meaningful for factors

I'm not sure where this error comes from as I have shown both elapsed and O2sat are numeric, so I am not regressing on factors. However, if I force them both to be numeric within the rolled function above like this.
...
coef(lm(formula = as.numeric(O2sat) ~ as.numeric(elapsed), data = as.data.frame(m)))
...

I no longer get the errors, however, I don't know why this would solve the error. Additionally, the resulting regressions appear suspect because the intercept terms seem inappropriately small.
Any thoughts on why I am getting these errors and why using as.numeric seems to eliminate the errors (if potentially still providing inappropriate regression terms)?
Thank you

A: rollapply passes a matrix to the function so only pass the numeric columns.  Using rolled from my prior answer and the setup in that question:
do.call("rbind", by(dat[c("x", "y")], dat[c("w", "z")], rolled))

Added
Another way to do it is to perform the rollapply over the row indexes instead of over the data frame itself.  In this example we have also added the conditioning variables as extra output columns:
rolli <- function(ix) {
   data.frame(coef = rollapplyr(ix, width = 6, function(ix) {
         coef(lm(y ~ x, data = dat, subset = ix))[2]
      }, by = 3), w = dat$w[ix][1], z = dat$z[ix][1])
}
do.call("rbind", by(1:nrow(dat), dat[c("w", "z")], rolli))


text:
Q: Case (or switch) in a for loop or for loop in a case (or switch)? Can it be known in general whether or not placing a case within a for loop will result in bad assembly. I'm interested mainly in Delphi, but this is an interesting programming question, both in terms of style and performance.
Here are my codez!

  case ResultList.CompareType of
  TextCompareType:
    begin
      LastGoodIndex := -1;
      for I := 1 to ResultList.Count -1 do
      if (LastGoodIndex = -1) and (not ResultList[I].Indeterminate) then
        LastGoodIndex := I
      else if not ResultList[I].Indeterminate then
      begin
        if (StrComp(ResultList[LastGoodIndex].ResultAsText,
                     ResultList[I].ResultAsText) > 0)
            and (Result  FalseEval) then
          Result := TrueEval
        else
          Result := FalseEval;

        LastGoodIndex := I;
      end;
    end;
  end;
  NumericCompareType:
  begin
    //Same as above with a numeric comparison
  end;
  DateCompareType:
  begin
    //Same as above with a date comparison
  end;
  BooleanCompareType:
  begin
    //Same as above with a boolean comparison
  end;

alternatively I could write

    begin
      LastGoodIndex := -1;
      for I := 1 to ResultList.Count -1 do
      if (LastGoodIndex = -1) and (not ResultList[I].Indeterminate) then
        LastGoodIndex := I
      else if not ResultList[I].Indeterminate then
      begin
      case ResultList.CompareType of
      TextCompareType:
      begin
         if (StrComp(ResultList[LastGoodIndex].ResultAsText,
                     ResultList[I].ResultAsText) > 0)
            and (Result  FalseEval) then
           Result := TrueEval
         else
           Result := FalseEval;
         LastGoodIndex := I;
      end;
      NumericCompareType:
      begin
       //Same as above with a numeric comparison
      end;
      DateCompareType:
      begin
       //Same as above with a date comparison
      end;
     BooleanCompareType:
     begin
       //Same as above with a boolean comparison
     end;

   end;
  end;
 end;

I don't like the second way because I'm asking a question I know the answer to in a for loop and I don't like the first way because I'm repeating the code I use to figure out which of my objects contain valid information.
Perhaps there is a design pattern someone could suggest that would circumvent this all together.

A: In general, there is no way to know what assembly-language output will be generated for particular programming-language constructs.  Every compiler is different.  Even for a particular compiler, every application will be different, and the compiler will have different optimization strategies available to it.
If you are really worried about it, the easiest thing to do is compile the program and see what it generates.  Play around with code and optimization settings until it looks how you want it to.  (Or write assembly by hand.)
The common advice is to just write the clearest code you can, and don't worry about tweaking performance unless you really need to.

A: Why not using subclasses?
This saves the use of the case statement.
TComparer = class
protected
  function Compare(const AItem1, AItem2: TItem): Boolean; virtual; abstract;
public
  procedure DoCompare(ResultList: ...);
end;

TTextComparer = class (TComparer)
protected
  function Compare(const AItem1, AItem2: TItem): Boolean; override;
end;

procedure TComparer.DoCompare(ResultList: ...);
var
  LastGoodIndex, I : Integer;
begin
  LastGoodIndex := -1;
  for I := 1 to ResultList.Count -1 do
  if (LastGoodIndex = -1) and (not ResultList[I].Indeterminate) then
    LastGoodIndex := I
  else if not ResultList[I].Indeterminate then begin
    if Compare(ResultList[LastGoodIndex], ResultList[I]) then
      Result := TrueEval
    else
      Result := FalseEval;
  end;
end;

function TTextComparer.Compare(const AItem1, AItem2: TItem): Boolean;
begin
  Result := StrComp(ResultList[LastGoodIndex].ResultAsText,
    ResultList[I].ResultAsText) > 0)
end;

A: I suspect that it's more efficient to use a lambda or closure or even just a function reference.  My Pascal's rusted right out, so my example is perl:
my %type = (
            TextCompareType => sub { $_[0] lt $_[1] },
            NumericCompareType => sub { $_[0] < $_[1] },
            DateCompareType => sub { ... },
            BooleanCompareType => sub { ... },
           );

for (my $i = 1; $i <= $#list; ++$i)
{
    if ( $type{$ResultList{CompareType}}->($list[$i-1], $list[$i]) )
    {
        $result = 1; # ?
    }
}

I'm not really following most of your code, but I think I've captured the essence of the question without fully capturing the code.
Another solution is to create comparator objects as subclasses off a base comparator class, and then call the object's compare function, but you do mention trying to stay structured instead of OO.


text:
Q: Validating XML against XSD is slow for long strings if maxLength and pattern restrictions are defined We have the following simple type defined in our xsd:
<xsd:simpleType name="SimpleText255NotBlankType">
        <xsd:annotation>
            <xsd:documentation xml:lang="en">String of maximum 255 characters, not blank</xsd:documentation>
        </xsd:annotation>
        <xsd:restriction base="xsd:string">
            <xsd:minLength value="1"/>
            <xsd:maxLength value="255"/>
            <xsd:pattern value=".*[^\s].*"/>
        </xsd:restriction>
</xsd:simpleType>

The problem is when a really long string (ca. 1000000 characters) is provided as a value in the input xml, we would assume that it is regarded invalid quickly because of the length. Actually the validation takes several minutes since the regex gets evaluated before the maxLength restriction.
We found a workaround for the issue if we define the simpleType this way:
     <xsd:simpleType name="SimpleText255Type">
        <xsd:annotation>
            <xsd:documentation xml:lang="en">String of maximum 255 characters</xsd:documentation>
        </xsd:annotation>
        <xsd:restriction base="xsd:string">
            <xsd:minLength value="1"/>
            <xsd:maxLength value="255"/>
            <xsd:pattern value=".{1,255}"/>
        </xsd:restriction>
    </xsd:simpleType>
    <xsd:simpleType name="SimpleText255NotBlankType">
        <xsd:annotation>
            <xsd:documentation xml:lang="en">String of maximum 255 characters, not blank</xsd:documentation>
        </xsd:annotation>
        <xsd:restriction base="SimpleText255Type">
            <xsd:pattern value=".*[^\s].*"/>
        </xsd:restriction>
    </xsd:simpleType>

The workaround only works because the Xerces implementation of the XSSimpleType builds a Vector of the regex patterns and the .{1,255} pattern will be evaluated first and it fails relatively quickly thus the time consuming second regex wont be checked.
Has anyone run into the same problem and found a solution, which doesn't depends on the implementation of xsd validation? Or is there any way to order the validation of xsd:restriction-s in jaxb (so that maxLength could be validated before checking the pattern)?
We created an example application on github:
https://github.com/petmaark/xsd-pattern-validation-test

A: Xerces2 supports XSD 1.1. Unfortunately, that version is not in the official maven central repository. You can use a third-party repository(You will need icu4j as well). If it is not a viable solution for you, you can download the official stable version from the Xerces website(Xerces2 Java 2.12.0 (XML Schema 1.1)), and install it to your local maven repository.
      <!-- https://mvnrepository.com/artifact/org.opengis.cite.xerces/xercesImpl-xsd11 -->
        <dependency>
            <groupId>org.opengis.cite.xerces</groupId>
            <artifactId>xercesImpl-xsd11</artifactId>
            <version>2.12-beta-r1667115</version>
        </dependency>

        <!--Needed for string-length -->
        <!-- https://mvnrepository.com/artifact/com.ibm.icu/icu4j -->
        <dependency>
            <groupId>com.ibm.icu</groupId>
            <artifactId>icu4j</artifactId>
            <version>4.6</version>
        </dependency>

You will need to replace your schema version as well.
SchemaFactory sf = SchemaFactory.newInstance("http://www.w3.org/XML/XMLSchema/v1.1");

You can use assertions in XSD 1.1(there are other useful new features in XSD 1.1 as well, that you can benefit from).  Now you can specify the evaluation order of your validation rules.
<xs:restriction base="xs:string">
            <!--<xs:minLength value="1"/>
            <xs:maxLength value="255"/>
            <xs:pattern value=".*[^\s].*"/>-->

            <xs:assertion test="(string-length($value) >= 1) and (string-length($value) <= 255) and (matches($value, '.*[^\s].*')) "/>

</xs:restriction>

I hope this is a viable solution and I could help you!


text:
Q: Method overloading is not working while using superclass reference class Communication {
    public void greet() {
        System.out.println("Greetings..");
    }

    public void greet(String custom) {
        System.out.println(custom);
    }
}

public class Human extends Communication {
    public void greet(int n) { //overloading
        for (int i = 1; i <= n; i++)
            System.out.println(i + " Hey..");
    }

    public void greet(String name) { //overriding
        System.out.println("Hi " + name);
    }

    public static void main(String[] args) {

        Communication communication = new Communication();
        communication.greet();
        communication.greet("Hello World");

        Communication humanCommunication = new Human();
        // humanCommunication.greet(2); is not working why?
        humanCommunication.greet("Sagar");

        Human human = new Human();
        human.greet();
        human.greet(2);

    }

}

Error:
Exception in thread "main" java.lang.Error: Unresolved compilation problem:
The method greet(String) in the type Communication is not applicable for the arguments (int).
I have overloaded the method in Human class and able to invoke while using Human object directly
but while assigning Human object to Communication reference Overridden method is working properly
and Overloading is not supporting Why?
Can any body help me to understand this behaviour?
Thanks in advance

A: The compiler has no way of knowing which run time object will be assigned to a reference.
For example you could re-write your above code as,
boolean creatHuman = true;
Communication humanCommunication;
if(createHuman)
  humanCommunication = new Human();
else
  humanCommunication = new Communication ();

The compiler can only tell for certain that humanCommunication will be of type Communication and so allows only methods available in type Communication
If you need to use methods available in Human you would need to tell the compiler that the Reference is a Human
Two ways you could do it,

*

*Declare humanCommunication as type Human

*Cast during the call to the method available only in Human (). In case the dynamic type of the reference humanCommunication is not Human a CastClassException will be thrown
((Human) humanCommunication).greet(2); --> should work

A: Finally I got the answer as my friend said that this is the difference between Compile-time polymorphism vs run-time polymorphism
1)Method overloading is a compile time Polymorphism.
[Reference type determines which overloaded version (based
on declared argument types) is selected. Happens at compile
time. The actual method that's invoked is still a virtual method
invocation that happens at runtime, but the compiler will
already know the signature of the method to be invoked. So at
runtime, the argument match will already have been nailed
down, just not the class in which the method lives.]
2)Method overriding is a run time Polymorphism.
[Object type (in other
words, the type of the
actual instance on the
heap) determines which
method is selected.
Happens at runtime.]
Thank you for comments :)


text:
Q: Difference of definite integrals inequality Could you help me how prove that for any $\mathcal{C}^1$ function we have:
$$\left|\int_{a} ^{\frac{a+b}{2}}f(x) d x - \int_{\frac{a+b}{2}} ^bf(x)dx\right| \le \frac{(b-a)^2}{4} \cdot \max _{x \in [a,b]} |f'(x)|.$$

A: Hint: Using mean value theorem for $$
\left|\int_{a} ^{\frac{a+b}{2}}f(x) d x - \int_{\frac{a+b}{2}} ^bf(x)dx\right|
=\left|\int_{a} ^{\frac{a+b}{2}}\big[f(x)-f(x+\frac{b-a}{2})\big] d x \right|.
$$


text:
Q: Bash script to sleep at given CPU temperature ~ update for 16.04 This is a radically updated version of the question.
I have to update this because this question is flagged as duplicate of this one, while this has no valid answer anymore.

*

*Initial version of this question, which had the 11.04 tag:
I am new to scripting and linux, my comp gets too hot sometimes and I want to make a script to detect temp1 and if it's over 65 C, it must put it to sleep. I have a diffuculty at comparing values in the script, I couldn't manage to define figures correctly, would anybody fix it please? Here is my stab at it so far
#!/bin/bash

max=65

val=$   sensors | grep '^temp1:' | sed -e 's/.*: \+\([+-][0-9.]\+\)°C.*$/0\1/'

while true; do
    if [[ "$val" > "$max" ]]; then
        sudo /etc/acpi/sleep.sh force
        sleep 1
    else
        sleep 10
    fi
    clear
    sensors
done

The above got an answer with  a script that according to the comments was at some point updated to work in 14.04:
 #!/bin/bash

 while true; do
    val=$(sensors | awk '/temp1/ {print $2}')
    max="+75.0"
    if [[ "$val" > "$max" ]]; then
        dbus-send --system --print-reply --dest="org.freedesktop.UPower" /org/freedesktop/UPower org.freedesktop.UPower.Suspend
    fi
    sleep 10
    clear
    sensors
 done
 exit 0

As indicated in the linked question, the above script doesn't work in 16.04.
That question got an answer with a simplistically modified version of the script:
 #!/bin/bash

 while true; do
    val=$(sensors | awk '/temp1/ {print $2}')
    max="+75.0"
    if [[ "$val" > "$max" ]]; then
        systemctl suspend
    fi
    clear
    sensors
 done
 exit 0

But while it does the job (the system goes to sleep when going above 75), it takes more CPU power than expected and pushes the temperature up while running up to 10 degrees celsius; this is more useful, more cooling when not running!
I don't know if the problem is with the initial 11.04 script or with the last change but this needs a fresh answer for 16.04.

A: Introduction
In order to facilitate both pre-systemd and post-systemd switch users, I've written a script that will take appropriate method of suspending based on your os version number. Essentially it does the same thing that OP's updated script does, except it forces to suspend despite inhibitors with -i flag. There are multiple considerations and improvements that can be done to the script, but as for right now this version does 90% of the job.
I tested it briefly on 16.04 LTS, works perfectly fine. In future I might rewrite this in Python just because I can or upon user request.
Script  Source
#!/usr/bin/env bash

suspend_system(){

    os_version=$(awk -F'["=]' '/VERSION_ID/{print substr($3,1,2)}' /etc/os-release)
    if [ $os_version -ge 15   ]
    then
        systemctl suspend -i
        # Alternative way is to call login manager method via dbus
        # qdbus --system org.freedesktop.login1 /org/freedesktop/login1 \
        #       org.freedesktop.login1.Manager.Suspend True

    else
        dbus-send --system --print-reply --dest="org.freedesktop.UPower"\
                  /org/freedesktop/UPower org.freedesktop.UPower.Suspend
    fi

}

is_critical_temp(){
    local temp=$(sensors | awk '/temp1/ {print substr($2,2,2)}')
    if [ $temp -gt 75  ]
    then
        return 0
    else
        return 1
    fi
}

main(){

    while true
    do
        if is_critical_temp
        then
           # optional dialog if running from GUI, not necessary if running form /etc/rc.local
           #zenity --info --text "Reached critical temperature. Suspending in 10 seconds" &
           sleep 10
           suspend_system
        fi
    sleep 3
    done
}
main "$@"

Alternative approach
A while back, I found pm-suspend utility, from pm-utils package. This program works regardless of the OS version. The small disadvantage is that it requires root access, but it is easy to get around of that inconvenience.
What I personally would do is the following:

*

*sudo apt-get install pm-utils

*sudo visudo and add yourusername ALL = NOPASSWD: /usr/sbin/pm-suspend at the end of the file.

*edit your script to call sudo pm-suspend instead of the dbus command.

Suspending an Ubuntu machine in general
You've requested that answers draw upon credible sources. In fact, Ask Ubuntu does have canonical post about suspending from command-line: How can I suspend/hibernate from command line? Depending on the approach and level of permissions you want your script to have, there's multiple ways to skin a cat there. Some work better than others. In my answer I provided the dbus and systemctl approach, since those work with screen-locking as well. If you write to /sys/class/power/state, it won't lock the screen, although it is possible to get around that with some scripting magic. For now, I think, the better approach is to simply determine the OS version and select appropriate method as in my script, or use pm-suspend alternative.

A: On my system every time sensors is run there is a stutter in video streaming. Having this happen every 10 seconds or however often proposed script is run would drive me bat crazy. A better solution to suspend would be using Intel's thermald and Powerclamp to slow down the CPU in order to reduce heat. I've written this answer for another question (Stop cpu from overheating) and am copying here for convenience.
Additionally the above script relies on temp1 which is often corrupted on my Ubuntu 16.04 and only temp3 is 100% reliable which doesn't show up on sensors. ie:
$ cat /sys/class/thermal/thermal_zone*/temp
27800
29800
58000

and from sensors:
acpitz-virtual-0
Adapter: Virtual device
temp1:        +27.8°C  (crit = +106.0°C)
temp2:        +29.8°C  (crit = +106.0°C)

This happens after suspend/resume. The REAL temperature is +58.0°C but is falsely reported as +27.8°C after resuming. So the heat protection would only work once to suspend and never work again until a reboot. So the system would hit critical (+106.0°C) at which point a hard power off is performed and data can be corrupted.
So here's my recommended solution to prevent overheating and utilizing CPU slow down rather than outright system suspend.
Slow down CPU to reduce heat
This works for Ubuntu 16.04+ with Intel Sandy Bridge and newer processors.
From (wiki.debian.org -thermald) is Debian's (used by Ubuntu) write up about thermald, a Linux daemon for cooling tablets and laptops.  Once the system temperature reaches a certain threshold, the Linux daemon activates various cooling methods to cool the system.
Linux thermal daemon (thermald) monitors and controls temperature in laptops, tablets PC with the latest Intel sandy bridge and latest Intel CPU releases. Once the system temperature reaches a certain threshold, the Linux daemon activates various cooling methods to try to cool the system.
It operates in two modes:
Zero Configuration Mode

*

*For most users, this should be enough to bring the CPU temperature of the system under control. This uses DTS temperature sensor and uses Intel P state driver, Power clamp driver, Running Average Power Limit control and cpufreq as cooling methods.

User defined configuration mode

*

*This allows ACPI style configuration in a thermal XML configuration file. This can be used to fix the buggy ACPI configuration or fine tune by adding more sensors and cooling devices. This is a first step in implementing a close loop thermal control in user mode and can be enhanced based on community feedback and suggestions.

How to install
apt-get install thermald

Intel Powerclamp
Intel's Powerclamp driver is defined here (kernel.org - Intel Power Clamp.txt) and is part of thermald described above. A direct quote for Powerclamp from the link:

Consider the situation where a system's power consumption must be
  reduced at runtime, due to power budget, thermal constraint, or noise
  level, and where active cooling is not preferred. Software managed
  passive power reduction must be performed to prevent the hardware
  actions that are designed for catastrophic scenarios.
Currently, P-states, T-states (clock modulation), and CPU offlining
  are used for CPU throttling.
On Intel CPUs, C-states provide effective power reduction, but so far
  they're only used opportunistically, based on workload. With the
  development of intel_powerclamp driver, the method of synchronizing
  idle injection across all online CPU threads was introduced. The goal
  is to achieve forced and controllable C-state residency.
Test/Analysis has been made in the areas of power, performance,
  scalability, and user experience. In many cases, clear advantage is
  shown over taking the CPU offline or modulating the CPU clock.

How do you know Powerclamp is running?
Powerclamp might only show itself once a year when your fan vents get too much dust & lint. So how do you know it's actually running in the background? Use:
lsmod | grep intel

And you should see a list similar to this:
btintel                16384  1 btusb
bluetooth             520192  29 bnep,btbcm,btrtl,btusb,rfcomm,btintel
intel_rapl             20480  0
intel_powerclamp       16384  0
   (.... more intel drivers ....)
snd                    81920  18 snd_hwdep,snd_timer,snd_hda_codec_hdmi,snd_hda_codec_idt,snd_pcm,snd_seq,snd_rawmidi,snd_hda_codec_generic,snd_hda_codec,snd_hda_intel,snd_seq_device

If you see intel_rapl and intel_powerclamp you know it's working and simply waiting temps to exceed 85C.

Powerclamp in action displayed by Conky
Here is a screen shot when Powerclamp injects sleep cycles:

Normally on this system CPU clock speed is 2400 Mhz to 3400 Mhz when watching HTML5 video and 10 Chrome tabs open. Normally CPU utilization is about 9% to 12% across 8 CPUs. When things get too hot (86C) Powerclamp kicks in and this happens:

*

*CPU speed is reduced to 1200 Mhz.

*CPU utilization spikes up to 80%. This is misleading because the extra 70% is sleeping time.

*The top 9 CPU processes are usually 5 or 6 Chrome processes plus Xorg, Conky, Pulse Audio and an occasional kworker. However now 8 of the top 10 are the kidle_inject/x process where x is from 0 to 7. For the first 8 CPUs.

The Powerclamp driver runs until temps drop below 85C again. While the driver is running you might have split second pausing in your videos and possibly split second keyboard and mouse lag.

Disable Intel Turbo Boost
Back in the "cool old days" of Ubuntu 14.04 Intel Turbo Boost was broken so my processor speed fluctuated between 1200 Mhz and 2400 Mhz. After upgrade to Ubuntu 16.04 it would go up to 3400 Mhz (3.4 Ghz) because Turbo Boost was finally working. But it also raised the heat.
To disable Intel Turbo Boost use:
echo "1" | sudo tee /sys/devices/system/cpu/intel_pstate/no_turbo

A: I managed to make my own script.
#!/bin/bash
while true; do
   val=$(sensors | awk '/temp1/ {print $2}')
   max="+75.0"
   if [[ "$val" > "$max" ]]; then
       dbus-send --system --print-reply --dest="org.freedesktop.UPower" /org/freedesktop/UPower org.freedesktop.UPower.Suspend
   fi
   sleep 10
   clear
   sensors
done
exit 0

For 16.04 (also here):
#!/bin/bash
while true; do
   val=$(sensors | awk '/temp1/ {print $2}')
   max="+75.0"
   if [[ "$val" > "$max" ]]; then
       systemctl suspend
   fi
   sleep 10
   clear
   sensors
done
exit 0

A: I have radically edited the above question in order to ask for updates for 16.04 and my answer below is therefore only an update to the the initial answer by Kenn, on which I posted a duplicate question and is also an answer under that.
As the error in 16.04 was Error org.freedesktop.DBus.Error.UnknownMethod: No such method 'Suspend', after the comment made by Nick Sillito under my duplicate question linking to this answer, I have modified the script by replacing this entire part:
    dbus-send --system --print-reply --dest="org.freedesktop.UPower" /org/freedesktop/UPower org.freedesktop.UPower.Suspend

with
    systemctl suspend

As indicated in the comment made by wjandreea under the duplicate question: sleep 10 or a similar value shouldn't be removed (as I initially did); without that line, the modified script will use more power because instead of running every 10 seconds, it will as fast as possible -- upwards of several dozen times per second.
At this point the system goes to sleep when going above the level set in the line
max="+75.0"

As I want a higher value, 82, the script I use is:
#!/bin/bash

while true; do
   val=$(sensors | awk '/temp1/ {print $2}')
   max="+82.0"
   if [[ "$val" > "$max" ]]; then
                        systemctl suspend

   fi
   sleep 10
   clear
   sensors
done
exit 0


text:
Q: DCOS Kafka Deployment Stuck on Vagrant Cluster I am using the latest DCOS release (0.8.0) and spun up a local vagrant cluster with 4 private agent nodes, one public agent node, one master and one boot machine
vagrant up m1 a1 a2 a3 a4 p1 boot

I then installed kafka with the default configurations using the following command:
dcos package install kafka

After examining the marathon logs, it looks like mesos is declining the resource offers for kafka and is therefore not able to deploy all three brokers. I suspect that the issue is with a mismatch between the role of the resource offer and the desired kafka role.
Aggregate cluster statistics:
CPU: 18 shares
Memory: 7GiB
Here is a snapshot of the marathon logs:
s.offer.OfferEvaluator: Satisfying resource requirement: name: "cpus" type: SCALAR scalar { value: 1.0 } role: "kafka-role" reservation { principal: "kafka-principal" labels { labels { key: "resource_id" value: "" } } }
with resource: name: "cpus" type: SCALAR scalar { value: 1.0 } role: "*"
INFO  [2016-08-02 16:28:08,919] org.apache.mesos.offer.OfferEvaluator: Reserves Resource
INFO  [2016-08-02 16:28:08,919] org.apache.mesos.offer.OfferEvaluator: Fulfilled resource: name: "cpus" type: SCALAR scalar { value: 1.0 } role: "kafka-role" reservation { principal: "kafka-principal" labels { labels { key: "resource_id" value: "f8468a5a-8166-4d5d-a594-f197a8b356cd" } } }
INFO  [2016-08-02 16:28:08,919] org.apache.mesos.offer.MesosResourcePool: Retrieving resource for reservation
WARN  [2016-08-02 16:28:08,919] org.apache.mesos.offer.OfferEvaluator: Failed to satisfy resource requirement: name: "mem" type: SCALAR scalar { value: 2304.0 } role: "kafka-role" reservation { principal: "kafka-principal" labels { labels { key: "resource_id" value: "" } } }
INFO  [2016-08-02 16:28:08,919] org.apache.mesos.offer.MesosResourcePool: Retrieving resource for reservation
INFO  [2016-08-02 16:28:08,919] org.apache.mesos.offer.OfferEvaluator: Satisfying resource requirement: name: "cpus" type: SCALAR scalar { value: 0.5 } role: "kafka-role" reservation { principal: "kafka-principal" labels { labels { key: "resource_id" value: "" } } }
with resource: name: "cpus" type: SCALAR scalar { value: 0.5 } role: "*"
INFO  [2016-08-02 16:28:08,919] org.apache.mesos.offer.OfferEvaluator: Reserves Resource
INFO  [2016-08-02 16:28:08,919] org.apache.mesos.offer.OfferEvaluator: Fulfilled resource: name: "cpus" type: SCALAR scalar { value: 0.5 } role: "kafka-role" reservation { principal: "kafka-principal" labels { labels { key: "resource_id" value: "37ba47a3-7c6e-47a2-972c-d35d130ae8df" } } }
INFO  [2016-08-02 16:28:08,919] org.apache.mesos.offer.MesosResourcePool: Retrieving resource for reservation
INFO  [2016-08-02 16:28:08,919] org.apache.mesos.offer.OfferEvaluator: Satisfying resource requirement: name: "mem" type: SCALAR scalar { value: 256.0 } role: "kafka-role" reservation { principal: "kafka-principal" labels { labels { key: "resource_id" value: "" } } }
with resource: name: "mem" type: SCALAR scalar { value: 256.0 } role: "*"
INFO  [2016-08-02 16:28:08,919] org.apache.mesos.offer.OfferEvaluator: Reserves Resource
INFO  [2016-08-02 16:28:08,919] org.apache.mesos.offer.OfferEvaluator: Fulfilled resource: name: "mem" type: SCALAR scalar { value: 256.0 } role: "kafka-role" reservation { principal: "kafka-principal" labels { labels { key: "resource_id" value: "8f937e43-c80a-4434-a858-08e6bdb02cc2" } } }
INFO  [2016-08-02 16:28:08,919] org.apache.mesos.offer.MesosResourcePool: Retrieving resource for reservation
INFO  [2016-08-02 16:28:08,919] org.apache.mesos.offer.OfferEvaluator: Satisfying resource requirement: name: "cpus" type: SCALAR scalar { value: 1.0 } role: "kafka-role" reservation { principal: "kafka-principal" labels { labels { key: "resource_id" value: "" } } }
with resource: name: "cpus" type: SCALAR scalar { value: 1.0 } role: "*"
INFO  [2016-08-02 16:28:08,919] org.apache.mesos.offer.OfferEvaluator: Reserves Resource
INFO  [2016-08-02 16:28:08,919] org.apache.mesos.offer.OfferEvaluator: Fulfilled resource: name: "cpus" type: SCALAR scalar { value: 1.0 } role: "kafka-role" reservation { principal: "kafka-principal" labels { labels { key: "resource_id" value: "b568cfaa-c216-4479-9853-5bc4e6ee2d9e" } } }
INFO  [2016-08-02 16:28:08,919] org.apache.mesos.offer.MesosResourcePool: Retrieving resource for reservation
WARN  [2016-08-02 16:28:08,919] org.apache.mesos.offer.OfferEvaluator: Failed to satisfy resource requirement: name: "mem" type: SCALAR scalar { value: 2304.0 } role: "kafka-role" reservation { principal: "kafka-principal" labels { labels { key: "resource_id" value: "" } } }
WARN  [2016-08-02 16:28:08,919] org.apache.mesos.scheduler.plan.DefaultStageScheduler: Unable to find any offers which fulfill requirement provided by block broker-0: org.apache.mesos.offer.OfferRequirement@2a28d9e[avoidAgents=[],colocateAgents=[],taskRequirements=[org.apache.mesos.offer.TaskRequirement@5c8e5b0f],executorRequirement=org.apache.mesos.offer.ExecutorRequirement@6179902f[executorInfo=executor_id {
  value: ""
}
resources {
  name: "cpus"
  type: SCALAR
  scalar {
    value: 0.5
  }
  role: "kafka-role"
  reservation {
    principal: "kafka-principal"
    labels {
      labels {
        key: "resource_id"
        value: ""
      }
    }
  }
}
resources {
  name: "mem"
  type: SCALAR
  scalar {
    value: 256.0
  }
  role: "kafka-role"
  reservation {
    principal: "kafka-principal"
    labels {
      labels {
        key: "resource_id"
        value: ""
      }
    }
  }
}
command {
  uris {
    value: "https://downloads.mesosphere.com/kafka/assets/jre-8u91-linux-x64.tar.gz"
  }
  uris {
    value: "https://downloads.mesosphere.com/kafka/assets/kafka_2.11-0.10.0.0.tgz"
  }
  uris {
    value: "https://downloads.mesosphere.com/kafka/assets/1.1.9-0.10.0.0/overrider.zip"
  }
  uris {
    value: "https://downloads.mesosphere.com/kafka/assets/1.1.9-0.10.0.0/executor.zip"
  }
  environment {
    variables {
      name: "JAVA_HOME"
      value: "jre1.8.0_91"
    }
  }
  value: "./executor/bin/kafka-executor -Dlogback.configurationFile=executor/conf/logback.xml"
}
framework_id {
  value: "2601d122-2b59-4823-83f8-84351376d53c-0001"
}
name: "broker-0"
,resourceRequirements=[org.apache.mesos.offer.ResourceRequirement@39ba5849, org.apache.mesos.offer.ResourceRequirement@2f62ec9d]]]
INFO  [2016-08-02 16:28:08,919] com.mesosphere.dcos.kafka.plan.KafkaUpdateBlock: broker-0: changed status from: Pending to: Pending
INFO  [2016-08-02 16:28:08,920] com.mesosphere.dcos.kafka.scheduler.KafkaRepairScheduler: Missing brokerIds: []
INFO  [2016-08-02 16:28:08,921] org.apache.mesos.offer.ResourceCleaner: 4 offers with 16 resources => 0 destroy and 0 unreserve operations
INFO  [2016-08-02 16:28:08,921] com.mesosphere.dcos.kafka.scheduler.KafkaScheduler: Accepted 0 of 4 offers: []
INFO  [2016-08-02 16:28:08,921] com.mesosphere.dcos.kafka.scheduler.KafkaScheduler: Declining offer: 2601d122-2b59-4823-83f8-84351376d53c-O1343
INFO  [2016-08-02 16:28:08,921] com.mesosphere.dcos.kafka.scheduler.KafkaScheduler: Declining offer: 2601d122-2b59-4823-83f8-84351376d53c-O1344
INFO  [2016-08-02 16:28:08,921] com.mesosphere.dcos.kafka.scheduler.KafkaScheduler: Declining offer: 2601d122-2b59-4823-83f8-84351376d53c-O1345
INFO  [2016-08-02 16:28:08,921] com.mesosphere.dcos.kafka.scheduler.KafkaScheduler: Declining offer: 2601d122-2b59-4823-83f8-84351376d53c-O1346
INFO  [2016-08-02 16:28:14,928]

A: The Kafka framework in DCOS 1.8 a stateful service.   It is specifically designed to allocate storage for each broker and maintain a link between the broker instance and that storage (so broker-0 is not re-deployed to a host that does not have the the storage initially allocated for broker-0).  My experience is that the messages around the resource offers are not very clear when that storage constraint is not met.  By default, the package will request 5 GB of dedicated storage for each broker.
I don't have a lot of experience with vagrant, but it could be that vagrant is not exposing the necessary "storage availability" for DC/OS to be able to honor the broker resource request.

A: The problem was indeed as the logs reported: not enough memory to schedule kafka using the default settings. I was able to deploy kafka on DCOS vagrant with the default vagrant config and three agent nodes using the following kafka config:
{
    "brokers": {
        "count": 1,
        "mem": 512,
        "disk": 1000
    }
}


text:
Q: I created a simple class that works without @jitclass. When I try to improve it with @jitclass it stops working. What is happening here? Following example 12.4 from the following website https://python-programming.quantecon.org/numba.html#id4 i constructed a simple class to model an AR(1) process.
Although the code works fine without the use of @jitclass, the code stops working after I remove ("#").
import numpy as np
import numba
import matplotlib.pyplot as plt
from numba import float64
from numba import int32
from numba.experimental import jitclass

#ar_1_data = [('ρ', float64), ('z_0', float64), ('μ', float64), ('σ', float64)]

#@jitclass(ar_1_data)

class ar_1:

    def __init__(self, ρ = 0.5, z_0 = 1, μ = 0, σ = 1):
        self.ρ = ρ
        self.z = z_0
        self.lnz = np.log(z_0)
        self.μ = μ
        self.σ = σ

    def update(self):
        self.z = self.z**(self.ρ) * np.e**(np.random.normal(self.μ,self.σ))

    def sequence(self, n):
        path = []
        path_log = []
        for i in range(n):
            path.append(self.z)
            path_log.append(np.log(self.z))
            self.update()
        self.sequence = path
        self.sequence_log = path_log

a = ar_1()
a.sequence(100)

Here is the Error im getting after removing the "#":

---------------------------------------------------------------------------
TypingError                               Traceback (most recent call last)
Input In [83], in <cell line: 1>()
----> 1 a = ar_1()
      2 a.sequence(100)

File ~\anaconda3\lib\site-packages\numba\experimental\jitclass\base.py:124, in JitClassType.__call__(cls, *args, **kwargs)
    122 bind = cls._ctor_sig.bind(None, *args, **kwargs)
    123 bind.apply_defaults()
--> 124 return cls._ctor(*bind.args[1:], **bind.kwargs)

File ~\anaconda3\lib\site-packages\numba\core\dispatcher.py:468, in _DispatcherBase._compile_for_args(self, *args, **kws)
    464         msg = (f"{str(e).rstrip()} \n\nThis error may have been caused "
    465                f"by the following argument(s):\n{args_str}\n")
    466         e.patch_message(msg)
--> 468     error_rewrite(e, 'typing')
    469 except errors.UnsupportedError as e:
    470     # Something unsupported is present in the user code, add help info
    471     error_rewrite(e, 'unsupported_error')

File ~\anaconda3\lib\site-packages\numba\core\dispatcher.py:409, in _DispatcherBase._compile_for_args.<locals>.error_rewrite(e, issue_type)
    407     raise e
    408 else:
--> 409     raise e.with_traceback(None)

TypingError: Failed in nopython mode pipeline (step: nopython frontend)
Failed in nopython mode pipeline (step: nopython frontend)
Cannot resolve setattr: (instance.jitclass.ar_1#2658a3e4d30<ρ:float64,z_0:float64,μ:float64,σ:float64>).z = int64

File "..\..\..\..\..\AppData\Local\Temp\ipykernel_17336\4275445632.py", line 9:
<source missing, REPL/exec in use?>

During: typing of set attribute 'z' at C:\Users\Hogar\AppData\Local\Temp\ipykernel_17336\4275445632.py (9)

File "..\..\..\..\..\AppData\Local\Temp\ipykernel_17336\4275445632.py", line 9:
<source missing, REPL/exec in use?>

During: resolving callee type: jitclass.ar_1#2658a3e4d30<ρ:float64,z_0:float64,μ:float64,σ:float64>
During: typing of call at <string> (3)

During: resolving callee type: jitclass.ar_1#2658a3e4d30<ρ:float64,z_0:float64,μ:float64,σ:float64>
During: typing of call at <string> (3)

File "<string>", line 3:
<source missing, REPL/exec in use?>


text:
Q: android can't load SupportV8 RenderScript in api <17 i just want to use RenderScript's ScriptIntrinsicBlur in my application , i've added renderscript.v8.jar (in android support lib v8) for supporting under 17 apis but it crashes on this line (in api <17 this happens it works fine on 4.2 or higher) :
        RenderScript rs = RenderScript.create(getApplicationContext());

and the Exception output is
 java.lang.RuntimeException: An error occured while executing doInBackground()
        at android.os.AsyncTask$3.done(AsyncTask.java:299)
        at java.util.concurrent.FutureTask$Sync.innerSetException(FutureTask.java:273)
        at java.util.concurrent.FutureTask.setException(FutureTask.java:124)
        at java.util.concurrent.FutureTask$Sync.innerRun(FutureTask.java:307)
        at java.util.concurrent.FutureTask.run(FutureTask.java:137)
        at android.os.AsyncTask$SerialExecutor$1.run(AsyncTask.java:230)
        at java.util.concurrent.ThreadPoolExecutor.runWorker(ThreadPoolExecutor.java:1076)
        at java.util.concurrent.ThreadPoolExecutor$Worker.run(ThreadPoolExecutor.java:569)
        at java.lang.Thread.run(Thread.java:856)
 Caused by: android.support.v8.renderscript.RSRuntimeException: Error loading RS jni library: java.lang.UnsatisfiedLinkError: Couldn't load RSSupport: findLibrary returned null
        at android.support.v8.renderscript.RenderScript.create(RenderScript.java:945)
        at android.support.v8.renderscript.RenderScript.create(RenderScript.java:982)
        at android.support.v8.renderscript.RenderScript.create(RenderScript.java:968)

anyone has any idea how can i handle this ?

A: You'll need to tell Eclipse or Android Studio to use RenderScript support mode.
In Eclipse, edit your project.properties file and add:

renderscript.target=18
renderscript.support.mode=true

In Android Studio, edit your build.gradle file in your app module and add this in the defaultConfig enclosure (see http://developer.android.com/guide/topics/renderscript/compute.html#ide-setup for details):

renderscriptTargetApi 18
renderscriptSupportModeEnabled true

The target API level there needs to be the max you can use.  If your minimum SDK level is higher, this value is ignored and the min SDK value is used instead.

A: It's interesting, that even the Android Renderscript examples wont work in an emulator, lets say with API 10. (Tested via Android Studio, recent updates, create Example, Emulator with API 10 -> Crash). That's surprising.
At my project, I did try/catch the Renderscript and take a fallback to at least do not crash the app, if the single stupid blur effect, made with Renderscript, is not available.
So we know, the shared library is missing on the device. That's why some people copy the Renderscript libraries to their project, usually the build tools would do the same. One could easily check this by having a look into the apk/zip file.
I think a good tutorial is given here: http://possiblemobile.com/2013/10/renderscript-for-all


text:
Q: Rails Cucumber access to controller variables I've a controller that defines the @projects variables to be displayed in the view.
There is any way to access to that projects in the cucumber step?
Note that this variables contains the paginated results, the idea is to test if the values are being displayed in the page.
I've tried to access the variable through assigns and controller but they are both nill.
Thanks.

A: The way you would generally handle this is in Cucumber is by testing the output directly.
So:

*

*Given X projects

*When I view project page N

*Then I should see Project A

*And I should not see Project B

You should not need to access controller variables from Cucumber features, as Cucumber is designed to emulate your users' experience on your site and users don't have direct access to controllers either.


text:
Q: React Starter Kit and Material UI: userAgent should be supplied in the muiTheme context for server-side rendering With the React Starter Kit, I add Material UI as follows:
npm install material-ui --save

and the following import to a component:
import RaisedButton from 'material-ui/lib/raised-button';

and:
<RaisedButton label="Default" />

I get the following error:

Warning: Material-UI: userAgent should be supplied in the muiTheme context for server-side rendering.

According to Material UI's documentation, it says I'd need to address three things:

*

*autoprefixer and the user agent

*process.env.NODE_ENV

What code should I put in and where exactly, specifically with the React Starter Kit?
P.S. this solution does not work for me  :-/

A:
When using Material-UI with server rendering, we must use the same environment for the server and the client. This has two technical implications.

as you seen on MaterialUI documentation page
You need to provide the same user-agent for both server and browser contexts as you seen it in documentation, but, I strongly discourage you to provide a "all" user-agent, since you will serve a lot of unnecessary code to your end-user.
Instead you can easily follow MaterialUI doc and pass user-agent value contained in http request headers.
With an express or koa server
global.navigator = global.navigator || {};
global.navigator.userAgent = req.headers['user-agent'] || 'all';

I just checked it has been added to the ReactStarterKit (not tested myself) in src/server.js
global.navigator = global.navigator || {};
global.navigator.userAgent = global.navigator.userAgent || 'all';

A: This should fix it
import themeDecorator from 'material-ui/lib/styles/theme-decorator';
import RaisedButton from 'material-ui/lib/raised-button';
import getMuiTheme from 'material-ui/lib/styles/getMuiTheme';

class MyComponent extends Component {
 render() {
   return (<RaisedButton label="Default" />);
  }
}

export default themeDecorator(getMuiTheme(null, { userAgent: 'all' }))(MyComponent);

A: This works for me. Add this to server.js:
global.navigator = { userAgent: 'all' };

Then verify that you see multiple vendor prefixes used like in this screengrab showing -webkit and -ms both being used:

A: Try adding global.navigator = { userAgent: 'all' }; at the top of your server.js file (Node.js entry point).

A: The working (and the cleanest) solution for me is short and simple:
getMuiTheme({userAgent: (typeof navigator !== 'undefined' && navigator.userAgent) || 'all' })

Example (from my test app):
<MuiThemeProvider muiTheme={getMuiTheme({userAgent: (typeof navigator !== 'undefined' && navigator.userAgent) || 'all' })}>
    <Provider store={store}>
        <MyApplication/>
    </Provider>
</MuiThemeProvider>

A: If you are using KoaJS server you should install koa-useragent and then use this before server side rendering:
  global.navigator = global.navigator || {};
  global.navigator.userAgent = this.state.userAgent.source || 'all';

It worked for me !


text:
Q: Not able to close the application in android I am new to android and java.I have created 9 activities(screens) and each one has a next button to navigate to next screen and 9th screen has an exit button to close the application.but if i call finish() or android.os.process.killProcess api's it is going to the previous screen but its not closing the whole application.
Could you please provide me the code snippet to close the whole application.

A: If you don't want to come back to your previous Activities then finish() every Activity before starting the new Activity.
Intent intent = new Intent(this, Second.class);
startActivity(intent);
finish();

Second option is to use startActivityForResult() in every Activity and setResult() in the last Activity that performs a call back onActivityResult() to all the previous Activities to finish().
int AnyNumber = 123;
Intent intent = new Intent(this, Second.class);
startActivityForResult(intent, AnyNumber);

override onActivityResult()
@Override
    protected void onActivityResult(int requestCode, int resultCode, Intent data) {

        if(requestCode == MyRequestCode){
            if(resultCode == Activity.RESULT_OK){
                finish();
            }
        }
    }

Do this in every Activity and in the 9th Activity set the Result,
setResult(Activity.RESULT_OK);

This will call back and all the Activities will finish depending on the requestCode.

A: in main Activity:
android.os.Process.killProcess(android.os.Process.myPid());

A: Use one activity and add fragments to it.
http://developer.android.com/guide/topics/fundamentals/fragments.html


text:
Q: Overflow of for loop? I have a little Problem with this code-snippet:
GrasTexture = pygame.image.load('Textures/Grounds/Gras.png')
StoneTexture = pygame.image.load('Textures/Grounds/Stone.png')
PathTexture = pygame.image.load('Textures/Grounds/Path.png')
SandTexture = pygame.image.load('Textures/Grounds/Sand.png')
SnowTexture = pygame.image.load('Textures/Grounds/Snow.png')
WaterTexture = pygame.image.load('Textures/Grounds/Water.png')
for i in range(936000):
        if(mapList[i][0] == 0):
            screen.blit(GrasTexture, (posX,posY))
        elif(mapList[i][0] == 1):
            screen.blit(StoneTexture, (posX,posY))
        elif(mapList[i][0] == 2):
            screen.blit(PathTexture, (posX,posY))
        elif(mapList[i][0] == 3):
            screen.blit(SandTexture, (posX,posY))
        elif(mapList[i][0] == 4):
            screen.blit(SnowTexture, (posX,posY))
        elif(mapList[i][0] == 5):
            screen.blit(WaterTexture, (posX,posY))
        if(posX != 144000):
            posX += 80
        else:
            posY += 80
            posX = 0

The map was created like this:
list01 =  [[0,0,0] for i in range(936000)]
f = open("map.txt", "w")
f.write(str(list01))
f.close()
f = open("map.txt", "r")
mapList = f.read()
mapList = ast.literal_eval(mapList)
f.close()

Here is the problem:
When I change something in the mapList like mapList[0][0] = 4, the Texture doesn't change.
But when I cut the for-loop out and replace the   i   by a 0. The Texture is right.
So what is my Problem? Please help me!


text:
Q: How to Eager Load The Session Query in laravel? I am trying to figure out where laravel makes the session query, i have these queries when i just log in my app
/****************************** Database Queries ******************************/

   0.79 | select * from `users` where `users`.`id` = ? limit 1 | 1
   0.8 | select `roles`.*, `role_user`.`user_id` as `pivot_user_id`............

Queries: 2
Time: 1.59
/****************************** End Queries ***********************************/

I would like to eager load the first query with the second query, i use the second query in every pages of my website to get the user nav bar according with his role
if i do Auth::user()->roles()->id the second query would run.. but if i do User::with('Role')->find(1); for example i would get the same result as the first query plus+ the second.. am i right? how could i change this laravel behavior to runs trough all the pages.. i would save one query :)
hope i could explain myself clearly..


text:
Q: Duplicate interface definition for class 'Resources.h' Due to security reason cannot paste the original code hence tried to be more intent full

*

*Have a project called Utils.xcodeproj which has an objective c files called Resources.m and its header is exposed as public header.

*Have another project called main.xcodeproj in which this Utils project is referenced.

Now when compiling the main.xcodeproj I get error "Duplicate interface definition for class Resources" iOS/Utils/Utils/Resources.h:23:1: @interface Resources : NSObject
Build/Products/Debug-iphoneos/include/Utils/Resources.h:23:12: note: previous definition is here @interface Resources : NSObject
Is there a way to overcome this error or turn this error into a warning?
Class Resources.h

@protocol ResourcesDelegate;

@interface Resources : NSObject

@property (weak, nonatomic) id<ResourcesDelegate> delegate;
+ (void) setDefault:(UIView *)view;
@end

@protocol ResourcesDelegate <NSObject>
@required
- (void)loadFromSDK:(NSString*)Name;

@end

Class Utils-Bridging-Header.h
#import "Resources.h"

Class XYZ in main.xcodeproj
#import "Utils/Resources.h"

[Resources setDefault:view]

A: also you could..
#ifndef Resources_h
#define Resources_h

// ... your #import or @import, #include <...> rules here...

// ... announcing a
// @class SomeClassWithName
// here if needed. This will make SomeClassWithName available
// to this header even if its interface is declared later on. (skaak's solution)

// ... all your @interface stuff here ...

#endif

This should keep it from being implemented twice per project.
Why is this working?
Because once #import "Resources.h" is done Resources_h would be defined and when #import "Utils/Resources.h" is processed the definition is jumping over the second attempt to declare the class.
Edit
forgot to mention that this approach should be used in header files of course. While it is not forbidden to make use of it in implementation files. In fact in cross platform source you will see this is used heavily.
Edit2
have a look at the following nice explained answer what is going on when #include is used and what was meant to work fine when using #import sven's stackoverflow answer

*

*so the #import preprocessor command reminds the files that have been imported already, but that seems to fail when files and with it declarations are re-established from another project with its own folder structure. In short: "Resources.h" and "Utils/Resources.h" are different files to the preprocessor so your class definitions are duplicate of each other.