text:
Q: Postgres varchar column using index inconsistently I have a query that will use a table's indexes when the input parameter is a given length, but not when the parameter is any other length.
This query will use the tables indexes correctly:
EXPLAIN SELECT *
FROM equipment_tests et
INNER JOIN equipments e ON e.id = et.equipment_id
WHERE e.organization_id = '6c93a9b5-cde7-4660-a55a-1ba74b97fc58'
LIMIT 100;

Its query plan:
     Limit  (cost=0.84..40.75 rows=100 width=294) (actual time=357.878..366.848 rows=100 loops=1)
   Output: et.id, et.equipment_id, et.test_id, et.equipment_config_id, et.context, et.created_at, e.id, e.organization_id, e.type, e.model, e.serial_number, e.version, e.calibration_date, e.created_at, e.updated_at, e.hw_version
   ->  Merge Join  (cost=0.84..232724.95 rows=583224 width=294) (actual time=357.874..366.647 rows=100 loops=1)
         Output: et.id, et.equipment_id, et.test_id, et.equipment_config_id, et.context, et.created_at, e.id, e.organization_id, e.type, e.model, e.serial_number, e.version, e.calibration_date, e.created_at, e.updated_at, e.hw_version
         Merge Cond: ((e.id)::text = (et.equipment_id)::text)
         ->  Index Scan using equip_id on public.equipments e  (cost=0.42..14251.87 rows=33030 width=134) (actual time=0.045..0.045 rows=1 loops=1)
               Output: e.id, e.organization_id, e.type, e.model, e.serial_number, e.version, e.calibration_date, e.created_at, e.updated_at, e.hw_version
               Filter: ((e.organization_id)::text = '6c93a9b5-cde7-4660-a55a-1ba74b97fc58'::text)
               Rows Removed by Filter: 5
         ->  Index Scan using equip_tests_equip_id on public.equipment_tests et  (cost=0.43..208750.41 rows=1525051 width=160) (actual time=0.005..173.042 rows=73224 loops=1)
               Output: et.id, et.equipment_id, et.test_id, et.equipment_config_id, et.context, et.created_at
 Total runtime: 366.989 ms

This query will not use the equipment_test.equipment_id index:
EXPLAIN SELECT *
FROM equipment_tests et
INNER JOIN equipments e ON e.id = et.equipment_id
WHERE e.organization_id = '6c93a9b5-cde7-4660-a55a-1ba74b97fc5'
LIMIT 100;

Its query plan:
     Limit  (cost=50.06..14630.82 rows=100 width=294) (actual time=0.043..0.043 rows=0 loops=1)
   Output: et.id, et.equipment_id, et.test_id, et.equipment_config_id, et.context, et.created_at, e.id, e.organization_id, e.type, e.model, e.serial_number, e.version, e.calibration_date, e.created_at, e.updated_at, e.hw_version
   ->  Hash Join  (cost=50.06..56623.39 rows=388 width=294) (actual time=0.040..0.040 rows=0 loops=1)
         Output: et.id, et.equipment_id, et.test_id, et.equipment_config_id, et.context, et.created_at, e.id, e.organization_id, e.type, e.model, e.serial_number, e.version, e.calibration_date, e.created_at, e.updated_at, e.hw_version
         Hash Cond: ((et.equipment_id)::text = (e.id)::text)
         ->  Seq Scan on public.equipment_tests et  (cost=0.00..50850.51 rows=1525051 width=160) (actual time=0.004..0.004 rows=1 loops=1)
               Output: et.id, et.equipment_id, et.test_id, et.equipment_config_id, et.context, et.created_at
         ->  Hash  (cost=49.79..49.79 rows=22 width=134) (actual time=0.027..0.027 rows=0 loops=1)
               Output: e.id, e.organization_id, e.type, e.model, e.serial_number, e.version, e.calibration_date, e.created_at, e.updated_at, e.hw_version
               Buckets: 1024  Batches: 1  Memory Usage: 0kB
               ->  Index Scan using equip_organization on public.equipments e  (cost=0.42..49.79 rows=22 width=134) (actual time=0.025..0.025 rows=0 loops=1)
                     Output: e.id, e.organization_id, e.type, e.model, e.serial_number, e.version, e.calibration_date, e.created_at, e.updated_at, e.hw_version
                     Index Cond: ((e.organization_id)::text = '6c93a9b5-cde7-4660-a55a-1ba74b97fc5'::text)
 Total runtime: 0.088 ms

Note that all I did was make the organization_id where parameter one character shorter.
Our schema:
                Table "equipment_tests"
       Column        |            Type             | Modifiers
---------------------+-----------------------------+-----------
 id                  | character varying           | not null
 equipment_id        | character varying           | not null
 test_id             | character varying           | not null
 equipment_config_id | character varying           | not null
 created_at          | timestamp without time zone | not null
Indexes:
    "equipment_tests_pkey" PRIMARY KEY, btree (id)
    "equipment_tests_test_config_context" UNIQUE, btree (test_id, equipment_config_id)
    "equip_tests_equip_id" btree (equipment_id)

                 Table "equipments"
      Column      |            Type             | Modifiers
------------------+-----------------------------+-----------
 id               | character varying           | not null
 organization_id  | character varying           | not null
 type             | integer                     |
 model            | character varying           |
 serial_number    | character varying           |
 created_at       | timestamp without time zone | not null
 updated_at       | timestamp without time zone | not null
Indexes:
    "equipments_pkey" PRIMARY KEY, btree (id)
    "equip_organization" btree (organization_id)
    "equipment_org_model_sn" btree (organization_id, model, serial_number)

Generally, the PK's are UUID's, but there is some legacy data where the IDs can be shorter sets of random characters (approx 22 random alphanum characters). Its when we query with these IDs (that are shorter than a UUID), do we find that PG is not using the equipment_id index, and is instead doing a table scan.
The equipment_tests table has roughly 40M rows. The equipments table has roughly 1M rows.
We are using Postgres 9.3.6
We believe this probably has something to do with the fact that the majority of the data in this column is one length, with a minority amount of the data being a shorter length, but I am not sure what that next step in debugging should be?


text:
Q: File injection with gulp, pick only some files from folder I use Gulp for injecting my js files into index.html. I have the following structure of my js resources:
js
|-ace-builds
  |-src
    |-ace.js
    |-ext-beautify.js
    |-ext-chromevox.js
    |-ext-elastic_tabstops_lite.js
    |-...
|-angular
  |-angular.js
|-angular-ui-ace
  |-ui-ace.js
|-...

The problem is that from the whole ace-builds folder I need to inject only one file ace.js. Of course, one of the possible solution is to list all injected files manually, but I would like to make the injector definition quite compact and flexible.
Questions is: is it possible with gulp to make such file injection, ingoring other files in the folder and if yes, how?
I tried the following code, also placing the lines (1) and (2) in reverse order, but it has not worked, the ace.js is not included.
gulp.task('index', function () {
    var target = gulp.src('./app/html/index.html');
    var sources = gulp.src([
        'app/js/*.js',
        '!app/js/ace-builds/**/*',                 // (1)
        'app/js/ace-builds/src-noconflict/ace.js'  // (2)
    ], { read: false });
    return target.pipe(inject(sources))
        .pipe(gulp.dest('./app/html'));
});

A: Nothing in your gulp.src's actually reads the folder that ace.js is in.  Why not just include app/js/**/ace.js?  With no negation.  And, by the way, the negation will always be performed last no matter where you have it listed.  That is why you never pick up ace.js.

redpajama_set_name: RedPajamaStackExchange


text:
Q: Update related property (like a trigger) in a POCO entity, is it possible? I have the following POCO entity:
public class User
{
    [...other properties...]

    public byte Status { get; set; }
    public DateTime? DataStatus { get; set; }
}

What I want: inside the set method of the property Status, update DataStatus with the current date when Status is changed, is it possible?

A: If you are using code first, you can just back the property to a private field and implement your own getter and setter. if you are using DB/Model first you can override the methods in the generated classes because they are partial. I'm guessing your example, you can do the following.
public class User
{
    private byte _status;
    public byte Status
    {
        get { return _status; }
        set
        {
            _status = value;
            this.DataStatus = DateTime.Now;
        }
    }
    public DateTime? DataStatus { get; set; }
}

A: public void SetupDbContext(DbContext context)
{
    (DbContext as System.Data.Entity.Infrastructure.IObjectContextAdapter).ObjectContext.SavingChanges += delegate(object sender, EventArgs e)
    {
        var modified = context.ChangeTracker.Entries<User>().Where(entry => entry.State == EntityState.Modified);
        foreach (var entry in modified)
        {
            if (entry.Property("Status").IsModified)
            {
                entry.Entity.DataStatus = DateTime.Now;
            }
        }
    };
}

A: Sure, it's fairly straightforward. You'll have to use a backing field property instead of an auto-property:
public class User
{

    private byte _status;
    public byte Status
    {
        get { return _status; }
        set
        {
            _status = value;
            DataStatus = DateTime.Now;
        }
    }
    public DateTime? DataStatus { get; set; }
}

A: If you use variables with backed properties, rather than auto-properties:
public class User {
    private byte m_Status;
    private DateTime? m_DataStatus;

    public byte Status {
        get { return m_Status; }
        set { m_DataStatus = DateTime.Now; m_Status = value; }
    }
    public DateTime? DataStatus {
        get { return m_DataStatus; }
        set { m_DataStatus = value; }
    }
}


text:
Q: Navigation in restricted area Java EE on Glassfish 4.1 I am developing a webapp based on Java EE 7 on Glassfish 4.1. I'm new to this environment and I followed some guides to create a JDBC Realm based authentication.
I have only one user role (named USER) that should be able to access all the XHTML pages in the /user folder.
The problem is that when the user logs in, he is redirected to his personal homepage (until now everything is fine), but if I add any link to another page in the same /user folder I still have to login again! Also if I refresh the user's homepage I still have to login.
How is it possible to resolve this problem? Am I missing something?
Here is some code you may find useful to help me:
web.xml
<login-config>
    <auth-method>FORM</auth-method>
    <realm-name>myJdbcRealm</realm-name>
    <form-login-config>
        <form-login-page>/login.xhtml</form-login-page>
        <form-error-page>/loginErr.xhtml</form-error-page>
    </form-login-config>
</login-config>
<security-constraint>
    <web-resource-collection>
        <web-resource-name>Logged User</web-resource-name>
        <description/>
        <url-pattern>/user/*</url-pattern>
    </web-resource-collection>
    <auth-constraint>
        <role-name>USER</role-name>
    </auth-constraint>
</security-constraint>
<security-role>
    <role-name>USER</role-name>
</security-role>

glassfish-web.xml
<glassfish-web-app error-url="">
  <class-loader delegate="true"/>
  <jsp-config>
    <property name="keepgenerated" value="true">
      <description>Keep a copy of the generated servlet class' java code.</description>
    </property>
  </jsp-config>
  <security-role-mapping>
    <role-name>USER</role-name>
    <group-name>USER</group-name>
  </security-role-mapping>
</glassfish-web-app>

login.xhtml
<h:form style="width: 500px; margin: auto; ">
    <p:panel header="Login Form">
        <p:panelGrid columns="2" id="loginGrid">
            <p:outputLabel for="usernameInput" value="Username"/>
            <p:inputText id="usernameInput" value="#{loginBean.username}"
                         required="false" />
            <p:outputLabel for="passwordInput" value="Password"/>
            <p:password id="passwordInput" value="#{loginBean.password}"
                        required="false" />
            <p:commandButton value="Login"
                             action="#{loginBean.login()}" update="loginGrid" />

            <p:messages/>
        </p:panelGrid>
    </p:panel>
</h:form>

LoginBean.java
public String login() {
    FacesContext context = FacesContext.getCurrentInstance();
    HttpServletRequest request = (HttpServletRequest) context.getExternalContext().getRequest();
    try {
        request.login(this.username, this.password);
    } catch (ServletException e) {
        MessageBean.addError("Login failed");
        return NavigationBean.toLogin();
    }
    return "/user/home?faces-redirect=true";
}


text:
Q: How to convert points in depth space to color space in Kinect without using Kinect SDK functions? I am doing a augmented reality application with 3D objects overlay on top of color video of user. Kinect version 1.7 is used and rendering of virtual objects are done in OpenGL. I have manage to overlay 3D objects on depth video successfully simply by using the intrinsic constants for depth camera from the NuiSensor.h header and compute a projection matrix based on the formula I have found on http://ksimek.github.io/2013/06/03/calibrated_cameras_in_opengl/. The 3D objects rendered with this projection matrix overlay exactly with the 2D skeleton points in depth space. This is not surprising as skeleton 3D points are computed from depth space and gives me confidence that the projection matrix computed outside Kinect SDK works.
Here are some codes for computation of projection matrix from intrinsic constants and how it is used:
glm::mat4 GetOpenGLProjectionMatrixFromCameraIntrinsics(float alpha, float beta, float skew, float u0, float v0,
    int img_width, int img_height, float near_clip, float far_clip )
{
    float L = 0;
    float R = (float)img_width;
    float B = 0;
    float T = (float)img_height;
    float N = near_clip;
    float F = far_clip;

    glm::mat4 ortho = glm::mat4(0);
    glm::mat4  proj = glm::mat4(0);

    //Using column major convention
    ortho[0][0] =  2.0f/(R-L);
    ortho[0][3] = -(R+L)/(R-L);
    ortho[1][1] =  2.0f/(T-B);
    ortho[1][3] = -(T+B)/(T-B);
    ortho[2][2] = -2.0f/(F-N);
    ortho[2][3] = -(F+N)/(F-N);
    ortho[3][3] = 1;

    proj[0][0] = alpha;     proj[0][1] = skew;  proj[0][2] = -u0;
    proj[1][1] = beta;  proj[1][2] = -v0;
    proj[2][2] = (N+F); proj[2][3] = (N*F);
    proj[3][2] = -1;

    //since glm is row major, we left multiply the two matrices
    //and then transpose the result to pass it to opengl which needs
    //the matrix in column major format
    return glm::transpose(proj*ortho);
}

//Compute projection matrix of Kinect camera
    m_3DProjectionMatrix = GetOpenGLProjectionMatrixFromCameraIntrinsics(m_fx, m_fy, m_skew, m_PPx0, m_PPy0, WIN_WIDTH, WIN_HEIGHT, 0.01f, 10);

//where the input variables are 1142.52, 1142.52, 0.00, 640.00, 480.00, 1280, 960 respectively for m_fx, m_fy, m_skew, m_PPx0, m_PPy0, WIN_WIDTH, WIN_HEIGHT. These numbers are derived from NuiImageCamera.h for depth camera.

Here is how the 2D points are drawn:
glMatrixMode(GL_PROJECTION);
glLoadIdentity();
glOrtho(0, WIN_WIDTH, WIN_HEIGHT, 0, 0.0, 1.0);
glMatrixMode(GL_MODELVIEW);
glLoadIdentity();

Draw2DSkeletonRGBPoints();//Uses NuiTransformSkeletonToDepthImage() followed by NuiImageGetColorPixelCoordinatesFromDepthPixel()
Draw2DSkeletonDepthPoints();//Uses NuiTransformSkeletonToDepthImage() only

Followed by 3D points:
glMatrixMode(GL_PROJECTION);
glLoadMatrixf(glm::value_ptr(m_3DProjectionMatrix));
glMatrixMode(GL_MODELVIEW);
glLoadIdentity();

Draw3DSkeletonPoints();//The Skeleton 3D coordinates from Kinect

However, overlaying virtual objects on top of color video is not that straight away. It seems there are some translation, scaling or even slight rotation between color and depth space. I know there is a SDK function to convert skeleton point to color point but this cannot be used easily for OpenGL rendering; I need a transformation matrix that maps 3D Skeleton points in Skeleton coordinate space into 3D points with Color camera as the origin. Does anyone know how to go about computing this transformation matrix? Where can I find more information about doing this?


text:
Q: Spring Boot OpenAPI 3 with Spring Data REST I'm failing at documenting my Spring Data REST API with OpenAPI. Nothing show in swagger-ui's homepage (and /v3/api-docs obviously).
Here is an excerpt from my dependencies:
    <dependency>
        <groupId>org.springframework.boot</groupId>
        <artifactId>spring-boot-starter-data-jpa</artifactId>
    </dependency>
    <dependency>
        <groupId>org.springframework.boot</groupId>
        <artifactId>spring-boot-starter-data-rest</artifactId>
    </dependency>

    <dependency>
        <groupId>org.springdoc</groupId>
        <artifactId>springdoc-openapi-ui</artifactId>
        <version>1.6.4</version>
    </dependency>
    <dependency>
        <groupId>org.springdoc</groupId>
        <artifactId>springdoc-openapi-data-rest</artifactId>
        <version>1.6.4</version>
    </dependency>

And there is my JPA repository:
@RepositoryRestResource(collectionResourceRel = "people", path = "people")
public interface PersonsRepository extends JpaRepository<Person, Long> {
Person findByLastname(@Param("name") @RequestParam("name") String lastname);
}

And this my Spring Boot setup:
spring.datasource.url=jdbc:h2:mem:testdb;DATABASE_TO_UPPER=false
spring.jpa.defer-datasource-initialization=true
spring.jpa.open-in-view=false
management.endpoints.web.exposure.include=*
springdoc.swagger-ui.operationsSorter=method
#springdoc.paths-to-match=/people/**

Of course, my CRUD API is ok over /people PATH.
Even the /profile/people PATH seems right.
I must be missing something... Thanks for any help.

A: Try this URL:
http://localhost:8080/swagger-ui/index.html?configUrl=/v3/api-docs/swagger-config#
My Configurations
I have also created this OpenAPI Bean:
 @Bean
    public OpenAPI customOpenAPI() {
        return new OpenAPI()
                .components(new Components())
                .info(new Info().title("Test")
                        .description("Test Description")
                        .version("1.0.0"));
    }

Above the RestController API Endpoint Method
,I added the following annotations
 @Operation(summary = "Send Messages to Ibm Mq", description = "Send Message to the related ibm mq")
    @ApiResponses(value = {
            @ApiResponse(responseCode = "200", description = "Success Response",
                    content = @Content(schema = @Schema(implementation = SomeClass.class), mediaType = "application/json")),
            @ApiResponse(responseCode = "500", description = "Internal System Error",
                    content = @Content(schema = @Schema(implementation = SomeClass.class), mediaType = "application/json")),
            @ApiResponse(responseCode = "400", description = "Invalid Parameter Request",
                    content = @Content(schema = @Schema(implementation = SomeClass.class), mediaType = "application/json"))
    })

All the imports came from
io.swagger.v3.oas.annotations package


text:
Q: People can see how people from different places live their lives and compare it with their own lifestyles Does this sentence look natural to native speaker? Is there any other better way to rephrase this sentence. I feel my sentence is a Little redundant

A: Repetition like this very rarely looks/sounds right in prose, and even in poetry and song only the sounds normally repeat, rather than specific words.
I would probably write this as: [Specific people] can see how people from different places live their lives ...
Where the square brackets might be Londoners, Southerners, Foreigners or something appropriate to your specific scenario.

A: You could substitute people from different place with an appropriate term like foreigner or outsider.
People can compare the lifestyle with their counterparts whom they consider foreign or strange.


text:
Q: Extract URL path segment string in PLSQL I have a table with full URLs in one field (URL_FIELD) and I want to extract the path segment of the URL. Here is an example of one URL (one cell in the table):
https://www1.ncdc.noaa.gov/pub/data/test/paleocean/sediment_files/complete/nantuck-tab.txt

The part I want is /pub/data/test/paleocean/sediment_files/complete/.
So far, I have:
SELECT SUBSTR(URL_FIELD, INSTR(URL_FIELD, '/pub', -1)) AS PATH_NAME FROM EG_VAR_UPLOAD_TEST;

which returns
/pub/data/test/paleocean/sediment_files/complete/nantuck-tab.txt

so I need to remove the part after the final forward slash (nantuck-tab.txt). I think nesting the current SUBSTR() function into another SUBSTR() function could do the trick, though I keep getting confused with all of the nested parameters. Keep in mind the section after the final forward slash varies for each URL and so does the section preceding /pub (sometimes).

A: Using REGEX_SUBSTR you can try as below:
I assume that  only final forward slash varies for each URL and so does the section preceding /pub
  SELECT REGEXP_SUBSTR (URL_FIELD, '/pub.*/') AS PATH_NAME
      FROM EG_VAR_UPLOAD_TEST;

see demo:
  SQL> SELECT REGEXP_SUBSTR (
                      'https://www1.ncdc.noaa.gov/pub/data/test/palaeocean/sedimeant_files/complete/nantuck-tab.txt'
                      ,'/pub.*/')
                      AS PATH_NAME
              FROM DUAL
       /

    PATH_NAME
    --------------------------------------------------
    /pub/data/test/palaeocean/sedimeant_files/complete

    SQL> SELECT REGEXP_SUBSTR (
                      'https://www1.ncdc.noaa.gov/pub/datttta/test/palaeocean/sedimeant_files/complete/nanttttuck-tab.txt'
                      ,'/pub.*/')
                      AS PATH_NAME
              FROM DUAL
        /

    PATH_NAME
    -----------------------------------------------------
    /pub/datttta/test/palaeocean/sedimeant_files/complete

    SQL>

A: select regexp_substr('https://www1.ncdc.noaa.gov/pub/data/test/paleocean/sediment_files/complete/nantuck-tab.txt', '^https?://[^/]+(.*/)[^/]+$', 1, 1, null, 1)
from dual;

Explanation of the regexp:

*

*^http matches "http" at the start

*s? matches the optional "s" in "https",

*:// matches the "://" after the "http"/"https",

*[^/]+ matches arbitrary number non-"/" characters after the "://",

*.*/ matches arbitrary number of arbitrary characters ending with "/", whereas the parentheses around it mark it as "subexpression #1",

*[^/]+$ matches arbitrary matches arbitrary number non-"/" characters at the end.

And then, the subsequent arguments to the regexp_substr() function are:

*

*1 is "start from position 1",

*1 is "take 1st occurence of the regexp",

*null is "no modifiers to the regexp processing",

*1 is "return the subexpression #1", which refers to the subexpression #1 defined in the actual regexp (see above).


text:
Q: Command line tool to create a pdf file with a4 sized pages from a poster pdf I am looking for a command line tool that "converts" a pdf file (whose size is larger than a4) into a single pdf file that consists of multiple a4 pages. The new pdf file, when printed, should look like the original content without scaling the original.
Searching the internet, I found pdfposter. Yet, it seems to require the size of the input pdf file which I don't know.
So, is there a tool that does that.

A: I wrote a tool that can do what you want. I explained it over at askubuntu: https://askubuntu.com/a/1155892/394569
It's called plakativ and its main interfaces is a GUI. But it also has a command line interface that allows you to do what you want including specifying borders to glue the pages together.
If you find a bug, please post it at https://gitlab.mister-muffin.de/josch/plakativ


text:
Q: How to Reduce Array to dynamic object in Powershell I have a JSON array like this:
$json = [
  {  "name": "Name",      "value": "Mike" },
  {  "name": "Age",       "value": 25 },
  {  "name": "IsMarried", "value": true }
]

Expected output is this:
{
  "Name": "Mike",
  "Age": 25,
  "IsMarried": true
}

In javascript I would do it this way:
const result = json.reduce((acc, { name, value }) => { acc[name] = value; return acc; }, {})
Question:
Is there an existing function like reduce? How can I achieve same effect?

A: To 'merge' array items like that, I would use an ordered Hashtable like below:
$json = @'
[
  {  "name": "Name",      "value": "Mike" },
  {  "name": "Age",       "value": 25 },
  {  "name": "IsMarried", "value": true }
]
'@

# create an ordered Hashtable to store the values
$combine = [ordered]@{}
($json | ConvertFrom-Json) | ForEach-Object {
    $combine[$_.Name] = $_.Value
}

# now you can leave it as Hashtable and convert it to JSON
$combine | ConvertTo-Json

# or you can convert (cast) to PsCustomObject first:
# [PsCustomObject]$combine | ConvertTo-Json

Result:
{
    "Name":  "Mike",
    "Age":  25,
    "IsMarried":  true
}


text:
Q: How to change screen resolution on linux via jenkins? I use jenkins for remote testing.
I create environmental variable and export display to linux machine running this cod in job configure
Xvfb :99 -ac &
export DISPLAY=:99

Now I want to change screen resolution there. I have try xrandr -s 1280x800 but it doesn't work.
How I can resolve this problem?

A: Xvfb :99 -ac -screen 0, 1680x1050x24 &
export DISPLAY=:99

Solve the problem

A: Better solution to add Jenkins plugin
https://wiki.jenkins-ci.org/display/JENKINS/Xvfb+Plugin


text:
Q: Get page load times from a server without a zabbix agent (cloudflare) I have a zabbix setup that monitors my servers. I also have cloudflare. I have setup monitoring for all the individual servers, but I would like to setup something to monitor response time for data served via cloudflare.
It would be a simple web page load that checks for response time, but of course I can't put zabbix agent on cloudflare!
Is there a way to do this?

A: Zabbix "web scenario" has

*

*average download speed per second for all steps of whole scenario

*download speed per second

*response time

*response code

see https://www.zabbix.com/documentation/current/manual/web_monitoring
There is also another web check, called "HTTP agent", to retrieve instead

*

*page headers and content

see https://www.zabbix.com/documentation/current/manual/config/items/itemtypes/http
both are executed by Zabbix Server / Proxy, no agent needed.


text:
Q: shared memory producer consumer in C I have to implement a producer-consumer problem via shared memory and semaphores. It should takes input from input.txt file and save it to output.txt file. Process of saving information should be showed in terminal. I have a problem with, I guess, synchronization. When I call fork() and then execl() producer.c file inside, the program seems to be not responding. producer(at least) was working before, but during modifying some lines of code it stopped working and I can't solve it. Here's the piece of code:
#include <stdio.h>      // main.c
#include <stdlib.h>
#include <unistd.h>
#include <sys/wait.h>
#include <time.h>
#include "semaphore.h"
#include "memory.h"

#define SIZE 10

typedef struct cyclicalBuf
{
    int size;
    char bufor[SIZE];
}   cyclicalBuf;

int main(int argc, char *argv[])
{
    if(argc != 1)
    {
        perror("Need no arguments!");
        exit(1);
    }

    int semid;
    int memoryID;

    int key;

    key = semGetKey('A');
    semid = semCreate(key, 2); // 2 sem made

    setVal(semid, 0, SIZE);
    setVal(semid, 1, 0);

    memoryID = memoryCreate('A', sizeof(cyclicalBuf));

    pid_t pid;
    pid = fork();

    switch(pid)
    {
        case -1:
            perror("fork() error in producer section");
            exit(2);
            break;
        case 0:
            execl("./producer", "./producer", NULL);
            perror("execl() error in producer section");
            exit(3);
            break;
        default:
            break;
    }

    sleep(1);

    switch(pid)
    {
        case -1:
            perror("fork() error in consumer section");
            exit(4);
            break;
        case 0:
            execl("./consumer", "./consumer", NULL);
            perror("execl() error in consumer section");
            exit(5);
            break;
        default:
            break;
    }

    int i;
    for(i = 0; i < 2; i++)
    {
        if(wait(0) < 0 )
        {
            perror("wait() error [main.c]");
        }
    }

    semDelete(semid, 2);

    memoryDelete(memoryID);

    return 0;
}

#include <stdio.h>        // producer.c
#include <stdlib.h>
#include <unistd.h>
#include <time.h>
#include "memory.h"
#include "semaphore.h"

#define SIZE 10

typedef struct cyclicalBuf
{
    int size;
    char bufor[SIZE];
} cyclicalBuf;

void producer()
{
    FILE *fp;
    int i;
    int semid;
    int memoryID;
    cyclicalBuf * buf;
    char c;

    if((fp = fopen("./input.txt", "r")) == NULL)
    {
        perror("fopen() error [producer]");
        exit(1);
    }

    int key;

    key = semGetKey('A');
    semid = semCreate(key, 2); y

    memoryID = memoryAccess('A');

    buf = (cyclicalBuf *)memoryLink(memoryID);

    printf("Producer: ");

    for(i = 0; (c = fgetc(fp)) != EOF; i++)
    {

        semRelease(semid, 0);

        usleep(rand()%5555);

        buf->bufor[i%SIZE] = c;

        buf->size++;

        semAcquire(semid, 1);

        printf(" %c", c);
    }

    if(fclose(fp) == EOF)
    {
        perror("fclose() error [producer]");
        exit(2);
    }

    memoryUnlink(buf);
}

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

    if(argc != 1)
    {
        perror("Need no arguments!");
        exit(3);
    }

    srand(time(NULL));

    producer();

    return 0;
}

#include <stdio.h>   // consumer.c
#include <stdlib.h>
#include <unistd.h>
#include <time.h>
#include <sys/sem.h>
#include "memory.h"
#include "semaphore.h"

#define SIZE 10

typedef struct cyclicalBuf
{
    int size;
    char bufor[SIZE];
} cyclicalBuf;

void consumer()
{
    FILE *fp;
    int c_cnt = 0;
    int i = 0;
    int semid;
    int memoryID;
    cyclicalBuf * buf;
    char c;

    if((fp = fopen("./output.txt", "w")) == NULL)
    {
        perror("fopen() error [consumer]");
        exit(1);
    }

    int key;

    key = semGetKey('A');
    semid = semCreate(key, 2);

    memoryID = memoryAccess('A');

    buf = (cyclicalBuf *)memoryLink(memoryID);

    printf("Consumer: ");

    while(!((semctl(semid, 0, GETVAL) == SIZE) && (c_cnt == buf->size)))
    {

        semRelease(semid, 1);

        usleep(rand()%5555);

        c = buf->bufor[i%SIZE];

        semAcquire(semid, 0);

        fputc(c, fp);

        printf(" %c", c);

        i++;
        c_cnt++;
    }

    if(fclose(fp) == EOF) //
    {
        perror("fclose() error [consumer]");
        exit(2);
    }

    memoryUnlink(buf); //
}

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

    if(argc != 1)
    {
        perror("Need no arguments!");
        exit(3);
    }

    srand(time(NULL));

    consumer();

    return 0;
}

I can provide semaphore and shared memory functions if needed.
OUTPUT:
./main
|  --> this is just blinking cursor, nothing happens


text:
Q: Table header column background color not changing I am using ASPOSE Slides in my project to perform a PPT task. I want to change my table header background-color but I have not found any solutions in Aspose forum for it. Can anybody provide me with the solution?
            ISlide sld = press.Slides[0];
            double[] dblCols = { 250, 250};
            double[] dblRows = { 70, 70, 70,70 };
            // Add table shape to slide
            ITable tbl = sld.Shapes.AddTable(100, 100, dblCols, dblRows);
            tbl[0, 1].TextFrame.Text = "some text";
            tbl[0, 2].TextFrame.Text = "some text";
            tbl[0, 3].TextFrame.Text = "some text";
            tbl[0, 3].BorderBottom.FillFormat.FillType = FillType.Solid;
            tbl[0, 3].FillFormat.SolidFillColor.BackgroundColor = Color.Blue;
            tbl[0,3].BorderBottom.Width = 2;

            Portion portion = (Portion)tbl[0, 1].TextFrame.Paragraphs[0].Portions[0];
            portion.PortionFormat.FillFormat.FillType = FillType.Solid;
            portion.PortionFormat.FillFormat.SolidFillColor.Color = Color.Black;

}

A: I have observed you requirements related to setting table header background. Please try using following sample code that has example of setting fill color for one of header row cell. You can replicate the same for other cells too.
public static void TestTableBackground()
{
    Presentation press = new Presentation();
    ISlide sld = press.Slides[0];
    double[] dblCols = { 250, 250 };
    double[] dblRows = { 70, 70, 70, 70 };
    // Add table shape to slide
    ITable tbl = sld.Shapes.AddTable(100, 100, dblCols, dblRows);
    tbl[0, 1].TextFrame.Text = "some text";
    tbl[0, 2].TextFrame.Text = "some text";
    tbl[0, 3].TextFrame.Text = "some text";
    tbl[0, 0].FillFormat.FillType = FillType.Solid;
    tbl[0, 0].FillFormat.SolidFillColor.Color = Color.Blue;

    Portion portion = (Portion)tbl[0, 1].TextFrame.Paragraphs[0].Portions[0];
    portion.PortionFormat.FillFormat.FillType = FillType.Solid;
    portion.PortionFormat.FillFormat.SolidFillColor.Color = Color.Black;

    press.Save(@"C:\Aspose Data\TableFormat.pptx", Aspose.Slides.Export.SaveFormat.Pptx);
}

I am working as Support developer/ Evangelist at Aspose.


text:
Q: Android buttons in xml with onClickListeners, have to click a second time for the button to Click Have tried various solutions including those in here:
Have to click a button twice for it to work in Android Studio and here:
I have to click the button twice for it to work
And have tried " android:focusableInTouchMode="false" " on the buttons in the xml file which did not work either.
My current code is as follows:
SplashActivity.java
//THIS BIT IS IN THE ONCREATE METHOD
    Button enterButton = (Button) findViewById(R.id.enter_button);
    enterButton.setOnClickListener(OnClick);

    Button bookButton = (Button) findViewById(R.id.book_button);
    bookButton.setOnClickListener(OnClick);

}

//THIS BIT IS OUTSIDE OF THE ONCREATE METHOD
private OnClickListener OnClick = new OnClickListener() {

    public void onClick(View v) {
        Intent intent = new Intent(SplashActivity.this, MainActivity.class);
        switch (v.getId()) {
            case R.id.enter_button:

                handler.removeCallbacksAndMessages(null);
                startActivity(intent);

                break;
            case R.id.book_button:

                handler.removeCallbacksAndMessages(null);
                intent.putExtra("source", "onClick");
                startActivity(intent);

                break;
            default:
                break;
        }
    }
};
}

activity_splash.xml
        <LinearLayout
            android:layout_width="wrap_content"
            android:layout_height="wrap_content"
            android:orientation="horizontal"
             >

            <Button
                android:id="@+id/enter_button"
                android:theme="@style/AppTheme.DevButton"
                android:layout_width="100dp"
                android:layout_height="50dp"
                android:text="Enter"
                android:stateListAnimator="@null"
                />

            <Button
                android:id="@+id/book_button"
                android:theme="@style/AppTheme.DevButton"
                android:layout_width="100dp"
                android:layout_height="50dp"
                android:text="Book"
                android:stateListAnimator="@null"
                />

    </LinearLayout>

Really can't work out how to work around this!
UPDATE to - activity_splash.xml
So I've narrowed this down to the Java file, it doesn't seem to be the xml code causing the issue as I've trimmed down the xml file to the following and the symptoms are the same:
<LinearLayout xmlns:android="http://schemas.android.com/apk/res/android"
    android:layout_width="match_parent"
    android:layout_height="match_parent"
    android:orientation="vertical"
     >

            <Button
                android:id="@+id/enter_button"
                android:layout_width="100dp"
                android:layout_height="50dp"

                />

            <Button
                android:id="@+id/book_button"
                android:layout_width="100dp"
                android:layout_height="50dp"
                />

</LinearLayout>

A: I would normally extend SplashActivity to include View.OnClickListener and implement
Button button = (Button)findViewById(R.id.button);
button.setOnClickListener(this);

@Override
public void onClick(View view_) {
    ...
}

Not sure if this would make a difference or not?

A: I think the focus is the parent view so add the android:descendantFocusability= attribute to your parent view

A: So after all of the testing I've managed to find out what the problem was.
It was this line of code here which helps with display the image as full screen:
getWindow().getDecorView().setSystemUiVisibility(View.SYSTEM_UI_FLAG_HIDE_NAVIGATION);

The SYSTEM_UI_FLAG_HIDE_NAVIGATION flag does not register touch events so you need to change it to SYSTEM_UI_FLAG_IMMERSIVE so it reads as follows:
getWindow().getDecorView().setSystemUiVisibility(View.SYSTEM_UI_FLAG_IMMERSIVE);

Note however this flag was only released after Android 4.4 API Level 19 so won't work in Android versions before this.
Thanks guys for looking into this as well for me, most appreciated.


text:
Q: Indicate a function has no side effects Member functions in C++ may be qualified as const to guarantee that they don't alter this, but I don't know of anyway to show that a function in general does not cause any changes to any data anywhere.
This would be helpful information to be able to put in a function signature, but I don't know of any way to accomplish this. How can I qualify a function as having no side effects in C++, preferably something not compiler specific but that may be too much to ask
Bonus points if there is a way that works for C as well.


text:
Q: Angular.js / Ionic make Tab-Button only clickable if var is set how is it possible to not let the user click on the tab-bar, before a scope variable is set. The first view in my app is a view, where you can choose your city. The other Tabs (which uses the value of "city") should only be clickable after the user selects that city. The city is stored in $rootScope.selectedCity and this is the state where the city is needed:
.state('tab.friends', {
      url: '/friends/:selectedCity',
      views: {
        'tab-friends': {
          templateUrl: 'templates/tab-friends.html',
          controller: 'FriendsCtrl'
        }
      }
    })

Any suggestions for only making the tabs clickable after the user selects the city? Ty

A: You can handle ion-tab click by using on-select attribute, see : DOCS

on-select
  (optional) |
  expression
  Called when this tab is selected.

In addition ion-tab supports ng-click as well: See $ionicTabsDelegate usage


text:
Q: Improve the build speed of Visual Studio 2019 Does any one face long time build process to run a website with visual studio 2019 and asp.net?
I tried to Free up some space in the disk and End up some tasks to free RAM memory, clear visual studio cashe but the peoblem still
Any suggestion regarding this issue, it is so frustrating to develop with such speed.
SOLVED
This was solved by setting source control to None and disable stratup in the task manager and followed the instructions posted below

A: @ Nadin Martini.
For improving the build speed of Visual Studio 2019, some attributes can be applied as follows:

*

*Set Current source control plug-in to None under "Tools" -> "Options"->"Source Control ".

*Uncheck Synchronized Visual Studio settings across devices under "Tools" -> "Options"->"Environment " ->"Accounts "

*Uncheck Enable CodeLens under "Tools" -> "Options"->"Text Editor " ->"All Languages ".

*If you have hardware acceleration enabled, or if you use the default visual experience settings you may experience intermittent performance issues, product crashes, or rendering issues.
You could apply the following settings under  "Tools" -> "Options"->" Environment " ->" General ".

*Delete the contents of the following directories:
Clean the content in WebSiteCache folder
(can be found in C:\Users%USERNAME%\AppData\Local\Microsoft\WebSiteCache).
Clean the content in Temporary ASP.NET Files folder
(can be found in C:\Users%USERNAME%\AppData\Local\Temp\Temporary ASP.NET Files)
For more information, you can visit here.


text:
Q: where can I find default inputrc/key-bindings config on macOsX? I know that I can add an .inputrc file in my home folder, but for studying purposes, I would like to see the default key-bindings (actually the default inputrc conf) used by my system.
Is that possible?

A: From the Mac Developer Library:
The standard key bindings are specified in /System/Library/Frameworks/AppKit.framework/Resources/StandardKeyBinding.dict. These standard bindings include a large number of Emacs-compatible control key bindings, all the various arrow key bindings, bindings for making field editors and some keyboard UI work, and backstop bindings for many function keys.
To customize bindings, you create a file named DefaultKeyBinding.dict in ~/Library/KeyBindings/ and specify bindings to augment or replace the standard bindings. You may use the standard bindings file as a template. It is recommended that you use the Property List Editor application to edit a bindings dictionary. You may use another application such as TextEdit or Xcode, but if you do you must ensure the encoding of the saved file is UTF8.

A: bind -P

and even better:
bind -p > .inputrc

was what I was looking for.


text:
Q: Programmatically check profile login hours I need to create a routine that records the accumulated amount of time spent by the user when he changes the case status from A to B, but i need to take in account the login hours of his profile to get the real spent time to treat the case.
My question is, is possible to programatically check the login hours configured in his profile to do the correct calculations?
If so, in which object it would be available to use in apex?
Thanks in advance.
Best regards.

A: My guess is that this information is stored under a table called LoginHours. This Sobject is currently not accessible via Apex. I would recommend storing this information somewhere else in Salesforce (maybe custom setting or new Sobject) so you can query out later and do your proper logic against.


text:
Q: what is difference between Borel algebra and Borel σ-algebra? I am a university student, professor gave us definitions of Borel algebra and Borel σ-algebra. In Wikipedia they are the same see here.
but professor defined Borel algebra as:
let $\Omega$ be $[a,b)$ set on real line. Borel algebra on $\Omega$ is finite intersection of such $[c1,c2), [c1,c2], (c1,c2], (c1,c2)$ intervals.(in wikipedia it is not finite it is countable, please help me which one is correct).
are in fact Borel algebra and Borel σ-algebra same? please give me real definitions.

A: Algebras are closed under finite unions and intersections;
$\sigma$-algebras are closed under countable unions and intersections.
The other requirements are that algebras include $\Omega$ and $\emptyset$, and are closed under complementation.
Borel algebras are a particular example, i.e. with the half open intervals serving as a subbase.

A: For instance consider $\Omega = \mathbb{R}$. Let $\mathcal{I}$ be the collection of all half open intervals $]a,b]$ with $a < b$. The $\sigma$-algebra generated by $\mathcal{I}$ is the smallest $\sigma$-algebra containing all sets in $\mathcal{I}$. Such a $\sigma$-algebra always exists. That one is called the Borel $\sigma$-algebra.
It contains at least all other types of intervals because
$$]a,b[ = \displaystyle\bigcup\limits_{m\geq k}\left(\left]a,b-\dfrac{1}{m}\right]\right)$$
as a countable union. Hence it also contains all sets
$$[a,b[ = \displaystyle\bigcap\limits_{m\in\mathbb{N}_0}\left(\left]a-\dfrac{1}{m},b\right[\right)$$
and also all sets
$$[a,b] = \displaystyle\bigcap\limits_{m\in\mathbb{N}_0}\left(\left[a,b+\dfrac{1}{m}\right[\right)$$
as countable intersections.
Hope this helps,


text:
Q: how to paginate ElasticSearch results using PHP API following the example in the docs, I search in my type like that:
    $params = [
        'index' => $this->index,
        'type' => $this->type,
        "scroll" => "30s",
        "size" => 10,
        'body' => $json
    ];

    $response = $this->es->search($params);

now $response includes 10 results and a _scroll_id. How can I use it to paginate my results? I am looking at this example
https://www.elastic.co/guide/en/elasticsearch/client/php-api/current/_search_operations.html#_scrolling
then the doc suggests to do:
while (isset($response['hits']['hits']) && count($response['hits']['hits']) > 0) {
$scroll_id = $response['_scroll_id'];
$response = $client->scroll([
        "scroll_id" => $scroll_id,  //...using our previously obtained _scroll_id
        "scroll" => "30s"           // and the same timeout window
    ]
);
}

but not clear if I have to do a new request or if the while loop is meant to store all the results in a variable and pass it to the template.
Any practical example to show?
thanks

A: After first request with scroll parameter, you will receive normal payload (_shards, took, hits, etc) and _scroll_id as well from elasticsearch. In hits you will have total number of found documents, hence you have: items per page and total count of items.
To figure out counts of pages - you need to do simple math.
To receive next batch of data from elasticsearch - run this:
curl 'localhost:9200/_search/scroll ' -d '{
    "scroll" : "30s",
    "scroll_id" : "cXVlcnlUaGVuRmV0Y2g7NTsxMzU0MDQzNjY6QnNHMjd0bXlTZ3Ftd1dkblRUd3NQZzsxMDE1NzI4Mjc6ajFzVmtLQUdSaEduRWFRVi1GZE05UTsxMDE1NzI4MjY6ajFzVmtLQUdSaEduRWFRVi1GZE05UTsxMDE1ODAzODc6TURuUG5nbzRUVU9NUUFjSERqM2hIQTsxMDE1ODAzODg6TURuUG5nbzRUVU9NUUFjSERqM2hIQTswOw=="
}'

With scroll you can only receive next batch, you can't jump on particular page.


text:
Q: Sort with case-sensitivity (lowercase before uppercase) in macOS in the Terminal I am trying to use the answer in GNU Sort by case-sensitive to sort a file in my Mac OS.
My file.txt looks like this:
"Best"
"A"
"BEST"

In the second answer to the mentioned question, it says that one can do:
echo -e "d\nD\nc\nb\nB\na" | sort --ignore-case file.txt

and the output should be:
"A"
"Best"
"BEST"

However, when I do it in my computer, I get:
"A"
"BEST"
"Best"

It does not matter if I use the --ignore-case or not, the output is the same.
Maybe LC_COLLATE=C can not be set in Mac OS?
Does someone know how to use sort and have lowercase < uppercase in Mac OS?
EDIT
@jaume recommended installing coreutils and using the GNU sort. I tried brew install coreutils and then gsort -f file.txt but still had no luck.

A: Sort order is defined in your locale.
locale
LANG="en_US.UTF-8"
LC_COLLATE="en_US.UTF-8"
LC_CTYPE="en_US.UTF-8"
LC_MESSAGES="en_US.UTF-8"
LC_MONETARY="en_US.UTF-8"
LC_NUMERIC="en_US.UTF-8"
LC_TIME="en_US.UTF-8"
LC_ALL=

When LC_COLLATE is defined as LC_COLLATE="en_US.UTF-8" on macOS, LC_COLLATE uses the C or POSIX definiton. The default behavior of sort is to sort in ascii order where uppercase has precedence over lowercase.
On Linux, when  LC_COLLATE="en_US.UTF-8" the LC_COLLATE definiton is non-standard. The default behavior of sort is to ignore-case and lowercase has precedence over uppercase.
To mimic Linux default sort behavior on macOS, You can use tr to "translate" lowercase letters to uppercase and uppercase to lowercase, sort with the ignore-case option (-f), then change the case back again.
tr 'a-zA-Z' 'A-Za-z' <file.txt | sort -f | tr 'a-zA-Z' 'A-Za-z'

EXAMPLE:
cat file.txt
"cat"
"Best"
"A"
"BEST"
"Castro"
"alfred"
"a"
"CAT"

tr 'a-zA-Z' 'A-Za-z' <file.txt | sort -f | tr 'a-zA-Z' 'A-Za-z'
"a"
"A"
"alfred"
"Best"
"BEST"
"Castro"
"cat"
"CAT"


text:
Q: using Regular Expression in Group by Clause I have a table 'items'
Item_Code             |Rate  |Quantity
--------------------------------------
JOGGER-POWER-BLACK    |699   |5
JOGGER-POWER-WHITE    |599   |8
JOGGER-PLAZA-WHITE    |1199  |2
SLEEPER-PLAZA-BLACK   |699   |6
SLEEPER-POWER-BLACK   |499   |5

I want to Group by Part1-%-Part3 of Item_Code like following which is just idea
select (part1 and part3 of Item_Code) as 'Category-Color',sum(Quantity)
as Quantity group by (part1 and part3 of Item_Code)

By Parts I mean looking Item_Code in terms of Hyphen
Desired Output
Category-Color|Quantity
-------------------
JOGGER-BLACK  |5
JOGGER-WHITE  |10
SLEEPER-BLACK |11

"regular expressions in group by clause","group by with regular expression". Google/Bing giving nothing relevant
I am unable to understand whether database developers are not required to  provide this feature or how they do it. I am required such grouping by the Store owner. e.g Category (Part1) wise Sum of quantities.

A: SELECT CONCAT(SUBSTRING_INDEX(Item_Code, '-', 1), '-',
              SUBSTRING_INDEX(Item_Code, '-', -1)) AS Category_Color,
       SUM(Quantity) AS Quantity
FROM items
GROUP BY 1;

Example: SQLFiddle


text:
Q: group multiple apps under the same icon in Application launcher I want to group multiple apps under the same icon in the application launcher.
For example, 5 apps each displaying 1 different image. But those 5 apps should appear as separate apps on the Android market, therefore they need to have different package name.
But different package name, means that on the Android device they will appear as 5 separate apps in the application launcher, which I am trying to avoid.
The closest solution that I found is to listen for PACKAGE_ADDED broadcast event, and every time another app from those 5 are installed on the device, all  the already installed apps would call setApplicationEnabledSetting from PackageManager to hide their icons and let the app that was just installed to handle things.
But the icons are hidden only after rebooting the device.
Is there a way to force the application launcher to refresh at runtime?
Or is there any other way to solve my goal?
I am running out of options. Thanks!

A: Miha,
What about having one main application, with the other 4 being add-ons (i.e., not shown in the launcher)?  You would then have only one launcher icon, and the other applications would be started from the main app.  By checking whether the other apps were installed, you could adjust your buttons/views accordingly.
As far as I know, there is no way to force the launcher to refresh.  However, you could implement your applications as you described -- having each app hide it's icon when I new one is installed.  The user would get an application not installed error though, which is probably not something you want.
Personally, I used the first method: have a main keyboard and then install add-ons which can then be loaded from the main app.
Hope this helps.


text:
Q: How to run path setting script in vscode terminal at startup? I have a script which sets path variables. I have to run this script manually every time I start a new terminal instance.
I am looking for an automated way to run this script at startup for every terminal instance.
I have tried the below approach which doesn't work
{
  "terminal.integrated.profiles.windows": {
    "Command Prompt": {
      "path": "cmd.exe",
      "args": [
         "-noexit",
         "-file",
         "h:\\all-languages-env.cmd"
      ]
    }
  },
  "terminal.integrated.defaultProfile.windows": "Command Prompt",
}

I am expecting the script h:\all-languages-env.cmd to run at every terminal(Command Prompt) startup.
The script file is as below
@ECHO OFF
call devtools isSupported nodejs 16.13.0 || exit /B %ERRORLEVEL%
call devtools isSupported phantomjs 2.1.1 || exit /B %ERRORLEVEL%
set npm_config_registry=http://example.com
set npm_config_user_agent="npm/{npm-version} node/{node-version} {platform} {arch} | NDS %USERNAME% %COMPUTERNAME%"
set SASS_BINARY_SITE=http://example.com/node-sass
set SPAWN_WRAP_SHIM_ROOT=H:\.nodejs
set CHROME_BIN="C:\Program Files (x86)\Google\Chrome\Application\chrome.exe"
set npm_config_prefix=H:\.nodejs\npm\8
set npm_config_cache=H:\.nodejs\npm\8\cache
set npm_config_tmp=H:\.nodejs\npm\8\tmp
set NODEJS_16_13_0=H:\nodejs\16
set PATH=%NODEJS_16_13_0%;H:\.nodejs\npm\8;%PATH%
type nul > H:\nodejs\16\lastUsed
set PHANTOMJS_2_1_1=H:\phantomjs\2\bin
set PHANTOMJS_BIN=%PHANTOMJS_2_1_1%\phantomjs.exe
set PATH=%PHANTOMJS_2_1_1%;%PATH%
type nul > H:\phantomjs\2\lastUsed
ECHO javascript environment set

A: cmd.exe uses different arguments
{
  "terminal.integrated.profiles.windows": {
    "Command Prompt": {
      "path": "cmd.exe",
      "args": [
         "/K",
         "h:\\all-languages-env.cmd"
      ]
    }
  },
  "terminal.integrated.defaultProfile.windows": "Command Prompt",
}


text:
Q: Java JSON deserialize String with property names as field names I am receiving from API json like that:
{
  "channel":"masta",
  "startTime":1427673600000,
  "endTime":1427760000000,
  "totalUniques":1,
  "totalViewtime":1927,
  "totalViews":13,
  "totalCountries":1,
  "countries":{
    "US":{
      "uniques":1,
      "views":13,
      "viewtime":1927
    }
  }
}

Now I want to deserialize it to class, so this class(Stats) will have fields like channel, startTime and so on.
But how to handle countries property?
I thought about making class Countries but not sure about that cause it's have "US" as property name. Not "country": "US". And what's more it has own parameters. How to deserialize it?
Mostly I am using ObjectMapper object.readValue(jsonString) to do that but don't know how to handle 'countries'. In example is just one country 'US' but can be more.

A: Declare Country class:
public class Country {
    private int uniques;
    private int views;
    private int viewtime;

    public int getUniques() {
        return uniques;
    }

    public void setUniques(int uniques) {
        this.uniques = uniques;
    }

    public int getViews() {
        return views;
    }

    public void setViews(int views) {
        this.views = views;
    }

    public int getViewtime() {
        return viewtime;
    }

    public void setViewtime(int viewtime) {
        this.viewtime = viewtime;
    }
}

In your Stats class you should declare countries as map of Country objects:
public class Stats {

   private String channel;
   private Long startTime;
   private Long endTime;
   private int totalUniques;
   private int totalViewtime;
   private int totalViews;
   private int totalCountries;

   ...

   private Map<String, Country> countries;

   public Map<String, Country> getCountries() {
       return countries;
   }

   public void setCountries(Map<String, Country> countries) {
       this.countries = countries;
   }

}

Now you can deserialize you object:
ObjectMapper mapper = new ObjectMapper();
Stats stats = mapper.readValue(jsonString, Stats.class);

After deserialization your Stack object will get map with one Country object with key "US".

A: Basically, you need to define a POJO like ViewInfo that has the attributes like channel, startTime, endTime and so on. countries is also another attribute, but it isn't a primitive, it's like a map with country code as the key and Country as another POJO (which has attributes like uniques, views and so on). This way, you should be able to deserialize the json into this pojo.


text:
Q: Need help to prove pigeonhole problem If we pick n+1 different positive integers with every integer is less than 2n. Prove that we can always find three numbers among these n+1 numbers that one is equal to the sum of the other two numbers.
These n+1 numbers will be chosen from 1 to 2n-1 totally 2n-1 choices. I am trying to do it by using the pigeonhole principle but I don't know how to set pigeons and holes in this case. Can someone help me? Thanks

A: hint: let the largest number in the set be $k<2n$.
Apply pigeonhole principle to the pairs of numbers which add up to $k$.


text:
Q: Can I name elements within components anything I want? If I have lets say App component, like this
    const App = () => {
         return(

hello world

)}

can I name div whatever i want like I did below? It works in the browser just fine but Im not sure,
      const App = () => {
           return(
                <whatever>

hello world

                </whatever>)}

A: Yes you can name them whatever you like, people often do it so the markup is a bit more friendly to read and understand. For example Appcues injects their widget into your website and if you look at the markup for it, it has elements like <appcues/>.
Just check the browser support for these custom HTML tags, I think most major ones do support it but just to be safe.

A: Yes You can. But:

*

*if You want to work with React, don't capitalize the name of div like this: <Whatever>, because it will seems to React that this is an another Component.

*And when Your project gets bigger, it will start to get more complicated, so its a good practice to write tags by they names.


text:
Q: Inserting and Ammending Text in ini file in CHEF I've just started using CHEF at work and I've been asked to download a package to a Linux host, unpack it, apply the license and start it.
As part of the unpack an ini file is created that should contain the license info. The license file itself is the same as the ini files [license] section but it also contains further detail in other sections.
What I would like to do is search the ini file for license block then insert the detail from the license file in to it.
So the ini file looks something like this initially
[Licence]
;You have to complete this section to start

[users]
admin=admin

[roles]
admin = admin, operate, user

[modules]

My license file would be like this
[licence]
Serial=123456789
baa=3 bags full
Key=123456789
ExpireDate=2016-06-10 00-00-00r

I don't know the best way to do this in CHEF. I've got a couple of questions

*

*Should I use a template with values and create it in my recipe?

*Can I do it using Ruby and how would I get that into my recipe?

*How do I check the line exists already and make sure I don't overwrite it?

Thanks for your help

A: The best way to do this is in Chef is to manage the entire file, and use a template resource. If you really want to try your 2nd or 3rd bullet points,  check out the line cookbook for some examples of file editing in-place (and using not_if to guard against appending lines twice).
To re-iterate, though -- manage the whole file with chef using a template. That's the most idiomatic way to do this in Chef.


text:
Q: ¿Como puedo validar 2 referencias o 2 botones de un campo estado de mi DB, cada que ingreso nuevos valores se mantiene en cancelado, y no quiero eso
como puedo validar estas 2 referencias?, cuando registro un nuevo estado automaticamente se pasa a cancelado pero lo que yo quiero es que se mantenga en pendiente, despues de darle click recien diga que se ha cancelado

                                @if ($chica->estado == 'PENDIENTE')

                                        <a class="btn btn-warning" href="{{
                                    route('cambio.estado.chicas', $chica) }}"
                                            title="Pendiente"
                                Pendiente

                                @else

                                            Cancelado

                                @endif

este es mi controller
public function cambio_de_estado($id)
{
    $chica = Chica::findOrFail($id);
    $chica->estado = 'CANCELADO';
    $chica->update();
    return redirect()->back()->with('cancelado', 'VENTA CANCELADA.');
}

base da datos
$table->enum('estado', ['PENDIENTE', 'CANCELADO'])->default('PENDIENTE');


text:
Q: How can I specify a Default value dynamically in Jersey? I am using Java Jersey library to create RESTful web service.
I am using query param for method. I want to specify the Default value for that query param. If I specify a constant string, then it is fine. But how can I specify a runtime value as the default value?
import javax.ws.rs.DefaultValue;
import javax.ws.rs.GET;
import javax.ws.rs.Path;
import javax.ws.rs.Produces;
import javax.ws.rs.QueryParam;
import javax.ws.rs.core.MediaType;

@Path( "Hello" )
public class HelloWorld
{
    private String defaultValue = "Default";

    @GET
    @Produces( MediaType.APPLICATION_XML )
    public String greet( @QueryParam( "User" ) @DefaultValue( "defaultValue" )String userName )
    {
        String returnValue = "Hello " + userName;
        System.out.println( returnValue );
        return returnValue;
    }
}

Instead of a constant how can I use a variable here? Is it possible at all?

A: No, it is not possible - at least not using the annotation. Can you say more about why you need to do that? Maybe I can then suggest some alternative approach.

A: Not sure if this is what you were looking for but did you tried to make the default value final?
final String defaultValue = "Default";

It works for me.


text:
Q: When refreshing the result of a view? I materialize the result of a view in a table.
I want to know if their is a way to know when the result of this view change to refresh it.
Materialized view and result cache can do that but I don't want to use both techniques.
Is their another way to answer to this question?
In fact we have a generic system who materialize and refresh views every n minutes. The cost for the refresh could be high and I try to know if we can know if underlying data has change or not.
We don't use materialized view because full refresh truncate the table and fast refresh work only on table with primary key.
Result cache can't do the job to because we don't have enough memory for that.
So I want to know if we could have a technique to know if underlying data of the view has change since last refresh

A: You could have a flag table that looks something like this:
CREATE TABLE FlagTable
  SourceTable varchar(30),
  UpdateDate DATETIME,
  Handled CHAR(1) DEFAULT 'N'

Create a trigger on your base tables, where on INSERT, UPDATE, or DELETE of the table, you insert a record into FlagTable with the name of the base table
When you want to check for a refresh, just select WHERE Handled = 'N', refresh the pseudo-view, then set Handled = 'Y'

A: You can do all this in an easier way, by setting the mat_view with refresh on commit option and if possible, also to make it refresh fast on commit. This will guarantee you that each time a change occurs the view will refresh only the new lines (compared to complete refresh, where the query behind the view is executed as a whole).
Now this last method can cause a lot of problems, because the refresh fast on commit option has limitations and if you can't comply with it, you just can't use it. If you can however set this to refresh complete on commit, this can either slow the system as you suggested happens from time to time and also suggests that you can't isolate the source of change.
If you want to see where the most frequent change occurs, I suggest you to use a custom table (per day) where to store the daily result of the query behind the mat_view. Then after a few days, just do something like:
select * from daily_table_day_one
minus
select * from mat_view
union all
select * from mat_view
minus
select * from daily_table_day_one

as the method with ORA_ROWSCN not always works. The method with the triggers works in limited cases and if it isn't required to create those triggers on like 100 tables ... that's ludicrous.
When you find the source of change - for example several columns, coming from some tables, then you might consider rewriting the mat_view query, following some DW principles and create a star schema of the query. This will segment the query and will most certainly speed-up the query. Check where the load is coming from - if those expensive joins, scans whatever can't be avoided, maybe breaking down the query on smaller queries can do the trick if you can materialize them as well, maybe you can set them with refresh fast on commit as well.
It all depends on the implementation. If you can give here an example of the query or a part of it,with the explain plan we can also give you concrete solutions to it.
cheers

A: This is only an heuristic, but as part of your view refresh procedure, you could query and store the max ora_rowscn and row count from your source table(s). Then periodically check those values to see if some of these tables have changed.
select MAX(ora_rowscn), COUNT(*)
  into last_change_scn, last_change_length
  from src_table;

If I'm not too wrong, is there was any insert or update in your table, MAX(ora_rowscn)  would change. And if there was some delete, COUNT(*) would change.
On the dark side, querying MAX(ora_rowscn) will trigger full table scan. And of course, this can't tell you if those changes will or will not impact the view.


text:
Q: Probability of default for a portfolio vs for individual accounts I have question on probability of default as it relates to a set of loans vs individual loans. I am unable to reconcile the following two viewpoints:
Let's say I have 100 loans and I observe 20 defaults and hence, I define my PD to be 20%. Basis this, I want to know what is the probability of default for a particular loan.
I came up with the following two setups:
Setup 1
I simply run some simulations and find the number of loans that default on average. Here's some R code:
N <- 100
nDef <- 20
pd <- nDef/N

nRandom <- 10000
out <- NULL

for(i in 1:nRandom){
  r <- rbinom(N, 1, pd)
  out <- rbind(out, table(r))
}

apply(out, 2, median)

The output is 0: 80, 1: 20 which supports the idea that on average I expect a particular loan to default with a probability of 20%.
Setup 2
I could think of doing this another way: (R code below)
(pd^n * (1-pd)^(N-n)) * choose(N, n)

But doing this gives me ~10% - What am I doing wrong here?

A:
trying to find the probability of observing 20 bad loans out of 100

If the probability that a given loan turning out to be bad is $\text{constant}$ 20% then you can calculate the probability to get $n$ bad loans if you select $N$ loans. This can be made by using the binomial distribution.
$$P(X=n)=\binom{N}{n}\cdot 0.2^n\cdot (1-0.2)^{N-n}$$
Thus the probability to observe 20 bad loans out of 100 is
$$P(X=20)=\binom{100}{20}\cdot 0.2^{20}\cdot (0.8)^{80}\approx 9.93\%$$
But you can calculate the probability to observe 57 bad loans out of 100 as well, for instance.

what is the probability of say a given loan turning out to be bad

This constant probability is an assumption, which has to be made to apply the binomial distribution above. The condition is that you have a large number  of loans (population). In this case the ratio of number of bad loans and number of all loans at the population is $20\%$. Then the probability that you draw a bad loan at every drawing is approximately $pd=0.2$, if the population is large. If the population is not large, then you have to use the $\text{hypergeometric distribution}$.


text:
Q: Proof of equation with gcds I was given this problem by a friend and am unable to solve it.
Given $x$ is an even integer, prove that $$\frac{x^3}{2}-x^{5/2} \leq x(x-\gcd(x,1))+x(x-\gcd(x,2))+x(x-\gcd(x,3))+\cdots+x(x-\gcd(x,\frac{x-2}{2}))+x(x-\gcd(x,\frac{x}{2}))\leq \frac{x^3}{2}.$$
I tried it out for 2-12 and indeed it does work. I have not yet tried out an induction proof so that might be possible. However, I am not even able to simplify anything except the last term.

A: The inequality
$$\frac{x^3}{2}-x^{5/2} \leq x(x-\gcd(x,1))+x(x-\gcd(x,2))+x(x-\gcd(x,3))+\cdots+x(x-\gcd(x,\frac{x-2}{2}))+x(x-\gcd(x,\frac{x}{2}))\leq \frac{x^3}{2}$$
is equivalent to the inequality
$$\frac{x^2}{2}-x^{3/2} \leq (x-\gcd(x,1))+(x-\gcd(x,2))+(x-\gcd(x,3))+\cdots+(x-\gcd(x,\frac{x-2}{2}))+(x-\gcd(x,\frac{x}{2}))\leq \frac{x^2}{2}.$$
Let $x = 2n$. Then it is equivalent to the following inequality:
$$2n^2 - (2n)^{1.5} \leq 2n^2 - \sum_{i=1}^n \gcd(2n,i) \leq 2n^2.$$
It is equivalent to
$$ 0 \leq \sum_{i=1}^n \gcd(2n,i) \leq (2n)^{1.5},$$
which shows that one of the inequality is trivial.
We know that $\gcd(2n,i) = \gcd(2n, 2n-i)$ for $i = 1, \ldots, n-1$, and $\gcd(2n,2n) = 2\gcd(2n,n)$.
Hence, if we show that
$$ \sum_{i=1}^{2n} \gcd(2n,i) \leq 2(2n)^{1.5},$$
then the right-side inequality is proved.
Let $\phi$ denote  Euler's phi function.
We can transform the left term by
\begin{equation}
\begin{split}
\sum_{i=1}^{2n} \gcd(2n,i)
&
= \sum_{d | 2n} d \phi (\frac{2n}{d})
= \sum_{d | 2n} \frac{2n}{d} \phi(d)
= 2n \sum_{d | 2n} \frac{\phi(d)}{d} \\
&
\leq 2n \sum_{d | 2n} 1
\leq 2n (2\sqrt{2n}) = 2 (2n)^{1.5}.
\end{split}
\end{equation}
We use the facts that

*

*If $d$ divides $n$, then the number of $i$ ($1\leq i \leq 2n$) satisfying $\gcd(2n,i) = d$ is $\phi(\frac{2n}{d})$.

*$\sum_{d \mid 2n} 1$, the number of divisors of $2n$ is at most $2\sqrt{2n}$.

$Q.E.D.$


text:
Q: SQL Developer format like Toad's Quest Parser version 5 I use version control and some of my team use Toad, others use SQL Developer.  Is there someway to align the two formats?
The reason being that when you compare the versions most of the changes are due to formatting.
In Toad, you use Ctrl + Shift + F
In SQL Developer, you use Ctrl + F7
In SQL Developer it has some other formatting, but nothing for Toad which uses QP5 (Quest Parser Version 5)

A: You can change how SQL Developer formats your code; from the menu go to:
Tools->Preferences->Code Editor->Format.

Go into Advanced Formatting to configure alignment, line breaks. whitespace etc.
Toad presumably has similar options. You just need to set them up the same, which may need a bit of trial and error to get right.


text:
Q: How can I perform array calculations with Vectors? I have been reading and in many places, vectors have been recommended over Arrays, but I am still not understanding completely, and I am not sure if they can work on my project.
I am doing CFD calculations and I have to make some calculations like the following,
for(int i = 1 ; i < M ; i++) {
    for(int j = 1 ; j < N ; j++) {
        for(int k = 0 ; k < 4 ; k++) {
            dU_dX_plus=(U[i+1][j+1][k]+dU_dT[i+1][j+1][k]*dt/2+U[i+1][j][k]+dU_dT[i+1][j][k]*dt/2-2*U_p[i][j][k])/dx;
            dU_dX_min=-(U[i][j+1][k]+dU_dT[i][j+1][k]*dt/2+U[i][j][k]+dU_dT[i][j][k]*dt/2-2*U_p[i][j][k])/dx;
            dU_dX[i][j][k]=Wfunct(dU_dX_plus, dU_dX_min);

            dU_dY_plus=(U[i+1][j+1][k]+dU_dT[i+1][j+1][k]*dt/2+U[i][j+1][k]+dU_dT[i][j+1][k]*dt/2-2*U_p[i][j][k])/dy;
            dU_dY_min=-(U[i][j][k]+dU_dT[i][j][k]*dt/2+U[i+1][j][k]+dU_dT[i+1][j][k]*dt/2-2*U_p[i][j][k])/dy;
            dU_dY[i][j][k]=Wfunct(dU_dY_plus, dU_dY_min);
        }
    }
}

Can I implement it with vectors? If so, how can I do it?
Is it worth it or should I keep working with arrays?
Thanks,

A: A vector has the advantage, that memory is allocated directly on the heap. This means that you can also use quite large arrays. This is especially important for 3D arrays. Remember: an array of floats with size 100x100x100 takes 4MB memory - too much for the stack in most cases.
By using a vector instead of a fixed-sized array, you can also implement arrays with dynamic size, i.e. not fixed at runtime.
You can do it like this:
struct Array3D {

    int N, M, K; // size of array

    std::vector<float> U; // storage

    Array3D(unsigned n, unsigned m, unsigned k)
    : N(n), M(m), K(k), U(n*m*k) {}

    float index(unsigned i, unsigned j, unsigned k) const {
        return (i*M + j)*K + k;
    }

    float operator()(unsigned i, unsigned j, unsigned k) const {
        return U[index(i,j,k)];
    }

    float& operator()(unsigned i, unsigned j, unsigned k) {
        return U[index(i,j,k)];
    }
};

Array3D U(6,7,8);
U(1,2,3) = U(2,3,4) + U(2,3,2);

Personally I think U(i+1,j+1,k) is more readable and writable than U[i+1][j+1][k].
You can also use boost::multi_array.

A: std::vector is nothing more than a wrapper around a heap allocated array and the array's size. You can do most anything with a vector that you can do with a heap allocated array.
std::vector is typically recommending over raw c++ arrays for two reasons:

*

*because std::vector is type safe. Raw arrays forget that they are arrays and forget their size very easily, which can lead to invalid memory accesses.

*because std::vector manages the lifetime of the heap allocated array rather than requiring you to use new[] and delete[] manually, which is error prone.

One disadvantage of std::vector is that it's not as convenient to use as a multi-dimentional array.
double U[M][N][4];
U[i][j][k];

You can flatten a multi-dimentional array into a single dimension:
std::vector<double> U(M * N * 4);
U[N*4*i + 4*j + k]

Another option would be to write your own typesafe, resource managing class that acts as a multi-dimentional array.
class _2d_array {
  std::vector<double> arr;
public:
  const int rows, columns;
  _2d_array(int rows, int columns) : arr(rows * columns), rows(rows), columns(columns) {}

  struct row_proxy {
    _2d_array &arr;
    int row;
    double &operator[] (int column) { return arr.arr[arr.columns*row + column]; }
  };

  row_proxy operator[] (int row) { return row_proxy{*this, row}; }
};

_2d_array U(M, N);
U[i][j] = 10.23;

A:
... vectors have been recommended over arrays, but I am still not understanding completely, and I am not sure if they can work on my project.

arrays are a C++ 11 feature. They are also fixed in size.
vectors are readily available. They are dynamic and can change size.
Use whatever works best for your situation. If you need C++03, then you have to use a vector. If you need to grow the array, then use a vector.


text:
Q: Creating a C Struct From Go I have struct in C that I serialize + persist to disk, and than read and deserialize, this is done usually in C code. now I need to write a Go code that serialize the same struct, so that the code in C can deserialize it as before.
as this is a fairly low level c, and I can't use any library such as JSON, it must be a "pure memory dump of the struct", also as I need the GO program to be statically linked I can't use CGO library.


text:
Q: Norm for an operator related to the Christoffel-Darboux kernel Let $p_0, p_1, \ldots$ be the orthonormal polynomials for the measure $\mu$ on the interval $[a,b]$. That is, $\displaystyle \int_a^b p_i(x)p_j(x) d\mu(x) = \delta_{i,j}$ with $\delta_{i,j}$ the Kronecker delta. Define the Christoffel-Darboux kernel
$$K_n(x,y) = \sum_{j=0}^n p_j(x)p_j(y)$$
And define the operator
$$K_n(f; x) = \int_a^b f(y)K_n(x,y) d\mu(y)$$
I would like to find the two operator norms $||K_n||_{\infty}$ and $||K_n||_2$.
In both cases one can take $f(y)$ outside of the integral and bound it by $||f||_{\infty} \le \mu([a,b])^{1/2}||f||_2$ so we are left with bounding the norm of $\int_a^b K_n(x,y) d\mu(y)$.
To find the latter norm, we might want to use the Christoffel-Darboux formula which states that, for some constant $a_n$,
$$\sum_{j=0}^{n} p_j(x)p_j(y) = a_{n} \frac{p_{n+1}(x)p_{n}(y) - p_{n+1}(y)p_{n}(x)}{x - y}$$
And this holds for $x \neq y$. For $x = y$ we have
$$\sum_{j=0}^{n} p_j(x)p_j(y) = a_n \left(p'_{n+1}(x)p_n(x) - p_{n+1}(x)p'_n(x) \right)$$
However, I do not know how to proceed further.

A: I suspect you meant $\|f\|_2\le\mu([a,b])^{1/2}\|f\|_\infty$.  But in any case, I'm not sure this is needed.
The $L^2$ case:
Observe that $\{p_n\}_0^\infty$ is an orthonormal basis of $L^2([a,b],\mu)$.  Let $(,)$ be the inner product.  By Bessel's inequality, we have $\sum_0^\infty|(f,p_i)|^2\le\|f\|^2_2$, so
$$
\|K_n(f)\|_2^2=\sum_{i=0}^n|(f,p_i)|^2\le\sum_{i=0}^\infty|(f,p_i)|^2\le\|f\|^2_2,
$$
i.e. $\|K_n\|_{L^2\to L^2}\le 1$.  But $K_n(p_0)=p_0$, so $\|K_n\|_{L^2\to L^2}=1$.
The $L^\infty$ case:
It is easy to see that
$$
\|K_n\|_{L^\infty\to L^\infty}\le \sup_{x\in[a,b]}\int_a^b|K_n(x,y)|d\mu(y).
$$
In fact, this is an equality.  Fix $x\in[a,b]$ and choose $f(y)=\text{sgn}\, K_n(x,y)$.  Then $K_n(f;x)=\int_a^b|K_n(x,y)|d\mu(y)$, so by continuity, $\|K_n(f)\|_\infty\ge \int_a^b|K_n(x,y)|d\mu(y)$.  Taking the supremum over $[a,b]$ gives the result.


text:
Q: Mocking Scala void function using Mockito I found a few answers for this but nothing is working for me.
Trying to mock Apache Shiro Subject interface login method which returns void.
Interface:
    void login(AuthenticationToken token) throws AuthenticationException;

I have tried :
   #1
  val subject = mock[Subject]
  doNothing().when(subject).login(new UsernamePasswordToken())

   #2
  val subject = mock[Subject]
  doNothing().when(subject).login(any[UsernamePasswordToken])

   #3
  when(subject.login(any[UsernamePasswordToken])).thenAnswer(new Answer[Void]() {
      override def answer(invocation: InvocationOnMock): Void = {
       null:Void
      }

I keep getting NullPointerException on login. My goal is test around the login method and test some success cases along with some failure cases where this method throws an exception.

A: The default behavior in Mockito is to return nothing if you don't "stub" a particular method. No need to force a void() function to doNothing() since it's doing nothing by default.


text:
Q: Interpretation of having a significant difference but no correlation between variables I have data that includes a specific metric for which I want to investigate if it is having a (causal) relation with the other metrics. When I check the correlations (Pearson and Kendall) I find no correlation between the target metric and the others.
However, if I split the data into two groups based on the target metric I do find a significant difference in the mean values of the other metrics. (I checked using Welch test since Levene check showed significant difference in variance)
Somehow I have a hard time wrapping my head around this conceptually. Does this make sense or is there something going wrong in my calculations or am I not allowed to do specific actions?
If there is a confound variable influencing both my target metric and the others, wouldn't that show as a correlation as well or could this be the cause of what I'm observing?


text:
Q: chapter on recto, blank verso in memoir I use the memoir class with option openright. In addition, I would also like to have the verso page before the chapter start blank, such that:
Chapter ends on recto: Next verso blank then next chapter.
Chapter ends on verso: Blank recto, blank verso, then next chapter.

Is there an option to achieve this automatically or do I need to create this manually for each chapter start?

A: What you are asking for is the default memoir behaviour. You can, of course change this:
% clearforchapprob.tex  SE 568204
\documentclass{memoir}
%% do not have a completely blank page before a chapter
\renewcommand{\clearforchapter}{\cleartooddpage[Non blank page]}

\begin{document}
\chapter{First}
Some text.
\chapter{Second}
More text.
\end{document}

Try the above MWE with and without the \renewcommand{\clearforchapter}{...}
BTW openright is a default memoir option.


text:
Q: Makedepend: Command not found I'm trying to compile a source code and I'm getting this error
make[1]: makedepend: Command not found

Do you have any suggestions?
I have Ubuntu 12 04 LTS, 2.6.28-17 kernel and gcc version 4.6.3

A: $ makedepend
The program 'makedepend' is currently not installed. You can install it by typing:
sudo apt-get install xutils-dev
You will have to enable the component called 'main'

For future, typing the command automatically searches it inside repository and suggests variants of packages which can be installed in case the command not found in system.

A:
$ apt-cache search makedepend
xutils-dev - X Window System utility programs for development

So you have to install xutils-dev package(which includes the program makedepend) .Install xutils-dev package by running the below command on terminal,
sudo apt-get install xutils-dev


text:
Q: How to force locale within an Android app I am developing an android app and the task is to support three languages. In the first screen the user selects language and rest of the app should appear in selected language.
I can use localization feature such as creating a default res/values/string.xml and language specific files res/values-fr/strings.xml. When the app is opened on a device with FR locale all strings appear translated.
Question: How do I force a locale on button click so that the next activity should use res/values-fr/strings.xml

A: Give it a try:
public class SigmaMiddleEastApplication extends PPGApplication {

    @Override
    public void onConfigurationChanged(Configuration newConfig) {
        newConfig.locale = Locale.ENGLISH;
        super.onConfigurationChanged(newConfig);

        Locale.setDefault(newConfig.locale);
        getBaseContext().getResources().updateConfiguration(newConfig, getResources().getDisplayMetrics());
    }
}

or take a look at the following attribute:
android:configChanges="locale"


text:
Q: How to iBooks like search UI on table I want to show the search bar of tableview like that in iBooks. How can i reduce the width of searchbar and how it can be shown without any background color.
Also how can i hide the search box initially when the page is displayed.

A: I can think of two options:
Create your own by subclassing UITextfield

*

*set border style to UITextBorderStyleNone

*set the leftView to a magnifying glass image

*set the background to a transparent png with only the round border showing

*make use if the uiimages stretchableImageWithLeftCapWidth:topCapHeight method so the background image will looks nice when stretched

Mess around with UISearchbar, not recommended
You can access the subviews of a UISearchbar in this way:
for (UIView *aSubview in [searchbar subviews]) {
            // this will remove the toolbar around the searchbar in iOS 4
    if ([aSubview isKindOfClass:NSClassFromString(@"UISearchBarBackground")])
    {
        [aSubview removeFromSuperview];
    }

    // get a grip on the underlying textfield...
    if ([aSubview isKindOfClass:NSClassFromString(@"UISearchBarTextField")])
    {
        UITextField *aTextfield = (UITextField *)aSubview;

        // this won't do anything at it is already none, just experimenting
        aTextfield.borderStyle = UITextBorderStyleNone;

        // this will remove the whole border as it is a custom background
        aTextfield.background = nil;

        // this will remove the magnifying glass
        aTextfield.leftView = nil;

        // play around even more :)
    }
}

You can hide the searchbar by

*

*setting the hidden property to YES

*set the frame or center property to somewhere outside the visible area

*set alpha property to 0.0

*adding the searchbar to your view only when needed


text:
Q: Vagrant: running Ansible provisioning after all VMs booted, Ansible cannot connect to all hosts I'm trying to figure out how to use Ansible with Vagrant the proper way. By default, it seems Vagrant is isolating Ansible execution per box and executes playbooks after each box partially as it applies to that single box in the loop. I find this VERY counterproductive and I have tried tricking Vagrant into executing a playbook across all of the hosts AFTER all of them booted, but it seems Ansible, when started from Vagrant never sees more than a single box at a time.
Edit: these are the version I am working with:
Vagrant: 2.2.6
Ansible: 2.5.1
Virtualbox: 6.1
The playbook (with the hosts.ini) by itsef executes without issues when I run it stand-alone with the ansible-playbook executable after the hosts come up, so the problem is with my Vagrant file. I just cannot figure it out.
This is the Vagrantfile:
# -*- mode: ruby -*-
# vi: set ft=ruby :

IMAGE_NAME = "ubuntu/bionic64"

Vagrant.configure("2") do |config|
    config.ssh.insert_key = false
    config.vm.box = IMAGE_NAME

    # Virtualbox configuration
    config.vm.provider "virtualbox" do |v|
        v.memory = 4096
        v.cpus = 2
        #v.linked_clone = true
    end

    # master and node definition
    boxes = [
        { :name => "k8s-master", :ip => "192.168.50.10" },
        { :name => "k8s-node-1", :ip => "192.168.50.11" }
    ]

    boxes.each do |opts|
        config.vm.define opts[:name] do |config|
            config.vm.hostname = opts[:name]
            config.vm.network :private_network, ip: opts[:ip]

            if opts[:name] == "k8s-node-1"
                config.vm.provision "ansible_local" do |ansible|
                    ansible.compatibility_mode = "2.0"
                    ansible.limit = "all"
                    ansible.config_file = "ansible.cfg"
                    ansible.become = true
                    ansible.playbook = "playbook.yml"
                    ansible.groups = {
                        "masters" => ["k8s-master"],
                        "nodes" => ["k8s-node-1"]
                    }
                end
            end
        end
    end
end

ansible.cfg
[defaults]
connection = smart
timeout = 60
deprecation_warnings = False
host_key_checking = False
inventory = hosts.ini

[ssh_connection]
ssh_args = -o ControlMaster=auto -o ControlPersist=60s -o UserKnownHostsFile=/dev/null -o IdentitiesOnly=yes

hosts.ini
[masters]
k8s-master ansible_host=192.168.50.10 ansible_user=vagrant

[nodes]
k8s-node-1 ansible_host=192.168.50.11 ansible_user=vagrant

[all:vars]
ansible_python_interpreter=/usr/bin/python3
ansible_ssh_user=vagrant
ansible_ssh_private_key_file=~/.vagrant.d/insecure_private_key

playbook.yml
- hosts: all
  become: yes
  tasks:
    - name: Update apt cache.
      apt: update_cache=yes cache_valid_time=3600
      when: ansible_os_family == 'Debian'

    - name: Ensure swap is disabled.
      mount:
        name: swap
        fstype: swap
        state: absent

    - name: Disable swap.
      command: swapoff -a
      when: ansible_swaptotal_mb > 0

    - name: create the 'mobile' user
      user: name=mobile append=yes state=present createhome=yes shell=/bin/bash

    - name: allow 'mobile' to have passwordless sudo
      lineinfile:
        dest: /etc/sudoers
        line: 'mobile ALL=(ALL) NOPASSWD: ALL'
        validate: 'visudo -cf %s'

    - name: set up authorized keys for the mobile user
      authorized_key:
        user: mobile
        key: "{{ lookup('pipe','cat ssh_keys/*.pub') }}"
        state: present
        exclusive: yes

- hosts: all
  become: yes
  tasks:
   - name: install Docker
     apt:
       name: docker.io
       state: present
       update_cache: true

   - name: install APT Transport HTTPS
     apt:
       name: apt-transport-https
       state: present

   - name: add Kubernetes apt-key
     apt_key:
       url: https://packages.cloud.google.com/apt/doc/apt-key.gpg
       state: present

   - name: add Kubernetes' APT repository
     apt_repository:
      repo: deb http://apt.kubernetes.io/ kubernetes-xenial main
      state: present
      filename: 'kubernetes'

   - name: install kubelet
     apt:
       name: kubelet=1.17.0-00
       state: present
       update_cache: true

   - name: install kubeadm
     apt:
       name: kubeadm=1.17.0-00
       state: present

- hosts: masters
  become: yes
  tasks:
   - name: install kubectl
     apt:
       name: kubectl=1.17.0-00
       state: present
       force: yes

- hosts: k8s-master
  become: yes
  tasks:
    - name: check docker status
      systemd:
        state: started
        name: docker

    - name: initialize the cluster
      shell: kubeadm init --apiserver-advertise-address 192.168.50.10 --pod-network-cidr=10.244.0.0/16 >> cluster_initialized.txt
      args:
        chdir: $HOME
        creates: cluster_initialized.txt

    - name: create .kube directory
      become: yes
      become_user: mobile
      file:
        path: $HOME/.kube
        state: directory
        mode: 0755

    - name: copy admin.conf to user's kube config
      copy:
        src: /etc/kubernetes/admin.conf
        dest: /home/mobile/.kube/config
        remote_src: yes
        owner: mobile

    - name: install Pod network
      become: yes
      become_user: mobile
      shell: kubectl apply -f https://raw.githubusercontent.com/coreos/flannel/master/Documentation/kube-flannel.yml >> pod_network_setup.txt
      args:
        chdir: $HOME
        creates: pod_network_setup.txt

- hosts: k8s-master
  become: yes
  gather_facts: false
  tasks:
    - name: get join command
      shell: kubeadm token create --print-join-command 2>/dev/null
      register: join_command_raw

    - name: set join command
      set_fact:
        join_command: "{{ join_command_raw.stdout_lines[0] }}"

- hosts: nodes
  become: yes
  tasks:
    - name: check docker status
      systemd:
        state: started
        name: docker

    - name: join cluster
      shell: "{{ hostvars['k8s-master'].join_command }} >> node_joined.txt"
      args:
        chdir: $HOME
        creates: node_joined.txt

The moment the playbook tries to execute against k8s-master, it fails like this:
fatal: [k8s-master]: UNREACHABLE! => {"changed": false, "msg": "Failed to connect to the host via ssh: ssh: Could not resolve hostname k8s-master: Temporary failure in name resolution", "unreachable": true}

The host is up. SSH works.
Who can help me sort this out?
Thanks!

A: I have managed to use Ansible inside of Vagrant.
Here is what I did to make it work:
Steps to reproduce:

*

*Install Vagrant, Virtualbox

*Create all the necessary files and directories

*

*ansible.cfg

*playbook.yml

*hosts

*insecure_private_key

*Vagrant file

*Test

Install Vagrant, Virtualbox
Follow installation guides at appropriate sites:

*

*Vagrant

*Virtualbox
Create all the necessary files and directories
This example bases on original poster files.
Create vagrant and ansible folders to store all the configuration files and directories. The structure of it could look like that:

*

*vagrant - directory

*

*Vagrantfile - file with main configuration

*ansible - directory

*

*ansible.cfg - configuration file of Ansible

*playbook.yml - file with steps for Ansible to execute

*hosts - file with information about hosts

*insecure_private_key - private key of created machines

Ansible folder is a seperate directory that will be copied to k8s-node-1.
By default Vagrant shares a vagrant folder with permissions of 777. It allows owner, group and others to have full access on everything that is inside of it.
Logging to virtual machine manualy and running ansible-playbook command inside vagrant directory will output errors connected with permissions. It will render ansible.cfg and insecure_private_key useless.
Ansible.cfg
Ansible.cfg is configuration file of Ansible. Example used below:
[defaults]
connection = smart
timeout = 60
deprecation_warnings = False
host_key_checking = False
[ssh_connection]
ssh_args = -o ControlMaster=auto -o ControlPersist=60s -o UserKnownHostsFile=/dev/null -o IdentitiesOnly=yes

Create ansible.cfg inside ansible directory.
Playbook.yml
Example playbook.yml is a file with steps for Ansible to execute.
It will check connections and test if groups are configured correctly:
- name: Check all connections
  hosts: all
  tasks:
    - name: Ping
      ping:

- name: Check specific connection to masters
  hosts: masters
  tasks:
    - name: Ping
      ping:

- name: Check specific connection to nodes
  hosts: nodes
  tasks:
    - name: Ping
      ping:

Create playbook.yml inside ansible directory.
Insecure_private_key
To successfully connect to virtual machines you will need insecure_private_key. You can create it by invoking command:$ vagrant init inside vagrant directory.
It will create insecure_private_key inside your physical machine in HOME_DIRECTORY/.vagrant.d.
Copy it to ansible folder.
Hosts
Below hosts file is responsible for passing the information about hosts to Ansible:
[masters]
k8s-master ansible_host=192.168.50.10 ansible_user=vagrant

[nodes]
k8s-node-1 ansible_host=192.168.50.11 ansible_user=vagrant

[all:vars]
ansible_python_interpreter=/usr/bin/python3
ansible_ssh_user=vagrant
ansible_ssh_private_key_file=/ansible/insecure_private_key

Create hosts file inside ansible directory.
Please take a specific look on: ansible_ssh_private_key_file=/ansible/insecure_private_key
This is declaration for Ansible to use  earlier mentioned key.
Vagrant
Vagrant file is the main configuration file:
# -*- mode: ruby -*-
# vi: set ft=ruby :

IMAGE_NAME = "ubuntu/bionic64"

Vagrant.configure("2") do |config|
    config.ssh.insert_key = false
    config.vm.box = IMAGE_NAME

    # Virtualbox configuration
    config.vm.provider "virtualbox" do |v|
        v.memory = 4096
        v.cpus = 2
        #v.linked_clone = true
    end

    # master and node definition
    boxes = [
        { :name => "k8s-master", :ip => "192.168.50.10" },
        { :name => "k8s-node-1", :ip => "192.168.50.11" }
    ]

    boxes.each do |opts|
        config.vm.define opts[:name] do |config|
            config.vm.hostname = opts[:name]
            config.vm.network :private_network, ip: opts[:ip]

            if opts[:name] == "k8s-node-1"
                config.vm.synced_folder "../ansible", "/ansible", :mount_options => ["dmode=700", "fmode=700"]

                config.vm.provision "ansible_local" do |ansible|
                    ansible.compatibility_mode = "2.0"
                    ansible.limit = "all"
                    ansible.config_file = "/ansible/ansible.cfg"
                    ansible.become = true
                    ansible.playbook = "/ansible/playbook.yml"
                    ansible.inventory_path = "/ansible/hosts"
                end
            end
        end
    end
end

Please take a specific look on:
config.vm.synced_folder "../ansible", "/ansible", :mount_options => ["dmode=700", "fmode=700"]

config.vm.synced_folder will copy ansible directory to k8s-node-1 with all the files inside.
It will set permissions for full access only to owner (vagrant user).
ansible.inventory_path =  "/ansible/hosts"

ansible.inventory_path will tell Vagrant to provide hosts file for Ansible.
Test
To check run the following command from the vagrant directory:
$ vagrant up
The part of the output responsible for Ansible should look like that:
==> k8s-node-1: Running provisioner: ansible_local...
    k8s-node-1: Installing Ansible...
    k8s-node-1: Running ansible-playbook...

PLAY [Check all connections] ***************************************************

TASK [Gathering Facts] *********************************************************
ok: [k8s-master]
ok: [k8s-node-1]

TASK [Ping] ********************************************************************
ok: [k8s-master]
ok: [k8s-node-1]

PLAY [Check specific connection to masters] ************************************

TASK [Gathering Facts] *********************************************************
ok: [k8s-master]

TASK [Ping] ********************************************************************
ok: [k8s-master]

PLAY [Check specific connection to nodes] **************************************

TASK [Gathering Facts] *********************************************************
ok: [k8s-node-1]

TASK [Ping] ********************************************************************
ok: [k8s-node-1]

PLAY RECAP *********************************************************************
k8s-master                 : ok=4    changed=0    unreachable=0    failed=0    skipped=0    rescued=0    ignored=0
k8s-node-1                 : ok=4    changed=0    unreachable=0    failed=0    skipped=0    rescued=0    ignored=0


text:
Q: Why I always get the 0 value even my collection is not empty I want dropVolume get the value to use it in another method after calling my  getAllDropsVolumePerDate(date) method.
but every time I get dropVolume = 0
 dropVolume = 0;
  getAllDropsVolumePerDate(date: string) {
    this.campaignService.getAllCampaigns().subscribe((res) => {
      res.forEach((campaign) => {
        campaign.drops.forEach((drop) => {
          if (drop.dropDate === date) {
            this.dropVolume = this.dropVolume +drop.dropVolume;
          }
        });
      });
     return this.dropVolume;
    });
    return this.dropVolume;
  }

A: Subscription is asynchronous and it can take time to return a value (even if it's in milliseconds), so your subscription starts BUT your return line is out of it and will be triggered before the subscription returns with a value. Move your return line inside the subscription.


text:
Q: Set theory basics involving unions,intersections, disjointness Let $B_n = \bigcup_{1}^{n}A_i$ where $A_i$ are a sequence of disjoint sets.
Suppose $A_1$ and $A_2$ are disjoint sets in some space $X$ and we have a set $E\subset X$. Suppose further that $B_2 = A_1\cup A_2$. Then would $$((E\cap B_2)\cap A_2)) = E \cap A_2?$$ and would $$((E\cap B_2)\cap A_2^c)) = E \cap A_1?$$
As I proceed in doing problems in measure theory I am confronted with stuff from set theory that stop me up. If anyone has any recommendations on getting a better understanding of set theory or more advanced set theory problems involving unions and intersections please let me know.

A: Given that $B_2 = A_1 \cup A_2$ and that $A_1$ and $A_2$ are disjoint, i.e., $A_1 \cap A_2 = \emptyset$,
$$
B_2 \cap A_2 = (A_1 \cup A_2)\cap A_2 = A_2
$$
Therefore
$$
E \cap B_2 \cap A_2 = E \cap A_2
$$
The same argument works for the other.

A: The first statement is is true even if $A_1$ and $A_2$ are not disjoint. Clearly we have $B_2 \cap A_2 \subset A_2$, and the opposite containment $A_2 \subset B_2 \cap A_2$ holds because $A_2 \subset  A_1 \cup A_2 = B_2$. Since both containments hold, we have $A_2 \cap B_2 = A_2$.
On the other hand, the second statement requires the disjointness of $A_1$ and $A_2$. For example, if $A_1 = A_2$ then the left hand side is $\emptyset$ but the right hand side need not be.
To prove that the second statement is true if $A_1$ and $A_2$ are disjoint, note that in this case
$$B_2 \cap A_2^c = (A_1 \cup A_2) \cap A_2^c = (A_1 \cap A_2^c) \cup (A_2 \cap A_2^c) = A_1 \cap A_2^c = A_1$$
where the last equality is true because $A_1$ and $A_2$ are disjoint.


text:
Q: What are the differences between creating signals in these two different ways? Using PySide2, it's possible to create signals in two ways that I know of:
file_changed = Signal()

or
@Signal
def file_changed(self):
    pass

They both seem to do the same thing.  What if I want a signal that can emit a value?  I know I can do:
file_changed = Signal(str)

...

def load_file(self, file_name):
   self.file_changed.emit(file_name)

But what is the equivalent using the @Signal decorator?