text:
Q: Entity Framework recursive Relations and Attaching errors I am creating an Application to manage Projects, Employees and assign Employees to Projects using WPF and EF 6.2.0.
So I've got an Employee entity with different properties (some of which are references to other entities), and I got a Project entity with different propeties (again, some of which are other entities).
This is my database scheme:

Now I want to create a Job entity which is assigned to an Employee and a Project.
So to add one, I have to attach the whole Employee and Project entities (including all their referenced entities) to my context before I can add the Job right?
If I don't do that or forget one of the entity's relations/properties, it's trying to create that whole entity on the database, and throws some error like the primary key for that employee already exists (obviously, because it shouldn't create it but rather attach the existing local one)
On the other side if I do try to attach it, it fails upon attaching the Project because (now comes the crazy part) the Project.CostCentre.Location.CostCentres[0].Projects[0].Contact (Employee) is already attached. It is trying to attach every single thing recursively including all Lists?!
That's the stack trace that causes this:
private void Attach(Job job, bool attachEntity = true)
{
    Attach(job.Employee);
    Attach(job.Project); // Calls next func
    if (attachEntity && !Attached(job))
        Context.Jobs.Attach(job);
}

private void Attach(Project project, bool attachEntity = true)
{
    Attach(project.Contact);
    Attach(project.CostCentre); // Calls next func
    Attach(project.CostType);
    Attach(project.Status);
    if (attachEntity && !Attached(project))
        Context.Projects.Attach(project);
}

private void Attach(CostCentre costCentre, bool attachEntity = true)
{
    Attach(costCentre.Location); // Calls next func
    if (attachEntity && !Attached(costCentre))
        Context.CostCentres.Attach(costCentre);
}

private void Attach(Location location, bool attachEntity = true)
{
    if (attachEntity && !Attached(location))
        Context.Locations.Attach(location); // The error (that code tries to attach location.CostCentres[0].Projects[0].Contact aswell, which is an already attached Employee!!)
}

The full error message:
System.InvalidOperationException: 'Attaching an entity of type 'ForecastLibrary.Employee' failed because another entity of the same type already has the same primary key value.
This can happen when using the 'Attach' method or setting the state of an entity to 'Unchanged' or 'Modified' if any entities in the graph have conflicting key values.
This may be because some entities are new and have not yet received database-generated key values.
In this case use the 'Add' method or the 'Added' entity state to track the graph and then set the state of non-new entities to 'Unchanged' or 'Modified' as appropriate.'

The full source code is here: https://pastebin.com/8YU0xQUC
I am already trying to solve this obscure error for some weeks, I hope someone here can help me out successfully adding this Job.
EDIT: Here's the code calling all of this:
// DataService::Add Function
public void Add(Job job)
{
    Attach(job, false);
    Context.Jobs.Add(job);
}

// UI Add job snippet
using (var service = new DataService(Session.ConnectionString))
{
    service.Add(JobToAdd);
    await service.SaveAsync();
}

A: I'd recommend using Eager loading if you know exactly what you need and have bigger data models.
Call Context.Configuration.LazyLoadingEnabled = false; in the constructor of you DataService and use .Include wherever you need a navigation property.
Then you need to use Find instead of Attach.
So your Job Add function could look this:
public void Add(Job job)
{
    var employee = Context.Employees.Find(job.Employee.Id);
    var project = Context.Projects.Find(job.Project.Id);
    Context.Jobs.Add(new Job { Employee = employee, Project = project, Time = job.Time });
}


text:
Q: java.lang.NoClassDefFoundError: wrong name? but how? So I was doing my assignment when I have to use my command prompt for this. I tried to look it up everywhere but I still don't understand how I get these error. Does anyone know what went wrong?
enter image description here
Microsoft Windows [Version 10.0.18363.1198]
(c) 2019 Microsoft Corporation. All rights reserved.

C:\Users\benny>cd C:\Users\benny\IdeaProjects\PA10\src\E22_7

C:\Users\benny\IdeaProjects\PA10\src\E22_7>javac WordCount.java

C:\Users\benny\IdeaProjects\PA10\src\E22_7>java WordCount file_one.txt file_two.txt
Error: Could not find or load main class WordCount
Caused by: java.lang.NoClassDefFoundError: E22_7/WordCount (wrong name: WordCount)

A: Sounds like you stuck package E22_7; at the top of that file.
In that case, go one directory up:
javac E22_7\WordCount.java
java E22_7.WordCount

redpajama_set_name: RedPajamaStackExchange


text:
Q: Trying to optimize my script Hey so i built a script that filters combo lists, it outputs only combos that not repeat itself more than 2 times but its super slow here is my script:
<?php
ini_set('max_execution_time', '-1');
ini_set('memory_limit', '-1');
$fileCombo = file("ww.txt", FILE_IGNORE_NEW_LINES);
$output = fopen("workpless.txt", "a") or die("Unable to open file!");

//all domains of the entire list
$domains = array();
//only domains that repeat themself less than 2 times
$less = array();

//takes the combo list explode it to domain names
foreach ($fileCombo as $combo) {
    $pieces = explode(":", $combo);
    $email = explode("@", $pieces[0]);
    //import domains to array
    $domains[] = strtolower($email[1]);
}
//count each string in the array
$ac = array_count_values($domains);
//this foreach just filter all the domains that not repeat themself over 2 times
foreach ($ac as $email => $item) {
    if($item <= 2) {
        $less[] = $email;
    }
}

/* this foreach is the one that makes all the trubles,
it takes all the domains that the last foreach filtered
and its runing it 1 by 1 on the entire combo list to get
the actual combo */

foreach ($less as $find) {
    $matches = array_filter($fileCombo, function($var) use ($find) { return preg_match("/\b$find\b/i", $var); });
    foreach ($matches as $match) {
        $data = $match . PHP_EOL;
        fwrite($output, $data);
    }
}

fclose($output);
?>

pseudocode(the best i can do):
file1:
exaple@example.com:password
exaple@example.com:password
exaple@example.com:password
exaple@example1.com:password
exaple@example2.com:password

array "fileCombo" load file1 into the array
splitting each line by ":" so you will get [0]example@example.com, [1]password
splitting value [0] by "@" so you will get [0]example, [1]example.com
putting value [1] into new array called "domains"
counting how many duplicates of each domain
putting all the domains that have less than 2 dupes inside new array that called "less"
runing 1 by 1 each domain in "less" array on "fileCombo" array
if "less" value was found inside "fileCombo" array value Than
write the entire line from "fileCombo" into a text file

This script used for big files with 2~5M lines evrey time thats why i need it to be optimized (its fast when u run like 20k lines on it).

A: The following should be the most "laconic" solution for your case.But you should test it on your big files(2~5M):
Let's say, file1.txt contains these lines:
exaple@example.com:password
exaple@example.com:password
exaple@example.com:password
exaple@example1.com:password
exaple@example2.com:password

$combos = file_get_contents("file1.txt");
preg_match_all("/\b\S+?@(\S+?):\S+?\b/m", $combos, $matches);
$less = array_filter(array_count_values($matches[1]), function ($v){
    return $v <= 2;
});
// $matches[0] - is an array of lines
// $matches[1] - is an array of domains in respective positions as lines
$matched_lines = "";
foreach (array_keys($less) as $domain) {
    $matched_lines .= $matches[0][array_search($domain, $matches[1])] . PHP_EOL;
}
if ($matched_lines) {
    file_put_contents("workpless.txt", $matched_lines, FILE_APPEND);
}
// Now "workpless.txt" contains the following lines:
example@example1.com:password
example@example2.com:password

A: UPDATED: To display all related lines for that domain at the cost of more 5 seconds for 1M lines file
Tested on 80,000 lines (40,000 unique lines) - 2.5 MB
Memory Usage

69,994,816 bytes
70,246,808 bytes (process)
71,827,456 bytes (process peak)

Execution Time
0.54409 seconds

Tested on 1,000,000 lines (500,000 unique lines) - 33 MB
Memory Usage

864,805,152 bytes
865,057,144 bytes (process)
866,648,064 bytes (process peak)

Execution Time
8.9173 seconds

My test Machine is i7-3612QM (CPU Mark 6833) 4GB RAM SSD
Sample from 80,000 lines file
exaple@example.com:password
exaple@example1.com:password
exaple@example1.com:password
exaple@example1.com:password
exaple@example2.com:password
exaple@example2.com:password
exaple@example3.com:password
exaple@example3.com:password

Here is your new version :))
<?php
// System Start Time
define('START_TIME', microtime(true));

// System Start Memory
define('START_MEMORY_USAGE', memory_get_usage());

function show_current_stats() {
?>
    Memory Usage

    <?php print number_format(memory_get_usage() - START_MEMORY_USAGE); ?> bytes
    <?php print number_format(memory_get_usage()); ?> bytes (process)
    <?php print number_format(memory_get_peak_usage(TRUE)); ?> bytes (process peak)

    Execution Time

<?php print round((microtime(true) - START_TIME), 5); ?> seconds

<?php
}

// Script start here

$fileCombo = file("ww.txt", FILE_IGNORE_NEW_LINES);
$output = fopen("workpless.txt", "a") or die("Unable to open file!");

//all domains of the entire list
$domains = array();
//only domains that repeat themself less than 2 times
$less = array();
//let make relateion between domains and its position(keys) in fileCombo
$domains_keys = array();

//takes the combo list explode it to domain names
foreach ($fileCombo as $key => $combo) {
    $pieces = explode(":", $combo);
    $email = explode("@", $pieces[0]);
    //import domains to array
    $domains[] = strtolower($email[1]);

    // check if domain exists or create new domain in $domains_keys array
    if (isset($domains_keys[strtolower($email[1])] )) {
        $domains_keys[strtolower($email[1])][] = $key;
    } else {
        $domains_keys[strtolower($email[1])] = array($key);
    }
}
//count each string in the array
$ac = array_count_values($domains);
//this foreach just filter all the domains that not repeat themself over 2 times
foreach ($ac as $email => $item) {
    if($item <= 2) {
        $less[] = $email;
    }
}

foreach ($less as $find) {
    array_map(function($domain_key) use ($fileCombo, $output) {
        $data = $fileCombo[$domain_key] . PHP_EOL;
        fwrite($output, $data);
    }, $domains_keys[$find]);
}

fclose($output);

// uncomment to show stats : Credit go to micromvc
/* show_current_stats(); */

output
exaple@example.com:password
exaple@example2.com:password
exaple@example2.com:password
exaple@example3.com:password
exaple@example3.com:password


text:
Q: D3 Slice array with from to values I have a dataset like below,
const data = [
    {frequency: 600, letter: 0, luminous: 234},
    {frequency: 2456, letter: 13, luminous: 4000},
    {frequency: 1200, letter: 2, luminous: 1402},
    {frequency: 1400, letter: 3, luminous: 1500},
    {frequency: 1234, letter: 4, luminous: 1800},
    {frequency: 768, letter: 5, luminous: 1900},
    {frequency: 3456, letter: 9, luminous: 2300},
    {frequency: 4567, letter: 10, luminous: 670},
    {frequency: 600, letter: 6, luminous: 2233},
    {frequency: 350, letter: 7, luminous: 1450},
    {frequency: 2340, letter: 8, luminous: 1470},
    {frequency: 4200, letter: 11, luminous: 5600},
    {frequency: 3000, letter: 12, luminous: 4500},
    {frequency: 1200, letter: 14, luminous: 4200},
    {frequency: 1100, letter: 15, luminous: 3000},
    {frequency: 1700, letter: 16, luminous: 4500},
];

and I need to slice this array data with from value and 2 value with d3
const maxLetter = d3.max(data, d => d.letter);
const width = 400;
const scaleX = scaleLinear()
    .domain([0, maxLetter])
    .range([0, width])
    .clamp(true)

is it possible to slice my data array with starting letter = 2 to endletter = 9 everything between this range as a new array? like below with d3?
const newData = [
    {frequency: 1200, letter: 2, luminous: 1402},
    {frequency: 1400, letter: 3, luminous: 1500},
    {frequency: 1234, letter: 4, luminous: 1800},
    {frequency: 768, letter: 5, luminous: 1900},
    {frequency: 600, letter: 6, luminous: 2233},
    {frequency: 350, letter: 7, luminous: 1450},
    {frequency: 2340, letter: 8, luminous: 1470},
    {frequency: 3456, letter: 9, luminous: 2300}
];

A: Why don't you do it with a simple loop?
Like this:
var newData = [];
for(var i = 0; i < data.length; i++){
  if(data[i].letter >= 2 && data[i].letter < 10){
    newData.push(data[i]);
  }
}

To get the newData array ordered by letter you could use a comparator:
newData.sort((a, b) => a.letter - b.letter)

A: To perform operations on data, Crossfilter is best solution.

*

*Feed data into crossfilter

*Create dimension based on the key [letter]

*Use filterRange to filter out the data

const data = [
    {frequency: 600, letter: 0, luminous: 234},
    {frequency: 2456, letter: 13, luminous: 4000},
    {frequency: 1200, letter: 2, luminous: 1402},
    {frequency: 1400, letter: 3, luminous: 1500},
    {frequency: 1234, letter: 4, luminous: 1800},
    {frequency: 768, letter: 5, luminous: 1900},
    {frequency: 3456, letter: 9, luminous: 2300},
    {frequency: 4567, letter: 10, luminous: 670},
    {frequency: 600, letter: 6, luminous: 2233},
    {frequency: 350, letter: 7, luminous: 1450},
    {frequency: 2340, letter: 8, luminous: 1470},
    {frequency: 4200, letter: 11, luminous: 5600},
    {frequency: 3000, letter: 12, luminous: 4500},
    {frequency: 1200, letter: 14, luminous: 4200},
    {frequency: 1100, letter: 15, luminous: 3000},
    {frequency: 1700, letter: 16, luminous: 4500},
];

const CFX = crossfilter(data);
const dimension = CFX.dimension(function (d){ return d.letter; });

console.dir(dimension.top(Infinity).length);
dimension.filterRange([2, 10]);

console.dir(dimension.top(Infinity));
console.dir(dimension.top(Infinity).length);
<script src="http://dc-js.github.io/dc.js/js/crossfilter.js"></script>


text:
Q: Can't start Docker Daemon and can't clean docker containers My docker daemon can't start. When running
dockerd

With the debug flag, it seems it gets stuck loading unused containers since this are the last lines before it hangs:
DEBU[2020-01-15T11:23:45.352998608-05:00] Loaded container fe8646a0750d267143d06a3138e2afa482b5744398191156705219eeda2dfd70, isRunning: false
DEBU[2020-01-15T11:23:45.360131801-05:00] Loaded container fee217b2865b6041f966d2c345e4ed948b8c1e250e491516be81cbb2a91832a7, isRunning: false
DEBU[2020-01-15T11:23:45.368410531-05:00] Loaded container feae3a8597d12f0d3aaf7a70cffa8b7eafbcc0be4b0f9e4f755ea55031d7d9ac, isRunning: false
DEBU[2020-01-15T11:23:45.369724660-05:00] Loaded container fed2cd064850fb9e6d2f38653ce020afc8d9257c290a08b5be56d60fad89b277, isRunning: false
DEBU[2020-01-15T11:23:45.370485780-05:00] Loaded container febafbee8bcaefca179676020e10f266eab49227eee5f4c30b8642d04d077aa7, isRunning: false
DEBU[2020-01-15T11:23:45.372800715-05:00] Loaded container fec9a082b345ffc810c99a1108ab1aa5d8245f2f4a6571d076c8b824216597e5, isRunning: false
DEBU[2020-01-15T11:23:45.373839942-05:00] Loaded container fedb695539c51e3e0446bb30bc6a9e4d44fd5e9b8a01d63ed5de79134886500b, isRunning: false
DEBU[2020-01-15T11:23:45.385171432-05:00] Loaded container fe8145beb93b01da59970bd95821263ed2864a17c17ae3be0843bb9aca272108, isRunning: false
DEBU[2020-01-15T11:23:45.396431763-05:00] Loaded container feacc8b3f9c58a40f076af43ab3a1b628f44938fd9b43c05efe3ff42042eba14, isRunning: false
DEBU[2020-01-15T11:23:45.414911377-05:00] Loaded container fea608d6ca184588ec14036db9f63da7fd9d04e91d423e26348ca036ce9d643d, isRunning: false

The SO (ubuntu) hangs, probably due to memory error.
I checked the containers folder and there are more than 30k containers, and I don't have any need to save containers, only images. My idea was to clean the docker containers using
docker container prune

But since the docker daemon can't start, that command cannot be ran.
Any insights on what I can do to find the problem or how to delete unused containers?
Maybe if I could find a safe way to backup my images without docker daemon, then I could restart everything.


text:
Q: How do I set the circle radius in a Forest tree drawing? I have following code to generate a tree using the forest package:
\documentclass{standalone}
\usepackage{forest}
\begin{document}
\begin{forest}
  for tree={circle,draw}
  [A
    [B
      [C
        [E]
        [F]]
      [D]]
    [G
      [H]
      [I
        [J]
        [K
          [L]
          [M]]]]]
\end{forest}
\end{document}

The resulting tree drawing looks like this:

You may notice that the circles surrounding each node differ slightly in size. This is most noticeable in the case of neighbouring nodes H and I, and L and M.
It could be argued that this is desirable behaviour as it ensures that the letter at each node is surrounded by the same amount of padding. However, I consider this to look bad and would like all circles to have the same radius.
I have tried various options to control the circle size, without success. How can I make all the circles have the same size? In addition, I think the circles are a bit too big as they are now, so I would like to reduce the padding inside the circle. It would be nice if I could set this in an option so that I could experiment with different values to see what looks best.

A: Since forest is based on tikz, you can use tikz shape's definition as
 minimum size, text width, font, etc in forest nodes style definitions in for tree={...}:
\documentclass[margin=5mm]{standalone}
\usepackage[utf8]{inputenc}
\usepackage[edges]{forest}

    \begin{document}
\begin{forest}
  for tree={circle, draw,
            minimum size=1.5em, % <-- added
            inner sep=1pt}      % <-- added
  [A
    [B
      [C
        [E]
        [F]]
      [D]]
    [G
      [H]
      [I
        [J]
        [K
          [L]
          [M]]]]]
\end{forest}
    \end{document}


text:
Q: HL7 performance testing with jmeter I'm new to JMeter and trying to send HL7 messages to test performance of application. Unfortunately i didn't find much information over the internet.
My first query is — is JMeter support HL7 messages to be send. If yes then do I need any plugin for it?
I am using TCP sampler for sending messages, is this a correct way?

A: Use this JMeter TCPClient plugin for TCP sampler for sending messages over MLLP to a HL7 interface engine.

*

*Clone plugin repo.

*Build using Maven - mvn install

*Copy compiled plugin jar file to <jmeter_home>/lib/

*Restrat JMeter

*Create new Thread Group

*Add a TCP Sampler to the Thread Group

*Specify nl.avisi.jmeter.mllpsampler.MllpTCPClient as the TCP client classname in the TCP Sampler.

*Enter a hostname and portnumber in the TCP Sampler, add a HL7 text message, set no delay

*Fire away!

Also, check this article to get more information about:
Performance testing of Health Care Applications

A: JMeter supports the protocols which are under the hood of its Samplers, some protocols are available via JMeter Plugins
Looking into Application Infrastructure:

JMeter supports all the mentioned protocols.

With regards to TCP - we don't know, i.e. it might be the case you need to mimic only TCP transport or you might have to consider all the mentioned above. Double check your NFRs and determine which protocol(s) is(are) in scope and once done you should be able to proceed with the coding. Remember one small requirement which applies to all load tests: a test conducted by the load test tool must represent the real-life application usage as close as possible. So if you have only TCP requests in scope - TCP Sampler might be a viable approach, however personally I would go for HAPI library using JSR223 Sampler or JUnit Request sampler - this way you will be able to perform parameterization/correlation much easier as you will be able to build messages / parse responses in cleaner way.


text:
Q: Drupal 7 - template override for node edit or node add I'm trying to create a template file for the node add or edit screens, I can override the normal node load by using node--contenttype.tpl.php but does anyone know how to go about doing it for edit or add? and this is for Drupal 7 not 6.
thanks

A: It really depends on what are you overriding the template for, but I'd suggest you either use page--node--edit.tpl.php - which will be called on every node editing page of your site (ie. is not content-type specific) - or add a condition in your node--contenttype.tpl.php using the arg() function:
if (arg(2) == 'edit') {

  // your overriding code here

}

You should also be aware that this will work only if you are using your custom theme in the node editing page, which is not the default behavior in the default drupal installation.


text:
Q: C# inheritance of fields This is probably a silly question, but here it goes.Imagine you have the following classes:
public class C
{
}

public class D : C
{
     //A subclass of C
}

public class A
{
    C argument;
}

Now, I want to have a class B, that inherits from A.This class would obviously inherit the "argument" field, but I wish to force the "argument" field in B to be of type D, rather than C.Since D inherits from C this shouldn't create any problems.
So, how would achieve this in c# ?

A: You could achieve something like so, where A is a generic type with its type parameter constrained to subclasses of C:-
public class C
{
}

public class D : C
{
}

public class A<T> where T:C
{
    public T Argument { get; set; }
}

public class B : A<D>
{
}

Bear in mind that you shouldn't expose public (or protected) fields, which is why I've changed them to properties.

A: This is not supported in C#.  You cannot change the type of an existing field, or property or method for that matter, by deriving from a given type.

A: As Jared points out, this is not possible. However, it is interesting to consider why not.
Suppose the field is private. Then it cannot be accessed in derived class B.  (Assuming B is not a nested type of A.)
Suppose the field is not private. Doesn't matter whether it is public, internal, protected or protected internal. Suppose its public and this were legal. Now you have the following situation.
class B : A
{
    override public D argument; // "overrides" A.argument
}

class E : C {  }

class F
{
    public static void M(A a)
    { a.argument = new E(); }
}

...
F.M(new B());

And hey, you just crashed the runtime. You just wrote an object of type E into a field that can only store type D. (We could make similar crashing scenarios for other configurations, like protected fields, and so on.)
Now, you might say, well, instead let me make a read-only property. That I can virtualize:
class A
{
    public virtual C Argument { get; }
}
class B : A
{
    public override D Argument { ... }
}

Now the problems go away. The public interface isn't writable, so there's no problem with someone writing something in there that is not supported. And the property is virtual, so there's a mechanism for overriding it.
That feature is called "return type covariance", and it is not supported in C# either. See Why the concept of "Covariance" and "Contravariance" are applicable while implementing the methods of an interface?.
Please explain what you are really trying to do, not how you're trying to do it. There is probably a better way.

A: To make it typesafe, you'll have to do something with generics. Otherwise just do a cast.
But in general, having non-private fields is not a good solution because it breaks the information hiding principe. You should therefore avoid this if possible and use properties and/or methods instead.

A: Unless I'm completely missing the boat, I think you're asking for something like this
class A
{
    public virtual C Argument { get; set; }
}

class B : A
{
    D argument = null;
    public override C Argument
    {
        get
        {
            return argument;
        }
        set
        {
            if (value is D)
            {
                argument = (D)value;
            }
            else
            {
                throw new Exception();
            }
        }
    }
}

class C
{
}

class D : C
{
}

...
static void Main()
{
    B b = new B();
    D arg = new D();
    b.Argument = arg;
}

A: this is a bit of a straightforward question.  It is generally bad practise to hide a base class argument with one of the same name in a derived class.
public class B : A
{
    D argument;
}
you could also do this ...
public class B : A
{
  public B()
  {
    argument = new D();
  }
}

A: The argument property/method in B can return a D since D inherits from C, but, as JaredPar wrote, it has to be typed as C.

A: What you're looking for is a language feature called "return type covariance", which C# doesn't support.
You have another option here: you can "shadow" the field instead of inheriting it. However, this is very dangerous and almost universally a bad idea, because anything assigned to an object as B.argument will not be available if it is upcast and referenced as A.argument.
If you're on C# 4.0, you can get some aspects of what you're attempting by using a generic covariant interface:
public class C
{
    public int foo;
}

public class D : C
{
}

public class A : ITest<C>
{
    public C foo { get; private set; }
}

public class B : ITest<D>
{
    public D foo { get; private set; }
}

public interface ITest<out T> where T : C
{
    T foo { get; }
}

static class Program
{
    public static void Covariance(ITest<C> test)
    {

    }

    static void Main()
    {
        A myCVar = new A();
        B myDVar = new B();
        Covariance(myDVar);
    }
}

Note that the Covariance function will accept a B (which is an ITest<D>, not an ITest<C>), because the ITest interface has marked the T parameter with the keyword out. This tells the compiler that this type parameter will only be used in output operations, so it is safe to substitute any derived class of T when using this interface.


text:
Q: Change position field from numeric to alphanumeric. Where to find $category->setPostedProducts? Each Product has a different position in each category. The position only accept numeric and will change it to alphanumeric. So I set the position from catalog_category_product and _index in the database to "varchar".
But it still wont work. So I think, that there is another validation in the php Code.
I found the Code in:
app/code/core/Mage/Adminhtml/controllers/Catalog/CategoryController.php:
Line 320:

    $category->setPostedProducts($products);

But i cant find the declaration of the Method "setPostedProducts" anywhere. I searched all files.
And where is the MySQL "Update product..." Statement, so that I can check the value before it will be send to the DB?
Can someone tell me where can find it? Or I can solve this problem?
The Second thing is, how can i display the Position to the Frontend (.phtml)
I Want to show it in Product Listing and View.
Thanks
Greetings

A: Ok I got it.
In Mage/Catalog/Model/Resource/Category.php Line 342 and 357
Change (int) to (string)

And
app/code/core/Mage/Adminhtml/Block/Catalog/Category/Tab/Product.php
Delete Line 137:

To show it in frontend:
$_product->getcat_index_position();


text:
Q: An exercise from Revuz, Yor; equality in distribution of 2 integrals. Here is the exercise I have been struggling to solve. It is taken from this book by Revuz and Yor: link. Here is the full text of the problem ( Exercise 3.32, chapter 4).
Exercise (3.32). Let $B$ and $C$ be two independent Brownian Motions started at $0$. Prove that
$$
\int _0 ^1 (B_t + C_{1-t})^2 dt \,{\buildrel (d) \over =}\,
\int _0 ^1 (B_t ^2 + (B_1 - B_t)^2) dt
$$
[Hint: The Laplace transform in $(\frac{\lambda ^2 }{2})$ of the right-hand side is the characteristic function in $\lambda$ of the sum of two stochastic integrals; see Exercise (2.19)]
I have been trying to apply formula
$E \exp(\lambda M_t) = E \exp (\frac{\lambda ^2}{2} \langle M , M \rangle _t)$ for a continiouos martingale $M$, but I wasn't able to come up with a good idea what should be $M$. For example, we may write
$$
 E \exp\left(\frac{\lambda ^2 }{2} \int _0 ^1 B_t ^2  dt\right) =
E \exp\left(\frac{\lambda ^2 }{2} \int _0 ^1 (B_1-B_t) ^2  dt\right)=
  E \exp\left(\lambda \int _0 ^1 B_t dB_t\right)
$$
but it did not help me.
Addition
Here are some
computations. Set $W_t = C_1 - C _{1-t}$. $W$ is a BM independent on $B$, and
$$
 E \exp\left(\frac{\lambda ^2 }{2} \int _0 ^1 (B_t + C_{1-t}) ^2  dt\right) =
  E \exp\left(\lambda \int _0 ^1( B_t + C_{1-t} )dB_t\right)
$$
$$
=E \exp\left(\lambda \int _0 ^1( B_t + W_1 - W_t )dB_t\right)
=E \exp\left(\lambda \int _0 ^1 B_t dB_t+ \lambda B_1 W_1
- \lambda \int _0 ^1 W_t dB_t\right) :=F
$$
Because $W$ and $B$ are independent, we have
$B_1W_1 = \int _0 ^1 W_t dB_t +\int _0 ^1 B_t dW_t$, so
$$
F = E \exp\left(\lambda \int _0 ^1 B_t dB_t
+ \lambda \int _0 ^1 B_t dW_t\right) =
$$
$$
= E \exp\left(\lambda \int _0 ^1 B_t d(B_t + W_t)\right) =
E \exp\left(\frac{\lambda ^2 }{2}2\int _0 ^1 B_t ^2 dt\right),
$$
the last equality due to relation $\langle B+M,B+M \rangle_t = 2t$. So, it should be
$$
\int _0 ^1 (B_t + C_{1-t})^2 dt \,{\buildrel (d) \over =}\,
2\int _0 ^1 B_t ^2  dt.
$$
May it be true?


text:
Q: Hot Reload with Dockerized Node-Typescript application I'm dockerizing an api container and want it to be able to hot reload whenever I make change in code. I created a volume to handle it but nothing happen.
Here's my docker-compose.yml file:
version: "3.8"
services:
  api:
    image: xinxo-api:latest
    build: ./api
    ports:
      - "5005:5005"
    networks:
      - xinxo-network
    volumes:
      - apibuild:/app/api/build
    depends_on:
      - db
      - redis
    env_file:
      - ./api/.env
    restart: always
networks:
  xinxo-network:
    driver: bridge
volumes:
  pgdata:
  cache:
  staticbuild:
  apibuild:

Here's my Dockerfile
FROM node:16-bullseye-slim

WORKDIR /app/api/build

COPY package*.json ./
COPY yarn.lock ./
COPY tsconfig.json ./
COPY ./prisma prisma

RUN yarn
RUN yarn prisma generate

COPY . .

EXPOSE 5005
CMD ["yarn", "start"]

I only have a screen shot of my package.json file.

A: I have fixed this issue already by changing 2 places:

*

*docker-compose:
volumes:

*

*apibuild:/app/api/build -> ./api:/app/api/build

*My start script in package.json

"start": "ts-node-dev --poll --respawn --transpile-only --exit-child    --no-notify --ignore-watch node_modules -r tsconfig-paths/register src/app.ts"


text:
Q: Error in get post by met_key I have this code,
    $type = get_the_ID();
    $paged = (get_query_var('paged')) ? get_query_var('paged') : 1;
    $units3 = new wp_query( array(  'post_type' => 'units' ,
                                    'posts_per_page'=> 6 ,
                                    'paged' => $paged  ,
                                    'meta_key' => 'unittype',
                                    'meta_value' => $type ) );
    while ($units3->have_posts()) : $units3->the_post();

Its must get me all post from unit That is in the unit type that id = $type
But the query is get me all post.
It must get me only all post from unit post type that in unit type post type,
Where is error

A: I don't really understand this sentence-- "It must get me only all post from unit post type that in unit type post type,"-- and honestly the query looks correct to me, but I would suggest trying a meta_query and specifying the type, as well as disabling sticky post juggling. If you have 6 or more sticky posts you could have the illusion of the query returning "all" posts.
$units3 = new wp_query(
  array(
    'post_type' => 'units',
    'posts_per_page'=> 6,
    'paged' => $paged,
    'ignore_sticky_posts' => true,
    'meta_query' => array(
      array(
        'key' => 'unittype',
        'value' => $type,
        'type' => 'numeric'
      )
    )
  )
);


text:
Q: Similar strings not being compared I am new to nodejs and mongodb please help!
I am fetching two values from a sample login page and based on the email id, I am searching through the collection to check if the password matches
This is the js file making the call for validating
exports.profile = function(req, res) {

var email=req.body.email;
var password=req.body.password;
var validUser=validate.isValidUser(email,password);

console.log(validUser);
res.sendfile(path.join(__dirname, '../public', 'profile.html'));};

This is my js file to check if the password matches
exports.isValidUser = function(emailEntered, passEntered) {

var pass;
mongoose.connect('mongodb://localhost/registration');
User.findOne({
    email : emailEntered
}, function(err, doc) {
    if (err) {
        console.log(err);
    } else {

        pass = doc.password;
        console.log(pass);
        console.log(passEntered);

        mongoose.connection.close();
    }

    console.log('Disconnected from server successfully');
});

if (passEntered===pass) {
    return true;
}

else {
    return false;
}};

Every time I run it even if the password matches, it is returning false.


text:
Q: Trying to sort a linked list There are many implementations available on the net, but I wanted to do it on my own.
Can anyone tell what mistakes I am making?
When I created the linked list, I gave input as 3,12,5,2. So after sorting it should have been 2,3,5,12, but it gave me output as 3,5,2,12.
#include <stdio.h>
#include <stdlib.h>

struct node
{
    int data;
    struct node *next;
};
struct node *start=NULL;

void sort()
{
    struct node *preptr, *ptr, *temp;
    temp = (struct node *)malloc(sizeof(struct node));
    ptr=start;
    while(ptr->next != NULL)
    {
        preptr=ptr;
        ptr=ptr->next;
        if (preptr->data > ptr->data )
        {
            temp->data=ptr->data;
            ptr->data=preptr->data;
            preptr->data=temp->data;
            ptr=start;
        }
    }
}

A: You appear to have attempted to implement Bubble Sort, but that requires multiple passes through the data in the general, and you perform only one.  On that one pass, with input 3, 12, 5, 2, your code

*

*compares 3 with 12, and makes no change;

*compares 12 with 5, and swaps them;

*compares 12 with 2, and swaps them.

Then it stops, leaving 3, 5, 2, 12 as the final result.
A Bubble Sort on an n-element list must make n - 1 passes through the list in the general case, and your particular input happens to require that maximum number of passes.  One way to fix it would be to just run your existing code for one sorting pass inside a for loop that runs n - 1 times, but of course you then need to compute n first.  A better way (without changing to an altogether better algorithm) would be to run an indeterminate number of passes, via an outer loop, keeping track of whether any swaps are performed during the pass.  You're then done when you complete a pass without making any swaps.
Additional notes:

*

*You don't need a struct node just to swap the int data of two nodes.

*If want a struct node for a local temporary, you don't need to allocate it dynamically.  Just declare it:
 struct node temp_node;

*If you want a struct node * for a local temporary, you (probably) do not need to allocate any memory for it to point to.

*If you want a struct node for a local temporary and a pointer to it, you still don't need to allocate anything dynamically.  Just declare the struct and take its address:
 struct node temp_node;
 struct node *temp = &temp_node;

The main reasons to allocate dynamically are that you don't know in advance how much memory you will need, or that the allocated object needs to outlive the execution of the function in which it is created.

*Sorting a linked list is usually accomplished by rearranging the nodes by changing their links, not by swapping the node payloads, as your function does.  It's not necessarily wrong to swap the payloads, but that does not take any advantage of the linked list structure.

A: As you wrote in comments that you actually need to move the nodes, not the values, you will need to reassign the next pointers.
For the same reason, it must be possible for start to reference a different node. Therefore I would suggest that sort takes start as an argument and returns the new value it.
For implementing bubble sort, you need an extra outer loop, which restarts the iteration over the list. This should be repeated at most n times, where n is the number of nodes in your list. You could also just check whether a swap was necessary and in that case decide to do another scan through your list... until no more swaps occur.
I have here implemented that second idea:
#include <stdio.h>
#include <stdlib.h>

struct node {
    int data;
    struct node *next;
};

// A function to create a new node.
// This allows for easy initialisation of a linked list
struct node *newNode(int data, struct node *next) {
    struct node *temp = (struct node *)malloc(sizeof(struct node));
    temp->data = data;
    temp->next = next;
    return temp;
}

// Useful to see what is in the list...
void printList(struct node *cur) {
    while (cur != NULL) {
        printf("%i ", cur->data);
        cur = cur->next;
    }
    printf("\n");
}

// Let the sort function
struct node * sort(struct node *start) {
    struct node *prev, *cur, *next;
    // flag indicating we are not sure yet that
    //    the list is sorted
    int mutation = 1;
    // extra dummy node that precedes the start node
    struct node sentinel;
    sentinel.next = start;

    while (mutation) {
        mutation = 0;
        prev = &sentinel;
        cur = sentinel.next;
        next = start->next;
        while (next != NULL) {
            if (cur->data > next->data ) {
                // swap cur and next
                prev->next = next;
                cur->next = next->next;
                next->next = cur;
                // flag that we need more iterations
                mutation = 1;
                // prepare for next iteration
                prev = next;
            } else {
                prev = cur;
                cur = next;
            }
            next = cur->next;
        }
    }
    return sentinel.next;
}

// demo:
int main(void) {
  // Create list that was given as example
  struct node *start = newNode(3, newNode(12, newNode(5, newNode(2, NULL))));

  printf("Input:\n");
  printList(start);
  start = sort(start);
  printf("Sorted:\n");
  printList(start);
  return 0;
}


text:
Q: Minimal normal subgroups of Product of simple groups Known Result:
Let
$$G= S_1 \times S_2 \times\dots\times S_n,$$
where each $S_i$ are non-abelian simple groups. Then $S_i$'s are the minimal normal subgroup of $G$. (Even $S_i$'s are the only minimal normal subgroups of of $G$.)
My claim is that this is true even when some $S_i$'s are abelian. More formally:
Consider
$$H= T_1 \times T_2 \times\dots \times T_m,$$
where each $T_i$'s are simple groups (abelian or non abelian).
Claim 1: Each $T_i$'s are minimal normal subgroups of $H$ (I mean the subgroups of $H$ isomorphic to $T_i$ is minimal normal in $H$).
Proof: Let $K\leq H$ such that $K \cong T_i$. $K$ is normal in $H$ by def of direct product.
If $K$ is not minimal normal in $H$, then there is $N < K$ such that $N \trianglelefteq H$. Thus there is $T' \leq T_i$ such that $T' \cong N$ and $T' \trianglelefteq H$. Which contradict the fact that $T_i$ is simple.
Thus $K$ is minimal normal in $H.$ And hence the claim follows.
EDIT:
Question 1: Does the Claim 1 is correct?
Question2: If yes, are $T_i$'s only minimal normal subgroups of $H$.

A: You are being careless with equalities and isomorphisms.
Let $G=S_1\times\cdots \times S_n$ where each $S_i$ is simple. Let $\iota_k\colon S_k\hookrightarrow G$ be the canonical embeddings, sending $g\in S_k$ to the tuple $(e,\ldots,g,\ldots, e)$ that has $g$ in the $k$th coordinate.
Your "Claim 1" should be:

Claim 1: For each $k$, $\iota_k(S_k)$ is a minimal normal subgroup of $G$.

This is true because each $\iota_k(S_k)$ is normal, and any normal subgroup of $G$ contained in $\iota_k(S_k)$ corresponds to a normal subgroup of $\iota_k(S_k)\cong S_k$, hence is trivial or all of $S_k$.

Claim 2: If each $S_k$ is nonabelian, then the only normal subgroups of $G$ are of the form $\iota_{i_1}(S_{i_1})\cdots\iota_{i_r}(S_{i_r})$ for some $1\leq i_1\lt\cdots\lt i_r\leq n$, $0\leq r\leq n$.

These are all normal, being products of normal subgroups. Now assume that $N\triangleleft G$. Then $\pi_j(N)\triangleleft S_j$, hence the projection is either trivial or all of $S_j$. Thus, we may assume that $N$ is a subdirect product $G=S_1\times\cdots\times S_n$, and we aim to show that it is then equal to $G$.
I claim that $\iota_1(S_1)\subseteq N$. Indeed, let $x,y\in S_1$. Because $N$ is a subdirect product, there exists an element in $N$ with first component equal to $x$, say $(x,s_2,\ldots,s_n)\in N$. Conjugating with $\iota_1(y)=(y,e,e,\ldots,e)$, we have that $(yxy^{-1},s_2,\ldots,s_n)\in N$. Now multiplying by $(x,s_2,\ldots,s_n)^{-1}\in N$ on the right we obtain
$$(yxy^{-1}x^{-1},e,\ldots,e)= ([y,x],e,\ldots,e)\in N.$$
Thus, $\iota_1([S_1,S_1])\subseteq N$. But because $S_1$ is nonabelian, $S_1=[S_1,S_1]$; thus, $\iota_1(S_1)\subseteq N$.
Similarly, $\iota_k(S_k)\subseteq N$ for each $k$; thus, a generating set for $G$ is contained in $N$, so $N=G$, as desired.

Corollary. If all $S_k$ are nonabelian and simple, then the minimal normal subgroups of $S_1\times\cdots \times S_n$ are precisely the subgroups $\iota_k(S_k)$, for $k=1,\ldots,n$.

Claim 2 is false if you have two isomorphic abelian factors, as then you have "diagonal" subgroups, like $\langle (x,x)\rangle\leq C_2\times C_2$.
As stated your Claim 1 is false, because you may have subgroups isomorphic to some of the $S_i$ which are not normal. For example, if there is any $S_k$ that is isomorphic to (a subgroup of) $S_j$ for some $k\neq j$ via a morphism $\phi$, then the subgroup generated by the elements $\iota_k(x)\iota_j(\phi(x))$ is a subgroup that is isomorphic to $S_k$, but will not be normal in $G$.

Let's look a bit more carefully at what happens when you have abelian factors. Suppose that
$$G=S_1\times\cdots\times S_n\times A_{n+1}\times\cdots\times A_{n+m}$$
where the $S_i$ are simple and nonabelian, and $A_{n+1},\ldots,A_n$ are simple abelian (hence cyclic of prime order).
Lemma. If $N\triangleleft G$ and there exists $k$, $1\leq k\leq n$ such that $\pi_k(N)\neq\{e\}$, then $\iota_k(S_k)\leq N$.
Proof. The argument is similar to the one for Claim 2 above: given $x,y\in S_k$, we have an element $n\in N$ with $\pi_k(n)=x$. Then $\iota(y)n\iota(y)^{-1}n^{-1}$ has $k$th entry equal to $[y,x]$, and all other entries trivial, so $\iota_k([S_k,S_k])\leq N$; but this equals $\iota_k(S_k)$ because $S_k$ is simple and nonabelian. $\Box$
Corollary. If $N\triangleleft G$, and $(s_1,\ldots,s_n,a_1,\ldots,a_m)\in N$, then  $(s_1,\ldots,s_n,e,\ldots,e)\in N$ and $(e,\ldots,e,a_1,\ldots,a_m)\in N$.
Proof. If any $s_j\neq e$, then  $N$ contains $\iota_j(S_j)$, Thus, it contains $(s_1,\ldots,s_n,e,\ldots,e)$. $\Box$
Corollary. If $N\triangleleft G$, then $N=M\times B$, where $M\triangleleft S_1\times\cdots\times S_n$, and $B\triangleleft A_{n+1}\times\cdots\times A_{n+m}$.
Now, we already know what the normal subgroups of $S_1\times \cdots\times S_n$ are, so we know what $M$ looks like.
For $B$, we have a finite abelian group, which is isomorphic to $E_{p_1,k_1}\times\cdots\times E_{p_r,k_r}$, where $p_1,\ldots,p_r$ are pairwise distinct primes, $k_i\geq 1$, and $E_{p_i,k_i}$ is an elementary abelian $p_i$-group of rank $k_i$; that is, $E_{p_i,k_i}\cong (C_{p_i})^{k_i}$. We know that $B$ is the product of its $p_i$ parts, so we are left with considering the subgroups of $E_{p_i,k_i}$. From linear algebra we know they just elementary abelian, isomorphic to $(C_{p_i})^{t_i}$ with $0\leq t_i\leq k_i$.
In particular, any minimal normal subgroup will be isomorphic to $C_{p_i}$, hence to one of the factors.
So we have:

Theorem. Let $G= S_1\times\cdots \times S_n$, where each $S_i$ is a finite simple group. Then the minimal normal subgroups of $G$ are precisely the subgroups $\iota_k(S_k)$ if and only if for each prime $p$ there is at most one $S_i$ that is cyclic of order $p$. If there are other minimal normal subgroups of $G$, then they are isomorphic to a cyclic group of order $p$, and so are at least two of the $S_k$.


text:
Q: Confused by Django's ImageField width and height I have added the image width and height fields to an ImageField-based model:
class Photo(models.Model):
    height = models.IntegerField()
    width = models.IntegerField()
    image = models.ImageField(
        upload_to=settings.PHOTO_UPLOAD_TO,
        height_field='height',
        width_field='width'
    )

When I do manage.py makemigrations, I am asked for the default value for existing rows. I already have many photos in the database (it's a running site), therefore I chose to add default=0 to width and height.
    height = models.IntegerField(default=0)
    width = models.IntegerField(default=0)

Now for all existing photos the two columns are populated with zeros, as expected. What I didn't expect however was that Photo.objects.all()[0].width and .height now return the correct non-zero values. Why? I couldn't find anything about such behaviour in documentation.

A: It seems the magic is being performed in Django's ImageField.update_dimension_fields method. The comments in the code say:

Update field's width and height fields, if defined.
This method is hooked up to model's post_init signal to update
          dimensions after instantiating a model instance.  However, dimensions
          won't be updated if the dimensions fields are already populated.  This
          avoids unnecessary recalculation when loading an object from the
          database.
Dimensions can be forced to update with force=True, which is how
          ImageFileDescriptor.__set__ calls this method.

So when instantiating the model, update_dimension_fields reads the dimensions from the image file and stores those on the instance. This will incur a little hit in a live environment.
Saving all images will store the dimensions in the database:
In [1]: for p in Photo.objects.all():
   ...:     p.save()

A: The documentation says https://docs.djangoproject.com/en/1.10/ref/models/fields/#django.db.models.ImageField.height_field

ImageField.height_field:
Name of a model field which will be
auto-populated with the height of the image each time the model
instance is saved.

model save() must have auto-populated both the height and width


text:
Q: What happens to the output of a process that has been disowned and lost its terminal? If I close the virtual terminal, where some process was started, does the output just go straight to /dev/null, or can it pollute memory somehow?
Can I anyhow grab the output to continue reading it at any point after that?
[EDIT]: So, is the moment of disowning a process effectively an end of my power to control its output?
I also noticed, that if I disown a stopped process, at first everything seems normal: it is neither terminated nor shown in jobs. But if I log out (and I don't mean close the terminal, just exit from su, for instance), the process is terminated. All the same, a background-running disowned process can stay running.

A: Just to address this specific question:

If I close the virtual terminal, where some process was started, does the output just go straight to /dev/null, or can it pollute memory somehow?

The terminal and the program(s) connected to it communicate via a tty device by reading and writing it like a file. Specifically, a virtual terminal creates a "pseudo-tty" ("pty" for short) and then spawns a shell (or other) process and connects the stdin/out/err of that process to the pty. (The details vary by operating system.)
When you close the virtual terminal, the virtual terminal closes its end of the connection (the pty "master"). After that, if the program at the other end of the connection writes to the tty, an error is returned and the data doesn't go anywhere. Similarly, if it reads from the tty it will get back an EOF (end of file) indicator.

A: To answer the most interesting part of your question: to change the output of a live running program, you have to edit its file descriptors. That is quite easy to do with gdb. It's a hack, but works.
See:
https://stackoverflow.com/questions/593724/redirect-stderr-stdout-of-a-process-after-its-been-started-using-command-line
A helper script is available at http://users.linpro.no/ingvar/fdswap.sh.txt.

A: The fact that a process is "disowned" has only a meaning for the interactive shell that created this process. It means that the shell doesn't include (anymore) the process in its jobs table, and that SIGHUP will not be sent to this process when the shell exits. It is not really related with your questions.
About what happens to the outputs that are sent to a deleted virtual terminal: I made some tests myself, and I noticed that /dev/pts/x devices are not accessible, and won't be allocated again until all filedescriptors that point to them have been closed. So, I can't see a reason why writes to a deleted terminal would be stored. I guess this is not even defined by POSIX.
About grabbing the output of some process that writes to a terminal, I don't think it is possible, even when the terminal is still alive¹. All you can do is grabbing the direct input to the terminal (i.e. keystrokes, or simulated keystrokes by the master part of a pty). If processes would read on stdin what is written to their terminals, that would lead to a self io loop for most process.
About the last remark on process termination, I don't really know what is happening, but I would suspect rather strange behaviors with signals (SIGTTOU, SIGTTIN, SIGHUP, or others) related to foreground/background state of process groups, when the session leader exits (e.g. su, in the case you mentioned).
Answer to the Edit: No, with respect to output, nothing changes when a process is disowned: it is still attached to its controlling terminal (unless it detached itself already like daemons do). You can see that using ps. However, you will not be able to use fg/bg/jobs commands provided by the shell anymore for this process. That means it might be difficult to feed it with input from the terminal (requires to be in the foreground process group).
—
1. unless the process is willing to, or hijacked with some debugging tools (see comments above).

A: Thanks to comment by Gilles, pointing me to this question, I learned about a program called retty.
It seems to use some dirty hack to reattach to a (pseudo-)tty effectively allowing to continue reading the output of a process - no matter whether it has been disowned or not. So this seems to answer most of the first part of my question. The second was answered by Stéphane.


text:
Q: Windows App Store - use of "results" view for my own search I have implemented a search mechanism in my app. The user fill a textbox and then click on a button. is there a way to use the nice results view of Microsoft? i'm talking about the view you can see in the image attached.

A: I am giving you few resources, please check it out and let us know if you face any problem.
Guidelines and checklist for search (Windows Store apps)
Quickstart: Adding search to an app
Windows 8 and the future of XAML: Part 4: Contracts in WinRT/Windows 8
Search contract sample from MSDN

A: That's just a page and layout that someone created for that given app... given the Contoso branding it's some sample, though I don't immediately recognize it.  I assume you saw the image, but don't have the source to it?
In Visual Studio, within an existing app you can use the Add>New Item dialog and select Search Contract to include a template page (with grid, filter combo box, etc.) to get you jumpstarted.
In the Windows 8 Camp Training kit, there is a fairly polished sample - Contoso Cookbook - that also includes a filtered search page, so that may be helpful as a start too.


text:
Q: How can I refer to the calling element in JQuery? For example:
<input type="text" size="5" id="question'+$qid+'"onKeyUp="checkanswer('+i+')"/></div>

I want to refer to the "question'+$qid+'" element inside the function checkanswer(), how to do it?
Maybe I can do it by onKeyUp="checkanswer('+$qid+')", is there other elegant way to do it?

A: Not sure I fully understand what you're asking for, but if you're trying to pass the current item to checkanswer() you can just do:
<input type="text" size="5" id="question'+$qid+'"onKeyUp="checkanswer(this)"/>

A: Assuming $qid and 'i' are the same number you could do $('#question' + param) in your checkanswer() function (where 'param' is the parameter that 'i' represents).


text:
Q: How to retain Gregorian date format of date input if region OS is Thai I have a date string pulled from Excel which I'm trying to parse. Said date is originally in Gregorian format. Is there any way to retain this even after using TryParse/TryParseExact?
Note: Since our end-users are from Thailand, I'm doing this while my machine's region is set to Thai. Hence, my system date as of this post is "12/7/2561".
Suppose I have the following string input in Gregorian M/d/yyyy format:
string validDate = "7/15/2018"

When I initially tried parsing this using DateTime.TryParseExact, it gave me 15/7/2561.
I've tried the following methods listed in these links, particularly the CreateSpecificCulture:

*

*MSDN: Convert Thailand DateTime TO English DateTime

*ASP.NET forums: DateTime issue while converting from thai culture to english culture
Here's my code right now:
public DateTime? ConvertThaiToGregorian(string text, string dateFormat)
{
    /// Note: Thailand uses the Thai Buddhist calendar, which is 543 years ahead of
    ///       the Gregorian calendar.
    /// dateFormat here is "M/d/yyyy".

    DateTime convertedDate;

    // Create Thai CultureInfo
    IFormatProvider thCulture = CultureInfo.CreateSpecificCulture("th-TH");

    // Parse date = returns "15/7/2018"...
    DateTime.TryParseExact(text, dateFormat, thCulture, DateTimeStyles.None, out convertedDate);

    // Create en-US CultureInfo
    IFormatProvider engCulture = CultureInfo.CreateSpecificCulture("en-US");

    // Parse date back to US format = gives me "01/01/0544"...
    DateTime.TryParseExact(convertedDate.ToString(), dateFormat, engCulture, DateTimeStyles.None, out convertedDate);

    return convertedDate;
}

Any help will be greatly appreciated. Thank you!

A: Hope it will help you understand how CultureInfo gets the DateTime from a string, the bare minimum requirement is in what culture date string is, but server or operating system shouldn't matter if string is parsed correct. Operating system will interfere only if culture isn't specified when string is parsed.
C# fiddle here: https://dotnetfiddle.net/wdDlts
using System;
using System.Globalization;

public class Program
{
    public static void Main()
    {
        string thaiBudistDate = "12/7/2561";

        // US format
        CultureInfo provider = CultureInfo.GetCultureInfo("en-US");
        DateTime date = DateTime.Parse(thaiBudistDate, provider);
        Console.WriteLine("Original string: '" + provider + "' in 'en-US' => Day: " + date.Day + " Month: " + date.Month + " Year: " + date.Year );

        // Thai Culture
        provider = CultureInfo.GetCultureInfo("th-TH");
        date = DateTime.Parse(thaiBudistDate, provider);
        Console.WriteLine("Original string: '" + provider + "' in 'th-TH' => Day: " + date.Day + " Month: " + date.Month + " Year: " + date.Year );

        // Thai Culture format! M/d/yyyy
        provider = CultureInfo.GetCultureInfo("th-TH");
        var format = "M/d/yyyy";
        date = DateTime.ParseExact(thaiBudistDate, format, provider);
        Console.WriteLine("Original string: '" + provider + "' in 'th-TH' format specified 'M/d/yyyy' => Day: " + date.Day + " Month: " + date.Month + " Year: " + date.Year );

        // Thai Culture format d/M/yyyy
        provider = CultureInfo.GetCultureInfo("th-TH");
        format = "d/M/yyyy";
        date = DateTime.ParseExact(thaiBudistDate, format, provider);
        Console.WriteLine("Original string: '" + provider + "' in 'th-TH' format specified 'd/M/yyyy' => Day: " + date.Day + " Month: " + date.Month + " Year: " + date.Year );

        // Using Gregorian time
        string usaDate = "12/7/2018";
        // US Culture
        provider = CultureInfo.GetCultureInfo("en-US");
        date = DateTime.Parse(usaDate, provider);
        Console.WriteLine("Original string: '" + usaDate + "' in 'en-Us' => Day: " + date.Day + " Month: " + date.Month + " Year: " + date.Year );

        // You got the point, dones't matter what provider you use! Hope this will help you undestand how wondows Culture works
        usaDate = "12/7/2018";
        // Thai Culture
        provider = CultureInfo.GetCultureInfo("th-TH");
        date = DateTime.Parse(usaDate, provider);
        Console.WriteLine("Original string: '" + usaDate + "' in 'th-TH' => Day: " + date.Day + " Month: " + date.Month + " Year: " + date.Year );

    }
}

A: If you already have the datetime converted to Thai culture (where day, month and year properties are correctly set) I think its enough to format it again to Datetime.ToString("M/d/yyyy") in case you want the string representation.


text:
Q: Sort a list based on order of subset of items in Python Assuming a list of variables {a,b,c,d,e} and based on some values their order should be c > b > d > e > a. What I have is a ordered subset of list, e.g:
b > d > a
c > e
b > e > a
c > b > a and so on.
Using the order of subset of lists, how can I arrive at full order of list. If a comparison of any 2 element doesn't exist, their respective order will not matter e.g. c > b > d = e > a if no comparison of d & e exist.

A: Consider each ordered subset as defining directed edges in a graph (the variables are the vertices), so for example, b>d>a defines edges b->d and d->a, and then topologically sort the resulted graph.

A: Solving the above problem, Follow these steps:
Step 1: Assign a unique integer to each character... for which I have used a dictionary.
Step 2: Then make comparisons as a list.
Step 3: Make a list of values they have in the dictionary...Sort that list and assign the values to the character's comparison list in the same order.
Step 4: Follow Step3 again using reset_list to maintain the comparison in the correct order.
At last, by performing the operations you will get the correct order by sorting character by their values in the dictionary.
list_alpha = [None,'a','b','c','d','e']
dictionary = dict()

for i in range(1,len(list_alpha)):
    dictionary[list_alpha[i]] = i

reset_list = []

n = int(input())
for seq in range(n):
    comparison = input()
    comparison_list = comparison.split(" ")
    reset_list.append(comparison_list)
    index_list = []
    for j in comparison_list:
        index_list.append(dictionary[j])
    index_list.sort()
    for i,j in enumerate(comparison_list):
        dictionary[j] = index_list[i]

for comparison_list in reset_list:
    index_list = []
    for j in comparison_list:
        index_list.append(dictionary[j])
    index_list.sort()
    for i,j in enumerate(comparison_list):
        dictionary[j] = index_list[i]

tp = []
for i,j in dictionary.items():
    tp.append((i,j))
tp.sort(key = lambda x : (x[1]))

for i,j in tp:
    print(i)

Input:
4

b d a

c e

b e a

c b a

Output:
c

b

d

e

a

A: If you have a suitable comparison function, you ought to be able to use this more or less directly with python's builtin list.sort (or sorted) via cmp_to_key to do this sorting (although I suggest this with the caveat that I might be missing some radically different and more efficient solution).
For example:
from functools import cmp_to_key

def compare(x, y):

    orders = [['b', 'd', 'a'],
              ['c', 'e'],
              ['b', 'e', 'a'],
              ['c', 'b', 'a']]

    for order in orders:
        if x in order and y in order:
            if order.index(x) > order.index(y):
                return 1
            else:
                return -1
    return 0

print(sorted(['a', 'b', 'c', 'd', 'e'],
             key=cmp_to_key(compare)))

This gives:
['c', 'b', 'd', 'e', 'a']

Here is a more efficient version that uses sets for inclusion testing, although it relies on the items being hashable:
from functools import cmp_to_key

orders = [['b', 'd', 'a'],
          ['c', 'e'],
          ['b', 'e', 'a'],
          ['c', 'b', 'a']]

order_pairs = [(set(order), order) for order in orders]

def compare(x, y):
    for order_set, order in order_pairs:
        if x in order_set and y in order_set:
            if order.index(x) > order.index(y):
                return 1
            else:
                return -1
    return 0

print(sorted(['a', 'b', 'c', 'd', 'e'],
             key=cmp_to_key(compare)))


text:
Q: openvino model "age-gender-recognition-retail-0013.xml" for child identification is it possible to add on age-gender-recognition-retail-0013 model to identify children age on openvino? If so, how can I retrain the model to make it able to identify the children age. Thank you in advance.

A: The age-gender-recognition-retail-0013 is able to recognize age of people in [18, 75] years old range, it is not applicable for children since their faces were not in the training set.
Intel's Pre-Trained Models are available in Open Model Zoo as Intermediate Representation (IR) format. The non-IR versions of pretrained models are not publicly provided, hence they cannot be used for retraining purpose.


text:
Q: C Programming 2D Array Problems I am learning C before I start learning C++ so I am very new to programming. I was playing around with 2D arrays and I sort of understand it. However I can't seem to figure out how to do this:
int x, y, z[4][4], i, j;
Where x = 10, and y = 10;
for (i=0; i<4; i++)
{
  for(j=0;j<4;j++)
  {
    z[i][j]=z[x][[y];
  }
}

I want the output to be:
When i=0 and j=0 print z[x][y]; As in print 10, 10.
Any help would be appreciated.

A: You're setting z[i][j] to be equal to z[x][y]. X and Y are 10 and 10 respectively which is outside the bounds of the array so that's going to fail

A: Here z[i][j] is just one value so it prints only 10 and you have to assign like this:
for (i=0; i<4; i++)
{
   for(j=0;j<4;j++)
   {
     z[i][j]=x;
   }
}

A: By doing z[4][4] you are declaring z as 4x4 matrix.
And when you try to use z[x][[y]; eg z[10][10]; you are clearly accessing elements out of bounds of your matrix.

A: #include <stdio.h>

int main(){
    int x, y, z[4][4], i, j;
    int base = 65536;

    for (i=0; i<4; i++){
        for(j=0;j<4;j++){
            int v;
            x = 10 + i;
            y = 10 + j;
            v = x * base + y;
            z[i][j] = v;
        }
    }
    i = 0;
    j = 0;
    if(i == 0 && j == 0)
        printf("%d, %d\n", z[i][j]/base, z[i][j] % base);

    return 0;
}

A: My understanding of a 2d array is definitely wrong. So I'll approach this question another way. Say I have the following variables.
int student_id[10], course_id[5];
int student_course[10][2];
There can only be 10 students.
There can only be 5 courses.
A student can only take 2 courses.
/*prompt user for student id*/

/*
say that the value for:
student_id[0]=123
*/

/*prompt user for course id*/

/*
say that the value for:
course_id[0]=101
course_id[1]=102
course_id[2]=103
course_id[3]=104
course_id[4]=105
*/

What I want to print out is the student_course[value of student_id][value of course_id].
So I thought of doing it this way:
int student_id[10], course_id[5], student_course[10][2]

int i, j, k;

for(i=0; i<10;i++){
    for(j=0; j<5; j++){

        /*prompt user for student id*/
        printf("Enter User ID: ");
        scanf("%d", &student_id[i]);

        /*prompt user for course id*/
        printf("Enter Course ID: ");
        scanf("%d", &course_id[j]);

        for(k=0; k<2; k++){
            student_course[i][j]=student_course[i][k];
        }

    }
}

If this is the wrong way, what is the correct way to get the results I want? A 3 dimensional array perhaps? I might not be ready for that yet.


text:
Q: Android O About ActivityManager.html#getRunningServices(int) I have one question.
https://developer.android.com/reference/android/app/ActivityManager.html#getRunningServices(int)

This method was deprecated in API level 26.
  As of O, this method is no longer available to third party applications. For backwards compatibility, it will still return the caller's own services.

Does 'pre installed application' work the same as 'third party application'?

A: Third party application in this context means 'an app not managed by Google'.

Does 'pre installed application' work the same as 'third party application'?

Yes, unless the pre installed application is by Google.


text:
Q: Dates are not increasing how they should when I drag a pattern down a column I am attempting to fill a column with dates and times. My time increments by hours. After 24 hours my date increases to the next. For some reason every 50 th cell or so the hours is thrown off by +- 1, 2, or 3 seconds. This is causing an issue for me because I am using this column as part of a match function I need to use in another workbook (I am using index match in another workbook). I am using the drag down "+" sign you get when you hover over the bottom right corner of the cell to generate the dates going down my column.

A: Try:
If A1 has your start date and time, put this formula in A2 and copy all the way down. This formula will round to the nearest hour.
=MROUND(A1,"1:00")+1/24


text:
Q: Recover data from formatted harddrive I had a dual boot machine with Windows 8 and Deepin linux on it. Last week I removed WIndows 8 and installed windows 8.1.
After installing Windows 8.1 grub was removed. I followed How can I repair grub? (How to get Ubuntu back after installing Windows?) to restore grub.
After repairing the machine restarted but for some reason after restarting in the middle of booting it shutdown.
Now the machine is not booting into any of the OS installed - it shows error message like "no boot device found please insert boot device and press any key".
I tried booting a live CD and it appears I have lost all my partitions and data.
I think it got formatted.
Is there any way to recover the lost partion data. If yes, how?
What all the requisites for that? is it possible to recover data into the same harddrive or do I need an external harddrive to store recover the data?
I Googled and got many tools which are available, but none have proper documentation on how to recover. My problem is I am not able to access any of the OS, so how can I to use the mentioned tool?
There are some bootable data recovery tools, but I dont know how to use them.

A: I deleted one of my partitions and i recovered it using  Active@ Partition Recovery Tool, Its not free*. It is like Linux OS you can live boot to it and recover files and partition. its really good.
here is a video btw : https://www.youtube.com/watch?v=tl5XgWJ3xK8
Title : "Recovery of accidentally deleted partition with Active@ Partition Recovery"
The video shows how to recover using the .exe file, not how to recover using the live OS tool.
*youtube can help ;)


text:
Q: Where should data reside in a watchOS app? I've been going through all of the Apple documents and videos related to creating watchOS apps, complications and the like. Carefully studying the flow of updating data and the user interface - yet there's one thing I didn't manage to figure out.
In all of the related videos and documents, it is explained that once a URLSession download task ends, the app should update it's data model and request the system to schedule a snapshot update.
My question is this: where should the data model be stored/persisted? Is it even necessary? Should I use Core Data? An in-memory singleton object? SQLite? UserDefaults? A simple JSON file? What is the preferred way of keeping your data model when writing apps for watchOS?
I am looking to store an array of very simple objects (e.g. a list of contacts, where each contact has a name, an address and a phone number, all of them represented as String objects)
Here's a link to the WWDC 2016 session named "Keeping Your Watch App Up to Date" that explains most of the tasks and best practices I've mentioned -
WWDC 2016: Keeping Your Watch App Up to Date

A: It is typically best practice to be storing persistent data for watchOS in the cloud or on a companion iPhone app. My guess is that what your source refers to by 'data model' is the data in active storage, i.e. when the app is open. You shouldn't be storing redundant data locally if you don't need to, esp. not for watchOS.
All that being said, watchOS does have access to CoreData and NSCoding methods. I'm not sure about NSUserDefaults - but I wouldn't use that anyway for data storage. (This is a general principle for iOS as well: CoreData is used for data, and UserDefaults for user preferences.) Here is a similar thread explaining how that's done.
But I would highly recommend finding an alternative before storing data on the watch - there just isn't a whole lot of persistent storage space available on there.
EDIT: Check out Apple's WatchKit docs for more details on your options.


text:
Q: Nested SQL statements Getting error. Three tables select I don't know if I am over complicating things or what but my SQL code gives errors. I am trying to find all the 'pid' that match from table parts.
Below is the necessary info.
Table: Parts:
pid, Color

Table: Supplier
sid

Table: Catalog
pid, sid

I am trying to retrieve the pid which have Color Red and a Supplier i.e exist in sid of table Supplier.
Here is my so far attempt:
SELECT pid
FROM catalog
WHERE sid = (SELECT sid
             FROM 'suppliers'
             WHERE sid=)(SELECT sid
                         FROM `catalog`
                         WHERE pid=)(SELECT pid
                                     FROM `parts`
                                     WHERE color = 'Red')

My 2nd Attempt says error, subquery returns more than 1 row:
SELECT pid FROM catalog c where c.pid=(SELECT pid from parts p where p.color='Red') AND c.sid=(SELECT sid FROM suppliers s)

A: Why don't you just use two simple INNER JOIN's instead of those nested subqueries?
SELECT c.pid
FROM catalog  c
INNER JOIN suppliers s ON c.sid = s.sid
INNER JOIN parts p ON c.pid = p.pid
WHERE p.color = 'Red'

A: I think you might be misplacing the open paranthesis. But I'd recommend using JOIN query instead.
SELECT pid
FROM Catalog C
INNER JOIN suppliers S ON C.sid = S.sid
INNER JOIN parts P ON C.pid = P.pid
WHERE P.color = 'Red'
AND S.sid = 'your_requirement'

A: You should avoid inner queries as suggested by @ncdreamy and use JOINS instead.
SELECT pid
FROM catalog AS c
INNER JOIN Parts AS p ON p.pid = c.pid
INNER JOIN suppliers AS s on s.sid = c.sid
WHERE p.color = 'RED'


text:
Q: TensorFlow serving: get input shape and labels I'm am currently trying to set up a TensorFlow Serving client that has the task of working through a queue of messages of the following format:
{
  "model_url":"http://path/to/some/model",
  "image_url":"http://path/to/some/image"
}

In other words, each message says which image should be predicted on using which model. Ideally, I should not have to specify any further information within the queue in order for this to work.
There are two problems though. The size of the input image could vary, whereas the expected input size is fixed (determined by the model). So the client must version resize the image. For that, it must know what the expected input size is.
So my concrete question is: if I know model_url, is there a way to make a request to the TensorFlow Serving server so that it tells me what the expected input shape looks like? Similary, I would need to know the labels that are associated with the predictions that the model delivers (e.g. "cat", "dog" etc. if we were doing image classification).
What I am looking for would be along the lines of the following pseudo code:
request_dict =    {
  "meta_info":["input_shape", "labels"]
}

response = requests.post(model_url, data=json.dumps(request_dict))

input_shape = response["input_shape"]
labels = response["labels"]

A: Yes, you can request all shapes of the inputs and outputs from your model by sending a request to the /metadata path of your TF server.
In its most simple form:
import requests
metadata_url = f'http://{host}:{port}/v1/models/{modelname}/metadata'
response = request.get(metadata_url).json()

The response will be a dictionary that contains the full signaturedef specification of your model (i.e., the shapes of all inputs and outputs).
This is probably easiest if using the REST api. See https://www.tensorflow.org/serving/api_rest for more examples (under 'metadata API'). Also know that it's possible to expose ports for gRPC traffic (for actual payload traffic) as well as for HTTP traffic (to request the model metadata) at the same time. Just specify both ports when running the server.


text:
Q: How do you know which relations will define a group? Consider the dihedral group of degree $n$, denoted $D_n$. I know that $D_n$ has presentation $\langle r,f\vert r^n,f^2,rfrf\rangle$, and I see why, but there are a lot of expressions which reduce to the identity $r_0$ in $D_n$, so I'm wondering how someone constructing a presentation for $D_n$ would know that just those three relations suffice to unambiguously define the group $D_n$.
In general, if I have a group $G$ and want to make a presentation for it, how would I go about doing so? Particularly, how would I know which relations need to be listed so that the presentation indeed defines my group and not a "more free" group?

A: Let $F_n$ denote the free group on $n$ generators, say $F_n = \langle x_1, \ldots, x_n\rangle$.
Suppose $G$ is a group and you want to find a presentation for $G$. You find some generators $g_1, \ldots, g_n \in G$. Then the universal property of free groups tells you there is a surjective group homomorphism $\Phi: F_n \twoheadrightarrow G$ via $x_i \mapsto g_i$.
Then you find some relations $r_1, \ldots, r_k \in F_n$ that are satisfied by the $g_i$, i.e., $r_i \in \ker(\Phi)$. So you let $N$ be the normal closure of the subgroup generators by $r_1, \ldots, r_k$, and $\Phi$ can be factored through the surjection $$\hat\Phi: F_n/N \twoheadrightarrow G.$$ Here $F_n/N = \langle x_1, \ldots, x_n \mid r_1, \ldots, r_k\rangle$.
Your question becomes: How do we show that $\hat\Phi$ is one-to-one, or determine that it's actually not one-to-one?
The best way to show that it is one-to-one, as far as I know, is to use the relations to convert every word in $x_1, \ldots, x_n$ into a "canonical representative", one for each element of $G$. In your example, every element of the group $\langle r,f\vert r^n,f^2,rfrf\rangle$ can be written as $f^\epsilon r^i$, for some $\epsilon \in \{0, 1\}$, and $i \in \{0, 1, \ldots, n-1\}$. These are precisely in correspondence with the elements of $D_n$, so you have a presentation for $D_n$.
To show that $\hat\Phi$ is not one-to-one, you simply need to somehow derive a contradiction from the assumption that $\hat\Phi$ is an isomorphism. One way to do this is to find a bigger group $\hat G$ such that $\hat\Phi$ can be expressed as a composition $$F_n/N \twoheadrightarrow \hat G \twoheadrightarrow G.$$
A more subtle way to get a contradiction is to find a group $\hat G$ which has generators satisfying the same specified relations, such that $\hat G$ cannot be expressed as a quotient of $G$. This is a contradiction because you have $F_n/N \twoheadrightarrow \hat G$ but $G \not\twoheadrightarrow \hat G$.
For example, you might think that the Quaternion group can be presented by $\langle i, j \mid i^2 = j^2, i^4=1\rangle$. But note that $F_2/N \twoheadrightarrow \mathbb Z/4\mathbb Z \times \mathbb Z/2\mathbb Z$, via $i \mapsto (1, 0)$ and $j \mapsto (1, 1)$. Since $\mathbb Z/4\mathbb Z \times \mathbb Z/2\mathbb Z$ is not a quotient of the quaternion group (it is the same size as the quaternion group, but, e.g., it is abelian while the quaternion group is not), our presentation must not be complete.

A: $\newcommand{\Span}[1]{\left\langle #1 \right\rangle}$In the particular case of the dihedral group, one knows that $D_{n}$ is a semidirect product of a cyclic group of order $n$ by a cyclic group of order $2$.
So the first relation $r^{n}$ attempts to define (see below) a group $\Span{r}$ of order $n$. The relation $f^{2}$ attempts to define a group $\Span{f}$ of order $2$. And the relation $r f r f$, which you can rewrite as $f^{-1} r f = r^{-1}$ tells you that the unique non-trivial element $f$ of the group $\Span{f}$ acts on $\Span{r}$ by inducing the inversion automorphism of $\Span{r}$. This is exactly what it takes to define the desired semidirect product.
The reason why I said "attempts" is that even if you start with the relation $r^{n}$, further relations may force $r$ to have a smaller order than $n$. For instance if you take relations $r^{4}, f^{2}, r^{-2} f r f$, then in the group you have $f^{-1} r f = r^{2}$, so that
$$f^{-1} r^{2} f = (f^{-1} r f)^{2} = (r^{2})^{2} = 1,$$
so that $r^{2} = 1$, and thus $r = 1$


text:
Q: Extract Version Number from String Using the following PowerShell command,
Get-ItemProperty HKLM:\Software\Wow6432Node\Microsoft\Windows\CurrentVersion\Uninstall\* |
  Select-Object DisplayName, DisplayVersion |
  Select-String 'Application Name'

I get an output like this:
@{DisplayName=Application Name; DisplayVersion=52.4.1521}

If this was on Unix, I could probably figure out a sed or awk command to extract the version number, but on Windows I don't even know where to begin. How do I get that version number out as the value of a variable?

A: Get-ChildItem produces a list of objects, so you should work with the properties of those objects. Filter the list via Where-Object for the object with the display name you're looking for, then expand the DisplayVersion property:
$regpath = 'HKLM:\Software\Wow6432Node\Microsoft\Windows\CurrentVersion\Uninstall'
$version = Get-ItemProperty "$regpath\*" |
           Where-Object { $_.DisplayName -eq 'Application Name' } |
           Select-Object -Expand DisplayVersion

You can also have the filter do partial matches with wildcards
... | Where-Object { $_.DisplayName -like '*partial name*' } | ...

or regular expressions
... | Where-Object { $_.DisplayName -match 'expression' } | ...


text:
Q: How to correlate vectors based on the position of the elements? I have two (and eventually more) character vectors that consist of several (ordered) names. Two examples of such vectors are:
 [1] "original" "gai"      "dea"      "iap"      "hso"      "los"      "ret"      "dap"      "wor"      "agi"
[11] "fat"      "con"      "dep"      "iso"      "int"

and
 [1] "int"      "iso"      "dep"      "con"      "fat"      "agi"      "wor"      "dap"      "ret"      "los"
[11] "hso"      "iap"      "dea"      "gai"      "original"

(which can be reacreated using):
c("original", "gai", "dea", "iap", "hso", "los", "ret", "dap",
"wor", "agi", "fat", "con", "dep", "iso", "int")

and
c("int", "iso", "dep", "con", "fat", "agi", "wor", "dap", "ret",
"los", "hso", "iap", "dea", "gai", "original")

Now I would like to compute the correlation between these two character vectors, based on the positions of the elements. For instance, in the first vector, the element "original" has position 1, but in the second it has position 14.
How would I go about this?
Thanks in advance!

A: For ordinal association, Kendall rank correlation coefficient () can be used. The catch here is to represent the strings as numeric so the result makes sense. That is for you to have a little taught and decide. Here is one way to go about it using a basic sequential numbers:
a <- c("original", "gai", "dea", "iap", "hso", "los", "ret", "dap",
       "wor", "agi", "fat", "con", "dep", "iso", "int")

# numeric representation
a_num <- seq(a)

b <- c("int", "iso", "dep", "con", "fat", "agi", "wor", "dap", "ret",
       "los", "hso", "iap", "dea", "gai", "original")

# numeric representation
b_num <- match(a,b)

# -------------------------------------------------------------------------
# eye ball the relationship
plot(a_num, b_num, type = "l", col="red", xlab = "a", ylab = "b")

# -------------------------------------------------------------------------

Output

You can see a negative correlation and further you can compute the Kendall's rank correlation tau to reject/accept the null as follows:
# use method kendall
cor.test(a_num,b_num, method="kendall")
# Kendall's rank correlation tau
#
# data:  a_num and b_num
# T = 0, p-value = 1.529e-12
# alternative hypothesis: true tau is not equal to 0
# sample estimates:
# tau
#  -1

see ?cor.test for more. This is just to get you started and if you have ties in your data, kendall handles that too but you need to know/read how to do that.

A: I am not sure if this is what you meant:
> r <- data.frame(pos = seq_along(x1), posinX2 = match(x1,x2))
> r
   pos posinX2
1    1      15
2    2      14
3    3      13
4    4      12
5    5      11
6    6      10
7    7       9
8    8       8
9    9       7
10  10       6
11  11       5
12  12       4
13  13       3
14  14       2
15  15       1

DATA
x1 <- c("original", "gai", "dea", "iap", "hso", "los", "ret", "dap",
        "wor", "agi", "fat", "con", "dep", "iso", "int")
x2 <- c("int", "iso", "dep", "con", "fat", "agi", "wor", "dap", "ret",
        "los", "hso", "iap", "dea", "gai", "original")

A: I think you could simply use match for that.
v1 <- c("original", "gai", "dea", "iap", "hso", "los", "ret", "dap",
        "wor", "agi", "fat", "con", "dep", "iso", "int")
v2 <- c("int", "iso", "dep", "con", "fat", "agi", "wor", "dap", "ret",
        "los", "hso", "iap", "dea", "gai", "original")

data.frame(v1 = v1, pos1 = 1:length(v1), pos2 =  match(v1, v2)) %>%
  summarise(corr = cor(pos1, pos2))

Not sure what this correlation would mean though..


text:
Q: Java hashcode() strings collision I do not know much about hashcodes. I found this code which prints the collisions.
Can you please tell me what are collisions and how to reduce it?
Why should we use hashcodes?
public static int getHash(String str, int limit)
{
    int hashCode = Math.abs(str.hashCode()%(limit));
    return hashCode;
}

/**
 * @param args
 */
public static void main(String[] args)
{
    int hashLimit = 10000;
    int stringsLimit = 10000;
    String[] arr = new String[hashLimit];
    List<String> test = new ArrayList<String>();
    Random r = new Random(2);
    for ( int i = 0 ; i < stringsLimit ; i++ )
    {
        StringBuffer buf = new StringBuffer("");
        for ( int j = 0 ; j < 10 ; j++ )
        {
            char c = (char)(35+60*r.nextDouble());
            buf.append(c);
        }
        test.add(buf.toString());
        //System.out.println(buf.toString());
    }
    int collisions = 0;
    for ( String curStr : test )
    {
        int hashCode = getHash(curStr,hashLimit);
        if ( arr[hashCode] != null && !arr[hashCode].equals(curStr) )
        {
            System.out.println("collision of ["+arr[hashCode]+"] ("+arr[hashCode].hashCode()+" = "+hashCode+") with ["+curStr+"] ("+curStr.hashCode()+" = "+hashCode+")");
            collisions++;
        }
        else
        {
            arr[hashCode] = curStr;
        }
    }
    System.out.println("Collisions: "+collisions);
}

A: To answer the other part of your question: To reduce the chance of collisions you should implement a hashing algorithm that provides an even distribution of hash codes over the set of possible inputs.
For example, supposing you implemented a naive hashCode() method for hashing MyString instances:
public class MyString {
  private final char[] arr;

  // Constructor and other methods.

  public int hashCode() {
    return arr.length == 0 ? 0 : (int) arr[0];
  }
}

In this example only the first character is used to create the hash code.  Therefore, if you were to hash the strings: "apple", "anaconda", "anecdote" they would all produce the same hash value.  A more efficient hash code would inspect all the letters in the character array to determine a hash code value, which would hopefully reduce the chance of a collision.

A:
Can you please tell me what are collisions and how to reduce it?

Collisions are when two non-equal objects have the same hash code. They're a fact of life - you need to deal with it.

Why should we use hashcodes?

Because they make it quick to look up values by key, basically. A hash table can use a hash code to very quickly get the set of possible key matches down to a very small set (often just one), at which point you need to check for actual key equality.
You should never assume that two hash codes being equal means the objects they were derived from are equal. Only the reverse is true: assuming a correct implementation, if two objects give different hash codes, then they are not equal.

A: We have a "collision" if two different non-equal objects have the same hashcode. This may be a problem, for example when try to use both objects as keys in a Hashmap.


text:
Q: "Ignoring unrecognized message" warning while listening for websocket events Trying to listen for a websocket event on frontend using the following code
var socket = new WebSocket(`wss://${window.location.host}`);

socket.onmessage = function (event) {
  this.step2Text = event.data
}

and firing from backend using
let app = express()
let server = http.createServer(app)
const WebSocket = require('ws')
let wss = new WebSocket.Server({ server });
wss.on('connection', function (ws, req) {
ws.send('some-data')
var stream = new WebSocketJSONStream(ws);
})

the registered function dosen't gets called but says
"Ignoring unrecognized message 'some-data'"


text:
Q: How I can input for API url? If I am NOT taking input from user using below mentioned API URL then i am able to access API.
import requests
import json
import pprint

response = requests.get('https://www.ncbi.nlm.nih.gov/research/bionlp/litvar/api/v1/entity/search/A146T')

if response.status_code == 200:
    data = json.loads(response.text)
    pprint.pprint(data)
else:
    print(f"Error : {response.status_code}")

OUTPUT:-
[{'_id': 'litvar@rs121913527##',
  'all_hgvs': [['c.146A>T', 231],
               ['p.A146T', 90],
               ['c.436G>A', 50],
               ['p.A146P', 49],
               ['c.436G>C', 15],
               ['g.25225628C>T', 1],
               ..........

But when I am trying to taking input from user them i am not able to do it :
import requests
import json
import pprint

url = requests.get('https://www.ncbi.nlm.nih.gov/research/bionlp/litvar/api/v1/entity/search/')
params = {"q":"A146T"}

response = requests.get(url, params)

if response.status_code == 200:
    data = json.loads(response.text)
    pprint.pprint(data)
else:
    print(f"Error : {response.status_code}")

ERROR :-
InvalidURL: Failed to parse: <Response [200]>


text:
Q: Find CDF of Z = min(X,Y) Conditions
1) Two random variables X, Y are independent and they follow binomial distribution with probability of success p.
2) X's mean is 2 and so does Y.
The question is to find the CDF of Z=min(X,Y)
I have no idea how to solve this question. I'm only familiar with continuous random variables not discrete ones.
Any help would be appreciated.

A: $X \sim Bin(n,p)$, $Y \sim Bin(m, p)$
$np=2$, $mp=2$, hence $n=m=\frac2p$
if $z \in \mathbb{Z}$
\begin{align}
P(Z \leq z) &= 1-P(Z > z)\\
&=1- P(\min(X,Y)>z) \\
&=1-P(X>z)P(Y>z), \text{ where I have used independence} \\
&= 1 - P(X>z)^2 \\
&= 1-\left(\sum_{i=z+1}^{\frac2p}\begin{pmatrix} \frac2p \\ i \end{pmatrix}p^i(1-p^{\frac2p-1})\right)^2
\end{align}


text:
Q: How to extract attachment Blob data from Google Cloud SQL using Google Apps Script? I am using Google Apps Script to extract attachment blobs from Google Cloud SQL using .getBlob() property of JdbcResultSet. I need to attach this data to a Google Site page.
My problem is, I am not able to get through the attachment blob from cloud SQL. ".getBlob()" property returns "Jdbc Blob". Clubbing it with ".getAppsScriptBlob()" property return "Blob". When I try to attach the blob to a Google Site page, script flashes an error: "Service error: JdbcBlob (line #, file "attachment")".
Here is my code snippet:
while(sql_assetsExt_result.next()){
    var dbBlob = sql_assetsExt_result.getBlob(11).getAppsScriptBlob();
    var page = "myPageURL";
    var prodExist = SitesApp.getPageByUrl(page);
    if(prodExist){
      prodExist.addHostedAttachment(dbBlob, (sql_assetsExt_result.getString(12)));
    }
    Logger.log(dbBlob)
  }
}

Can someone please help me on how to go about it? Thanks In Advance!


text:
Q: Importing a dynamically generated model class in `__init__.py` I have a function that returns django models class and would like to import them in my app/models/__init__.py.
My function is a slight modification of this dynamic model exemple (Django Wiki). It clones a model and returns a <class 'django.db.models.base.ModelBase'>, a slightly modified "shadow model".
Just like one would do (in app/models/__init__.py) from a import test1, I would like to do something like:
from c import modeltocopy
from b import dynamic_model('ShadowModel', app_label='fake',fields=modeltocopy._meta.fields)`

I want to do this in order to create tables in an alternative db from my dynamic models.
Is such a thing possible?
My currently working solution is a management command that is a modification of django/core/management/commands/syncdb.py that creates tables from a tuple of tuples defined in settings.py (SHADOW_MODELS = (('app.module1.module_a', 'ClassName1'),)).
 It does work but I am being asked to import my dynamic models in /app/models/__init__.py rather than having to run a separate command just for my dynamic models.

A: You cannot import the result of a function call. Instead you could first import the function, then call it to create the model class in the module's namespace:
from c import modeltocopy
from b import dynamic_model as dyn_model_factory

ShadowModel = dyn_model_factory('ShadowModel', app_label='fake', fields=modeltocopy._meta.fields)

The resulting dynamic_model is then read to be imported from other module.


text:
Q: Removing numbers from text using C# I have a text file for processing, which has some numbers. I want JUST text in it, and nothing else. I managed to remove the punctuation marks, but how do I remove the numbers? I want this using C# code.
Also, I want to remove words with length greater than 10. How do I do that using Reg Expressions?

A: You can do this with a regex:
string withNumbers = // string with numbers
string withoutNumbers = Regex.Replace(withNumbers, "[0-9]", "");

Use this regex to remove words with more than 10 characters:
[\w]{10, 100}

100 defines the max length to match. I don't know if there is a quantifier for min length...

A: Only letters and nothing else (because I see you also want to remove the punctuation marks)
Regex.IsMatch(input, @"^[a-zA-Z]+$");

A: You can also use string.Join:
string s = "asdasdad34534t3sdf43534";
s = string.Join(null, System.Text.RegularExpressions.Regex.Split(s, "[\\d]"));

A: The Regex.Replace method should do the trick.
// regex to match any digit
var regex = new Regex("\d");
// replace all matches in input with empty string
var output = regex.Replace(input, String.Empty);


text:
Q: jQuery clone with ajax autocomplete The achieved idea is an invoice, with fields item, description, rate, etc. Each line of fields, with a add row - achieved by jquery clone. And it is working.
However, I also have a working autocomplete, which gets the data from a database, and update the rest of the fields.
But I cant get the two to work together. I don't know how else to explain it.
So;
<script type="text/javascript">
$(function() {
$( "#label" ).autocomplete({
source: "<?=base_url()?>admin/autocomplete/",
minLength: 1,
select: function( event, ui ) {
event.preventDefault();

this.value = ui.item.valuedesc;
$('#label').val(ui.item.valuedesc);
$('#description').val(ui.item.description);
$('#rate').val(ui.item.rate);
}
});
});
</script>

Then the return I get is the valuedesc, description, rate, which then automatically updates the relevan fields.
<input type="text" maxlength="255" name="item_sku[]" data-required="1" class="form-control" id="label" autocomplete="off" required/>

<input type="text" maxlength="255" name="item_description[]" data-required="1" id="description" class="form-control" required/>

<input type="text" maxlength="255" name="item_amount[]" data-required="1" id="rate" class="form-control calculate" autocomplete="off" required/>

And this is what I use to clone the row and clears the input values of the newly added row
// add new product row on invoice
var cloned = $('#invoice_table tr:last').clone();
$(".add-row").click(function (e) {
    e.preventDefault();
    cloned.clone().appendTo('#invoice_table').find('input').val('');
});

So, the autocomplete works for the first row - because I get the "label" id from the text input.
But if I add more, getting the autocomplete to work doesn't work, because of duplicate IDs.
My question would be thus; How can I dynamically add a unique ID to where "label" id currently is? Secondly, is it possible to alter the autocomplete javascript to prevent duplicating the javascript for each clone?
Image here: http://i.stack.imgur.com/RxFCN.jpg

A: The simplest way of doing it is to use classes instead of id-s:
<input type="text" maxlength="255" name="item_sku[]" data-required="1" class="form-control label" autocomplete="off" required/>
<!-- ... etc ... -->

and then initialise a new autocomplete every time you generate a new row:
$(function() {
    var options = {
        source: "<?=base_url()?>admin/autocomplete/",
        minLength: 1,
        select: function( event, ui ) {
            event.preventDefault();

            this.value = ui.item.valuedesc;
            $(this).val(ui.item.valuedesc);
            $(this).parents('tr').find('.description').val(ui.item.description);
            $(this).parents('tr').find('.rate').val(ui.item.rate);
        }
    };
    $( ".label" ).autocomplete(options);

    var cloned = $('#invoice_table tr:last').clone();
    $(".add-row").click(function (e) {
        e.preventDefault();
        cloned.clone().appendTo('#invoice_table').find('input').val('')
                                                 .filter('.label').autocomplete(options);
    });
});


text:
Q: How to align text in automatically generated SVG? I have project to convert data from CSV to graph in SVG. Graph has not strict size, because width and height are based on data gained from CSV (that is export from smartphone/tablet app IoTool).
To describe graph, I added some texts - that are partially based on data, too.
In image seen by browser, there is text (for example - there are another six lines of such descriptive text)
    Graph name: RR interval

that has code
<text x="0" y="170">
    Graph name:<tspan id="LineName">RR interval</tspan>
</text>

Problem is, that text should be aligned to the left side of graph without any space before text. And instead it, there is big space between left side of graph and text.
And if code is
<text x="0" y="170">
    Graph name:
    <tspan id="LineName">RR interval</tspan>
</text>

then big space is also between the first and the second part of text
    Graph name:    RR interval

like if element text would count with text-indent from source code. This behaviour is without regardless of which font family is used. I tested generic families sans, sans-serif and monospace.
And I don't know why this happens - and how to stick text back to left side of graph.

A bit shortened code of one generated svg
<svg xmlns="http://www.w3.rg/2000/svg" xmlns:link="http://www.w3.org/1999/xlink" xml:space="preserve" width="47887pt" height="1197pt" viewbox="0 0 191548 4788">

    <g>
        <rect x="0" y="0" width="47887" height="1197" style="fill: #EFEFEF;"></rect>
    </g>
    <g style="stroke-width: 0.5; stroke: #AAAAAA;">
        <line x1="0" x2="0" y1="0" y2="1197"></line>
            <line x1="200" x2="200" y1="0" y2="1197"></line>
            <line x1="400" x2="400" y1="0" y2="1197"></line>
            <line x1="600" x2="600" y1="0" y2="1197"></line>
            ...
            <line x1="47200" x2="47200" y1="0" y2="1197"></line>
            <line x1="47400" x2="47400" y1="0" y2="1197"></line>
            <line x1="47600" x2="47600" y1="0" y2="1197"></line>
        </g>
        <g style="stroke-width: 0.5; stroke: #AAAAAA;">
            <line x1="0" x2="47887" y1="1197" y2="1197"></line>
            <line x1="0" x2="47887" y1="1097" y2="1097"></line>
            <line x1="0" x2="47887" y1="997" y2="997"></line>
            ...
            <line x1="0" x2="47887" y1="297" y2="297"></line>
            <line x1="0" x2="47887" y1="197" y2="197"></line>
            <line x1="0" x2="47887" y1="97" y2="97"></line>
        </g>
        <g font-size="170" style="font-family: monospace; fill: #005959;">
            <text x="0" y="170">
                Graph name:
                <tspan id="LineName">RR interval</tspan>
            </text>
            <text x="0" y="340">
                From time:
                <tspan id="StartTime">2017-09-04 20:10:31.941</tspan>
            </text>
            ...
            <text x="0" y="1020">
                Minimum value:
                <tspan>722.656</tspan>
            </text>
            <text x="0" y="1190">
                Maximum value:
                <tspan>1718.75</tspan>
            </text>
        </g>
        <g width="47887" height="1197" style="stroke-width: 1; stroke: #000000; fill: none;">
            <polyline points="0,1055.008 205.4,1047.195 409.6,1027.664 ... 47686.8,958.328 47886.2,976.883 47886.2,988.601"></polyline>
        </g>
    </svg>

A: It sounds like you have xml:space="preserve" defined in your SVG.
The default is to not preserve spaces, so you would have had to have added it yourself.  Check if you have that set and remove it.