Q: Opengl hide parts of the screen (code snippet. I know it's ugly but i wanted to make it work before making it better so please don't pay too much attention to the structure)
I modified slightly the glfw example present in the documentation to have a triangle that rotates when pressing the right arrow key and draws a circle described by the position of one of his  vertices (the blue one in this case).
I clear the GL_COLOR_BUFFER_BIT only when initializing the window to avoid having to store all the coordinates that will be needed to draw the line (they would be hundreds of thousands in the final program), that means that on the screen every time i press the right arrow a "copy" of the triangle is draws rotated by 12 degrees and a line is drawn that connects the old blue angle position to the new one.
The problem now is that i would want to be able to press the escape key GLFW_KEY_ESCAPE and "delete" the triangles while keeping the lines drawn.
I tried using a z-buffer to hide the triangles behind a black rectangle but only the last line drawn is visualized (i think this is because opengl doesn't know the z of the previous lines since i don't store them).
Is there a way to do what i want without having to store all the point coordinates and then clearing the whole screen and redrawing only the lines? If this is the case, what would be the best way to store them?
Here is part of the code i have so far.
bool check = 0;

Vertex blue = {0.f, 0.6f, 0.5f};
Vertex green = {0.6f,-0.4f, 0.5f};
Vertex red = {-0.6f, -0.4f, 0.5f};
Vertex line = {0.f, 0.6f, 0.f};
Vertex line2 = {0.f, 0.6f, 0.f};

static void
key_callback(GLFWwindow *window, int key, int scancode, int action, int mods) {
    if (key == GLFW_KEY_ESCAPE && action == GLFW_PRESS)
        check = !check;
    if (key == GLFW_KEY_RIGHT && action == GLFW_PRESS) {
        line.x = line2.x;
        line.y = line2.y;
        rotation -= 12;
        rad = DegToRad(-12);
        double x = line.x*cos(rad) - line.y * sin(rad);
        double y = line.y * cos(rad) + line.x * sin(rad);
        line2.x = x;
        line2.y = y;
}

int main(void) {
    GLFWwindow *window;
    glfwSetErrorCallback(error_callback);
    if (!glfwInit())
        exit(EXIT_FAILURE);
    window = glfwCreateWindow(1280, 720, "Example", NULL, NULL);
    if (!window) {
        glfwTerminate();
        exit(EXIT_FAILURE);
    }
    glfwMakeContextCurrent(window);
    glfwSetKeyCallback(window, key_callback);
    glClear(GL_COLOR_BUFFER_BIT);
    while (!glfwWindowShouldClose(window)) {

        glPolygonMode(GL_FRONT_AND_BACK,GL_LINE);
        float ratio;
        int width, height;
        glfwGetFramebufferSize(window, &width, &height);
        ratio = width / (float) height;
        glViewport(0, 0, width, height);
        glMatrixMode(GL_PROJECTION);
        glLoadIdentity();
        glOrtho(-ratio, ratio, -1.f, 1.f, 1.f, -1.f);
        glMatrixMode(GL_MODELVIEW);

        glLoadIdentity();
        glRotatef(rotation, 0.f, 0.f, 1.f);
        glBegin(GL_TRIANGLES);
        glColor3f(1.f, 0.f, 0.f);
        glVertex3f(red.x, red.y, red.z);
        glColor3f(0.f, 1.f, 0.f);
        glVertex3f(green.x, green.y, green.z);
        glColor3f(0.f, 0.f, 1.f);
        glVertex3f(blue.x, blue.y, blue.z);
        glEnd();

        glLoadIdentity();
        glLineWidth(1.0);
        glColor3f(1.0, 0.0, 0.0);
        glBegin(GL_LINES);
        glVertex3f(line.x, line.y, line.z);
        glVertex3f(line2.x, line2.y, line2.z);
        glEnd();

        if (check){
            //hide the triangles but not the lines
         }

        glEnd();

        glfwSwapBuffers(window);
        glfwPollEvents();

    }

    glfwDestroyWindow(window);
    glfwTerminate();
    exit(EXIT_SUCCESS);
}

A:
I clear the GL_COLOR_BUFFER_BIT only when initializing the window

That's your problem right there. It's idiomatic in OpenGL to always start with a clear operation of the main framebuffer color bits. That is, because you don't know the state of your window main framebuffer when the operating system is asking for a redraw. For all you know it could have been all replaced with cat pictures in the background without your program knowing it. Seriously: If you have a cat video running and the OS felt the need to rearrange your window's main framebuffer memory this is what you might end up with.

Is there a way to do what i want without having to store all the point coordinates and then clearing the whole screen and redrawing only the lines?

For all intents and purposes: No. In theory one could come up with a contraption made out of a convoluted series of stencil buffer operations to implement that, but this would be barking up a very wrong tree.
Here's something for you to try out: Draw a bunch of triangles like you do, then resize your window down so there nothing remains, then resize it back to its original size… you see where the problem? There's a way to address this particular problem, but that's not what you should do here.
The correct thing is to redraw everything. If you feel that that's to slow you have to optimize your drawing process. On current generation hardware it's possible to churn out on the order of 100 million triangles per second.


Q: Springboot REST API returning 404 when deployed in Jboss EAP.7.1.0 I have created a simple Springboot REST api, which is working fine when deployed in Tomacat container but returning 404 message when deployed in Jboss EAP 7.1.0. Need help to resolve this problem.
Below are the classes i wrote along with pom.xml and application.properties
SpringRestApiApplication.java
package com.test.spring;

import org.springframework.boot.SpringApplication;
import org.springframework.boot.autoconfigure.SpringBootApplication;

@SpringBootApplication
public class SpringRestApiApplication{

    public static void main(String[] args) {
        SpringApplication.run(SpringRestApiApplication.class, args);
    }

}

RestExample.java
package com.test.spring.web.controller;

import org.springframework.web.bind.annotation.GetMapping;
import org.springframework.web.bind.annotation.RequestMapping;
import org.springframework.web.bind.annotation.RestController;

@RestController
@RequestMapping(value = "/test")
public class RestExample {

    @GetMapping(value = "/hello")
    public String HelloWorldAPI() {
        return "Hello World!";

    }

}

pom.xml
<?xml version="1.0" encoding="UTF-8"?>
<project xmlns="http://maven.apache.org/POM/4.0.0" xmlns:xsi="http://www.w3.org/2001/XMLSchema-instance"
    xsi:schemaLocation="http://maven.apache.org/POM/4.0.0 https://maven.apache.org/xsd/maven-4.0.0.xsd">
    <modelVersion>4.0.0</modelVersion>
    <parent>
        <groupId>org.springframework.boot</groupId>
        <artifactId>spring-boot-starter-parent</artifactId>
        <version>1.5.10.RELEASE</version>
        <relativePath/> <!-- lookup parent from repository -->
    </parent>

    <groupId>com.example</groupId>
    <artifactId>SpringRestAPI</artifactId>
    <version>0.0.1-SNAPSHOT</version>
    <packaging>war</packaging>
    <name>SpringRestAPI</name>
    <description>Rest API Test Example</description>

    <properties>
        <java.version>1.8</java.version>
    </properties>

    <dependencies>
        <dependency>
            <groupId>org.springframework.boot</groupId>
            <artifactId>spring-boot-starter-web</artifactId>
            <exclusions>
                <exclusion>
                    <groupId>org.springframework.boot</groupId>
                    <artifactId>spring-boot-starter-tomcat</artifactId>
                </exclusion>
                <exclusion>
                    <groupId>ch.qos.logback</groupId>
                    <artifactId>logback-classic</artifactId>
                </exclusion>
            </exclusions>
        </dependency>

        <dependency>
              <groupId>javax.servlet</groupId>
              <artifactId>javax.servlet-api</artifactId>
              <scope>provided</scope>
        </dependency>

        <dependency>
            <groupId>org.springframework.boot</groupId>
            <artifactId>spring-boot-starter-test</artifactId>
            <scope>test</scope>
        </dependency>
    </dependencies>

    <build>
        <finalName>rest-api</finalName>
        <plugins>
            <plugin>
                <groupId>org.springframework.boot</groupId>
                <artifactId>spring-boot-maven-plugin</artifactId>
            </plugin>
        </plugins>
    </build>

</project>

application.properties
server.servlet-path=/*

A: You are using 7.1.0 right. Remove this and try server.servlet-path=/*


Q: How to execute an unordered SQL script I have a SQL script but there is an issue with the order of the statements in the script
e.g.
INSERT INTO PERMISSIONS_FOR_ROLE (ROLE_ID, PERMISSION_ID) VALUES (3, 8);
INSERT INTO permissions (id, name) VALUES (8, 'update');

The order of occurrence in the script should have been reverse! And this results in a error because the foreign key with id 8 is not yet inserted when the first statement executes
leading to:
[Code: -177, SQL State: 23503]  integrity constraint violation:
foreign key no parent; PERMISSIONS_FOR_ROLE_PERM_FK table: PERMISSIONS_FOR_ROLE value: 8

statements used to create the relationships are as below
create table PERMISSIONS ( ID bigint not null, NAME varchar(255), primary key (ID) );

create table PERMISSIONS_FOR_ROLE ( ROLE_ID bigint not null, PERMISSION_ID bigint not null, primary key (ROLE_ID, PERMISSION_ID) );

alter table PERMISSIONS_FOR_ROLE add constraint permissions_for_role_perm_fk foreign key (PERMISSION_ID) references PERMISSIONS;

Any suggestions on how to execute such a script ? I tried manually changing the order and the script executes properly but is there any other way to do it as its run as part of a ANT build target.

A: For mass inserts with very large scripts that are out of order, you can disable referential integrity checks with:
SET DATABASE REFERENTIAL INTEGRITY FALSE

see http://hsqldb.org/doc/2.0/guide/management-chapt.html#mtc_sql_settings on how to check for possible violations after the insert.


Q: c# - reading from binary log file that is updated every 6 seconds with 12k of data I have a binary log file with streaming data from a sensor (Int16).
Every 6 seconds, 6000 samples of type Int16 are added, until the sensor is disconnected.
I need to poll this file on regular intervals, continuing from last position read.
Is it better to
a) keep a filestream and binary reader open and instantiated between readings
b) instantiate filestream and binary reader each time I need to read (and keep an external variable to track the last position read)
c) something better?
EDIT: Some great suggestions so far, need to add that the "server" app is supplied by an outside source vendor and cannot be modified.

A: If it's always adding the same amount of data, it may make sense to reopen it. You might want to find out the length before you open it, and then round down to the whole number of "sample sets" available, just in case you catch it while it's still writing the data. That may mean you read less than you could read (if the write finishes between you checking the length and starting the read) but you'll catch up next time.
You'll need to make sure you use appropriate sharing options so that the writer can still write while you're reading though. (The writer will probably have to have been written with this in mind too.)

A: Can you use MemoryMappedFiles?
If you can, mapping the file in memory and sharing it between processes you will be able to read the data by simply incrementing the offset for your pointer each time.
If you combine it with an event you can signal your reader when he can go in an read the information. There will be no need to block anything as the reader will always read "old" data which has already been written.

A: I would recommend using pipes, they act just like files, except stream data directly between applications, even if the apps run on different PCs (though this is really only an option if you are able to change both applications). Check it out under the "System.IO.Pipes" namespace.
P.S. You would use a "named" pipe for this (pipes are supported in 'c' as well, so basically any half decent programming language should be able to implement them)

A: I think that (a) is the best because:

*

*Current Position will be incremented as you read and you don't need to worry about to store it somewhere;

*You don't need to open it and seek required position (it shouldn't be much slower to reopen but keeping it open gives OS some hints for optimization I believe) each time you poll it;

*Other solutions I can think out requires PInvokes to system interprocess synchronisation primitives. And they won't be faster than file operations already in framework.

You just need to set proper FileShare flags:
Just for example:
Server:
using(var writer = new BinaryWriter(new FileStream(@"D:\testlog.log", FileMode.Append, FileAccess.Write, FileShare.Read)))
{
    int n;
    while(Int32.TryParse(Console.ReadLine(), out n))
    {
        writer.Write(n);
        writer.Flush(); // write cached bytes to file
    }
}

Client:
using (var reader = new BinaryReader(new FileStream(@"D:\testlog.log", FileMode.Open, FileAccess.Read, FileShare.ReadWrite)))
{
    string s;
    while (Console.ReadLine() != "exit")
    {
        // allocate buffer for new ints
        Int32[] buffer = new Int32[(reader.BaseStream.Length - reader.BaseStream.Position) / sizeof(Int32)];

        Console.WriteLine("Stream length: {0}", reader.BaseStream.Length);
        Console.Write("Ints read: ");
        for (int i = 0; i < buffer.Length; i++)
        {
            buffer[i] = reader.ReadInt32();
            Console.Write((i == 0 ? "" : ", ") + buffer[i].ToString());
        }
        Console.WriteLine();
    }
}

A: you could also stream the data into a database, rather than a file as another alternative, then you wouldn't have to worry about file locking.
but if you're stuck with the file method, you may want to close the file each time you read data from it; it depends alot on how complicated the process writing to the file is going to be, and whether it can detect a file locking operation and respond appropriately without crashing horribly.


Q: Docker and localhost seem not to connect as should So Im new to Docker and wanted to start a docker container with a apache system on it that should just show one simple "hello world" php-file.
I followed a youtube tutorial for that.
Now I could set up the container and I could run the image, I also connected the port of the container with the port outside, but it seems like its not working.
My http://localhost:80 (<- I connected Port 80 to port 80 in the container) and nothing happened.
Is it possible, that my firewall is killing the connection?
Here is the dockerfile and my php file:
PHP
<? php
echo "Hello World";

Dockerfile
FROM php:7.0-apache
COPY src/ /var/www/html
EXPOSE 80

The tutorial is this one:
https://www.youtube.com/watch?v=YFl2mCHdv24
Unfortunately my knowledge is so limited, that I have not even an idea where to search for the probelm.
Edit:
After building my container I used
docker run -p 80:80 <name of container>

Thanks for taking your time

A: You have to run the image with the -p option like:
docker run -p 80:80 <image name>

Expose is only working for internal docker image communication. -p then maps the host port to the container port:
-p <host_port>:<container_port>


Q: Kubernetes pod readiness probe failed I have a kubernetes cluster running with minikube in my local. I am trying to train a model with KubeFlow's TFJob operator which implements TensorFlow's distributed training strategies.
The YAML for the TFJob looks like this
apiVersion: kubeflow.org/v1
kind: TFJob
metadata:
  name: tf-job-cifar
  namespace: kubeflow
spec:
  tfReplicaSpecs:
    Worker:
      replicas: 2
      restartPolicy: Never
      template:
        metadata:
          annotations:
            kubectl.kubernetes.io/default-container: tensorflow
        spec:
          containers:
            - name: tensorflow
              imagePullPolicy: IfNotPresent
              image: tf-dist-cifar10:1.0
              livenessProbe:
                exec:
                  command:
                    - cat
                    - /tmp/healthy
                initialDelaySeconds: 10
                periodSeconds: 5
              readinessProbe:
                exec:
                  command:
                    - cat
                    - /tmp/healthy
                initialDelaySeconds: 10
                periodSeconds: 5

When I deploy this YAML using kubectl create -f <file-name>.yaml. The pods thus created for the job fails with error:
Readiness probe failed: Get "http://172.17.0.31:15021/healthz/ready": dial tcp 172.17.0.31:15021: connect: connection refused

The error after few minutes changes to:
Readiness probe failed: Get "http://172.17.0.31:15021/healthz/ready": context deadline exceeded (Client.Timeout exceeded while awaiting headers)

Where could possibly the error be?


Q: Issues with font/text-color in css I keep having issues with the text-color rule in css whereas I'll have a code like this:
#horizontal > ul > li > a:hover {
    background-color: rgb(255,101,101);
    text-color: black;

And the background color will change, but the text remains blue.

A: The colour property in CSS is 'color' not 'text-color'.

A: Use color: black; "text-color" is not a function.

A: Use color
#horizontal > ul > li > a:hover {
    background-color: rgb(255,101,101);
    color: black;


Q: Authenticating gcloud SDK in Cloud Run with user credentials I'm currently working on a project that will automatically set up a new Firebase/Gcloud project. It relies heavily on the Firebase CLI and gcloud SDK with user credentials for several mandatory steps.
I am now trying to move this project to a Docker container on Cloud Run. I have been able to authenticate the Firebase CLI with user credentials using their built-in token-based CI command.
I would like to ask if it's possible to authenticate the gcloud SDK using a similar method.
Why service accounts probably won't work
I realize that service-to-service programs like this should be authenticated with service accounts. In my case, however, the flow of the program goes like this:

*

*Use Firebase CLI to create a new gcloud/firebase project

*Use gcloud SDK to add IAM-bindings, enable APIs, billing, etc. for the new project

I am unable to use a service account to authenticate the requests in step 2 as the project has only just been created and I therefore haven't yet had the opportunity to give any service accounts permission to edit it or download the key-files. This is why I'd like to authenticate with a token representing user credentials.
By default, the Cloud Run environment actually has access to a service account for the project hosting the container. Since this service account doesn't have permission to edit the newly created project, using it for authenticating is pointless.
Ideas so far

*

*gcloud auth login --no-launch-browser - Requires user interaction and the key that is provided seems to be unique per login session

*Since the Firebase CLI is authenticated with user credentials, maybe there's a way to use that to authenticate the gcloud SDK?

*Would it be possible to let a service account inherit all permissions from a user? I have seen a couple of examples of this, but they only work on a per-project level. I realize how unseemly this solution would be.

*The gcloud SDK seems to save user credentials in the /root/.config/gcloud folder. I went against all sensible logic and copied this folder over when setting up my Docker-container. This actually works, when I run it on a local Docker container, but when I run it on Cloud Run, the default service account seems to override all other credentials. A local Docker container can access the copied configurations, but even though the files are copied successfully, the gcloud SDK doesn't seem to recognize them.

EDIT:
My intentions are to allow less tech-savvy colleges to create a new Firebase project with a large set of pre-defined settings via the click of a button. This includes the following steps:

*

*Set up a new Firebase project (which automatically sets up a new Google Cloud project)

*Enable billing

*Set user IAM roles and upgrade/download service accounts

*Add Google Analytics

*Add Cloud storage

*Create new Cloud storage bucket

*Add Firestore Native mode

*Copy pre-defined cloud functions and security roles and deploy them to the cloud

The created Google Cloud project must be a part of our Google Cloud organization. The owner of the project is not important as I manually set IAM roles after creation.
All of the above steps work on my local system and when I use idea #4, they also work on a generic docker container outside of Cloud Run. The problems I'm dealing with is authenticating the request for step #2 and step #3. As both of these requests deal with the newly created project, the default service identity for Cloud Run can't have the required roles to authenticate these requests at this time. This is why I am looking for a way to authenticate via the same user credentials used in step #1 by the Firebase CLI, as those credentials will have owner privileges by default.

A: I'm not sure that what you want to achieve is possible. And even if a hack is possible, you don't know if a day it will be broken because of version update or API change.
In addition, using a personal account into an app running on a VM is not a good idea. The log will trace you as user and not the app identity (the service account). What are your personal actions (on your computer and your access to the Cloud) and the app actions (those perform on behalf of you)?
If your concern is about the deployment, you can have a look to terraform or you can even script you own deployment.
I'm not sure to have caught all your blockers and problems, tell us more, maybe there is good workaround!!


Q: PHP cannot connect to LDAP Oracle Directory Server Enterprise Edition Been playing with this for days and can not get php to bind to ldap on Oracle's DSEE.
function test(){

    // LDAP variables
    $ldaphost = "xxx.xxxxx.com";
    $ldapport = 636;
    $ldaprdn  = 'cn=xyxyxyxy,ou=Accounts,dc=xxx,dc=xxxxx,dc=com';
    $ldappass = 'vcvcvcvcvc';

    ldap_set_option(NULL, LDAP_OPT_DEBUG_LEVEL, 7); // isn't helping

    // Connecting to LDAP
    $ldapconn = ldap_connect($ldaphost, $ldapport)
              or die("Could not connect to $ldaphost");

    if ($ldapconn) {

        // binding to ldap server
        $ldapbind = ldap_bind($ldapconn, $ldaprdn, $ldappass);

        // verify binding
        if ($ldapbind) {
            echo "LDAP bind successful...";
        } else {
            echo "LDAP bind failed...";
        }

    }
}

I get the error:
Message: ldap_bind() [function.ldap-bind]: Unable to bind to server: Can't contact LDAP server
Tearing my hair out on this one. I just can't get the thing to bind.
Have tried a straight telnet to the host on port 636 and am not being blocked by any firewall. Peculiarly I am not getting any extra debug info from the 'LDAP_OPT_DEBUG_LEVEL' on screen or in my logs.

A: start_tls() and ldaps is mutually exclusive, meaning you cannot issue start_tls() on the ssl port (standard 636), or initiate ldaps on an unecrypted port (standard 389). The start_tls() command initiate a secure connection on the unencrypted port after connection is initiated, so you would then issue this before the bind takes place to make it encrypted. Another set of common ports is 3268 (unecrypted) and 3269 (ssl) which might be enabled in your server.
ldap_set_option(NULL, LDAP_OPT_DEBUG_LEVEL, 7);
is logging to your web servers error log, depending on your log level, or to stout (from PHP CLI). To gain more information here, check your web server log level setting, or simply run your php script from command line.
To successfully use the ssl port, you need to specify the ldaps:// prefix, while on the unencrypted port this is not necessary  (with a ldap:// prefix).
Looking at your code, this could be a protocol version issue as PHP by default use version 2. To solve this, you can issue:
ldap_set_option($conn, LDAP_OPT_PROTOCOL_VERSION,3);
ldap_set_option($conn, LDAP_OPT_REFERRALS,0);

before you attempt to bind.
You can also have a look at the code in Problems with secure bind to Active Directory using PHP which I successfully use in CentOS 5, but is having problems in Ubuntu. If your server has an open unencrypted port, it's a good idea to do an unencrypted test bind against it to rule out any connectivity issues.
To check if the port is open, you can check if telnet connects to it, E.G:
telnet my.server.com 3268

If the port is open, then you should be able to bind using it.
*Edit: If the ssl certificate is deemed invalid, the connection will fail, if this is the case, setting the debug level to 7 would announce this. To get around this specific problem you need to ignore the validity:
You can ignore the validity in windows by issuing
putenv('LDAPTLS_REQCERT=never');

in your php code. In *nix you need to edit your /etc/ldap.conf to contain
TLS_REQCERT never

A: The port 636 is the SSL enabled port and requires an SSL enabled connection.
You should try to connect on port 389, or change your code to include the secure layer (much more complex).
Kind regards,
Ludovic

A: To connect using SSL you should try
$ldapconn = ldap_connect('ldaps://'.$ldaphost);

This will automatically connect on port 636 which is the default ldaps-port. Depending on your server installation and configuration it may be possible that connections are only allowed on port 389 (using no encryption or using TLS) or only on port 636 using SSL-encryption. Although it might be possible that your server exposes other ports. So in general you need to know which port you're gonna connect to and which encryption method the server requires (no encryption, SSL or TLS).

A: Is the certificate of the LDAP server signed by a valid CA? Maybe your client just rejects the certificate!


Q: RAR file downloaded with C# becoming corrupt I'm download a .rar file from a github release but the downloaded file is becoming corrupt. The file is fine it's just not working when I download it with code
this is my current code
WebClient wc = new WebClient();
Uri fileLink = new Uri("https://api.github.com/repos/{my name}/{my repo}/releases/latest");
wc.DownloadFileCompleted += new AsyncCompletedEventHandler(UpdateCompleted);
wc.DownloadFileAsync(fileLink, $@"{appRoot}\updated.rar");

A: My best guess is that the file that you want to download is not a .rar but some text (html or json) that contains information for the real download.
Can you open the downloaded file with notepad to see what it contains?
According to https://docs.github.com/en/rest/releases/releases#get-the-latest-release, it should contains a json file with some assets that contain the real download link.

A: You need to keep the WebClient instance alive during the download. What does that mean?
If the WebClient instance is only hold in the wc variable, and wc is being local to whatever method which contains the code in your question, then as soon as this method returns, the wc variable gets out of scope.
If there is no other field/property/whatever holding a reference to the WebClient instance, the WebClient instance becomes subject to the next garbage collection.
Normally, you cannot predict when a garbage collection happens (well, you can, but it's a complicated topic for another day...). If it so happens that the garbage collection happens while the download is still in progress, well, the WebClient instance will be finalized and destroyed anyway, effectively aborting download and leaving you with a partially downloaded file.
Another possibility is that your program just exits without actually waiting for the download to complete before exiting, again leaving you with a partially downloaded file.
Are there other possibilities of what might have gone wrong there with your download? Sure, there are. But for me, it's enough tea leaves reading for a day, so i leave the troubleshooting and debugging of your program and inspection of the downloaded data to you...


Q: Elasticsearch ILM index data is not shifting/migrating We have created ILM (index lifecycle management) policies, to automate index rollover using a matching index template and a bootstrap index to enable write index with an alias.
Please find the below API code:
Polices
{
  "policy": {
    "phases": {
      "hot": {
        "min_age": "0ms",
        "actions": {
          "rollover": {
            "max_size": "50mb",
            "max_primary_shard_size": "50mb",
            "max_age": "30m"
          },
          "set_priority": {
            "priority": 200
          }
        }
      },
      "cold": {
        "min_age": "5m",
        "actions": {
          "searchable_snapshot": {
            "snapshot_repository": "found-snapshots",
            "force_merge_index": true
          },
          "set_priority": {
            "priority": 0
          }
        }
      },
      "frozen": {
        "min_age": "10m",
        "actions": {
          "searchable_snapshot": {
            "snapshot_repository": "found-snapshots",
            "force_merge_index": true
          }
        }
      },
      "delete": {
        "min_age": "1h",
        "actions": {
          "delete": {
            "delete_searchable_snapshot": true
          }
        }
      }
    }
  }
}

Template
PUT _index_template/sree
{
"index_patterns":["sree-*"],
"template":{
"settings":{
"number_of_shards":1,
"number_of_replicas":1,
"index.lifecycle.name":"sree",
"index.lifecycle.rollover_alias":"sree"
}
}
}

Bootstrap Index:
PUT sree-000001
{
"aliases":{
"sree":{
"is_write_index":true
}
}
}

Note: I'm using logstash to send data to elastic search by using the elasticsearch output plugin.
Here is the output plugin code:
output {
        elasticsearch {
                hosts => "https:xyz:9243"
                user => "elastic"
                password => "xyz"
                index => "sree-"
                ilm_enabled => true
        }

}

For the above scenario, I'm successfully creating index and index-alias, indexes are moving to next nodes like cold/frozen but data is not shifting/migrating.
So, can anyone please help us to resolve this issue?


Q: if a process mallocs memory and then forks, will the child process have a proper malloced memory For the following code :
main() {
    int *p = (int *)malloc(2*sizeof(int)) ;
    if(fork()) wait() ;
    else *p = 10 ;
}

I want to know that when we fork does the child process receive the malloced block in its process space too. That is, in the above code is it safe to say --:
*p = 10 ;

A: Yes the child will have proper malloc()ed memory.
First, know that there are two memory managers in place:

*

*One is the Linux kernel, which allocates memory pages to processes. This is done through the sbrk() system call.

*On the other hand, malloc() uses sbrk() to request memory from the kernel and then manages it, by breaking it in chunks, remembering how the memory has been divided and later mark them as available when free()ed (and at times perform something similar to garbage collection).

That said, what malloc() does with memory is completely transparent to the Linux kernel. It's effectively just a linked list or two, which you could have implemented yourself. What the Linux kernel sees as your memory are the pages assigned to your process and their contents.
When you call fork() (emphasis mine):

*

*The child process is created with a single thread--the one that called fork(). The entire virtual address space of the parent is replicated in the child, including the states of mutexes, condition variables, and other pthreads objects; the use of pthread_atfork(3) may be helpful for dealing with problems that this can cause.

*The child inherits copies of the parent's set of open file descriptors. Each file descriptor in the child refers to the same open file description (see open(2)) as the corresponding file descriptor in the parent. This means that the two descriptors share open file status flags, current file offset, and signal-driven I/O attributes (see the description of F_SETOWN and F_SETSIG in fcntl(2)).

*The child inherits copies of the parent's set of open message queue descriptors (see mq_overview(7)). Each descriptor in the child refers to the same open message queue description as the corresponding descriptor in the parent. This means that the two descriptors share the same flags (mq_flags).

*The child inherits copies of the parent's set of open directory streams (see opendir(3)). POSIX.1-2001 says that the corresponding directory streams in the parent and child may share the directory stream positioning; on Linux/glibc they do not.

So fork() not only copy the entire virtual address space, but also all mutexes, file descriptors and basically every kind of resource the parent has opened. Part of the virtual address space copied is the linked list(s) of malloc(). So after a fork(), the malloc()ed memories of both processes are equal and the information malloc() keeps and what memory is allocated is also the same. However, they now live on separate memory pages.

Side information: One might think that fork() is a very expensive operation. However (from the man page):

Under Linux, fork() is implemented using copy-on-write pages, so the only penalty that it incurs is the time and memory required to duplicate the parent's page tables, and to create a unique task structure for the child.

This basically says that on fork()ing, no actual copying is done, but the pages are marked to be copied if the child tries to modify them. Effectively, if the child only reads from that memory, or completely ignore it, there is no copy overhead. This is very important for the common fork()/exec() pattern.


Q: Can Azure IOT hub be used to read(Get) data from some devices? In my case I have 1000+ of devices that stores activity inside. I need to send a http get request to this device to get those data in csv or json format and save it in a storage hosted on azure.
Cab IOT hub require data using get request and can it be scheduled to read daily/weekly?
What other azure services would you suggest to facilitated this scheduled reads?

A: You have not mentioned which the Azure IoT Hub scale tier is used. Basically there are two price groups such as Basic and Standard with a significant different cost and capabilities. The Basic tier offers only services for one-way communications between the devices and Azure IoT Hub.
Based on that, the following scenarios can be used for your business case:
1. Basic Tier (non event-driven solution)
The device pushs periodicaly a telementry and non-telemetry messages based on the needs to the Azure IoT Hub, where the non-telemetry messages are routed to the Azure Function via the Service Bus Queue/Topic. Responsibility for this non-telemetry pipe is to persist a real device state in the database. Note, that the 6M messages will cost only $50/month. The back-end application can any time to query this database for devices state.
2. Standard Tier (event-driven solution) In this scenario you can use a Device Twin of the Azure IoT Hub to enable storing a real-device state in the cloud-backend (described by @HelenLo). The device can be triggered by C2D message, changing a desired property, invoking a method or based on the device edge trigger to the action for updating a state (reported properties).
The Azure IoT Hub has a capabilities to run your scheduled jobs for multiple devices.
In this solution, the back-end application can call any time a job for ExportDevicesAsync to the blob storage, see more details here. Note, that the 6M messages will cost $250/month.
As you can see the above each scenario needs to build a different device logic model based on the communications capabilities between the devices and Azure IoT Hub and back. Note, there are some limitations for these communications, see more details here.

A: You can consider using Device Twin of IoT Hub
https://learn.microsoft.com/en-us/azure/iot-hub/iot-hub-devguide-device-twins
Use device twins to:

*

*Store device-specific metadata in the cloud. For example, the deployment location of a vending machine.

*Report current state information such as available capabilities and conditions from your device app. For example, a device is connected to your IoT hub over cellular or WiFi.

*Synchronize the state of long-running workflows between device app and back-end app. For example, when the solution back end specifies the new firmware version to install, and the device app reports the various stages of the update process.

*Query your device metadata, configuration, or state.

A: IoT Hub provides you with the ability to connect your devices over various protocols. Preferred protocols are messaging protocols, such as MQTT or AMQP, but HTTPS is also supported. Using IoT hub, you do not request data from the device, though. The device will send the data to the IoT Hub. You have to options to implement that with IoT Hub:

*

*The device connects to the IoT Hub whenever it has some data to be sent, and pushes the data up to IoT Hub

*The device does not send any data on its own, but stays always or at least regularly connected to IoT Hub. You then can send a cloud to device message over IoT Hub to the device, requesting the data to be sent. The device then sends the data the same way it would in the first option.

When the data then has been sent to IoT Hub, you need to push it somewhere where it is persistently stored - IoT Hub only keeps messages for 1 day by default. Options for this are:

*

*Create a blob storage account and push to that directly from IoT Hub using a custom endpoint This would probably be the easiest and cheapest. Dependening on how you need to access your data, a blob might not be the best option, though

*Create a function app, create a function with an EventHubTrigger, connect it to IoT Hub and let the function process incoming data by outputting it into any kind of data sink, such as SQL, CosmosDB, Table Storage...


Q: lockDays in Litepicker Js Using Litepicker (https://github.com/wakirin/litepicker/) I'm having troubles adding lockDays to my calendar.
I'm retrieving some data from my DB and this is the JSON answer:
{
    "error":0,
    "reservation_counter":1,
    "reservations":[
        {
            "start_date":"2022-02-28 00:00:00",
            "end_date":"2022-03-02 00:00:00"
        }
    ]
}

Then I format the dates fields with this JS script
const obj = JSON.parse(result);
if(parseInt(obj.error) === 0) {
    var lockedArray = [];
    if(parseInt(obj.reservation_counter) > 0){
        for (let i = 0; i < parseInt(obj.reservation_counter); i++) {
            let subArray = [obj.reservations[i].start_date.slice(0, 10), obj.reservations[i].end_date.slice(0, 10)];
            lockedArray.push(subArray);
        }
    }
}

The output of this code is, as string: [["2022-02-28", "2022-03-02"]], so is compliant with the Litepicker format.
To render the calendar, I use this script:
$('input[name="litepicker"]').daterangepicker({
    parentEl: "#calendarelement-div",
    opens: 'center',
    inlineMode: false,
    minDate: new Date(),
    autoUpdateInput: true,
    singleMode: false,
    locale: {
        format: "DD/MM/YYYY",
        separator: " - "
     },
     lockDaysFormat: 'YYYY-MM-DD',
     lockDays: lockedArray,
     disallowLockDaysInRange: true,
     highlightedDays: lockedArray
});

The calendar is fully working, but it not locks the dates. I tried with hand-coded dates, but nothing.
This is an image of the result:

The expected resut is dates between 2022-02-28 and 2022-03-02 are locked, as JSON data.
I post the entire code to show the chronological order of the code
$.ajax({
        url: 'php/getbedroomavailability.php',
        type: 'GET',
        data: { space: space, offer: offer, guests: guests},
        dataType: "text",
        success: function(result){
            console.log(result);
            const obj = JSON.parse(result);
            if(parseInt(obj.error) === 0) {
                // No error
                var lockedArray = [];
                if(parseInt(obj.reservation_counter) > 0){
                    // Some reservations
                    for (let i = 0; i < parseInt(obj.reservation_counter); i++) {
                        let subArray = [obj.reservations[i].start_date.slice(0, 10), obj.reservations[i].end_date.slice(0, 10)];
                        lockedArray.push(subArray);
                    }
                }
                $('input[name="litepicker"]').daterangepicker({
                    parentEl: "#calendarelement-div",
                    opens: 'center',
                    inlineMode: false,
                    minDate: new Date(),
                    autoUpdateInput: true,
                    singleMode: false,
                    locale: {
                        format: "DD/MM/YYYY",
                        separator: " - "
                    },
                    lockDaysFormat: 'YYYY-MM-DD',
                    lockDays: lockedArray,
                    disallowLockDaysInRange: true,
                    highlightedDays: lockedArray
                });
                document.getElementById("ava-box").style.display = "block";
                document.getElementById("over-shadow").style.display = "block";
                simulateClick(document.getElementById("litepicker"));
                document.getElementById("selectfareckt").onclick = function () {
                    goCheckout(space, offer);
                }
            }
            else {
                alert(obj.error_msg);
            }
        }
    });


Q: SQLAlchemy relationship between inherited tables throws primary key error I'm trying to set up a joined inheritance in SQLAlchemy which is working fine. My schema design requires a one-to-many relationship between two inherited table. My actual working example is quite complex but I was able to reproduce the issue with the SQLAlchemy joined inheritance tutorial code.
"""Joined-table (table-per-subclass) inheritance example."""

from sqlalchemy import Column
from sqlalchemy import create_engine
from sqlalchemy import ForeignKey
from sqlalchemy import inspect
from sqlalchemy import Integer
from sqlalchemy import or_
from sqlalchemy import String
from sqlalchemy.ext.declarative import declarative_base
from sqlalchemy.orm import relationship
from sqlalchemy.orm import Session
from sqlalchemy.orm import with_polymorphic

Base = declarative_base()

class Resource(Base):
    __tablename__ = "resource"
    id = Column(Integer, primary_key=True)
    # Permissions and other common columns.
    # Left out for simplicity
    type = Column(String(50))

    __mapper_args__ = {
        "polymorphic_identity": "resource",
        "polymorphic_on": type,
    }

class ChildResource(Resource):
    __tablename__ = "child_resource"
    id = Column(ForeignKey("resource.id"), primary_key=True)
    name = Column(String(30))

    parent_id = Column(ForeignKey('parent_resource.id'), nullable=False)
    parent = relationship('ParentResource', back_populates='children', foreign_keys=parent_id)

    __mapper_args__ = {"polymorphic_identity": "child_resource"}

class ParentResource(Resource):
    __tablename__ = "parent_resource"
    id = Column(ForeignKey("resource.id"), primary_key=True)
    name = Column(String(30))

    children = relationship('ChildResource', back_populates='parent', foreign_keys='ChildResource.id')

    __mapper_args__ = {"polymorphic_identity": "parent_resource"}

if __name__ == "__main__":
    engine = create_engine("sqlite://", echo=True)
    Base.metadata.create_all(engine)

    session = Session(engine)

    res_child = ChildResource(
                name="My child shared resource",
            )

    res_parent = ParentResource(
                name="My parent shared resource"
            )

    res_parent.children.append(res_child)
    session.add(res_child)
    session.add(res_parent)

    session.commit()

So I have a ParentResource and a ChildResource. Both are inherited from a common Resource class (in real life the common base is necessary it contains much more columns). Between the ParentResource and the ChildResource there is a one-to-many relationship. The tables are created correctly in sqlite & postgres, but when I try add one parent and one child object to the session I've got the following error:
sqlalchemy.exc.IntegrityError: (sqlite3.IntegrityError) UNIQUE constraint failed: resource.id
[SQL: INSERT INTO resource (id, type) VALUES (?, ?)]
[parameters: (1, 'child_resource')]
(Background on this error at: http://sqlalche.me/e/gkpj)

When I check the SQLAlchemy echo I see the following.
2020-06-17 07:28:42,276 INFO sqlalchemy.engine.base.Engine ()
2020-06-17 07:28:42,276 INFO sqlalchemy.engine.base.Engine COMMIT
2020-06-17 07:28:42,280 INFO sqlalchemy.engine.base.Engine BEGIN (implicit)
2020-06-17 07:28:42,280 INFO sqlalchemy.engine.base.Engine INSERT INTO resource (type) VALUES (?)
2020-06-17 07:28:42,280 INFO sqlalchemy.engine.base.Engine ('parent_resource',)
2020-06-17 07:28:42,281 INFO sqlalchemy.engine.base.Engine INSERT INTO parent_resource (id, name) VALUES (?, ?)
2020-06-17 07:28:42,281 INFO sqlalchemy.engine.base.Engine (1, 'My parent shared resource')
2020-06-17 07:28:42,281 INFO sqlalchemy.engine.base.Engine INSERT INTO resource (id, type) VALUES (?, ?)
2020-06-17 07:28:42,281 INFO sqlalchemy.engine.base.Engine (1, 'specific_resource_1')
2020-06-17 07:28:42,281 INFO sqlalchemy.engine.base.Engine ROLLBACK

It's looks like res_child and res_parent will get the same primary key which of course breaks the pk constraint.
What am I doing wrong?

A: As above_c_level suggested the minimal solution is to change the primary key column name in the base class. The mistake what I made both the base class and the subclass had the "id" property which was overriden by the subclass. You can find below the working code sample.
"""Joined-table (table-per-subclass) inheritance example."""

from sqlalchemy import Column
from sqlalchemy import create_engine
from sqlalchemy import ForeignKey
from sqlalchemy import inspect
from sqlalchemy import Integer
from sqlalchemy import or_
from sqlalchemy import String
from sqlalchemy.ext.declarative import declarative_base
from sqlalchemy.orm import relationship
from sqlalchemy.orm import Session
from sqlalchemy.orm import with_polymorphic

Base = declarative_base()

class Resource(Base):
    __tablename__ = "resource"
    resource_id = Column(Integer, primary_key=True)
    # Permissions and other common columns.
    # Left out for simplicity
    type = Column(String(50))

    __mapper_args__ = {
        "polymorphic_identity": "resource",
        "polymorphic_on": type,
    }

class ChildResource(Resource):
    __tablename__ = "child_resource"
    id = Column(ForeignKey("resource.resource_id"), primary_key=True)
    name = Column(String(30))

    parent_id = Column(ForeignKey('parent_resource.id'), nullable=False)
    parent = relationship('ParentResource', back_populates='children', foreign_keys=parent_id)

    __mapper_args__ = {"polymorphic_identity": "child_resource", "inherit_condition": id == Resource.resource_id}

class ParentResource(Resource):
    __tablename__ = "parent_resource"
    id = Column(ForeignKey("resource.resource_id"), primary_key=True)
    name = Column(String(30))

    children = relationship('ChildResource', back_populates='parent', foreign_keys='ChildResource.id')

    __mapper_args__ = {"polymorphic_identity": "parent_resource", "inherit_condition": id == Resource.resource_id}

if __name__ == "__main__":
    engine = create_engine("sqlite://", echo=True)
    Base.metadata.create_all(engine)

    session = Session(engine)

    res_child = ChildResource(
                name="My child shared resource",
            )

    res_parent = ParentResource(
                name="My parent shared resource"
            )

    res_parent.children.append(res_child)
    session.add(res_child)
    session.add(res_parent)

    session.commit()


Q: Is there an equivalent to Java -Xmx for python? I am used to running .command scripts with terminal that use java, which allocates an amount of memory by the arguments -Xmx and -Xms.
I am now using a .sh script with python and can't seem to figure out what the equivalent is.
EDIT: Let me explain a little more. Is it possible to do that in the shell script or am I stuck decompiling Python scripts?


Q: Not able to install Tomcat9 to Netbeans 8.0.2 Need some help. Its my first time with netBeans and i am trying to install Tomcat server9 with netbeans 8.0.2.
I am succesfully using it with eclipse but
I googled ofcourse but none of the solution seemed to work. My CATALINA_HOME is set and pointing to tomcat location. In Path i added %CATALINA_HOME%\bin
But when i try to add it in netbeans  It gives the error:
" The specified Server Location (Catalina Home) folder is not valid.
Can someone please help me
Thanks


Q: Using request count for hpa I am trying to deploy HorizontalPodAutoscaler on GKE referring the following
link
#HPA.yaml
apiVersion: autoscaling/v2beta1
kind: HorizontalPodAutoscaler
metadata:
  name: hello-hpa
spec:
  minReplicas: 1
  maxReplicas: 5
  metrics:
  - external:
      metricName: loadbalancing.googleapis.com|https|backend_request_count
      metricSelector:
        matchLabels:
          resource.labels.forwarding_rule_name:
            k8s-fw-default-hello-hpa--fbeacb94cfa9120e
      targetAverageValue: "1"
    type: External
  scaleTargetRef:
    apiVersion: apps/v1
    kind: Deployment
    name: hello-hpa

Here k8s-fw-default-hello-hpa--fbeacb94cfa9550e is the name of the forwarding rule in ingress.
The above works for us but we would like to automate the deployment process where even when there is a change in the Ingress/HPA object it should work without human intervention. AFAIK the forwarding rule name changes per deployment and this requires us to go and change the HPA object accordingly.
Is there some way to get that value as a reference to point to something that is same across deployments?
Where can I describe the external metrics to see if we can use some other selector? Referenced this and this but did not find anything
It would be great if I could use the service name (or may be service name and project id pair) to filter.
example-
       matchLabels:
          resource.labels.forwarding_rule_name:
            k8s-fw-default-hello-hpa.*

OR
       matchLabels:
          resource.labels.backend_name: hello-hpa

OR
       matchLabels:
          resource.labels.backend_name: hello-hpa
          resource.labels.project_id: hello-project


Q: Cloudfront CloudFormation We have option to get the value of DomainName in cloudformation template while creating a CloudFront Distribution using Fn::GetAtt function. But I could not find anywhere that how we get Origin's Id and DefaultCacheBehaviour's TargetOriginId dynamically?
Can I just use Ref to my S3 and ELB?
This is my code, I have used some parameters also and changed the Cloudfront code as well. Please check it once whether it is correct or not.
And it is throwing me an error called "Property validation failure: [Encountered unsupported properties in {/DistributionConfig/Origins/1/S3OriginConfig}: [HTTPSPort, HTTPPort, OriginProtocolPolicy]]"
{
    "AWSTemplateFormatVersion": "2010-09-09",
    "Parameters": {
        "ClientName": {
            "Type": "String",
            "Description": "Name of the Client"
        },
        "EnvName": {
            "Type": "String",
            "Description": "Name of the Environment"
        }
    },
    "Resources": {
        "distd2v0l803ay8odocloudfrontnet": {
            "Type": "AWS::CloudFront::Distribution",
            "Properties": {
                "DistributionConfig": {
                    "Enabled": true,
                    "DefaultRootObject": "index.html",
                    "PriceClass": "PriceClass_All",
                    "CacheBehaviors": [
                        {
                            "TargetOriginId": {
                                "Ref": "elbhtlbetaelb"
                            },
                            "PathPattern": "/app*",
                            "ViewerProtocolPolicy": "allow-all",
                            "MinTTL": 0,
                            "AllowedMethods": [
                                "HEAD",
                                "DELETE",
                                "POST",
                                "GET",
                                "OPTIONS",
                                "PUT",
                                "PATCH"
                            ],
                            "CachedMethods": [
                                "HEAD",
                                "GET"
                            ],
                            "ForwardedValues": {
                                "QueryString": true,
                                "Cookies": {
                                    "Forward": "all"
                                }
                            }
                        },
                        {
                            "TargetOriginId": {
                                "Ref": "elbhtlbetaelb"
                            },
                            "PathPattern": "/api*",
                            "ViewerProtocolPolicy": "allow-all",
                            "MinTTL": 0,
                            "AllowedMethods": [
                                "HEAD",
                                "DELETE",
                                "POST",
                                "GET",
                                "OPTIONS",
                                "PUT",
                                "PATCH"
                            ],
                            "CachedMethods": [
                                "HEAD",
                                "GET"
                            ],
                            "ForwardedValues": {
                                "QueryString": true,
                                "Cookies": {
                                    "Forward": "all"
                                }
                            }
                        }
                    ],
                    "DefaultCacheBehavior": {
                        "TargetOriginId": {
                            "Ref": "s3htlbeta"
                        },
                        "ViewerProtocolPolicy": "allow-all",
                        "MinTTL": 0,
                        "AllowedMethods": [
                            "HEAD",
                            "DELETE",
                            "POST",
                            "GET",
                            "OPTIONS",
                            "PUT",
                            "PATCH"
                        ],
                        "CachedMethods": [
                            "HEAD",
                            "GET"
                        ],
                        "ForwardedValues": {
                            "Cookies": {
                                "Forward": "none"
                            }
                        }
                    },
                    "Origins": [
                        {
                            "DomainName": {
                                "Fn::GetAtt": [
                                    "s3htlbeta",
                                    "DomainName"
                                ]
                            },
                            "Id": {
                                "Ref": "s3htlbeta"
                            },
                            "S3OriginConfig": {
                                "OriginAccessIdentity": "origin-access-identity/cloudfront/EYD1QGO9CUDA2"
                            }
                        },
                        {
                            "DomainName": {
                                "Fn::GetAtt": [
                                    "elbhtlbetaelb",
                                    "DNSName"
                                ]
                            },
                            "Id": {
                                "Ref": "elbhtlbetaelb"
                            },
                            "S3OriginConfig": {
                                "HTTPPort": "80",
                                "HTTPSPort": "443",
                                "OriginProtocolPolicy": "http-only"
                            }
                        }
                    ],
                    "Restrictions": {
                        "GeoRestriction": {
                            "RestrictionType": "none",
                            "Locations": []
                        }
                    },
                    "ViewerCertificate": {
                        "CloudFrontDefaultCertificate": "true",
                        "MinimumProtocolVersion": "TLSv1"
                    }
                }
            }
        },
        "s3htlbeta": {
            "Type": "AWS::S3::Bucket",
            "Properties": {
                "AccessControl": "Private",
                "VersioningConfiguration": {
                    "Status": "Suspended"
                }
            }
        }
    },
    "Description": "xxx-beta cloudformation template"
}

A: The DistributionConfig/Origins/ID field should just be a text name, it doesn't need to reference anything.
ie. Set DistributionConfig/Origins/ID to a string e.g. 'MyOriginBucket'
Then your CacheBehaviour TargetOriginId is also a string set to 'MyOriginBucket'
The only Ref required to your new bucket is in Origins/DomainName.
The purpose of the TargetOriginId is to point to the origin ID that you specified in the list of Origins, not point to the bucket name.


Q: Print in terminal after`freopen("file.txt", "wb", stdout);` (or similar solution to preserve a printing function) I want to store the printed output of a function with freopen("file.txt", "wb", stdout); (or another solution, but the function matrix_output_printf() should remained untouched.
However, I want to be able to further print something after having closed fclose(stdout); as shown below but the hello of printf("hello"); does not appear in terminal. Is it possible print hello in another way (on a MacOS system).
/*
 *  main.c
 *  https://stackoverflow.com/questions/75349098/stream-the-output-of-a-void-function-using-printf/75352112#75352112
 */
#include <stdio.h>
#include <stdlib.h>

void matrix_output();

void matrix_output_printf(){
  for (int i = 0; i < 3; i++){
    for (int j = 0; j < 3; j++){
      printf("%d\t", i+j);
    }
    printf("\n");
  }
}

int main ()
{
  freopen("file.txt", "wb", stdout);
  matrix_output_printf();
  fclose(stdout);
  printf("hello");
  return 0;
}

Edit
The code provided in the answer is not working on my MacOS computer ( 'io.h' file not found). Is there another solution portable for UNIX like systems?

A: Tried and tested on my Windows box:
#include <stdio.h>
#include <stdlib.h>
#include <io.h>

void matrix_output_printf() {
    for( int i = 0; i < 3; i++ ) {
        for( int j = 0; j < 3; j++ )
            printf( "%d\t", i+j );
        printf( "\n" );
    }
}

int main( void ) {
    int saved = _dup( fileno( stdout ) );

    freopen( "file.txt", "w", stdout );
    matrix_output_printf();
    fclose( stdout );

    _dup2( saved, 1 );

    printf( "hello\n" );

    return 0;
}

A: If stdout was originally tied to the console, you can reopen the stream to /dev/tty:
#include <stdio.h>

void matrix_output_printf(void) {
    for (int i = 0; i < 3; i++) {
        for (int j = 0; j < 3; j++) {
            printf("%d\t", i + j);
        }
        printf("\n");
    }
}

int main() {
    freopen("file.txt", "w", stdout);
    matrix_output_printf();
    freopen("/dev/tty", "w", stdout);
    printf("hello");
    return 0;
}

This should work on most unix systems, such as macOS, but if stdout was redirected to another file or device, reopening it with freopen won't work.  You could try and duplicate the system handle with dup() and use fdopen() to open a standard stream after closing stdout, but there is no guarantee that the stream returned by fdopen will be the same as stdout.
Using freopen for your purpose is a hack. A much better approach is to rewrite matrix_output_printf to take a FILE * argument for the output stream, or a const char *filename for the name of the file to produce:
void matrix_output_printf(const char *filename) {
    FILE *fp = stdout;
    if (filename) {
        fp = fopen(filename, "w");
        if (fp == NULL) {
            /* handle error */
            return;
        }
    }
    for (int i = 0; i < 3; i++) {
        for (int j = 0; j < 3; j++) {
            fprintf(fp, "%d\t", i + j);
        }
        fprintf(fp, "\n");
    }
    if (filename)
        fclose(fp);
}

A: Another option:

*

*Flush the stream

*Duplicate stdout's file descriptor before calling the function, duplicate a file descriptor open to the desired file to the stream's original file descriptor value

*Call the function

*Restore the original stdout descriptor

Similar to this:
#include <stdio.h>
#include <stdlib.h>
#include <fcntl.h>
#include <sys/stat.h>
#include <unistd.h>

void matrix_output_printf(void){
  for (int i = 0; i < 3; i++){
    for (int j = 0; j < 3; j++){
      printf("%d\t", i+j);
    }
    printf("\n");
  }
}

int main()
{
  int fd = open("file.txt", O_WRONLY | O_CREAT | O_TRUNC, 0644);
  int savedStdoutFD = dup(fileno(stdout));
  fflush(stdout);
  dup2(fd, STDOUT_FILENO);
  close(fd);

  matrix_output_printf();

  fflush(stdout);
  dup2(savedStdoutFD, STDOUT_FILENO);
  close(savedStdoutFD);

  printf("hello\n");
  return 0;
}

Note that this code is inherently unsafe to use in a multithreaded process.
@chqrlie had the best answer: "A much better approach is to rewrite matrix_output_printf to take a FILE * argument for the output stream, or a const char *filename for the name of the file to produce".


Q: Why did css 'position: absolute' stop working? In my site, I have a language bar floating on the top right of the screen.
html:
<form id='form2' name='form2' method='get' action=''>
<div id='langs' class='langs'>
<button type='submit' name='lang' value='PT'>PT</button>
<button type='submit' name='lang' value='EN'>EN</button>
</div></form>

css:
.langs {
    background-color: #90A090;
    position:absolute;
    right:4;
    top:4;
}

So far so good. But when I updated the website to include a login system from here, something went wrong, and the language bar don't float anymore. Instead, it is at the end of the page. There's no css in any file added. And every other aspect of the css still works (like change the background color). The file, that was index.php, is now main.php (index.php is now used for the login screen). The css is all inside the main.php file. What can be causing the change in behavior?

A: your missing the the units of the value
try:
.langs {
    background-color: #90A090;
    position:absolute;
    right:4px; /* right:0; is ok but right:4; will fail */
    top:4px;
}

But you are expected to set position relative to the parent, for better results xD
form#form2 {
  position: relative;
}


Q: Delphi - Two Modal forms I have a main form (A) that call a modal form (B). and (B) call another modal form (C) and they work normal
the problem when I added new modal form (D) and make it called from (B) then when I close the form (D) the form (B) also closed !! although I made sure the close button modal result = mrnone
please advise
Code:
Form A calling B

B := TB.Create(self);
B.ShowModal;

Form B Calling C
C := TC.Create(self);
C.ShowModal;

Form B Calling D
D := TD.Create(self);
D.ShowModal;

I use Delphi 2010
More Code added
this is how I free the form that cause the problem and make the caller close !
procedure TForm2.FormClose(Sender: TObject; var Action: TCloseAction);
begin
  action := cafree;
end;

procedure TForm2.FormDestroy(Sender: TObject);
begin
  Form2 := nil;
end;

This is how I show the modal form
procedure Tmymodalfrm.Button1Click(Sender: TObject);
begin
  form2 := Tform2.Create(self);
  form2.ShowModal;
end;

And after tracing with the call stack I get the code that originally created form B which is so normal:
   B := TB.Create(self);
   B.ShowModal;

and I am going crazy soon :)

A: Found the problem. the button that call the form has a modal result = mrclose !!


Q: How to get the Google Custom Search (V2) to execute immediately with a pre-loaded search string? I've been tasked with adding GCS to a website. After I followed the instructions to create my free GCS (http://www.google.com/cse/sitesearch/create), and pasted the supplied snippet into the appropriate place, the search box & button components render OK and the user is able to enter a search string, run the search and see the results. So far so good.
However, when the components render for the first time I want to be able to pass a pre-entered string into the box and programmatically have the search executed immediately. This bit is not working.
The code I currently have in place is as follows, consisting of the supplied snippet plus some extra code derived from my reading of the Custom Search Element Control API doc (https://developers.google.com/custom-search/docs/element) and intended to implement the 'execute immediate':

    <gcse:search> gname="2DSearch"</gcse:search>

primarySearch is the string I want to automatically search on. When the components render, the string 'gname="2DSearch"' appears briefly then disappears again just before the search components appear, then nothing else happens.
There appear to be some similarities here with this question (unanswered): https://stackoverflow.com/questions/15871911/passing-optional-search-parameters-into-google-custom-search-query
I have searched the Web in vain for a number of hours for anything else relevant.
Can anybody tell me why it's not working and/or what I need to do?
My apologies, I have done alot of programmming but am virtually illiterate when it comes to HTML & javascript.
Thanks
Jim
I discovered that the Chrome console is showing the following error:
Uncaught ReferenceError: google is not defined
My code now looks like this:

In the console again I'm now also seeing the following:
XMLHttpRequest cannot load (insert here the jsapi link above that I'm not allowed to post). Origin (insert here the URL for my localhost) is not allowed by Access-Control-Allow-Origin.
There are numerous references to similar errors to this all over the Net, each one slightly different, with solutions proposed referring to JSON, JQUERY, AJAX etc.etc., but nothing that I have found seems directly relevant to what I am trying to do (ie make available to my code the file or library in which 'google' is defined), and nothing that I have tried has worked.
Talk about trying to find your way through a coalmine with a candle... :)
Cheers

A: Can you pass the search term via the URL?

<gcse:searchbox queryParameterName="term"></gcse:searchbox>
<gcse:searchresults></gcse:searchresults>

If you call your "search" page via yourdomain.com/search?term=searchword the search results appear immediately.

A: <gcse:search gname='abcd'></gcse:search>

And when the page loaded:
google.search.cse.element.getElement('abcd').execute(query);

A: I've got it working with the gcse callback option (I also changed my layout in the CSE Control Panel to prevent the default overlay).


Q: Elasticsearch 6.2 (java/gradle) integration test I am spending days trying to find solution what to use for  this "simple" test:

*

*inside of test stand up ES node that will be used for test only

*connect with transport client to that ES instance and add new index.
(that is just a start of all integration tests, but I need to see how
to do one if anyone has an example)

Note: we have to continue to use transport client, we know it is going away.
We are upgrading from ES version 2 to version 6 and trying to keep integration tests as much unchanged as possible.
This is exactly the same issue as this person had in lower version, we had it that way but it is not supported anymore in 6, and how do I accomplish the same now: Start elasticsearch within gradle build for integration tests
I am finding comments about "existing gradle plugin" will do the job - what is that plugin and how to use it?
Or, example with ESIntegTestCase would be perfect too, anything that works. Thank you!


Q: Best way to create a unique number for each many to many relationship I have a table of Students and a table of Courses that are connected through an intermediate table to create a many-to-many relationship (ie. a student can enroll in multiple courses and a course can have multiple students). The problem is that the client wants a unique student ID per course. For example:
rowid Course Student      ID (calculated)
1     A      Ben          1
2     A      Alex         2
3     A      Luis         3
4     B      Alex         1
5     B      Gail         2
6     B      Steve        3

The ID's should be numbered from 1 and a student can have a different ID for different course (Alex for example has ID=2 for course A, but ID=1 for Course B). Once an ID is assigned it is fixed and cannot change. I implemented a solution by ordering on the rowid of the through table "SELECT Student from table WHERE Course=A ORDER BY rowid" and then returning a number based on the order of the results.
The problem with this solution, is that if a student leaves a course (is deleted from the table), the numbers of the other students will change. Can someone recommend a better way? If it matters, I'm using PostgreSQL and Django. Here's what I've thought of:

*

*Creating a column for the ID instead of calculating it. When a new relationship is created assigning an ID based on the max(id)+1 of the students in the course

*Adding a column "disabled" and setting it True when a student leaves the course. This would involve changing all my code to make sure that only active students are used

I think the first solution is better, but is there a more "database centric way" where the database can calculate this for me automatically?

A: If you want to have stable ID's, you certanly need to store them in the table.
You'll need to assign a new sequential ID for every student that joins a course and just delete it if the student leaves, without touching others.
If you have concurrent access to your tables, don't use MAX(id), as two queries can select same MAX(id) before inserting it into the table.
Instead, create a separate table to be used as a sequence, lock each course's row with SELECT FOR UPDATE, then insert the new student's ID and update the row with a new ID in a single transaction, like this:

Courses:

Name     NextID
-------  ---------
Math     101
Physics  201

Attendants:

Student Course   Id
------- ------   ----
Smith   Math     99
Jones   Math     100
Smith   Physics  200

BEGIN TRANSACTION;

SELECT NextID
INTO   @NewID
FROM   Courses
WHERE  Name = 'Math'
FOR UPDATE;

INSERT
INTO Attendants (Student, Course, Id)
VALUES ('Doe', 'Math', @NewID);

UPDATE
  Courses
SET NextID = @NewID + 1
WHERE Course = 'Math';

COMMIT;

A: Your first suggestions seems good: have a last_id field in the course table that you increase by 1 any time you enroll a student in that course.

A:
Creating a column for the ID instead
  of calculating it. When a new
  relationship is created assigning an
  ID based on the max(id)+1 of the
  students in the course

That how I'd do it. There is no point of calculating it. And the id's shouldn't change just because someone dropped out.

Adding a column "disabled" and setting
  it True when a student leaves the
  course.

Yes, that would be a good idea. Another one is creating another table of same structure, where you'll store dropped students. Then of course you'll have to select max(id) from union of these two tables.

A: I think there are two concepts that you need to help you out here.

*

*Sequences where the database gets the next value for an ID for you automatically

*Composite keys where more than one column can be combined to make the primary key of a table.

From a quick google it looks like Django can handle sequences but not composite keys, so you will need to emulate that somehow. However you could equally have two foreign keys and a sequence for the course/student relationship
As for how to handle deletions, it depends on what you need from your app, you may find that a status field would help you as you may want to differentiate between students who left and those that were kicked out, or get statistics on how many students leave different courses.


Q: Django view that rewrites URL to contain username as a query parameter? I want to do simple analytics over which user is doing what on my Django site.
I think the simplest way is to rewrite all URLs so that they contain "?username=foo".
This will only happen on GET urls that don't already have any URL query parameters.
How do I do this? Can I rewrite the URL to include a new query parameter from a view?

A: Why would you want to add a get parameter to each view while the request already contains the user? Also you should probably use the middleware layer to log user actions.

A: I don't think you would have to change anything except the templates for this.
If your existing url like http://server/myapp/view1 then accessing an url like this http://server/myapp/view1?username=foo will also work.
So your existing views will work as is.
However, you will have to change templates that renders the links as per new scheme. For example for above view if you are doing {% url 'view1' %} to get a link, then you will have to change it to {% url 'view1'%}?username={{user}}.


Q: LDA - Assigning keywords to topics I have unstructured data of about 150k documents. I am trying to group these documents using unsupervised learning algorithm. Currently I am using LDA (Latent Dirichlet allocation) in gensim Python. For LDAModel I have passed num_topics=20. Hence my whole 150k data is falling into 20 topics.
Now that I have these groups, I have 2 questions:

*

*How should I assign new documents to these topics?

The approach I am taking is:
Calculate the sum of the word scores of the document per topic and assign the document to the topic with the highest score. However this is not giving me good results.
Is there any better way to get this?

*How do I assign the main keywords that denote the topic?

A: How should I assign new documents to these topics?
Once you have a trained model you can query the model for your document with:
doc_bow = model.id2word.doc2bow(doc.split()) # convert to bag of words format first
doc_topics, word_topics, phi_values = model.get_document_topics(bow, per_word_topics=True)

re.
This code is going to provide you with per-doc and per-word information about the level of belonging to a particular topic. This means the per-word calculations are done for you automatically.
How do I assign the main keywords that denote the topic?
it is difficult to understand what you mean. The keywords denoting a topic along with their weights are the actual LDA model that you got from the training using a corpus.

I suppose you may be interested in reviewing the following notebook [*] for more information how to query model for specific information regarding a  document (per-word topic information, etc.).
[*] from which I took the excerpt of the code above


Q: Git push atomically, only if the target branch is at the expected SHA Is there a way to push to a branch only if it hasn't changed since I last fetched it?
More specifically, I'd like to delete branches that have already been merged, but only if no one else pushes new commits to them between when I check that the branch has been merged and when I push the deletion.
From the git push documentation, I see that it does support a --atomic option, but that option is for making updates to multiple branches atomically with respect to each other, rather than for ensuring that my update to a remote branch will be atomic with respect to other users' updates.
Ie, I want to delete merged branches on a remote git repository without any risk of deleting anyone else's work, even if they are working concurrently.

A: Yes, this is possible by using the --force-with-lease option.  For example:
$ git push --force-with-lease=refs/heads/foo origin :refs/heads/foo

This is designed for force pushes, but works for deletes as well.  The option has many variants and can take explicit values if you like.


Q: git - cannot push to repository - bug with hashmap When I try to push to repository, I got this message
BUG: remote.c:236: hashmap_put overwrote entry after hashmap_get returned NULL

Any idea what is wrong? Google shows nothing...
When I try push to another repository on the same server, it is working correctly. The problem is only with one repo.
Local Git version: 2.36.0.windows.1
Server Git version: 2.19.2

A: Git has self-detected an internal error.  Report this to the Git mailing list (git@vger.kernel.org).  The output from git config --list --show-origin may also be useful to the Git maintainers, along with the output of git ls-remote on the remote in question (origin, probably).  (The bug itself is in your Windows Git; the server version of Git should be irrelevant, but it won't hurt to mention that too.)

A: Based on reporting problem to git team, the problem was caused by branch with an empty name "". After removing this form .git/config, pushing works again.
However, the problem is passed to git team and will probably be solved in future version.


Q: How to get stderr using Popen + vim I am trying capture error messages from gvim using subprocess.Popen(), but not having much luck.
import sys
import subprocess
import time

ppp = subprocess.Popen(
    ["vim", "-g", "--nofork", "--some_option_that_does_not_exist", "blah"],
    stderr=subprocess.PIPE
)
time.sleep(1)
poll = ppp.poll()
err = ''
if poll != None and poll != 0:
    err  = ppp.communicate()
print '-------------------------------->>POLL\n',
print poll
print '-------------------------------->>PPP\n',
print ppp
print '-------------------------------->>err\n',
print err
print '--------------------------------<<\n\n',

print 'Trying to get:\n'
subprocess.Popen(
    ["vim", "-g", "--nofork", "--some_option_that_does_not_exist", "sasa"]
)

Result:
$ ./poperr.py
-------------------------------->>POLL
1
-------------------------------->>PPP
<subprocess.Popen object at 0xb73effec>
-------------------------------->>err
(None, '')
--------------------------------<<

Trying to get:

VIM - Vi IMproved 7.3 (2010 Aug 15, compiled Oct 26 2012 16:45:52)
Unknown option argument: "--some_option_that_does_not_exist"
More info with: "vim -h"

The point is to start vim in background and on success continue with script, on error log error message and abort script.
Guess there are some quirks using vim. Have tested various with no luck. Any ideas?
vim -h:
    -g                      Run using GUI (like "gvim")
    -f  or  --nofork        Foreground: Don't fork when starting GUI

Edit:
To emphasize: It is the (None, '') part that is the issue. As one can see stderr is an empty string: ''. If there is no error it will be None as well (like stdout).
The reason for the sleep is to give the sub-process a chance to succeed or fail. However, the real script keep polling for status on the process to detect if it has ended during its lifetime. As such the sleep is not that important, but reduces stress on the host as a lot of other tasks are skipped.
… and it makes for a more re-producible snippet here. I increased the sleep time in sample to one second to perhaps make it more clear.

Another example would be this. In this case errorfile.txt is always empty.
ppp = subprocess.Popen(
    ["vim", "-g", "--nofork", "--some_option_that_does_not_exist", "blah"],
    stderr=open('errorfile.txt', 'a')
)

A: ppp.communicate() will not be called unless the process terminates in less than 0.01 seconds, which evidently is not happening. Note that ppp.communicate() will wait for the process to finish, so I'm not sure why you do time.sleep() and ppp.poll(). The following consistently works:
import subprocess

stdout, stderr = subprocess.Popen(
    ["vim", "-g", "--nofork", "--nonexistent_option", "blah"],
    stderr=subprocess.PIPE
).communicate()

print '---stdout---\n%s\n---stderr---\n%s\n---expected---' % (stdout, stderr)

subprocess.Popen(
    ["vim", "-g", "--nofork", "--nonexistent_option", "blah"]
).wait()


Q: What's the gain I can have with blocks over regular methods? I am a Java programmer, and I am learning Ruby...
But I don't get where those blocks of codes can give me gain... like what's the purpose of passing a block as an argument ? why not have 2 specialized methods instead that can be reused ?
Why have some code in a block that cannot be reused ?
I would love some code examples...
Thanks for the help !

A: Consider some of the things you would use anonymous classes for in Java. e.g. often they are used for pluggable behaviour such as event listeners or to parametrize a method that has a general layout.
Imagine we want to write a method that takes a list and returns a new list containing the items from the given list for which a specified condition is true. In Java we would write an interface:
interface Condition {
    boolean f(Object o);
}

and then we could write:
public List select(List list, Condition c) {
    List result = new ArrayList();
    for (Object item : list) {
        if (c.f(item)) {
            result.add(item);
        }
    }
    return result;
}

and then if we wanted to select the even numbers from a list we could write:
List even = select(mylist, new Condition() {
    public boolean f(Object o) {
        return ((Integer) o) % 2 == 0;
    }
});

To write the equivalent in Ruby it could be:
def select(list)
  new_list = []
  # note: I'm avoid using 'each' so as to not illustrate blocks
  # using a method that needs a block
  for item in list
    # yield calls the block with the given parameters
    new_list << item if yield(item)
  end
  return new_list
end

and then we could select the even numbers with simply
even = select(list) { |i| i % 2 == 0 }

Of course, this functionality is already built into Ruby so in practice you would just do
even = list.select { |i| i % 2 == 0 }

As another example, consider code to open a file. You could do:
f = open(somefile)
# work with the file
f.close

but you then need to think about putting your close in an ensure block in case an exception occurs whilst working with the file. Instead, you can do
open(somefile) do |f|
  # work with the file here
  # ruby will close it for us when the block terminates
end

A: The idea behind blocks is that it is a highly localized code where it is useful to have the definition at the call site. You can use an existing function as a block argument. Just pass it as an additional argument, and prefix it with an &


Q: HighChart - Stacked Bar chart - To show dash line over the bar chart but it is not visible on Left side of the bar I have attached the screenshot to show the dash line in left side of the chart. It would be helpful if we can achieve the functionality and I tried to increase the width of the border, it is visible slightly. Do you have any proper approach to achieve this?

Code Snippet :
Highcharts.chart('container', {
chart: {
type: 'bar',
charWidth: 520,
chartHeight:300,
margin: [70,0,0,0]
},
xAxis: {
categories: ['Jan'],
visible: false
},
yAxis: {
min: 0,
visible: false
},
plotOptions: {
series:{
stacking:'normal'
},
dataLabels: {
enabled : false,
}
},

series: [{
name: 'John',
data: [{
  y: 15
}]

}, {
name: 'Jane',
data: [{
y: 22
}]
}, {
name: 'Joe',
data: [{
y: 33,
}]
}, {
stacking: false,
data: [55],
grouping: false,
dashStyle:'ShortDash',
color: 'transparent',
borderWidth: 2,
borderColor: 'red',

}]
});
Thanks for the response
[![enter image description here][2]][2]

A: The left side of the bar is connected to the xAxis, which makes the left border less visible. There are some possible solutions to this issue.

*

*You can set the minimum value of the xAxis to -0.1 and set startOnTick property to false. Then the left border is visible (it's not directly connected to the axis).
Demo:
https://jsfiddle.net/BlackLabel/pqy84hvs/
API references:
https://api.highcharts.com/highcharts/xAxis.startOnTick
https://api.highcharts.com/highcharts/xAxis.min
yAxis: {
 min: -0.1,
 visible: false,
 startOnTick: false
}

*You can set the borderWidth property to 3. Then the border is visible.
Demo:
https://jsfiddle.net/BlackLabel/01m6p47f/
API references:
https://api.highcharts.com/highcharts/series.bar.borderWidth
{
 name: 'Joe',
 borderWidth: 3,
 borderColor: 'red',
 data: [{
  y: 33,
 }]
}

*You can also use SVG Renderer and render the border yourself.
Docs:
https://api.highcharts.com/class-reference/Highcharts.SVGRenderer
Example demo of using SVG Renderer:
https://jsfiddle.net/BlackLabel/2koczuq0/


Q: how to connect socket_io_client via https in flutter? I work with socket_io_client. So how do I connect the https socket in my application.
below is code example
Socket socket = io('https://abcd.co.in:1000005',
OptionBuilder().setTransports(['websocket']).build());

    socket.connect();
    socket.onConnect((_) {
      print('connect');
      socket.emit("Client", [MyConstants.CtName]);
      socket.emit("room", [MyConstants.CtName]);
    });

I am use socket_io_common: ^2.0.0 because of my flutter channel is flutter channel stable 2.2.3.
also I am use socket_io_client: any. it is work fine with my other http socket url


Q: Can't hear sound from bluetooth speaker I'm using Raspberry Pi with Ubuntu 22.10 and Java 19.
I'm trying to play a sound with the following code:
private static void testMixers() throws IOException, UnsupportedAudioFileException
{
    try (AudioInputStream audioInputStream = AudioSystem.getAudioInputStream(new BufferedInputStream(Objects.requireNonNull(Listener.class.getResourceAsStream("/alarmSound.wav")))))
    {
        final Scanner scanner = new Scanner(System.in);
        for (Mixer.Info info : AudioSystem.getMixerInfo())
        {
            System.out.println("Testing sound for mixer \"" + info + "\"...");
            try (Clip clip = AudioSystem.getClip(info))
            {
                clip.open(audioInputStream);
                clip.setFramePosition(0);
                clip.start();
                System.out.println("Did you hear any sound? (true|false)");
                if (Boolean.parseBoolean(scanner.nextLine()))
                    return;
            }
            catch (Exception e)
            {
                System.out.println(e);
            }
        }
    }
    System.out.println("Mixer not found!");
}

alarmSound.wav is under src/main/resources (this is a Maven project).
AudioSystem.getMixerInfo() gives me the following Mixer.Info[]:

*

*Port Headphones [hw:0], version 5.19.0-1006-raspi

*Port vc4hdmi0 [hw:1], version 5.19.0-1006-raspi

*Port vc4hdmi1 [hw:2], version 5.19.0-1006-raspi

*Headphones [default], version 5.19.0-1006-raspi

*Headphones [plughw:0,0], version 5.19.0-1006-raspi

*vc4hdmi0 [plughw:1,0], version 5.19.0-1006-raspi

*vc4hdmi1 [plughw:2,0], version 5.19.0-1006-raspi
Only the Headphones Mixers don't give the error:

java.lang.IllegalArgumentException: Line unsupported: interface Clip supporting format PCM_SIGNED unknown sample rate, 16 bit, stereo, 4 bytes/frame, big-endian

I didn't tested the headphone jack.
This is completely different from Ubuntu 22.04 which gave more Mixer.Infos.
Is there any workaround? it seems that every Ubuntu version requires different workaround for being able to play a sound that can be heard not through the headphones (but from bluetooth speakers or via HDMI for example).


Q: Can I use html area tag to create different shape text containers? Is it possible to create text container which is not square/rectangle?
Can I use area tag for this?
Any example snippet will be appreciated.

A: No. All elements are rectangles by defintion. Even the <area> tag wouldn't get past that.


Q: Getting the Value which is already selected in drop down menu by Selenium Webdriver i have a Drop Down menu which has pre-selected a value please help me how to get the selected value text and print it in console
drop down menu html code is
<select id="ctl00_ContentPlaceHolder1_ddlCalculation" class="normalText"
    style="width:100%;"
    onchange="javascript:LoadMethods(this.value);
              CallonChange(this.value,'spn_ddlCalculation');
              return false;"
    disabled="disabled" name="ctl00$ContentPlaceHolder1$ddlCalculation">

    <option value="0" selected="selected">--- Select ---</option>
    <option value="f">Formula Based</option>
    <option value="m">Formula Based with Matrix Table</option>
    <option value="q">Quantity Based</option>
    <option value="t">Time Based</option>
</select>

A: Please try the following and let me know if it works :
Select dropdown = new Select(driver.findElement("Use the correct selector");
WebElement option = dropdown.getFirstSelectedOption();
String content = option.getText();
System.out.println("selected Value " + content);


Q: how to write value to file with node.js so i have a multiple requests from client, each request contain data,
{
 key: 'string',
 public_url: 'string'| null ,
 value: 'string',
 created_at:'string',
 updated_at: 'string',
 content_type: 'string',
 size: 'int',
 checksum: 'string',
 theme_id: 'int',
 warnings: []
}

so lets say i have 243 requests, for each request i need to write the data to file,
i have tried many ways like fs.writeFile , fs.writeFileSync,fs.createWriteStream,promises,etc,
const sourceStoreShopName = session.shop.split('.')[0]
    const fetchData = await restClient.get({
        path: 'assets',
        theme_id: id,
        query: {
            ['asset[key]']: assetPath,
        },
    })
    const asset = fetchData.body.asset
    const filename = asset.key.split('/')
    const dir = filename.length > 2 ? `${process.cwd()}/tmp/${sourceStoreShopName}/${filename[0]}/${filename[1]}` : `${process.cwd()}/tmp/${sourceStoreShopName}/${filename[0]}`
    if (!fs.existsSync(dir)) {
        fs.mkdirSync(dir, { recursive: true })
    }
    const ws = fs.createWriteStream(path.join(dir, filename.slice(-1)[0]))
    const API_LIMIT = fetchData.headers.get('x-shopify-shop-api-call-limit').split('/')
    return asset
}

so i want to copy content from value to file
for one file it passed , more then 2 got the error.
the error i got
1:23:07 PM [vite] http proxy error:
Error: socket hang up
  at connResetException (node:internal/errors:704:14)
  at Socket.socketOnEnd (node:_http_client:505:23)
  at Socket.emit (node:events:525:35)
  at endReadableNT (node:internal/streams/readable:1359:12)
  at process.processTicksAndRejections (node:internal/process/task_queues:82:21)

any ideas how to solve that problem?


Q: Best method to get double value from datetime in jquery Which is the best way to convert datetime to double in jquery? I have used Date.parse. But, it is not correct in few cases. Also,i am unable to pass datetime format for that method.
-
Viji

A: In JavaScript, you can simple do variablename.toFixed(2); for that.
Example:
var num1 = 12312.12312
console.log(num1.toFixed(2)); // Will give 12312.12


Q: javascript program to check if a string is palindromes not returning false I wrote this bit of code a a part of an exercise to check weather or not a string is palindromes. They program is working correctly in terms of checking the string but it does not return false when the string is not palindromes. What am I doing wrong? thanks
//convert the string to array
var stringArr = [ ];
var bool;
function palindrome(str) {
  // make lowercase
  var lowerCase = str.toLowerCase();
  //remove numbers, special characters, and white spaces
  var noNumbers = lowerCase.replace(/[0-9]/g, '');
  var noSpecials = noNumbers.replace(/\W+/g, " ");
  var finalString = noSpecials.replace(/\s/g, '');
  stringArr = finalString.split("");

    if (stringArr.sort(frontToBack)==stringArr.sort(backToFront)) {
       bool = true;
    }
    else {
       bool= false;

    }
  return bool;
}
function frontToBack (a,b) {return a-b;}
function backToFront (a,b) {return b-a;}

palindrome("eye");

A: if (stringArr.sort(frontToBack)==stringArr.sort(backToFront)) { is your problem.
In JavaScript, the sort method updates the value of the variable you are sorting. So in your comparison, once both sort's have run, both end up with the same value (since the second sort, effectively overrides the first).
For example.
var a = [1,7,3];
a.sort();
console.log(a); // will print 1,3,7

Edit: had a quick test, I think eavidan's suggestion is probably the best one.
Edit2: Just put together a quick version of a hopefully working palindrome function :)
 function palindrome(str) { return str.split("").reverse().join("") == str;}

A: It is because string subtraction yields NaN, which means both sorted arrays are the same as the original.
Even if you did convert to ASCII coding,  you sort the entire string, then for instance the string abba would be sorted front to back as aabb and back to front as bbaa. (edit: and also what Carl wrote about sort changing the original array. Still - sort is not the way to go here)
What you should do is just reverse the string (using reverse on the array) and compare.

A: You might do as follows;

var isPalindrome = s => { var t = s.toLowerCase()
                                   .replace(/\s+/g,"");
                          return [].slice.call(t)
                                   .reverse()
                                   .every((b,i) => b === t[i]);
                        };

console.log(isPalindrome("Was it a car or a cat I saw"));
console.log(isPalindrome("This is not a palindrome"));

A:        function pal()
        {
            var x=document.getElementById("a").value;

            //input String

            var y="";

           //blank String

            for (i=x.length-1;i>=0;i--)
          //string run from backward

                {

                    y=y+x[i];
       //store string last to first one by one in blank string

                }

            if(x==y)

          //compare blank and original string equal or not

                {

                    console.log("Palindrome");

                }

            else

                {

                    console.log("Not Palindrome ");

                }

        }


Q: How can I add meta data to the head section of the page from a wordpress plugin? I am writing a wordpress plugin and need to add some meta tags to the head section of the page from within my plugin. Does anyone know how I would do this?
Thanks

A: Yes you can add an action hook to wp_head like this:
add_action('wp_head', myCallbackToAddMeta);
function myCallbacktoAddMeta(){
  echo "\t<meta name='keywords' content='$contents' />\n";
}