text:
Q: Extracting website data with Excel and VBA I want to extract data from a Website and store it in an Excel tablet.
It is a list of suppliers in a register from A to Z. This is the URL: http://www.euroshop.de/cgi-bin/md_euroshop/lib/pub/tt.cgi/Ausstellerverzeichnis_A-Z.html?oid=18864&lang=1&ticket=g_u_e_s_t
The steps I need to take are i.e.: Click B - > Click B2BTrip GmbH -> Extract "Allgemeine Dienstleistungen" and "Sonstiges" into a new row -> repeat with next supplier.
I have an Excel list with all the names of the suppliers and some additional information, where the gathered data should be saved in. here is a Picture of the list. Help would be much appreciated!


text:
Q: If an avatar goes into the avatar state while being poisoned, do they still die? I was wondering but how exactly is the avatar state very useful for example if an avatar like Korra gets poisoned by a metallic based venom?
The Avatar State, yes, is a defense mechanism designed to empower you with skills and knowledge from your pasts lives and stuff but if we think about it, it would only ever be good in attack or if you were nearly killed by some huge fire blast of some magnitude.
When I think of how the Avatar State was shown in both Avatar the Last Airbender and Legend of Korra, I think of the Avatar State as some type of safety shield. It gives you the wisdom and knowledge and power which practically make you invincible.
If you were poisoned however, the avatar state can't really do much. Suddenly becoming powerful at bending and being able to destroy a mountain out of lava really wouldn't save you from getting killed, would it?
So if Korra stayed poisoned while in the forced Avatar State, would that mean it would have somehow healed her or would she have died anyways and if she died, would the avatar cycle had ended?

A:
How exactly is the avatar state very useful for
  example if an avatar like Korra gets poisoned by a metallic based
  venom?

It isn't. That's the point of Zaheer's plan: since the Avatar State is automatically triggered when the Avatar is in absolute danger, he knows that the pain from the poison will force the state on Korra so that he'll be able to kill her and finish the cycle.
However, keep in mind that Zaheer's posion was flawed either way. Suyin Bei Fong was capable of extracting the poison by bending it - in the same manner, Korra may have done the same (but she was raging against Zaheer so she either didn't have the time or didn't even think about it).

If an avatar goes into the avatar state while being poisoned, do they
  still die?

Yes, this becomes specially clear from Zaheer's statement when he is finally caught:

You're too late. The poison has been in her system for too long. The
  Red Lotus, has won!

Zaheer can't kill Korra with his own hands since he's been finally defeated - but he knows that Korra will die either way thanks to the poison. Until Suyin comes to the rescue, of course.
So indeed, the poison would effectively kill Korra even with her Avatar State - given enough time.

Ultimately, the Avatar State doesn't provide any particular help against the poison. One could theorize that the "extra wisdom" could aid Korra into extracting the venom on her own, but technically speaking, there is no extra wisdom since she lost her connection with her past lives.

A: If the poison kills them, yes. The Avatar State is, among other things, a failsafe that protects the Avatar from harm. To do this, it triggers when the Avatar is in danger of dying. However, it cannot make the Avatar invincible, which is why it is also a vulnerability: the Avatar can die while in this state, and doing so would be Very Bad.
The problem with this trigger is that it is not very smart. In particular, the mechanism which triggers the Avatar State does not know whether or not it can be of any actual use against whatever danger the Avatar faces at the moment. It only knows that the Avatar is in mortal danger, and so it activates, because that is what it's for.
Zaheer's plan was to trick the Avatar State. He figured out a situation in which it would trigger, but not be able to get the Avatar out of her predicament, and also not pose any additional threat to him (he turned out to be wrong about the last part, but he got the rest of it right). If the plan had worked, then the Avatar State -normally one of Korra's greatest strengths- would have been nothing but a weakness, even though it was working properly.

A: Yes, they would still die. I got amout that Zaheer's plan was a genius one Korra would've die from Zaheer's minion or the poison ultimately ending the avatar cycle. I think the reason Korra didn't bend poison out was because, if you remember zaher it platinum and even toph can't bend solid platinum so think really hard to bend liquid platinum which is less pure them solid. Platinum and you got you to remember that Korra only learned metal bending a couple episode ago is a while to from being a master but suy who has been metal bending for year could

redpajama_set_name: RedPajamaStackExchange


text:
Q: UIActionSheet is taking longer to load are their any reasons why my UIActionSheet would be taking a while to load. It works fine just after lauch, but as soon as I loop through some actions once or twice, is loads very slow, and you can see the grey backdrop crawl down to finish drawing the sheet.
help?
Sam

A: Ok, so I found the solution moments later.
I assume this is how it works, feel free to correct me.
U used the cheats animation way of [ UIView ]
and i guess this changed the way for the UIActionSheet to pop up, so I wrote in these two lines before i asked it to show.in.view
 - (IBAction)goToBlog{

contactUs.actionSheetStyle = UIActionSheetStyleDefault;
[UIActionSheet setAnimationDelay:0];
[UIActionSheet setAnimationDuration:0.1];
[contactUs showInView:self.view];

}

and that seemed to work. so im happy.


text:
Q: Crop image to specified size and picture location I have an image that is being taken using AVCaptureSession and being returned to my view controller.
Here is a screen shot of the camera interface:

The AVCaptureSession takes the FULL SCREEN photo, and now I want to crop it down to the size of the visible window above.
The window will always be at the same location and the same size.
Height = 360 (180 non retina)px, Width = 640 (320 non retina)px, x = 0, y = 160.
How can I crop the image down to these coordinates so that the image itself is now 360 x 640?
Any help would be great, thanks!

A: You would need to do something like this.  I am typing this off the top of my head, so this may not be 100% correct.
CGColorSpaceRef colorSpace = CGColorSpaceCreateDeviceRGB();
CGContextRef context = CGBitmapContextCreate(NULL, 640, 360, 8, 4 * width, colorSpace, kCGImageAlphaPremultipliedFirst);
CGColorSpaceRelease(colorSpace);

CGContextDrawImage(context, CGRectMake(0,-160,640,360), cgImgFromAVCaptureSession);

CGImageRef image = CGBitmapContextCreateImage(context);
UIImage* myCroppedImg = [UIImage imageWithCGImage:image];
CGContextRelease(context);


text:
Q: Ensuring only factory can create instance class XFactory {

  private XFactory() {}

  static void getX() {
    if(...)
      return new A(new XFactory());
    else
      return new B(new XFactory());
  }

}

class A {
   private A() {}
   public A(XFactory xf) {}
}

class B {
   private B() {}
   public A(XFactory xf) {}
}

By this way I can ensure only Factory can create instances of it's belonging Classes.
Is this right approach or there is any other alternative/good approach?

A: The common approach (in C++) is to make the "belonging classes" constructors private, and have them declare the factory class as friend.

A: I would make classes A and B friends of XFactory, and keep all their constructors private. Therefore, only XFactory has access to their constructors.
That is, in C++. In Java or C#, I don't see any clean way of enforcing that at compile-time. Your example is far from fool-proof and even a bit confusing, since as long as one has an instance of XFactory, he can pass it to the constructor of A or B and instantiate them directly like that.

A: If you were up for hacks and could not make your constructors private, you could:
Make your factory a global singleton and to create an object:

*

*Create a random key

*Add that key to a private list in the factory object of keys in use

*Pass the key to the constructor

*Have the constructor retrieve the global factory object and call it to validate the key.

*If they key validation fails, scuttle your program (call exit, die, ... whatever is appropriate). Or possibly email a stack tract to an admin. This is the kind of thing that should be caught quickly.

(Do I get hack points?)
Jacob

A: In Java you can make the constructors private and provide the factory in the form of a public nested class, since nested classes have access to the private members of the class in which they are declared.
public class ExampleClass {

    private ExampleClass() {

    }

    public class NestedFactory {
        public ExampleClass createExample() {
            return new ExampleClass();
    }
}

Anyone who wanted to could create an instance of ExampleClass.NestedFactory and through it instantiate ExampleClasses.
I haven't been able to figure out a way to do this that lets you then inherit from ExampleClass since the Java compiler demands that you specify a constructor for the superclass... so that's a disadvantage.


text:
Q: iOS Universal Links redirect to AppStore to Update Application I am working on a feature that implementing of 3rd party sdk (Firebase etc) to handle Universal Links in iOS and my apple-app-site-association file is like below.
{
  "applinks": {
     "apps": [],
     "details": [
        {
          "appID": "teamid.bundleid",
          "paths": [
              "NOT /auth",
              "/*"
           ]
       },
     ]
   }
}

Everything is working fine but in a domain like myappsite.com/deeplink/live-chat it goes directly to the AppStore but the problem here is my application is already installed on the phone, when I go to AppStore, there is a button named Update for updating application then nothing changed, do you have any idea of this problem?


text:
Q: React- Filter array based on search and dropdown values I have a page that is displaying a list of article titles. On this page, I've added a search bar and a drop-down menu to be able to filter through this array. onChange of the input field for the search I am calling setSearchTerm. I also have a drop-down filter menu for All, True and False there is an object completed in this array. Upon clicking true/or false it filters and returns based on if the article is completed or not.
Individually they are both functioning as expected, but I am having issues coming up when I am getting them both to work together. I would like to be able to search within the filtered article titles. For example. If I select "True" I would like to be able to search through all "True" articles. So the array would be filtered by both the drop-down value "True" and the words typed into the search bar.
This is where I am struggling with:
  } else if (searchTerm != "" && filter != "") {
            console.log('here')

           // return what includes the search term
            val.title.toLowerCase().includes(searchTerm.toLowerCase())
            return val
          }

With the logic, I am expecting when searching and filter are both not empty, to return what matches with the search term. At the moment, there is nothing being returned when both the drop-down and search is used.
Here is the entire logic set up:
 let posts =  articles.filter((val) => {
  // if search is empty and if "all" or nothing is selected return the entire array
  if (searchTerm == "" && filter == "" || filter == "all") {
    return val

 // if the filter is not selected, return whats included with the search term
  } else if (filter == "" && val.title.toLowerCase().includes(searchTerm.toLowerCase())) {
      return val

 // if search is empty and filter drop down value exists return what matches with the filter
  } else if (searchTerm == "" && val.completed.toString().includes(filter)) {
    return val

 // if there neither are empty do logic here
  } else if (searchTerm != "" && filter != "") {
    console.log('here')

   // return what includes the search term
    val.title.toLowerCase().includes(searchTerm.toLowerCase())
    return val
  }
})

Here is my full code snippet:
 import { useState, useEffect } from 'react';

const Posts = ({ articles }) => {

  const [searchTerm, setSearchTerm] = useState("");
  const [filter, setFilter] = useState("")

      let posts =  articles.filter((val) => {
  // if search is empty and if "all" or nothing is selected return the entire array
  if (searchTerm == "" && filter == "" || filter == "all") {
    return val

 // if the filter is not selected, return whats included with the search term
  } else if (filter == "" && val.title.toLowerCase().includes(searchTerm.toLowerCase())) {
      return val

 // if search is empty and filter drop down value exists return what matches with the filter
  } else if (searchTerm == "" && val.completed.toString().includes(filter)) {
    return val

 // if there neither are empty do logic here
  } else if (searchTerm != "" && filter != "") {
    console.log('here')

   // return what includes the search term
    val.title.toLowerCase().includes(searchTerm.toLowerCase())
    return val
  }
})

 return (
      <>
<select value={filter} onChange={(event) => {setFilter(event.target.value)}} className="dropmenu dropdown-menu">
    <option value="">All</option>
                <option value="true">True</option>
                <option value="false">False</option>

    </select>
       <input
        type="text"
        placeholder="Search..."
        onChange={(event) => {
          setSearchTerm(event.target.value);
        }}
      />

h1

      {posts && posts.map(post => (

          {post.title}

      ))}

    </>

  );
};

export default Posts;

How can I set up this condition to where the user can search when the articles are filtered by True or False?
Articles array:
const articles = [{"title": "title one", completed: false},
{"title": "article two", completed: true},
{"title": "testing three", completed: false},
{"title": "title four", completed: false},
{"title": "title five", completed: true}]

A: Following your original format, just move the conditional into the if statement
} else if (searchTerm != "" && filter != "" &&
              val.title.toLowerCase().includes(searchTerm.toLowerCase())) {
            console.log('here')

           // return what includes the search term

            return val
          }

A: All you need to do is add this line in the last case like this
else if (searchTerm !== "" && filter !== "") {
    console.log('here')
   // return what includes the search term
    if(val.title.toLowerCase().includes(searchTerm.toLowerCase()) && val.completed.toString().toLowerCase().includes(filter.toLowerCase()))
      return val
  }

what it basically does is check if completed property in val is equal to filter and searchTerm is equal to title I just combined your logic but it code be a little neater by doing this
else if (val.title.toLowerCase().includes(searchTerm.toLowerCase()) && val.completed.toString().toLowerCase().includes(filter.toLowerCase())) {
   // return what includes the search term
      return val
  }

since it won't reach this else if and only if searchTerm and filter are both != "" so I just moved the inside condition to the else if


text:
Q: .NET ORM solution with class auto-generation: Subsonic, Castle AR, ...? I used to work with a custom data mapping library, and curently I'm trying to switch to a more widespread ORM solution.
After some experimentation, I refined my requirements to the following:

*

*able to generate usable classes from database schema (SQL Server support is enough),

*support for ActiveRecord pattern,

*programmaticaly configurable (via code or attributes, no HBM files),

*free.

Could you please recommend one?

So far I have tried:
Subsonic 3.0
The one I currently like most, as it feels like a good balance between functionality and simplicity.
What I don't like:

*

*uses IQueryable<> and plural names for both ends of one-to-many relationship - that seems rather counter-intuitive to me;

*generates one file for all classes - like a thousand lines per class, I have a bad feeling about code files being that large;

*T4 processing is invoked automatically, so a database with up-to-date schema must be available all the time.

Castle ActiveRecord
CastleAR with ActiveWriter add-in is almost what I need, but ActiveWriter's code isn't perfect (it seems, Nullable<> properties are not supported, and default one-to-many implementation doesn't work) and I couldn't find how to fix this code manually.
Darkside GeneratorStudio produces better code - correct definitions, one file per entity - though it uses cryptic names like RefclassIdRefclass. Personally I like Studio addin more than standalone app, but this certainly is a minor issue.
There're about twenty files bundled in the CastleAR distribution; though not a problem by itself, it feels like overweight. Won't I need too much esoteric knowledge about NHibernate and other stuff?
Fluent NHibernate
Widely recommended, but I wasn't able to find a code generator for it.
Have I missed something important?

A: NHibernate does not follow the active record pattern, it follows the repository pattern.
FluentNHibernate's goal is the end of needing to maintain mapping files, code generation etc. It supports Fluently defined C# equivalents of NHibernate HBM files which is very nice and alot more maintainable than XML however it's much stronger aspect is its auto mapping capabilities. If your database is designed with strongly defined conventions FNH can be configured that it will generate the correct mapping of all of your domain objects correctly to your database structure.
If you're more interested in designing the database and having that dictate your domain model (this would make me feel very dirty) there is a question here devoted to NHibernate Generators
Answer to your comment: NHibernate itself does not alter the database itself however there is a utility class included called SchemaExport that provides a factory method called Create. You can use this to generate the SQL statements that it would take to create your database the way NHibernate sees your relationship structure. And can be optionally either directly run against the database or write to the console.
This utility is very useful for forward generation of your domain to your database, it's currently how I am writing my database for all my new application development. I am still working on figuring out the best way to maintain versions of the database. Worst case scenario would to be just SC the sql output and require comments for each line that changes the schema to have it's specific update/delete statements to achieve the result. This would make it easy to roll forward/backwards by version or just execute the entire script to make the db from scratch.
If you go purely for reverse mapping, there should be tools available to generate the corresponding HBM your database needs to map to the equivalent classes (ie if you would have written those classes originally in your domain model it would export a matching schema of your current database)

A:

*

*able to generate usable classes from database schema (SQL Server support is
  enough),

*support for ActiveRecord pattern,

*programmaticaly configurable (via code or attributes, no HBM files),
  free.

*

*Linq-to-SQL autogenerates from the database schema. One big problem is the property names are lowercase so you need a tool like this one to rename them. It isn't restricted to SQL Server.

*It sort of supports the ActiveRecord pattern - it's very close.

*The classes are configurable via the dbml file which is simply an XML file. Visual Studio generates a designer.cs file that allows you to add to the entities it produces as they're produced as partial classes.
A few others to have a look at besides NH and Subsonic:

*

*Lightspeed - free for under 8 entities, the link shows some example code. You have to define the mappings from tables to classes via an interface though so it doesn't meet 1)

*LLBlgen - it's not free

A: A few thoughts on the things you don't like about SubSonic:

*

*uses IQueryable<> and plural names for both ends of one-to-many relationship - that seems
rather counter-intuitive to me;

True, I agree this is very counter intuitive and I've never got to the bottom of why it is that way, but you can pretty easily modify the templates to fix this.

*

*generates one file for all classes - like a thousand lines per class, I have a bad feeling about code files being that large;

You'd think this might cause problems but I've yet to come across any and I've yet to see one reported on stackoverflow.

*

*T4 processing is invoked automatically, so a database with up-to-date schema must be available all the time.

It's only invoked automatically if you edit the t4 files so really you only need an up-to-date schema available when you're making changes to the templates.

A: We use CodeSmith for Code Generation and can highly recommend it as a generation tool.
If you look at CodeSmith it supports various ORM / Business Object Templates.
We implemented our own CSLA (see http://www.lhotka.net/) templates a few years ago to get to grips with CSLA which is more than just ORM. CSLA is great and works very well and its highly scalable. We have now created our own framework and dropped the core CSLA framework as we didnt need all the features and made things a bit more lightweight.

A: I wonder whether the older SubSonic 2.2 may be a better fit for your requirements?  It does generate individual classes per table, only regenerates when you tell it to, and supports the ActiveRecord pattern.  See more details in the docs at http://subsonicproject.com/docs/Main_Page

A: Regarding previous Posts CSLA is not an ORM (You do the mapping from the DB to your Business Objects manually). CSLA, NHibernate, subsonic etc do not support the active records pattern.
If you are considering Frameworks that do not support the Active Records pattern then I would consider Habanero (http://www.habanerolabs.com/) this is open source and allows you to build your Business Objects either via an XML configuration or via code.
Habanero is far more than an ORM and has a rich domain (Business Object) support with a powerfull object model for representing your Domain objects (Business Objects).


text:
Q: HP 110-023wp desktop computer The specification states that it has 1 PCIe half-length slot that can be used on this computer.  I am wanting to put a graphics card in the case, as I don't like the Intel onboard HD2500 graphics chip.  Can the mini slot be used for a graphics card if get an adapter to make slot a pci-ex1 slot?  Can this even be done?

A: According to other sites, the easy answer is no.
The main concern is fitting it in physically. Yes, there are adapters to make it fit, if it's a small video card; however, power can become an issue. Because of that, I'd say no, it's not recommended, but try at your own risk (and likely void any warranty).
Having said that, and looking at the specs/reviews, I'd be wary of this PC doing any sort of decent graphics at an acceptable speed.

A: There are plenty of PCI-E 1x graphics cards if you look for them.
One of these for example.
Alternatively you can still purchase (for a premium) PCI video cards.


text:
Q: How to connect from Web App to SQL Database in another region "privately"? Is there a way to establish a connection from Azure Web App to Azure SQL Database in another region "privately", that is without having to leave database open to the public.
Specifically, I would like my database to have the following firewall options set on the database:

*

*"Deny public network access" - YES

*"Allow Azure services and resources to access this server" - NO

What I have tried unsuccessfully (it is possible that I got something wrong in my setup):

*

*VNET-VNET peering - allows cross region VNET connection but does not seem to work for Web App

*SQL Database Private Endpoint - Endpoint was created in VNET hosted in the same region as Web App.

Update:
Tried to follow instructions in Azure Global VNet peering and WebApps but I am not sure what VNET should gateways be created in? Create a gateway first in the remote network then checked "App Service Plan" blade, then created Gateway in the Web App VNET, still no luck.
In the "App Service Plan" blade, all of the gateway related settings are greyed out and gateway status is "N/A". "Sync Network" button is greyed out.

A: You should be able to do this using a Private Link, there are instructions on the following Microsoft documentation: Multi-region web app with private connectivity to database
However, the part about adding the private link (i.e. part 3a of the "Deploy this scenario" section) isn't very clear as to what settings you need to select when actually creating the Private Link so I have created a blog post which helps to explain this part a bit better with screenshots: Connect from Azure Web App to Azure SQL Database in another region using Private Link

A: Firstly, your linked SO answer is used to access Azure VMs from Azure web app. The Azure VMs are Azure IaaS. However, the Azure SQL database is Azure PaaS. You don't need to follow it in this scenario.
If you want to connect from Web App to Azure SQL Database in another region in a security way, you could do the these two steps:

*

*Enable regional VNet Integration with app service in the same region.

*Add the integrated subnet in the firewall and virtual networks in the Azure SQL database server. If selected subnet does not have service endpoint enabled for Microsoft.Sql. Enabling access may take up to 15 minutes to complete.

For more information, you could refer to this blog.
The above method will add the integrated subnet in the SQL server firewall. If you don't like to add it, you may consider to use Azure Private Link and with gateway required VNet integration. See this blog for more information. You could make sure you have set up the gateway in your virtual network (it will have private endpoint for SQL database and in the same region as the SQL database) well. see Use cases of Private Link for Azure SQL Database for more details.


text:
Q: Is there a way to pass the correct remote address to Nginx in a Docker container I have a Nginx webserver that I'm running from inside a docker container. The problem I am having is that all client IP addresses in the nginx access.log are 172.19.0.1, the container's gateway. I would like the IP addresses shown to nginx to be the real IP addresses of the clients.
I've tried a few solutions that I found, including

*

*Using Nginx's realip module

    set_real_ip_from 172.19.0.1;
    real_ip_header X-Real-IP;
    real_ip_recursive on;

which still logged the gateway ip

*Setting the ports to host networking mode, which was ineffectual because I'm on macOS, and it is only supported on Linux.

The dockerfile I'm using looks like this
version: "3"
services:
    nginx:
        container_name: nginx
        ports:
            - target: 80
              published: 80
            - target: 443
              published: 443
        volumes:
            # [my volumes]
        restart: unless-stopped
        image: nginx


text:
Q: Integrating Spring with Serenity/JBehave test I am trying to get Spring dependency injection to work inside a Serenity/JBehave test, but neither SpringClassRule nor SpringMethodRule gets applied (which, I suspect, is why both @ContextConfiguration and @Autowired are ignored, and I get a NullPointerException when tyring to call the service).
I've also tried SpringIntegrationClassRule and SpringIntegrationMethodRule from the serenity-spring library, but to no avail.
Does anyone have any idea how to get it working?
My test class:
@ContextConfiguration(locations = "test-beans.xml",
                      loader = TestContextLoader.class)
public class GreetingServiceTest extends SerenityStories {

    @ClassRule
    public static final SpringClassRule SPRING_CLASS_RULE = new SpringClassRule();
    @Rule
    public final SpringMethodRule springMethodRule = new SpringMethodRule();

    @Autowired
    private GreetingService greetingService;

    private String greeting;

    @When("I want a greeting")
    public void whenIWantAGreeting() {
        greeting = greetingService.getGreeting();
    }

    @Then("I shall be greeted with \"$greeting\"")
    public void thenIShallBeGreetedWith(String greeting) {
        assertEquals(greeting, this.greeting);
    }

    @Override
    public InjectableStepsFactory stepsFactory() {
        return new InstanceStepsFactory(configuration(), this);
    }
}

My story:
Scenario: Hello world
When I want a greeting
Then I shall be greeted with "Hello world"

TestContextLoader.java:
public class TestContextLoader implements ContextLoader {

    @Override
    public String[] processLocations(Class<?> clazz, String... locations) {
        return locations;
    }

    @Override
    public ApplicationContext loadContext(String... locations) throws Exception {
        System.err.println("This is never printed.");
        return new ClassPathXmlApplicationContext(locations);
    }

}

test-beans.xml:
<?xml version="1.0" encoding="UTF-8"?>
<beans xmlns="http://www.springframework.org/schema/beans"
    xmlns:xsi="http://www.w3.org/2001/XMLSchema-instance"
    xmlns:context="http://www.springframework.org/schema/context"
    xsi:schemaLocation="
       http://www.springframework.org/schema/context http://www.springframework.org/schema/context/spring-context-4.3.xsd
       http://www.springframework.org/schema/beans http://www.springframework.org/schema/beans/spring-beans-4.3.xsd">

    <context:component-scan base-package="com.example"/>

</beans>

GreetingService.java:
@Service
public class GreetingService {

    public String getGreeting() {
        return "Hello world";
    }
}

I use the following libraries:
org.springframework:spring-core:5.1.4.RELEASE
org.springframework:spring-context:5.1.4.RELEASE
org.springframework:spring-test:5.1.4.RELEASE
net.serenity-bdd:serenity-core:2.0.40
net.serenity-bdd:serenity-jbehave:1.44.0
junit:junit:4.12

Note: This is a very simplified version of my real-life case, and I need both the Spring XML config and the custom context loader.

A: I solved this using the following hack (basically injecting the service(s) myself):
@ContextConfiguration(locations = "test-beans.xml",
                      loader = TestContextLoader.class)
public class GreetingServiceTest extends SerenityStories {

    @Autowired
    private GreetingService greetingService;

    private String greeting;

    @When("I want a greeting")
    public void whenIWantAGreeting() {
        greeting = greetingService.getGreeting();
    }

    @Then("I shall be greeted with \"$greeting\"")
    public void thenIShallBeGreetedWith(String greeting) {
        assertEquals(greeting, this.greeting);
    }

    @Override
    public InjectableStepsFactory stepsFactory() {
        return new InstanceStepsFactory(configuration(), this);
    }

    @BeforeStories
    public final void beforeStories() {
        AutowireCapableBeanFactory beanFactory = getContext().getAutowireCapableBeanFactory();
        beanFactory.autowireBeanProperties(this, AutowireCapableBeanFactory.AUTOWIRE_NO, false);
        beanFactory.initializeBean(this, getClass().getName());
    }

    private ApplicationContext getContext() {
        return SpringClassRuleHack.getTestContextManager(getClass())
            .getTestContext()
            .getApplicationContext();
    }
}

SpringClassRuleHack (must be the same package as SpringClassRule to get access to the getTestContextManager method):
package org.springframework.test.context.junit4.rules;

import org.springframework.test.context.TestContextManager;

public final class SpringClassRuleHack {

   private SpringClassRuleHack() {}

   public static TestContextManager getTestContextManager(Class<?> testClass) {
      return SpringClassRule.getTestContextManager(testClass);
   }

}

I'm getting the Spring context through SpringClassRule so that it gets cached by Spring, letting Spring control when the context needs reloading (if I have understood correctly).
I'm not entirely satisfied with this solution and I suspect it's not equivalent to enabling SpringClassRule/SpringMethodRule in the standard way, but it works in my case.


text:
Q: Mysql : foreign key relative to multiple tables I'm trying to improve the database integrity adding some foreign key (it's the first time i use them).
I have some tables relative to different type of devices (different tables because the "devices" are completely different from each other), a table groups and a relation-table group_device (the same device can be in more groups).

devices_typeA
id is primary key
id | column1 | column2 |
------------------------
1  | aaa     | bbbb    |
2  | aaa     | bbbb    |

devices_typeB
id is primary key
id | column1 | column2 | column2 | columnN |
--------------------------------------------
1  | aaa     | bbbb    | cccc    | dddd    |
2  | aaa     | bbbb    | cccc    | dddd    |

devices_typeC
id is primary key
id | column1 |
--------------
1  | aaa     |
2  | aaa     |

groups
id is primary key
id | name    |
--------------
1  | group 1 |
2  | group 2 |
3  | group n |

group_device
id | type_device | id_device | id_group |
-----------------------------------------
1  | typeA       | 1         | 1        |
2  | typeA       | 1         | 2        |
3  | typeB       | 1         | 1        |
4  | typeC       | 2         | 3        |

Now i would like to add some foreign key to the tables group_device (in such a way that when a device is deleted, is deleted also in the table group_device [with the ON DELETE CASCADE action]). My problem is the id_device column, that is relative to multiple tables (devices_typeA.id, devices_typeB.id , devices_typeC.id).

A: FOREIGN KEYs have severe limitations.  I think you have exceeded them.
Complex data structures cannot depend on FKs for integrity, your code is required.
Suggest that you build Stored Routines and/or subroutines in your application language, and encapsulate the integrity constraints there.  And build a clean API into the routines to make it easy for the clients to achieve their goals while the routine achieves the integrity goals.

A: A declared foreign key (i.e., one enforced by the database engine) cannot tie to multiple other tables. So id_device in group_device cannot be a foreign key to all three device tables.
You have a few options:
Multiple group_device tables
Have a unique table linking each type of device to the appropriate group (group_device_typeA, group_device_typeB, group_device_typeC, etc.).
You can create a group_device view that's basically the same as the current group_device table. You wouldn't have a true group_device.id column (the other three columns should uniquely identify a row). You could find a way to create a unique ID across the actual group_device_* tables if absolutely required, but that's a bit more work.
This does involve a certain amount of maintenance pain - when a new device is added, you have to create two tables (device_typeN and group_device_typeN), plus you have to modify the group_device view.
Multiple columns in group_device (don't use)
You could create the group_device table with a unique column for each possible device type (device_typeA_id, device_typeB_id, device_typeC_id, etc.). Then, add a trigger (as shown in this answer) to ensure that all but one of these values is NULL.
Maintenance requirements are similar to the first suggestion: when a new type is added, you have to create the device_typeN table; add the device_typeN_id column to the group_device table, and modify your trigger.
However, this approach is generally frowned upon. You're trying to use the built-in foreign key mechanism - but you're also trying to work around it. The trigger's code will be repetitive enough that it should be easy to maintain - but it's also easy to screw it up and not notice. And then, you could wind up with rows with multiple ID columns filled in, which is likely to cause some confusion in joins and such (if not outright bad data). It's also easy to have a typo that results in assigning a single id value to the wrong column, with similar confusing results.
I mention it more for the sake of completeness than for any other reason.
Use a "virtual" foreign key
(This is the option that Rick James' answer covers - refer to that for more detail).
Use group_device as you have it defined now, where the foreign key is one column that identifies a table (type_device) and one that identifies a row in that table (device_id). Create code to confirm that the device_id is a valid ID from the table in question, and to delete the appropriate group_device row if the underlying device is deleted. It's possible this can be done in triggers (insert/update trigger on group_device to validate new/changed data; delete trigger on each device table, to check for and remove any group_device rows when a device is deleted).
Maintenance should simply be creating the delete trigger when you create the device table, and updating the insert/update trigger on group_device to work with the new table.
If using this solution, I recommend that you either use the full table name for type_device; have a type_device table listing the device_type* tables with an ID, and use that ID in group_device; or (at a minimum) establish a strict naming convention for device_typeN tables, so you know that CONCAT('device_' + type_device) will always yield the correct table name.

A: Here's one sketch. Introduce a generic DEVICES table.
CREATE TABLE devices
( device_id ... NOT NULL
, device_type ... NOT NULL
, ... -- generice attributes
, PRIMARY KEY (device_id)
, UNIQUE (device_type, device_id)
, CHECK (device_type IN ('A','B','C'))
);

CREATE TABLE devices_typeA
( device_id ... NOT NULL
, device_type ... NOT NULL
, ... -- type_A specific attributes
, PRIMARY KEY (device_id)
, CHECK (device_type = 'A') -- introduced in 8.0.16
, FOREIGN KEY (device_id, device_type)
      REFERENCES devices (device_id, device_type)
          ON DELETE CASCADE -- I assume

Some notes, a FOREIGN KEY can reference a UNIQUE constraint, not only the PRIMARY KEY. That together with CHECK constraint can guarantee that the correct device_type is used in devices.
For MySQL < 8.0.16 CHECK CONSTRAINTS did not exist (introduced SQL92, 199x). Mimic them with ENUM may seem like a good idea at first, DONT!!!, see for example: how-does-mariadb-handle-enum-types-used-in-foreign-key-constraints
Now GROUP_DEVISES can reference GROUPS as well as DEVICES
CREATE TABLE group_devices
( group_id ...
, device_id ...
, PRIMARY KEY (group_id, device_id)
, FOREIGN KEY (group_id)
      REFERENCES groups (group_id)
          ON DELETE CASCADE
          ...
, FOREIGN KEY (device_id) REFERENCES devices (device_id)
      REFERENCES devices (device_id)
          ON DELETE CASCADE
          ...

If a device is deleted, the delete is cascaded to both device_type... as well as to group_devices.


text:
Q: Open node debugging url in google-chrome automatically I would like to open the URL from running the node --inspect app.js in the browser automatically. I am on Ubuntu Linux and the osascript solution does not work well for me.
I have tried:
$(grep 'chrome-devtools://' <(node --inspect bin/www.js $@ 2>&1)) | xargs google-chrome

( export DEBUG_URL = $(grep 'chrome-devtools://' <(node --inspect bin/www.js $@ 2>&1)); google-chrome DEBUG_URL )

google-chrome $(grep 'chrome-devtools://' <(node --inspect bin/www.js $@ 2>&1))

xdg-open $(grep 'chrome-devtools://' <(node --inspect bin/www.js $@ 2>&1))


text:
Q: Actions - perform() method not working in iOS ionic app on textfields I'm trying to enter data in text fields(username and password). I tried 2 approaches,
1. sendkeys(),

Issue: it didn't entered any data but test continued.
2. Actions actions = new Actions(driver);
   actions.moveToElement(element);
   actions.click();
   actions.sendKeys(str);
   actions.build().perform();

Issue: perform() threw exception:
Method has not yet been implemented
    org.openqa.selenium.WebDriverException: Method has not yet been implemented   (WARNING: The server did not provide any stacktrace information)
    Command duration or timeout: 14 milliseconds

OS: iOS 10.3.3
App: cordova app
Java-client: 4.1.2
Appium version: 1.6.5

A: Try this:

*

*xpath selector for email be:
login.input.email=id:Email

*tree.setPage("login);
driver.input("input","email",str); //your input string


text:
Q: warning adding methods into app delegate for core-data I have created a new project using core data then copied all of the app delegate code for core-data that I need over into my current projects app delegate..
my appdelegate.m looks like this now.
//
//  AppDelegate.m
//  testingcoredata
//
//  Created by iMac on 18/11/11.
//  Copyright (c) 2011 __MyCompanyName__. All rights reserved.
//

#import "AppDelegate.h"

#import "MasterViewController.h"

@implementation AppDelegate

@synthesize window = _window;
@synthesize managedObjectContext = __managedObjectContext;
@synthesize managedObjectModel = __managedObjectModel;
@synthesize persistentStoreCoordinator = __persistentStoreCoordinator;
@synthesize navigationController = _navigationController;

- (BOOL)application:(UIApplication *)application didFinishLaunchingWithOptions:(NSDictionary *)launchOptions
{
    self.window = [[UIWindow alloc] initWithFrame:[[UIScreen mainScreen] bounds]];
    // Override point for customization after application launch.

    MasterViewController *masterViewController = [[MasterViewController alloc] initWithNibName:@"MasterViewController" bundle:nil];
    self.navigationController = [[UINavigationController alloc] initWithRootViewController:masterViewController];
    masterViewController.managedObjectContext = self.managedObjectContext;
    self.window.rootViewController = self.navigationController;
    [self.window makeKeyAndVisible];
    return YES;
}

- (void)applicationWillTerminate:(UIApplication *)application
{
    // Saves changes in the application's managed object context before the application terminates.
    [self saveContext];
}

- (void)saveContext
{
    NSError *error = nil;
    NSManagedObjectContext *managedObjectContext = self.managedObjectContext;
    if (managedObjectContext != nil)
    {
        if ([managedObjectContext hasChanges] && ![managedObjectContext save:&error])
        {
            /*
             Replace this implementation with code to handle the error appropriately.

             abort() causes the application to generate a crash log and terminate. You should not use this function in a shipping application, although it may be useful during development.
             */
            NSLog(@"Unresolved error %@, %@", error, [error userInfo]);
            abort();
        }
    }
}

#pragma mark - Core Data stack

/**
 Returns the managed object context for the application.
 If the context doesn't already exist, it is created and bound to the persistent store coordinator for the application.
 */
- (NSManagedObjectContext *)managedObjectContext
{
    if (__managedObjectContext != nil)
    {
        return __managedObjectContext;
    }

    NSPersistentStoreCoordinator *coordinator = [self persistentStoreCoordinator];
    if (coordinator != nil)
    {
        __managedObjectContext = [[NSManagedObjectContext alloc] init];
        [__managedObjectContext setPersistentStoreCoordinator:coordinator];
    }
    return __managedObjectContext;
}

/**
 Returns the managed object model for the application.
 If the model doesn't already exist, it is created from the application's model.
 */
- (NSManagedObjectModel *)managedObjectModel
{
    if (__managedObjectModel != nil)
    {
        return __managedObjectModel;
    }
    NSURL *modelURL = [[NSBundle mainBundle] URLForResource:@"testingcoredata" withExtension:@"momd"];
    __managedObjectModel = [[NSManagedObjectModel alloc] initWithContentsOfURL:modelURL];
    return __managedObjectModel;
}

/**
 Returns the persistent store coordinator for the application.
 If the coordinator doesn't already exist, it is created and the application's store added to it.
 */
- (NSPersistentStoreCoordinator *)persistentStoreCoordinator
{
    if (__persistentStoreCoordinator != nil)
    {
        return __persistentStoreCoordinator;
    }

    NSURL *storeURL = [[self applicationDocumentsDirectory] URLByAppendingPathComponent:@"testingcoredata.sqlite"];

    NSError *error = nil;
    __persistentStoreCoordinator = [[NSPersistentStoreCoordinator alloc] initWithManagedObjectModel:[self managedObjectModel]];
    if (![__persistentStoreCoordinator addPersistentStoreWithType:NSSQLiteStoreType configuration:nil URL:storeURL options:nil error:&error])
    {
        /*
         Replace this implementation with code to handle the error appropriately.

         abort() causes the application to generate a crash log and terminate. You should not use this function in a shipping application, although it may be useful during development.

         Typical reasons for an error here include:
         * The persistent store is not accessible;
         * The schema for the persistent store is incompatible with current managed object model.
         Check the error message to determine what the actual problem was.

         If the persistent store is not accessible, there is typically something wrong with the file path. Often, a file URL is pointing into the application's resources directory instead of a writeable directory.

         If you encounter schema incompatibility errors during development, you can reduce their frequency by:
         * Simply deleting the existing store:
         [[NSFileManager defaultManager] removeItemAtURL:storeURL error:nil]

         * Performing automatic lightweight migration by passing the following dictionary as the options parameter:
         [NSDictionary dictionaryWithObjectsAndKeys:[NSNumber numberWithBool:YES], NSMigratePersistentStoresAutomaticallyOption, [NSNumber numberWithBool:YES], NSInferMappingModelAutomaticallyOption, nil];

         Lightweight migration will only work for a limited set of schema changes; consult "Core Data Model Versioning and Data Migration Programming Guide" for details.

         */
        NSLog(@"Unresolved error %@, %@", error, [error userInfo]);
        abort();
    }

    return __persistentStoreCoordinator;
}

#pragma mark - Application's Documents directory

/**
 Returns the URL to the application's Documents directory.
 */
- (NSURL *)applicationDocumentsDirectory
{
    return [[[NSFileManager defaultManager] URLsForDirectory:NSDocumentDirectory inDomains:NSUserDomainMask] lastObject];
}

@end

My questions are as follows
Is the URLForResource in this part of the code ment to reflect the name of my xcdatamodeld that I have created?
NSURL *modelURL = [[NSBundle mainBundle] URLForResource:@"testingcoredata" withExtension:@"momd"];

With the URLByAppendingPathComponent: do I have to create a sqlite database called Code.sqlite or is this made automatically for me by the core-data code?
NSURL *storeURL = [[self applicationDocumentsDirectory] URLByAppendingPathComponent:@"Code.sqlite"];

what is the purpose of this method exactly?
applicationDocumentsDirectory

A: *

*URLForResource represents the uri path to the momd file in the bundle.

*URLByAppendingPathComponent - code you provided will create database named Code.sqlite. You can freely change the name to whatever you want.

*applicationDocumentsDirectory method returns path to the Documents folder in the app sandbox


text:
Q: User's threads in Thin, Sinatra application on Heroku I have a set of time-costly operations which are specific for every single user of my app, it's all encapsulated in a method (e.g write_collections method). In this method program communicates with Facebook and MongoDB. I want to run this method in a thread for every user.
    This thread is called in get '/' Sinatra route but result of thread (a state in database) is needed only on get '/calculate'. My idea is to run the thread on get '/' and to join it on get '/calculate' to ensure that all the user's data has written properly in database before calculating results for the user starts.
To illustrate:

Approach I
get "/" do
  @user = @graph.get_object("me")

  data_thread = Thread.new do
    write_collections(@user)
  end

  session[:data_thread] = data_thread.object_id

  erb :index
end

get "/calculate" do
  begin
  # Is this safe enough?
  if ObjectSpace._id2ref(session[:data_thread]).alive?
      data_thread = ObjectSpace._id2ref(session[:data_thread])
      data_thread.join
  end
  rescue RangeError => range_err
    # session[:data_thread] is not id value
    # direct access to /calculate without session
  rescue TypeError => type_err
    # session[:data_thread] is nil
  end

  # do calculations based on state in database
  # and show results to user

  "
Under construction
"
end

    To find the proper thread on which specific user should waiting to join I currently use ObjectSpace._id2ref(session[:data_thread]).

*

*Is it safe enough?

Detailed:
From the official Ruby docs for Object#object_id:

object_id → fixnum:
  Returns an integer identifier for obj. The same number will be returned on all calls to id for a given object, and no two active objects will share an id.

and for ObjectSpace:

The ObjectSpace module contains a number of routines that interact with the garbage collection facility and allow you to traverse all living objects with an iterator.

*

*Is 'active object' from the first quote same as 'living object' from the second?

    Let's assume following situation:

*

*User A access '/' [now A thread is started with object_id a]

*Thread A is finished [it is not active anymore and it's object_id is released]

*User B access '/' [now B thread is started with the same object_id a (* is it possible?)]

*User A access '/calculate' [session[:data_thread] is a so ObjectSpace._id2ref(session[:data_thread]) is actually B thread.]

*Inconsistent state - user A is waiting for thread B.

*

*Is this scenario possible within Sinatra, Thin, Heroku?

Approach II
configure do
  # map user_id to corresponding user's thread
  data_threads_hash = {}
  set :data_threads_hash, data_threads_hash
end

get "/" do
  @user = @graph.get_object("me")

  data_thread = Thread.new do
    write_collections(@user)
  end

  session[:user_id] = @user['id']
  settings.data_threads_hash[session[:user_id]] = data_thread

  erb :index
end

get "/calculate" do

  if settings.data_threads_hash[session[:user_id]].alive?
    data_thread = settings.data_threads_hash[session[:user_id]]
    data_thread.join
    settings.data_threads_hash.delete session[:user_id]
  end

  # do calculations based on state in database
  # and show results to user

  "
Under construction
"

end

Detailed:
I tried this after reading Sinatra: README.
Under Configuration:

Run once, at startup, in any environment
  ...
  You can access those options via settings
  ...

And under Scopes and Binding, Application/Class Scope:

Every Sinatra application corresponds to a subclass of Sinatra::Base. If you are using the top-level DSL (require 'sinatra'), then this class is Sinatra::Application, otherwise it is the subclass you created explicitly. At class level you have methods like get or before, but you cannot access the request or session objects, as there is only a single application class for all requests.

I'm using the top-level DSL.

Options created via set are methods at class level ... You can reach
  the scope object (the class) like this: settings from within the
  request scope

*

*Bearing in mind what has been said @FrederickCheung in comments and quote from Scopes and Binding, whether this approach would worked if I ever need more than one dyno/worker (currently this app using only one dyno)?

Summary

*

*How should I handle described situation with users and their corresponding threads in Sinatra, how good or bad are approaches from the examples above?

Any comment or reference is welcome.

A: I'm not sure if this design makes sense. Why does each user need its own thread? Why would one request ever join a thread created by another request? Even if it were possible (by using only one dyno), I don't think it is a good way of doing what you want to do.
Based on the description of the app in the question, you want to run some calculate method after the write_collections method finishes. So, why can't the write_collections method call some calculate method? Or, why can't an after filter or observer be used to do the calculation?
More generally, you seem to be confounding two separate functions:

*

*The calculate functionality

*GET /calculate
I think there should only be one trigger for calling the calculate functionality. It is either upon completion of write_collections or when the user requests it (GET /calculate).
The more general solution is to have the calculate functionality run in the background, and save the results to the database. Later, when the user makes a request, it is ready and can be returned quickly.


text:
Q: Visual Studio doesn't reset tests results I am on Visual Studio 2015 and I am using MsTest.
If I open Visual Studio "first time" after Windows boot, I can see all test results empty, I can right click and choose "Run all tests" and they run.
After first run, if I re-compile the solution the test results are not wipe out and when I run a test it looks like it is using the "old code" after my modifications.
If I right click a test and choose "debug test" then it starts to use the latest changes...
It happens on my PC but on TFS everything is fine. It started to happen after I installed VS 2015.

A: to get around it, i just unload/reload the test project, and it should reset the tests.

A: Test results are not cleared after a build.  I've never experienced a situation where tests were run against old code after a new build.  Are you sure this is happening?

A: It sometimes occurs due to an error in the test engine. I had a similar problem, and I went to the Output window, then selected Tests. The output helped me get a hint about the problem.

A: You can try 2 solution bellow

*

*Right click your test project, then "clean"

*Delete .sln file and restart vs (when something go wrong with my solution, this option always work with me)

A: For me (on VS2017) I have to restart the whole VS. Closing the project/solution is insufficient. Thankfully I don't need to rebuild though.

A: In Visual Studio, solution explorer
Right-click on your solution "ProjectName" -> Clean solution.


text:
Q: Cython - Wrapping pointer to structure from C to python I have a C function which take pointer to struct and i want to use it in python by C-Extensions by Cython way but when i want to pass pointer to struct from python give me an error: "Cannot convert Python object to 'Foo *'"
In the below example i make object to call the C function but what passed to C function is NULL pointer.
My Trial:
hello.h
#include <stdio.h>

typedef struct
{
    int x;
} Foo;

int hello(Foo* what);

hello.c
#include "hello.h"

int hello(Foo* what)
{
    printf("Hello Wrapper\n");
    printf("what: %p\n", what);
    what->x = 5;
    return what->x;
}

phello.pxd
cdef extern from "hello.h":
    ctypedef struct Foo:
        int x

    cdef int hello(Foo* what)

phello.pyx
cimport phello

cdef class Foo_c:
    cdef phello.Foo* s

    def hello_fn(self):
        return phello.hello(self.s)

setup.py
from distutils.core import setup, Extension
from Cython.Distutils import build_ext

setup(
cmdclass = {'build_ext': build_ext},
ext_modules=[ Extension("hellomodule",
                         sources=["phello.pyx", "hello.c"],
                       ) ]

test.py
import hellomodule

print "Hello test.py"

tobject = hellomodule.Foo_c()
print "Object:", tobject

tobject.hello_fn()

So i want create "Foo" struct in "test.py" and pass it to "hello_fn()" function to call the C function "hello()" after passing this struct, so i can read or write on this structure from both sides python & C.
Can Anyone help me in this, please?

A: Your code does not allocate memory for phello.Foo. Allocation can be done in __cinit__ with calloc (or malloc) and deallocation in __dealloc__ with free.
cimport phello
from libc.stdlib cimport calloc, free

cdef class Foo_c:
    cdef phello.Foo* s

    def __cinit__(self, int n):
        self.s = <phello.Foo *>calloc(1, sizeof(phello.Foo))

    def __dealloc__(self):
        free(<void *>self.s)

    def __init__(self, int n):
        self.s.x = n


text:
Q: React Native Android SDK packages as some licences have not been accepted (Windows) I create a new project by npx react-native init AwesomeProject and I try to start run the project by npx react-native run-android
There is error that occur
error Failed to install the app. Please accept all necessary Android SDK licenses using Android SDK Manager: "$ANDROID_HOME/tools/bin/sdkmanager --licenses".
Error: Command failed: gradlew.bat app:installDebug -PreactNativeDevServerPort=8081

FAILURE: Build failed with an exception.

and
Could not determine the dependencies of task ':app:compileDebugJavaWithJavac'.
> Failed to install the following Android SDK packages as some licences have not been accepted.
     patcher;v4 SDK Patch Applier v4
     emulator Android Emulator
     platforms;android-30 Android SDK Platform 30
     build-tools;30.0.2 Android SDK Build-Tools 30.0.2
     tools Android SDK Tools
  To build this project, accept the SDK license agreements and install the missing components using the Android Studio SDK Manager.
  Alternatively, to transfer the license agreements from one workstation to another, see http://d.android.com/r/studio-ui/export-licenses.html

  Using Android SDK: C:\Users\user\AppData\Local\Android\Sdk\platform-tools

How should I solve this licenses issue?

A: To solve the problem, you need to accept all required Android SDK licenses. Just execute one of the following commands.
Windows:
cmd.exe /C"%ANDROID_HOME%\tools\bin\sdkmanager.bat --licenses"
macOS
yes | $ANDROID_HOME/tools/bin/sdkmanager --licenses


text:
Q: How can I detect changes in zoom level? Open this page on Chrome or Safari and fiddle with the zoom level. You'll notice a cute easing effect on its elements when you change the zoom level.
Apparently this only works on Chrome and Safari (webkit?), but how is this done? And is there a cross-browser way to do this?

A: I figured it out. JavaScript is not involved, it's pure CSS.
Namely, webkit's -webkit-transition property:
/* css */
.box {
   background: #5599ff; text-align: center;
   line-height: 80px; height: 80px; width: 100px;
   font-family: arial, helvetica; color: #FFF;
   -webkit-border-radius:3px; margin: 10px }

.trans {
    -webkit-transition:all .218s; }

 STIFF

 FLUID

EDIT: Upon further research, I found out most browsers (ie: everything but IE) support a vendor specific transition CSS property. However, only webkit browsers use transitions when the page is resized.
See demo on jsfiddle

A: I dont think there is any (cross-browser) direct way of listening to page zoom event. There are some backdoors  described on Catch browser's "zoom" event in JavaScript . however I think you can listen to Ctrl + + / - OR Ctrl+Mouse Wheel Event.


text:
Q: Xamarin: Not able to run app on an iOS 9.2.1 device I'm an IOS developer in Xcode, but I still new to Xamarin environment ..
In Xamarin Studio on mac, I'm trying to run a single view app on my iPad, using this tutorial ...
But when I choose to run the app.. it gives me these two errors :

Error: Could not locate the iOS '9.2' SDK usr path at
  '/Applications/Xcode.app/Contents/Developer/Platforms/iPhoneOS.platform/Developer/SDKs/iPhoneOS9.2.sdk'
Error: Error executing task DetectSdkLocations: Value cannot be null.
  Parameter name: path1

Here are some informations about what I'm using
The iPad is running IOS 9.2.1
Xamarin Studio: Version 5.10.2
Xamarin.iOS: Version 8.10.0.303
Xcode: Version 7.2.1
And the SDK locations in Xamarin preferences are set properly

So where is the problem ?? and can I run the app on iPad with IOS 9.2.1 ??
Thanks in advance ..

A: You can not have access to the 9.x version of IOS until the 9.x.x.x version of Xamarin.IOS


text:
Q: Pfquery...object to array.. to label it is my first time that I use parse and I'm a beginner.
I have built a table, and I show in the rows the data of my array
myArray= [NSMutableArray arrayWithObjects:@"Pasquale", @"Mario", nil];

cell.label1.text=  [myArray objectAtIndex:indexPath.row];
Now I want to fetch the data from a class in parse and I wrote:
PFQuery *query = [PFQuery queryWithClassName:@"Dispositivi"];
[query whereKey:@"NomeDispositivo" equalTo:@"Franco"];
[query findObjectsInBackgroundWithBlock:^(NSArray *objects, NSError *error) {
    if (!error) {
// The find succeeded.
        NSLog(@"Successfully retrieved %d scores.", objects.count);
        // Do something with the found objects
for (PFObject *object in objects) {
            NSLog(@"%@", object.objectId);
}
    } else {
        // Log details of the failure
        NSLog(@"Error: %@ %@", error, [error userInfo]);
    }
}];

The code worked. But I want to know : How I can put the object in the array...and I can put a row in the array. For example every String of row: Name.
Thanks

A: If you want to append to the array:
[myArray addObjectsFromArray:objects];

*instead of your for loop. Note that this would currently result in your array containing NSString and PFObject instances and that could cause you issues...
Alternatively, replace the existing array:
myArray = [objects mutableCopy];


text:
Q: What make # go in different line instead of continuing the line? I'm not sure why # go in the wrong line when it supposed to continue after 'u'
#include <stdio.h>
#define LEN 5

int inputNumber() {
    int size;
    printf("Input Size: ");
    scanf("%d",&size);
    printf("===\nTriangle Size is %d\n===\n",size);
    return size;
}

void printTriangle(int size, char ch[]) {
    for(int i = 0; i < size; i++)
    {
        for(int j = 0; j <= i; j++)
        {
            if(j<=LEN)
                printf("%c ",ch[j]);
            if(j>LEN)
                printf("# ");
        }
        printf("\n");
    }
}

int main() {
    char arr_char[LEN] = {'a','e','i','o','u'};
    int number;
    number = inputNumber();
    printTriangle(number,arr_char);
    return 0;
}

I used to ask about this same code before but I want to try using if-else instead of ? :  because I haven't learn that yet in class so I want to know if it's possible using basic thing like if-else.

A: Your code has undefined behavior because you are trying to access memory beyond the declared array arr_char in this if statement
        if(j<=LEN)
            printf("%c ",ch[j]);

The valid range of indices for the array is [0, LEN ).
You need to rewrite the if statement like
        if(j < LEN)
            printf("%c ",ch[j]);

As it is seen from the output picture it seems that in the byte just after the array it occurred such a way that there is stored the new line character '\n'.
a e i o u
a e i o u

a e i o u
 #


text:
Q: How to use the WP Plugin List Category Post widget (!) with more than one category? The Plugin List Category Post used as shortcode in a post/page allows to display a number of random posts from several categories.
But when I use the plugin's widget I can choose only one category.
Is there a way to use the widget and allow to choose several categories?

A: You can use these shortcodes:
This will show posts that are in Categories 17 AND 25 AND 2
[catlist id=17+25+2]

OR
This will include post that are from any of categories 17 OR 24 OR 32
[catlist id=17,24,32]

You can also us catlist name in the same way:
[catlist name=sega+nintendo]
[catlist name=sega,nintendo]

I have it in use on my site like that:
eg:
[catlist id=191+199, orderby=date order=dec numberposts=10 Date=yes]

191 = a country category and 199 = latest news category.

A: Unfortunately, the widget for this rather slip-shod plugin seems to have been built as an afterthought, and doesn't appear to do what you require. There's really no excuse for not directly supporting the plugin, and I'd advise against using this one.
That said, if you must, try adding the following to your functions.php:
add_filter( 'widget_text', 'shortcode_unautop');
add_filter( 'widget_text', 'do_shortcode');

Then use a standard text widget instead of the plugin widget. Within that text widget, add the desired shortcode.


text:
Q: Need to create multiple HUDSON_HOME environment variables with different name for multiple hudson instance I have 2 Hudson instances deployed in single tomcat. For that i need to set different Hudson home directories. 1st hudson has home directory set as HUDSON_HOME(D:\Hudson) and its working fine.
In 2nd hudson, i have tried to change the name HUDSON_HOME to HUDSON_HOME_BOSS in web.xml & set HUDSON_HOME_BOSS as D:\hudson_boss in environment variables but it is still taking the location d:\hudson.
DOes anyone has any idea how to change hudson home directory with different name???

A: HUDSON_HOME is the environment variable that you need to set. You cannot change its name. Try setting HUDSON_HOME to different directories on each instance's web.xml.

A: I noticed this is a bit old but will assume you're still looking for the answer. Go here and you will find out how easy it is: http://www.jamesthigpen.com/blog/2009/04/17/running-multiple-hudson-instances-simultaneously/
I actually had to have two instances running a few days ago.


text:
Q: How add a link to an icon of another component not in app.js in React.js I am working on a react project
In the App.js
I have all my imports and routers
Now I want to apply a router to an icon on the nav that routes to settings.
And I did that by creating another component for Settings, then I import the Settings to my App.js then link it to my icon  route
So when I click it, it displays Settings.
Now the issue is
On that my settings page
I have lots of contents and icons
Now I want that if I click a
( General Settings icon ) it should display General Settings.
So how will I now add route to that icon.
My General Settings(page) is a different component. And not in the App.js page

A: You can do it as the same  way as if it was in the app.js
App.js (react 18)
<Route path="/url/to/settings" element={<SettingsComponent/>} />

The Component where you 'have lots of contents and icons'
<Link to={/url/to/settings}>
   <Icon />
</Link>

A: You should use nested routes, Robin Wieruch has a good post about it: https://www.robinwieruch.de/react-router-nested-routes/
/index.js
root.render(
  <BrowserRouter>
    <Routes>
      <Route path="/" element={<App />} />
      <Route path="settings" element={<Settings />}>
        <Route path="general-settings" element={<GeneralSettings />} />
      </Route>
    </Routes>
  </BrowserRouter>
);

/App.js
...
<Link to="settings">Settings icon</Link>

/Settings.js
...
<Link to="general-settings">General settings icon</Link>
<Outlet />


text:
Q: Is it safe to extract the root filesystem of a Docker.io image and use it in a chroot? I have recently discovered Docker, and I think it's a great tool for managing my runtime environments. However, I also have some OpenVZ VPS'es that don't support LXC, so I'm thinking about using docker export to export the filesystem of an image, extract the resulting tarball to a directory in the VPS, and then chroot into that directory and run the services inside the image.
Is it safe to do this? What customizations does Docker make to the filesystem of its image (I can see a .dockerinit file in the root directory at first glance)? Any tips & pitfalls of this approach?

A: The main risk would be isolation. If your OpenVZ is properly configured and warranty the isolation, you are good to go.
Docker does not do any modification to the file system. At runtime, it mounts itself as .dockerinit. We use this in order to setup the user/group and network once the container is started.
In future version, docker will support different isolation backend like libvirt or even chroot. The base image aren't going to change though, so there is no problem using docker images on OpenVZ.


text:
Q: How to have events in WPF user control I got a user control:
<UserControl x:Class="NeocClinic.WPFSystem.Templatas.FunctionButtonsUserControl"
             xmlns="http://schemas.microsoft.com/winfx/2006/xaml/presentation"
             xmlns:x="http://schemas.microsoft.com/winfx/2006/xaml"
             xmlns:mc="http://schemas.openxmlformats.org/markup-compatibility/2006"
             xmlns:d="http://schemas.microsoft.com/expression/blend/2008"
             mc:Ignorable="d" >
    <Grid Name="GridFunctionButtons" Margin="5" >
        <Grid.ColumnDefinitions >
            <ColumnDefinition />
            <ColumnDefinition />
            <ColumnDefinition />
            <ColumnDefinition />
        </Grid.ColumnDefinitions>

        <Button Name="btnExecute" Content="Execute" MinHeight="50" MinWidth="120" Grid.Column="0"/>
        <Button Name="btnUndo" Content="Undo" MinHeight="50" MinWidth="120" Grid.Column="1"/>
        <Button Name="btnBack" Content="Back" MinHeight="50" MinWidth="120" Grid.Column="2"/>
        <Button Name="btnDelete" Content="Delete" MinHeight="50" MinWidth="120" Grid.Column="3"/>

    </Grid>
</UserControl>

I used it in my Windows form XAML:
<windowsControls:FunctionButtonsUserControl x:Name="UserControlFunctionButtons" Grid.Row="5" Grid.Column="0" />

I can now see the buttons in my C# code, but the problem is the events. The four buttons must have each events but differs with each form that I deployed it, so I can't put the events in the usercontrol.xaml.

A: You need to have the same events in the UserControl and then you subscribe to them on the "form" (though it is not proper WPF terminology), and then you can raise new events from there if that is required or call appropriate methods...
EDIT: To raise events from UserControl, just declare them in code behind like (updated later according the comments below):
public event RoutedEventHandler MyEvent;
private void button_Clicked(object sender, RoutedEventArgs e)
{
    if (MyEvent != null)
        MyEvent(this, e);
}

This is from the head without editor, so I might wrote something wrong, but you'll get the idea.

A: There are two ways to approach this problem:

*

*Use Routed Events. This lets you put events on your UserControl that the "owning" XAML can use and register for. The internal buttons would then raise these events. For more information on Routed Events, see MSDN.

*Use Commands exposed as DepenencyProperty. This allows the "owning" XAML to bind commands to your user control, which would then be invoked by your buttons. You could even bind the exposed Command properties straight to the button's.
The second is prefered since it stays within MVVM, but both will work.


text: Q: How do I install an external library in Dev-c++? (raylib) I want to include an external library called "raylib" on Dev-C++. I downloaded the library with .zip extension from github and tried to install it with Dev-C++ package installer, but it gives me an erorr and doesn't work. I exctracted it and tried other things like adding the library folder in the "Library" section in "Compiler Option" but it was useless. Could you help me please?


text:
Q: How to run Battle Simulator could you please advise, how to run battle simulator? I've seen post on battle net it should be available and post is quite old, but how can I start it?
I heard there are custom maps searched and found one... on start I have just observer... (i started with Protoss only) and can't figure out how to build units...
I saw how Nany and other streamers do that in much better way, but cannot recall how do they do that.
Maybe I should find the PROPER map?
P.S. In fact, Now I need to check whom marines are targeting when fight with mix of immortals and zealots.
Thank you.

A: If I understand you correctly, you need to create a set of units quickly for 2 players and they run a battle with them against 1 AI.
Then you can go to Arqades and find "HOTS Unit Tester Online" Map (I can't be sure about other servers, but it is on Europe server and I saw it on American server).
Then it is quite self explanatory, you can change terrain and choose units for both sides, and choose upgrades for them. Also you have help button.
Once you put everything you need you can run it, taking control of one side.


text:
Q: 2D Mercator map onto globe method Preface to the question: I came up with a method of transferring a 2d projection map of the earth onto a globe and made a webapp to help me do that here:
http://codepen.io/vez/full/YVWLRm/
(press alt and move the mouse to rotate the globe/translate the map. Click to place a point on the globe.)
My idea was to take a globe that can be rotated and allow the user to place points on it at the point with the least depth on the globe (always in the middle). When you rotate the sphere you also move a map behind it such that the whole width of the map will be translated given a full horizontal rotation of the sphere, and the height of the map translated given a full vertical rotation. The idea was to move the map so that the borders of land are in the middle circle and place points along the borders in order to capture the globe from the map.
This is where I run into my problem. I imagined that I could find a good 2d map projection so that when I transferred it onto the globe using this method it would be an accurate globe.
https://en.wikipedia.org/wiki/List_of_map_projections
I've heard that no 2d map is accurate, but surely one is the "inverse" of the method I am using to create this globe? So my question is: Using the method described, which type of 2d projection map of the earth, will result in an accurate globe?

A: As ALB pointed out it is theoretically impossible to map the plane to the sphere (There is no homeomorphism between the plane and the sphere).
in practice however, it is entirely possibly because there is a homeomorphism between the plane and the sphere with a single point removed. In computing this makes no difference because nothing is continuous anyways.
So the answer: The method I listed above is the approximate inverse of the Equirectangular Projection of the globe.


text:
Q: Limiting values of column to +100% in Python I have columns in df whose values should be limited to +100%
Current output:
var1  var2   var3    var4
140%  475%   895%   16249%
337% -100%  -100%    -100%
173%  -95%  5165%     454%
458%   18%   354%    -100%
483%  -73%  6962%    -100%
147%   18%  -100%    -100%

Desired output
var1  var2   var3    var4
100%  100%   100%     100%
100% -100%  -100%    -100%
100%  -95%   100%     100%
100%   18%   100%    -100%
100%  -73%   100%    -100%
100%   18%  -100%    -100%

So each value in each column which higher than 100%, should be replaced with 100%.
And I don't know how to do it
EDIT: data is not strings, but previously looked like this:
Previous output:
var1  var2   var3    var4
1.40  4.75   8.95   162.49
3.37 -1.00  -1.00    -1.00
1.73 -0.95  51.65     4.54
4.58  0.18   3.54    -1.00
4.83 -0.73  69.62    -1.00
1.47  0.18  -1.00    -1.00

on which I applied this:
df = df.style.format({'var1': '{:.0%}','var2': '{:.0%}', 'var3': '{:.0%}','var4': '{:.0%}'})

as I need numbers in % as final output
Big apologies for not providing sufficient info, and thank you very much for your help @user19077881

A: To apply numpy clip to a DataFrame df with the % values as strings you could use:
def clip_it(x):
    try:
        n = x.replace('%', '')
        n = np.clip(int(n), -100, 100)
        return str(n)+'%'
    except ValueError:
        return x

df = df.applymap(clip_it)
with
df = pd.DataFrame({'x': ['100%', '-200%', '57%'],
                   'y': [ '45%', '167%', '-23%']})

it gives
       x     y
0   100%   45%
1  -100%  100%
2    57%  -23%

A: If you want to clip your data to -100%, 100%, you should do it before styling it. Because your styler is basically multiplying by 100 and adding a '%' character, a -100%, 100% clip in your styled data is equivalent to a -1.0, 1.0 clip in your original data.
df = df.apply(lambda x: np.clip(x, -1, 1))
df

    var1    var2    var3    var4
0   1.0     1.00    1.0    1.0
1   1.0    -1.00   -1.0   -1.0
2   1.0    -0.95    1.0    1.0
3   1.0     0.18    1.0   -1.0
4   1.0    -0.73    1.0   -1.0
5   1.0     0.18   -1.0   -1.0

df.style.format({'var1': '{:.0%}','var2': '{:.0%}', 'var3': '{:.0%}','var4': '{:.0%}'})

    var1    var2    var3    var4
0   100%    100%    100%    100%
1   100%   -100%   -100%   -100%
2   100%   -95%     100%    100%
3   100%    18%     100%   -100%
4   100%   -73%     100%   -100%
5   100%    18%    -100%   -100%

However, I wonder whether you actually nedd to clip your data as your example suggest or whether you may want to scale it relative to the maximum and minimum in each column. If you clip it, you loss the differences between 162.49 and 4.54, both becoming 100%. By scaling it, you can keep it in the desired range while conserving the relative distances.
Based on this answer, you can do
def scaler(data):
    top, bottom = 1, -1
    minimum, maximum = data.min(), data.max()
    return (data - maximum) / (minimum - maximum) * (bottom - top) + top

df = df.apply(scaler)
df

    var1    var2    var3    var4
0  -1.000000    1.000000   -0.718210    1.000000
1   0.148688   -1.000000   -1.000000   -1.000000
2  -0.807580   -0.982609    0.491079   -0.932228
3   0.854227   -0.589565   -0.871425   -1.000000
4   1.000000   -0.906087    1.000000   -1.000000
5  -0.959184   -0.589565   -1.000000   -1.000000

df.style.format({'var1': '{:.0%}','var2': '{:.0%}', 'var3': '{:.0%}','var4': '{:.0%}'})

    var1    var2    var3    var4
0  -100%    100%    -72%    100%
1    15%   -100%   -100%   -100%
2   -81%    -98%     49%    -93%
3    85%    -59%    -87%   -100%
4   100%    -91%    100%   -100%
5   -96%    -59%   -100%   -100%

Of course, because this is scaling based on the max and min values of each column, while clipping on -1.0, 1.0, the 0 of the scaled data is not going to correspond with the 0 of the original data. For example, in the column var4, 4.54 becomes -93% because is really close tot the minimum. You can adapt the previous function to use the maximum absolute value when scaling:
def scaler_abs(data):
    top, bottom = 1, -1
    max_abs = max([data.min(), data.max()], key=abs)
    minimum, maximum = -max_abs, max_abs
    return (data - maximum) / (minimum - maximum) * (bottom - top) + top

df = df.apply(scaler_abs)
df

    var1    var2    var3    var4
0   0.289855    1.000000    0.128555    1.000000
1   0.697723   -0.210526   -0.014364   -0.006154
2   0.358178   -0.200000    0.741885    0.027940
3   0.948240    0.037895    0.050847   -0.006154
4   1.000000   -0.153684    1.000000   -0.006154
5   0.304348    0.037895   -0.014364   -0.006154

df.style.format({'var1': '{:.0%}','var2': '{:.0%}', 'var3': '{:.0%}','var4': '{:.0%}'})

    var1    var2    var3    var4
0   29%     100%     13%     100%
1   70%     -21%     -1%      -1%
2   36%     -20%     74%       3%
3   95%       4%      5%      -1%
4   100%    -15%    100%      -1%
5   30%       4%     -1%      -1%

A: You might use numpy.clip to set values outside range with range min or max, consider following simple example
import numpy as np
arr = np.array([[-500,-300,-100],[0,50,150]])
arr2 = np.clip(arr, -100, 100)
print(arr2)

gives output
[[-100 -100 -100]
 [   0   50  100]]


text:
Q: ResultSet object reaches the end after one iteration I'm trying to read all records in a table from a database, and do some processing using those data. Following is the code that I use.
package differences;

import java.sql.Connection;
import java.sql.DriverManager;
import java.sql.PreparedStatement;
import java.sql.ResultSet;
import java.sql.SQLException;
import java.util.HashMap;
import java.util.Map;
import java.util.logging.Level;
import java.util.logging.Logger;
import javax.swing.JOptionPane;

public class ConformancePercentageChecking {

    private final String dbDriver = "com.mysql.jdbc.Driver";
    private Connection connection = null;
    private final String serverName = "localhost";
    private final String mydatabase = "google";
    private final String username = "root";//kh hoseinpur
    private final String password = "123";
    private final String extrainfo = "?useUnicode=true&characterEncoding=UTF-8";
    int numberOfInsertedIDs = 0;

    public void findConformances() {
        try {
            try {
                Class.forName(dbDriver);//a call to forname("X") causes the class named X to be initialized
                String url = "jdbc:mysql://" + serverName + "/" + mydatabase + extrainfo;
                if (connection == null) {
                    connection = (Connection) DriverManager.getConnection(url, username, password);
                }
            } catch (ClassNotFoundException | SQLException e) {
                JOptionPane.showMessageDialog(null, "database");
            }

            String query1, query2, query3, query4, query5, query6, testSuite, id;
            PreparedStatement statement1, statement2, statement3, statement4, statement5, statement6;
            query1 = "drop table PresConformance;";
            query2 = "drop table PostConformance;";
            statement1 = connection.prepareStatement(query1);
            statement2 = connection.prepareStatement(query2);
            statement1.executeUpdate();
            statement2.executeUpdate();
            query1 = "CREATE TABLE PresConformance(testSuite Text, conformance numeric(10), depthDifference numeric(10),pathLength numeric(10));";
            query2 = "CREATE TABLE PostConformance(testSuite Text, conformance numeric(10), depthDifference numeric(10),pathLength numeric(10));";
            query3 = "SELECT * FROM presDifference;";
            query4 = "SELECT * FROM presdifference;";
            query5 = "insert into PresConformance values(?,?,?,?);";
            query6 = "insert into PostConformance values(?,?,?,?);";
            statement1 = connection.prepareStatement(query1);
            statement2 = connection.prepareStatement(query2);
            statement3 = connection.prepareStatement(query3);
            statement4 = connection.prepareStatement(query4);
            statement5 = connection.prepareStatement(query5);
            statement6 = connection.prepareStatement(query6);
            Map<String, String> map = new HashMap<>();

            statement1.executeUpdate();
            statement2.executeUpdate();

            ResultSet r1, r2, r3, r4;
            r1 = statement3.executeQuery();
            System.out.println("***1");
            r2 = statement4.executeQuery();
            System.out.println("***2");

            int idCount = 0, depthDifference = 0, totalNumberOfExecutions = 0, testSuitesCounts = 0, difference = 0, pathLength = 0;
            float conformancePercentage = 0, sumOfconformancePercentage = 0;
            r3 = r1;
            r4 = r2;
            while (r1.next()) {
                testSuitesCounts = 0;
                sumOfconformancePercentage = 0;
                testSuite = r1.getString("testSuite");
                id = null;
                id = map.get(testSuite);
                if (id == null) {
                    idCount++;
                    map.put(Integer.toString(idCount), testSuite);
                    r3.absolute(r1.getRow());
                    r3.previous();
                    while (r3.next()) {
                        if (testSuite.equals(r3.getString("testSuite"))) {
                            System.out.println(testSuite + " equal");
                            totalNumberOfExecutions = r3.getInt("totalNumberOfExecutions");
                            difference = r3.getInt("difference");
                            conformancePercentage = (1 - ((float) difference / totalNumberOfExecutions)) * 100;
                            if (testSuitesCounts == 0) {
                                String[] testSuite1, testSuite2, testSuite3;
                                testSuite1 = testSuite.split("_");
                                testSuite2 = testSuite1[0].split("/");
                                testSuite3 = testSuite1[1].split("/");
                                depthDifference = Math.abs(testSuite2.length - 1) - testSuite3.length;
                                pathLength = (testSuite2.length - 1) + testSuite3.length;
                            }
                            testSuitesCounts++;
                            sumOfconformancePercentage += conformancePercentage;
                        }
                    }
                    statement5.setString(1, testSuite);
                    statement5.setFloat(2, (sumOfconformancePercentage / testSuitesCounts));
                    statement5.setInt(3, depthDifference);
                    statement5.setInt(4, pathLength);
                    statement5.executeUpdate();
                }
                System.out.println(r1.getRow());
            }

            System.out.println("Pres Finished*****************************************");
            idCount = 0;
            map = new HashMap<>();
            while (r2.next()) {
                testSuitesCounts = 0;
                sumOfconformancePercentage = 0;
                testSuite = r2.getString("testSuite");
                id = null;
                id = map.get(testSuite);
                if (id == null) {
                    idCount++;
                    map.put(Integer.toString(idCount), testSuite);
                    r4.absolute(r2.getRow());
                    r4.previous();
                    while (r4.next()) {
                        if (testSuite.equals(r4.getString("testSuite"))) {
                            System.out.println(testSuite + " equal");
                            totalNumberOfExecutions = r4.getInt("totalNumberOfExecutions");
                            difference = r4.getInt("difference");
                            conformancePercentage = (1 - ((float) difference / totalNumberOfExecutions)) * 100;
                            if (testSuitesCounts == 0) {
                                String[] testSuite1, testSuite2, testSuite3;
                                testSuite1 = testSuite.split("_");
                                testSuite2 = testSuite1[0].split("/");
                                testSuite3 = testSuite1[1].split("/");
                                depthDifference = Math.abs(testSuite2.length - 1) - testSuite3.length;
                                pathLength = (testSuite2.length - 1) + testSuite3.length;
                            }
                            testSuitesCounts++;
                            sumOfconformancePercentage += conformancePercentage;
                        }
                    }
                    statement6.setString(1, testSuite);
                    statement6.setFloat(2, (sumOfconformancePercentage / testSuitesCounts));
                    statement6.setInt(3, depthDifference);
                    statement6.setInt(4, pathLength);
                    statement6.executeUpdate();
                }
            }
            System.out.println("Post Finished*****************************************");

            System.out.println("Finished Inserting to DB");
        } catch (SQLException ex) {
            Logger.getLogger(DifferencesPresPost.class.getName()).log(Level.SEVERE, null, ex);
        }
    }
}

The problem, is that for both ResultSet objects r1 and r3, which contain tables' records, it just iterates once, and then reaches the end of the ResultSet objects.
I tried to count number of records in both ResultSet objects before each while loop, and it correctly prints the number of recoreds, but when it enters in these while loops, it works for only first row of each ResultSet objects.
Can any body help me to find out the result of this problem?

A: I believe by default your resultsets are TYPE_FORWARD_ONLY. You need to specify TYPE_SCROLL_INSENSITIVE when preparing your prepared statements. Hope this helps.


text:
Q: Proving Convexity for a function $f(x) = \frac1{g(x)}$? So I have a function $g$ that maps from some subspace, $S$, of $\mathbb{R}^n$ to $\mathbb{R}$. $g$ is concave such that $g(x) > 0$ for all $x$ in this subspace, $S$, of $\mathbb{R}^n$.
$f(x)$ is defined as $f(x) = \frac1{g(x)}$ and the question is to show that $f(x)$ is convex.
How would I do this by the definition of convexity?
My try:
As g is concave we have $g(ax + (1-a)y) \Rightarrow ag(x) + (1-a)g(x)$ which means that
$f(ax + (1-a)y) = 1 / g(ax + (1-a)y) \Leftarrow 1/ag(x) + (1-a)g(x)$.
Thanks!


text:
Q: How can I get specific tag with jsoup android here is some part of my HTML

hello world

</p

goodbye world

As you see have 3
 tag inside HTML. But how can I define in jsoup to take just normal
 tag like hello world and goodbye world and ignore that
 tag with img class?
here is my code so far :
public class MainActivity extends AppCompatActivity {

   public WebView webView;

    @Override
    public void onCreate(Bundle savedInstanceState) {
        super.onCreate(savedInstanceState);
        setContentView(R.layout.main_page);
        webView=(WebView)findViewById(R.id.webi);

        new AsyncTask<Void, Void, String>() {
            @Override
            protected String doInBackground(Void... voids) {
                String html = "";
                try {
                    Document document = Jsoup.connect("http://memaraneha.ir/%db%8c%da%a9%d9%be%d8%a7%d8%b1%da%86%da%af%db%8c-%d9%87%d9%85%d8%a7%d9%87%d9%86%da%af%db%8c-%d8%b7%d8%b1%d8%a7%d8%ad%db%8c-%d8%af%d8%a7%d8%ae%d9%84%db%8c/")
                            .timeout(20000).get();

                    Elements elements=document.select("div.base-box:nth-child(2)").select("p");
                    html = elements.toString();

                } catch (IOException e) {
                    e.printStackTrace();
                }
                return html;
            }
            @Override
            protected void onPostExecute(String html) {

                String mime = "text/html";
                String encoding = "utf-8";

                webView.loadDataWithBaseURL(null,html, mime, encoding,null);
            }
        }.execute();

    }

}

A: You can avoid the loop and use the following:
Elements e = doc.select("p:not(:has(img))");

A: You can try with something like this.
Selects all
 tags that don't have any  tag inside
    Document document = Jsoup.connect().get();
    Elements elements = new Elements();
    for (Element e : document.select("p")) {
        if (e.select("img").isEmpty()) {
            elements.add(e);
        }
    }


text:
Q: In an equilateral spherical triangle, show that $\sec A=1+\sec a$ Q. In an equilateral spherical triangle, show that $\sec A=1+\sec a$
So $A$ is the vertex or the angle of the triangle and $a$ is the side of the equilateral spherical triangle.
I started off the proof by using the law of cosines:
$$\cos(a)-\cos(a)\cos(a)=\sin(a)\sin(a)\cos(A)$$
and after simplifying it a bit, I obtained:
$$\cos(a)-\cos^2(a)=\sin^2(a)\cos(A)$$
I replaced $\sin^2(a)$ with $(1-\cos^2(a))$.
Then I obtained:
$$\cos(a)-\cos^2(a)=(1-\cos^2(a))\cos(A)$$
and I realized on the left side, I can pull a $\cos(a)$. So through factoring:
$$\cos(a)(1-\cos(a))=(1-\cos^2(a))\cos(A)$$
Either I'm not seeing it but I do not how to proceed after this. If anyone can help, I'd like that. Thanks!

A: lambda, mu are lattitude and longitude. $R = 1$.
$O = (0,0,0)$
$A = (\cos \lambda_a \cos \mu_a, \cos \lambda_a \sin \mu_a, \sin \lambda_a)$
$B = (\cos \lambda_b \cos \mu_b, \cos \lambda_b \sin \mu_b, \sin \lambda_b)$
$C = (\cos \lambda_c \cos \mu_c, \cos \lambda_c \sin \mu_c, \sin \lambda_c)$
The planes $AOB$ and $AOC$ have the line $OA$ in common. Let $\alpha = \angle (AOB, AOC)$.
$OB \cdot OC = \cos \beta$.
You claim that $\frac{1}{\cos \alpha} = 1 + \frac{1}{\cos \beta}$ (*)
Angle between normals implies vectorial product: $\alpha = \angle (OA \times OB, OA \times OC)$.
$\cos \alpha = (OA \times OB) \cdot (OA \times OC)$
$(*) \Rightarrow  \cos \beta = \cos \alpha \cos \beta + \cos \alpha \Rightarrow \cos \beta (1 - \cos \alpha) = \cos \alpha$
$\cos \alpha = b_x c_x + b_y c_y + b_z c_z$
$A \times B = (a_y b_z - a_z b_y, - a_z b_x + a_x b_z, a_x b_y - a_y b_x)$
$A \times C = (a_y c_z - a_z c_y, - a_z c_x + a_x c_z, a_x c_y - a_y c_x)$
$\cos \beta = (a_y b_z - a_z b_y)(a_y c_z - a_z c_y) + (- a_z b_x + a_x b_z)(- a_z c_x + a_x c_z) + (a_x b_y - a_y b_x)(a_x c_y - a_y c_x)$
$\cos \beta = (a_y^2 b_z c_z - a_y a_z b_z c_y - a_y a_z b_y c_z + a_z^2 b_y c_y) + (a_z^2 b_x c_x - a_x a_z b_x c_z - a_x a_z b_z c_x + a_x^2 b_z c_z) + (a_x^2 b_y c_y - a_x a_y b_y c_x - a_x a_y b_x c_y + a_y^2 b_x c_x)$
$\cos \beta = a_y^2 (\cos \alpha - b_y c_y) + a_z^2 (\cos \alpha - b_z c_z) + a_x^2 (\cos \alpha - b_x c_x) + (- a_y a_z b_z c_y - a_y a_z b_y c_z) + (- a_x a_z b_x c_z - a_x a_z b_z c_x) + (- a_x a_y b_y c_x - a_x a_y b_x c_y)$
$\cos \beta = \cos \alpha - a_x^2 b_x c_x - a_y^2 b_y c_y - a_z^2 b_z c_z + (- \cos \lambda_a \sin \mu_a \sin \lambda_a \sin \lambda_b \cos \lambda_c \sin \mu_c - \cos \lambda_a \sin \mu_a \sin \lambda_a \cos \lambda_b \sin \mu_b \sin \lambda_c) + (- \cos \lambda_a \cos \mu_a \sin \lambda_a \cos \lambda_b \cos \mu_b \sin \lambda_c - \cos \lambda_a \cos \mu_a \sin \lambda_a \sin \lambda_b \cos \lambda_c \cos \mu_c) + (- \cos \lambda_a \cos \mu_a \cos \lambda_a \sin \mu_a \cos \lambda_b \sin \mu_b \cos \lambda_c \cos \mu_c - \cos \lambda_a \cos \mu_a \cos \lambda_a \sin \mu_a \cos \lambda_b \cos \mu_b \cos \lambda_c \sin \mu_c)$
$\cos \beta = \cos \alpha - a_x^2 b_x c_x - a_y^2 b_y c_y - a_z^2 b_z c_z + \cos \lambda_a [(- \sin \mu_a \sin \lambda_a \sin \lambda_b \cos \lambda_c \sin \mu_c - \sin \mu_a \sin \lambda_a \cos \lambda_b \sin \mu_b \sin \lambda_c) + (- \cos \mu_a \sin \lambda_a \cos \lambda_b \cos \mu_b \sin \lambda_c - \cos \mu_a \sin \lambda_a \sin \lambda_b \cos \lambda_c \cos \mu_c) + (- \cos \mu_a \cos \lambda_a \sin \mu_a \cos \lambda_b \sin \mu_b \cos \lambda_c \cos \mu_c - \cos \mu_a \cos \lambda_a \sin \mu_a \cos \lambda_b \cos \mu_b \cos \lambda_c \sin \mu_c)]$
I may have not defined right.

A: Let $\,x:=\cos(a)\,$ and $\,X:=\cos(A).\,$ Then
$$ 1+\sec(a)-\sec(A) = 1+\frac1x-\frac1X = \frac{-x+X+xX}{xX}.$$
$$ \cos(a)(1-\cos(a))-(1-\cos^2(a))\cos(A)=x(1-x)-(1-x^2)X=(x-1)(-x+X+xX).$$
Thus, if $\,x\ne 1,\,$ then
$\, \cos(a)(1-\cos(a))=(1-\cos^2(a))\cos(A)\, $ implies that
$\, 1+\sec(a)=\sec(A).$


text:
Q: How to understand MTA's real-time gtfs data feeds So far I've filled out the MTA online registration form for a Developer's API Key. Then in my android project, I implemented the gtfs realtime bindings dependecy from one of Google's github repositories,
compile group: 'com.google.transit', name: 'gtfs-realtime-bindings', version: '0.0.4'

Using their Java class, I tried this following code to print out all the gtfs data from the link given by MTA,
try {
    String urlString = "http://datamine.mta.info/mta_esi.php?key=insertmykeyhere";
    URL url = new URL(urlString.toString());
    GtfsRealtime.FeedMessage feed = GtfsRealtime.FeedMessage.parseFrom(url.openStream());
    for (GtfsRealtime.FeedEntity entity : feed.getEntityList()) {
        if (entity.hasTripUpdate()) {
            Log.d("stuff", entity.getTripUpdate().toString());
        }
    }

} catch (IOException e) {
            e.printStackTrace();
}

However, I'm now having trouble interpreting the data printed out. I understand that there are static data feeds from http://web.mta.info/developers/developer-data-terms.html, which I used to interpret some of the data. Here is one of the trip updates printed out,
stuff: trip {
    trip_id: "036000_GS.N01R"
    start_date: "20170218"
    route_id: "GS"
    1001: "\n\0200S 0600  GCS/TSS\020\001\030\001"
}
stop_time_update {
    departure {
        time: 1487415600
    }
    stop_id: "901N"
    1001: "\n\0011\022\0011"
}
stop_time_update {
    arrival {
        time: 1487415690
    }
    stop_id: "902N"
    1001: "\n\0011"
}

I understand some parts such as trip_id, start_date, and stop_id. But parts such as trip_id, time, and 1001 I'm still unsure about it and the text files from the static feed don't do the best job of explaining them.

A: The MTA Subway GTFS-RT feeds are a little different than most others.
Typically, GTFS-RT refers directly back to a static GTFS' via trip_id/stop_id/etc. Since in NYC there is usually a deviation from normal service ("2 Train via the 5 Line"), the RT feed retains the option to create new trips that do not exist in the static feed.
To answer your immediate questions, you need to add the realtime extensions. That should solve the empty 1001: field.
To do so, either compile the proto file, or just import the onebusaway-gtfs-realtime-api library, which has the extensions pre-compiled in:
    ExtensionRegistry registry = ExtensionRegistry.newInstance();
    registry.add(GtfsRealtimeNYCT.nyctFeedHeader);
    registry.add(GtfsRealtimeNYCT.nyctStopTimeUpdate);
    registry.add(GtfsRealtimeNYCT.nyctTripDescriptor);

   GtfsRealtime.FeedMessage feed = GtfsRealtime.FeedMessage.parseFrom(url.openStream(), registry);

This gives a result like:
trip {
  trip_id: "B20170217WKD_132800B..S"
  start_date: "2017-02-17 22:08:00"
  route_id: "B"
  [transit_realtime.nyct_trip_descriptor] {
    train_id: "1B 2208 145/BBC"
    is_assigned: true
    direction: SOUTH
  }
}
stop_time_update {
  arrival {
    time: 1487390920
  }
  departure {
    time: 1487390920
  }
  stop_id: "D39"
  schedule_relationship: SCHEDULED
  [transit_realtime.nyct_stop_time_update] {
    scheduled_track: "A3"
    actual_track: "A3"
  }
}
stop_time_update {
  arrival {
    time: 1487391130
  }
  departure {
    time: 1487391130
  }
  stop_id: "D40"
  schedule_relationship: SCHEDULED
  [transit_realtime.nyct_stop_time_update] {
    scheduled_track: "A3"
    actual_track: "A3"
  }
}