text:
Q: Error converting data type nvarchar to decimal I try to copy data from oracle to a table in SQL Server after loading some batch I come across this error
code:
           ResultSetMetaData rsmd = rs.getMetaData();
           int total = rsmd.getColumnCount();
            while(rs.next()) {
                for (int i =1; i <= total; i++) {
                    pstmt.setObject(i, rs.getObject(i));
                }

                pstmt.addBatch();

                count++;

                if(count % batchSize == 0|| rs.isLast()){
                    System.out.println("Confirmar o Lote");
                    result = pstmt.executeBatch();
                    System.out.println("Numero de Linhas inseridas: "+ result.length);
                    connection1.commit();
                }
            }

Saida:
OK, in time:39447
Confirmar o Lote
java.sql.BatchUpdateException: Error converting data type nvarchar to decimal.
    at com.microsoft.sqlserver.jdbc.SQLServerPreparedStatement.executeBatch(SQLServerPreparedStatement.java:1870)
    at connect.testeValorporPagar.main(testeValorporPagar.java:74)


text:
Q: How does JavaScript compare a number to a string? I know the meaning of ===: it will check whether the operands are identical or not,so

*

*1 === '1' will give false and

*1 == '1' will give true,

But typeof 1 is number and typeof '1' is string, so how is JavaScript comparing 1 == '1'? Are there any conversions happening? If so, which ones?

A: If types are number and string,
JavaScript will convert the string to a number.
Out of Annotated ECMAScript 5.1:

The comparison x == y, where x and y are values, produces true or
  false. Such a comparison is performed as follows:
...
5. If Type(x) is Number and Type(y) is String, return the result of the
  comparison x == ToNumber(y).
  6. If Type(x) is String and Type(y) is
  Number, return the result of the comparison ToNumber(x) == y.

A: You can do 1 == parseInt("1") to parse the string into an integer.

A: Use String()
It converts the input to a string before doing a comparison.
Example:
var test1= 1;
var test2= "1";

var answer = String(test1) === String(test2);

Answer will equal true in this case.

redpajama_set_name: RedPajamaStackExchange


text:
Q: How to implement content Geo-fencing in facebook messenger bot? I want to share videos via subscription messages with my messenger bot. However the content I am willing to share is restrictive to certain countries only.
When posting a video, geo-fencing is straight forward and facebook allows you to select the countries the post will be visible at.
However when sharing content via messenger this gets tricky. Any workaround besides asking from the user to share their location?

A: You could restrict countries of Facebook Apps in the developer console, Settings -> Advanced tab.


text:
Q: Rooms & Availability Dates PHP/MySQL So, I'm desinging a web application that is going to work for a Hotel and it should eventually become an easy way to install for every hotel website with some extra code. The application is working with php and mysql. So, as you probably guessed, I'm pretty confused with the database structure. Though, I've made some research and I'm not just asking for a full-fledged system for bookings.
So, owner of the hotel has to have many types of rooms. So probably a table for rooms is a "must" I suppose. Here we go:
---------- Rooms Table (example)

ID     NAME         ADULTS     ROOM_COUNT     PRICE/NIGHT

1      DoubleRoom   2          5              45$
2      Family       3          2              75$
3      Single       1          3              35$

This is pretty straightforward. Rooms can be added through my application and I'll also attach a proper description as well as a variety of images for each room. But let's get back to the point. People should make bookings so...
---------- Bookings Table (example)

ID    ROOM_ID      BOOKING_USER     CHECKIN (timestamp)   CHECKOUT (timestamp)

1     2            A full name      208420842042          308230482042824
2     3            A full name      208423242525          529752972595272
...

So, this is -hopefully- the database structure. Now, I'm thinking of a way to check for availability. I know, it might sound stupid but I can't figure out a smart and easy way. In the form of the website, there should be the following fields: check-in date and check-out-date which will be then transformed to timestamps and.. well here's the time I stuck!
How can I check for availabily of rooms when I only have the above tables. Is there any way or I need to change my database structure? Even if I manage to check for availability, how comes the total number of rooms (ROOM_COUNT) in count? I mean, how can I check availability for multiple types of rooms? I thought something like:
SELECT count(ROOM_ID) FROM bookings WHERE
bookings.checkin < DATE_GIVEN_AS_CHECKIN_INPUT and
bookings.checkout > DATE_GIVEN_AS_CHECKOUT_INPUT

then depending on the output of this query I would know if there's a room available or not. But what about room count? Is there any better ways?
I'd be really glad if someone here could enlight me on this. Best regards and thanks in advance, even for reading this!
Blane
P.S. Oh, it's not a homework! :P I don't go to school anyway :D

A: the following query will find all rooms which have no bookins, or bookings which are before or after the checkin/checkout input.
SELECT r.*
FROM rooms r
LEFT JOIN bookins b ON b.room_id = r.id
WHERE b.id IS NULL
OR (b.checkout >= DATE_GIVEN_AS_CHECKIN_INPUT AND b.checkin >= DATE_GIVEN_AS_CHECKOUT_INPUT)
OR (b.checkout <= DATE_GIVEN_AS_CHECKIN_INPUT AND b.checkout <= DATE_GIVEN_AS_CHECKOUT_INPUT)

to get the room count just replace SELECT r.* with SELECT COUNT(DISTINCT r.id)

A: If you look at your requested period [SDATE,EDATE] in timeline there are four booking cases (1),(2),(3),(4) that can (totally/partially) occupy requested period:
    SDATE    EDATE
      |--------|              <-- requested period

  |--1--|   |--2--|           <-- booking periods
    |-----3------|            <-- relevant for
        |-4--|                <-- occupancy test

|-5-|            |--6--|      <-- periods not relevant

you can find these period cases (1,2,3 and 4) with the following statements:
case 1, 2 and 3
WHERE (b.checkout >= SDATE AND b.checkin >= EDATE)

case 4:
WHERE (b.checkout <= SDATE AND b.checkin >= EDATE)

Then combining these two cases the query that will list all room IDs of occupied rooms in given period [SDATE,EDATE] is:
SELECT DISTINCT b.roomid FROM bookings AS b
WHERE (b.checout >= SDATE AND b.checkin <= EDATE)
OR (b.checkout <= SDATE AND b.checkin >= EDATE)

Since you need the opposite case - all available rooms in requested period, you query will look like this:
SELECT r.roomid FROM rooms AS r WHERE r.roomid NOT IN
(
  SELECT b.roomid FROM bookings AS b
  WHERE (b.checout >= SDATE AND b.checkin <= EDATE)
  OR (b.checkout <= SDATE AND b.checkin >= EDATE)
)

DISTINCT is not needed in subquery (if 1 is not in [1,2] then it is not in [1,1,2] too).


text:
Q: cxf client side dependencies I tried to build an REST Client via CXF. The following code works within the junit environment.
JAXRSClientFactoryBean bean2 = new JAXRSClientFactoryBean();
bean2.setAddress("http://localhost:8181/cxf/treenodeService/");
bean2.setResourceClass(ITreeNodeService.class);
bean2.setProviders( Arrays.asList(new TreeNodeBeanProvider()) );
ITreeNodeService treeService = bean2.create(ITreeNodeService.class);

List<TreeNodeBean> treeNodeBeans = treeService.getNodes();
assertEquals("We expected only one node, the global", 1, treeNodeBeans.size());

But if I try this code within the osgi environment, it fails because of missing dependencies. So what is the minimal set of dependencies I need for this code to run within an equinox / osgi environment?
Currently I have added
javax.ws.rs.javax.ws.rs-api;bundle-version="2.0.0",
org.apache.cxf.cxf-rt-frontend-jaxrs;bundle-version="2.7.10",
org.apache.cxf.cxf-api;bundle-version="2.7.10",
org.apache.cxf.cxf-rt-core;bundle-version="2.7.10",
org.apache.cxf.cxf-rt-bindings-xml;bundle-version="2.7.10",
org.apache.cxf.cxf-rt-transports-http;bundle-version="2.7.10",
org.apache.cxf.cxf-rt-transports-http-jetty;bundle-version="2.7.10",
javax.wsdl;bundle-version="1.6.2",

UPDATE -1- Missing dependencies
These are the missing dependencies I get from the validation from eclipse.

*

*com.wordnik.swagger.jaxrs.config

*com.wordnik.swagger.jaxrs.listing

*org.apache.ws.commons.schema

*org.apache.ws.commons.schema.constants

*org.apache.ws.commons.schema.extensions

*org.apache.ws.commons.schema.resolver

*org.apache.ws.commons.schema.utils

Sincerely

A: Ok I didn't get it up and running. So I switch to CXF - DOSGI, using the dependencies listed above. (But different version)
Then I had to solve another issue due to a missing http transport. In the end the code for accessing a REST service via an OSGI REST client looks like.
JAXRSClientFactoryBean sf = new JAXRSClientFactoryBean();
sf.setResourceClass(serviceClass);
sf.setAddress("http://" + getServerUrl() + "/cxf/" + serviceName);
sf.setProviders(providers);

ConduitInitiatorManager cim = sf.getBus().getExtension(ConduitInitiatorManager.class);
   cim.registerConduitInitiator("http://cxf.apache.org/transports/http",
   new HTTPTransportFactory(sf.getBus()));

service = sf.create(serviceClass);

Further reading link


text:
Q: strcpy on a string pointer gives errors I have read a lot about the subject and I am confused .
What used to work in a C file ,not working on a cpp file :
 char  *builtinFunctions[20];

Then I get error on the strcpy function here :
void Intepreter::setBuiltIns(char *builtins)
{
   strcpy(builtinFunctions, builtins); // no matching function call to strcpy
}

I probably don't understand the basics here, but why in C++ this will not work ( do i need to use = instead ? )
strcpy(char *, const char*) = thats the structure

if I change the  builtinFunctions from being a pointer it works.
EDIT:
The reason for being a const before this edit is that I read here :
Why is conversion from string constant to 'char*' valid in C but invalid in C++
that char  *builtinFunctions[20]; will produce warning when :
builtinFunctions[0]="me";

and it did. I could fix it by removing the const .

A: This is an array of pointers to char.
char  *builtinFunctions[20];

So you call
strcpy(builtinFunctions, builtins);

gets treated as strcpy(char **, char*), not as strcpy(char *dest, const char *src). So you get a mismatch for first parameter type.
EDIT:
So let's suppose builtinFunctions is "an array of words" you wish to populate, with void Intepreter::setBuiltIns(char *builtins) meant to do just that with it's first parameter being a pointer to a new incoming word. (And you're doing this in a C-style manner. Well, up to you.)
Some things to consider.

*

*If you declare an array type arrName[N]; then the array's name
being used all alone without index is treated as a variable of type
type *arrName. If you type is initially char *, then
builtinFunctions by itself is of type char**. That's why your
strcpy fails, but strcpy(builtinFunctions[someIndex], builtins);
works.

*Before invoking strcpy you should consider, if you have a
destination space allocated. builtinFunctions[someIndex] is of
type char *. Where does it point to? Is it a valid pointer to an
allocated space, or a gateway to hell of undefined behaviour strcpy  will happily take you to?


text:
Q: try to get webric to work I been trying for weeks now to get webric Webric to work and been unable to.
The error shown in the log is
Started GET "/config.json" for 82.2.58.4 at 2016-10-26 23:19:50 +0200

ActionController::RoutingError (No route matches [GET] "/config.json"):

actionpack (5.0.0.1) lib/action_dispatch/middleware/debug_exceptions.rb:53:in `call'
web-console (3.3.1) lib/web_console/middleware.rb:131:in `call_app'
web-console (3.3.1) lib/web_console/middleware.rb:20:in `block in call'
web-console (3.3.1) lib/web_console/middleware.rb:18:in `catch'
web-console (3.3.1) lib/web_console/middleware.rb:18:in `call'
actionpack (5.0.0.1) lib/action_dispatch/middleware/show_exceptions.rb:31:in `call'
railties (5.0.0.1) lib/rails/rack/logger.rb:36:in `call_app'
railties (5.0.0.1) lib/rails/rack/logger.rb:24:in `block in call'
activesupport (5.0.0.1) lib/active_support/tagged_logging.rb:70:in `block in tagged'
activesupport (5.0.0.1) lib/active_support/tagged_logging.rb:26:in `tagged'
activesupport (5.0.0.1) lib/active_support/tagged_logging.rb:70:in `tagged'
railties (5.0.0.1) lib/rails/rack/logger.rb:24:in `call'
sprockets-rails (3.2.0) lib/sprockets/rails/quiet_assets.rb:13:in `call'
actionpack (5.0.0.1) lib/action_dispatch/middleware/request_id.rb:24:in `call'
rack (2.0.1) lib/rack/method_override.rb:22:in `call'
rack (2.0.1) lib/rack/runtime.rb:22:in `call'
activesupport (5.0.0.1) lib/active_support/cache/strategy/local_cache_middleware.rb:28:in `call'
actionpack (5.0.0.1) lib/action_dispatch/middleware/executor.rb:12:in `call'
actionpack (5.0.0.1) lib/action_dispatch/middleware/static.rb:136:in `call'
rack (2.0.1) lib/rack/sendfile.rb:111:in `call'
railties (5.0.0.1) lib/rails/engine.rb:522:in `call'
puma (3.6.0) lib/puma/configuration.rb:225:in `call'
puma (3.6.0) lib/puma/server.rb:578:in `handle_request'
puma (3.6.0) lib/puma/server.rb:415:in `process_client'
puma (3.6.0) lib/puma/server.rb:275:in `block in run'
puma (3.6.0) lib/puma/thread_pool.rb:116:in `block in spawn_thread'
  Rendering /home/chat/.rvm/gems/ruby-2.3.1/gems/actionpack-5.0.0.1/lib/action_dispatch/middleware/templates/rescues/routing_error.text.erb
  Rendering /home/chat/.rvm/gems/ruby-2.3.1/gems/actionpack-5.0.0.1/lib/action_dispatch/middleware/templates/rescues/_trace.text.erb
  Rendered /home/chat/.rvm/gems/ruby-2.3.1/gems/actionpack-5.0.0.1/lib/action_dispatch/middleware/templates/rescues/_trace.text.erb (0.8ms)
  Rendered /home/chat/.rvm/gems/ruby-2.3.1/gems/actionpack-5.0.0.1/lib/action_dispatch/middleware/templates/rescues/routing_error.text.erb (7.9ms)

Can any help me please Many Thanks


text:
Q: Firebase Cloud Firestore Design I am having trouble finishing the design for a android application I am working on. I have three main groups that I need to store data in; Hosts, Volunteers, and Events. The problem I am running into is that most events will have more than one volunteer, and I do not know how I should structure the collections so I can query my database for all events created by a host and for all volunteers within each event.
I currently have 3 top level collections; Hosts, Volunteers, and Events. However, I am wondering if this is actually the best way to go about this, and can someone explain how to query the database for all volunteers within each event with this design.
If this is not the best way to do it, then I would appreciate it if someone could explain another approach and how it would work.

A:
I currently have 3 top level collections

That's a common way for structuring a Cloud Firestore database.

can someone explain how to query the database for all volunteers within each event with this design.

A possible database structure might be:
Firestore-root
  |
  --- volunteers (collection)
  |    |
  |    --- volunteerId (document)
  |          |
  |          --- //Volunteer properties
  |          |
  |          --- eventIds: ["generatedEventId", "generatedEventId"]
  |
  --- events (collection)
       |
       --- eventId (document)
             |
             --- //Event properties

As you can see I have added the eventId as a value within eventIds array, since a volunteer can participate at more than one event. To get all volunteers within each event, you can use the following query:
FirebaseFirestore rootRef = FirebaseFirestore.getInstance();
CollectionReference volunteersRef = rootRef.collection("volunteers");
Query query = volunteersRef.whereArrayContains("eventIds", "generatedEventId");

Where the generatedEventId is the id of event you at which the volunteers are participating.
Since you didn't choose a tag for a platform, I have wrote the above lines of code in Android but it can be simply written also for other programming languages.


text:
Q: On Windows 10, I cannot two-finger-scroll in Google Inbox with Chrome I have a Dell XPS 13 (2015) which I just upgraded to Windows 10. I can no longer scroll using two-finger drag on the touchpad when in Google Inbox, using Chrome 45.0.2454.15. I can still scroll using the scroll bar on the right, and my touch screen.
This goes for reading individual emails, viewing the entire list, and my chat contacts on the right.
I don't seem to have the issue on other websites.

A: Try entering chrome://flags in your adress bar, searching for Enable touch events and setting that dropdown to Disabled. Recent versions of  chrome do strange things on some pages that rely on detecting touch capabilities. Honestly I don't know why, but disabling touch events usually fixes the issue. You'll be left without touch support though, which may or may not be a dealbreaker for you.


text:
Q: Can I import a type synonym's data constructors without using the ViewPatterns GHC extension? I have a module A and B which both export the Event type. Module C defines a type synonym to module A's Event, calling it InputEvent.
I then consume both module B and module C in a module D:
module D where

import B (Event)
import C (InputEvent)

However, if I try to import InputEvent's type constructors (say, MakeEvent), I get the error:
Module
'C'
does not export
'InputEvent(MakeEvent)'

This could be solved by using the ViewPatterns GHC extension and exporting an alias to MakeEvent from module C:
makeEvent = MakeEvent

However, is there a way of importing the MakeEvent data constructor without using the ViewPatterns extension?

A: Don't use type synonyms to enforce abstraction barriers, except possibly small, private ones. They're no good at it. If you want to hide Event, use a newtype and pattern synonyms.


text:
Q: Format a number with leading sign How do I format in Java a number with its leading sign?
Negative numbers are correctly displayed with leading -, but obviously positive numbers are not displayed with +.
How to do that in Java? My current currency format string is \#\#\#,\#\#\#,\#\#\#,\#\#\#,\#\#0.00 (yes, I need to format positive/negative currency values)

A: I did:
private NumberFormat plusMinusNF = new DecimalFormat("+#;-#");

Integer newBalance = (Integer) binds.get("newBalance");
bindsForUpdate.put("plusMinus", plusMinusNF.format(newBalance));

which formatted positive integers, e.g. 5 to "+5" and negative integers, e.g -7 to "-7" (as expected)

A: Use a negative subpattern, as described in the javadoc for DecimalFormat.
DecimalFormat fmt = new DecimalFormat("+#,##0.00;-#");
System.out.println(fmt.format(98787654.897));
System.out.println(fmt.format(-98787654.897));

produces (in my French locale where space is the grouping separator and the comma is the decimal separator) :
+98 787 654,90
-98 787 654,90

A: API for Formatter provides an example:
Formatter formatter = new Formatter();
System.out.println(formatter.format(Locale.FRANCE, "e = %+10.4f", Math.E));
//e =    +2,7183

A:
It requires a little tweaking of the
  DecimalFormat returned by
  NumberFormat.getCurrencyInstance() to
  do it in a locale-independent manner.
  Here's what I did (tested on Android):
DecimalFormat formatter = (DecimalFormat)NumberFormat.getCurrencyInstance();
String symbol = formatter.getCurrency().getSymbol();
formatter.setNegativePrefix(symbol+"-");
// or "-"+symbol if that's what you need
formatter.setNegativeSuffix("");

IIRC, Currency.getSymbol() may not
  return a value for all locales for all
  systems, but it should work for the
  major ones (and I think it has a
  reasonable fallback on its own, so you
  shouldn't have to do anything)

ageektrapped
Source: Format negative amount of USD with a minus sign, not brackets (Java)


text:
Q: Auto pre-select dropdown value from URL address I'm using the dropdown select menu which redirects users to selected cities. I have searched for this topic everywhere and tried many solutions found on stackoverflow but each of them did not work. In many cases it even disabled the redirection of my dropdown. So I am posting a new question. Hopefully that someone could solve my problem.
Problem: When I visit URL I see select delivery city - non value option. It should show the selected city based on URL address.
My URL looks like this /kategoria-produktu/CITY U SELECT (/kategoria-produktu/cadca/)
To sum up: When u visit url /kategoria-produktu/cadca the dropdown should be preselect on current url and display Čadca.
Any ideas how could I solve this?
Thank you very much!
CODE
JS
if(location.href.indexOf(localStorage.country) == -1){
location.href = localStorage.country
}

function formChanged(form) {
var val = form.options[form.selectedIndex].value;
if (val !== 'non-value') {
if (localStorage) {
localStorage.country = val;
}

if (!location.href.indexOf(val)) {
location = val;
   }
  }
 }

HTML
 <form name="form1">
 <select id="saleTerm" onchange="formChanged(this); location =
 this.options[this.selectedIndex].value;" NAME="country" SIZE="1">
 <OPTION VALUE="non-value">Select delivery city</option>
 <OPTION VALUE="/kategoria-produktu/cadca/">Čadca</option>
 <OPTION VALUE="/kategoria-produktu/brno/">Brno</option>
 <OPTION id="bratislava" VALUE="/kategoria-produktu/bratislava/">Bratislava</option>
 </select>
 </form>

A: So a bunch of little things need to change here for you to get what you want. I'll try to write them all down:

*

*You should access localStorage using getItem and setItem like in the localStorage MDN documentation

*Use an event listener instead of the inline onchange attribute, it's much cleaner.

*You probably want to use includes instead of indexOf since you are looking for a substring (country) in a string (href), indexOf won't do this for you.

*I used location.pathname since you really only care about the path, there are better ways to get the exact path parameter you want.

*No need to use a <form/> as far as I can see from the code you shared.

*I removed /kategoria-produktu/ from the option's value attribute since its repetitive and just placed it once in the js

*You should change the value of the select to the city you want as the default selected. You can do this by parsing out the city from the path and setting it as the value attribute on the select
I think that's it, here is an example using those points above.

const PREFIX = "kategoria-produktu";
window.addEventListener('load', function() {
  let countryInStorage = localStorage.getItem("country");

  if (countryInStorage && !location.pathname.includes(countryInStorage)) {
    location.href = `/${PREFIX}/${countryInStorage}`;
  }

  document.getElementById("saleTerm").addEventListener("change", formChanged);
  setDefaultOption();
})

function setDefaultOption() {
  let countryPath = location.pathname.split("/")[2];

  if (countryPath) {
    document.getElementById("saleTerm").value = countryPath;
  }
}

function formChanged() {
  let selectedCountry = this.value;
  if (selectedCountry !== "non-value") {
    if (localStorage) {
      localStorage.setItem("country", selectedCountry);
    }

    if (!location.pathname.includes(selectedCountry)) {
      location.href = `/${PREFIX}/${selectedCountry}`;
    }
  }
}
<select id="saleTerm" name="country">
  <option value="non-value">Select delivery city</option>
  <option value="cadca">Čadca</option>
  <option value="brno">Brno</option>
  <option value="bratislava">Bratislava</option>
</select>

A: If I understand it correctly, you are looking onto showing the proper option from the select element based on the URL.
Look at the example below. It basically runs a process on page load and when the DOM is ready (hence DOMContentLoaded) to check if an option based on URL exists in the select options and picks that. You may have to update your logic depending on the URL structure. The example below assumes your URL is always formatted like http://your.domain.com/kategoria-produktu/<city>/.
document.addEventListener("DOMContentLoaded", function() {
  // find the option based on the URL.
  let option = document.querySelector("#saleTerm > option[value='" + location.pathname + "']");

  // assign the option value to the select element if such exists.
  if (option) {
    document.querySelector("#saleTerm").value = option.value;
  }
});


text:
Q: iOS 8 Code working on iPhone 5s but not iPhone 5 After testing my spritekit game on the iPhone 5s simulator all the time I finally tried to run it on the iPhone 5 simulator. Unfortunately I get an error as soon as I do the first touch that I don't understand. My touchesBegan function calls my addCoin function (see below)
The error is somewhere in this code-block. If I comment out this part of the code everything else works fine:
func addCoin()
{
    var coin:SKSpriteNode = SKSpriteNode(texture: coinFrames[0])
    coin.size.width = 50
    coin.size.height = 50
    coin.physicsBody = SKPhysicsBody(circleOfRadius: coin.size.height / 2)
    coin.physicsBody?.dynamic = false
    coin.physicsBody?.allowsRotation = false
    coin.physicsBody?.categoryBitMask = coinCategory
    coin.physicsBody?.contactTestBitMask = playerCategory

    var positionX:CGFloat = CGFloat(Int(arc4random()) % Int(500)) + CGFloat(70.0)
    var positionY:CGFloat = CGFloat(Int(arc4random()) % Int(1007)) + CGFloat(63.0)

    coin.position = CGPointMake(positionX, positionY)
    coin.runAction(SKAction.repeatActionForever(SKAction.animateWithTextures(coinFrames, timePerFrame: 0.1, resize:false, restore:true)))

    self.addChild(coin)
}

Here is the error that occurs. If I comment out this line, the next one gives an error...

Like I said, iPhone 5s works perfectly...
What could be wrong with my code?
xCode 6 beta 6 & iOS 8 beta 7
Thanks in advance

A: The debugger is misleading you. The real problem is arc4random, which will return an UInt32 on both iPhone 5 and 5s. But as iPhone 5 is a 32-bit device, the Int(arc4random()) will cause an overflow if the random number is big enough.
Instead of using Int(arc4random()), you can try to replace it by using arc4random_uniform. Maybe the code below will do the trick for you.
var positionX: CGFloat = CGFloat(arc4random_uniform(500)) + CGFloat(70.0)
var positionY: CGFloat = CGFloat(arc4random_uniform(1007)) + CGFloat(63.0)


text:
Q: WPF Control moves but its Adorner - Not :"/ I created an adorner on a WPF line element, because there was neet to add some text.
Now, when this line is moved, the adorner does not "follow" the line automatically. In fact, it does not refresh itsef:

here black curves is the Control drawing, and the red "120 m" is the adorner one.
Some code
    void SegmentLine_Loaded(object sender, RoutedEventArgs e)
    {
        AdornerLayer aLayer = AdornerLayer.GetAdornerLayer(this);
        if (aLayer != null)
        {
            aLayer.Add(new TextAdorner(this));
        }
    }

    class TextAdorner : Adorner
    {
        public TextAdorner(UIElement adornedElement)
            : base(adornedElement)
        {
        }

        protected override void OnRender(DrawingContext drawingContext)
        {
            SegmentLine segment = (this.AdornedElement as SegmentLine);

            if (segment != null)
            {
                Rect segmentBounds = new Rect(segment.DesiredSize);
                var midPoint = new Point(
                    (segment.X1 + segment.X2) / 2.0,
                    (segment.Y1 + segment.Y2) / 2.0);
                var lineFont = // get line font as Font

                FormattedText ft = new FormattedText(
                    string.Format("{0} m", segment.Distance),
                    Thread.CurrentThread.CurrentCulture,
                    System.Windows.FlowDirection.LeftToRight,
                    new Typeface(lineFont.FontFamily.ToString()),
                    ligneFont.Size, Brushes.Red);

                drawingContext.DrawText(ft, midPoint);
            }

        }
    }

A: Why MeasureOverride, etc aren't being called
Your adorner's MeasureOverride, ArrangeOverride, and OnRender aren't being called because your SegmentLine control is never changing size or position:

*

*Since your SegmentLine doesn't implement MeasureOverride, it always has the default size assigned by the layout engine.

*Since your SegmentLine doesn't implement ArrangeOverride or manipulate any transforms, its position is always exactly the upper-left corner of the container.

The Adorner's MeasureOverride, ArrangeOverride and OnRender are only called by WPF under these conditions:

*

*The AdornedElement changes size or position (this the most common case), or

*One of the Adorner's properties chagnes and that property is marked AffectsMeasure, AffectsArrange, or AffectsRender, or

*You call InvalidateMeasure(), InvalidateArrange(), or InvalidateVisuaul() on the adorner.

Because your SegmentLine never changes size or position, case 1 doesn't apply.  Since you don't have any such properties on the Adorner and don't call InvalidateMeasure(), InvalidateArrange() or InvalidateVisual(), the other cases don't apply either.
Precise rules for Adorner re-measure
Here are the precise rules for when an adorned element change triggers a call to Adorner.MeasureOverride:

*

*The adorned element must force a layout pass by invalidating its Measure or Arrange in response to some event.  This could be triggered automatically by a change to a DependencyProperty with AffectsMeasure or AffectsArrange, or by a direct call to InvalidateMeasure(), InvalidateArrange() or InvalidateVisual().

*The adorned element's Measure and Arrange methods must not be called directly from user code between the invalidation and the layout pass.  In other words, you must wait for the layout manager to do the job.

*The adorned element must make a non-trivial change to either its RenderSize or its Transform.

*The combination of all transforms between the AdornerLayer and the adorned element must be affine.  This will generally be the case as long as you are not using 3D.
Your SegmentLine is just drawing the line in a new place rather than updating its own dimensions, thereby omitting my requirement #3 above.
Recommendation
Normally I would recommend your adorner have AffectsRender DependencyProperties bound to the SegmentLine's properties, so any time X1, Y1, etc change in the SegmentLine they are also updated in the Adorner which causes the Adorner to re-render.  This provides a very clean interface, since the adorner can be used on any control that has properties X1, Y1, etc, but it is less efficient than tightly coupling them.
In your case the adorner is clearly tightly bound to your SegmentLine, so I think it makes just as much sense to call InvalidateVisual() on the adorner from the SegmentLine's OnRender(), like this:
public class SegmentLine : Shape
{
  TextAdorner adorner;

  ...

  protected override void OnRender(DrawingContext drawingContext)
  {
    base.OnRender(drawingContext);
    if(adorner==null)
    {
      var layer = AdornerLayer.GetAdornerLayer(this); if(layer==null) return;
      adorner = new TextAdorner(this);
      ... set other adorner properties and events ...
      layer.Add(adorner);
    }
    adorner.InvalidateVisual();
  }
}

Note that this doesn't deal with the situation where the SegmentLine is removed from the visual tree and then added again later.  Your original code doesn't deal with this either, so I avoided the complexity of dealing with that case.  If you need that to work, do this instead:
public class SegmentLine : Shape
{
  AdornerLayer lastLayer;
  TextAdorner adorner;

  ...

  protected override void OnRender(DrawingContext drawingContext)
  {
    base.OnRender(drawingContext);
    var layer = AdornerLayer.GetAdornerLayer(this);
    if(layer!=lastLayer)
    {
      if(adorner==null)
      {
        adorner = new TextAdorner(this);
        ... set other adorner properties and events ...
      }
      if(lastLayer!=null) lastLayer.Remove(adorner);
      if(layer!=null) layer.Add(adorner);
      lastLayer = layer;
    }
    adorner.InvalidateVisual();
  }
}

A: How is the line being moved? Does the MeasureOverride or ArrangeOverride of the adorner get invoked after the move? OnRender will only get invoked if the visual is invalidated (e.g. invalidatevisual) so I'm guessing that the render isn't being invalidated.

A: May be you wanted to use segmentBounds to define midPoint? Otherwise what is it doing there? Looks like you are defining midPoint relative to not rerendered segment.

A: idiot fix, but it works
    AdornerLayer aLayer;
    void SegmentLine_Loaded(object sender, RoutedEventArgs e)
    {
        aLayer = AdornerLayer.GetAdornerLayer(this);
        if (aLayer != null)
        {
            aLayer.Add(new TextAdorner(this));
        }
    }

    protected override void OnRender(DrawingContext drawingContext)
    {
        base.OnRender(drawingContext);
        if (aLayer != null)
        {
            aLayer.Update();
        }
    }

Now, the problem is that when I click on a the adorner the control itself does not recieve the hit...


text:
Q: Запустить PHP скрипт отдельным потоком с массив данными Задача состоит в том, что б при запуске определенной команды, данные массива со скрипта A поступали на скрипт B. И этот скрипт принял эти данные и был запущен отдельным потоком, в не зависимости от скрипта A. Как это сделать и принять массив на том конце.
Был найдет вот такой код
exec('bash -c "exec nohup setsid php send.php ' . escapeshellarg($data) . ' > /dev/null 2>&1 &"');

где $data это просто некое значение, пока не массив. Но на том конце я не могу принять данные и не понятно работает ли оно. Как правильно построить код и передать/принять массив данные?

A: Разобрался. Все работает. Нужно лишь принимать данные через $_SERVER['argv']


text:
Q: firebase console database display instantly flips back to Overview In testing a firestore database and reviewing the results in the firebase console, the database data will not load and keeps returning to the Overview display. By using two devices to test with, I can determine that the updates are correct.
This problem started with one rogue record on the console causing the data display to backout but all other records were correctly displayed. Other project database records display correctly.
Is there any way I isolate the problem by finding an error message?

A: firebaser here
This is indeed a bug in the Firestore console: if you select a document with a newline (\n) in its ID, the URL of your browser doesn't reflect the selected document.
Thanks for reporting! This will be fixed in an upcoming update to the Firebase console.
In the meantime, the API will allow you to access these documents without problems. So your apps should continue to work, and consider performing actions on affected documents through the API instead of through the console.


text:
Q: discord.js Unhandled Promise Rejection Warning : TypeError: Cannot read property 'includes' of null I made an auto role code for my bot recently, which reads the status of every user and gives them a role if they have our server vanity invite link in their status. The code works perfectly, the bot adds the role, and removes it, but the problem here is it loops through an error without crashing the bot :
(node:38) UnhandledPromiseRejectionWarning: TypeError: Cannot read property 'includes' of null
(node:38) UnhandledPromiseRejectionWarning: Unhandled promise rejection. This error originated either by throwing inside of an async function without a catch block, or by rejecting a promise which was not handled with .catch(). To terminate the node process on unhandled promise rejection, use the CLI flag `--unhandled-rejections=strict` (see https://nodejs.org/api/cli.html#cli_unhandled_rejections_mode). (rejection id: 345)

I'm pretty sure it's because the bot isn't able to read the status of such users who are offline and don't have a status. I'd be thankful for a help since I couldn't figure out the fix to this.
This is my code :
client.on('presenceUpdate', async (oldPresence, newPresence) => {

    const role = newPresence.guild.roles.cache.get("832132526302035992");
    const member = newPresence.member
    const activities = member.user.presence.activities[0];

    if (activities && (activities.state.includes( ".gg/moonxile" ) || activities.state.includes("discord.gg/moonxile" ))) {
      return newPresence.member.roles.add(role)
      .catch(err => {
      console.log(err)
      return;
      })

    } else {
    if(member.roles.cache.get(role.id)) {
      newPresence.member.roles.remove(role)
      .catch(err => {
      console.log(err)
      return;

      })
      }
    }
});

A: With some people when they change from exist state to none it will not having data so the checking should be

    if (activities &&  activities.state && (activities.state.includes( ".gg/moonxile" ) || activities.state.includes("discord.gg/moonxile" ))) {
      return newPresence.member.roles.add(role)
      .catch(err => {
      console.log(err)
      return;
      })

    }

A: Check for activities first, then check for activities.state and finally include .include()


text:
Q: Hide specific value of option form I have this code generated with plugin arrays categories. I need hide some specifics categories from form, like "pro", "basico" and "Todas las Provincias.
<select id="category_name" class="taxonomies-filter-widget-input tax-with-childrens" name="category_name">
<option value="0">Todas</option>
<option class="level-0" value="pro">pro</option>
<option class="level-0" value="basico">basico</option>
<option class="level-0" value="todas-las-provincias">Todas las Provincias</option>
<option class="level-0" value="alava">Álava</option>
<option class="level-0" value="albacete">Albacete</option>
<option class="level-0" value="alicante">Alicante</option>
<option class="level-0" value="almeria">Almería</option>
<option class="level-0" value="avila">Ávila</option>
<option class="level-0" value="teruel">Teruel</option>
</select>

A: $(function() {
    var toHideValues = ["pro", "basico", "todas-las-provincias"];
    $('#category_name option').each(function() {
        var $option = $(this);
        if ($.inArray($(this).val(), toHideValues) !== -1) {
            $option.hide();
        }
    });
});

See this : http://jsfiddle.net/p6fY7/

A: Problem solved!
(function($) {
$("select > option[value='pro']").remove();
$("select > option[value='basico']").remove()
})(jQuery);

A: this would do just what you need
var el = "alava";
$('select option[value="' + el + '"]').hide();

here is a working example :
http://jsfiddle.net/vrcrP/

A: this will work for you
$('.level-0').each(function(){
var value = $(this).attr('value');
if (value == 'pro' || value == 'basico' || value == 'Todas las Provincias' ) {
$(this).hide();
}
});


text:
Q: Check value In each row datagridview in vb I have a datagridview and I want to check a cell value in each rowdatagridview. I take the program in button. So, I click the button and will check the value. If the value from input text equal to the value, will go to next row, if different will still in the row and check the value from input text and will go to the next row if the cell value equal with input text. I'm newbie in vb guys.
I used to play with Arduino. In Arduino, I assume the program like this:
If (datagridview1.cell(1).value == textbox.text/input value) {
  i = i++
Else
  i = i
}

A: I think if i have understood your question correctly something like this will help.
For Each row as DataGridViewRow in yourDataGridView.Rows
    If Not row.Cells(columnName/index).Value = Textbox1.Text Then
       'Set the rows Value to your Textbox.Text/Input Value
       row.Cells(columnName/index).Value = Textbox1.Text
    End If
Next


text:
Q: In-line string substitution in Java? I'm doing some work in Processing, which is basically Java. I normally do only work in Ruby and I've gotten used to a lot of the fairly elegant and beautiful code conventions there.
If I have a string that I'd like to insert other strings into, what's the most beautiful way to do it in Java?
In Ruby, I do something like this generally (where each variable is a string):
p "The #{person_title} took a #{mode_of_transit} to the #{holiday_location} for a nice #{verb} in the #{noun}"

It would appear in Java that I need to manually concatenate them like this:
println("The " + personTitle + " took a " + modeOfTransit + " to the " holidayLocation + for a nice " + verb + " in the " + noun)

This just feels wrong to me. It works, but it just isn't smooth. Is there a way to do this in Java?

A: The closest would be something like:
 String s = String.format("The %s took a %s to the %s for a nice %s in the %s", personTitle, modeOfTransit, holidayLocation, verb, noun);

A: Take a look at the String.format() method for building a formatted string, or PrintStream.format() for formatting and printing directly. (System.out is a PrintStream.)

A: You may use System.out.format() method to write formatted string to System.out or format a string using the static method String.format. For more details on formatting read this article.
System.out.format("The %s took a %s to the %s for a nice %s in the %s",
         personTitle, modeOfTransit, holidayLocation, verb, noun);

A: You can use System.out.printf (same as System.out.format) and a format string ("%s" is the format specifier for a string) to both make it look more fluid and also format your output the way you want.
There's also String.format that returns the formatted String, rather than having to print it (like sprintf in C).


text:
Q: Is there possibility of exporting mathematica code directly into $\LaTeX$? I'm a very novice  user of Mathematica - is there possibility of exporting Mathematica code directly into $\LaTeX$? I'm interested only in exporting mathematical formulas. Also, from which version of program is it possible?

A: The Mathematica help system has useful information, and links to videos etc.

A: Select the text, right click, and select Copy As -> LaTex.


text:
Q: Parameter override: 'TypeError: Cannot read property 'type' of undefined', make sure it follows JavaScript Object Notation (JSON) I want to override parameters in the azure pipeline task AzureResourceGroupDeployment@2, but cannot get it to work.
I get the error:
Parameter override: 'TypeError: Cannot read property 'type' of undefined', make sure it
follows JavaScript Object Notation (JSON)

The task is configured like this:
- task: AzureResourceGroupDeployment@2
  displayName: Validate ADF Template
  inputs:
    azureSubscription: DataPlatform Deploy SP - Staging
    resourceGroupName: $(RESOURCE_GROUP)
    deploymentMode: Validation
    csmFile: $(Pipeline.Workspace)/DataFactory_ARM/ARMTemplateForFactory.json
    csmParametersFile: $(Pipeline.Workspace)/DataFactory_ARM/ARMTemplateParametersForFactory.json
    overrideParameters: -factoryName "$(DATAFACTORY_NAME)"
      -Storage_01_RCE_accountKey "$(cedl2-key1)"
      -Storage_02_Curated_accountKey "$(curdl2-key1)"
      -Storage_03_LandingZone_connectionString "$(lnzsa-conn-string)"
      -Storage_04_AzFunction_connectionString "$(funcsa-conn-string)"
      -CT-Reload-ST_properties_CT_Customers_reload_parameters_KafkaTopic "dapl-acc-ct-customers"
      -DW_Optimove-DE_properties_pl_demandware_dim_product_parameters_env "$(ENV)"
      -DW_Optimove-DE_properties_pl_demandware_dim_account_parameters_env "$(ENV)"
      -DW_Optimove-DE_properties_pl_demandware_fact_order_parameters_env "$(ENV)"
      -DW_Optimove-DE_properties_pl_demandware_dim_product_parameters_cluster_id "$(DATABRICKS_CLUSTERID_DEMANDWARE)"
      -DW_Optimove-DE_properties_pl_demandware_dim_account_parameters_cluster_id "$(DATABRICKS_CLUSTERID_DEMANDWARE)"
      -DW_Optimove-DE_properties_pl_demandware_fact_order_parameters_cluster_id "$(DATABRICKS_CLUSTERID_DEMANDWARE)"
      -DW_Optimove-IT_properties_pl_demandware_dim_product_parameters_env "$(ENV)"
      -DW_Optimove-IT_properties_pl_demandware_dim_account_parameters_env "$(ENV)"
      -DW_Optimove-IT_properties_pl_demandware_fact_order_parameters_env "$(ENV)"
      -DW_Optimove-IT_properties_pl_demandware_dim_product_parameters_cluster_id "$(DATABRICKS_CLUSTERID_DEMANDWARE)"
      -DW_Optimove-IT_properties_pl_demandware_dim_account_parameters_cluster_id "$(DATABRICKS_CLUSTERID_DEMANDWARE)"
      -DW_Optimove-IT_properties_pl_demandware_fact_order_parameters_cluster_id "$(DATABRICKS_CLUSTERID_DEMANDWARE)"
      -DW_Optimove-UK_properties_pl_demandware_dim_product_parameters_env "$(ENV)"
      -DW_Optimove-UK_properties_pl_demandware_dim_account_parameters_env "$(ENV)"
      -DW_Optimove-UK_properties_pl_demandware_fact_order_parameters_env "$(ENV)"
      -DW_Optimove-UK_properties_pl_demandware_dim_product_parameters_cluster_id "$(DATABRICKS_CLUSTERID_DEMANDWARE)"
      -DW_Optimove-UK_properties_pl_demandware_dim_account_parameters_cluster_id "$(DATABRICKS_CLUSTERID_DEMANDWARE)"
      -DW_Optimove-UK_properties_pl_demandware_fact_order_parameters_cluster_id "$(DATABRICKS_CLUSTERID_DEMANDWARE)"
      -DW_Optimove-RU_properties_pl_demandware_dim_product_parameters_env "$(ENV)"
      -DW_Optimove-RU_properties_pl_demandware_dim_account_parameters_env "$(ENV)"
      -DW_Optimove-RU_properties_pl_demandware_fact_order_parameters_env "$(ENV)"
      -DW_Optimove-RU_properties_pl_demandware_dim_product_parameters_cluster_id "$(DATABRICKS_CLUSTERID_DEMANDWARE)"
      -DW_Optimove-RU_properties_pl_demandware_dim_account_parameters_cluster_id "$(DATABRICKS_CLUSTERID_DEMANDWARE)"
      -DW_Optimove-RU_properties_pl_demandware_fact_order_parameters_cluster_id "$(DATABRICKS_CLUSTERID_DEMANDWARE)"
      -DW_Optimove-FR_properties_pl_demandware_dim_product_parameters_env "$(ENV)"
      -DW_Optimove-FR_properties_pl_demandware_dim_account_parameters_env "$(ENV)"
      -DW_Optimove-FR_properties_pl_demandware_fact_order_parameters_env "$(ENV)"
      -DW_Optimove-FR_properties_pl_demandware_dim_product_parameters_cluster_id "$(DATABRICKS_CLUSTERID_DEMANDWARE)"
      -DW_Optimove-FR_properties_pl_demandware_dim_account_parameters_cluster_id "$(DATABRICKS_CLUSTERID_DEMANDWARE)"
      -DW_Optimove-FR_properties_pl_demandware_fact_order_parameters_cluster_id "$(DATABRICKS_CLUSTERID_DEMANDWARE)"
      -DW_Optimove-JP_properties_pl_demandware_dim_product_parameters_env "$(ENV)"
      -DW_Optimove-JP_properties_pl_demandware_dim_account_parameters_env "$(ENV)"
      -DW_Optimove-JP_properties_pl_demandware_fact_order_parameters_env "$(ENV)"
      -DW_Optimove-JP_properties_pl_demandware_dim_product_parameters_cluster_id "$(DATABRICKS_CLUSTERID_DEMANDWARE)"
      -DW_Optimove-JP_properties_pl_demandware_dim_account_parameters_cluster_id "$(DATABRICKS_CLUSTERID_DEMANDWARE)"
      -DW_Optimove-JP_properties_pl_demandware_fact_order_parameters_cluster_id "$(DATABRICKS_CLUSTERID_DEMANDWARE)"
      -DW_Optimove-IE_properties_pl_demandware_dim_product_parameters_env "$(ENV)"
      -DW_Optimove-IE_properties_pl_demandware_dim_account_parameters_env "$(ENV)"
      -DW_Optimove-IE_properties_pl_demandware_fact_order_parameters_env "$(ENV)"
      -DW_Optimove-IE_properties_pl_demandware_dim_product_parameters_cluster_id "$(DATABRICKS_CLUSTERID_DEMANDWARE)"
      -DW_Optimove-IE_properties_pl_demandware_dim_account_parameters_cluster_id "$(DATABRICKS_CLUSTERID_DEMANDWARE)"
      -DW_Optimove-IE_properties_pl_demandware_fact_order_parameters_cluster_id "$(DATABRICKS_CLUSTERID_DEMANDWARE)"
      -DW_Optimove-ES_properties_pl_demandware_dim_product_parameters_env "$(ENV)"
      -DW_Optimove-ES_properties_pl_demandware_dim_account_parameters_env "$(ENV)"
      -DW_Optimove-ES_properties_pl_demandware_fact_order_parameters_env "$(ENV)"
      -DW_Optimove-ES_properties_pl_demandware_dim_product_parameters_cluster_id "$(DATABRICKS_CLUSTERID_DEMANDWARE)"
      -DW_Optimove-ES_properties_pl_demandware_dim_account_parameters_cluster_id "$(DATABRICKS_CLUSTERID_DEMANDWARE)"
      -DW_Optimove-ES_properties_pl_demandware_fact_order_parameters_cluster_id "$(DATABRICKS_CLUSTERID_DEMANDWARE)"
      -OM-API-ETL-ST_properties_OM_reload_parameters_Env "acc"

$(ENV is set as stage variable:
ENV: acc
$(DATABRICKS_CLUSTERID_DEMANDWARE) is set as job variable
DATABRICKS_CLUSTERID_DEMANDWARE: 1234-123456-abcd123
I have tried replacing "$(ENV)" with "acc" but. same error.
Also tried adding a single quote before the first key and after the last key.
The full log of the task is available through pastebin as it was to big to paste in here:
https://pastebin.com/gijMthx6

A: The issue is Deployment template validation failed: 'The template parameters 'DW_Optimove-DE_properties_pl_demandware_dim_product_parameters_env, ... , DW_Optimove-ES_properties_pl_demandware_fact_order_parameters_cluster_id' in the parameters file are not valid; they are not present in the original template and can therefore not be provided at deployment time. The only supported parameters for this template are 'factoryName, ADF_Pipeline_Database_connectionString, Storage_01_RCE_accountKey, Storage_02_Curated_accountKey, Storage_03_LandingZone_connectionString, Storage_04_AzFunction_connectionString,....'
The error message says that the ARM template is missing these parameters. You need check your ARM template file.
The error message says the ARM template has the following parameters:
...
"parameters": {
  "factoryName": {
    "type": "string"
  },
  "ADF_Pipeline_Database_connectionString": {
    "type": "string"
  },
  "Storage_01_RCE_accountKey": {
    "type": "string"
  },
  "Storage_02_Curated_accountKey": {
    "type": "string"
  },
  "Storage_03_LandingZone_connectionString": {
    "type": "string"
  }
  ....
    },
    "variables": {},
    ...

You could check this doc and ticket for more details.


text:
Q: Why git search does not find string I already used search and also found another post with answers, but I can't find the following string in my history (using git bash on Windows):
$ git log --all -S'paste0(gsub("0",""'

And it must have been added somewhere - I think:

and later

Any idea what can go wrong? Did I miss anything?

A: There seems to be a space after the comma in the screenshot, but not in your query.


text:
Q: Different Meanings of "Clusters" in Statistics Typically, I have always come across the term "cluster" within statistics as reference to "clustering" - that is, for example the "K Means Clustering" algorithm. Recently, I have started coming across the term "cluster" in regression and longitudinal settings, such as "clustered profiles", "clustered survival data" and "cluster correlated data."
I am having a bit of trouble in understanding this point - do "clusters" (regardless of their context) generally refer to some groupings of observations within a dataset? Or in the case of survival analysis and regression, are "clusters" referring to something else?
Thanks!

A: From the Merriam-Webster Dictionary:

a number of similar things that occur together

The two uses of the term that you describe have to do whether you are trying to discover a cluster in a data set or whether you are trying to account for known clusters in a data set. The first use is what you are familiar with already, so here's a brief explanation of the second.
Many statistical tests are based on an assumption that the observations are "independently and identically distributed" (iid). That assumption, however, is often not tenable. For example you might be evaluating results for individuals who are inherently grouped in ways that might lead to outcomes being correlated within each group: students grouped within schools, patients within hospitals.
There are several ways to account for such multi-level structuring of data, discussed for example on this page. The "cluster" term that you see as an option in many regression models is one way to do that. It takes the associations of outcomes within each "cluster" into account when estimating the standard errors of coefficient estimates.
The dictionary entry cited above has two additional, self-explanatory uses of the term that are important in statistics:

a larger than expected number of cases of disease (such as leukemia) occurring in a particular locality, group of people, or period of time

a number of computers networked together in order to function as a single computing system.


text:
Q: Shouldn't motion be represented as a Taylor series rather than a finite sum of functions or a polynomial? Since the change in velocity of an object at rest prior to time $t_{0}$ implies a change in acceleration — that is, let's postulate, $ \mathbb{P} $, the object would have remained still, so there was no velocity change before time $t_{0}$, or put formally, $ \forall( t<t_{0} ), \| \Delta \vec{v} \| = 0 $), which implies a change in jerk, because (by the same reasoning) before time $t_{0}$ standstill requires there was no change in velocity (remember our postulate $ \mathbb{P} $), which also requires no change in acceleration, or put formally, the standstill-postulate $ \mathbb{P} \implies \forall( t<t_{0} ), \| \Delta \vec{a} \| = 0 $), but by this same reasoning, the standstill-postulate requires that there was no prior change in jerk, or put formally, the standstill-postulate $  \mathbb{P} \implies \forall( t<t_{0} ), \| \Delta \vec{j} \| = 0 $, etc., by induction we can arrive at the generalized form:  $\tiny \forall(n\in \mathbb{N}) \left [ \left ( \forall( t<t_{0} ), \| \Delta \vec{x^{\left ( n \right )}\left ( t \right )}\| = 0 \right ) \wedge \left ( \exists( t \geq t_{0} ) \exists(\nu\in\mathbb{N}) [ \vec{x^{\left ( \nu \right )}\left ( t \right )} > 0 ] \right ) \implies \forall( t\geq t_{0} )\exists(\nu \in \mathbb{N}) [ \nu = ( n + 1 ) \wedge \vec{x^{\left ( \nu \right )}\left ( t \right )} > 0 ] \right ] $  which is to say, if an object was at standstill and it obtained some motion after  $t_{0}$, this implies that for any given time-derivative its next highest time-derivative should be non-zero in view of the fact that its prior time-derivative changed some time after $t_{0}$  — but if this is correct, shouldn't that motion be represented as a Taylor series of position functions rather than a polynomial or a finite sum of any other functions?

A: If you explicitly state the times $t$ for which some finite sum $x(t)=\sum_i^N x_i(t)$ is valid, then you avoid the issue altogether.
For example, a ball is dropped at $t=0$. I can write $y(t) = h+1/2 gt^2 $ for $t\ge0$ and be done with it.


text:
Q: cmd terminates when delete fails I have the following bat file mybat.bat that:
1) Stops a service
2) Deletes some logfiles
3) starts the service again:
@echo off

net stop "myservice"
if ERRORLEVEL 1 goto error
exit
:error
echo There was a problem...maybe it was alreay stopped

rem sometimes the terminal simply closes when trying to delete the logfiles :-(
set folder="C:\stuff\logs"
del %folder%\*.*   /s /f  /q

net start "myservice"
if %errorlevel% == 2 echo Could not start service.
if %errorlevel% == 0 echo Service started successfully.
echo Errorlevel: %errorlevel%

I manually open a cmd.exe instance and run mybat.bat but sometimes it simply closes when its trying to delete the logfiles and the content of stuff\logs is not deleted. Any ideas on why this is happening and how to keep the cmd instance alive even though the delete fails?
If I wait sometime and execute the mybat again it typically works.

A: I see a few problems.  The biggest is, do you know you have exit just below where you stop your services?  Did you intend, perhaps, a goto :label there instead?
Also, try moving your quotation marks from the set folder= line to the del %folder% line like this:
set folder=C:\stuff\logs
del /s /f /q "%folder%\*.*"

Or, to delete subfolders as well,
set folder=C:\stuff\logs
rmdir /q /s "%folder%" && md "%folder%"

Here, try this.
@echo off

net stop "myservice" || echo There was a problem...maybe it was alreay stopped

:: Now that "exit" is gone, the console probably won't close any more.

set folder=C:\stuff\logs
rmdir /q /s "%folder%" && md "%folder%"

net start "myservice"

:: "if ERRORLEVEL x" checks if %errorlevel% is greater than or equal to x

if ERRORLEVEL 1 (
    echo Could not start service.
) else (
    echo Service started successfully.
)

echo Errorlevel: %errorlevel%

note: The net start "myservice" code could be condensed like this:
:: (leave the carat in the emoticon.  It escapes the parenthesis.)
(net start "myservice" && echo Great success.) || echo Fail. :^(

echo Errorlevel: %errorlevel%

See conditional execution for more info.


text:
Q: iOS app occasionally sends an invalidly-formatted ISO8601 date to REST API A couple of times a day, our PHP REST API logs an error causing by an invalidly-formatted ISO8601 date, coming from a GET request sent by our iOS app. The interesting thing is that most of the calls are fine (eg. 2015-07-07T00:00:00+10:00), but every so often we get a strange one (eg. 2015-07-07T12:00:00 am+10:00).
The code I believe is causing this is as follows:
NSDateFormatter *dateFormatter = [[NSDateFormatter alloc] init];
[dateFormatter setDateFormat:@"yyyy-MM-dd'T'HH:mm:ssZZZZZ"];

NSString *iso8601StringStart = [dateFormatter stringFromDate:self.searchStartTime];

Is there any circumstance in which NSDateFormatter could somehow (incorrectly) get am/pm from "yyyy-MM-dd'T'HH:mm:ssZZZZZ", when it's clearly the unintended behaviour? Are there certain kinds of NSDate that cause different behaviour? I'm stumped. The date given is always created via dateFromComponents.

A: I do not believe that that format string could ever generate the date with the am/pm annotations which you show. If I were you, my first course would be to double check that those dates are really being generated by those lines of code.
However, if you're sure this is happening, the only issue I can see is that it might be incorrect that you are not explicitly setting the locale and the calendar of the date formatter object. The date format syntax is defined by the unicode consortium, and the governing spec does say in section 4.5 that "If locales are not listed, dayPeriods fallback to AM/PM". I don't understand the whole document, but it suggests that being very explicit is the safest path.
If your only requirement is ISO8601, then you could use RFC3339 in UTC time zone, since this is a profile of ISO8601. This creates a correct formatter for that format:
let formatter = NSDateFormatter()
formatter.dateFormat = "yyyy-MM-dd'T'HH:mm:ss.SSS'Z"
formatter.timeZone = NSTimeZone(forSecondsFromGMT: 0)
formatter.calendar = NSCalendar(calendarIdentifier: NSCalendarIdentifierISO8601)!
formatter.locale = NSLocale(localeIdentifier: "en_US_POSIX")

A: My final solution (towards which I was nudged by algal's answer):
[dateFormatter setLocale:[[NSLocale alloc] initWithLocaleIdentifier:@"en_US_POSIX"]];

The Unicode spec was helpful (thanks algal), as was this Apple Technical QA, which suggested the en_US_POSIX as a specific solution.

"On iOS, the user can override the default AM/PM versus 24-hour time setting (via Settings > General > Date & Time > 24-Hour Time), which causes NSDateFormatter to rewrite the format string you set, which can cause your time parsing to fail."

Most helpfully, I found this explanation of the behaviour by huyz, although a little old:

When iPhone users change their region format between, say, "United States" and "France", the users' "24-Hour Time" setting is automatically switched to the mode that is most prevalent in that region. In France, that would set 24-Hour Time to "ON", and in the U.S., that would set it to "OFF". The users can then manually override that setting and that's where trouble starts.
The problem comes from NSDateFormatter somehow "getting stuck" in the 12 or 24-hour time mode that the user has manually selected. So if a French user manually selects 12-hour mode, and the application requested NSDateFormatter to output time with the 24-hour format "HHmm", it would actually receive time in a 12-hour format, e.g. "01:00 PM", as if the application had instead requested "hhmm aa". The reverse would happen if a US user manually selected 24-hour mode: outputting time with the 12-hour format "hhmm aa" would actually get you time in the 24-hour format instead, e.g. "17:00″.


text:
Q: Check if a file is an image or a video Is there a way to check if the file I'm loading as a URI is a image or a video in android? I'm trying to dynamically loaded both images and videos into fragments for a list/detail view and need to tell them apart.

A: I'd check the mimeType and then check if it corresponds to an image or video.
A full example, for checking if a filepath is an image, would be:
public static boolean isImageFile(String path) {
    String mimeType = URLConnection.guessContentTypeFromName(path);
    return mimeType != null && mimeType.startsWith("image");
}

And for video:
public static boolean isVideoFile(String path) {
    String mimeType = URLConnection.guessContentTypeFromName(path);
    return mimeType != null && mimeType.startsWith("video");
}

A: It seems most proper to check type via ContentResolver (as in jsrssoftware answer). Although, this may return null in some cases.
In such case, I ended up trying to decode stream as Bitmap to confirm it is in image (but only decoding bounds, so it's quite fast and not much memory-consuming).
My image-tester helper function looks like this:
public static boolean checkIsImage(Context context, Uri uri) {
    ContentResolver contentResolver = context.getContentResolver();
    String type = contentResolver.getType(uri);
    if (type != null) {
        return  type.startsWith("image/");
    } else {
        // try to decode as image (bounds only)
        InputStream inputStream = null;
        try {
            inputStream = contentResolver.openInputStream(uri);
            if (inputStream != null) {
                BitmapFactory.Options options = new BitmapFactory.Options();
                options.inJustDecodeBounds = true;
                BitmapFactory.decodeStream(inputStream, null, options);
                return options.outWidth > 0 && options.outHeight > 0;
            }
        } catch (IOException e) {
            // ignore
        } finally {
            FileUtils.closeQuietly(inputStream);
        }
    }
    // default outcome if image not confirmed
    return false;
}

For videos, one could do similar approach. I did not need it, but I believe MediaMetadataRetriever could be used to verify if stream contains valid video in case type check fails.

A: enum class MediaType {
    MediaTypeImage,
    MediaTypeVideo,
    Unknown
}

fun getMediaType(context: Context, source: Uri): MediaType {
    val mediaTypeRaw = context.contentResolver.getType(source)
    if (mediaTypeRaw?.startsWith("image") == true)
        return MediaType.MediaTypeImage
    if (mediaTypeRaw?.startsWith("video") == true)
        return MediaType.MediaTypeVideo
    return MediaType.Unknown
}

A: If you are getting your Uri from a content resolver you can get the mime type using getType(Uri);
ContentResolver cR = context.getContentResolver();
String type = cR.getType(uri);

should get back something similar to "image/jpeg" which you can check against for your display logic.

A: The best way to check is ...
Image:
private fun isImage(path: String): Boolean {
        val mimeType: String = URLConnection.guessContentTypeFromName(path)
        return mimeType.startsWith("image")
}

Video:
private fun isVideo(path: String): Boolean {
        val mimeType: String = URLConnection.guessContentTypeFromName(path)
        return mimeType.startsWith("video")
}

.zip or .rar:
private fun isZip(name: String): Boolean {
        return name.contains(".zip") || name.contains(".rar")
}

A: Easiest way is to check extensions I guess
if ( file.toString().endsWith(".jpg") {
//photo
} else if (file.toString().endsWith(".3gp")) {
//video
}


text:
Q: ScrollToRowAtIndex equivalent in Flutter Background:
I recently started development using flutter/dart, and as you can guess I came from iOS background. It was very easy to scroll in a UITableView to some given indexPath (section, row) in iOS, and I believe similar is the case in Android, but it has been a real pain to achieve the same in Flutter.
Questions:
Can someone please point me to a solution where, in a ListView, I can scroll to a given index smoothly?
What I have tried:
I have been trying different packages like (https://pub.dev/packages/flutter_section_table_view) because I needed a section-wise list view, it comes with an animate to section/row, but it depends on the accurate height of each row and creates a map to jump or animate the scroll view to that height value. It is not easy to achieve given that the items in that list view are dynamic and can expand or shrink depending on some actions. I tried to handle that as well by calculating heights and all that, but that was impacting the performance of scrolling. That is why I am looking for a solution with some precalculated map that can scroll to the tag or hash just like we have in web pages.

A: You can copy paste run full code below
You can use package https://pub.dev/packages/scroll_to_index
You can wrap widget with AutoScrollTag and call controller.scrollToIndex
code snippet
await controller.scrollToIndex(98,
        preferPosition: AutoScrollPosition.begin);
...
Widget _wrapScrollTag({int index, Widget child}) => AutoScrollTag(
        key: ValueKey(index),
        controller: controller,
        index: index,
        child: child,
        highlightColor: Colors.black.withOpacity(0.1),
      );

working demo

full code
import 'dart:math' as math;

import 'package:flutter/material.dart';
import 'package:scroll_to_index/scroll_to_index.dart';

void main() => runApp(MyApp());

class MyApp extends StatelessWidget {
  // This widget is the root of your application.
  @override
  Widget build(BuildContext context) {
    return MaterialApp(
      title: 'Scroll To Index Demo',
      theme: ThemeData(
        primarySwatch: Colors.blue,
      ),
      home: MyHomePage(title: 'Scroll To Index Demo'),
    );
  }
}

class MyHomePage extends StatefulWidget {
  MyHomePage({Key key, this.title}) : super(key: key);

  final String title;

  @override
  _MyHomePageState createState() => _MyHomePageState();
}

class _MyHomePageState extends State<MyHomePage> {
  static const maxCount = 10000;
  final random = math.Random();
  final scrollDirection = Axis.vertical;

  AutoScrollController controller;
  List<List<int>> randomList;

  @override
  void initState() {
    super.initState();
    controller = AutoScrollController(
        viewportBoundaryGetter: () =>
            Rect.fromLTRB(0, 0, 0, MediaQuery.of(context).padding.bottom),
        axis: scrollDirection);
    randomList = List.generate(maxCount,
        (index) => <int>[index, (1000 * random.nextDouble()).toInt()]);
  }

  @override
  Widget build(BuildContext context) {
    return Scaffold(
      appBar: AppBar(
        title: Text(widget.title),
      ),
      body: ListView(
        scrollDirection: scrollDirection,
        controller: controller,
        children: randomList.map<Widget>((data) {
          return Padding(
            padding: EdgeInsets.all(8),
            child: _getRow(data[0], math.max(data[1].toDouble(), 50.0)),
          );
        }).toList(),
      ),
      floatingActionButton: FloatingActionButton(
        onPressed: _scrollToIndex,
        tooltip: 'Increment',
        child: Text(counter.toString()),
      ),
    );
  }

  int counter = -1;
  Future _scrollToIndex() async {
    setState(() {
      counter++;

      if (counter >= maxCount) counter = 0;
    });

    //await controller.scrollToIndex(counter, preferPosition: AutoScrollPosition.begin);
    await controller.scrollToIndex(98,
        preferPosition: AutoScrollPosition.begin);
    controller.highlight(counter);
  }

  Widget _getRow(int index, double height) {
    return _wrapScrollTag(
        index: index,
        child: ListTile(title: Text('index: $index, height: $height')));
  }

  Widget _wrapScrollTag({int index, Widget child}) => AutoScrollTag(
        key: ValueKey(index),
        controller: controller,
        index: index,
        child: child,
        highlightColor: Colors.black.withOpacity(0.1),
      );
}


text:
Q: Accessibility for iOS, VoiceOver read order issue
Is it possible to change the order in which the VoiceOver feature for accessibility in iPad reads out the elements, when the 'Two-finger Flick Down' gesture is done?
For the attached image, which contains 3 labels and a button, the VoiceOver reads the elements in the following way,
Label 1 -> Label 2 -> Button -> Label 3
Can the order be changed to,
Label 1 -> Label 2 -> Label 3 -> Button

A: I tried setting the shouldGroupAccessibilityChildren to YES but it didn't work for me.
What did work for me was setting the accessibility label of the parent view directly (because I wanted all the items to be read in one go/one VoiceOver gesture).
[cell setAccessibilityLabel:[NSString stringWithFormat:@"%@, %@", cityLabel, temperatureLabel]];

The above snippet of codes is from Apple's documentation Enhancing the Accessibility of Table View Cells

A: The quickest way to achieve this for your example is to place the three labels in a transparent UIView subclass to serve as a container for your labels. This subclass will have to be properly setup to let VoiceOver know how to interpret it. If your deployment target is iOS6 then you can simply answer the "should group accessibility children" question in this subclass.
-(BOOL)shouldGroupAccessibilityChildren{
    return YES;
}

For below iOS6 it would be more complicated, except that your UIView container subclass would contain only UILabels which are accessibility elements. You could implement it like this:
-(BOOL)isAccessibilityElement{
    return NO;
}
-(NSInteger)accessibilityElementCount{
    return self.subviews.count;
}
-(id)accessibilityElementAtIndex:(NSInteger)index{
    return [self.subviews objectAtIndex:index];
}
-(NSInteger)indexOfAccessibilityElement:(id)element{
    return [self.subviews indexOfObject:element];
}

I have tested this example code and it does what you are looking for, if you need any clarification please add a comment. Always happy to help make things more accessible.

A: In Swift, attaching an IBOutlet to the parent UIView, then setting shouldGroupAccessibilityChildren to true will suffice.

abc.shouldGroupAccessibilityChildren = true

I did note that if also setting isAccessibilityElement = true the grouping will not take effect. Similarly, checking the accessibility checkbox in the storyboard or xib will also prevent the grouping from taking place.

A: I think you can do it in the storyboard. The VoiceOver order is determined by the order of the views in the document outline.
Just drag and drop the views in the view hierarchy in the right order.


text:
Q: Sum of reciprocals of prime-index-primes Let $p_1=2$, $p_2=3$, $p_3=5$, $\ldots$ be an enumeration the prime numbers. If $q$ is a prime number, we call $p_q$ a prime-index-prime. A list of prime-index-primes can be found here.
My question is:

Does $$\sum_{i=1}^{\infty}\frac{1}{p_{p_i}}=\frac{1}{3}+\frac{1}{5}+\frac{1}{11}+\frac{1}{17}+\frac{1}{31}+\ldots$$ converges or diverges?

The graph below shows the values of the partial sums $S_n$ of the previous series from $n=1$ to $n=1184$, $n$ is the $x$-coordinate and $S_n$ is the $y$-coordinate.

We can't conclude much by the graph. But my guess is that it diverges because, perhaps, it grows very, very, slow.

A: Maybe it's interesting to see a proof of the convergence. From PNT we have that $$p_{n}\sim n\log\left(n\right)
 $$ as $n\rightarrow\infty
 $ so $$p_{p_{n}}\sim p_{n}\log\left(p_{n}\right)\sim n\log^{2}\left(n\right)
 $$ and we can observe that, using the integral test, that $$\sum_{n=2}^{\infty}\frac{1}{n\log^{2}\left(n\right)}\leq\frac{1}{2\log^{2}\left(2\right)}+\int_{2}^{\infty}\frac{dx}{x\log^{2}\left(x\right)}=\frac{1+2\log\left(2\right)}{2\log^{2}\left(2\right)}.$$

A: Your link to the OEIS says that the series converges: "$\displaystyle\sum_{n\ge1} {1\over a(n)}$ converges. In fact, $\displaystyle\sum_{n>N} {1\over a(n)} < {1\over \ln(N)}$, by the integral test. --- Jonathan Sondow, Jul 11 2012."


text:
Q: Managing many clients with the same java projects with small changes I have several java projects with small differences between them for each client, those differences are:

*

*differences in jrxml reports

*differences in properties files

*Changes in static classes

When I go to update the clients, I committed to SVN and generating the WAR for each project (approx 90mb) using Jenkins, upload to FTP and install it on each server.
The problem I'm having is the time it takes me to do it this way, which is between 3 and 4 hours for 6 projects every week.

*

*It is possible that all clients are handled by a single project (single WAR) and separate the differences outside the war?

*What would be the best way to do this?

*This is recommended or is there a better way to handle this?

A:
It is possible that all clients are handled by a single project (single WAR) and separate the differences outside the war?

Sure but... bear with me for a second.
With 4 hours of building/deployment time i'd say the bandwith between the jenkins server and you production servers could be the issue. If upgrading it is not viable you will need to optimize your projects setup.
Usually 90% of the size of a war file is composed by the collection of libraries your application relies on to do his job (spring, hibernate, struts and so on...).
Supposing you currently store them in your WEB-INF/lib folder, you could consider to extract those and install them in your application server shared classpath, removing them from your war.
It will not shock me if after this operation you will not need further optimizations...

A: I found that when I need to save time, this command saves me every time:
rsync -razpv --delete /folder/name server_name:/folder/name

you can also add:
--exclude 'file/inside/folder'

Use it cleanly, and wisely, but a process of copying files for some of my builds that took 20 minutes always, now take 10 seconds when there is no change, and less than 1 minute when there is a change.
Also - did you think about a management tool (puppet/chef/ansible) to do some of the work?


text:
Q: Книги по написанию драйверов под Windows Доброго времени суток. Задался я тут целью написать драйвер под Windows, да и вообще разобраться с этим, поэтому прошу у Вас помощи. Подскажите статьи, книги по написанию драйверов под Windows. Сразу оговорюсь я подхожу к этому серьезно, поэтому готов перелопатить кучу материала, который хоть как то связан с данной темой. Наверное, мне понадобиться знание asm и С++ (С я неплохо знаю). Поэтому прошу так же посоветовать дельные книги по asm.
A: Начните с скачивания WinDDK и изучения сэмплов, идущих в поставке. Их довольно-таки много и они неплохо задокументированы. Это даст хороший толчок для старта, ну а дальше — MSDN, — содержит более чем исчерпывающую документацию по вопросам разработки драйверов.
Часть вызовов недокументированна и относится к Private API, но использовать их, тем не менее, приходится  часто. В этом случае вам понадобятся .dbg файлы соответствующих библиотек для извлечения информации о смещениях в структурах.
A: Мне кажется, что вам может пригодиться следующее:
Почитать:

*

*Уолтер Они. "Использование Microsoft Windows Driver Model"

*Марк Руссинович, Дэвид Соломон. "Внутреннее устройство Microsoft Windows"

*"Everything Windows Driver Development". http://www.osronline.com/

*Блог: http://redplait.blogspot.ru/

*Блог: http://sww-it.ru/
Для разработки:

*

*WinDBG -> Virtual KD -> VmWare Workstation с Windows

*Настроенная переменная _nt_symbol_path

*Возможно пригодится pykd. Модуль к Windbg для автомазации на Python

*Исходники некоторых частей Windows, опытные знают где и что взять. Здесь приводить не имеет смысла

Рекомендации:

*

*Читайте MSDN

*Если плохо понимаете в MSDN читайте в книгах, но предпочитайте англоязычные

*Не читайте книги Солдатова

*Не пытайтесь использовать SoftICE. Он замечателен, но умер. Остался убогий, но всегда актуальный Windbg.

A: Из классики вспоминается, например
Walter Oney - Programming the Microsoft Windows Driver Model (Уолтер Они - Использование Microsoft Windows Driver Model)

A: Если Вам нужно пока только "потренироваться на кошечках", то можно попробовать использовать NuMega DriverStudio - статейка, для написания простейших драйверов и получения представления, она подойдет, хоть и уже малость устарела. А если серьезно драйверами заниматься - то да, - WinDDK.


text:
Q: Woocommerce SPA embedded on woocommerce site I am building a tool (SPA) which helps customers decide which product is best for them. The tool also allows them to make a purchase.
Built using vue.js, and originally intended to be embedded within a page on a Shopify store, I have been asked to replace Shopify with Woocommerce.
I've not used woocommerce in this way before (I typically use it as is, and make changes to templates via action hooks and templates).
The SPA will be embedded within a page on the woocommerce site. I see that woocommerce has an API, with various endpoints from which I can retrieve data, and post when a customer wishes to purchase.
Should I use this api, or, should I make woocommerce templates which return json? It seems sensible to use the API as its useful for this type of thing.
If using the API, will I need to authenticate against it using oauth etc? The SPA will exist within a page of the woocommerce site, within the same domain as the API.
Sorry, this is probably a poor question - I just need a nudge in the right direction. Does anyone have any pointers on the best way I should proceed? Thanks, Rob

A: You can take a look at WooCommerce REST API, which uses Wordpress REST API.   Then you can use the builtin Backbone Client with wp_enqueue_script('wp-api'); and make use of the Backbone.Model and Collection to handle CRUD operations or other JavaScript client libraries.
You can define your own REST Endpoints.
I think this what you are looking for.
And there is of course the old friend AJAX ;-)


text:
Q: How to use .loc with multiple conditions and groupby I have a df thats grouped by 'Key'. I want to flag any row within a group where the discharge date matches another discharge date AND between those rows one of rows has a num1 value in the range of 5-12. Similar question found here, but didn't realize the complexity for having multiple conditions.
df =  pd.DataFrame({'Key': ['10003', '10003', '10003', '10003', '10003','10003','10034', '10034'],
       'Num1': [12,13,13,13,12,13,16,13],
       'Num2': [121,122,122,124,125,126,127,128],
      'admit': [20120506, 20120508, 20121010,20121010,20121010,20121110,20120516,20120520],
  'discharge': [20120508, 20120508, 20121012,20121016,20121023,20121111,20120520,20120520]})
df['admit'] = pd.to_datetime(df['admit'], format='%Y%m%d')
df['discharge'] = pd.to_datetime(df['discharge'], format='%Y%m%d')

initial df:
    Key     Num1    Num2    admit       discharge
0   10003   12      121     2012-05-06  2012-05-08
1   10003   13      122     2012-05-08  2012-05-08
2   10003   13      122     2012-10-10  2012-10-12
3   10003   13      124     2012-10-10  2012-10-16
4   10003   12      125     2012-10-10  2012-10-23
5   10003   13      126     2012-11-10  2012-11-11
6   10034   16      127     2012-05-16  2012-05-20
7   10034   13      128     2012-05-20  2012-05-20

final df
    Key     Num1    Num2    admit       discharge   flag
0   10003   12      121     2012-05-06  2012-05-08  1
1   10003   13      122     2012-05-08  2012-05-08  1
2   10003   13      122     2012-10-10  2012-10-12  0
3   10003   13      124     2012-10-10  2012-10-16  0
4   10003   12      125     2012-10-10  2012-10-23  0
5   10003   13      126     2012-11-10  2012-11-11  0
6   10034   16      127     2012-05-16  2012-05-20  0
7   10034   13      128     2012-05-20  2012-05-20  0

num1_range = [5,6,7,8,9,10,11,12]
df.loc[df.groupby('Key').apply(lambda x : x.duplicated(subset='discharge',keep=False)).values,'flag']=1

A: You can accomplish that by using filter.
df.loc[df.groupby(['Key','discharge']).Num1.filter(lambda x : (x.isin(num1_range).any())&(len(x)>1)).index,'flag']=1
df
Out[317]:
     Key  Num1  Num2      admit  discharge  flag
0  10003    12   121 2012-05-06 2012-05-08   1.0
1  10003    13   122 2012-05-08 2012-05-08   1.0
2  10003    13   122 2012-10-10 2012-10-12   NaN
3  10003    13   124 2012-10-10 2012-10-16   NaN
4  10003    12   125 2012-10-10 2012-10-23   NaN
5  10003    13   126 2012-11-10 2012-11-11   NaN
6  10034    16   127 2012-05-16 2012-05-20   NaN
7  10034    13   128 2012-05-20 2012-05-20   NaN


text:
Q: How to convert two different strings to date format and finding their differences in JSP/JAVA I have 2 strings
Str1: 2016-7-25.15.38. 32. 0 (This is what im getting from DB)
String2 : July 25, 2016 3:19 PM (This one I wrote a program to read from the email timestamp)
How to convert these 2 strings to date format and find their differnce in time.. Pls help.
Ive gone through so many pages in SO and google but not getting anything specific

A:
How to convert these 2 strings to date format

Using Java 8, you'd parse them like this:
ZoneId zoneId = ZoneId.systemDefault();
ZonedDateTime dt1 = ZonedDateTime.parse("2016-7-25.15.38. 32. 0",
            DateTimeFormatter.ofPattern("uuuu-M-d.H.m. s. 0").withZone(zoneId));
ZonedDateTime dt2 = ZonedDateTime.parse("July 25, 2016 3:19 PM",
            DateTimeFormatter.ofPattern("MMMM d, uuuu h:mm a").withZone(zoneId));

Using a non-standard indentation to align format string with value to be parsed, for easier comparison.
The code is using ZonedDateTime so Daylight Savings Time will be handled correctly.

and find their difference in time

Getting the difference in time is then easy enough, using until() or between():
long seconds = dt1.until(dt2, ChronoUnit.SECONDS);
long seconds = ChronoUnit.SECONDS.between(dt1, dt2);

They are the same. Use whichever you like best.

If you print the values above, you get (I'm in USA Eastern time zone):
2016-07-25T15:38:32-04:00[America/New_York]
2016-07-25T15:19-04:00[America/New_York]
-1172

A: I would simply use Oracle to figure out the difference. It's quite easy:
select to_date('2016-07-25.15.38.32', 'yyyy-mm-dd.hh24.mi.ss') - to_date('July 25, 2016 3:19 PM', 'Month dd, yyyy hh:mi PM')
from dual

A: 1.Convert java.sql.timestamp into java.util.Date
Date startDate = new Date(startTimestamp.getTime());
Date endDate= new Date(endTimestamp.getTime());

2.You can find the time difference using TimeUnit enum as below.
Date startDate = // Set start date
Date endDate   = // Set end date

long duration  = endDate.getTime() - startDate.getTime();

long diffInSeconds = TimeUnit.MILLISECONDS.toSeconds(duration);
long diffInMinutes = TimeUnit.MILLISECONDS.toMinutes(duration);
long diffInHours = TimeUnit.MILLISECONDS.toHours(duration);

and so on..


text:
Q: Minimal PySide6 code to get screen resolution I'm fairly new to Qt for Python, and tried to get screen resolution like this:
screen = QtGui.QScreen()
print(f'screen geometry: {screen.geometry()}')

The numbers it gave were crazy, and were different every time I ran the script.
What's the right way to do it?

A: Searching the web gave me surprisingly little info about this.
This answer provided the clues that I needed.
Seems like you have to get to a screen through QApplication.screens(), which returns a list of QScreen objects.
I wanted to know the minimal PySide6 code to get the resolution of a single screen ...
EDIT, UTC 22-11-13 15h :
Researching the suggestion in @musicamente's comment, I found QGuiApplication.primaryScreen.
For a single screen, or the main one, this two-liner gets the screen size in pixels:
from PySide6.QtGui import QGuiApplication
width,height = QGuiApplication().primaryScreen().size().toTuple()

Caution: beginner's error: QGuiApplication.primaryScreen() returns None,
as QGuiApplication does not make an instance without () after it.
In the original answer below, the code seems not quite so minimal now.

from PySide6.QtWidgets import QApplication

class App(QApplication):

    def __init__(self):
        super().__init__()
        (width,height) = self.screens()[0].size().toTuple()
        print( width,height )

App()

self.screens()[0] returns the main (or only) QScreen object.
Note that you don't need to create any window or widget.
Although you need a QApplication instance, you do not need to run its exec loop.
If you want to recurse through all screens, you can add something like:
for scrn in self.screens() :
    print(f'index : {self.screens().index(scrn)}')
    print(f'\n name       : {scrn.name()}')
    print('\n actual size')
    print(f'  width      : {scrn.size().width()}')
    print(f'  height     : {scrn.size().height()}')
    print('\n available size')
    print(f'  width      : {scrn.availableSize().width()}')
    print(f'  height     : {scrn.availableSize().height()}\n')


text:
Q: systemd-nspawn on fedora 21 - can't set root password I'm trying to use systemd-nspawn but when I launch it and try to login as root - it still asks for a password.  They've mentioned turning off auditing - which I've done.
My cmd line says audit=0 at the end.
$ cat /proc/cmdline
BOOT_IMAGE=/vmlinuz-3.19.7-200.fc21.x86_64 root=/dev/mapper/fedora_localhost-root ro rd.lvm.lv=fedora_localhost/swap rd.lvm.lv=fedora_localhost/root rhgb audit=0 quiet

(This is fedora 21) Using these docs https://fedoraproject.org/wiki/Features/SystemdLightweightContainers
When I try to change the password it tells me I have a auth token manipulation error.
$ sudo systemd-nspawn -D /srv/eq1
Spawning container eq1 on /srv/eq1.
Press ^] three times within 1s to kill container.
-bash-4.3# passwd
Changing password for user root.
New password:
Retype new password:
passwd: Authentication token manipulation error
-bash-4.3#

A: it's about selinux context
almost following example 6 from http://www.freedesktop.org/software/systemd/man/systemd-nspawn.html
you have to change the container context and then run it with the proper one:
chcon system_u:object_r:svirt_sandbox_file_t:s0:c0,c1 -R /srv/container
systemd-nspawn -L system_u:object_r:svirt_sandbox_file_t:s0:c0,c1 -D /srv/container

after issuing the second command you'd be able to change password. Right after CTRL+]]] you can issue the usual "systemd-nspawn -bD /srv/container" and boot you container.


text:
Q: AS3 Return Object currently under another Object without HitTestObject Is it possible to return the Object that is underneath/in contact with another Object without using hitTestObject ?
I'm wondering if I can remove the need to loop through an array of 'active' Objects and simply get the instance that's underneath at any given time. Possibly using as3 events ?
many thanks SC

A: You can use the getObjectsUnderPoint() method of the DisplayObjectContainer class.

A: Be carefully, using a getObjectsUnderPoint().
getObjectsUnderPoint() return types Array. this mean specify Point above all DisplayObjects return. sometimes you do not want to get the value. So the objects in the array must be verified. Faced this problem, especially DisplayObjects when they overlap or if you load the other swf


text:
Q: Slightly different FFT results from Matlab fft and Scipy fft I've been making a routine which measures the phase difference between two spectra using NumPy/Scipy.
I already had the routine written in Matlab, so I basically re-implemented the function and the corresponding unit test using NumPy. However, I found that the unit test fails because scipy.fftpack.fft is introducing some small numerical errors:
import numpy as np
import scipy.fftpack.fft
x = np.array([0.0, 1.0, 2.0, 3.0, 4.0, 3.0, 2.0, 1.0])
X = scipy.fftpack.fft(x)

In this case, since the time-domain signal is symmetric, the expected output is
[16.0000   -6.8284         0   -1.1716         0   -1.1716         0   -6.8284]

as shown in the following Matlab code:
>> x = [0.0, 1.0, 2.0, 3.0, 4.0, 3.0, 2.0, 1.0];
>> X = fft(x)

X =

   16.0000   -6.8284         0   -1.1716         0   -1.1716         0   -6.8284

The result should not contain any imaginary components, based on DSP theory. However, the scipy result is as follows:
array([ 16.00000000 +0.00000000e+00j,  -6.82842712 -2.22044605e-16j,
         0.00000000 -0.00000000e+00j,  -1.17157288 -2.22044605e-16j,
         0.00000000 +0.00000000e+00j,  -1.17157288 +2.22044605e-16j,
         0.00000000 +0.00000000e+00j,  -6.82842712 +2.22044605e-16j])

Why does scipy.fftpack.fft introduce small imaginary components? I really want to avoid this issue. Could anyone give me a suggestion?

A: For one thing, scipy.fftpack.fft is guaranteed to always return a complex result, whereas the result of MATLAB's fft function is sometimes real and sometimes complex, depending on whether there is a non-zero imaginary component. However, that doesn't explain why the result of scipy.fftpack.fft actually contains non-zero imaginary components, whereas the result of MATLAB's fft function does not.
I suspect that the underlying reason for the difference has to do with the fact that MATLAB's fft function is apparently based on FFTW, whereas scipy and numpy use FFTPACK due to licensing restrictions.
pyfftw, however, does provide Python bindings to FFTW. If we compare the imaginary components of the results for FFTPACK and FFTW:
from pyfftw.interfaces import scipy_fftpack as fftw

Fx1 = fftpack.fft(x)
print(Fx1.imag)
# [  0.00000000e+00  -2.22044605e-16  -0.00000000e+00  -2.22044605e-16
#    0.00000000e+00   2.22044605e-16   0.00000000e+00   2.22044605e-16]
print(Fx1.imag == 0)
# [ True False  True False  True False  True False]

Fx2 = fftw.fft(x)
print(Fx2.imag)
# [ 0.  0.  0.  0.  0.  0.  0.  0.]
print(Fx2.imag == 0)
# [ True  True  True  True  True  True  True  True]

we see that the imaginary component of the FFTW result compares exactly equal to zero, whereas FFTPACK has a tiny amount of floating-point rounding error.
Beyond that, I have no idea why FFTW's implementation suffers less from rounding error than FFTPACK, but in any case it's important to note that these rounding errors are small enough that they normally don't cause problems (you know you shouldn't be testing for exact equality between float values, right?).
Usually you would simply take the real component of the result, e.g.:
scipy.fftpack.fft(x).real

If these errors are a problem then you could switch to using pyfftw instead of numpy/scipy, but if your code is that sensitive to rounding error then it probably means you're doing something wrong anyway.


text:
Q: python convention for functions that require different variables depending in which if-elif criteria they satisfy I have a function to calculate an engineering parameter via a few different methods.
Is there a better approach than any of the below?
Input variables:
User will have supplied either these 4 arguments:
option = 1
strength = 10
gradient = 2
depth = 5

Or these 3 arguments:
option = 2
factor = 9
alpha = 2.3

Approach 1
def func1(option, *args):
    if option==1:
        return args[0] + args[1] * args[2]
    elif option==2:
        return args[0] * args[1]

Called with either:
func1(option, strength, gradient, depth) # if option = 1
func1(option, factor, alpha) # if option = 2

*

*Pros: Function call does not require duplicating names

*Cons: What function is doing is unclear unless you match up with the function call

Approach 2
def func2(option, **kwargs):
    if option==1:
        return kwargs['strength'] + kwargs['gradient'] * kwargs['depth']
    elif option==2:
        return kwargs['factor'] * kwargs['alpha']

Called with either:
func2(option=option, strength=strength, gradient=gradient, depth=depth) # option=1
func2(option=option, factor=factor, alpha=alpha) # option=2

*

*Pros: What function is doing is clear from function alone, albeit a bit clunky

*Cons: Cumbersome function call as names are duplicated, especially for more complex functions

Approach 3
def func3(option, **kwargs):
    if option==1:
        return strength + gradient * depth
    elif option==2:
        return factor * alpha

Called with:
dict1 = {'option': 1, 'strength': 10, 'gradient': 2, 'depth': 5}
# alternatively the user may have supplied:
dict1 = {'option': 2, 'factor': 9, 'alpha': 2.3}

func3(**dict1)

*

*Pros: What function is doing is clear from function alone. Call is simple & flexible.

*Cons: Must view the dictionary to be sure what variables the function call is passing.

A: Ideally, you should try to make 2 distinct functions with self-descriptive names & call the function according to need. All your current iterations are opaque about how is first argument working and the next people reading this code will have to make logical connections themselves.
However, assuming that is not possible in your problem case, you should go with Approach 3 and use assert to make sure dictionaries passed consists of the keys it needs (with appropriate value constraints as per need).

A: I'd probably go with a variation on Approach 1.
The way I've done this type of thing in the past is making a function map, with the keys being your options:
def func1(strength, gradient, depth):
    return strength + gradient * depth

def func2(factor, alpha):
    return factor * alpha

func_map = {1: func1, 2: func2}

func_map[1](strength, gradient, depth)
func_map[2](factor, alpha)

It makes it explicit what the functions are doing, and makes unit testing easy. You could also throw in kwargs in there if you feel strongly about making it easy to call without knowing what arguments go into what function, although you lose some traceability in that approach:
def func1(strength, gradient, depth, **kwargs):
    return strength + gradient * depth

def func2(factor, alpha, **kwargs):
    return factor * alpha

func_map = {1: func1, 2: func2}

args = {strength: 1, gradient: 2, depth: 3, factor: 4, alpha: 5}
func_map[1](**args)
func_map[2](**args)


text:
Q: Using cookies from httpclient in webview In my app I'm sending a device ID to a server using http post and I'm getting a session ID back. Now I need to get the session cookie in my webviewclient. I did some research and found this:
Android WebView Cookie Problem
The problem is the solution doesn't work for me. I keep getting an error on this line:
List<Cookie> cookies = httpClient.getCookieStore().getCookies();

The method getCookieStore() is undefined for HttpClient type. I should have all the right libraries loaded, so I don't know why I keep getting an error.
Here is my code, maybe someone will be able help me implement a solution to get the session cookie into my webview.
Thanks in advance!
package mds.DragonLords;

import java.io.BufferedReader;
import java.io.IOException;
import java.io.InputStream;
import java.io.InputStreamReader;
import java.util.ArrayList;
import java.util.List;

import org.apache.http.HttpResponse;
import org.apache.http.NameValuePair;
import org.apache.http.client.ClientProtocolException;
import org.apache.http.client.HttpClient;
import org.apache.http.client.entity.UrlEncodedFormEntity;
import org.apache.http.client.methods.HttpPost;
import org.apache.http.impl.client.DefaultHttpClient;
import org.apache.http.message.BasicNameValuePair;

import android.app.Activity;
import android.content.Context;
import android.os.Bundle;
import android.telephony.TelephonyManager;
import android.webkit.WebView;
import android.webkit.WebViewClient;

public class Home extends Activity {

WebView mWebView;

    private class HelloWebViewClient extends WebViewClient {
        @Override
        public boolean shouldOverrideUrlLoading(WebView view, String url) {
            view.loadUrl(url);
            return true;
        }
    }

    private String tmDevice;
    private String sid;
    private String url;

    public void onCreate(Bundle savedInstanceState) {
        super.onCreate(savedInstanceState);

        final TelephonyManager tm = (TelephonyManager) getBaseContext().getSystemService(Context.TELEPHONY_SERVICE);

         tmDevice = "2" + tm.getDeviceId();

         postData();

        url = "myserver"+sid.substring(5);

        setContentView(R.layout.web);
        mWebView = (WebView) findViewById(R.id.webview);
        mWebView.getSettings().setJavaScriptEnabled(true);
        mWebView.setWebViewClient(new HelloWebViewClient());
        mWebView.loadUrl(url);
    }

    public void postData() {
        // Create a new HttpClient and Post Header
        HttpClient httpclient = new DefaultHttpClient();
        HttpPost httppost = new HttpPost("myserver");
        try {
            // Add your data
            List<NameValuePair> nameValuePairs = new ArrayList<NameValuePair>(1);
            nameValuePairs.add(new BasicNameValuePair("uid", tmDevice));
            httppost.setEntity(new UrlEncodedFormEntity(nameValuePairs));

            // Execute HTTP Post Request
            HttpResponse response = httpclient.execute(httppost);

            inputStreamToString(response.getEntity().getContent());

        } catch (ClientProtocolException e) {
            // TODO Auto-generated catch block
        } catch (IOException e) {
            // TODO Auto-generated catch block
        }

   }

    private void inputStreamToString(InputStream is) {
        String line = "";
        StringBuilder total = new StringBuilder();

        // Wrap a BufferedReader around the InputStream
        BufferedReader rd = new BufferedReader(new InputStreamReader(is));

        // Read response until the end
        try {
            while ((line = rd.readLine()) != null) {
                total.append(line);
            }
        } catch (IOException e) {
            // TODO Auto-generated catch block
            e.printStackTrace();
        }
        sid = total.toString();

    }

}

A: I've just ran into the same thing. I know it's an old post, but maybe it'll help somebody else.
The problem is in declaration of postData().
That line now is :

HttpClient httpclient = new DefaultHttpClient();
It should be:
DefaultHttpClient httpclient = new DefaultHttpClient();

see this: http://hc.apache.org/httpcomponents-client-ga/httpclient/apidocs/org/apache/http/impl/client/DefaultHttpClient.html