text:
Q: Differentiability linear function The question may seems idiot, but I prefer to ask it rather than let some doubt resist. So, we consider $f \in \mathcal{L}(E \times F, G)$ and we want to show that $f$ is differentiable in each point $(a \; b) \in E \times F$ (and calculate $Df_{(a \, b)}$).
The first question is :
a) Write $f(a+h,b+k)$ according to $f(a,b)$, $f(a,k)$, $f(h,b)$ and $f(h,k)$. But this is the problem. In fact, I've said that :
$f(a+h,b+k) = f((a,b)+(h,k)) = f((a,b)) + f((h,k))$ as $f$ is linear.
So, we have as well :
$f(a+h,b+k) = f((a,k)+(h,b)) = f((a,k)) + f((h,b))$.
And so, if we want to answer the question, this is what I've found :
$f(a+h,b+k) = \frac{1}{2}(f((a,b)) + f((h,k)) + f((a,k)) + f((h,b)))$
But I don't figure out why we should do that to answer the show that $f$ is differentiable. Actually, let $(a \; b) \in E \times F$. Then, let $(h \; k) \in E \times F$, we have :
$f((a,b)+(h,k)) - f((a,b)) = f(a+h, b+k) - f(a,b) = f(a,b)+f(h,k)-f(a,b) = f(h,k)$. So :
$f((a,b)+(h,k)) - f((a,b)) - f(h,k) = f((a,b)+(h,k)-(a,b)-(h,k)) = 0_G$, and then : $\lim\limits_{\substack{(h \; k) \rightarrow (0 \; 0) \\ (h \; k) \neq (0 \; 0)}} \frac{||f((a,b)+(h,k)) - f((a,b)) - f(h,k)||}{||(h,k)||} = 0$, and we have finally :
$Df_{(a \; b)} : E \times F \rightarrow G$ defined by $Df_{(a \; b)}(h,k) = f(h,k)$.
I've the feeling that it's not this at all, because if it would do, what's the point of the first question ?
But I don't figure out why could been wrong, and it's my first step on differentiable functions, so I'm not sure at all of what I'm writting down...


text:
Q: Azure App Service Certificates Error on importing into key vault I have purchased an Azure app service certificate for an "A" record. After that, I am trying to import the certificate into the key vault, but I am getting error code 500 as shown on the attached screen.
Step 1 - in Azure
Import certificate into Key Vault for secure administration.

A: The issue is solved after a couple of hours.

redpajama_set_name: RedPajamaStackExchange


text:
Q: Unable to start apache2 after reinstall I had an issue with my original install of apache2.4 on ubuntu14.
I have removed and purged the files in /etc/apache2 and reinstalled apache.
Now I am unable to start the server.
Can you please let me know if you have seen this issue before?
apache2: Syntax error on line 140 of /etc/apache2/apache2.conf:
Syntax error on line 2 of /etc/apache2/mods-enabled/access_compat.load:
Cannot load /usr/lib/apache2/modules/mod_access_compat.so into server:
/usr/lib/apache2/modules/mod_access_compat.so: cannot open shared object file: No such file or directory
Action 'configtest' failed.

A: You have a configuration file that's trying to load a library (mod_access_compat.so) that it can't find.
The file appears to be part of the apache2-bin package so first check that that's installed (and that all its files are present) with:
sudo apt-get --reinstall install apache2-bin


text:
Q: C++ to Java division operator C++ code: if (!(number % i)) {
Java code: if (!(number % i == 0)) {
Is that right?
Correct version:
Java code: if ((number % i == 0)) {

A: Correct, yes. They don't do the same thing though.
In Java you need the comparison because there's no automatic conversion to a boolean value.
The equivalent C++ code would be either
if (!(number % i == 0))

or simply
if (number % i)

A: Yes, that would be correct.
Java, treats boolean as a separate data type which has 2 distinct values: true and false
C++ regards integer 0 to be equivalent to false and other values to be true.
However, you have inverted the logic in your statements.
if (!(number % i)) { //returns true if number is divisible by i
if (!(number % i == 0)) { //returns true if number is not divisible by i


text:
Q: How to most efficiently generate string from array of objects in javascript? I have the following:
var students = [{name:"Jordan", age:"6"},{name:"Jake", age:"7"},{name:"Mark", age:"10"}]

I want to generate a string like this:
"Jordan,6|Jake,7|Mark,10"
What is the most efficient way to do this?
I am currently using:
var studentstr = "";
for(var i = 0; i < students.length; i++) {
  studentstr = students['name'] + "," + students['age'] + "|"
}
studentstr = studentstr.substring(0, studentstr.length - 1);

Also, performance-wise, if I had an array of 2,000 items, is it "costly" to perform this transformation? The resulting string contains both keys in the object and not a single join on one object in the property.

A: You can map each student object to a string and then join them all with |:
var studentstr = students.map(function (student) {
    return student.name + ',' + student.age;
}).join('|');

Also, performance-wise, if I had an array of 2,000 items, is it "costly" to perform this transformation?

No.

A: Yes, using string concatenation in a loop is costly. The string grows for each iteration, and each time you have to copy the entire previous string to create the new version. The execution time of the loop grows exponentially to the number of items.
You can put the string for each object in an array, then join them together:

var students = [{name:"Jordan", age:"6"},{name:"Jake", age:"7"},{name:"Mark", age:"10"}];

var items = [];
for (var i = 0; i < students.length; i++) {
  items.push(students[i].name + ',' +students[i].age);
}
var str = items.join('|');

// display result in snippet
document.write(str);

A: map works well for this:
var students = [{name:"Jordan", age:"6"},{name:"Jake", age:"7"},{name:"Mark", age:"10"}];
var result = students.map(function(student) {
    return student.name + ',' + student.age;
});
alert(result.join('|'));

A: Try this and see your console:
var string = '';
for (var s in students) {
    string += students[s].name + ', ' + students[s].age + ' | ';
}

console.log(string);

Fiddle: http://jsfiddle.net/80ss0u14/
I do not think it is costly to go on with such approach. It may be the most efficient way to iterate through the data.


text:
Q: How to add new REST GET action to this Spring Boot code? This is a basic question coming from someone who just tried out Spring Boot 2 hours ago and a newbie to Java.
I followed the tutorial here;
http://patrickgrimard.com/2014/08/14/how-to-build-a-spring-boot-application-using-intellij-idea/
When I visit http://localhost:8080/api, I get the following json output;
{
type: "green",
length: 10,
height: 7
}

I would like to modify the code such that when I visit http://localhost:8080/api/test, I will get the following json output;
{
type: "red",
length: 8,
height: 7
}

The following is the controller code I modified;
@RequestMapping("/api/**")
@RestController
public class WidgetController {

    @RequestMapping(method = RequestMethod.GET, produces = {MediaType.APPLICATION_JSON_VALUE})
    public Widget index() {
        return new Widget("green", 10, 7);
    }

    public Widget test() {
        return new Widget("red", 8, 7);
    }
}

What is wrong with my code? Apologies if this question looks too simple. It would  also be helpful if links are provided where I can learn enough to answer my own question. There seems to be so much to read for a newbie.
I am using IntelliJ idea Ultimate trial edition.

A: You need to add a @RequestMapping annotation for your test method with the desired path.  The one at the class level will map /api/* to this controller, but you have to give it more information about when to call test() versus index().  The way it is right now, any "GET" to an /api/* URL will get mapped to index().


text:
Q: bind() call in tcp client I am trying to change the source ip address for a tcp packet. Code snippet as given bellow
 bzero(&clientaddr,sizeof(clientaddr));
 clientaddr.sin_family = AF_INET;
 clientaddr.sin_addr.s_addr=inet_addr("172.16.2.10");
 clientaddr.sin_port=htons(8080);
 if (bind(sockfd, (struct sockaddr *) &clientaddr,
   sizeof(clientaddr)) < 0)
{
    perror("bind");
}

Binding a particular port is working fine,
  but when i tried to bind with a diffrent ip adress, the bind is failing with error
bind: Cannot assign requested address

I also tried by setting the socket option as follows,]
setsockopt (sockfd, SOL_IP, IP_TRANSPARENT, &n1, sizeof(int));*

then also its failing with same error.
How could i change my source ip address for packet, originated from my PC.
Please help me, its for a proxy application.
OS :Linux 2.6.37-tproxy #1 SMP Wed Apr 3 23:34:00 IST 2013 x86_64 x86_64 x86_64 GNU/Linux
Thanks in advance.

A: You will need to use a raw socket and create the ip and tcp headers (where you will be able to set the desired IP Address (spoofing).
raw_socket = socket(AF_INET, SOCK_RAW, IPPROTO_RAW);

You can check the linux manual page man 7 raw

A: You can only bind() to an IP address that is local to your computer, i.e. implemented by one of your network interfaces.


text:
Q: SpringBoot absolute path clarification I'm new to SpringBoot web dev.
I need to save an image to a directory in the current project. I have given path as "String uploaddir = "./src/main/imageuploads/"+ savedadvert.getId();" but the image not save to the "./src/main/imageuploads/" directory in eclipse project.
@RequestMapping(value="/upload", method = RequestMethod.POST)
public String FileUpload(@RequestParam("file1Url") MultipartFile multipartfile, Model model) throws IOException {

    model.addAttribute("advertsim",new advertsummary());

    advertsummary advert = new advertsummary();

    String file1Urlname= StringUtils.cleanPath(multipartfile.getOriginalFilename());
    advert.setFile1Url(file1Urlname);

    advertsummary savedadvert = AdvertService.addadvert(advert);

    String uploaddir = "./src/main/imageuploads/"+ savedadvert.getId();

    FileUploadUtil.saveFile(multipartfile, file1Urlname, uploaddir);

    return "uploadview";
}

This is the saveFile method for ref.
public static void saveFile(MultipartFile multipartFile, String fileName, String uploadDir) throws IOException {
     Path uploadPath = Paths.get(uploadDir);

        if (!Files.exists(uploadPath)) {
            Files.createDirectories(uploadPath);
        }

        try (InputStream inputStream = multipartFile.getInputStream()) {
            Path filePath = uploadPath.resolve(fileName);
            System.out.println(filePath.toFile().getAbsolutePath());
            Files.copy(inputStream, filePath, StandardCopyOption.REPLACE_EXISTING);
        } catch (IOException ioe) {
            throw new IOException("Could not save image file: " + fileName, ioe);
        }

}

I need to upload the image to this directory,

when I get the absolute path, it shows like this "/Users/chathura/eclipse/jee-2021-03/Eclipse.app/Contents/MacOS/./src/main/imageuploads/24/new file.jpg".
There is no way to go to this directory but I can access that directory using the terminal.

Please tell me what is the mistake here?
Note : I'm using macos
Thanks in advance

A: *

*Could you try 'src/main/resources/imagesuploads' (without .)

*Just a reminder: This directory will disappear when you package your application (production mode)

*This directory should be configurable from an external file (application. properties for example)

A: Thank you Ali, your response gave a lead to the solution. My project sits on MacOS partition therefore, I couldn't write a file without permission. I simply changed the location to another partition and it worked.
    @RequestMapping(value="/upload", method = RequestMethod.POST)
public String FileUpload(@RequestParam("file1Url") MultipartFile multipartfile, Model model) throws IOException {

    model.addAttribute("advertsim",new advertsummary());

    advertsummary advert = new advertsummary();

    String file1Urlname= StringUtils.cleanPath(multipartfile.getOriginalFilename());
    advert.setFile1Url(file1Urlname);

    advertsummary savedadvert = AdvertService.addadvert(advert);

    String uploaddir = "/Volumes/My Data/Fileupload"+ savedadvert.getId();

    FileUploadUtil.saveFile(multipartfile, file1Urlname, uploaddir);

    return "uploadview";
}

Thank you


text:
Q: net use command works in cmd, but not powershell? I'm running a simple
net use N: \\myserver\myshare
It works fine in cmd, but not powershell where I want to run the script.
When I run it from CMD the drive shows up in the explorer. When I run it in PS, it does not.
Doesn't matter if I run as admin or not.
Why is this?

A: This happens when you try to map a drive in an elevated PowerShell session. You'll need to map any persistent drives from an unelevated session. Similarly, any mapped shares available in File Explorer aren't available in an elevated PowerShell session, either.


text:
Q: how can display caption from another table in mysql? I have two table
table A
add1 |add2 | add3

1    |2    |3

another table B contains what the add1,add2,add3 means
table B
add1           | add2       | add3       |
Caption1       | Caption2   | Caption3

I want to display like
Caption  | Value
Caption1 | 1
Caption2 | 2
Caption3 | 3

or
Caption1 | Caption2 | Caption3

1        | 2        | 3

how can do this in mysql ?
If it is not possible pls suggest a better structure for this need. Every month the caption may be changed.

A: I suggest the following table structure:
CREATE TABLE B (
  add varchar(10) PRIMARY KEY,
  caption varchar(50)
);
CREATE TABLE A (
  add varchar(10) PRIMARY KEY,
  value int
);

Then use this query:
SELECT caption, value
FROM A INNER JOIN B
ON A.add = B.add

But if you want to keep your table structure, you can do:
SELECT B.add1 Caption, A.add1 Value
FROM A, B
UNION ALL
SELECT B.add2, A.add2
FROM A, B
UNION ALL
SELECT B.add3, A.add3
FROM A, B


text:
Q: Laravel Eager Load with conditional statement good day everyone
I'm new to Laravel and currently building my first simple news app with it
I have a simple query that using laravel's eager loading function
But in this eager loading function, I want to fetch certain comments based on some conditions
Example:
use App\News;
...

public function home() {
    $news = News::with([
                    'thumbnail',
                    'source', // link to real news source
                    'comments' => function ($query) {
                        // fetch a comment where likes > 0, otherwise, get latest comment
                        // *get only one*
                    }
                ])->paginate(5);

    return response()->json([
        'news' => $news
    ]);
}

How to do this?

UPDATE

I found a way to order comments by likes count, but I do not know how to order them by 'created_at' (fetch latest comment) if there are no likes in each comment
I need to include 'likes_count' using withCount('likes')
And then order them in by descending
public function home() {
    $news = News::with([
        'thumbnail',
        'source',
        'comments' => function ($query) {
            $query->withCount('likes');
            $query->orderBy('likes_count', 'DESC')->first();

            // return the first comment that has likes or most liked comment
        }
    ])->paginate(5);

    ...
}

Now how to put fallback query to order comments by 'created_at' (newest one) if there are no like in comments?
Thanks in advance

A: Your current approach looks fine for ordering your results by likes count in case of no likes you can still get latest record by adding another order by clause with created_at column
$news = News::with([
    'thumbnail',
    'source',
    'comments' => function ($query) {
        $query->withCount('likes');
        $query->orderBy('likes_count', 'DESC')
              ->orderBy('created_at', 'DESC');
    }
])->paginate(5);

Copied from initial comment

So if all comments have 0 likes then the newest one will appear first in list, same if comments have likes then they are also sorted first with likes count and then with created at.

Once you have ordered collection then while you are looping your news records then pick the first item from your related records


text:
Q: Euclidean Algorithm for Polynomials in $\mathbb F_7$
I have two polynomials $x^4+5x+1$ and $x^2-1$ and I'm trying to find their GCD over $\mathbb F_7$.

My attempt is:
$x^4+5x+1$ = $(x^2+1)(x^2-1)+5x+2$
$x^2-1 =\ ?$
I get lost on the second step...

A: $x^4+5x+1=(x^2+1)(x^2-1)+5x-5=(x-1)(x^3+x^2+x+6)$
$x^2-1=(x-1)(x+1)$
$x^3+x^2+x+6$ has no $-1$ as a root
$\gcd(x^4+5x+1,x^2-1)=x-1$
Using the Euclidean algorithm: $x^2-1=(5x+2)(3x+1)+3(x-1)$


text:
Q: How to change Windows boot manager priority I recently had to reinstall Windows 10 on my PC due to some issues, the problem is whenever I start my computer I always have to press F11 to select what Windows boots from. I have 4 options to select from to boot Windows:

*

*Windows Boot Manager (P1: [Drive Name])

*Windows Boot Manager (P5: [Drive Name])

*[Drive Name]

*[Drive Name]

All of the drive names are identical (I do have 2 HDDs but only 1 has any data on it, multiple formats of the spare drive have made sure of that). Windows can only boot from boot option 2 but by default, it tries to boot using boot option 1. I have managed to swap options 3 and 4 with 1 and 2 but I would need to swap 2 and 1 so the computer boots correctly without having to select the correct boot option.
I have been through the BIOS and boot order settings and I haven't been able to find a way to swap boot option 1 and option 2 around because they are group together as 'Windows Boot Manager'.
How would I go about swapping them?

A: Start > Run > msconfig
Go to the Boot tab. Choose a different drive, and click Set as default.


text:
Q: Putting a timestamp to the records after pulling at regular intervals I have one database table with the following columns .
ZoneName ZoneCount

I want to copy this data to another db table with a time stamp .
I can copy using the following query
insert into ... select * FROM ...

My question is how do i add timestamp to it , if i am running this query at every 15 min.

A: You can use NOW() or CURRENT_TIMESTAMP
insert into destination_table (col1, col2, col3)
select ZoneName, ZoneCount, NOW()
FROM source_table


text:
Q: using template literal when returning json? Node.js I'm using express and I want to return some JSON, would a template literal work? What I currently have:
resp.status(201).json({
        message: "Customer added to database",
        url: "http://localhost:5000/Customer/" + doc._id
        }
});

I want to change to this:
url: `http://localhost:5000/Customer/${doc._id}`

Would that be permissible?
Thanks for reading.

A: Yes it is possible!
I recommend this. it's good readability.
const message = "Customer added to database";
const url = `http://localhost:5000/Customer/${doc._id}`

res.status(201).json({
    message,
    url
});


text:
Q: Elasticsearch cluster NodeStatsCollector time out when collecting data A few minutes after the elasticsearch cluster run, all nodes gives the error:
[ERROR][o.e.x.m.c.n.NodeStatsCollector] [node-1] collector [node_stats] timed out when collecting data
[ERROR][o.e.x.m.c.n.NodeStatsCollector] [node-1] collector [node_stats] timed out when collecting data

all nodes gives this error and indexer that is a java program index data whit bulk api very well. and there is no error in logs of my indexer program. but elastic search node gives this error.
i used 4 elasticsearch nodes and kibana in one machine whit windows server 2019 data center
the version of elasticsearch and kibana is 7.10.0 and Cluster Status is :
    {
  "_nodes" : {
    "total" : 4,
    "successful" : 4,
    "failed" : 0
  },
  "cluster_name" : "es-cluster",
  "cluster_uuid" : "RRhGhaElfh5lUxGfsKg",
  "timestamp" : 1245375859907,
  "status" : "green",
  "indices" : {
    "count" : 1,
    "shards" : {
      "total" : 9,
      "primaries" : 3,
      "replication" : 2.0,
      "index" : {
        "shards" : {
          "min" : 9,
          "max" : 9,
          "avg" : 9.0
        },
        "primaries" : {
          "min" : 3,
          "max" : 3,
          "avg" : 3.0
        },
        "replication" : {
          "min" : 2.0,
          "max" : 2.0,
          "avg" : 2.0
        }
      }
    },
    "docs" : {
      "count" : 0,
      "deleted" : 0
    },
    "store" : {
      "size" : "36.1mb",
      "size_in_bytes" : 37936718,
      "reserved" : "0b",
      "reserved_in_bytes" : 0
    },
    "fielddata" : {
      "memory_size" : "0b",
      "memory_size_in_bytes" : 0,
      "evictions" : 0
    },
    "query_cache" : {
      "memory_size" : "0b",
      "memory_size_in_bytes" : 0,
      "total_count" : 0,
      "hit_count" : 0,
      "miss_count" : 0,
      "cache_size" : 0,
      "cache_count" : 0,
      "evictions" : 0
    },
    "completion" : {
      "size" : "0b",
      "size_in_bytes" : 0
    },
    "segments" : {
      "count" : 0,
      "memory" : "0b",
      "memory_in_bytes" : 0,
      "terms_memory" : "0b",
      "terms_memory_in_bytes" : 0,
      "stored_fields_memory" : "0b",
      "stored_fields_memory_in_bytes" : 0,
      "term_vectors_memory" : "0b",
      "term_vectors_memory_in_bytes" : 0,
      "norms_memory" : "0b",
      "norms_memory_in_bytes" : 0,
      "points_memory" : "0b",
      "points_memory_in_bytes" : 0,
      "doc_values_memory" : "0b",
      "doc_values_memory_in_bytes" : 0,
      "index_writer_memory" : "233.1mb",
      "index_writer_memory_in_bytes" : 244509188,
      "version_map_memory" : "0b",
      "version_map_memory_in_bytes" : 0,
      "fixed_bit_set" : "0b",
      "fixed_bit_set_memory_in_bytes" : 0,
      "max_unsafe_auto_id_timestamp" : -1,
      "file_sizes" : { }
    },
    "mappings" : {
      "field_types" : [
        {
          "name" : "boolean",
          "count" : 3,
          "index_count" : 1
        },
        {
          "name" : "date",
          "count" : 4,
          "index_count" : 1
        },
        {
          "name" : "geo_point",
          "count" : 1,
          "index_count" : 1
        },
        {
          "name" : "integer",
          "count" : 8,
          "index_count" : 1
        },
        {
          "name" : "ip",
          "count" : 2,
          "index_count" : 1
        },
        {
          "name" : "keyword",
          "count" : 12,
          "index_count" : 1
        },
        {
          "name" : "object",
          "count" : 1,
          "index_count" : 1
        },
        {
          "name" : "text",
          "count" : 17,
          "index_count" : 1
        }
      ]
    },
    "analysis" : {
      "char_filter_types" : [ ],
      "tokenizer_types" : [ ],
      "filter_types" : [
        {
          "name" : "stop",
          "count" : 3,
          "index_count" : 1
        }
      ],
      "analyzer_types" : [
        {
          "name" : "custom",
          "count" : 1,
          "index_count" : 1
        }
      ],
      "built_in_char_filters" : [ ],
      "built_in_tokenizers" : [
        {
          "name" : "standard",
          "count" : 1,
          "index_count" : 1
        }
      ],
      "built_in_filters" : [
        {
          "name" : "arabic_normalization",
          "count" : 1,
          "index_count" : 1
        },
        {
          "name" : "decimal_digit",
          "count" : 1,
          "index_count" : 1
        },
        {
          "name" : "lowercase",
          "count" : 1,
          "index_count" : 1
        },
        {
          "name" : "persian_normalization",
          "count" : 1,
          "index_count" : 1
        }
      ],
      "built_in_analyzers" : [ ]
    }
  },
  "nodes" : {
    "count" : {
      "total" : 4,
      "coordinating_only" : 0,
      "data" : 3,
      "data_cold" : 3,
      "data_content" : 3,
      "data_hot" : 3,
      "data_warm" : 3,
      "ingest" : 3,
      "master" : 3,
      "ml" : 0,
      "remote_cluster_client" : 4,
      "transform" : 3,
      "voting_only" : 1
    },
    "versions" : [
      "7.10.0"
    ],
    "os" : {
      "available_processors" : 48,
      "allocated_processors" : 24,
      "names" : [
        {
          "name" : "Windows Server 2019",
          "count" : 4
        }
      ],
      "pretty_names" : [
        {
          "pretty_name" : "Windows Server 2019",
          "count" : 4
        }
      ],
      "mem" : {
        "total" : "383.4gb",
        "total_in_bytes" : 411772076032,
        "free" : "127.2gb",
        "free_in_bytes" : 136611741696,
        "used" : "256.2gb",
        "used_in_bytes" : 275160334336,
        "free_percent" : 33,
        "used_percent" : 67
      }
    },
    "process" : {
      "cpu" : {
        "percent" : 0
      },
      "open_file_descriptors" : {
        "min" : -1,
        "max" : -1,
        "avg" : 0
      }
    },
    "jvm" : {
      "max_uptime" : "38.2m",
      "max_uptime_in_millis" : 2297261,
      "versions" : [
        {
          "version" : "14.0.2",
          "vm_name" : "Java HotSpot(TM) 64-Bit Server VM",
          "vm_version" : "14.0.2+12-46",
          "vm_vendor" : "Oracle Corporation",
          "bundled_jdk" : true,
          "using_bundled_jdk" : false,
          "count" : 4
        }
      ],
      "mem" : {
        "heap_used" : "2.2gb",
        "heap_used_in_bytes" : 2433056080,
        "heap_max" : "50gb",
        "heap_max_in_bytes" : 53687091200
      },
      "threads" : 153
    },
    "fs" : {
      "total" : "6.5tb",
      "total_in_bytes" : 7196607758336,
      "free" : "6.2tb",
      "free_in_bytes" : 6888031485952,
      "available" : "6.2tb",
      "available_in_bytes" : 6888031469568
    },
    "plugins" : [ ],
    "network_types" : {
      "transport_types" : {
        "security4" : 4
      },
      "http_types" : {
        "security4" : 4
      }
    },
    "discovery_types" : {
      "zen" : 4
    },
    "packaging_types" : [
      {
        "flavor" : "default",
        "type" : "zip",
        "count" : 4
      }
    ],
    "ingest" : {
      "number_of_pipelines" : 2,
      "processor_stats" : {
        "gsub" : {
          "count" : 0,
          "failed" : 0,
          "current" : 0,
          "time" : "0s",
          "time_in_millis" : 0
        },
        "script" : {
          "count" : 0,
          "failed" : 0,
          "current" : 0,
          "time" : "0s",
          "time_in_millis" : 0
        }
      }
    }
  }
}

Any Idea for solve this error?


text:
Q: React useState: How can I update my useState with onChange for input and OnClick for the button? I am trying to update the useState hook but the object is returning empty. I have tried to use something like: <input onChange={e => setFilter(name: e.target.value)} > however, it submits on each key stroke and the button is pointless, and the user cant fully complete the value (Copy and paste only works). What am I doing wrong?
export default function Search() {
  const [filter, setFilter] = useState({ name: "Hungary" });
  const { data, loading, error } = useQuery(GET_COUNTRY_INFO, {
    variables: { filter },
  });

  if (loading) {
    return <Loader />;
  }
  if (error) return
Error
;

  const userReq = {
    name: ''
  }

  function onChangeHandler (e) {
    const userReq = {name: e.target.value}
    return userReq
  };

  const onClickHandler = (e) => {
    setFilter(userReq)
  }

  return (

        Get Information

 about Countries!

          <input
            className="search"
            type="text"
            id="search"
            placeholder="Enter a Country"
            onChange={onChangeHandler}
          />

          <button className="submit" name="name" type="submit" onClick={onClickHandler}>
            Search
          </button>

        {data?.Country?.[0] && <CountryInfo country={data?.Country[0]} />}

  );
}

A: your setFilter is wrong, you are using :
setFilter(name: e.target.value)

and should be:
setFilter({ name: e.target.value });

So, the code below should work and you dont need the 'userReq' variable:
function onChangeHandler(e) {
    setFilter({ name: e.target.value });
}

const onClickHandler = (e) => {
   console.log(filter);
};

<input type="text" id="search" onChange={onChangeHandler} />

If you want onChange inline:
onChange={(e) => setFilter({ name: e.target.value })}

A: You probably want 2 separate states here,

*

*A state which holds the current filter

*A state which holds the current user's input
and on clicking the button you want to sync the user's input with the filter
Looking at your code I think you've already figured this out, so just making your userReq a state should solve your problem
Basically changing this
 const userReq = {
    name: ''
  }

  function onChangeHandler (e) {
    const userReq = {name: e.target.value}
    return userReq
  };

to this
  const [userReq, setUserReq] = useState({ name: '' })

  function onChangeHandler (e) {
    setUserReq({ name: e.target.value })
  };


text:
Q: Split on period without removing the period punctuation once split - Python I have seen a lot of related questions to mine but I still can't seem to get my specific example to work.
I have some data in a file which is several sentences strung together. I am trying to split the sentences into a list with each sentence being an element of the list. But when I split on a period followed by a space I lose the period in all the elements of my list (except the last one).
I begin with this:
text = "This sentence. And this one. One more."

Desired output:
["This sentence.", "And this one.", "One more."]

Currently I am getting this by doing text.split('. "):
["This sentence","And this one","One more."]

A: Use positive look behind:
import re
re.split(r'(?<=\.) ', text)

The above assumes your sentence always end with a period and a space (except the last sentence).
(?<=\.) is a positive look behind, so the regexp above will split on a space that is just after a dot, but it won't take dot into account when doing the substrings.

A: Given you stored the splitted list in a variable:
strList = text.split()
for line in strList:
   line.append('.')
strList[len(strList) - 1] = strList[len(strList) - 1][:-1]

A: You could use the following and trim the leading whitespace.
[^\.]+\.

REGEX demo

A: this can also be done
[ i.group(0) for i in re.finditer('\S[^\.]+(\.|.$)', text)]

it matches any character other than dot till it reaches a dot or end of line


text:
Q: React UnhandledPromiseRejectionWarning unhandled-rejections=strict I have a React code showing error below. It keeps closing and ending the program build. How can I stop this? I have a lot of APIs, and don't want to change existing code. Which file in React do I add this into? --unhandled-rejections=strict I don't see any filename containing this. Or how else can I prevent the stop build problem in file/config settings?

(node:42021) UnhandledPromiseRejectionWarning: [object Array]
(Use node --trace-warnings ... to show where the warning was created)
(node:42021) UnhandledPromiseRejectionWarning: Unhandled promise rejection. This error originated either by throwing inside of an async
function without a catch block, or by rejecting a promise which was
not handled with .catch(). To terminate the node process on unhandled
promise rejection, use the CLI flag --unhandled-rejections=strict
(see https://nodejs.org/api/cli.html#cli_unhandled_rejections_mode).
(rejection id: 1)
(node:42021) [DEP0018] DeprecationWarning: Unhandled promise rejections are deprecated. In the future, promise rejections that are
not handled will terminate the Node.js process with a non-zero exit
code.


text:
Q: JSS7 - TC-CONTINUE: No dialog/transaction for id: We are working on SS7 CAMEL application. The application is based on jboss 5.10GA
and Mobicents/Restcomm's jss7 and Restcomm's CAP Resource adapter.
In our Sbb we receive InitialDP message and delimiter from switch. After we recieve the delimiter we try to send connect message to the switch.
Unfortunatelly, when we invoke .send() method on the dialog that we receive in onDelimiter method, no message to switch is sent and what we can see in the jboss log is:
TC-CONTINUE: No dialog/transaction for id: 67793592
    public void onDelimiter(DialogDelimiter delimiter, ActivityContextInterface aci)
    {
        try
        {
            CAPDialogCircuitSwitchedCall dialog = (CAPDialogCircuitSwitchedCall) delimiter.getCAPDialog();
            dialog.addRequestReportBCSMEventRequest(bcsmevents, extensions);
            dialog.addCallInformationReportRequest(requestsTypes, null, null);
            dialog.addConnectRequest(new DestinationRoutingAddressImpl(new ArrayList<CalledPartyNumberCap>(Arrays.asList(new CalledPartyNumberCapImpl(new CalledPartyNumberImpl("48602465380".getBytes()))))), null, new OriginalCalledNumberCapImpl(new OriginalCalledNumberImpl(cdr.getBNumber().substring(0,10).getBytes())), null, new CarrierImpl("9191".getBytes()), null, null, null, null, null, null, null, null, false, false, false, null, false);
            dialog.addContinueRequest();
            dialog.send();
            (...)
         }
     }

If it is a problem with our sccp rules then what should be the correct sccp settings for the following addresses:
Switch:
PC: 6801,
SSN: 146,
GT: 4794733271,
AI: 18
Our server:
PC: 5100,
SSN: 146,
GT: 442080000100,
AI: 18
Here's the boot.log file
Here's the server.log file

A: This message "TC-CONTINUE: No dialog/transaction for id: 67793592" means that a TC-CONTINUE primitive came to TCAP stack but no such local dialog. No processing was done and onDelimiter() method was not invoked.
The most probably reason is that the TCAP dialog was already timeed out. You need :
- either increase dialogTimeout stack options (many times because it is CAP)
- or inside "CAPDialogListener.onDialogTimeout(CAPDialog capDialog)" invoke capDialog.keepAlive(); (this way you need to check if dialog is not kept for too long time)

A: I think you are using Restcomm jainslee with cap RA?
Can you please attach server.log?
Br,
TN


text:
Q: Core Data Table View Section Sort by weekdays using NSSortDescriptor I'm currently trying to sort my array of objects into day order so they can be grouped in the correct order i.e. Monday, Tuesday, Wednesday then by start time.
Only problem is I can't figure out how to do this, my code currently looks like this: Which sorts alphabetically then by time:
NSString *sectionKey = nil;
switch (tab) {

case kByWeekA: {
NSSortDescriptor *sortDescriptor1 = [[NSSortDescriptor alloc] initWithKey:@"day" ascending:NO];
NSSortDescriptor *sortDescriptor2 = [[NSSortDescriptor alloc] initWithKey:@"starttime" ascending:YES];
NSArray *sortDescriptors = [[NSArray alloc] initWithObjects:sortDescriptor1, sortDescriptor2, nil];
[fetchRequest setSortDescriptors:sortDescriptors];
[sortDescriptor1 release];
[sortDescriptor2 release];
[sortDescriptors release];
sectionKey = @"day";
break;
}
case kByWeekB:{
NSSortDescriptor *sortDescriptor1 = [[NSSortDescriptor alloc] initWithKey:@"day" ascending:YES];
NSSortDescriptor *sortDescriptor2 = [[NSSortDescriptor alloc] initWithKey:@"starttime" ascending:YES];
NSArray *sortDescriptors = [[NSArray alloc] initWithObjects:sortDescriptor1, sortDescriptor2, nil];
[fetchRequest setSortDescriptors:sortDescriptors];
[sortDescriptor1 release];
[sortDescriptor2 release];
[sortDescriptors release];
sectionKey = @"day";
break;
}
default:
break;
}

Please help!

A: I see two solutions:

*

*Create a custom comparison for your sort descriptor that looks at the "day" key and orders them as desired. See Specifying Custom Comparisons here.

*Make the "day" key into an integer and use an enumeration for the day values in the desired order.

UPDATE 2 Example code for option 2:
-Change the "day" attribute to a number (Int16) and add a transient (non-persistant) "dayName" string attribute.
-Add this enumeration of the week days:
typdef enum {
    kMonday,
    kTuesday,
    kWednesday,
    kThursday,
    kFriday,
    kSaturday,
    kSunday
} WeekDay;

-Set the "day" property of your managed objects to be NSNumber objects. For example:
object.day = [NSNumber numberWithInteger:kMonday];

-Implement the getter function for the transient "dayName" property:
- (NSString*)dayName {
    switch ((WeekDay)self.day.integerValue) {
        case kMonday:
            return @"Monday";
            break;
        case kTuesday:
            return @"Tuesday";
            break;
        case kWednesday:
            return @"Wednesday";
            break;
        case kMonday:
            return @"Monday";
            break;
        case kThursday:
            return @"Thursday";
            break;
        case kFriday:
            return @"Friday";
            break;
        case kSaturday:
            return @"Saturday";
            break;
        case kSunday:
            return @"Sunday";
            break;
    }
}

-In the fetch request, sort by "day" and use "dayName" as the section name key path.
UPDATE
Note: Option 1 works fine for sorting an array, but Core Data is throwing an 'NSInvalidArgumentException' exception for 'unsupported NSSortDescriptor selector: weekdayCompare:'
Example code for option 1:
// category on NSString for custom comparison
@interface NSString (WeekdayComparison)
- (NSComparisonResult)weekdayCompare:(NSString*)otherDay;
@end
@implementation NSString (WeekdayComparison)
- (NSComparisonResult)weekdayCompare:(NSString*)otherDay {
    NSArray *weekDays = [NSArray arrayWithObjects:@"Sunday", @"Monday", @"Tuesday", @"Wednesday", @"Thursday", @"Friday", @"Saturday", nil];

    NSUInteger selfIndex = [weekDays indexOfObject:self];
    NSUInteger otherDayIndex = [weekDays indexOfObject:otherDay];

    if (selfIndex < otherDayIndex) {
        return NSOrderedAscending;
    }
    else if (selfIndex > otherDayIndex) {
        return NSOrderedDescending;
    } else {
        return NSOrderedSame;
    }
}
@end

To use the new comparison method:
NSSortDescriptor *sortDescriptor = [[NSSortDescriptor alloc] initWithKey:@"day" ascending:YES selector:@selector(weekdayCompare:)];
NSArray *sortDescriptors = [NSArray arrayWithObjects:sortDescriptor, nil];
[sortDescriptor release];

A: I was working with the same requirements for custom sorting of sections and Solution #1 worked for me very well, thanks!
One thing I'd like to add is that after adding the transient property if your app crashes mysteriously a couple of seconds after loading, you need to reset your database.
NSError *error;
NSURL *applicationDocumentsDirectory = [[[NSFileManager defaultManager] URLsForDirectory:NSDocumentDirectory inDomains:NSUserDomainMask] lastObject];
NSURL *databaseURL = [applicationDocumentsDirectory URLByAppendingPathComponent:@"My Database Name"];
[[NSFileManager defaultManager] removeItemAtPath:databaseURL.path error:&error];

Hope this helps!


text: Q: Newton's 3rd law and rocket nozzles For a given solid propellent charge the energy given off by the charge is equivalent in all cases. Yet by varying the throat of the nozzle, the rocket velocity will be different for each individual throat. Total energy given off and total mass remains identical. How does this not conflict with the 3rd law?


text:
Q: Remove partitions that appear after GPT format I recently formatted my USB to EFI with GPT partition on Windows 10 using diskpart. Since then, even though the USB is not plugged in there are two partitions (empty and useless) that show up among others. Check the image. Can someone guide me on removing them (H: and I:) since they don't show up on Disk Management or diskpart.

A: I fixed it. I just plugged in the USB that I had converted to GPT. I used diskpart to clean it and create a primary partition. This removed the two phantom drives.
Anyways, I got a question now. What'd I have to do if I had lost that USB? Just a question I had.


text:
Q: How do I save a custom class in swift to NSUserDefaults? I have made a custom class called test. I made a variable called "game" equal to test. I tried to save "game" to NSUserDefaults and attempted to print values from "game". After running the project I got an error: "Thread 1:signal SIGABRT". How do I save my custom object to NSUserDefaults without getting this error?
Here is my class:
class Test {
    var boolean = false
    var int = 1
    var arr = ["one": 1]
}

Here is my saving code:
    let defaults = NSUserDefaults.standardUserDefaults()

    let game = Test()

    game.arr = ["two": 3]
    game.hi = true
    game.int = 100

    defaults.setObject(game, forKey: "SG")

    let gameSet = defaults.objectForKey("SG")! as! Test

    print(gameSet.int)
    print(gameSet.boolean)
    print(gameSet.arr["one"])

This is all in the viewDidLoad method. Excluding the test class.

A: From the documentation:

The value parameter can be only property list objects: NSData, NSString, NSNumber, NSDate, NSArray, or NSDictionary.

You'll want to look at using NSKeyedArchiver instead for custom objects.


text:
Q: Unable to create new React Native app with Expo I attempted to create a new React native project using the expo-cli. I enter the command "npx create-expo-app my-app" and I get this message in the terminal "Something went wrong in downloading and extracting the project files: Could not parse JSON returned from "npm pack expo-template-blank@latest --dry-run""
And the error it gives me is "Unexpected token e in JSON at position 0".
This has come completely out of nowhere. I had created a new expo project just yesterday with no issues. I have uninstalled and reinstalled the expo-cli and updated node and npm.
The versions I am using are:
npm  - 8.13.2 |
node - 16.15.1 |
expo-cli - 5.4.12
If anyone knows why this might be happening, I'd appreciate the help. Thank you


text:
Q: Como trazer no resultado do SELECT as condições inseridas como parâmetros? Tem alguma forma de trazer no resultado do SELECT os valores dos parâmetros utilizados na cláusula WHERE ?
Exemplo:
SELECT
  a.*, cast(:dataIni as date) AS inidate , cast(:dataFin as date) AS inidate
FROM
  mytable a
WHERE
  a.date BETWEEN :dataIni AND :dataFin

Existe alguma forma de se retornar os valores dos parâmetros como campos da consulta utilizando o Firebird?

A: Se eu entendi direito é so colocar os parâmetros como fields:
SELECT
  a.*,
  cast(:dataIni as date) AS inidate ,
  cast(:dataFin as date) AS inidate,
  :dataIni as DataInicial,
  :dataFin as DataFinal
FROM
  mytable a
WHERE
  a.date BETWEEN :dataIni AND :dataFin

Não sei se é isso que precisa!!!

A: Não há como fazer isso.
Tampouco um recurso como este parece necessário pois quem enviou a consulta é também quem vai obter os resultados e este sujeito conhece os valores que passou como parâmetro.


text:
Q: Making a row clickable to take you to a link I've made some CSS modifications to it already and now I need to make one programming modification.  I'm a C# guy so this PHP is throwing me a little curve ball.
Here is the part I would like to modify:

{forumrow.FORUM_IMAGE}

                            {forumrow.L_SUBFORUM_STR}{L_COLON}

                                {forumrow.subforum.SUBFORUM_NAME}

                        {forumrow.FORUM_NAME}
                        {forumrow.FORUM_DESC}

{L_REDIRECTS}{L_COLON} {forumrow.CLICKS}

                        (<dfn>{L_TOPICS}{L_COLON}</dfn> {forumrow.TOPICS} | <dfn>{L_POSTS}{L_COLON}</dfn>{forumrow.POSTS})
                        {LAST_POST_IMG}{L_NO_POSTS}

                            {UNAPPROVED_IMG}

                            {UNAPPROVED_POST_IMG}

I would like if the "row" is clicked for it to take you to the forum.  Right now only if the title/header is clicked will it take you to the forum.
Which I believe is this line:

Here is a demo of how the default template works:
https://www.phpbb.com/customise/db/style/pbtech/demo/3.1
The only difference I have made from the demo is those forum "blocks" are now changed to take up 100% width instead of 33.3%.  I'd like it so if you click anywhere on the forum "block/row" it takes you to the forum.

A: This cannot be achieved with PHP. It could be achieved with a small JavaScript snippet on the front end.

What this does is attaches an event handler to any clicks on li.row. It finds the link within and either triggers click to it, or uses its href property to change browser window location URL.
This requires a JavaScript library called jQuery which appears to already be in use on your demo template. The code block above would need to be included BELOW the


text:
Q: SVN options not coming in Eclipse Springsource For Eclipse Spring Tool Suite Version: 3.5.1,
Have installed Subclipse 1.10 and other plugins like Subversion Client Adapter.
Still, on right clicking a file and under menu 'Team', SVN options are not coming up.
Thanks in advance, Kakoli

A: Maybe you have to reinstall the plugin http://subclipse.tigris.org/servlets/ProjectProcess?pageID=p4wYuA and restart eclipse.


text:
Q: Why is nobody dead? So I'm a short way into the game and I don't understand why everyone has been alive for centuries? It seems that the end of the world has been coming for 500 years and everyone it just still alive?
So, why is everyone still alive? What is stopping them from dying and why have they existed for centuries?

A: Reading on Wikipedia about the plot of FF 13-2.

! Caius has been driven mad by watching her [Yuel] die repeatedly and seeks to end the process by unleashing the chaos trapped in Valhalla to destroy all time.
! [After Serah dies] Just then, a black cloud erupts from the sky as the chaos that Etro was keeping trapped breaks free.

So it seems that the Chaos has stopped the flow of time, which means that people no longer age, nor do they die. Hence why, in the final chapter of the story in FF Lightning Returns, everyone has been alive for centuries.


text:
Q: Invariance of Space and Time in Different Reference Frames I'm studying dynamics by Anil Rao's book. He said something that made me really confused. The citations below construct the problem.

[...]
An assumption of Newtonian mechanics is that space is invariant with
respect to changes in reference frames, i.e., observations made of
space are the same in all reference frames. As a result of the
assumption of the invariance of space, observations of an arbitrary
vector b are the same regardless of the reference frame. Consequently,
for any two reference frames A and B we have
$ {}^{A} {\bf b} = {}^{B} {\bf b} = {\bf b}$
[...]

Then he talks about rate of change of a vector function:

[...] given an arbitrary vector function of time, at every instant of time
observers in all reference frames see the same vector. In other words,
a vector is independent of the reference frame in which it is
observed. However, unlike a scalar function of time, observers in
different reference frames do not see the same rate of change of a
vector function of time. Contrariwise, observers fixed in different
reference frames will, in general, make different observations about
the rate of change of a vector function of time. As a result, the
phrase "rate of change of a vector" must always be qualified by
stating explicitly the reference frame in which the observation is
being made.
[...]

Further, about velocity:

It is important to understand that the notation $ {}^{A} {\bf v} $ is
merely a shorthand for $ {}^{A} d{\bf r}/dt $. In other words, when we
write $ {}^{A} {\bf v} $, we mean that the vector $ {}^{A} {\bf v} $
arises from taking the rate of change of another vector (in this case
position) in reference frame A. Furthermore, it is important to
understand that, although $ {}^{A} {\bf v} $ arises from taking the
rate of change of r in reference frame A, the quantity $ {}^{A} {\bf v} $
is itself a vector. Consequently, by assumption observations of
the vector $ {}^{A} {\bf v} $ are the same in all reference frames.

*

*The rate of change of the position is dependent of the frame of reference.

*Velocity is the rate of change of the position.

So why velocity is independent of reference frame?
Or more generally: i can't understand why vectors are independent of reference frame, but their rate of change are.


text:
Q: C++: How call a function with type parameter on variadic template arguments? So I have a function with variadic template arguments and I'm trying to invoke a method (with a type parameter) for every argument, pack every result value in a std::tuple and return it. However variadic templates are pretty hard for me and I haven't fully understood them yet.
Is it even possible to realize this in C++?
Here's my code so far (which has an error in the getMultiple function). Thank you very much for helping!
#include <iostream>
#include <fstream>
#include <sstream>

template<typename T>
T get(std::istream &stream) {
    T data;
    stream >> data;
    return data;
}

template<typename ... Ts>
std::tuple<Ts...> getMultiple(std::istream &stream) {
    // What am I doing wrong here?
    return std::make_tuple((get<Ts...>(stream)));
}

int main() {
    std::istringstream stream("count 2");
    auto [command, number] = getMultiple<std::string, int>(stream);

    return 0;
}

A: First of all, you forgot the
#include <tuple>

And the syntax you're probably looking for is:
return std::make_tuple(get<Ts>(stream)...);

A: You are nearly correct, but your ... are misplaced,
get<Ts...>(stream) translates to get<T0, T1, .., Tn>(stream)
it would be
foo(get<Ts>(stream)...) which translate to foo(get<T0>(stream), get<T1>(stream), .., get<Tn>(stream))
and you have issue with evaluation order
in foo(a(), b()), a() and b() are indeterminately sequenced, so a() might happens before b(), or the reverse. variadic template doesn't change that.
So you cannot use std::make_tuple. Fortunately inside {..}, order is determined from left to right, so you might use:
return std::tuple{get<Ts>(stream)...};


text:
Q: How to show double quote in input tag? How to show double quote in input tag ?
my $test is i test "hello"
and input like this
<input name="test" type="text" value="<?PHP echo $test; ?>">

When test code in input show only i test
How can i do for show i test "hello" in input tag ?

A: Try to use htmlspecialchars or use htmlentities
<input name="test" type="text" value="<?php echo htmlspecialchars($test); ?>">

<input name="test" type="text" value="<?php echo htmlentities($test); ?>">

Or by using PHP echo you can do it
<?php echo '<input name="test" type="text" value="'.$test.'">'; ?>

A: use html_entity_decode since you're using php like so:
<input name="test" type="text" value="<?PHP echo html_entity_decode($test); ?>">


text:
Q: Android Studio Bumblebee I was using Android Studio Arctic Fox and was having few problems.
Stupidly, I responded to the constant prompting to upgrade to Bumblebee and now I have no Android emulator.
The button on the toolbar does nothing and there is no emulator option in the view-Tool Windows tab.
I definitely have the emulator installed. I even deleted and reinstalled it in case something had become corrupted in the update.
Anyone got any ideas?


text:
Q: How to reconcile monorepo with multiple tsconfig.json each having its own paths? We have a codebase setup like so:
-A
--utils
---index.ts
--index.ts
--tsconfig.json
-B
--utils
---index.ts
--index.ts
--tsconfig.json
-tsconfig.json

Our root tsconfig.json contains the following:
    "paths": {
      "A/*": ["A/*"],
      "B/*": ["B/*"],
    },

Each package's tsconfig.json contains the following:
    "paths": {
      "utils/*": ["./utils/*"],
    },

This works for our current purposes, since we currently only use TS for type checking but we actually generate builds with Babel, which has a similar setup in the alias property of the various .babelrc files.
We are looking to start running code using ts-node (or an equivalent) and have run into the issue that at runtime, TS has no idea how to resolve modules. For example:
// A/index.ts
import { someUtil } from 'utils'
export const someFunc() => someUtil();

// B/index.ts
import { someFunc } from 'A';

When we run npx ts-node ./B/index.ts we get an error saying `Cannot find modules 'utils'.
We know that we can get this working by hoisting everything to the root tsconfig.json, but it seems superfluous to have to import { someUtil } from 'A/utils when you are already in package A.
Is there a way to use paths in the manner that we have? We have also read a bit about project references and tried that but it didn't seem to get us anywhere.

A: Inside the tsconfig.json file in each of the projects you should use extends on the root tsconfig like this:
// A/tsconfig.json
{
 "extends": "../tsconfig.json",
 ...
}

Thay way all the subprojects will inherit the paths from other general packages.
I think you can even define the utils path on the root, that way you won't have to repeat that either.
More about the extends option here:
https://www.typescriptlang.org/docs/handbook/tsconfig-json.html#tsconfig-bases
UPDATE
Also you need to use this lib:
https://www.npmjs.com/package/tsconfig-paths
and inside the package.json in the ts-node script in the scripts property you use: ts-node ... -r tsconfig-paths/register ... index.ts.
This lib will read the packages in ts-config.json and place them in node_modules, so your other packages can find them when you run with node or ts-node.

A: I hope it's not rude or unhelpful to suggest what you're trying to do might make no sense.
From the point of view of package A, './utils' can be different from the './utils' that package B sees - since they have a different filesystem 'root'. However, the attempt to alias two different './utils' paths as 'utils' from the point of view of BOTH packages creates an inevitable collision.
I am far from sure there's any value in doing this either. I would personally drop the aliasing of folders "./utils" to top-level aliases "utils" and then I think your issues will go away. Probably what you want on a per-package basis is specific includes, and for the 'local' utils for each package to be addressed relatively to the package...
{
  "extends": "../tsconfig.json",
  "include": ["index.ts", "utils/index.ts"]
}


text:
Q: How to create email address generator with Ruby?   def emails
    i = 0
    number = rand(252...4350)

    males = ["tom", "jack", "adam"]
    females = ["elizabeth", "rose", "juliet"]

    surnameMales = ["oak", "yew", "timber"]
    surnameFemales = ["rosewelth", "gates", "jobs"]

    providers = ["gmail.com", "hotmail.com", "yahoo.com"]

    while i <= 100 do
      @addresses <<
    end
  end

What I want to do is pick a random number, name, surname and provider and put them all together + attach a random number at the end of the surname so that it looks, for example, like this: rose.gates643@gmail.com, but kind of got stuck at the point where I have to put the whole thing together. As you can probably tell, I want to create a 100 random emails for testing purposes.
Can you please point me out how I could do what I have intended to do with Ruby?

A: Use a combination of string interpolation and Array#sample.
"#{females.sample}.#{surnameFemales.sample}#{rand(252...4350)}@#{providers.sample}"
>> "rose.rosewelth3266@gmail.com"

A: Is your goal to do this as an exercise or is this just something you're trying to get done?  If it's the latter, install the faker gem and just use it:
Faker::Internet.email #=> "kirsten.greenholt@corkeryfisher.info"

For 100:
100.times.map { Faker::Internet.email }

A: There's a couple ways to join strings in Ruby. Inline placeholders seems to make the most sense here:
@addressess << "#{ males.sample }.#{ surnameMales.sample }#{ number }@#{ providers.sample }"

In a double-quoted string, #{ expr } is evaluated and subbed inline. "#{ 1 + 1 }" outputs "2", for example.
Also a couple ways you can distinguish male or female — for example, checking if a random number is even or odd:
name = if rand(1..100) % 2 == 0 ? "#{ males.sample }.#{ surnameMales.sample }" : "#{ females.sample }.#{ surnameFemales.sample }"
@addresses << "#{ name }#{ number }@#{ providers.sample }"


text:
Q: Call all Java interface methods In many programs I see that when I implement an interface and override the methods they are called on specific events (example: onActionListener). I need to know how to call the methods from all the class that implements that specific interface. Thanks ahead for the answers.

A: You can only call a method of a class if it is static. If it is not, you can only call the method of "an Object" (an instance of this class). Now, assume you have a bunch of objects and an interface called ActionListener with actionPerformed() method in it. In order to call the method you will have to check if this object implements ActionListener - has the actionPerformed() method. Then, cast it to action listener, and call the method.
Take a look at this example:
JButton b1 = new JButton();
JButton b2 = new JButton();
Object[] objects = { b1, b2 }; // Some objects
for (Object obj : objects) {
    if (obj instanceof ActionListener) { // Check if they implement action listener
        ActionListener objListener = (ActionListener) obj;
        objListener.actionPerformed(new ActionEvent(null, 1, "command"));
    }
}


text:
Q: implement Zoom in/out in android camera preview I am using this as an example and it works nice (camera api, not camera2): http://examples.javacodegeeks.com/android/core/hardware/camera-hardware/android-camera-example/
But, how can I implement zoom in/out using two buttons like + and - ?!?
Already searched for hours and nothing yet.
Thank you very much.

A: Try this code, it should be helpful:-
  case MotionEvent.ACTION_MOVE:

                  if (mode == ZOOM) {
                    float newDist = spacing(event);

                    double zoomDist = newDist-oldDist;

                    if(zoomDist > 0){
                        if(zoomDist > 50 && zoomDist <= 200){

                            if (curZoomLevel < mZoomMax && gestureZoom == 0) {
                                gestureZoom ++;
                                GestureZoomIn();
                            }

                        }else if(zoomDist > 200 && zoomDist <= 300){

                            if (curZoomLevel < mZoomMax && gestureZoom == 1) {

                                gestureZoom ++;
                                GestureZoomIn();
                            }
                        }else if(zoomDist > 300 && zoomDist <= 400){

                            if (curZoomLevel < mZoomMax && gestureZoom == 2) {

                                gestureZoom++;
                                GestureZoomIn();
                            }

 //zoomin
     private void GestureZoomIn(){
           if (mParameters.isZoomSupported()){
                mZoomMax = mParameters.getMaxZoom();
                if (zoom_text_value<mZoomMax) {
                    zoom_text_value++;
                    curZoomLevel++;
                    zoom_float=zoom_float+0.5;
                    onZoomValueChanged(curZoomLevel);

 //zoomout
    private void GestureZoomOut(){
           if (mParameters.isZoomSupported()){

                if (0<zoom_text_value) {
                    zoom_text_value--;
                    curZoomLevel--;
                    zoom_float=zoom_float-0.5;
                    onZoomValueChanged(curZoomLevel);

Thanks


text:
Q: Pass data to different controllers using Angularjs I have the below code in one controller.
    $scope.DataModel= [];
    $scope.DataModelTexts= { buttonDefaultText: '' };

I will be using the same code in one more controller. Now instead of writing the same code in 2nd controller too, i want to know if there is a way to put this in a common code in some factory or service and use that in both the controllers. I have tried to read about factory and services and i am getting a bit confused of how to use any one of these in my scenario.
Any information would help me gain more knowledge about factory and services in angularjs. Thanks.

A: You're on the right track, use can use a factory or a service to share code between controllers. Note that in angular services(and factories) are singletons; they are instantiated once when the app starts and then anytime you inject it into a controller, you are referencing the same instance. Consider the following code:
var myApp = angular.module('myApp',[]);

myApp.service('MyService', function() {
  let _someValue = 'Initial Value';
  this.setValue = function(value){
    _someValue = value;
  }
  this.getValue = function(){
    return _someValue;
  }
});

//First Controller Run
myApp.controller('ControllerA', function($scope, MyService) {
  MyService.getValue(); //Initial Value
  MyService.setValue("BRAND NEW VALUE!!!");
});

//Run after ControllerA
myApp.controller('ControllerB', function($scope, MyService) {
  MyService.getValue(); //BRAND NEW VALUE!!!
});

Her you'll see that MyService holds the state of someValue. ControllerA get MyService injected to it and can use the methods of that service to set a new value. Now for any subsequent call for that same state, like for instance by ControllerB, the updated value will be returned.

A: You can use the .config() or a run() blocks (good SO on these here: AngularJS app.run() documentation?) to bind these reused variables to $rootScope, then call them from $rootScope.DataModel and $rootScope.DataModelTexts from within your controllers or services (as long as you inject $rootScope into these controllers and services).


text:
Q: Accessing current Activity from any place I'm writing application which needs in some places access to current Activity. So I have written code which gives access by calling Application.getApplication().getCurrentActivity(). I'm wondering what are possible drawbacks of such solution and is it a good practice for writing Android applications? Can someone share his one experience?
public class Application extends android.app.Application {

    private static volatile Application INSTANCE;

    private ApplicationLifecycleListener mApplicationLifecycleListener;

    public static Application application() {
        return INSTANCE;
    }

    @Override
    public void onCreate() {
        super.onCreate();
        INSTANCE = this;
        initApplicationLifecycleListener();
    }

    private void initApplicationLifecycleListener() {
        mApplicationLifecycleListener = new ApplicationLifecycleListener();
       registerActivityLifecycleCallbacks(mApplicationLifecycleListener);
    }

    public Activity getCurrentActivity() {
       return mApplicationLifecycleListener.getCurrentActivityReference().get();
    }

    private class ApplicationLifecycleListener implements android.app.Application.ActivityLifecycleCallbacks {

        private WeakReference<Activity> mCurrentActivityReference;

        @Override
        public void onActivityResumed(Activity activity) {
            mCurrentActivityReference = new WeakReference<>(activity);
        }

        @Override
        public void onActivityPaused(Activity activity) {
            mCurrentActivityReference = null;
        }

        @Override
        public void onActivityCreated(Activity activity, Bundle savedInstanceState) {}

        @Override
        public void onActivityStarted(Activity activity) {}

        @Override
        public void onActivityStopped(Activity activity) {}

        @Override
        public void onActivitySaveInstanceState(Activity activity, Bundle outState) {}

        @Override
        public void onActivityDestroyed(Activity activity) {}

        public WeakReference<Activity> getCurrentActivityReference() {
            return mCurrentActivityReference;
        }
    }
}


text:
Q: How to determined which Windows ISO was used to installed OS? Does anyone know of a command or registry key which shows the installation media used to install Windows?
Winver only gives me the current installed built.
Thanks


text:
Q: Calculating the maximum number of sectors per track for a hard disk If you know the media transfer rate of a hard disk, how do you use that information to calculate the maximum number of sectors per track?

A: You probably cannot.  Even wimpy hard drives have caches and one logical track is not the same as a physical track anymore.

A: If a sector is a known size (in bytes), you know the rpm of the drive, you know the maximum transfer rate* (in Megabytes/sec or somesuch) it should be fairly straightforward to work out the maximum number of sectors on a track.
I say "should be" because you're not being given enough data for a modern drive. You'll have to assume that the number of sectors per track is constant over the area where you are measuring the maximum transfer rate for starters. It probably is but it might not be, so the best you can get using these numbers is a pretty close estimate  provided the drive is physically simple. Unfortunately drives are not physically simple anymore.
To expand on Michael Graff's answer - there is a lot going on at the physical level (remapping of sectors, variable track geometry, multiple heads and more) that will make it hard to give an absolute answer. Sector interleaving would completely throw any calculations out too but that is rare in modern drives as far as I'm aware. For drives with multiple physical platters and multiple heads you have to adjust for that too - for example on a drive with six read\write heads on three platters, there might be 200 sectors per track, (on each side of a platter) but there will be 1200 sectors per cylinder.
If you know the physical structure of the drive (number of read/write heads), you know that it's pretty healthy (so there are no significant amount of remapped sectors), you know that it doesn't use interleaving and you know that the read test you carried out was thorough enough to swamp any cache effects, then you can make a reasonable calculation based on the rpm of the drive and the maximum transfer rate.


text:
Q: How to get cheapest product from every group How to do the following with laravel ORM?
select f.type, f.variety, f.price
from (
 select type, min(price) as minprice
 from fruits group by type
 ) as x inner join fruits as f on f.type = x.type and f.price = x.minprice;

A: $subQuery = "(select type, min(price) as minprice from fruits group by type) as x";
$query = DB::table('fruits')::selectRaw( "fruits.type,fruits.variety,x.minprice" );
$query->join( DB::raw($subQuery), function ($join) {
    $join->on ( 'fruits.type', '=', 'x.type' );
});
$data = $query->get();

I have not tested the code but hopes it works.


text:
Q: How to prove that $p^{e-f}\mid\binom{n}{t}$ Let $p$ a prime odd number, $e,f,n,t\in\mathbb{N}$ such that: $2\leq t\leq n$, $p^{e}|n$, and $p^f\mid t$ but $p^{f+1}\nmid t$ . So we have $n=p^en',t=p^ft'$ and $gcd(p,t')=1$.
I already know that $\binom{n}{t}=\frac{n}{t}\binom{n-1}{t-1}=p^{e-f}\frac{n'}{t'}\binom{n-1}{t-1}$, but I don't know how prove that  $\frac{n'}{t'}\binom{n-1}{t-1}\in\mathbb{Z}$.
Any help or idea is well received.

A: Since
$$
\binom{n}{t} = \frac{n}{t}\binom{n - 1}{t - 1},
$$
it follows that
$$
t | n\binom{n - 1}{t - 1}.
$$
In particular,
$$
t^\prime | n\binom{n - 1}{t - 1} = p^en^{\prime}\binom{n - 1}{t - 1}.
$$
But $gcd(t^\prime, p^e) = 1$. Thus
$$
t^\prime|n^{\prime}\binom{n - 1}{t - 1}.
$$


text:
Q: Srcset not working on IPhone's Safari I have the following HTML for a logo:
<img src="logo.png" srcset="logo-1x.png 1x, logo-2x.png 2x"/>

When I try this on IPhone's Safari the image is not displayed.
What might be wrong?


text:
Q: How can I concatenate arrays of 2D data I am attempting to read 2D data like the following:
12345678
abcdefgh
ABCDEFGH

With the API available to me, I can read it into a 1D array in two parts, split down the middle:
First array: 1234abcdABCD
Second array: 5678efghEFGH
Now I need to merge these to get 12345678abcdefghABCDEFGH.
Is there a more sophisticated/stable way of doing this than memcpy and careful counting?

A: A sequence of inserts can do the job. The code can be extracted into a function that takes a number of chunks and chunk size as parameters.
std::vector<unsigned char> my_merge(
    const std::vector<unsigned char>& part1,
    const std::vector<unsigned char>& part2,
    const unsigned int chunk_count,
    const unsigned int chunk_size)
{
    std::vector<unsigned char> merged;
    merged.reserve(part1.size() + part2.size());
    for(unsigned int i = 0; i < chunk_count; ++i)
    {
        merged.insert(
            merged.end(),
            part1.begin() + i * chunk_size,
            part1.begin() + (i + 1) * chunk_size);
        merged.insert(
            merged.end(),
            part2.begin() + i * chunk_size,
            part2.begin() + (i + 1) * chunk_size);
    }
    return merged;
}

Usage:
std::vector<unsigned char> merged = my_merge(part1, part2, 3, 4);

Demo

A: Try std::copy.
example below (may be you can rewrite below code by looping logically).
int a[12] = {1,2,3,4,'a','b','c','d','A','B','C','D'};
int b[12] = {5,6,7,8,'e','f','g','h','E','F','G','H'};

int c[3][8];

//First Row
std::copy(a, a+4, c[0]);
std::copy(b, b+4, c[0]+4);

//Second Row
std::copy(a+4, a+8, c[1]);
std::copy(b+4, b+8, c[1]+4);

//Third Row
std::copy(a+8, a+12, c[2]);
std::copy(b+8, b+12, c[2]+4);


text:
Q: Find max and min date from an array of date strings I have an array of objects as follows
data = [
 {
  mas_name: (...),
  mas_plan_end: (...) // 'YYYY-MM-DD' eg: '2021-03-19'
  mas_plan_start: (...) // 'YYYY-MM-DD' eg: '2021-03-19'
  ...
 },
 {
  mas_name: (...),
  mas_plan_end: (...)
  mas_plan_start: (...)
  ...
 }
]

In the above array, some of the objects might even contain mas_plan_start as null..
I need to get the minimum and maximum values of mas_plan_start from this array.
I tried using moments in the following manner
const max = moment.max(children.map((o) =>
          o.mas_plan_start ? o.mas_plan_start : moment(new Date()).format("YYYY-MM-DD")
        )) ;

const min = moment.min(children.map((o) =>
          o.mas_plan_start ? o.mas_plan_start : moment(new Date()).format("YYYY-MM-DD")
        )) ;

But it threw me this error

How can I fix this, ...or is there any way to do this without using moments.
Solution:
const max_date = moment.max(data.filter((o) =>
          o.mas_plan_end !== null
        ).map((date) =>
        moment(date.mas_plan_end, 'YYYY-MM-DD') // converting to moment instance so that .max command will work
        ));
      parent.mas_plan_end = max_date._i; // to get the date String back from the moment instance

A: I've not used moment.js before but from your code, I figure this is how it's used to format dates
const max = moment(data.map(obj => new Date(obj.mas_plan_end ?? '')).reduce((a, b) => b > a ? b : a)).format("YYYY-MM-DD");
const min = moment(data.map(obj => new Date(obj.mas_plan_start ?? '')).reduce((a, b) => b < a ? b : a)).format("YYYY-MM-DD");

The ?? operator I used is called the nullish coalescing operator it returns the second value, if the first value is null or undefined. Nullish Coalescing MDN


text:
Q: operator << interprets arithmetic operation if the result is unsigned int or unsigned short I use gcc 4.8.3 under  fedora 19 64bits
unsigned u1=10, u2=42;
unsigned short us1=10, us2=42;

int main() {
   cout << "u1-u2="<<u1-u2<<", us1-us2="<<us1-us2<<endl;
}

Result :
u1-u2=4294967264, us1-us2=-32
The << operator seems to interpret the result of the second operation as a signed short
whereas it interprets the result of the first operation as an unsigned int

A: As operands of - and most other arithmetic operators, any values of integral type narrower than int are promoted to int.
So us1 - us2 behaves as (int)us1 - (int)us2.
This rule is pretty annoying in modern C++, but it came in right from the earliest version of C (because int-sized registers were used for arithmetic) and it would break too much code to change it now.


text:
Q: How to remove duplicate values from an array of objects in react for select components of MUI I wanted to remove data from my array of objects. There are lots of duplicate values in my data, and this should be in the form of map so this is on my select value for selection.
Array of Objects:
rawData = [
0: {
  style_no: "BAG-011459",
  Item_description: "Hoplite Top Load Bag Standard 21 x 36 Olive",
  mon: "21310026-4",
  type: "Bags",
  oq: 51,
  force_update: 62,
  c_n: "WHITE DUCK",
  pl_q: 51,
  os: "Open",
},
1: {
  style_no: "BAG-010865",
  Item_description: "Hoplite Top Load Bag Large 25 x 42  Olive",
  mon: "21310030-5",
  type: "Bags",
  oq: 102,
  force_update: 63,
  c_n: "WHITE DUCK",
  pl_q: 102,
  os: "Open",
},
2: {
  style_no: "BAG-011932",
  Item_description: "Hoplite Top Load Bag Large 25x42 Black",
  mon: "21310035-8",
  type: "Bags",
  oq: 464,
  force_update: 64,
  c_n: "WHITE DUCK",
  pl_q: 464,
  os: "Open",
},
3:{
  style_no: "BAG-011932",
  Item_description: "Hoplite Top Load Bag Large 25x42 Black",
  mon: "21310034-8",
  type: "Bags",
  oq: 464,
  force_update: 65,
  c_n: "WHITE DUCK",
  pl_q: 464,
  os: "Open",
},
4:{
  style_no: "BAG-011931",
  Item_description: "Hoplite Top Load Bag Standard 21x36 Black",
  mon: "21310034-7",
  type: "Bags",
  oq: 160,
  force_update: 66,
  c_n: "WHITE DUCK",
  pl_q: 160,
  os: "Open",
},
5: {
  style_no: "BAG-011931",
  Item_description: "Hoplite Top Load Bag Standard 21x36 Black",
  mon: "21310036-7",
  type: "Bags",
  oq: 150,
  force_update: 67,
  c_n: "WHITE DUCK",
  pl_q: 150,
  os: "Open",
},
6: {
  style_no: "BAG-011931",
  Item_description: "Hoplite Top Load Bag Standard 21x36 Black",
  mon: "21310035-7",
  type: "Bags",
  oq: 160,
  force_update: 68,
  c_n: "WHITE DUCK",
  pl_q: 160,
  os: "Open",
},
7: {
  style_no: "BAG-011460",
  Item_description: "Hoplite Top Load Bag Extra Large 30 x 50 Olive",
  mon: "21310034-6",
  type: "Bags",
  oq: 456,
  force_update: 69,
  c_n: "WHITE DUCK",
  pl_q: 456,
  os: "Open",
},
8: {
  style_no: "BAG-011460",
  Item_description: "Hoplite Top Load Bag Extra Large 30 x 50 Olive",
  mon: "21310035-6",
  type: "Bags",
  oq: 456,
  force_update: 70,
  c_n: "WHITE DUCK",
  pl_q: 456,
  os: "Open",
},
]

Select Body:
    {/* Customer */}
    <FormControl sx={{ m: 0.5 }} variant="standard">
      <InputLabel
        style={{ fontSize: "15px" }}
        id="demo-customized-select-label"
      >
        Customer
      </InputLabel>
      <Select
        required
        style={{
          fontSize: "12px",
          width: "125px",
        }}
        labelId="demo-customized-select-label"
        id="demo-customized-select"
        value={plandata.customer}
        onChange={(e) => {
          setPlanData((prev) => ({ ...prev, customer: e.target.value }));
        }}
        input={<BootstrapInput />}
      >
        {rawData
          ?.filter((data) => data.type.includes(plandata.division))
          .map((value) => (
            <MenuItem value={value.c_n.toString()}>
              {value.c_n.toString()}
            </MenuItem>
          ))}
      </Select>
    </FormControl>

The snippet of the select box is

Note: I already go through the answers which was related to this question but not find my query.
Edited: If any senior find me out for this problem is great, because yet I am unable to find solution.

A: Try this way:
{/* Customer */}
<FormControl sx={{ m: 0.5 }} variant="standard">
  <InputLabel
    style={{ fontSize: "15px" }}
    id="demo-customized-select-label"
  >
    Customer
  </InputLabel>
  <Select
    required
    style={{
      fontSize: "12px",
      width: "125px",
    }}
    labelId="demo-customized-select-label"
    id="demo-customized-select"
    value={plandata.customer}
    onChange={(e) => {
      setPlanData((prev) => ({ ...prev, customer: e.target.value }));
    }}
    input={<BootstrapInput />}
  >
    {rawData
      ?.filter((data) => data.type.includes(plandata.division))
      ?.filter((value, index, self) => self.indexOf(value) === index)
      .map((value) => (
        <MenuItem value={value.c_n.toString()}>
          {value.c_n.toString()}
        </MenuItem>
      ))}
  </Select>
</FormControl>


text:
Q: USAEPAY Payment Gateway integration I am working on integrating USAEPAY with my eCommerce website. I am able to make a payment through Payment form.
I recieve an email saying that the payment was successful with all the information entered by the client. I have selected the response as POST to a URL in my website.
If you notice, most of the fields are empty and I cannot know, what is the amount and the client name and so on. Please let me know if I have missed anything.
Here is the response received when the payment was successful :
UMstatus=Approved,
UMauthCode=TESTMD,
UMrefNum=0,
UMavsResult=Address: Match & 5 Digit Zip: Match,
UMavsResultCode=YYY,
UMcvv2Result=Match,
UMcvv2ResultCode=M,
UMresult=A,
UMvpasResultCode=,
UMerror=,
UMerrorcode=00000,
UMcustnum=,
UMbatch=,
UMbatchRefNum=,
UMisDuplicate=N,
UMconvertedAmount=,
UMconvertedAmountCurrency=840,
UMconversionRate=,
UMcustReceiptResult=No Receipt Sent,
UMprocRefNum=,
UMcardLevelResult=,
UMauthAmount=,
UMresponseHash=s/1424267120.9422973438661/c250f9c99a9a324be1064213b42703ba61620eb0,
UMinvoice=1234,
UMinvioce=1234,

A: You should deactivate the test mode for the Source key. For sandbox login at https://sandbox.usaepay.com/console/, go to Settings -> Source Keys, then edit the necessary one, and uncheck the "Test Mode" option.
Sandbox is a test environment by itself, and it's recommended not to use the production environment in a test mode, which is actually deprecated.
help.usaepay.com/developer/testmode
help.usaepay.com/developer/guide/testaccount


text:
Q: How to get selected row data from datatable and send with JSON format? I have written a code to get data from dynamic table and and that through ajax. My code is working but I want to send only checked row data. Tried some code but getting error or empty array .
Code
$("#sbt").click(function () {
     var TableData;
    TableData = storeTblValues()

    function storeTblValues()
    {
        var TableData = new Array();
        $('#example tr').each(function(row, tr){
              TableData[row]={
              "title" : $(tr).find('td:eq(1)').text()
                , "categories" :$(tr).find('td:eq(2)').text()
                , "description" : $(tr).find('td:eq(5)').text()
                , "excerpt" : $(tr).find('td:eq(6)').text()
                , "FeaturedImage" : $(tr).find('td:eq(3)').text()
                            }

        });
        TableData.shift();  // first row will be empty - so remove
        return TableData;
    }

    var TableData;
    TableData = $.toJSON(storeTblValues());
    //alert(TableData);

     $.ajax({
        type: "POST",
        url: "post.php",
        data: "pTableData=" + TableData,
        success: function(msg){
            alert(msg);
            // return value stored in msg variable
        }
    });

    });

A: The AJAX call should be:
 $.ajax({
    type: "POST",
    url: "post.php",
    data: {pTableData: TableData},
    success: function(msg){
        alert(msg);
        // return value stored in msg variable
    }
});

Changed data: "pTableData=" + TableData to {pTableData: TableData}

A: Hi here is an example using dataTables with raw HTML data jsfiddle

$(document).ready(function() {
 $('#example').find('tbody').children('tr').append('<button>get data</button>	');// append a button
   let table = $('#example').DataTable(),
   keys = $('th', $('#example').children('thead').find('tr')).map(function(index, value) {
        return $(value).text();
    }),
    row = {};
  $('#example tbody').on( 'click', 'button', function () {
    var data = table.row( $(this).parents('tr') ).data();
  keys.each((i,v)=>{
      var string = `{"${v}":"${data[i]}"}`;
      Object.assign(row,JSON.parse(string));
    });
    console.log(row);
    if(confirm('want to submit this data?')){
    //make ajax call here
    $.ajax({
  url: '/echo/json/',
  type: 'POST',
  dataType: 'JSON',
  data: {row: row, json:JSON.stringify(row)}//json simulate the response just send the row data and get it in php like $data = json_decode($_POST["row"],true) this returns an associative array
  }).done((response)=>{
    console.log(response);
    }).always(()=>{
    row = {};
    })
    }else{
    row={};
    }
    } );

} );

<link href="https://cdn.datatables.net/1.10.19/css/jquery.dataTables.min.css" rel="stylesheet"/>

                Name
                Position
                Office
                Age
                Start date
                Salary
                Action

                Tiger Nixon
                System Architect
                Edinburgh
                61
                2011/04/25
                $320,800

                Garrett Winters
                Accountant
                Tokyo
                63
                2011/07/25
                $170,750

                Ashton Cox
                Junior Technical Author
                San Francisco
                66
                2009/01/12
                $86,000

                Cedric Kelly
                Senior Javascript Developer
                Edinburgh
                22
                2012/03/29
                $433,060

                Airi Satou
                Accountant
                Tokyo
                33
                2008/11/28
                $162,700

                Brielle Williamson
                Integration Specialist
                New York
                61
                2012/12/02
                $372,000

                Herrod Chandler
                Sales Assistant
                San Francisco
                59
                2012/08/06
                $137,500

                Rhona Davidson
                Integration Specialist
                Tokyo
                55
                2010/10/14
                $327,900

                Colleen Hurst
                Javascript Developer
                San Francisco
                39
                2009/09/15
                $205,500

                Sonya Frost
                Software Engineer
                Edinburgh
                23
                2008/12/13
                $103,600

                Jena Gaines
                Office Manager
                London
                30
                2008/12/19
                $90,560

                Quinn Flynn
                Support Lead
                Edinburgh
                22
                2013/03/03
                $342,000

                Charde Marshall
                Regional Director
                San Francisco
                36
                2008/10/16
                $470,600

                Haley Kennedy
                Senior Marketing Designer
                London
                43
                2012/12/18
                $313,500

                Tatyana Fitzpatrick
                Regional Director
                London
                19
                2010/03/17
                $385,750

                Michael Silva
                Marketing Designer
                London
                66
                2012/11/27
                $198,500

                Paul Byrd
                Chief Financial Officer (CFO)
                New York
                64
                2010/06/09
                $725,000

                Gloria Little
                Systems Administrator
                New York
                59
                2009/04/10
                $237,500

                Bradley Greer
                Software Engineer
                London
                41
                2012/10/13
                $132,000

                Dai Rios
                Personnel Lead
                Edinburgh
                35
                2012/09/26
                $217,500

                Jenette Caldwell
                Development Lead
                New York
                30
                2011/09/03
                $345,000

                Yuri Berry
                Chief Marketing Officer (CMO)
                New York
                40
                2009/06/25
                $675,000

                Caesar Vance
                Pre-Sales Support
                New York
                21
                2011/12/12
                $106,450

                Doris Wilder
                Sales Assistant
                Sidney
                23
                2010/09/20
                $85,600

                Angelica Ramos
                Chief Executive Officer (CEO)
                London
                47
                2009/10/09
                $1,200,000

                Gavin Joyce
                Developer
                Edinburgh
                42
                2010/12/22
                $92,575

                Jennifer Chang
                Regional Director
                Singapore
                28
                2010/11/14
                $357,650

                Brenden Wagner
                Software Engineer
                San Francisco
                28
                2011/06/07
                $206,850

                Fiona Green
                Chief Operating Officer (COO)
                San Francisco
                48
                2010/03/11
                $850,000

                Shou Itou
                Regional Marketing
                Tokyo
                20
                2011/08/14
                $163,000

                Michelle House
                Integration Specialist
                Sidney
                37
                2011/06/02
                $95,400

                Suki Burks
                Developer
                London
                53
                2009/10/22
                $114,500

                Prescott Bartlett
                Technical Author
                London
                27
                2011/05/07
                $145,000

                Gavin Cortez
                Team Leader
                San Francisco
                22
                2008/10/26
                $235,500

                Martena Mccray
                Post-Sales support
                Edinburgh
                46
                2011/03/09
                $324,050

                Unity Butler
                Marketing Designer
                San Francisco
                47
                2009/12/09
                $85,675

                Howard Hatfield
                Office Manager
                San Francisco
                51
                2008/12/16
                $164,500

                Hope Fuentes
                Secretary
                San Francisco
                41
                2010/02/12
                $109,850

                Vivian Harrell
                Financial Controller
                San Francisco
                62
                2009/02/14
                $452,500

                Timothy Mooney
                Office Manager
                London
                37
                2008/12/11
                $136,200

                Jackson Bradshaw
                Director
                New York
                65
                2008/09/26
                $645,750

                Olivia Liang
                Support Engineer
                Singapore
                64
                2011/02/03
                $234,500

                Bruno Nash
                Software Engineer
                London
                38
                2011/05/03
                $163,500

                Sakura Yamamoto
                Support Engineer
                Tokyo
                37
                2009/08/19
                $139,575

                Thor Walton
                Developer
                New York
                61
                2013/08/11
                $98,540

                Finn Camacho
                Support Engineer
                San Francisco
                47
                2009/07/07
                $87,500

                Serge Baldwin
                Data Coordinator
                Singapore
                64
                2012/04/09
                $138,575

                Zenaida Frank
                Software Engineer
                New York
                63
                2010/01/04
                $125,250

                Zorita Serrano
                Software Engineer
                San Francisco
                56
                2012/06/01
                $115,000

                Jennifer Acosta
                Junior Javascript Developer
                Edinburgh
                43
                2013/02/01
                $75,650

                Cara Stevens
                Sales Assistant
                New York
                46
                2011/12/06
                $145,600

                Hermione Butler
                Regional Director
                London
                47
                2011/03/21
                $356,250

                Lael Greer
                Systems Administrator
                London
                21
                2009/02/27
                $103,500

                Jonas Alexander
                Developer
                San Francisco
                30
                2010/07/14
                $86,500

                Shad Decker
                Regional Director
                Edinburgh
                51
                2008/11/13
                $183,000

                Michael Bruce
                Javascript Developer
                Singapore
                29
                2011/06/27
                $183,000

                Donna Snider
                Customer Support
                New York
                27
                2011/01/25
                $112,000

                Name
                Position
                Office
                Age
                Start date
                Salary

Hope it helps


text:
Q: Swift: Finding and plotting the hours in between two Dates I am trying to create a UI like the below.  I have a startDate and endDate (e.g. 1:55am and 11:35am).  How can I proportionally (using Geometry reader) find each hour in between two dates and plot them as is done here?  I am thinking at some point I need to use seconds or timeIntervalSince perhaps, but can't quite get my head around how best to go about it?

my code so far which gets the hours correctly, but I need to space them out proportionally according to their times:
What my code looks like:
struct AsleepTimeView: View {

    @EnvironmentObject var dataStore: DataStore

    static let sleepTimeFormat: DateFormatter = {
        let formatter = DateFormatter()
        formatter.dateStyle = .none
        formatter.timeStyle = .short
        return formatter
    }()

    var body: some View {
        Color.clear.overlay(
            GeometryReader { geometry in
                if let mostRecentSleepDay = dataStore.pastSevenSleepDays?.last, let firstSleepSpan = mostRecentSleepDay.sleepSpans.first, let lastSleepSpan = mostRecentSleepDay.sleepSpans.last {
                    VStack(alignment: .center) {
                        HStack {
                            Text("\(firstSleepSpan.startDate, formatter: Self.sleepTimeFormat) ")
                                .font(.footnote)
                            Spacer()
                            Text("\(lastSleepSpan.endDate, formatter: Self.sleepTimeFormat)")
                                .font(.footnote)
                        }
                        HStack(spacing: 3) {

                            ForEach(dataStore.sleepOrAwakeSpans) { sleepOrAwakeSpan in

                                RoundedRectangle(cornerRadius: 5)
                                    .frame(width: getWidthForRoundedRectangle(proxy: geometry, spacing: 3, seconds: sleepOrAwakeSpan.seconds, sleepOrAwakeSpans: athlyticDataStore.sleepOrAwakeSpans), height: 10)

                                    .foregroundColor(sleepOrAwakeSpan.asleep == false ? TrackerConstants.scaleLevel5Color : TrackerConstants.scaleLevel8Color)

                            }
                        }
                        HStack {
                            ForEach(getHoursBetweenTwoDates(startDate: firstSleepSpan.startDate, endDate: lastSleepSpan.endDate).map {  Calendar.current.component(.hour, from: $0) }, id: \.self) { hour in
                                HStack {
                                    Text("\(hour)")
                                        .font(.footnote)
                                    Spacer()
                                }
                            }
                        }
                        HStack {
                            HStack {
                                Circle()
                                    .foregroundColor(TrackerConstants.scaleLevel8Color)
                                    .frame(width: 10, height: 10)
                                Text("Asleep")
                                    .font(.footnote)
                            }
                            HStack {
                                Circle()
                                    .foregroundColor(TrackerConstants.scaleLevel5Color)
                                    .frame(width: 10, height: 10)
                                Text("Awake")
                                    .font(.footnote)
                            }
                            Spacer()
                        }
                    }
                }

            })     // end of overlay
    }

    //helper
    private func getWidthForRoundedRectangle(proxy: GeometryProxy, spacing: Int, seconds: TimeInterval, sleepOrAwakeSpans: [SleepOrAwakeSpan]) -> CGFloat {

        let totalSpace = (sleepOrAwakeSpans.count - 1) * spacing
        let totalSleepTime = sleepOrAwakeSpans.map { $0.endTime.timeIntervalSince($0.startTime) }.reduce(0, +)

        guard totalSleepTime > 0 else { return 0}

        let width =  (proxy.size.width - CGFloat(totalSpace)) * CGFloat(seconds / totalSleepTime)
        return width
    }

    func datesRange(from: Date, to: Date, component: Calendar.Component) -> [Date] {
        // in case of the "from" date is more than "to" date,
        // it should returns an empty array:
        if from > to { return [Date]() }

        var tempDate = from
        var array = [tempDate]

        while tempDate < to {
            tempDate = Calendar.current.date(byAdding: component, value: 1, to: tempDate)!
            array.append(tempDate)
        }

        return array
    }

    func getHoursBetweenTwoDates(startDate: Date, endDate: Date) -> [Date] {

        var finalArrayOfHours = [Date]()

        guard endDate > startDate else { return finalArrayOfHours }

        let arrayOfHours = datesRange(from: startDate, to: endDate, component: .hour)

        for date in arrayOfHours {
            let hour = date.nearestHour()
            finalArrayOfHours.append(hour)
        }

        return finalArrayOfHours

    }

}

extension Date {
    func nearestHour() -> Date {
        return Date(timeIntervalSinceReferenceDate:
                        (timeIntervalSinceReferenceDate / 3600.0).rounded(.toNearestOrEven) * 3600.0)
    }
}

A: There are a whole suite of methods in the Calendar class to help with what you're trying to do.
Off the top of my head, Id say you'd do something like the following:
In a loop, use date(byAdding:to:wrappingComponents:) to add an hour at a time to your startDate. If the result is ≤ endDate, use component(_:from:) to get the hour of the newly calculated date.


text:
Q: instagram api rails hidden token in heroku I want to upload my api to heroku, what I want is that the token is hidden for possible hakers.This code is in ruby on rails app / assets / application.js This is my code
   var token = "MYTOKEN",
      userid =  MYUSERID,
      num_photos = 4;

    $(document).ready(function() {

    $.ajax({
        url: 'https://api.instagram.com/v1/users/' + userid + '/media/recent/?access_token=' + token,
        dataType: 'jsonp',
        type: 'GET',
        data: {access_token: token, count: num_photos},
        success: function(data){
            console.log(data);
            for( x in data.data ){
                $("#container").append('

');
            }
        },
        error: function(data){
            console.log(data);
        }
    });
    });

A: Store the token in an environment variable which your rails app can then access and pass to the view. There are gems such as dotenv that can help you manage access to them locally. This article explains how to configure your variables in heroku.


text:
Q: Confused by Continuity Equation I thought I was aware of it. My question is about the derivative of time.
Sometimes it is the total derivative

and sometimes it is partial, we can ignore the $\phi$ here

Does mass change with time or position?

A: In these equations, $\rho$ is the density.  It should not be surprising that density can depend on time and position.
When we integrate over the entire system, we do get the mass.  Having integrated over the whole system, there is no possibility of position dependence.  However, there can easily be time dependence if mass is being added to or removed from the modeled system.  (Typical examples: chemical reactions produce gasses which escape the system, nuclear interactions convert mass to energy or vice versa, evaporation from a free boundary is being modeled, a bullet is fired into a semi-elastic medium, et al.)
When we integrate over a modeling cell, position dependence becomes possible.  For instance evaporation can occur from a cell meeting the free boundary, but not from an interior cell.

A: The total derivative is made of two pieces: the partial and the convective. You are following an individual particle in your fluid. It's density can change because of local compression/rarefaction or because of the particle moving to a different location. If you write the continuity eqn in integral terms the time derivative should be total since it only depends on time once you fix your control volume. When you localize the equation you obtain
$$
\frac{d\rho}{dt}+\rho {\rm div}v=0
$$
With total time derivative which equals
$$
\frac{\partial\rho}{dt}+v\cdot\nabla\rho
$$
When you replace the total time derivative by this expression you can put together the second and third terms which amounts to taking the density inside the divergence.