text:
Q: Why do Chinese characters in JSON cause "bad control character" error with JSON.parse? I have a standard HTML5-type client/server set up. The server side is all Java, and the client side is JavaScript. Using ajax I send queries and receive replies. Up to now, I've had no problems with JSON.parse(data). However, I have a new user who entered her last name using Chinese characters. This is causing a "JSON.parse: bad control character in string literal" error on the client side.
The server builds a reply as follows (exception handling omitted):
JSONObject jsono = new JSONObject();
jsono.put("last_name", last_name);
jsono.put("first-name", first_name);
String response = jsono.toString();

The client receives something like:
{"last_name":"Smith","first_name":"Bob"}

The reply is displayed on a web page which is set to  <meta charset="utf-8">:
var theResult = JSON.parse(data);
$('#first_name').html(theResult.first_name);

This works just fine. However, for the Chinese user, the client receives
{"last_name":"唐","first_name":"Bob"}

and this causes the json.parse error.
I've now started looking at other characters. For example, Andrés does not cause an error, but also does not display properly. It looks like Andr�s.
So, I'm clearly missing something. Could someone enlighten me where the problem lies (e.g., is it server side? client side? JavaScript? jquery? html?) and how to solve it?

A: The most useful libraries in Java I have used are Gson API and JSONObject and both can handle this issue, then if you this your problem is probably solved. just be careful all the utf-8 related params here are really important:
JSONObject jsono = new JSONObject();
jsono.put("last_name", "唐");
jsono.put("first-name", firstName);
String myjsonString = jsono.toString();

//write your output
DataOutputStream out = new DataOutputStream(new FileOutputStream("myjson.txt"));
out.write(myjsonString.getBytes("utf-8"),0, myjsonString.getBytes("UTF-8").length);


text:
Q: Oracle 11g r2: strange behavior on index I have the query:
    SELECT count(*)
FROM
(
SELECT
 TBELENCO.DATA_PROC, TBELENCO.POD, TBELENCO.DESCRIZIONE, TBELENCO.ERROR, TBELENCO.STATO,
 TBELENCO.SEZIONE, TBELENCO.NOME_FILE, TBELENCO.ID_CARICAMENTO, TBELENCO.ESITO_OPERAZIONE,
 TBELENCO.DES_TIPO_MISURA,
 --TBELENCO.RAGIONE_SOCIALE,
 --ROW_NUMBER() OVER (ORDER BY TBELENCO.DATA_PROC DESC) R
 ROWNUM R
FROM(
 SELECT
  LOG.DATA_PROC, LOG.POD, LOG.DESCRIZIONE, LOG.ERROR, LOG.STATO,
  LOG.SEZIONE, LOG.NOME_FILE, LOG.ID_CARICAMENTO, LOG.ESITO_OPERAZIONE, TM.DES_TIPO_MISURA
  --,C.RAGIONE_SOCIALE
  --ROW_NUMBER() OVER (ORDER BY LOG.DATA_PROC DESC) R
 FROM
  MS042_LOADING_LOGS LOG JOIN MS116_MEASURE_TYPES TM ON
   TM.ID_TIPO_MISURA=LOG.SEZIONE
--  LEFT JOIN(
--   SELECT CUST.RAGIONE_SOCIALE,STR.POD,RSC.DATA_DA, RSC.DATA_A
--   FROM
--    MS038_METERS STR JOIN MS036_REL_SITES_CUSTOMERS RSC ON
--     STR.ID_SITO=RSC.ID_SITO
--    JOIN MS030_CUSTOMERS CUST ON
--     CUST.ID_CLIENTE=RSC.ID_CLIENTE
--  ) C ON
--  C.POD=LOG.POD
  --AND LOG.DATA_PROC BETWEEN C.DATA_DA AND C.DATA_A
  WHERE
   1=1
   --AND LOG.DATA_PROC>=TRUNC(SYSDATE)
   AND LOG.DATA_PROC>=TRUNC(SYSDATE)-3
   --TO_DATE('01/11/2014', 'DD/MM/YYYY')
) TBELENCO
)
WHERE
 R BETWEEN 1 AND 200;

If I execute the query with AND LOG.DATA_PROC>=TRUNC(SYSDATE)-3, Oracle uses the index on the data_proc field of the MS042_LOADING_LOGS (LOG) table, if I use, instead, AND LOG.DATA_PROC>=TRUNC(SYSDATE)-4 or -5, or -6, etc, it uses a table access full. Why this behavior?
I also execute a :
ALTER INDEX MS042_DATA_PROC_IDX REBUILD;

but with no changes.
Thank,
Igor
--***********************************************************
SELECT count(*)
FROM
(
SELECT
 TBELENCO.DATA_PROC, TBELENCO.POD, TBELENCO.DESCRIZIONE, TBELENCO.ERROR, TBELENCO.STATO,
 TBELENCO.SEZIONE, TBELENCO.NOME_FILE, TBELENCO.ID_CARICAMENTO, TBELENCO.ESITO_OPERAZIONE,
 TBELENCO.DES_TIPO_MISURA,
 ROWNUM R
FROM(
 SELECT
  LOG.DATA_PROC, LOG.POD, LOG.DESCRIZIONE, LOG.ERROR, LOG.STATO,
  LOG.SEZIONE, LOG.NOME_FILE, LOG.ID_CARICAMENTO, LOG.ESITO_OPERAZIONE, TM.DES_TIPO_MISURA
 FROM
  MS042_LOADING_LOGS LOG JOIN MS116_MEASURE_TYPES TM ON
   TM.ID_TIPO_MISURA=LOG.SEZIONE
  WHERE
   1=1
   AND LOG.DATA_PROC>=TRUNC(SYSDATE)-1
) TBELENCO
)
WHERE
 R BETWEEN 1 AND 200;

Plan hash value: 2191058229

-------------------------------------------------------------------------------------------------------
| Id  | Operation                       | Name                | Rows  | Bytes | Cost (%CPU)| Time     |
-------------------------------------------------------------------------------------------------------
|   0 | SELECT STATEMENT                |                     |     1 |    13 | 30866   (2)| 00:06:11 |
|   1 |  SORT AGGREGATE                 |                     |     1 |    13 |            |          |
|*  2 |   VIEW                          |                     | 94236 |  1196K| 30866   (2)| 00:06:11 |
|   3 |    COUNT                        |                     |       |       |            |          |
|*  4 |     HASH JOIN                   |                     | 94236 |  1104K| 30866   (2)| 00:06:11 |
|   5 |      INDEX FULL SCAN            | P087_TIPI_MISURE_PK |    15 |    30 |     1   (0)| 00:00:01 |
|   6 |      TABLE ACCESS BY INDEX ROWID| MS042_LOADING_LOGS  | 94236 |   920K| 30864   (2)| 00:06:11 |
|*  7 |       INDEX RANGE SCAN          | MS042_DATA_PROC_IDX | 94236 |       | 25742   (2)| 00:05:09 |
-------------------------------------------------------------------------------------------------------

Predicate Information (identified by operation id):
---------------------------------------------------

   2 - filter("R"<=200 AND "R">=1)
   4 - access("TM"."ID_TIPO_MISURA"="LOG"."SEZIONE")
   7 - access(SYS_OP_DESCEND("DATA_PROC")<=SYS_OP_DESCEND(TRUNC(SYSDATE@!)-1))
       filter(SYS_OP_UNDESCEND(SYS_OP_DESCEND("DATA_PROC"))>=TRUNC(SYSDATE@!)-1)

Plan hash value: 69930686

---------------------------------------------------------------------------------------------
| Id  | Operation             | Name                | Rows  | Bytes | Cost (%CPU)| Time     |
---------------------------------------------------------------------------------------------
|   0 | SELECT STATEMENT      |                     |     1 |    13 | 95921   (1)| 00:19:12 |
|   1 |  SORT AGGREGATE       |                     |     1 |    13 |            |          |
|*  2 |   VIEW                |                     |  1467K|    18M| 95921   (1)| 00:19:12 |
|   3 |    COUNT              |                     |       |       |            |          |
|*  4 |     HASH JOIN         |                     |  1467K|    16M| 95921   (1)| 00:19:12 |
|   5 |      INDEX FULL SCAN  | P087_TIPI_MISURE_PK |    15 |    30 |     1   (0)| 00:00:01 |
|*  6 |      TABLE ACCESS FULL| MS042_LOADING_LOGS  |  1467K|    13M| 95912   (1)| 00:19:11 |
---------------------------------------------------------------------------------------------

Predicate Information (identified by operation id):
---------------------------------------------------

   2 - filter("R"<=200 AND "R">=1)
   4 - access("TM"."ID_TIPO_MISURA"="LOG"."SEZIONE")
   6 - filter("LOG"."DATA_PROC">=TRUNC(SYSDATE@!)-4)

A: The larger the fraction of rows that will be returned, the more efficient a table scan is and the less efficient it is to use an index.  Apparently, Oracle expects that inflection point to come when the query returns more than 3 days of data.  If that is inaccurate, I would expect that the statistics on your table or indexes are inaccurate.

redpajama_set_name: RedPajamaStackExchange


text:
Q: Impersonating list of users with Google Service Account According to the docs, Google Apps domain administrators can grant service accounts domain-wide authority to access user data on behalf of users in the domain. My understating is this gives service account authority to access data for all users inside the domain. Is there a way to restrict which users service account has access to?
For example, an application that uses Google Calendar API to view events from the calendars of specific list of users in a Google Apps domain.
Can google apps administrator authorize application for access to some but not all users?
Thanks

A: The answer was to publish an app in Google Apps Marketplace. An app can be turned ON for everyone or some specific organization unit. See Turn a Marketplace app on or off for users. Organization Unit is how you can control who in organization has access to your app.

A: If you're an administrator, yes. You can control who uses any particular Google service from their account. Just turn the service on or off for those people in your Google Admin Console. When users sign in to their account, they see only those services that are turned on for them.
To delegate domain-wide authority to a service account, first enable domain-wide delegation for an existing service account in the Service accounts section of the Developers Console Permissions page or create a new service account with domain-wide delegation enabled. Your application has the authority to make API calls as users in your domain(to impersonate users).
Here's a useful material for Delegating domain-wide authority to the service account:
https://developers.google.com/identity/protocols/OAuth2ServiceAccount


text:
Q: Get & diplay from database error I am trying to write a simple stream, streaming everything from a mysql field. But my current script shows absolutely nothing.. no errors, nothing. Here it is:
include("user_sytem_scripts/connect.php");

   $sql_updates = mysql_query("SELECT item_id, username, item_content, update_time FROM updates ORDER BY update_time DESC LIMIT 30")  or die("Query failed with error: ".mysql_error());

while($row = mysql_fetch_array($sql_updates)){

    $update_id = $row["item_id"];
    $update_username = $row["username"];
    $item_content = $row["item_content"];
    $update_time = $row["update_time"];

$updatestream = '

                    ' . $update_time . ' ' . $username . ' via

                     ' . $item_content . '

'; }

Then down in the HTML I use: <?php echo $updatestream ?>

But as i said i get absolutly nothing.. Can anyone spot any errors or general mistakes that would cause this? Thanks :D

A: I would check the following:

*

*Does the query run when you run it manually (in phpMyAdmin for example)?

*Do you get any output at all? If not, it seems that your while look is getting 0 results from the DB.

You should also change: $updatestream = ' to $updatestream .= so that you append text, in the current while loop you'll overwrite the last $updatestream value.

A: First you need to initialize $updatestream,($updatestream = ""), before the while loop, then inside the loop you change it to $updatestream .= "the string". You might want to echo your result at the end, sometimes we forget the little stuff.
echo $updatestream;


text:
Q: Any Yahoo YUI validation framework that I can implement in asp.net MVC? Has anyone seen a Yahoo YUI validation framework that I could implement into asp.net MVC?  I've seen a jQuery one but I want to work wit YUI.

A: It's not quite as spiffy (IMO) as jQuery, but here's a yazaar validation framework.

A: It's worth noting that Microsoft have announced they'll be shipping JQuery with Visual Studio and there will be more integration with the MVC framework. This may or may not affect your decision to use YUI.
More details here:
http://weblogs.asp.net/scottgu/archive/2008/09/28/jquery-and-microsoft.aspx

A: You might try the yui-form-validator on Google code...
It looks promising for what you are looking for.

A: I recently found indputEx. Hope it helps.


text:
Q: Can't add maven module in IntelliJ IDEA I'm using IntelliJ IDEA 2016.2.1 (Latest version) and I just can't create a new maven module to my project. I have a parent project packaged as pom, as I'm using it just to handle some dependencies and settings across all child modules. In order to create new child modules, all I had to do till now was right click it's name in the project panel, click "New" -> "Module" -> "Maven" and then just complete the name, artifactId, and version fields and hit Finish at the end. The thin is, it does work, but it doesn't show up as a maven module. It looks just like a normal folder in my project view.
I even know why: Normally, maven modules should contain the "isMavenModule" tag marked as true inside the module's iml file, but my iml file doesn't even have that setting:
<module type="JAVA_MODULE" version="4">

That's all it has, while my other modules look like this:
<module org.jetbrains.idea.maven.project.MavenProjectsManager.isMavenModule="true" type="JAVA_MODULE" version="4">

What makes it all even stranger is that I can easily create modules if they have a different name. I tried creating a test module called, well, "test" which I used the exact same way of creating as the other module, with the only difference being it's name. It does work as expected and I can't really see why this happens. While I can technically bypass this issue by manually adding the isMavenModule tag to my module's iml file, I'm intrigued by what is actually causing this.

A: Well, thank you for the help guys, but apparently the issue was much simpler than I though. It seems that at some point I created a module in that project with the exact same name, which I later deleted (I don't remember why). The issue was that I just removed the module from the parent pom and simply deleted the folder that contained the module, but I didn't remove the configuration options of the project that intellij kept using (by that I mean those xml files in the IdeaProjects//.idea folder that contain various info for the editor). So all I had to do was manually open those files and 'CTRL+F' through them to remove all entries that referred in some way to the module '1_8_R3'. This seems to have solved the issue, but the good thing is that I finally learned how to properly delete a module...
https://www.jetbrains.com/help/idea/2016.2/removing-modules-from-a-project.html


text:
Q: Selector.select(timeout) returns 0 before timeout According to Javadoc,

It returns only after at least one channel is selected, this selector's wakeup method is invoked, the current thread is interrupted, or the given timeout period expires, whichever comes first.

But occasionally it returns without any of these 4 cases:

*

*at least one channel is selected: it returns 0

*wakeup method is invoked: wakeup is not called

*the current thread is interrupted: Thread.interrupted() returns false

*given timeout period expires: not expired according to logs

UPDATED 2016-03-15
In my source at line 392 and line 402 I added some logs:
https://github.com/xqbase/tuna/blob/debug/core/src/main/java/com/xqbase/tuna/ConnectorImpl.java
public boolean doEvents(long timeout) {
    Log.v("Before Select: " + timeout);
    int keySize;
    try {
        keySize = timeout == 0 ? selector.selectNow() :
                timeout < 0 ? selector.select() : selector.select(timeout);
    } catch (IOException e) {
        throw new RuntimeException(e);
    }
    Set<SelectionKey> selectedKeys = selector.selectedKeys();
    if (keySize == 0) {
        Log.v("After Select(0): selectedKeys=" + selectedKeys.size() + ", " +
                "interrupt=" + Thread.interrupted());
        invokeQueue();
        return false;
    }

    for (SelectionKey key : selectedKeys) {
        ...

Here is the log:
...
2016-03-15 23:07:49.695 com.xqbase.tuna.ConnectorImpl doEvents
FINE: Before Select: 8120
2016-03-15 23:07:49.696 com.xqbase.tuna.ConnectorImpl doEvents
FINE: After Select(0): selectedKeys=0, interrupt=false
2016-03-15 23:07:49.696 com.xqbase.tuna.ConnectorImpl doEvents
FINE: Before Select: 8119
2016-03-15 23:07:49.696 com.xqbase.tuna.ConnectorImpl doEvents
FINE: After Select(0): selectedKeys=0, interrupt=false
2016-03-15 23:07:49.700 com.xqbase.tuna.ConnectorImpl doEvents
FINE: Before Select: 8115
2016-03-15 23:07:49.701 com.xqbase.tuna.ConnectorImpl doEvents
FINE: After Select(0): selectedKeys=0, interrupt=false
2016-03-15 23:07:49.701 com.xqbase.tuna.ConnectorImpl doEvents
FINE: Before Select: 8114
2016-03-15 23:07:49.702 com.xqbase.tuna.ConnectorImpl doEvents
FINE: After Select(0): selectedKeys=0, interrupt=false
...

That is very strange: no selected keys, no interruption, no timeout and no wakeup, but it returned.
Is there a bug in Java? My Java version is 1.8.0_51-b16 (64-Bit Server VM), and run on a CentOS 6.5 x64 linode.

A: This may really be a bug in JDK. It seems that Netty and Mina also encounter such a problem and they rebuild the selector as a workaround.
See latest Netty code https://github.com/netty/netty/blob/4.1/transport/src/main/java/io/netty/channel/nio/NioEventLoop.java L641-681:
            if (selectedKeys != 0 || oldWakenUp || wakenUp.get() || hasTasks() || hasScheduledTasks()) {
                // - Selected something,
                // - waken up by user, or
                // - the task queue has a pending task.
                // - a scheduled task is ready for processing
                break;
            }
            ...
            } else if (SELECTOR_AUTO_REBUILD_THRESHOLD > 0 &&
                    selectCnt >= SELECTOR_AUTO_REBUILD_THRESHOLD) {
                // The selector returned prematurely many times in a row.
                // Rebuild the selector to work around the problem.
                logger.warn(
                        "Selector.select() returned prematurely {} times in a row; rebuilding selector.",
                        selectCnt);

                rebuildSelector();
                selector = this.selector;

                // Select again to populate selectedKeys.
                selector.selectNow();
                selectCnt = 1;
                break;
            }

See Mina 2.0 code https://github.com/apache/mina/blob/2.0/mina-core/src/main/java/org/apache/mina/core/polling/AbstractPollingIoProcessor.java L1070-1092:
                if (!wakeupCalled.getAndSet(false) && (selected == 0) && (delta < 100)) {
                    // Last chance : the select() may have been
                    // interrupted because we have had an closed channel.
                    if (isBrokenConnection()) {
                        LOG.warn("Broken connection");
                    } else {
                        LOG.warn("Create a new selector. Selected is 0, delta = " + (t1 - t0));
                        // Ok, we are hit by the nasty epoll
                        // spinning.
                        // Basically, there is a race condition
                        // which causes a closing file descriptor not to be
                        // considered as available as a selected channel,
                        // but
                        // it stopped the select. The next time we will
                        // call select(), it will exit immediately for the
                        // same
                        // reason, and do so forever, consuming 100%
                        // CPU.
                        // We have to destroy the selector, and
                        // register all the socket on a new one.
                        registerNewSelector();
                    }
                }

Therefore, registering a new selector may be the best practice if select() returns an unexpected zero.

A: The Javadoc is pretty clear.

During each selection operation, keys may be added to and removed from a selector's selected-key set ... . Selection is performed by the select(), select(long), and selectNow() methods, and involves three steps:

*

*...

*The underlying operating system is queried for an update as to the readiness of each remaining channel to perform any of the operations identified by its key's interest set as of the moment that the selection operation began. For a channel that is ready for at least one such operation, one of the following two actions is performed:

*

*If the channel's key is not already in the selected-key set then it is added to that set and its ready-operation set is modified to identify exactly those operations for which the channel is now reported to be ready. Any readiness information previously recorded in the ready set is discarded.

*Otherwise the channel's key is already in the selected-key set, so its ready-operation set is modified to identify any new operations for which the channel is reported to be ready. Any readiness information previously recorded in the ready set is preserved; in other words, the ready set returned by the underlying system is bitwise-disjoined into the key's current ready set.

What is happening is that on the select that returns zero, the selection key wass already in the selected-key set, so no change in the number of ready keys occurred.
Note also in the section for the select(int timeout) method (my emphasis):

Returns:

*

*The number of keys, possibly zero, whose ready-operation sets were updated


text:
Q: Programmatically add servlet to embedded grizzly I am trying to integrate Swagger into my Java SE Application which is running an embedded grizzly server.
To acchieve this i was following this tutorial and I'am shure that I'm 90% there.
I want to configure swagger using this servlet:
@WebServlet(name = "SwaggerJaxrsConfig", loadOnStartup = 1)
public class SwaggerJaxrsConfig extends HttpServlet {

    @Override
    public void init(ServletConfig servletConfig) {
        try {
            super.init(servletConfig);
            System.out.println("Swagger init");
            SwaggerConfig swaggerConfig = new SwaggerConfig();
            ConfigFactory.setConfig(swaggerConfig);
            swaggerConfig.setBasePath("http://localhost:8082/swagger4javaee-web/rest");
            swaggerConfig.setApiVersion("1.0.0");
            ScannerFactory.setScanner(new DefaultJaxrsScanner());
            ClassReaders.setReader(new DefaultJaxrsApiReader());
        } catch (ServletException e) {
            System.out.println(e.getMessage());
        }
    }
}

Since I'am using an embedded server, the @WebServlet annotation does not add the servlet to the grizzly server.
Does anybody know how i can add the servlet to the grizzly server programmatically?
PS I'am using this dependency
<dependency>
    <groupId>org.glassfish.jersey.containers</groupId>
    <artifactId>jersey-container-grizzly2-servlet</artifactId>
    <version>2.9</version>
</dependency>

A: The following works for me.  I hope it works for you too.
Main.java
import com.wordnik.swagger.jaxrs.config.BeanConfig;
import java.io.IOException;
import java.net.URI;
import java.util.HashMap;
import java.util.Map;
import java.util.logging.Level;
import java.util.logging.Logger;
import javax.ws.rs.ext.ContextResolver;
import org.glassfish.grizzly.http.server.HttpServer;
import org.glassfish.jersey.grizzly2.httpserver.GrizzlyHttpServerFactory;
import org.glassfish.jersey.moxy.json.MoxyJsonConfig;
import org.glassfish.jersey.server.ResourceConfig;

public class Main {

    private static final URI BASE_URI
            = URI.create("http://localhost:8080/api/");

    public static void main(String[] args) {
        try {
            BeanConfig beanConfig = new BeanConfig();
            beanConfig.setVersion("1.0");
            beanConfig.setScan(true);
            beanConfig.setResourcePackage(
                    HelloResource.class.getPackage().getName());
            beanConfig.setBasePath(BASE_URI.toString());
            beanConfig.setDescription("Hello resources");
            beanConfig.setTitle("Hello API");

            final HttpServer server
                    = GrizzlyHttpServerFactory.createHttpServer(
                            BASE_URI, createApp());

            System.out.println(
                    String.format(
                            "Application started.%nHit enter to stop it..."));
            System.in.read();
            server.shutdownNow();
            System.exit(0);
        } catch (IOException ex) {
            Logger.getLogger(Main.class.getName()).log(Level.SEVERE, null, ex);
        }
    }

    public static ResourceConfig createApp() {
        return new ResourceConfig().
                packages(HelloResource.class.getPackage().getName(),
                        "com.wordnik.swagger.jaxrs.listing").
                register(createMoxyJsonResolver());
    }

    public static ContextResolver<MoxyJsonConfig> createMoxyJsonResolver() {
        final MoxyJsonConfig moxyJsonConfig = new MoxyJsonConfig();
        Map<String, String> namespacePrefixMapper
                = new HashMap<String, String>(1);
        namespacePrefixMapper.put(
                "http://www.w3.org/2001/XMLSchema-instance", "xsi");
        moxyJsonConfig.setNamespacePrefixMapper(namespacePrefixMapper)
                .setNamespaceSeparator(':');
        return moxyJsonConfig.resolver();
    }

}

HelloResource.java
import com.wordnik.swagger.annotations.Api;
import com.wordnik.swagger.annotations.ApiOperation;
import com.wordnik.swagger.annotations.ApiResponse;
import com.wordnik.swagger.annotations.ApiResponses;
import javax.json.Json;
import javax.json.JsonObject;
import javax.ws.rs.GET;
import javax.ws.rs.Path;
import javax.ws.rs.Produces;
import javax.ws.rs.core.MediaType;
import javax.ws.rs.core.Response;

@Path("hello")
@Api(value = "/hello", description = "Say Hello!")
public class HelloResource {

    @GET
    @Produces(MediaType.APPLICATION_JSON)
    @ApiOperation(value = "Say Hello World",
            notes = "Anything Else?")
    @ApiResponses(value = {
        @ApiResponse(code = 200, message = "OK"),
        @ApiResponse(code = 500, message = "Something wrong in Server")})
    public Response sayHello() {
        JsonObject value = Json.createObjectBuilder()
                .add("firstName", "Jeremy")
                .add("lastName", "Chung")
                .add("message", "Hello World!")
                .build();
        return Response.status(200).entity(value).build();
    }
}

Maven pom.xml contains the following dependencies.
<dependency>
    <groupId>org.glassfish.jersey.containers</groupId>
    <artifactId>jersey-container-grizzly2-servlet</artifactId>
    <version>2.9</version>
</dependency>
<dependency>
    <groupId>com.wordnik</groupId>
    <artifactId>swagger-jaxrs_2.10</artifactId>
    <version>1.3.1</version>
</dependency>
<dependency>
    <groupId>com.wordnik</groupId>
    <artifactId>swagger-jersey-jaxrs_2.10</artifactId>
    <version>1.3.0</version>
</dependency>
<dependency>
    <groupId>org.glassfish</groupId>
    <artifactId>javax.json</artifactId>
    <version>1.0.4</version>
</dependency>
<dependency>
    <groupId>org.glassfish.jersey.media</groupId>
    <artifactId>jersey-media-moxy</artifactId>
    <version>2.10.1</version>
</dependency>
<dependency>
    <groupId>org.glassfish.jersey.media</groupId>
    <artifactId>jersey-media-json-processing</artifactId>
    <version>2.10</version>
</dependency>
<dependency>
    <groupId>com.sun.jersey</groupId>
    <artifactId>jersey-json</artifactId>
    <version>1.17.1</version>
</dependency>

Calling http://localhost:8080/api/hello results in:

{"firstName":"Jeremy","lastName":"Chung","message":"Hello World!"}

Calling http://localhost:8080/api/api-docs results in:

{"apiVersion":"1.0","swaggerVersion":"1.2","apis":[{"path":"/hello","description":"Say
  Hello!"}]}

Calling http://localhost:8080/api/api-docs/hello results in:
{"apiVersion":"1.0","swaggerVersion":"1.2","basePath":"http://localhost:8080/api/","resourcePath":"/hello","apis":[{"path":"/hello","operations":[{"method":"GET","summary":"Say Hello World","notes":"Anything Else?","type":"void","nickname":"sayHello","produces":["application/json"],"parameters":[],"responseMessages":[{"code":200,"message":"OK"},{"code":500,"message":"Something wrong in Server"}]}]}]}


text:
Q: play flv and mkv format video in web page without downloading I'm developing exam portal site, where faculty upload video tutorials for students. I want to play video when the student click the tutorial without downloading.video include (.flv,.mkv,.mp4) formats
I referred internet but not able to understand please any one help with simple example.
I'm using php and mysql

                Department Name
                Video Tutorials
                Action

        <?php
        $query=mysql_query("select * from video_uploads order by id desc");
        while($row=mysql_fetch_array($query)){
            $name=$row['file'];
            $dept=$row['dept_name'];
        ?>

         <?php echo $dept;?>

            <iframe width="460" height="215" src="staff/video/<?php echo $name ;?>" allowfullscreen="">

        <?php }?>

code for upload video is here
    if(isset($_POST['submit'])){
 $dept_name=$_POST['dept'];
  $name=$_FILES['file']['name'];
  $size=$_FILES['file']['size'];
  $type=$_FILES['file']['type'];
  $temp=$_FILES['file']['tmp_name'];

  move_uploaded_file($temp,"video/".$name);
  $sql="INSERT INTO video_uploads(dept_name,file,type,size) VALUES('$dept_name','$name','$type','$size')";
    if(executeQuery($sql))

    {
    echo "      ";

    }
    else
    {
    ?>

    <?php
    }
   }
   ?>

A:

                Department Name
                Video Tutorials
                Action

        <?php
        $query=mysql_query("select * from video_uploads order by id desc");
        while($row=mysql_fetch_array($query)){
            $name=$row['file'];
            $dept=$row['dept_name'];
        ?>

         <?php echo $dept;?>

            <video width="460" height="215" >
                 <source src="staff/video/<?php echo $name ;?>" type="videp/mp4" >
            </video>

        <?php }?>

If you want to play flv or mkv video then just replace the "mp4" to "mkv" or any video format you want it.


text:
Q: Can I have a default type value for an associated type family? Consider this code:
{-# LANGUAGE TypeFamilies #-}
{-# LANGUAGE TypeFamilyDependencies #-}

module Study where

class C a where
    type T a = r | r -> a
    pred :: T a -> Bool
    pred _ = True

I want to have a more meaningful default definition of pred, like this:
class C' a where
    ...
    pred' = not . null

(I imagine a default T' a to be = [a].)
Is there a way?

A: You need a default signature.
Prelude> :{
Prelude| class C a where
Prelude|   type T a = r | r -> a
Prelude|   pred :: T a -> Bool
Prelude|   default pred :: (T a ~ [a]) => T a -> Bool
Prelude|   pred = not . null
Prelude| :}

(Thanks to @luqui.) Note that, if you want to be able to write an empty instance C Integer, you should also provide a default for T by adding the line type T a = [a].


text:
Q: Thread pooling configurability in Finagle Let's assume I've got two Finagle services, as per below
val service1: Service[http.Request, http.Response] = ???
val service2: Service[http.Request, http.Response] = ???

and I run them both against different ports
val server1 = Http.serve(":9090", service1)
val server2 = Http.serve(":8080", service2)

*

*would requests coming to these 2 servers be handled by different Netty worker/thread pools?

*if not, is there a way to configure Finagle so they would be handled by different Netty worker/thread pools?

A: If you are using netty 3, you can set up execution handlers in a pipeline.
http://netty.io/3.5/api/org/jboss/netty/handler/execution/ExecutionHandler.html
Then transform the channel pipeline into a Finagle Codec, which offers builder  methods to create a stack client or stack server, and just set the netty3 threadpool size to 0, finagle has been moving towards, hiding netty from it's users which can be a pain when you're trying to get fine grained control.
Hopefully that works, since I see no reason to do that when you can just run the servers in separate jvm instances.


text:
Q: how to call a simple javascript method in cefsharp resource handler -OnBeforeResourceLoad- This is where I want to block some content to be displayed when the page is loaded.
This is the function simply returns true or false
   _myfilters.blocking.matches('" + request.Url + "', '" + elType + "',  document.location.href.replace(/#.*$/, ''));

I want to decide CefReturnValue according to this javascript method above.
How can I do it?
    CefReturnValue IRequestHandler.OnBeforeResourceLoad(IWebBrowser browserControl, IBrowser browser, IFrame frame, IRequest request, IRequestCallback callback)
        {
bool result = ... this is coming from javascript, how ?

if (result )
CefReturnValue.Cancel;
else
CefReturnValue.Continue;

}

//My approach
   CefReturnValue IRequestHandler.OnBeforeResourceLoad(IWebBrowser browserControl, IBrowser browser, IFrame frame, IRequest request, IRequestCallback callback)
    {

        string elType = "object";

        CefReturnValue cc = CefReturnValue.Continue;

        //  Task<CefSharp.JavascriptResponse> response = BrowserView.browser.EvaluateScriptAsync(" function() { return _myfilters.blocking.matches('" + request.Url + "', '" + elType + "',  document.location.href.replace(/#.*$/, '')); } ");
        Task<CefSharp.JavascriptResponse> response = BrowserView.browser.EvaluateScriptAsync("onBeforeRequestHandler({type:'" + elType + "' , url:'" + request.Url + "' , frameDomain:document.location.href.replace(/#.*$/, '')});");
        Func<Task<CefSharp.JavascriptResponse>> func = () =>
            {

                response.Wait();
                return response;
            };

        func.BeginInvoke((ar) =>
        {
            var result = func.EndInvoke(ar);
            if (result.Result.Result != null && bool.Parse(result.Result.Result.ToString()))
            {
                cc = CefReturnValue.Cancel;
            }
        },
        null);

        return cc;
    }


text:
Q: Convert base64 encoded integer to long I am returning some XML like below in SQL Server 2016. If I do the CONVERT option I get this error below.  I don't want that error and would like to return the current type for this odd text AAAAAAF+nuc=.  Am I able to convert this in .NET to a long?

Explicit conversion from data type timestamp to date is not allowed.

XML
<Assets>
  <Asset>
    <Type>2</Type>
    <FileName>179605.png</FileName>
    <Id>179605</Id>
    <Version>AAAAAAF+nuc=</Version>
    <Version1>25075431</Version1>
  </Asset>
</Assets>

SQL
SELECT
    ga.[Type], ga.[FileName], ga.Id, ga.[Version],
    CONVERT(BIGINT, ga.[Version]) AS [Version1]
FROM
    Test ga
WHERE
    ga.id = 179605
FOR XML PATH('Asset'), ROOT('Assets')

Example Try
[TestMethod]
        public void Convert()
        {
            byte[] bytes = System.Convert.FromBase64String("AAAAAAF+nuc=");
            var longValue = BitConverter.ToInt64(bytes, 0); // -1756828261867847680
        }

A: Well what do you know, got this exact answer from SQL Server using this code.  If there is a faster way please comment.
[TestMethod]
        public void Convert()
        {
            byte[] bytes = System.Convert.FromBase64String("AAAAAAF+nuc=");
            Array.Reverse(bytes, 0, bytes.Length);
            var longValue =  BitConverter.ToInt64(bytes, 0); // 25075431
        }


text:
Q: The meteor/meteorite fell over there Let's not get too pedantic on the exact difference. What I'll stick with is this:

*

*If it is still in the air, falling, it's a meteor.

*If it has hit the ground, it's a meteorite.

In this case, which of the following is correct?

*

*The meteor fell over there.

*The meteorite fell over there.

This sets up a scenario where the object is now a meteorite, but was previously a meteor. The action we give to it, i.e., falling, corresponds to its state as a meteor, but it is a meteorite now; it is no longer a meteor.
If we're talking about an action of something that changes state, do we use the current state, or the state it was in at the time it was performing the action? Could it be that the verb form we pick affects this, i.e., that using "was falling" would cause "meteor" to be the correct choice, as falling in the present tense is something only a meteor can do, and that using "fell" would cause "meteorite" to be the correct choice, as only a meteorite can be done falling, mandating a past tense form?

A: "The meteorite fell over there" is correct because you're talking about a thing present-tense thing.
Another example:

*

*The man grew up in the countryside.

He's a man now, even though he was a boy when growing up.
However, if you're talking about something in the past-tense, i.e. describing the night it fell, you would use meteor:

*

*The sky was dark and the moon was bright as the meteor fell to earth.

And:

*

*He used to go fishing when he was a boy growing up in the country.

A: Meteorite is correct.
Now if someone can explain the origin of the astronomically nonsensical phrase "meteoric rise"…

A: A Greek is responsible to give the best explanation on this topic!
First things first, I'm Greek and the word "meteor" & "meteorite" are Greek words!

*

*"Meteor" comes from the Greek word "Μετέωρος" and denotes a state! "Μετέωρος" is someone ("Μετέωρο" is something) that is hanging in the air without changing its height relative to a reference surface. It may be either motionless OR not (i.e a pendulum that is hanging - it moves but it does not change its height). It also emphasizes the great possibility for something to start falling into the reference surface. Let's say it could be a "pendulum" that is considered a "meteor" because if we cut the rope it will start falling into a reference surface (for example a table).

*"Meteorite" , on the other hand, comes from the Greek word "Μετεωρίτης" and denotes something that is falling either it was a "meteor" before or not (i.e it was thrown by someone from outter space towards the earth for example)! Thus, "Μετεωρίτης" is someone or something that is falling into a reference surface (changing its height relative to a given reference surface).

Both a "Meteor" and a "Meteorite" words are meaningless without their reference surface. That is, we say that a "meteorite" for the earth is something that is falling into the earth's surface. The earth is the reference surface. Otherwise it is MEANINGLESS to call something a "meteorite" that is travelling through space.
Thus if we cut the rope that holds the pendulum we can say that instantly the pendulum becomes a "meteorite" FOR THE TABLE. The table removes its ability to be called as "meteor" any more. It is "safe" the is no possibility to start falling again.
To get an even better understanding..assume that you could stabilize a ping-pong ball on a needle's edge. That is also considered a "meteor" because there is a great possibility to loose its stability and start falling towards the table (and become a "meteorite" for the table).

*

*"Meteoric rise" ("Μετεωρική ανύψωση" in Greek) it means that something moves or being move upwards relative to a reference surface that could possibly be stabilized at some final point so that it can be definitely called a "meteor".


text:
Q: Multiple query vs Single (multiple has many joins) Recently stumbled on this situation. Doing both queries might be "light" in my situation, I just want to know when it comes to big dataset on what is better. Better in overall (performance, speed, etc etc).
Currently I do single queries of 2 1:N (has-many) relationship and reduce/transform the data in the application.
It looks like this transformed/reduced:
[
  'field' => 'value',
  'hasMany-1' => [],
  'hasMany-2' => []
]

I'm actually somehow tempted to just do separate queries as it eliminates the pain of reducing it if I had more than 2 hasMany queries and is more quite readable but code currently works so I'll maybe just do it next time.
Is the compromise worth it? Again, in my situation it might be very "light" as I only have few rows (< 100) and structure is not complex as it is on early stage yet.
But asked in case I stumble upon this next time and when dataset grows larger.
** EDIT **
So the has-many relationship I'm talking about are: A customer has-many phones and pets.
My current query returns me this result (simplified):
customer_id | pet_name | phone
1           | john     | 1234
1           | john     | 5678
2           | jane     | 1357
2           | jane     | 2468
2           | joe      | 1357
2           | joe      | 2468

I think my query is fine. It seems logical for some rows to repeat because the other field has different value.

A: In general, you should issue a single query and let the optimizer do the work for you.  At the very least, this saves multiple round-trips to the database and query compilation.
There are cases where multiple queries can have better performance, but I think it is better to start with a single query.
You have a particular issue regarding joins along multiple many-to-many dimensions.  There is no need to do the joins "generally" and then "reduce" the results.  There are more efficient methods.
I would suggest that you ask another question.  Provide sample data, desired results, and an explanation of the logic you are attempting.  You may be able to learn a more efficient way to write a single query.

A: You did not describe your table structures so i assume few things.
If you want to have pets and phones as one row do:
select c.customer_id, c.name,
       array_to_string((array_agg(p.pet_name)),',')  pet_names
       array_to_string((array_agg(ph.phone)),',')  phones
  from customer c, pet p, phones ph
 where p.customer_id=1
   and p.customer_id=c.customer_id
   and ph.customer_id=c.customer_id
 group by c.customer_id, c.name

If you want to have row per pet_name with all possible phone numbers:
select c.customer_id, c.name,
       p.pet_name
       array_to_string((array_agg(ph.phone)),',')  phones
  from customer c, pet p, phones ph
 where p.customer_id=1
   and p.customer_id=c.customer_id
   and ph.customer_id=c.customer_id
 group by c.customer_id, c.name, p.pet_name

If we talk about performance it will be faster to do 2 queries to pets and phones separetly by customer_id. But until you have milions of rows it is not so important.
Of course you should have indexes on customer_id.


text:
Q: How can I Serialize/De-serialize a Boolean Value from FasterXML\Jackson as an Int? I'm writing a JSON Client for a Server that returns Boolean values as "0" and "1".  When I try to run my JSON Client I currently get the following Exception:
HttpMessageNotReadableException: Could not read JSON: Can not construct instance of java.lang.Boolean from String value '0': only "true" or "false" recognized

So how can I setup FasterXML\Jackson to correctly parse something like:
{
   "SomeServerType" : {
     "ID" : "12345",
     "ThisIsABoolean" : "0",
     "ThisIsABooleanToo" : "1"
   }
}

Sample Pojo's:
@JsonInclude(JsonInclude.Include.NON_NULL)
@JsonPropertyOrder({"someServerType"})
public class myPojo
{
   @JsonProperty("someServerType")
   SomeServerType someServerType;

   @JsonProperty("someServerType")
   public SomeServerType getSomeServerType() { return someServerType; }

   @JsonProperty("someServertype")
   public void setSomeServerType(SomeServerType type)
   { someServerType = type; }
}

@JsonInclude(JsonInclude.Include.NON_NULL)
@JsonPropertyOrder({"someServerType"})
public class SomeServerType
{
   @JsonProperty("ID")
   Integer ID;

   @JsonProperty("ThisIsABoolean")
   Boolean bool;

   @JsonProperty("ThisIsABooleanToo")
   Boolean boolToo;

   @JsonProperty("ID")
   public Integer getID() { return ID; }

   @JsonProperty("ID")
   public void setID(Integer id)
   { ID = id; }

   @JsonProperty("ThisIsABoolean")
   public Boolean getThisIsABoolean() { return bool; }

   @JsonProperty("ThisIsABoolean")
   public void setThisIsABoolean(Boolean b) { bool = b; }

   @JsonProperty("ThisIsABooleanToo")
   public Boolean getThisIsABooleanToo() { return boolToo; }

   @JsonProperty("ThisIsABooleanToo")
   public void setThisIsABooleanToo(Boolean b) { boolToo = b; }
}

Rest Client Line
Note 1: This is using Spring 3.2
Note 2: toJSONString() - is a helper method that uses Jackson to Serialize my Parameters Object
Note 3: The Exception happens on Reading IN the result object
DocInfoResponse result = restTemplate.getForObject(docInfoURI.toString()
                                  + "/?input={input}",
                                  DocInfoResponse.class,
                                  toJSONString(params));

A: Instead of custom deserializer, you could also simply have a setter like:
public void setThisIsABoolean(String str) {
  if ("0".equals(str)) {
    bool = false;
  } else {
    bool = true;
  }
}

since your method can claim different type than what you use internally.
And if you have to support both Boolean and String, you can indicate value is an Object, and check what you might get.
It should even be possible to have different type for getter method (Boolean) and setter (String or Object).

A: As Paulo Pedroso's answer mentioned and referenced, you will need to roll your own custom JsonSerializer and JsonDeserializer. Once created, you will need to add the @JsonSerialize and @JsonDeserialize annotations to your property; specifying the class to use for each.
I have provided a small (hopefully straightforward) example below. Neither the serializer nor deserializer implementations are super robust but this should get you started.
public static class SimplePojo {

    @JsonProperty
    @JsonSerialize(using=NumericBooleanSerializer.class)
    @JsonDeserialize(using=NumericBooleanDeserializer.class)
    Boolean bool;
}

public static class NumericBooleanSerializer extends JsonSerializer<Boolean> {

    @Override
    public void serialize(Boolean bool, JsonGenerator generator, SerializerProvider provider) throws IOException, JsonProcessingException {
        generator.writeString(bool ? "1" : "0");
    }
}

public static class NumericBooleanDeserializer extends JsonDeserializer<Boolean> {

    @Override
    public Boolean deserialize(JsonParser parser, DeserializationContext context) throws IOException, JsonProcessingException {
        return !"0".equals(parser.getText());
    }
}

@Test
public void readAndWrite() throws JsonParseException, JsonMappingException, IOException {
    ObjectMapper mapper = new ObjectMapper();

    // read it
    SimplePojo sp = mapper.readValue("{\"bool\":\"0\"}", SimplePojo.class);
    assertThat(sp.bool, is(false));

    // write it
    StringWriter writer = new StringWriter();
    mapper.writeValue(writer, sp);
    assertThat(writer.toString(), is("{\"bool\":\"0\"}"));
}


text:
Q: multi select not work in ng-repate I'm using ultraselect Jquery, I want to select multiple options but the one which  I did,doesn't work.May I know where is the issue?
Codes:
<script type="text/javascript">

    $(document).ready(function () {

        // Options displayed in comma-separated list
        $(".control_7").ultraselect({oneOrMoreSelected: '*'})

    });

</script>

<!-- Main content -->
<div  ng-repeat="salon in salons">  <!-- dir-paginate="salon in salons| itemsPerPage: 1"-->

    <select class="control_7" name="control_7[]" multiple >
        <option >Option 1</option>
        <option >Option 2</option>
        <option >Option 3</option>
        <option >Option 4</option>
        <option >Option 5</option>
        <option >Option 6</option>
        <option >Option 7</option>
    </select>
</div>


text:
Q: Write and Update record on Cassandra along with clustering columns I have a notification table and additional index
CREATE TABLE notification (
    postid double,
    userid double,
    type text,
    message text,
    hasread boolean,
    postdate timestamp,
    PRIMARY KEY (userid, postdate)
)  WITH  CLUSTERING ORDER BY (postdate DESC);

CREATE INDEX postid ON notification(postid);

Let's say I inserted several rows
select * from notification;

 userid | postdate                        | hasread | message                | postid | type
--------+---------------------------------+---------+------------------------+--------+---------
    104 | 2016-11-18 17:21:32.692000+0000 |   False | Let\'s do it together! |  70521 | newpost
    104 | 2016-11-18 17:21:26.511000+0000 |   False | Let\'s do it together! |  90521 | newpost
    103 | 2016-11-18 17:20:17.284000+0000 |   False | Let\'s do it together! |  40521 | newpost
    103 | 2016-11-18 17:20:02.925000+0000 |   False | Let\'s do it together! |  40521 | newpost
    103 | 2016-11-18 17:19:55.643000+0000 |   False | Let\'s do it together! |  30521 | newpost
    103 | 2016-11-18 17:19:49.029000+0000 |   False | Let\'s do it together! |  60521 | newpost

If I do simple queries i.e.
select * from notification where postid=40521;

then the result seems fine
userid | postdate                        | hasread | message                | postid | type
--------+---------------------------------+---------+------------------------+--------+---------
    103 | 2016-11-18 17:20:17.284000+0000 |   False | Let\'s do it together! |  40521 | newpost
    103 | 2016-11-18 17:20:02.925000+0000 |   False | Let\'s do it together! |  40521 | newpost

Or let's get a single row like this
select * from notification where postid=60521;

again the one single row seems fine
userid | postdate                        | hasread | message                | postid | type
--------+---------------------------------+---------+------------------------+--------+---------
    103 | 2016-11-18 17:19:49.029000+0000 |   False | Let\'s do it together! |  60521 | newpost

However, when I am updating the hasread row in one row, I am getting missing postdate error which is the clustering column
update notification set hasread=true where postid=60521 and userid=103;
InvalidRequest: Error from server: code=2200 [Invalid query] message="Some clustering keys are missing: postdate"

I need to get the list in sorted order, that's the reason I have to use postdate for clustering column.
However at the same time I need to update a specific row. I guess it's about the design but still couldn't figure it out. Any suggestions would be appreciated.

A: When updating a row in Cassandra, you must provide your entire PRIMARY KEY.  That's essentially what that error message is telling you.  Remember, Cassandra is NOT a relational database, so you will NOT be able to update by postid.
Additionally, it is important to remember that Cassandra does not differentiate between an INSERT and an UPDATE.  As a specific row's uniqueness is determined by its complete PRIMARY KEY, you must have all PRIMARY KEY components present for all upserts.  Essentially, this is what you need to do:
UPDATE notification SET hasread=true
  WHERE userid=103 AND postdate='2016-11-18 17:19:49.029+0000';

Also, it looks like postid is a high-cardinality column.  Therefore, calls relying on that secondary index are not going to perform well.  Like at all.  If you really need to query by postid, you should consider building an additional query table for that pattern.

A: You can't update or delete with specifying non primary column to where clause.

The WHERE clause specifies the row or rows to be updated. To specify a row, the WHERE clause must provide a value for each column of the row's primary key. To specify more than one row, you can use the IN keyword to introduce a list of possible values. You can only do this for the last column of the primary key.

Let's update hasread  for postid=60521 and userid=103
First You need to select the postdate
SELECT postdate FROM notification where postid=60521 and userid=103;

You will get postdate. Now you can update the hasread field with userid and postdate
update notification set hasread=true where userid=103 and postdate=?;


text:
Q: Getting index number slow in UIpageviewController while using custom pageControl Before closing this question as a duplicate just see I'm facing a serious issue for the past two days.
I'm following UIPageViewController with storyboards tutorial.
I tried to develop my UIPageviewController. I've to show a number of user photos. I don't want to show  apagecontrol in bottom so I created a custom page control instead. When I try to set the index to the UIPageControl it's not working properly - getting some delay some times reaching 5th page only its updating so the counts are not proper
This is my datasource:
 -(UIViewController*)pageViewController:(UIPageViewController *)pageViewController viewControllerBeforeViewController:(UIViewController *)viewController
{

    NSUInteger index = ((BMEnlargePhotoPageView*) viewController).pageIndex;
    [self.enlargePhotoPageControl setCurrentPage:index];

    if((index == 0 ) || (index==NSNotFound)){

        return nil;

    }
    index--;

    return [self viewControllerATindex:index];

}

-(UIViewController*)pageViewController:(UIPageViewController *)pageViewController viewControllerAfterViewController:(UIViewController *)viewController
{

    NSUInteger index = ((BMEnlargePhotoPageView*) viewController).pageIndex;
    [self.enlargePhotoPageControl setCurrentPage:index];

    if(index==NSNotFound){

        return nil;
    }

    index++;

    if(index==[self.userImages count])
    {
        return nil;
    }

    return [self viewControllerATindex:index];

}

- (BMEnlargePhotoPageView*)viewControllerATindex:(NSUInteger)index
{
       if(([self.userImages count]==0) || (index >= [self.userImages count])){

              }

    BMEnlargePhotoPageView *PageContentViewControl = [self.storyboard instantiateViewControllerWithIdentifier:@"EnlargePhoto"];

    PageContentViewControl.imageFIle =self.userImages[index];
    PageContentViewControl.pageIndex = index;

    return PageContentViewControl;

}

My other issue is that I want to find the current visible photos's index ID so that too I can't take properly - it's getting delayed value and is not correct.
Note: when I use animation page scroll everything works well but in scroll animation it's getting delayed but I want to show it as scroll only i tried many SO ansers nothing getting my problem some one guide or am i doing any wrong.

A: After long frustration week finally found which one good with iOS7 and don mind answering my question bcz no one answered so i supposed to fill the blank space.
In UIPageViewController there is delegate named didFinishAnimating: so in this there is a BOOL function which can identify your page turned completely or partially so using that BOOL you can check that and when you using even animation scroll it will be useful. Your code goes like this
- (void)pageViewController:(UIPageViewController *)pageViewController didFinishAnimating:(BOOL)finished previousViewControllers:(NSArray *)previousViewControllers transitionCompleted:(BOOL)completed{

    if(completed){

        COntentViewController *enlarge =[self.pageViewController.viewControllers lastObject];
        self.enlargePhotoPageControl.currentPage =  enlarge.pageIndex;

    }

}

in this last object hold your last transmitted content if you partially scroll page the BOOL will not be get true it will indicate if the page scrolled completely this will help you those who wants to use custom page control. its working for me well how i expected set your pagecontrol index when the page scrolled completely unless the page indicator will not be set. It remains as last page count thx if i did any mistakes pls correct myself or even some good approach.


text:
Q: during, while or whilst (the) rain? Does the last part of the following sentence sound natural for  native  speakers?

"Alicia was standing under the tree during rain".

Some users have suggested I need to place the article "the" before the noun rain. Could anyone please explain why? And some answers have suggested that "during" should be replaced with "while" or "whilst", but aren't they synonymous? Why should I prefer "while" to "during"?

A: The problem with during rain is that during is followed by an indication of a time period. During the winter or during Christmas make perfect sense.
Rain without a definite article generally refers to actual drops of water that are falling. "Rain is falling on my head".
The choice of while over during is because during is followed by a noun, and we don't have a convenient noun available here. The verb to rain allows us to form while it rained. This particular case is not a general rule for all weather-related phenomena. During the storm is perfectly fine; storm is a noun which clearly describes an event.

A: The word "rain" is an activity noun.  Most activity nouns do not take "the" as an article.  Rain, (along with a few other activity nouns) is an exception and takes "the."  When we say "the rain" we are talking about the weather activity.  When we say "rain" we mean the actual water.  (There is a song "Singing in The rain."  Watch it on youtube, it's a classic. http://youtu.be/w40ushYAaYA)
Here are some examples of activity nouns that don;t take "the" in sentences:  "I like going to church."  "I was sent to jail."  "I'm tired.  I think I'll go to bed."  Here are some of the exceptions: "I need to see the doctor."  "If you want answers, you should go to the library."  "Can you find avocados at the store during Winter?"
So, your sentence works best with "the," and I would write it thus: "Alicia was standing under the tree during the rain."  However, I think it works better if you use the simple past, "Alicia stood under the tree during the rain."
"Whilst" is used chiefly in BrE.  It introduces a "background activity" in which to place an event.  "While I was writing this answer, my dog begged for attention."  "While" cannot be placed before "the rain" in your sentence because it is not a preposition but a subordinate conjunction (http://englishplus.com/grammar/00000377.htm).  If you want to use "while" (and you can) this is a possibility: "While it rained, Alicia was standing under the tree."  I prefer, "While it rained, Alicia stood under the tree."
Hope this helps.  Ask in the comments section if you need some follow-up.

A: I think it would sound better like this: Alicia was standing under the tree while it was raining.

A: 'Alicia stood under the tree whilst it was raining'. 'Alicia was standing under the tree in the rain'. 'Alicia was standing under the tree whilst it rained' 'Alicia stood under the tree during the rainstorm'
Any of those would work.

A: "During rain" is not a typical American way of expressing this.  As noted above by Lacy, those are more typical modes of expression.


text:
Q: How do I filter a list for the next bigger value on two depending variables in ts? I get a list of objects from my backend where one object looks like this:
{
id: 1,
height: 100,
length: 100,
price: 50
}
In my Angular application, I try to find a price regarding to the legth and width which the user chose. However, if the input doesnt conclude to perfectly matching dimensions my programm should look for the next bigger entry where none of the values entered are smaller then the values of the object.
In a nutshell we can look at it like the following pricing table:

Height/Length
100
200
300

100
50
86
97

200
75
79
86

300
100
102
107

(Not real values, just to show, no relation between dimensions and price)
If the input is 100x100 the result is 50 so far so good.
But if the input is 100x150 the result should be 100x200.
And if the input is 150x150 the result should be 200x200.
This was my previous try:
    var temp = areas.reduce((prev,curr) => {
    return curr.width - width >= 0 && curr.height - height >= 0 &&
    curr.width - width < prev.width - width &&
    curr.height - height < prev.height - height ? curr : prev;
});

height and width are the inputvalues of the user
but the out come of my code is always the maximum of my list.
Thank you in advance for your time and help, if you need anything more from me let me know.
And have a nice day!


text:
Q: Extend com.mikepenz.materialdrawer.AccountHeaderBuilder I need to build my own AccountHeaderBuilder implementation.
So I'm trying to extend a class from MaterialDrawer library.
In Android studio, how do I need to proceed in order to do that?
Should MaterialDrawer library be imported as a module?
If yes, why do I get errors like:
Error:(1290) Error retrieving parent for item: No resource found that matches the given name 'MaterialTheme'. when I import the project as a module...
Even when my gradle is set to :
  compileSdkVersion 23
  minSdkVersion 15
  targetSdkVersion 23

My class extending AccountHeaderBuilder needs to be in the same package... So my understanding is that I cannot just use in the gradle file.
compile('com.mikepenz:materialdrawer:5.0.9@aar')

So, in one sentence : how to I proceed to be able to extend classes from another project?
Thanks a lot for the help
ps: I have been able to integrate this library and make it work in my project but now I need extra funcionalities.

A: The exception occurs because the required dependencies are missing. The MaterialDrawer depends on the Materialize and FastAdapter libraries which provide required helper classes.
The documentation of the MaterialDrawer states to add transitive=true which will automatically resolve the sub dependencies of the MaterialDrawer
So replace your compile statement with:
compile('com.mikepenz:materialdrawer:5.1.4@aar') {
    transitive = true
}

As of the requirement mentioned in the comment.
It is also possible to overwrite the layout used for the AccountHeader https://github.com/mikepenz/MaterialDrawer/blob/develop/library/src/main/res/layout/material_drawer_header.xml
You can alter that layout to anything you want, just remember the ids which are in need to stay the same, and you can't remove existing views like the profiles, but you could just alter it so the ImageViews are within a layout, and set this one to gone. So the profiles won't be visible anymore.
For the additional row. You can add this one to the selection container where the existing two TextViews are included. After that you just listen for the onProfileChanged event from the AccountHeaderBuilder, and update this TextView when the profile changes.
(You can get this view by searching for it with findViewById on the AccountHeader container view https://github.com/mikepenz/MaterialDrawer/blob/develop/library/src/main/java/com/mikepenz/materialdrawer/AccountHeader.java#L38)


text:
Q: Flutter Slidable Widget does not get removed when onDismissed I am having trouble where a Slidable does not get removed when I pressed delete action as shown in an image below.
The problem is in class NotificationInputPage where onDismissed got triggered, but notificationList.removedAt(index); does not seems to work.
If you spot something isn't right, please let me know.  Thank you so much.

return SlidableWidget(child: notification, onDismissed: (context) {
                    setState(() {
                      notificationList.removeAt(index);
                      print('deleted..');
                    });
                  });

Here is my code
import 'package:flutter/material.dart';
import 'package:flutter/widgets.dart';
import 'package:flutter_slidable/flutter_slidable.dart';

class SlidableWidget extends StatelessWidget {
  final Widget child;
  final void Function(BuildContext context) onDismissed;

  const SlidableWidget({required this.child, required this.onDismissed , Key? key}) : super(key: key);

  @override
  Widget build(BuildContext context) => Slidable(
        child: child,
        endActionPane: ActionPane(motion: ScrollMotion(), children: [
          SlidableAction(
            flex: 1,
            onPressed: onDismissed,
            backgroundColor: Colors.red,
            foregroundColor: Colors.white,
            icon: Icons.delete,
            label: 'delete',
          ),
        ],
        extentRatio: 0.2,),
      );
}

import 'package:carwashqueue/constants/constants.dart';
import 'package:carwashqueue/constants/enumerations.dart';
import 'package:carwashqueue/models/carwash_notification.dart';
import 'package:carwashqueue/widget/slidable_widget.dart';
import 'package:cloud_firestore/cloud_firestore.dart';
import 'package:firebase_auth/firebase_auth.dart';
import 'package:flutter/cupertino.dart';
import 'package:flutter/material.dart';
import 'package:flutter/widgets.dart';
import 'package:font_awesome_flutter/font_awesome_flutter.dart';

class NotificationInputPage extends StatefulWidget {
  const NotificationInputPage({Key? key}) : super(key: key);

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

class _NotificationInputPageState extends State<NotificationInputPage> {
  DateTime thirtyDaysAgo = DateTime.now().subtract(const Duration(days: 30));
  final _auth = FirebaseAuth.instance;
  final _fireStore = FirebaseFirestore.instance;

  @override
  Widget build(BuildContext context) {

    Stream<List<CarWashNotification>> readNotification() => _fireStore
        .collection('notifications')
        .orderBy('notification_date', descending: false)
        .where('notification_date',
        isGreaterThanOrEqualTo: thirtyDaysAgo)
        .snapshots()
        .map((snapshot) => snapshot.docs.map((doc) => CarWashNotification.fromJson(doc.data(), doc)).toList());

    return Scaffold(
      body: StreamBuilder<List<CarWashNotification>>(
        stream: readNotification(),
        builder: (context, snapshot) {
          if (snapshot.hasError) {
            return Text('There is an error.  Please try again.');
          } else if (snapshot.hasData) {
            final notifications = snapshot.data!;
            List<Widget> notificationList = notifications.map((e) => buildListTile(e)).toList();
            // return ListView(children: notificationList,);
            return ListView.separated(
                itemBuilder: (context, index) {
                  final notification = notificationList[index];

                  return SlidableWidget(child: notification, onDismissed: (context) {
                    setState(() {
                      notificationList.removeAt(index);
                      print('deleted..');
                    });
                  });
                },
                separatorBuilder: (context, index) => Divider(),
                itemCount: notificationList.length);
          } else {
            return Center(
                child: Text('There is no notification at the moment.'));
          }
        }),
    );
  }

  Widget buildListTile(CarWashNotification item) {
    return ListTile(
      leading: FaIcon(
        FontAwesomeIcons.bullhorn,
        size: 30.0,
        color: mainColour1,
      ),
      title: Text(item.title),
      subtitle: Text(item.message.length > textLimit
          ? item.message.substring(0, textLimit) + '...'
          : item.message),
      onTap: () {
        print('onTap');
      },
    );
  }

A: You should use dissmissible widget for this.
Dissmissible Widget
Dissmissible Widget Swiping

A: Now I understand why item didn't get removed from the list.
Actually it did get removed but when setState function runs, it reruns the build method so all the items are retrieved from firebase and reassigned to the list.  That's why the item looks like it's never been removed from the list.

So What I will need to do is to really delete selected item from firebase or I will need to use a different mechanism.


text:
Q: "Karma is a bitch" I recently sent a message to my credit union complaining about the misbehavior of some staff members (treating customers with contempt). I ended my message by writing:

Karma is a b*tch.

The credit union flagged my message for "inappropriate or foul language."
Given the context and circumstances, are they right?
If you were a senior staff member at a credit union, and a customer correspondence landed on your desk critical of junior staff, and using the phrase in question, would you conclude it as "inappropriate or foul language?"
Or would you think, this customer has a valid point, as expressed?

A:
Given the context and circumstances, are they right? Is this inappropriate or foul language?

Yes, it's inappropriate in this context. The word "bitch" has offensive and misogynistic connotations. If we were talking about breeding puppies, the word wouldn't be a problem, but your email trades on the taboo nature of the word in order to get across your anger. This is inappropriate in business correspondence and rude to the person who receives your email.
I'll leave it at that. I would have written a longer answer, but it's time for me to take my two fine bitches for a walk. One is a schnauzer mutt and the other is an Italian greyhound.


text:
Q: Is this method to find mean already discovered? I am a 10th class student and in our syllabus, we have three methods for finding mean of grouped data:

*

*Direct method.

*Assumed mean method.

*Step deviation method.

Out of these, the Step deviation method is the simplest but still requires a lot of calculations. In the step-deviation method, you have to first find class mark ($x_i$), subtract some number ($a$) from all of them to get $d_i$ and then divide them all by some number ($h$) to get $u_i$, and then use a formula to get mean. After doing some of the excercises, I noticed that in most of the questions, the values of ui were ...,-2,-1,0,1,2,... etc., so I made this method.

Suppose this is the data:
$$\begin{array}{c|cc}
i & \text{CI} & f_i \\\hline
1 & 1-3 & 1\\
2 & 3-5 & 2\\
3 & 5-7 & 2\\
4 & 7-9 & 1\\
\end{array}$$

*

*Let $m=$ the class number with the largest $f_i$. (It doesn't matter which number you choose but it will be easy in this way). $\qquad\therefore \qquad m=3$.

*Set $k_i = m-i$.
$$\begin{array}{c|cc|c}
i & \text{CI} & f_i & k_i \\\hline
1 & 1-3 & 1 & 2\\
2 & 3-5 & 2 & 1\\
3 & 5-7 & 2 & 0\\
4 & 7-9 & 1 & -1\\
\end{array}$$

*Let Mean of $kf = \bar k$, that is, $\bar k = \frac{\displaystyle \Sigma f_ik_i}{\displaystyle  \Sigma f_i }$
$$\begin{array}{c|cc|c|c}
i & \text{CI} & f_i & k_i&f_ik_i \\\hline
1 & 1-3 & 1 & 2 & 2\\
2 & 3-5 & 2 & 1 & 2\\
3 & 5-7 & 2 & 0 & 0\\
4 & 7-9 & 1 & -1&-1\\\hline
&&\Sigma f_i = 6&&\Sigma f_ik_i=3
\end{array}$$$$\therefore\qquad\bar k=\frac12$$

*Use this formula which I discovered:
$$\bar x = -h\bar k+l+hm-\frac h2$$
(where $h$ is class size and $l$ is lower limit of the first class)
$$\therefore\qquad\bar x = -2\times\frac12+1+2\times 3-\frac22=5$$
Which is the correct answer.

Now the question is

*

*Has this method been dicovered earlier? What do we call it?

*If it has been dicovered earlier, then why do they still teach us so complicated methods in school?

(As we all know, math is ungooglable.)


text:
Q: drag and drop actionscript issue, how to fix? I have a problem with my ActionScript drag and drop + clone. An object gets stuck after a few instances, when it overlaps with another instance. Each object is a movieclip, that is vector graphic imported form Adobe Illustrator.
What must i change to make it not get stuck? I borrowed from this stackoverflow question: Drag, Drop and Clone - Flash AS3
Here is my actionscript:
 import flash.display.MovieClip;

 for (var i = 1; i < 27; i++)
 {
    this["object" + i].addEventListener(MouseEvent.MOUSE_DOWN, onStart);
    this["object" + i].addEventListener(MouseEvent.MOUSE_UP, onStop);
 }

 var sx = 0, sy = 0;

 function onStart(e)
 {
    sx = e.currentTarget.x;
    sy = e.currentTarget.y;
    e.currentTarget.startDrag();
 }

 function onStop(e)
 {
    if (e.target.dropTarget != null &&
        e.target.dropTarget.parent == dest)
    {
        var objectClass:Class =
        getDefinitionByName(getQualifiedClassName(e.currentTarget)) as Class;
        var copy:MovieClip = new objectClass();
        this.addChild(copy);
        copy.x = e.currentTarget.x;
        copy.y = e.currentTarget.y;
    }

    e.currentTarget.x = sx;
    e.currentTarget.y = sy;
    e.currentTarget.stopDrag();
}

Thank you.


text:
Q: Custom Theme Blog page not showing Posts I am developing my custom theme in WordPress from scratch. Now when i am working with my blogs page its not showing any of the posts i have changed my "index.php" page but i think there must be some function that is missing from my "functions.php" page due to which my posts are not showing . i have searched for it a lot but didn't found any good solutions. please tell me what i can do.
this is my index.php page:
<?php
/**
 * The main template file
 *
 * This is the most generic template file in a WordPress theme
 * and one of the two required files for a theme (the other being style.css).
 * It is used to display a page when nothing more specific matches a query.
 * e.g., it puts together the home page when no home.php file exists.
 *
 * Learn more: {@link https://codex.wordpress.org/Template_Hierarchy}
 *
 * @package WordPress
 * @subpackage customtheme
 * @since 2016
 */

get_header(); ?>

        <?php if ( have_posts() ) : ?>

            <?php if ( is_home() && ! is_front_page() ) : ?>

<?php single_post_title(); ?>

            <?php endif; ?>

            <?php
            // Start the loop.
//                        var_dump(the_post());
//                        exit;
            while ( have_posts() ) : the_post();

                /*
                 * Include the Post-Format-specific template for the content.
                 * If you want to override this in a child theme, then include a file
                 * called content-___.php (where ___ is the Post Format name) and that will be used instead.
                 */
                get_template_part( 'content', get_post_format() );

            // End the loop.
            endwhile;

            // Previous/next page navigation.
            the_posts_pagination( array(
                'prev_text'          => __( 'Previous page', 'customtheme' ),
                'next_text'          => __( 'Next page', 'customtheme' ),
                'before_page_number' => '' . __( 'Page', 'customtheme' ) . ' ',
            ) );

        // If no content, include the "No posts found" template.
        else :
            get_template_part( 'content', 'none' );

        endif;
        ?>

<?php get_footer(); ?>

and my functions.php page:
<?php
/**
 * customtheme functions and definitions
 *
 * Set up the theme and provides some helper functions, which are used in the
 * theme as custom template tags. Others are attached to action and filter
 * hooks in WordPress to change core functionality.
 *
 * When using a child theme you can override certain functions (those wrapped
 * in a function_exists() call) by defining them first in your child theme's
 * functions.php file. The child theme's functions.php file is included before
 * the parent theme's file, so the child theme functions would be used.
 *
 * @link https://codex.wordpress.org/Theme_Development
 * @link https://codex.wordpress.org/Child_Themes
 *
 * Functions that are not pluggable (not wrapped in function_exists()) are
 * instead attached to a filter or action hook.
 *
 * For more information on hooks, actions, and filters,
 * {@link https://codex.wordpress.org/Plugin_API}
 *
 * @package WordPress
 * @subpackage custometheme
 * @since 2016
 */

/**
 * Set the content width based on the theme's design and stylesheet.
 *
 * @since 2016
 */

function customtheme_setup() {

    /*
     * Let WordPress manage the document title.
     * By adding theme support, we declare that this theme does not use a
     * hard-coded <title> tag in the document head, and expect WordPress to
     * provide it for us.
     */
        add_theme_support( 'title-tag' );

    /*
     * Enable support for Post Thumbnails on posts and pages.
     *
     * See: https://codex.wordpress.org/Function_Reference/add_theme_support#Post_Thumbnails
     */
    add_theme_support( 'post-thumbnails' );
    set_post_thumbnail_size( 825, 510, true );
    // For adding Menus
    register_nav_menus( array(
        'primary' => __( 'NavMenu', 'Primary Menu' ),
        'PFooter1'  => __( 'Product Footer1', 'Product Footer1'  ),
            'PFooter2'  => __( 'Product Footer2', 'Product Footer2'  ),
            'CFooter1'  => __( 'Company Footer1', 'Company Footer1'  ),
            'CFooter2'  => __( 'Company Footer2', 'Company Footer2'  ),
             'ContactUs'  => __( 'ContactUs', 'ContactUs'  ),
            ) );

        add_theme_support( 'html5', array(
        'search-form', 'comment-form', 'comment-list', 'gallery', 'caption'
    ) );

            /*
     * Enable support for Post Formats.
     *
     * See: https://codex.wordpress.org/Post_Formats
     */
    add_theme_support( 'post-formats', array(
        'aside', 'image', 'video', 'quote', 'link', 'gallery', 'status', 'audio', 'chat'
    ) );

    // Setup the WordPress core custom background feature.
    add_theme_support( 'custom-background', apply_filters( 'custometheme_custom_background_args', array(
        'default-color'      => $default_color,
        'default-attachment' => 'fixed',
    ) ) );

}

add_action( 'init', 'customtheme_setup' );

/**
 * Register our sidebars and widgetized areas.
 *
 */

if ( function_exists('register_sidebar') ){

    register_sidebar( array(
        'name'          => 'Footer Icons Bar',
        'id'            => 'home_right_1',
        'before_widget' => '',
        'after_widget'  => '',
//      'before_title'  => '
',
//      'after_title'   => '
',
    ) );

            register_sidebar( array(
        'name'          => 'Footer CopyRight',
        'id'            => 'home_right_2',
        'before_widget' => '',
        'after_widget'  => '',
//      'before_title'  => '
',
//      'after_title'   => '
',
    ) );

}

//function customtheme_widgets_init() {
//
//  register_sidebar( array(
//      'name'          => 'Footer Icons Bar',
//      'id'            => 'home_right_1',
//      'before_widget' => '',
//      'after_widget'  => '',
////        'before_title'  => '
',
////        'after_title'   => '
',
//  ) );
//
//}
//
//add_action( 'widgets_init', 'customtheme_widgets_init' );

//  register_sidebar( array(
//      'name'          => 'Footer Copyright',
//      'id'            => 'home_right_2',
//      'before_widget' => '',
//      'after_widget'  => '',
////        'before_title'  => '
',
////        'after_title'   => '
',
//  ) );
//        add_action( 'widgets_init', 'customtheme_widgets_init' );

?>

A: Problem solved .
as i was making my custom theme from scratch so there was not content.php file included in my custom theme that displays the posts titles and contents i have added that.
and it can also be solved if u add this line in you index.php page.
the_content();

or
the_title();

whatever u need.
it can be like this in the while loop :
while ( have_posts() ) : the_post();

                /*
                 * Include the Post-Format-specific template for the content.
                 * If you want to override this in a child theme, then include a file
                 * called content-___.php (where ___ is the Post Format name) and that will be used instead.
                 */
                get_template_part( 'content', get_post_format() );
the_content();
the_title();
            // End the loop.
            endwhile;


text:
Q: Does testflight wipeout local data? I have a react-native app that asks for user credentials if it detects that the device have no credentials previously saved, it didn't use to happen but nowadays whenever I update the app through test flight it asks for the credentials again.
Does testflight wipeout sqlite data?
I use react-native-sqlite-storage

A: When using asyncStorage form react-native which also uses SQLite on Android, it doesn't wipe out the stored data, only if you delete the App.


text:
Q: hwo do I setup my personal ssh config file for ssh tunneling At the office on my laptop where I have postgresql database installed I need to use a SSH tunnel to explore the filesystem of a remote system on the office network.
I have successfully run a "ssh -L" command to setup the tunnel and my Perl script was successfull in exploring the filesystem of the remote machine.
It has been suggested to me that I can make my life a lot easier by specifying the SSH tunnel information in my personal ssh config file. I have been searching for information and an example, but it is still not clear to me as to what information to put into my personal ssh config file. Can someone provide me with an example of a ssh config file that specifies data for a ssh tunnel?


text:
Q: How do I stop a result from a radio button from showing when the question is hidden I'm using radio buttons and I need to get the result for the second question to be hidden from the screen if I change my answer to question #1.
For example, if I say 'Yes' to question #1 and then 'No' to question #2 and then I go back up to question #1 and change my answer to 'No', question 2 will be hidden as it should, but the result from question 2 will stay on the screen along with the results from question #1.
Is the accurate SKU on the LOS?

Yes <input type="radio" onclick="javascript:yesnoCheck();" name="yesno" id="yesCheck">
No <input type="radio" onclick="javascript:yesnoCheck();" name="yesno" id="noCheck">

    Can the customer call the VM from their phone?

    Yes <input type="radio" onclick="javascript:yesnoCheck1();" name="yesno1" id="yesCheck1">
    No <input type="radio" onclick="javascript:yesnoCheck1();" name="yesno1" id="noCheck1">

    Result of selecting Yes to second question.

    Result of selecting No to second question

    Result of selecting No to first question

A: If I understand your question correctly, the code below should do what you want. To help you understand the changes:

*

*Let's say you have two elements, and one is a parent of the other, like this:

    I am the parent

        And I am the child

The parent element will be hidden, but the child element will not be. If you want to control the visibility of an element, plus all of its children, you can instead use the 'display' attribute:

    I am the parent

        And I am the child

Now the child element is also hidden.
The other useful thing about using display rather than visibility is that elements with visibility:hidden still take up space on the page, while elements with display:none do not.

*Using that technique, I moved your ifYes1 and ifNo1 divs inside the ifYes div. That way hiding or showing the ifYes div makes everything related to question 2 visible or invisible at the same time.

*This is more a style thing, but if you're using two radio buttons, once the user has checked a button, then it's enough to just look at the 'checked' attribute of one of them.  If it's checked, then you know the other one isn't, and vice versa. Based on that logic, I simplified your if/else statements a bit. Personally, I think it makes the code easier to read.
Here's the revised code:
Is the accurate SKU on the LOS?

Yes <input type="radio" onclick="javascript:yesnoCheck();" name="yesno" id="yesCheck">
No <input type="radio" onclick="javascript:yesnoCheck();" name="yesno" id="noCheck">

Can the customer call the VM from their phone?

Yes <input type="radio" onclick="javascript:yesnoCheck1();" name="yesno1" id="yesCheck1">
No <input type="radio" onclick="javascript:yesnoCheck1();" name="yesno1" id="noCheck1">

Result of selecting Yes to second question.

Result of selecting No to second question

Result of selecting No to first question


text:
Q: Avoiding copy paste - how to make multiple files with different names I would like to avoid copy pasting in my code, and I would like to use a string as a name of multiple files.
bands <- c('B1', 'B2', 'B3', 'B4', 'B5')

for (band in bands){
  path <- paste0('./data/landsat/LE07_L2SP_012054_20120217_20200909_02_T1', '_SR_', band, '.tif')
  band <- raster(path)
}

In this case, I understand that I am making a raster called "band" five times. Is there any way I could end up with 5 files called respectively 'B1', 'B2', 'B3', 'B4', 'B5'?

A: You should put your data in a list rather than giving it sequential names.
bands <- c('B1', 'B2', 'B3', 'B4', 'B5')
## paste0 is vectorized, no for loop needed
filepaths <- paste0('./data/landsat/LE07_L2SP_012054_20120217_20200909_02_T1', '_SR_', bands, '.tif')
bandlist <- lapply(filepaths, raster)
names(bandlist) <- bands

You can then refer to individual items of the ist as bandlist[[2]] or bandlist[["B2"]].
Read more about this general idea at How do I make a list of data frames?


text:
Q: Created Angular component not visible after 'ng build' I'm new to Angular and recently I started working on a simple personal SPA project. It was created using the angular cli, and the folder structure is nothing special:
- myApp
----e2e
----node_modules
----src
--------app
------------ main app module with two .ts components and html for each of them
...

Everything works fine when I use ng serve: I can see my components on localhost:4200 and Angular's functionality works as a charm.
However, when I run ng build and from inside the newly created dist folder I open index.html, I can't see my components at all.
The index.html file is as follows:
<!doctype html>
<html lang="en">
<head>
  <meta charset="utf-8">
  <title>RoutingDemo</title>

  <meta name="viewport" content="width=device-width, initial-scale=1">
  <link rel="icon" type="image/x-icon" href="favicon.ico">
</head>
<body>
  <app-root></app-root>
<script type="text/javascript" src="runtime.js"></script><script type="text/javascript" src="polyfills.js"></script><script type="text/javascript" src="styles.js"></script><script type="text/javascript" src="vendor.js"></script><script type="text/javascript" src="main.js"></script></body>
</html>

I get no errors in the console for missing files and all of the JS and CSS files are being successfully read by the index.html.
Can someone explain why am I not seeing the components?

A: So you need to serve your page, easiest way is to do npm i -g http-server and the run http-server from command lint in your dist folder, then you will be able to see your page


text:
Q: Unhandled Rejection (Error): Request failed with status code 404 - Axios, React Its throwing an error in the details page saying Unhandled Rejection (Error): Request failed with status code 404. Could someone help me what i'm doing wrong. I'm basically trying to get the data to be printed when the user clicks on movielist component and it directs to details page and displays all the content.
Whats wrong with api call using Axios?
Home.js:
import React, { Component } from 'react';
import './Home.css';
import Title from '../Title/Title';
import MovieList from '../MovieList/MovieList';
import axios from 'axios';

 class Home extends Component {

    constructor(props){
        super(props);
        this.state = {
            allMovies : [],
            crimeMovies : [],
            dramaMovies : [],
            actionMovies : []
        }
    }
     componentDidMount (){
        const token = 'Bearer Wookie2019';
         axios.get('https://wookie.codesubmit.io/movies',{
            headers: {
              'Authorization': token
            }
          }).then(response => {
            const { data: {movies} } = response;
            this.setState({
              allMovies: movies,
              crimeMovies: movies.filter(movies => movies.genres === 'Crime'),
              dramaMovies: movies.filter(movies => movies.genres === 'Drama'),
              actionMovies: movies.filter(movies => movies.genres === 'Action'),
          });
         console.log(response);
       });

     }

    render() {

        const movies = this.state.allMovies.map(movie => {
            return <MovieList key = {movie.id} title = {movie.title} poster = {movie.poster} genres = { movie.genres} />
        })
        const criMovies = this.state.crimeMovies.map(movie => {
            return <MovieList key = {movie.id} title = {movie.title} poster = {movie.poster} genres = { movie.genres} />
        })

        return (

                <Title/>
                {movies}
                {criMovies}

        )
    }
}

export default Home;

MovieList.js:
import React, { Component } from 'react'
import { Link, withRouter } from 'react-router-dom';

class MovieList extends Component {
    handleClick = () => {
        const { history, movie } = this.props;
        if(history) history.push(`/Details/${this.props.slug}`);
    }
        render () {
            return (

{this.props.genres}

                            <Link  to={`/Details/:${this.props.slug}`}>

                                </Link>

            )
        }
    }

export default withRouter(MovieList);

Details.js:
import React, { Component } from 'react';
import Title from '../Title/Title';
import './Details.css';
import axios from 'axios';
import Notfound from "../Notfound/Notfound";

class Details extends Component {

    state = {
        movie : []
    }
     componentDidMount (){
         const  { match } = this.props;

         const slug = match.params.slug;

        const token = 'Bearer Wookie2019';
         axios.get(`https://wookie.codesubmit.io/movies/${slug}`,{
            headers: {
              'Authorization': token
            }
          }).then(response => {
            this.setState({
                movies: response.data.movies
            })
         });

     }

    render () {

        const  { movie } = this.state;

        if (!movie){
            <Notfound/>
        }
        return (

                <Title/>

                                Title:  {movie.title}

                                    Cast:

                              Movie Description:
                             {movie.overview}

        )

    }
}

export default Details;


text:
Q: Replacing a character with a space and dividing the string into two words in R I have a dataframe that contains a column that includes strings separeted with semi-colons and it is followed by a space. But unfortunately in some of the strings there is a semi-colon that is not followed by a space.
In this case, This is what i'd like to do: If there is a space after the semi-colon we do not need a change. However if there are letters before and after the semi-colon, we should change semi-colon with space
i have this:
        datacolumn1
 row 1  knowledge; information; data
 row 2  digital;transmission; interoperability; data labeling
 row 3  library catalogs; libraries; mobile;libraries

I need this output:
       datacolumn1
row 1  knowledge; information; data
row 2  digital transmission; interoperability; data labeling
row 3  library catalogs; libraries; mobile libraries

A: Try something like:
library(stringr)
str_replace_all(datacolumn1, "(\\w);(\\w)", "\\1 \\2")

This is probably a neater regex out there, but this will do!

A: you can use this regex to select ";" not leaded or followed by space then replace it with space :
(?<!\s);(?!\s)

(?<!\s) : negative lookbehind to check if not leaded by space or \n or \t
(?!\s) : negative lookahead to check if not followed by space or \n or \t

demo


text:
Q: Change intel parallel Studio 2018 install directory I am going crazy with the parallel studio installer. I installed some time ago PS2018.1 in a first directory. Now I would like to install PS2018.2 in another directory.
The installer tells me that I cannot install PS2018.2 in another directory because it has detected my previous installation of PS2018.1. So I uninstalled PS2018.1 with the uninstall_GUI.sh tool in the PS2018.1 install directory, and remove manually this (cleaned) install directory.
But when I try to install PS2018.2, the installer still says that I have a previous installation (which does not exists anymore...) and so do not let me install where I want.
My questions are:

*

*How does the installer detect this previous installation whereas I uninstalled it. There must be a file storing that information somewhere, but where?

*Is it possible to have multiple installations of PS at the same time?
Thanks!

A: I had the same problem. It seems there is some metadata stored in
/opt/intel
so basically although i had specified a different install dir, /opt/intel was still created. So if you are sure you do not want the content of /opt/intel (such as the license info and you can re-activate it) just delete /opt/intel. That solved the problem for me at least.