text:
Q: Stop SKVideoNode Playing When Not In View Of Camera I use SpriteKit image recognition. SpriteKit works normally and I can image recognition. After recognition, I add a video on that picture. When the camera changes its direction and the videoNode is not in view, How can I remove the video?
simple code:
override func viewDidLoad() {
    super.viewDidLoad()

    guard let referenceImages = ARReferenceImage.referenceImages(inGroupNamed: "Room", bundle: nil) else {
        fatalError("Missing expected asset catalog resources.")
    }

    let configuration = ARWorldTrackingConfiguration()
    configuration.detectionImages = referenceImages

    sceneView.session.run(configuration, options: [.resetTracking, .removeExistingAnchors])

}

func view(_ view: ARSKView, didAdd node: SKNode, for anchor: ARAnchor) {

    if let imageAnchor = anchor as? ARImageAnchor,
        self.myImage == imageAnchor.referenceImage {
        node.addChild(self.addNode())
    }
}

private func addNode () -> SKVideoNode {
    let video = SKVideoNode(url: URL(string: "http://techslides.com/demos/sample-videos/small.mp4")!)
    video.size = CGSize(width: 40, height: 40)
    video.position = CGPoint(x: 0, y: 0)
    video.play()
    return video
}

A: Just do camera.contains(videoNode) If you want to check if the videoNode is in the camera or not.
basically on camera moved (Wherever you are moving the camera) do:
if !scene.camera.contains(videoNode){
    videoNode.pause()
}


text:
Q: how to return 0 instead of null with 'in' operator I have hree tables:

*

*text: text in lines

*trigram: trigram of all text lines

*text_trigram: trigrams that a text line contains, intermediate table
When I execute this:
select count(coalesce(text_id,0)), text_id
from text_trigram
where text_id in (1, 2, 3)
and trigram_id = 1
group by text_id;

it came out with the result without having the null result which I want it to be 0:
count|text_id
1       1
1       2

This is what I except to have:
count|text_id
 1       1
 1       2
 0       3

Further more I want to execute something like this:
select count(coalesce(text_id,0)), text_id
from text_trigram
where text_id in (1, 2, 3)
and trigram_id in (1, 2, 3)
group by text_id;

count|text_id|trigram_id
   1       1        1
   1       1        2
   0       1        3
   1       2        1
   1       2        2
   1       2        3
   0       3        1

it is possible? or is it wrong using in operator?

A: You can use conditional aggregation if every text_id has at least one trigram:
select text_id, sum(case when trigram_id = 1 then 1 else 0 end) as cnt
from text_trigram
where text_id in (1, 2, 3)
group by text_id

Or you can use a left join:
select t.text_id, count(tt.trigram_id) as cnt
from text t left join
     text_trigram tt
     on tt.text_id = t.text_id and tt.trigram_id = 1
where t.text_id in (1, 2, 3)
group by t.text_id

A: I think the confusion here is that you are assuming there is a null for text_id=3, but actually there is just no row that matches. Consider this simplified version:
select *
from text_trigram
where text_id in (3)

This will not return any rows if there is no entry with text_id=3; it won't fabricate a row with a bunch of nulls in.
In order to force a row to exist even if there is no matching data, you can create a table expression containing those IDs, e.g.
select * from
(
    values (1), (2), (3)
) as required_ids ( text_id );

Then LEFT JOIN your data, so you get NULL where there is no matching data:
select *
from
    (
        values (1), (2), (3)
    ) as required_ids ( text_id )
left join text_trigram
    on text_trigram.text_id = required_ids.text_id;

To get to your first query, note two things:

*

*count ignores nulls, so count(text_trigram.text_id) will only count rows where a match was found in the text_trigram table

*any extra conditions need to be in the on clause of the left join, so that they eliminate rows from text_trigram, not from the whole query

select count(text_trigram.text_id), required_ids.text_id
from
    (
        values (1), (2), (3)
    ) as required_ids ( text_id )
left join text_trigram
    on text_trigram.text_id = required_ids.text_id
    and text_trigram.trigram_id = 1
group by text_id
order by text_id;

Changing this to every permutation of text_id and trigram_id would just involve an extra table expression and a CROSS JOIN:
select required_text_ids.text_id, required_trigram_ids.trigram_id, count(text_trigram.text_id)
from
    (
        values (1), (2), (3)
    ) as required_text_ids( text_id )
cross join
    (
        values (1), (2), (3)
    ) as required_trigram_ids( trigram_id )
left join text_trigram
    on text_trigram.text_id = required_text_ids.text_id
    and text_trigram.trigram_id = required_trigram_ids.trigram_id
group by required_text_ids.text_id, required_trigram_ids.trigram_id
order by required_text_ids.text_id, required_trigram_ids.trigram_id;

redpajama_set_name: RedPajamaStackExchange


text:
Q: Why do these two implementations produce different results? I asked this question and got an excellent answer (thanks!).  Part of the problem to be solved involved taking a word and de-interlacing it, so that you get two words, one containing the even-indexed characters of the original word, the other containing the odd-indexed characters.
The responder used the following code to do this:
for w in words:
    even, odd = w[::2], w[1::2]

I did it this (worse) way:
for w in words:
    lst1 = []
    lst2 = []
    for c in w:
        if w.index(c) % 2 == 0:
            lst1.append(c)
        else:
            lst2.append(c)
    even = ''.join(lst1)
    odd = ''.join(lst2)

Okay, my way is worse for a number of reasons.  But it seems to me as though both ways should at least produce the same pairs of words.  And yet, I get different results using his implementation than mine.  Why is that?

A: Because index(c) asks the index of the first occurrance of the letter in the word — so you are creating a single "bucket" for each letter. So if the first 'a' is odd, then all of the 'a' letters also get stuffed into the "odd" string. To fix this, you should just use enumerate() to count:
for i, c in enumerate(word):
    # check whether ``i`` is even/odd, etc


text:
Q: Row spacing to group rows based on 1st column I need to know how to easily space out the data based on profile_id. Adding a row between each number will help the data look clean for the users. Top picture is what the current data looks like and the bottom picture is what I want it to look like.

A: If you want to avoid VBA and your only goal is to visually differentiate each ID number, you can use conditional formatting with the following formula:
=ISODD($A1)

A: If it's too much to do manually, you can use a simple macro with a loop to check through the column.
Something like
Sub ShiftGroups()
Dim lastCell As Variant: lastCell = Range("A2").Value2
For Each cell In Range("A2:A" & Cells(Rows.Count, 1).End(xlUp).Row)
    If Not cell.Value2 = lastCell And Not cell.Value2 = "" And Not lastCell = "" Then
        cell.EntireRow.Insert
    End If
    lastCell = cell.Value2
Next cell
End Sub

This is a pretty basic loop with the added feature that it should skip any already empty rows, so running it several times should be no problem.
IF you are unfamiliar with macros/visual basic, you might need to start with showing the developer tab. And then look up the basics on how to use them.


text:
Q: Will three bulbs connected in parallel glow brighter than two bulbs in parallel? The question is simple but i have not heard anything like this before. This was asked by my teacher in the viva of my electrical workshop class. And she said the three bulbs will glow brighter and i had to tell the reason for this. Now was this a trick question or is this true? Cause i clearly said ma'am there will be no difference. I want to know the truth before the finals please help. Cause i cannot find a reason for the bulbs to glow brighter the voltage is same and the current will be divided among three bulbs now so why would they glow brighter?

A: There's a simple way to tell who's right: build the circuit and see what happens. Nature doesn't care about people's opinions, and She, by definition, will give you the right answer!
But you are correct: full marks on this one! If the three bulbs are connected in parallel across a voltage source, the voltage across them theoretically stays the same as when one bulb is connected across the same source.
The difference between the two situations is that, in the three bulb case, the total current drawn from the voltage source is tripled. This is what I think your teacher may be thinking of.
Practically, you will find that the bulbs will be slightly dimmer in the three bulb case as opposed to the one bulb case. This is because all practical voltage sources have a nonzero source impedance (also called "internal impedance" or "output impedance"), which means that they look like a voltage source in series with a resistance (in a DC circuit case). So, as the current increases to cope with the three bulb case, the voltage drop across the source impedance roughly triples, leading to a lower voltage across the parallel light bulbs.


text:
Q: clearInterval when object is no longer referenced? I have a class that acts as a client to a server (through a WebSocket). I would like to implement a system that periodically pings the server to determine latency. However, I am concerned that if I use setInterval inside the class for this purpose, it will continue to try to ping after the object should be garbage collected. How can I know when to call clearInterval?
Summary of code:
class WSClient extends EventEmitter
{
    private latency: number;
    public get Latency(): number
    { return this.latency; }

    public async ping(): Promise<number>
    { ... }

    public constructor(options)
    {
        super();

        // Do constructor stuff

        setInterval(() => this.ping().then(latency => this.latency = latency), 1000);
    }
}

A: You can use setInterval() and save it to an variable, then you can access that interval like so:
class WSClient extends EventEmitter
{
    private latency: number;
    public get Latency(): number
    { return this.latency; }

    public async ping(): Promise<number>
    { ... }

    public constructor(options)
    {
        super();

        // Do constructor stuff

        this.interval = setInterval(() => this.ping()
        .then(latency => this.latency = latency), 1000);
    }
}

Then when you need:
WSClient.interval.clearInterval();

A: Here's the thing: you'll never reach a point where the object "should" be garbage collected, because the setInterval you've defined is holding a reference to that object (in your context, as this) in perpetuity. You're going to need some extra logic to determine if you still need to run it.
What I'd recommend, and it's an easy approach since you've already defined your get Latency(), is to put some logic in there to monitor if anyone's actually asked for the latency in a while. If the getter's been run recently, keep polling. If it hasn't, remove the interval.
You could make this much easier if you defined, instead, async getLatency(), that way if you detect that the latency hasn't been recently pinged, you can wait until the latency is recalculated.
I haven't run this, but am including it to illustrate the idea:
// ms to wait until cancelling the interval
const latencyTimeout = 200000;

// In your class

async getLatency(): number {
  if (!this.latency) {
    const started = Date.now();
    const poller = setInterval(async () => {
       if (Date.now() - started > latencyTimeout) {
         clearInterval(poller);
         this.latency = null;
       }
       this.latency = await this.ping();
    }, 1000);
    this.latency = await this.ping();
  }
  return this.latency;
}

As an aside, you may want to consider not using the setInterval, but a recurring setTimeout instead. The problem with the interval, is that it's based on its own clock. It won't take into account the amount of time needed to complete the ping. eg if you're polling every second, but it takes 500ms to complete the ping, it'll be okay, but if it takes 2000ms to ping then your pings will actually go out of order. It could look like you have a much slower ping, because you're receiving the return from a ping that took longer than a recent one that ran fast. Better to do a setTimeout instead that only runs after the last one completed.


text:
Q: How to decrypt,encrypted data using Cryptography Hello i'm trying to make a simple encrypt,decrypt algorithm and i maked encrypt code correctly,but description code not working
    static string Encript(string value)
    {
        using (MD5CryptoServiceProvider md5 = new MD5CryptoServiceProvider())
        {
            UTF8Encoding utf8 = new UTF8Encoding();
            byte[] data = md5.ComputeHash(utf8.GetBytes(value));
            return Convert.ToBase64String(data);
        }
    }

    static string Decript(string value)
    {
        using (TripleDESCryptoServiceProvider Tdecript = new TripleDESCryptoServiceProvider())
        {

             UTF8Encoding utf8 = new UTF8Encoding();
             byte[] DataToDecrypt = Convert.FromBase64String(value);
             return utf8.GetString(DataToDecrypt);
        }
    }

this is show when i press decript button

A: First of all you are using a Hash Function to "encrypt" your data. Hashing is a one way function. Thus you will not be able to "decrypt" your data.
Second of all: MD5 is not a good hashing mechanism. Please use something like SHA256.
Third: To encrypt + decrypt I would recommend you to use AES256.
Here is a sample on how to achieve this:
AESManaged Microsoft

A: This may not answer you original question but do not use MD5 - it is considered broken. I would use sha-256 as a minimum if you actually want to keep the information you are hashing secure.
To answer you question
To my knowledge the MD5 hash you are using is a one way function - meaning you take a password and hash it, stick it in a db - when a user comes back you do not decrypt the data and check the two values match but you create a new hash of the data they gave you and compare these two.
If you need a two way encryption service I would look at AES.


text:
Q: Reportviewer displaying not properly when a style sheet is used I am using Report viewer inside the master page.
When i display it. The controls of the Reportviewer are all over the place(part of display shown in figure)

After some debugging i found that the style sheet used in the master page is causing this.
Below Tags when i remove from my style sheet the reports displays perfectly.
Tags Removed
table
{
    width: 90%;

color: #333333;
margin: 10px 10px 20px;
border-left: 1px solid #cbcbb4;
border-top: 1px solid #cbcbb4;

}

table caption
{
    margin: 10px 0 5px;
    font-weight: bold;
}

th, td
{
    right: 1px solid #cbcbb4;
    border-bottom: 1px solid #cbcbb4;
    padding: 2px 10px;
}

What is the solution?

A: I don't believe there would be one other than don't use tags in your style sheet that are really general. The Report Viewer Control builds a html table from the data, so the style sheet applied to the page will definitely affect this.
this may be helpful to you: CSS Help - How can a DIV ignore css previously set on the page?


text:
Q: Can a Git hook automatically add files to the commit? I'd like to add an automatically generated file to the same commit using a pre- or post-commit hook in Git, dependent on the files that were modified in that commit.  How would I go about this?
I've tried this as a pre-commit hook, but no luck:
#!/bin/sh
files=`git diff --cached --name-status`
re="<files of importance>"
if [[ $files =~ $re ]]
then
  echo "Creating files"
  exec bundle exec create_my_files
  exec git add my_files
  exec git commit --amend -C HEAD
fi

This successfully adds them to the repository, but does not add them to the commit.  I've also tried using the last two exec lines in a post-commit hook along with the pre-commit inspection, but no good either.

A: Since git add was also not working for me in a pre commit, I followed mark's idea of using a .commit file and splitting the process into pre- and post-commit.
Here is some code that should be easy to understand
In the pre-commit:

*

*Touch a file .commit or something. (be sure to add this to .gitignore)

#!/bin/sh
echo
touch .commit
exit

In the post-commit:

if .commit exists you know a commit has just taken place but a
  post-commit hasn't run yet. So, you can do your code generation here.
  Additionally, test for .commit and if it exists:

*

*add the files

*commit --amend -C HEAD --no-verify (avoid looping)

*delete .commit file

#!/bin/sh
echo
if [ -e .commit ]
    then
    rm .commit
    git add yourfile
    git commit --amend -C HEAD --no-verify
fi
exit

Hope this makes it easier for people with few bash knowledge to follow mark's idea.

A: It's possible to do what you want using pre-commit hooks.  We do something similar for a heroku deployment (compiling coffeescript to javascript).  The reason your script isn't working is because you used the exec command improperly.
From the man page:

The exec builtin is used to replace the currently running shells process image with a new command. On successful completion, exec never returns. exec can not be used inside a pipeline.

Only your first exec command is running.  After that your script is basically terminated.
Give something like this a try (as a pre-commit hook):
#!/bin/sh
files=`git diff --cached --name-status`
re="<files of importance>"
if [[ $files =~ $re ]]
then
  echo "Creating files"
  bundle exec create_my_files
  git add my_files
fi

A: How about writing a post-commit script instead which generates your files, and then have that do (something along the lines of) git add my_files; git commit --amend.

A: #!/bin/sh
#
#  .git/hooks/pre-commit
#

git add file.xyz

This worked just fine for me.
It will be part of the current commit.
git version 1.7.12.4 (Apple Git-37)

A: You can use update-index:
git update-index --add my_files

A: You could use a combination of a pre and post commit script.
In the pre-commit:

*

*Touch a file .commit or something. (be sure to add this to .gitignore)

In the post-commit:
if .commit exists you know a commit has just taken place but a post-commit hasn't run yet. So, you can do your code generation here. Additionally, test for .commit and if it exists:

*

*add the files

*commit --amend -C HEAD --no-verify (avoid looping)

*delete .commit file

This is roughly the process I use to store a .metadata file in the repository generated from metastore.
If anyone knows a better way I'm all ears but it seems to work for now.

A: I had the same need and this approach worked pretty well for me:
#!/bin/sh
files='git diff --cached --name-only'
re="<files of importance>"
if [[ $files =~ $re ]]
then
   echo "Creating files"
   create_my_files && git add my_files
fi

where "create_my_files" should be executable, for example if it is a python file you could execute it as "python create_my_files && git add my_files"
and is true you don't need a pre-commit to commit again (that would create a infinite nasty loop :p)

A: If the files are automatically generated, and they can be generated anywhere (implicit in your desire to build them in the Git pre-commit hook) then you shouldn't be putting them under source control in the first place. You should only control source files -- generated files should be generated as part of the build scripts.
The only reason to put a generated file under source control is when it requires unique/privileged resources to generate (such as a licensed program) or it requires a significant amount of time to generate.
Added
From http://git-scm.com/docs/githooks :

pre-commit This hook is invoked by git
  commit, and can be bypassed with
  --no-verify option. It takes no parameter, and is invoked before
  obtaining the proposed commit log
  message and making a commit. Exiting
  with non-zero status from this script
  causes the git commit to abort.
The default pre-commit hook, when
  enabled, catches introduction of lines
  with trailing whitespaces and aborts
  the commit when such a line is found.
All the git commit hooks are invoked
  with the environment variable
  GIT_EDITOR=: if the command will not
  bring up an editor to modify the
  commit message.

The intent of the pre-commit hook is to be a pass-fail check on the state of the workspace and the contents of the commit, prior to making the commit.  Attempting to change the contents of the commit won't work.
My recommendation would be add two steps to your build scripts:  (1) a step that will build all of the out-of-date files that needs to be generated (and adds them to the workspace), and (2) a step that will check to ensure that all of the generated files are up-to-date, and return a non-zero status code.  Your Git pre-commit hook should run the second step.  Your developers should be trained to run the first step as necessary.

A: Yes, you can add generated files automatically on the commit using git hooks! But it requires a tricky script.
Here you can find the problem solved. There, it is updating the file version on every commit, adding a new modified file and amending the commit as you need it to. It is fully working:
https://github.com/evandrocoan/.versioning
Then you just replace the 'Version File Replacement' algorithm on the file 'updateVersion.sh', by your  algorithm. Maybe you need to change a few things like, remove the branch limitation, because there, the script only runs if you are on the 'develop' branch.
Also, it will only change the specified file, if is staged. If the file is not staged, then it will do nothing than the normal/usual commit. More precisely, it print out what it is doing on every step.
I am going to explain, that trick. It is quite tricky. On the prepare-commit-msg-hook, it detects whether the desired file is being staged and committed. After that, it creates a flag file, and stops the prepare-commit-msg-hook.
Later on the post-commit-hook, it checks whether the flag file exists. If yes, it amends the files on the commit.
Attention, it would create a infinity loop because it would call again the prepare-commit-msg-hook (as we are amending). But it does not happen because of the flag file. When the prepare-commit-msg-hook runs and find the flag file, it "knows" what is happening. Then is just deletes the flag file and do not create it again. Doing it, it will block the post-commit-hook from amending again the commits, allowing the commit to finish for good.

A: I was facing same problem in pre-commit hook also. I was modifying one file and committing but it was taking previous file not updated file so by adding git command(as below) in pre-commit hook, it solved.
git add $file

note: $file is your file to be added.


text:
Q: Getting related object's ID without fetching it from the database (Play framework) Say I have these two models:
public class City extends Model
{
    @ManyToOne
    private Country country;
}

public class Country extends Model
{
}

I have a City object and want to know the related Country's ID. I could fetch from the database by doing city.getCountry().getId() but that seems very wasteful. How can I just get the ID (stored in the database table as country_id)?

A: I think fetchType=LAZY is what you need. It creates a proxy-object for the country and it should not do any queries by requesting the id.
@OneToOne(fetch = FetchType.LAZY)
private Country country;

But you also need do mark your id-getter in Country.
public class Country extends Model
{
    @Id
    public Long getId()
    {
        return id;
    }
}

If you don't want do change your id-annotations you can also use this workaround:
  Serializable id = ((HibernateProxy) country).getHibernateLazyInitializer().getIdentifier()


text:
Q: Grouping value by time frames Here is what I am using to group items by time frame when parsing a csv file, it is working fine, but now I would like to create slices by 4h and 30mn, this particular code just works for slices by the hour, I would like to create 4 hours slices ( or 30m slices )
tf = "%d-%b-%Y-%H"

lmb = lambda d: datetime.datetime.strptime(d["Date[G]"]+"-"+d["Time[G]"], "%d-%b-%Y-%H:%M:%S.%f").strftime(tf)

for k, g in itertools.groupby(csvReader, key = lmb):
    for i in g:
        "do something"

Thanks!

A: The general best approach is to have the groupby key return a tuple which groups items into the appropriate bucket.
For example, for 4h slices:
def by_4h(d):
    dt = datetime.datetime.strptime(d["Date[G]"]+"-"+d["Time[G]"], "%d-%b-%Y-%H:%M:%S.%f")
    return (dt.year, dt.month, dt.day, dt.hour // 4)

You now know that if two times are in the same 4 hour slice (starting from midnight) then hour // 4 will give the same result for those times, so you end the tuple there.
Or for 30m slices:
def by_30m(d):
    dt = datetime.datetime.strptime(d["Date[G]"]+"-"+d["Time[G]"], "%d-%b-%Y-%H:%M:%S.%f")
    return (dt.year, dt.month, dt.day, dt.hour, dt.minute // 30)

This is using // integer division for Python 3 compatibility, but it also works in Python 2.x and makes it clear that you want integer division.


text:
Q: Why dont my calculations work? This is more of a why doesn't this work question. I obviously must be missing something because I cannot for the life of me figure out why calculating the width and height values give me the same static value that I started with. But when I substitute hardcoded values it works just fine. So obviously my calculations are bad but I cannot seem to figure out why. Can anyone help? If you need more info please ask.
 if(objectList[selectedIndex].Selected == true)
 {
      //The width would be mouselocationx - objectlocationx
      //The height would be mouselocationy - objectlocationy
      //Off set the position so it doesnt snap to mouse location
      //WHY THE *%$!! DOESNT THIS WORK!!?!?!?!?!?!?
      //int width = e.X - objectList[selectedIndex].X;
      //int height = e.Y - objectList[selectedIndex].Y;
      //Why is this so hard??
      //Point location = objectList[selectedIndex].Location;
      //location.X = e.X - (e.X - objectList[selectedIndex].Location.X);
      //location.Y = e.Y - (e.Y - objectList[selectedIndex].Location.Y);
      objectList[selectedIndex].X = e.Location.X - 12;
      objectList[selectedIndex].Y = e.Location.Y - 12;
      objectLocationXLabel.Text = "OBJX: " + objectList[selectedIndex].X.ToString();
      objectLocationYLabel.Text = "OBJY: " + objectList[selectedIndex].Y.ToString();
      panel1.Invalidate();
   }

A: It's not at all clear what you want to do. But there are at least two issues with your commented code:
location.X = e.X - (e.X - objectList[selectedIndex].Location.X);

is equivalent to
location.X = objectList[selectedIndex].Location.X;

Point is a value type. So when you do this:
Point location = objectList[selectedIndex].Location;
location.X = ...;

location is modified, but not objectList[selectedIndex].Location.
Edit in response to comment: I think you must determine the offset in the MouseDown event, store it in a member and use it in MouseMove.


text:
Q: The type 'TNestedInterface' must be convertible to 'INestedInterfaceTest' in order to use it as parameter 'TNestedInterface' public interface INestedInterfaceTest<TChildType>
    where TChildType : INestedInterfaceTest<TChildType>
{
     List<TChildType> children { get; set; }
}

public abstract class NestedInterfaceTest : INestedInterfaceTest<NestedInterfaceTest>
{
    public List<NestedInterfaceTest> children { get; set; }

    public TNestedInterface GetNestedInterface<TNestedInterface>()
        where TNestedInterface : NestedInterfaceTest, new()
    {
        return GateWay<TNestedInterface>.GetNestedInterface();
    }
}

public class GateWay<TNestedInterface>
    where TNestedInterface : class, INestedInterfaceTest<TNestedInterface>, new()
{
    public static TNestedInterface GetNestedInterface()
    {
        return new TNestedInterface();
    }
}

Things go wrong at the GetNestedInterface method in the abstract class.
The error message is: The type 'TNestedInterface' must be convertible to 'INestedInterfaceTest' in order to use it as parameter 'TNestedInterface' in the generic class 'GateWay'.
But..., my abstract class NestedInterfaceTest implements the INestedInterfaceTest interface.
What am I missing here?
The following does work, without the recursive interface implementation:
public interface INestedInterfaceTest
{
}

public abstract class NestedInterfaceTest : INestedInterfaceTest
{
    public List<NestedInterfaceTest> children { get; set; }

    public TNestedInterface GetNestedInterface<TNestedInterface>()
        where TNestedInterface : NestedInterfaceTest, new()
    {
        return GateWay<TNestedInterface>.GetNestedInterface();
    }
}

public class GateWay<TNestedInterface>
    where TNestedInterface : class, INestedInterfaceTest, new()
{
    public static TNestedInterface GetNestedInterface()
    {
        return new TNestedInterface();
    }
}

It seems that it goes wrong in the recursive implementation.

A: You're missing a generic constraint on GetNestedInterface<>().  Change it to this:
public TNestedInterface GetNestedInterface<TNestedInterface>()
    where TNestedInterface :
        NestedInterfaceTest,
        INestedInterfaceTest<TNestedInterface>, // new
        new()
{
    return GateWay<TNestedInterface>.GetNestedInterface();
}

Note the second constraint is new.

A: NestedInterfaceTest implements INestedInterfaceTest<NestedInterfaceTest> and the requirement on the TNestedInterface in the GetNestedInterface is that it should implement INestedInterfaceTest<TNestedInterface> too.
If I create a subclass of NestedInterfaceTest that does not re-implement the INestedInterfaceTest<> interface, that constraint will not be satisfied:
//does not implement INestedInterfaceTest<Derived>
class Derived : NestedInterfaceTest {}
class Derived2 : NestedInterfaceTest {}

Derived d = new Derived();
// breaks because GateWay<Derived2> cannot be constructed
d.GetNestedInterface<Derived2>();

Simplest work-around I see, that might not fit into your object model is to redefine the constraint on the GateWay class with:
public class GateWay<TNestedInterface>
  where TNestedInterface : class, INestedInterfaceTest<NestedInterfaceTest>, new()

This way, any class that inherits from NestedInterfaceTest will fulfill the constraint without the need to reimplement the interface, because NestedInterfaceTest fulfills it. It might be even handier to do:
public class GateWay<TNestedInterface>
  where TNestedInterface : class, NestedInterfaceTest, new()

Anyway, even if you manage to get this to work, it's still confusing, both for the consumer of the class, and for the (eventual) maintainer. Also, you can almost never be sure that some misuses will not be possible

A: I think I solved my own problem.
Please review the code and let me know what you think:
public interface INestedInterfaceTest<TChildType>
    where TChildType : INestedInterfaceTest<TChildType>
{
    List<TChildType> children { get; set; }
}

public abstract class NestedInterfaceTest<TChildNestedInterface> : INestedInterfaceTest<TChildNestedInterface>
    where TChildNestedInterface : INestedInterfaceTest<TChildNestedInterface>
{
    public List<TChildNestedInterface> children { get; set; }

    public virtual TNestedInterface GetNestedInterface<TNestedInterface>()
        where TNestedInterface : NestedInterfaceTest<TChildNestedInterface>, INestedInterfaceTest<TNestedInterface>, new()
    {
        return GateWay<TNestedInterface>.GetNestedInterface();
    }
}

public class GateWay<TNestedInterface>
    where TNestedInterface : class, INestedInterfaceTest<TNestedInterface>, new()
{
    public static TNestedInterface GetNestedInterface()
    {
        List<TNestedInterface> nestedChildren = new List<TNestedInterface>();
        return new TNestedInterface
            {
                children = nestedChildren
            };
    }
}

public class NestedClass : NestedInterfaceTest<NestedClass>
{
    public NestedClass GetNestedClass()
    {
        return GetNestedInterface<NestedClass>();
    }
}

That did the trick alright and it prevents the interface from 'leaking out'.


text:
Q: OpenTBS/PHP - Merge content into embedded worksheet inside of a PowerPoint template How do I properly fill an embedded worksheet of a PowerPoint template with data using OpenTBS, where the worksheet is embedded inside of a PowerPoint presentation?
I used sub files but the embedded worksheet retains the input tags and no replaced values.
Excel Template that merges properly as a standalone xls file, but not when embedded in a presentation (PPTX).
+------------------------------+---------------------------------+
|                              |    [c.key;block=tbs:cell]       |
+------------------------------+---------------------------------+
|       [r.#;block=tbs:row]    |    [cell.val;block=tbs:cell]    |
+------------------------------+---------------------------------+

PHP Merge Code
$template = 'riskwaterfalltemplate.pptm';
$TBS->LoadTemplate($template.'#ppt/embeddings/Microsoft_Excel_Worksheet2.xlsx',  OPENTBS_ALREADY_UTF8);

// -----------------
// Output the result
// -----------------
$nbr_row = 5;
$nbr_col = 5;
// List of column's names
$columns = array();
for ($col=1; $col <= $nbr_col; $col++)
{
    $columns[$col]['key'] = $col;
}

$data = array();
$record = array();

for ($col=1; $col <= $nbr_col; $col++)
{
    $record[$col]['val'] = 1;
}
for ($row=0; $row < $nbr_row; $row++)
{

    $data[$row] = $record;
}

// Expanding columns
$TBS->MergeBlock('c',$columns);

//Expanding Cells
$TBS->MergeBlock('cell', $record);

// Merging rows
$TBS->MergeBlock('r',$data);

$TBS->Show();

Debug Output
* OPENTBS DEBUG MODE: if the star, (*) on the left before the word OPENTBS, is not the very first character of this page, then your
merged Document will be corrupted when you use the OPENTBS_DOWNLOAD option. If there is a PHP error message, then you have to fix it.
If they are blank spaces, line beaks, or other unexpected characters, then you have to check your code in order to avoid them.

------------------------------
INFORMATION
------------------------------
* Debug command: OPENTBS_DEBUG_XML_CURRENT
* OpenTBS version: 1.9.9
* TinyButStrong version: 3.10.1
* PHP version: 5.6.25YES
* Opened document: riskwaterfalltemplate.pptm
* Activated features for document type: openxml/pptx
* Deleted files in the archive: none
* Added files in the archive: none
* Modified files in the archive:
  - ppt/embeddings/Microsoft_Excel_Worksheet2.xlsx

------------------------------
File merged with OpenTBS: ppt/embeddings/Microsoft_Excel_Worksheet2.xlsx

A: If you are merging the embedded XLSX in order to have a chart modified in the PPTX Presentation, this  will not work.
In both Ms Word ans Ms PowerPoint, embedded XLSX attached to chart does not contains the true data of the chart. It is a simple copy that helps the user for editing the data using Ms Excel. The true data are stored in the XML sub-file related to the chart.
If you want to edit the chart, use command OPENTBS_CHART.
If you actually want to merge the embedded XLSX file, your code is not working because the sub-file ppt/embeddings/Microsoft_Excel_Worksheet2.xlsx is not an XML file, it is a binary file. So TBS cannot merge anything in it directly.
The solution is to:

*

*load the PPTX template using $TBS->LoadTemplate('my_presentation.pptx'),

*the load the ppt/embeddings/Microsoft_Excel_Worksheet2.xlsx sub-file as the current sub-file using $TBS->PlugIn(OPENTBS_SELECT_FILE, $SubFile)

*save the binary of the XLSX sub-file in a temp file using $handle = tmpfile(); fwrite($handle, $TBS->Source);

*open a new TBS instance for this temp file using $TBS2->LoadTemplate($handle);

*do your data merging in the XLSX with $TBS2,

*finalize the XLSX using $TBS2->Show(OPENTBS_STRING);

*save the result in the PPTX using $TBS->Source = $TBS2->Source;

*finalize the PPTX using $TBS->Show(...);


text:
Q: gps data in sqlite I'd like know how to create a database in sqlite which contains gps data(latitude,longitude) and then retrieving from the database to display the data on the map?
please I need it urgent
Thanks

A: public class DBAdapter{
public static final String KEY_ROWID = "_id";
public static final String KEY_latitude  = "latitude";
public static final String KEY_longitude = "longitude";
          Cursor cur=null;

private static final String DATABASE_NAME = "MyDB.sqlite";
private static final String DATABASE_TABLE = "gpsCordinates";
private static final int DATABASE_VERSION = 1;

private static final String DATABASE_CREATE =
        "create table gpsCordinates(_id integer primary key autoincrement,"
+ "latitude text not null, longitude text not null);";

private final Context context;

private DatabaseHelper DBHelper;
private SQLiteDatabase db;

public DBAdapter (Context ctx){
    this.context = ctx;
    DBHelper = new DatabaseHelper(context);
}

private static class DatabaseHelper extends SQLiteOpenHelper{
    DatabaseHelper (Context context)
    {
        super(context, DATABASE_NAME, null, DATABASE_VERSION);
    }

    @Override
    public void onCreate(SQLiteDatabase db) {
        // TODO Auto-generated method stub
        try{
            db.execSQL(DATABASE_CREATE);
        }
        catch (SQLException e){
            e.printStackTrace();
        }

    }

    @Override
    public void onUpgrade(SQLiteDatabase db, int oldVersion, int newVersion) {
    Log.w(TAG,"Upgrading database from version"
        +oldVersion + " to " +newVersion + ", This will remove all previous data");
        db.execSQL("Drop TABLE IF EXISTS");
        onCreate(db);
    }
}

public DBAdapter open() throws SQLException {
    db = DBHelper.getWritableDatabase();
    return this;

}

public DBAdapter openReadable() throws SQLException {
    db = DBHelper.getReadableDatabase();
    return this;

}

public void close(){
    DBHelper.close();
}
//*-- inserts a new contact into database --*//
public long insertContact(String latitudE, String longitudE){
    ContentValues initialValues = new ContentValues();
    initialValues.put(KEY_latitude, latitudE);
    initialValues.put(KEY_longitude, longitudE);
    return db.insert(DATABASE_TABLE, null, initialValues);

}

public Cursor retrieveRecord(){
  cur= db.rawQuery("YOUR SQL QUERY", null);
    return cur;
}

This should take care of creating a database. Use the cursor to retrieve your values.


text:
Q: How to move the wordpress template style.css file in another folder? I would like to follow one of Page Speed's recommendation: Serve static content from a cookieless domain. So I need to move the style.css file away from the default template folder and put it in my cookieless domain.
How do I notice wordpress for this change?
Thanks.

A: Style.css is ultimately called in the header file of a wordpress template. Simply changing the location call in your templates header to the one where your new styles.css file is located should do the trick.

A: OR you could leave everything where it is and set up a sub-domain (say http://static.example.com) and using CNAME in your DNS have that point to your www/root so that any existing file path can be called using that new sub-domain. As long as none of the resource using that sub-domain set cookies then your are achieving the same effect of using a separate (cookie less) domain. See http://www.ravelrumba.com/blog/static-cookieless-domain/ for a full run down.


text:
Q: How to use Azure Authorization social providers with a static html angular website? I have followed this documentation on how to use the azure social authorization provider for google plus sign-in. https://learn.microsoft.com/en-us/azure/app-service-mobile/app-service-mobile-how-to-configure-google-authentication
After authentication is finished it sends the app to this page: https://yourapp.azurewebsites.net/.auth/login/done
Is the post_login_redirect_url a way to redirect back to your web application and pass the token?
Is there anyway to redirect back to your static html website with the token?

A: After looking more into the post_login_redirect_url it looks like the way is that this parameter is attached like this /.auth/login/?post_login_redirect_url=/
You can then grab the token from your url as it is stored in the hash value.
This question was helpful: How to set Azure Authentication custom login return url?
Another way to get the token that I found was to call /.auth/me to get back your authorized array of tokens.


text:
Q: Calculating the equation of a zig zag line on a graph I have plotted a time v/s some hardware sensor value graph. I have many readings and want to calculate a mean or any possible value (may be equation of a zig zag line, may be oscillatory motion or harmonic motion) to compare multiple readings.
I am recording data at the interval of 0.01 seconds.
Here is the graph plot of a single reading:

Here is the graph plot of multiple readings:

Also, equation of a curve can also be calculated. The data can be divided into time (2 second blocks), to calculate the equation of curve at that time.

A: Add each value to a buffer when you plot it, then you can calculate whatever you want.
For the mean sum the buffer contents and then divide by the number of entries in the buffer.
To find equations for curves, this page should help.


text:
Q: Human resource allocation algorithm I'm working on this application to help the restaurant boss to allocate his staff.
For simplification, consider that we only have part-time staff. Each staff member has a different wage and a different available time (2pm-7pm on Thursday, 7am-9am on Monday, etc).
We divide every day into 12 hours. For every hour we need a different amount of staff (5 staff members during 7am-9am, Sunday; 1 member during 1pm-5pm Monday, etc).
I have a feeling that this is a maximum matching problem, but can't really figure it out. Except for a genetic algorithm, can anyone give me some advice?

A: Just want to answer so if anyone have the same problem as me could have a clue. The fastest and simplest solution I can find is Hungarian algorithm. Every time section is a node. Each staff member divide to k node ( k is their available time). With this model, we just run the Hungarian algorithm and problem solved.


text:
Q: Reinstalling Win10 alongside Linux Mint I have a 750GB drive that is failing, but still functional (I already backed up what can't simply be reinstalled), and I would like to reinstall Win10 on the SSD (I assume my key should still be valid, but this is not the problem here), probably in the 500GB gap, but I could add another HD if that's better.

*

*I know there were many problems installing Windows after Linux and I would like to avoid scrapping everything on the SSD, even if I could theoretically do it, as I have backups and the Z2 array, which I assume won't be touched; OTOH, I seem to understand these problems are (almost?) gone with modern UEFI boot.

I have  a rather modern PC with:

*

*1TB SSD containing Linux Mint 20.2 "Ulyssa", with ~500GB of free space for sda2/sda3, and another ~350Gb of free space at end
/dev/sda1       2048     264191    262144   128M EFI System
/dev/sda4  975587328  983400447   7813120   3,7G Linux swap
/dev/sda5  983400448 1283399679 299999232 143,1G Linux filesystem

*4x identical 3TB drives in a ZFS Z2 array, providing space for /home and other data

*750GB disk where Win10 is installed with its normal partitioning:
/dev/sdb1     2048    1023999    1021952  499M Windows recovery environment
/dev/sdb2  1024000    1228799     204800  100M EFI System
/dev/sdb3  1228800    1261567      32768   16M Microsoft reserved
/dev/sdb4  1261568 1465145343 1463883776  698G Microsoft basic data

What steps should I follow to maximize my success chances?

*

*A full guide would be best, but a list of possible pitfalls and how to steer clear would also be welcome; I am aware of this answer, but I'm unsure if it applies to Win10

WIP: I will update this section to reflect my attempts.
Following @JW0914 input I tried to create an "image" on my NAS (syno0).
I opened a PowerShell as Administrator and then:
PS C:\WINDOWS\system32> New-SmbMapping -LocalPath 'X:' -RemotePath '\\syno0\Store'

Status Local Path Remote Path
------ ---------- -----------
OK     X:         \\syno0\Store

PS C:\WINDOWS\system32> Dism /Capture-Image /ImageFile:"X:\recover\Base.wim" /CaptureDir:"C:" /Name:"Windows Backup" /Description:"Base Image 2021.03.20 @ 16:20" /Compress:Max /CheckIntegrity /Verify /ScratchDir:"X:"

Strumento Gestione e manutenzione immagini distribuzione
Versione: 10.0.19041.1

Errore: 32

Impossibile accedere al file. Il file è utilizzato da un altro processo.

Il file di registro di Gestione e manutenzione immagini
distribuzione è disponibile in C:\WINDOWS\Logs\DISM\dism.log
PS C:\WINDOWS\system32>

Sorry for the Italian text, it essentially says:
Error: 32
Impossible to access file. File is in use by another process.

I assume I should try to issue this command either from "Safe mode" or from "Preboot Environment", but I don't know how (I'm a Linux guy). Any pointer welcome.
Another problem I see with "instructions" is I assume I will have to make (at least) two images: one for my setup and one for WinPE, right?
If so I have no idea how to access WinPE partition from Win Dism.
Another problem is I would like to add the partitons to my SSD, so I think using Diskpart ... clean could be trouble; also here I would need some guidance, if possible.


text:
Q: Help installing Microsoft office 10 in Ubuntu 14 64 bits using Winetricks I was trying to install Microsoft Office in Ubuntu 14.04 64 bits using winetricks,I selected wine default prefix,then choose dlls dotnet20 and msxml6 after that a warning message appears (mono not installed, but it was installed previously)

A: The "Mono is not installed" message is normal, just click OK.


text:
Q: Parsing Javascript cookie values and separating values I'm still learning Javascript and I'm trying to parse a value from a cookie in a specific key:
I'm using this current line:
const cookieObj = new URLSearchParams(document.cookie.replaceAll("; ","&","|"))
cookieObj.get("LG_AFF_TRK")
LG_AFF_TRK is the key that I'm pulling the value from. Doing so creates the output value of the following:
1|2|3|4|5|6
Each number represented would be a value that will have a random number of characters -and- could possibly be empty but each section always be separated by the "|" symbol.
How can I pull a specific value?  As an example question, what do I need to do pull value 3?
I'm trying to understand this logically and my guess is I have to create an array first?


text:
Q: ¿How I load Richtexbox.rtf from dataBase with Datatype XML? In my database I have a column of XML datatype. I use an RTF to XML converter and I using DbContext.
How do I load Richtexbox.rtf from the database with datatype XML?
CREATE TABLE [dbo].[Table]
(
    [Id] INT IDENTITY (777000000, 1) NOT NULL,
    [XmlData] XML NULL
)

My code:
var ht = (from h in db.Table where (h.ID == 777000001) select h);

if (ht.Count() > 0)
{
    var xml = ht.FirstOrDefault().XmlData;

    // Code to convert....
    richTexBox.rtf = ????;
}


text:
Q: Can sequential pattern mining be called an unsupervised learning method? Sequential pattern mining finds patterns in unlabeled data. So I assume its an unsupervised learning algorithm. But most references to pattern mining never mention the learning part. Why? Can sequential pattern mining be called an unsupervised learning method?
This Wikipedia articles lists the Apriori algorithm as an unsupervised method, but no citations.


text:
Q: jQuery fadeIn and fadeOut not compatible with IE8 I have written this script to fade in/out an error container. it works fine in FF and Chrome but does not work at all in IE8.
You can play with the fiddle here: http://jsfiddle.net/mostafatalebi/8tw2x/
or look the below code:
Here is the Container CSS:
.error-box
{
    filter:inherit;
    width: auto;
    display: inline;
    padding: 5px;
    border-radius: 5px;
    -webki-border-radius: 5px;
    -moz-border-radius: 5px;
    direction: rtl;
    text-align: right;
    background-color: #C00;
    color: white;
    font-size: 13px;
    width: 200px;
    float: left;
    margin-bottom: 5px;
    opacity:inherit;
    filter:inherit;
}

Here is the HTML DOM:
Email

                    <input id='email' type="text" name="email" class="form-input" />

And here is the jQuery code to handle the process:
        $(document).ready(function(e) {

            var email = $("#email");
            email.on('blur', function(){
                console.log(email_regexp.test(email.val()));
                if(!email_regexp.test(email.val()))
                {
                    $(this).siblings('.error-box').fadeIn(600).text("رایانامه شما اشتباه است");
                }
                else
                {
                    $(this).siblings('.error-box').fadeOut(600);
                }
            });
        });

A: On compatability and jQuery
jQuery 2.x is only meant to be used with Internet Explorer 9 and up. If you wish to have support for fading elements in Internet Explorer 8 (and down to 6), you will need to use jQuery 1.x instead, which still supported the older IE filter property.
I have confirmed that switching to jQuery 1.x resolves the issue. Nothing else was necessary, even though it seems in the past additional workarounds may have been needed.
On console and old Internet Explorer
One other thing to keep in mind is that by console doesn't initially exist in IE8. As such, any attempt to call console.log will cause problems. If you wish to use it, pre-check for the availability of console first. You could do this with &&, though this is considered an abusage:
window.console && console.log( email_regexp.test( email.val() ) );

Alternatively, you can take the more verbose route and make it a proper condition:
if ( window.console ) { console.log( email_regexp.test( email.val() ) ); }

If you don't want to litter your code with console checks, just define your own:
if ( !window.console ) {
    // When debug is true, console.log alerts
    var debug = true;
    window.console = {
        log: function ( message ) {
            if ( debug ) alert( message );
        }
    };
}

Further Reading: jQuery Browser Support

A: Taken from jQuery fadeIn fadeOut - IE8 does not fade
Taken from Omeriko:
'Apparently there's a workaround!
Simply set the absolute/relative positioned elements the following css attributes:
opacity:inherit;
filter:inherit;

E.g:

Have fun,
Omer'

A: You need to create a manual fadeIn fadeOut function for IE that removes the filter attribute.
Then it will work perfectly.
Good tutorial on how to do it:
http://www.epochdev.com/blog/tutorials/javascript_development/fixing_jquery_fade_in_and_out_functions_for_internet_explorer

A: FadeIn and FadeOut does not seem to be supported well in IE8. Although it works as expected on other higher versions of IE.


text:
Q: How to set in Report the TextBox visibility by expression in VisualStudio? I have a simple TextBox in my Precision Design related to a Field in Temporary Table.
I need to show this TextBox only If the it value under Temporary Table is pupulated : so if the value field is pupulated (is a string) I show the Text Box , otherwise I don't show the text Box.
I need to set Visibility by Expression :

Which is the best way forward over ?
Thanks!

A: You can use iif function. Press fx button, here you can writte your code.
iif function evaluate a condition and return 1 of 2 options, for example, in your case you need show one value only if exist.
check this code:
=iif(fields!YourFieldName.value = "", true, false)

if your field is a number
=iif(fields!YourFieldName.value = 0, true, false)

This code evaluate the value of your field and only populate the value if is complete.


text:
Q: Doctrine one-to-many returning null I'm trying to map a Milestones to a Project but when I try to reference the relation it's always returning null.
The database looks perfect, the targetEntity paths are correct and the scheme is validating by using
doctrine:scheme:validate

project.php
/**
 * @ORM\OneToMany(targetEntity="Planning\Readmodel\Project\Milestone\Milestone", mappedBy="project", cascade={"persist", "remove"})
 */
private $milestones;

milestone.php
/**
 * @ORM\ManyToOne(targetEntity="Planning\Readmodel\Project\Project", inversedBy="milestones", cascade={"persist", "remove"})
 * @ORM\JoinColumn(name="projectId", referencedColumnName="projectId")
 */
private $project;

But when I try to get the milestone I get null using:
$this->milestones;

Any idea what I might be doing wrong? Thank you.

A: Your owning entity definition i.e Project looks fine to me but your inversed entity i.e  Milestone has a problem in JoinColumn annotation in JoinColumn annotation name relates to the column of your current entity which hold the relation to project entity but in referencedColumnName you have to provide the column of your parent entity that is primary key of project entity which should be referencedColumnName="id"
So your annotation for milestone entity should be like
/**
 * @ORM\ManyToOne(targetEntity="Planning\Readmodel\Project\Project", inversedBy="milestones", cascade={"persist", "remove"})
 * @ORM\JoinColumn(name="project_id", referencedColumnName="id")
 */
private $project;

According to the official docs 5.11. Mapping Defaults

The name of the join table defaults to a combination of the simple,
  unqualified class names of the participating classes, separated by an
  underscore character. The names of the join columns default to the
  simple, unqualified class name of the targeted class followed by
  "_id". The referencedColumnName always defaults to "id", just as in
  one-to-one or many-to-one mappings.

Make sure to update your database by running doctrine update command


text:
Q: Plotting histogram using clusters I have tried to research this problem, but failed. I'm quite a beginner at python, so bear with me.
I have a textfile containing numbers on each line (they are angles in degrees).
I want to first cluster the angles into cluster sizes of 20. Then I want to plot this on a histogram. I have the following code:
angle = open(output_dir+'/chi_angle.txt', 'r').read().splitlines()
array = numpy.array(map(float, angle))
hello = list(array)
from cluster import *
cl = HierarchicalClustering(hello, lambda x,y: abs(x-y))
clusters = cl.getlevel(20)
frequency = [len(x) for x in clusters]
average = [1.0*sum(x)/len(x) for x in clusters]

Now. My question is: How do I plot the histogram?
Doing the following:
pylab.hist(average, bins=50)
pylab.xlabel('Chi 1 Angle [degrees]')
pylab.ylabel('#')
pylab.show()

will show a histogram with bars correctly placed (i.e. at the average of each cluster), but it wont show how many "angles" each cluster contains.
Just for clarification. The clustered data looks like this:
clusters = [[-60.26, -30.26, -45.24], [163.24, 173.24], [133.2, 123.23, 121.23]]

I want the mean of each cluster, and the number of angles in each cluster. On the histogram the first bar will thus be located at around -50 and will be a height of 3. How do I plot this?
Thanks a lot!

A: Not sure I understood your question. Anyhow try saving your histogram in this array
 H=hist(average, bins=50)

If you want to plot it then do
 plot(H[1][1:],H[0])

H[1] is an array that stores the bins centers and H[0] the counts in each bin. I hope this helped.

A: Why don't you just use a histogram right away?
A histogram of cluster centers is not a very sensible representation of your data.


text:
Q: can't update list adapter in list view while posting in onPostExecute adapter.notifyDataSetChanged(); Basically i have been try to do the damn this for over 40 hours - read all threads about it and still no result!!! So I can't update list adapter in list view while posting in onPostExecute  adapter.notifyDataSetChanged();
ArrayAdapter<String> adapter;
private ProgressDialog dialog;

protected void onCreate(Bundle savedInstanceState)
{

    super.onCreate(savedInstanceState);

    setListAdapter(adapter);
    dialog = new ProgressDialog(
            Table.this);
    dialog.setProgressStyle(ProgressDialog.STYLE_SPINNER);
        dialog.setMessage("Загружаю. Подождите...");

    AsyncTask<Void, Void, Void> loadingTask = new AsyncTask<Void, Void, Void>() {
        @Override
        protected void onPreExecute() {
              dialog.show();
        }

        @Override
        protected Void doInBackground(Void... params) {

  ........ adapter = new ArrayAdapter<String>(Table.this,         android.R.layout.simple_list_item_1,CreateStringArray
   .getString(myData, null, null, null, null));

            return null;
        }
        @Override
        protected void onPostExecute(Void result) {
          adapter.notifyDataSetChanged();
         Table.this.
            dialog.dismiss();
        }

    };
    loadingTask.execute();

    getListView().setOnItemClickListener(this);

}

So it shows me the spinner and successfully load and deletes it. After a while of debugging i noticed that it successfully changes data in the adapter. Still it dent display it. Am working with listvew

A: By instantiating a new Adapter in doInBackGround you lose the reference to the adapter you set doing setListAdapter(adapter); Therefore, the adapter you notify in OnPostExecute is not the one in your ListView.


text:
Q: Loop causes Firefox to crash So it seems like this javascript loop will sometimes cause my Firefox to overload and crash. I just don't understand why.
        //prep genresArray
        var genPrint = ""; //variable initialized to avoid "undefined" in print loop
        var GAL = movieListLocal[i].genresArray;
        for(var i=0; i<2; i++){
            genPrint = genPrint+GAL[i].name+", ";
        }

genresArray contains a number of genre-objects, each one with a id and a name (such as adventure, horror etc). I simply want to turn into into a continuous string instead.

A: It looks like this loop is nested inside another loop that also uses i. For the inner loop, you should use a different variable name, like j.
    var genPrint = "";

    // outer loop counter----v
    var GAL = movieListLocal[i].genresArray;

    // -----v--inner loop counter
    for(var j=0; j<2; i++){
        genPrint = genPrint+GAL[j].name+", ";
    }

JS doesn't have block scope when using var, so the inner i declaration overwrites the outer one.
It will work with the let declaration, coming in ECMAScript 6, and currently available in Firefox.
for (let i = 0; i < 3; ++i) {
    console.log("foo", i)
    for (let i = 0; i < 3; ++i)
         console.log("bar", i)
}


text:
Q: Qual a diferença de se colocar -g nas instalações de pacotes por npm, webpack, etc...? Já faz um certo tempo que instalo pacotes via prompt com npm, bower entre outros gerenciadores de pacote, mas nunca entendi direito para que serve a comando -g. Sei que significa global, instalando os pacotes globalmente no computador e não apenas localmente no projeto especificamente. Mas minhas dúvidas são:

1 - Com o uso de -g onde ficam alocados no computador os pacotes instalados?
2 - Se instalar por exemplo o Vue.js assim npm install -g @vue-cli em um projeto, e em outro projeto utilizando Vue.js instalá-lo com o comando npm install @vue-cli, da onde é buscado o Vue, do repositório da internet ou do meu computador?
3 - Se instalar o Vue.js em um projeto globalmente com uma determinada versão e por acaso instalar ele novamente globalmente com uma versão mais nova em outro projeto, o primeiro projeto que está utilizando a versão antiga poderá gerar problemas, o último sobrescreve o anterior ou são alocados dois Vue.js?

A: A principal diferença entre instalar um pacote globalmente é que você passa a executar os comandos na linha de comando, segundo o [doc do npm])https://docs.npmjs.com/getting-started/installing-npm-packages-globally#how-to-install-global-packages):

There are two ways to install npm packages: locally or globally. Choose which kind of installation to use based on how you want to use the package.
If you want to use a package as a command line tool, then install it globally. This way, it works no matter which directory is current. This is the choice you would use if you were installing grunt, for example.
If you want to depend on the package from your own module, then install it locally. This is the choice you would use if you are using require statements, for example.

Traduzido fica assim:

Existem duas maneiras de instalar pacotes: localmente ou globalmente. Escolha que tipo de instalação baseado em como você quer utilizar o pacote.
Se você quer usar o pacote como uma ferramenta de linha de comando, então instale o comando globalmente. Desta maneira, o comando funciona independente de qual diretório você está. Esta é a escolha que você usuário se estivesse instalando o grunt, por exemplo.
Se você quer depender do pacote no seu próprio modulo, então instale-o localmente. Esta é a escolha que você usaria para caso estiver usando require, por exemplo.

*

*Depende do sistema operacional e da configuração realizada, mas geralmente os pacotes ficam localizados dentro da pasta do usuário.

*

*MacOS: /usr/local/lib/node_modules

*Windows: \AppData\Roaming\npm

*Não entendi bem a pergunta de onde é buscado. Ambos comandos npm i com ou sem -g irão baixar o último pacote estável publicado no NPM, lembrando que a versão do pacote que será baixado pode ser outra dependendo do seu arquivo package.json. Documentação

*Se você instalar o vue globalmente não vai fazer diferença pois esse pacote precisa estar instalado localmente (ao menos que você realize um npm link porque ai ele passar a buscar o pacote no global). Documentação

*

*Não tem problema você atualizar o vue-cli pois é uma ferramenta de desenvolvimento.

*Quando você fala em instalar o Vue.js globalmente, você diz instalar o pacote vue-cli, certo? Geralmente não se instala os pacotes cli localmente porque ele é uma ferramenta para utilizar via command line, de acordo com a documentação deles:

The CLI (@vue/cli) is a globally installed npm package and provides the vue command in your terminal. It provides the ability to quickly scaffold a new project via vue create, or instantly prototype new ideas via vue serve. You can also manage your projects using a graphical user interface via vue ui. We will walk through what it can do in the next few sections of the guide.


text:
Q: How to Create a Real-Time Color Map in Python? I am trying to create a real-time colour map. I want to continuously change slightly the RGB values of some elements in the matrix to make up my colour map. I read data from an excel file and a part of my data looks like this

Then I want to show the colour change in my colour map in one figure like a video. I tried this code:
df=pd.read_excel(r"G:\3Y_individualProject\Crop_color_data.xlsx", usecols="C:E")
color_data_2d=np.array(df.iloc[0:101])
color_data_1d=np.reshape(color_data_2d,(300))
color_data=color_data_1d.reshape(5,20,3)

for x in range(5):
    fig, ax = plt.subplots()
    ax.imshow(color_data)
    ax.set_aspect("equal")
    plt.pause(0.05)
    for i in range(3):
        color_data[0,1,i]=color_data[0,1,i]+0.1
        color_data[1,1,i]=color_data[1,1,i]+0.2
        color_data[2,1,i]=color_data[1,1,i]+0.25
        print(color_data)

But it plots many different figures instead of showing them in a figure as I expected. I've also just tried to learn and use matplotlib.animation. I have tried the code below:
from matplotlib import pyplot as plt
import pandas as pd
import numpy as np
from matplotlib import cm
from matplotlib.animation import FuncAnimation
from matplotlib.colors import ListedColormap, LinearSegmentedColormap
import itertools

def changeColor(x):

    fig, ax = plt.subplots()
    ax.imshow(color_data)
    ax.set_aspect("equal")

    for i in range(3):
        color_data[0,1,i]=color_data[0,1,i]+0.1
        color_data[1,1,i]=color_data[1,1,i]+0.2
        color_data[2,1,i]=color_data[1,1,i]+0.25

results=FuncAnimation(plt.gcf(), changeColor, interval=5)

plt.tight_layout()
plt.show()

But with that code, my figure doesn't even display anything. As said I am quite new to matplotlib.animation so can anyone show me how to use matplotlib.animation or any other way to plot a real-time color map in my case, please? Thank you so much!


text:
Q: pandas validating data frame cells I have a non-indexed data frame (read from a csv file) as follows:
John   Mullen  12/08/1993  Passw0rd
Lisa   Bush    06/12/1990  myPass12
Maria  Murphy  30/03/1989  qwErTyUi
Seth   Black   21/06/1991  LoveXmas

I would like to validate each cell of each row against a specific regular expression:

*

*validate birth date as dd/mm/yyyy

*validate the password with the PassRegex below

*validate First name/ last Name with the NameRegex

*below replace ' in the first name with _

*etc...

and then move the row where any of the cells do not validate to a new data frame.
import re
PassRegex = re.compile(r"^(?!.*\s)(?=.*[A-Z])(?=.*[a-z])(?=.*\d).{8,50}$")
NameRegex = re.compile(r"^[a-zA-Z0-9\s\-]{2,80}$")

Is there a way to do this without iterating through the whole data frame row by row, and cell by cell?
Any help is much appreciated.

A:
Is there a way to do this without iterating through the whole data
  frame row by row, and cell by cell?

You don't have to look at every value in every row, but clearly, in every row, you have to look at the columns relevant to your filter/conditional.
from pandas import DataFrame
from dateutil.parser import parse

df = DataFrame([['John', 'Mullen', '12/08/1993',  'Passw0rd'],
... ['Lisa',   'Bush' ,   '06/12/1990',  'myPass12'],
... ['Maria' , 'Murphy',  '30/03/1989',  'qwErTyUi'],
... ['Seth' ,  'Black' ,  '21/06/1991' , 'LoveXmas']])

df.columns = ['name1','name2','date','pwd']

# convert date column to datetime type
df.date = df.date.apply(parse)

>>> df[df.date > parse('1/1/91')]
  name1   name2       date       pwd
0  John  Mullen 1993-12-08  Passw0rd
3  Seth   Black 1991-06-21  LoveXmas

>>> df[df.date <= parse('1/1/91')]
   name1   name2       date       pwd
1   Lisa    Bush 1990-06-12  myPass12
2  Maria  Murphy 1989-03-30  qwErTyUi

>> indexes = df[df.date <= parse('1/1/91')].index
>> new_df = DataFrame(df.drop(indexes))
>>> new_df
  name1   name2       date       pwd
0  John  Mullen 1993-12-08  Passw0rd
3  Seth   Black 1991-06-21  LoveXmas


text:
Q: Why can't I update a p:graphicImage twice after upload a file with p:uploadFile I have been trying to upload an image with a p:uploadFile and it work fine at first time, but after the first uploaded file it not update the p:graphicImage, but if I reload the page the value of the graphicImage is fine and the image is showed. So, I think that is a problem with the primefaces uploadFile component, but I not sure.
My xhtml is this:
<h:form id="formNuevo" size="150%"  enctype="multipart/form-data">

    <h:outputLabel value="Diseño Neumatico: *" />
<p:fileUpload fileUploadListener="#{serviciosVentanaDiseno.manejarUploadedFile}" mode="advanced" auto="true" sizeLimit="9000000000" allowTypes="/(\.|\/)(gif|jpe?g|png)$/" update="mensajes graficImage"/>

<p:graphicImage id="graficImage" styleClass="disenoNeumatico" value="#{serviciosVentanaDiseno.streamedContentImagen}" ajax="true"/>

 </h:form>

and my bean is a @SessionScoped bean, it's here:
public void manejarUploadedFile(FileUploadEvent event) {
    UploadedFile uploadedFile = (UploadedFile)event.getFile();
    try {
        diseno.setImagen(uploadedFile.getContents());
        streamedContentImagen = new DefaultStreamedContent(new    ByteArrayInputStream(diseno.getImagen()));
    } catch (IOException e) {
        //log error
    }
}

public StreamedContent getStreamedContentImagen() {
    return streamedContentImagen;
}

public void setStreamedContentImagen(StreamedContent streamedContentImagen) {
    this.streamedContentImagen = streamedContentImagen;
}

A: Try setting the cache attribute of the graphicImage component to false:
<p:graphicImage cache="false"

A: change scope @SessionScoped then <p:graphicImage cache="false">


text:
Q: How to replace multiple variable from file.txt Inside file form.txt

Name : $name
Gender : $gender
Age : $age

is my code to replace variable in form.txt
const fs = require('fs').promises;

var rForm = await fs.readFile(__dirname + '/form.txt', 'utf8');

var name = 'maman';
var gender = 'male';
var age = 10;

rForm.replace('$name', name);
rForm.replace('$gender', gender);
rForm.replace('$age', age);

console.log(rForm);

and is my result from my code

Name : $name
Gender : $gender
Age : $age

There is noting changed. The result I wanted is

Name: maman
Gender: male
Age: 10

How to change multiple variable in this case ??
I try this
const fs = require('fs').promises;

var rForm = await fs.readFile(__dirname + '/form.txt', 'utf8');

var name = 'maman';
var gender = 'male';
var age = 10;

var nm = rForm.replace('$name', name);
var gn = rForm.replace('$gender', gender);
var ag = rForm.replace('$age', age);

console.log(nm);
console.log(gn);
console.log(ag);`

and the result is

Name : maman
Gender : $gender
Age : $age
Name : $name
Gender : male
Age : $age
Name : $name
Gender : $gender
Age : 10

A: The replace() method returns a new string with one, some, or all matches of a pattern replaced by a replacement.
rForm = rForm.replace('$name', name)
             .replace('$gender', gender)
             .replace('$age', age);

console.log(rForm);

or
rForm = rForm.replace('$name', name);
rForm = rForm.replace('$gender', gender);
rForm = rForm.replace('$age', age);

console.log(rForm);


text:
Q: Android keep alive IntentService I need to keep alive a thread which allows me to send data, even if the app is in background or killed (the user slide the app away or close it).
I know I could use Service or IntentService. Someone told me that with IntentService I can use notification, what I am doing is something like app such as Telegram or Whatsapp which listens continuously for new messages.
I used Service and this is my result :
package test.com.connectionservices.Services;

import android.app.Service;
import android.content.Intent;
import android.os.IBinder;
import android.util.Log;
import java.net.DatagramPacket;
import java.net.DatagramSocket;
import java.net.InetAddress;

public class UDPListenerService extends Service {
    static String UDP_BROADCAST = "UDPBroadcast";

    DatagramSocket socket;

    private void listenAndWaitAndThrowIntent() throws Exception {
        try {
            DatagramSocket clientSocket = null;
            clientSocket = new DatagramSocket();
            String data ;
            byte[] sendData ;
            InetAddress IPAddress = InetAddress.getByName("AN IP");

            int i = 0;
                while (true) {
                data = "TEST THE SERVICE"+i;
                sendData = data.getBytes();
                DatagramPacket sendPacket = new DatagramPacket(sendData, sendData.length, IPAddress, 21);
                clientSocket.send(sendPacket);
                i++;
            }

        } catch (Exception e) {

        }
    }

    private void broadcastIntent(String senderIP, String message) {
        Intent intent = new Intent(UDPListenerService.UDP_BROADCAST);
        intent.putExtra("sender", senderIP);
        intent.putExtra("message", message);
        sendBroadcast(intent);
    }

    Thread UDPBroadcastThread;

    void startListenForUDPBroadcast() {
        UDPBroadcastThread = new Thread(new Runnable() {
            public void run() {
                try {
                    while (shouldRestartSocketListen) {
                        listenAndWaitAndThrowIntent();
                    }
                    //if (!shouldListenForUDPBroadcast) throw new ThreadDeath();
                } catch (Exception e) {
                    Log.i("UDP", "no longer listening for UDP broadcasts cause of error " + e.getMessage());
                }
            }
        });
        UDPBroadcastThread.start();
    }

    private Boolean shouldRestartSocketListen = true;

    void stopListen() {
        shouldRestartSocketListen = false;
        socket.close();
    }
    @Override
    public void onCreate() {
    }

    @Override
    public void onDestroy() {
        stopListen();
    }

    @Override
    public int onStartCommand(Intent intent, int flags, int startId) {
        shouldRestartSocketListen = true;
        startListenForUDPBroadcast();
        Log.i("UDP", "Service started");
        return START_STICKY;
    }
    @Override
    public IBinder onBind(Intent intent) {
        return null;
    }
}

This works fine, if I go in another app or I kill the app using Android (sliding it away in Lollipop) there will be a process in background which flood the reciver.
How could I change it using IntentService? Why should I change, is there a way to use notification with Service?

A: There is no reason for you to use IntentService here. IntentService queues the start commands it receives (from calls to startService()) and executes them serially on a background thread, then stops itself when the queue is depleted. That's not the behavior you want, so don't use it.
To use the service with a notification, use the startForeground() method and provide a Notification object to show. I wouldn't recommend this except for something that should be visible to the user, like a music playback service (with playback controls in the notification).


text:
Q: MVVM-Light EventToCommand UserControl_SizeChanged I used in wired view-code behind to write something like this
private void UserControl_SizeChanged(object sender, SizeChangedEventArgs e)
{
    if (e.NewSize.Width < _originalWidth ||
    .....
}

How I can handle events in Silverlight UserControl itself using EvnentToCommand in MVVMLight.
I tried to add this code in XAML but have no luck.
<i:Interaction.Triggers>
    <i:EventTrigger EventName="SizeChanged">
        <cmd:EventToCommand
            Command="{Binding onSizeChangedRelayCommand, Mode=TwoWay, ElementName=this}" **// Edit: ElementName=this has been removed**
            PassEventArgsToCommand="True">
        </cmd:EventToCommand>
    </i:EventTrigger>
</i:Interaction.Triggers>


text:
Q: Debugging AngularJS Framework I am trying to understand how AngularJS framework works. For that reason I want to debug angularjs framework code (not my application code) however I am not able to figureout how angular gets attached to DOM and starts compilation. Can anybody help me to findout which is piece of code or lines in angularjs script file from where AngularJS kicks off and starts parsing and compilation.

A: you need to read the application bootstrap section in the angular docs, but basically angular will take your html, starts the compilation processes, at which point it will start replacing any custom html or directives with the matching templates, no scopes or bindings done just yet, html might not even be in dom yet, afer that angular goes to linking process, where bindings are made, scopes are created and  html gets attached to DOM, thats the short version you can find it here
https://docs.angularjs.org/guide/bootstrap


text:
Q: sqlalchemy: multiple bases for the same class This is probably very straightforward, but still picking up sqlalchemy and can't seem to find an answer. I have a basic module sometable.py
import config
class SomeTable(config.Base):
    __tablename__ = 'bla'
    def __init__(self, name):
        self.name = name

Now, I want to write a test on this module: basically add a few test rows, do some calculations using the other functions of SomeTable, and check the results. But i don't want to do these manipulations in my main database. how can i pass a different Base object to the class defined in sometable module? Or is there a better way to achieve this?
e.g. my test_sometable.py currently looks like this:
import sometable, config
class TestSomeTable(unittest.TestCase):

    def setUp(self):
        engine = create_engine('sqlite:///:memory:')
        self.Base = declarative_base(config.Base.metadata, engine)

    def test_some_functionality(self):
        tbl = sometable.SomeTable('name1')
        # if i create a session and add a row here,
        # it will add it to my main database, rather than the in-memory one

A: SomeTable uses config.Base as base, it doesn't matter that you define a new Base in your test class. How is your entity supposed to know that it should another base?
i think it should work if you first import config, then replace config.Base with the base you want to use and only after that import sometable. otherwise you have to find another way to use a test configuration instead of the production configuration when running your unittests.


text:
Q: Python 3: Convert CSV My csv file is like this,
1,no,apple,water
2,,grape,
3,yes,,coke
4,no,orange,water
5,no,,water

with some blanks in it
and I'm trying to convert this file to list of dictionaries, which should be,
[{'id': '1', 'yesno': 'no', 'fruit': 'apple', 'drink': 'water'},
{'id': '2', 'fruit': 'grape'},
{'id': '3', 'yesno': 'yes', 'drink': 'coke'},
{'id': '4', 'yesno': 'no', 'fruit': 'orange', 'drink': 'water'},
{'id': '5', 'yesno': 'no', 'drink': 'water'}]

However, it returns,
[{'id': '1', 'yesno': 'no', 'fruit': 'apple', 'drink': 'water'},
{'id': '2', 'yesno': 'no', 'fruit': 'grape', 'drink': 'water'},
{'id': '3', 'yesno': 'yes', 'fruit': 'grape', 'drink': 'coke'},
{'id': '4', 'yesno': 'no', 'fruit': 'orange', 'drink': 'water'},
{'id': '5', 'yesno': 'no', 'fruit': 'orange', 'drink': 'water'}]

It seems like the blank values are filled with the copied one from the previous dictionary
Here is my code,
import csv
def data(file):
    header = ['id', 'yesno', 'fruit', 'drink']
    list_data = []
    dict_record = {}
    var = 0
    csv_r = list(csv.reader(open(file)))
    while var < len(csv_r):
        for i in range(4): #since there are 4 fields
            if csv_r[var][i] != '':
                dict_record[header[i]] = csv_r[var][i]
        list_data.append(dict_record.copy())
        var = var + 1
    return(list_data)

A: Python comes with a csv parser, don't re-invent the wheel:
In [1]: import csv

In [2]: with open('example.csv') as f:
   ...:     reader = csv.DictReader(f, fieldnames=['id', 'yesno', 'fruit', 'drink'])
   ...:     data = list(reader)
   ...:

In [3]: data
Out[3]:
[{'drink': 'water', 'fruit': 'apple', 'id': '1', 'yesno': 'no'},
 {'drink': '', 'fruit': 'grape', 'id': '2', 'yesno': ''},
 {'drink': 'coke', 'fruit': '', 'id': '3', 'yesno': 'yes'},
 {'drink': 'water', 'fruit': 'orange', 'id': '4', 'yesno': 'no'},
 {'drink': 'water', 'fruit': '', 'id': '5', 'yesno': 'no'}]

It seems like the blank values are filled with the copied one from the previous dictionary

There is no previous dictionary, fundamentally the problem with your approach is that you keep reusing the same dictionary, so of course the old values are always there. Just use a new dictionary:
In [6]: with open('example.csv') as f:
   ...:     data = []
   ...:     names = ['id', 'yesno', 'fruit', 'drink']
   ...:     for line in f:
   ...:         items = line.strip().split(',')
   ...:         data.append({k:v for k,v in zip(names, items)})
   ...:
   ...:

In [7]: data
Out[7]:
[{'drink': 'water', 'fruit': 'apple', 'id': '1', 'yesno': 'no'},
 {'drink': '', 'fruit': 'grape', 'id': '2', 'yesno': ''},
 {'drink': 'coke', 'fruit': '', 'id': '3', 'yesno': 'yes'},
 {'drink': 'water', 'fruit': 'orange', 'id': '4', 'yesno': 'no'},
 {'drink': 'water', 'fruit': '', 'id': '5', 'yesno': 'no'}]

And if you really don't want to include the empty fields, you can do something like:
In [8]: with open('example.csv') as f:
   ...:     data = []
   ...:     names = ['id', 'yesno', 'fruit', 'drink']
   ...:     for line in f:
   ...:         items = line.strip().split(',')
   ...:         data.append({k:v for k,v in zip(names, items) if v})
   ...:

In [9]: data
Out[9]:
[{'drink': 'water', 'fruit': 'apple', 'id': '1', 'yesno': 'no'},
 {'fruit': 'grape', 'id': '2'},
 {'drink': 'coke', 'id': '3', 'yesno': 'yes'},
 {'drink': 'water', 'fruit': 'orange', 'id': '4', 'yesno': 'no'},
 {'drink': 'water', 'id': '5', 'yesno': 'no'}]

General advice: don't use while-loops when you can easily use a for-loop. File-objects are iterable, just do for line in f:, and for that matter, always use a with statement to use files (i.e. use context-managers), and don't materialize the whole thing, i.e. don't do list(csv.reader(open(file))) unless you actually want a list-of-lines. Also, don't use index-based loops if you don't have to, learn about the handy iterators in python, like enumerate and zip.
Even better yet, don't reinvent the wheel:
In [10]: with open('example.csv') as f:
    ...:     reader = csv.DictReader(f, fieldnames=['id', 'yesno', 'fruit', 'drink'])
    ...:     data = [{k:v for k,v in row.items() if v} for row in reader]
    ...:

In [11]: data
Out[11]:
[{'drink': 'water', 'fruit': 'apple', 'id': '1', 'yesno': 'no'},
 {'fruit': 'grape', 'id': '2'},
 {'drink': 'coke', 'id': '3', 'yesno': 'yes'},
 {'drink': 'water', 'fruit': 'orange', 'id': '4', 'yesno': 'no'},
 {'drink': 'water', 'id': '5', 'yesno': 'no'}]


text:
Q: Cant add data to Gridview I am trying to make a simple Gridview application and I have found an example on the internet and made some changes. I have one problem and am confused about one thing. The problem is I can't add data to gridview in edit mode. I set a breakpoint at Gridview RowCommand Property and saw that all the textbox values are empty. It's probably a silly mistake but I don't know where it is. And there is one more thing, while adding data we use this code:
(e.CommandName.Equals("ADD"))

I didn't understand but there is no (e.CommandName.Equals("Update")) or anything like that in the code. How is the update button triggered in this case?.
Thanks in advance.
This is My Code:
<asp:GridView ID="gvEmployeeDetails" runat="server" Width="600px"
     AutoGenerateColumns="false" ShowFooter="true"
     onrowcommand="gvEmployeeDetails_RowCommand"
     onrowdeleting="gvEmployeeDetails_RowDeleting"
     onrowupdating="gvEmployeeDetails_RowUpdating"
     onrowcancelingedit="gvEmployeeDetails_RowCancelingEdit"
     onrowediting="gvEmployeeDetails_RowEditing"
     HeaderStyle-BackColor="#4D4D4D"
     HeaderStyle-ForeColor="White">
     <Columns>
         <asp:TemplateField HeaderText="Employee ID">
             <ItemTemplate>
                 <asp:Label ID="lblEmpID"
                     runat="server"
                     Text='<%#DataBinder.Eval(Container.DataItem, "empid") %>'>
                 </asp:Label>
             </ItemTemplate>
             <EditItemTemplate>
                 <asp:Label ID="lblEditEmpID"
                     runat="server"
                     Text='<%#DataBinder.Eval(Container.DataItem, "empid") %>'>
                 </asp:Label>
             </EditItemTemplate>
             <FooterTemplate>
                 <asp:TextBox ID="txtAddEmpID" runat="server" Width="100px">
                 </asp:TextBox>
             </FooterTemplate>
         </asp:TemplateField>

         <asp:TemplateField HeaderText="Name">
             <ItemTemplate>
                 <asp:Label ID="lblName" runat="server"
                     Text='<%#DataBinder.Eval(Container.DataItem, "name") %>'>
                 </asp:Label>
             </ItemTemplate>
             <EditItemTemplate>
                 <asp:TextBox ID="txtEditName" runat="server"
                     Text='<%#DataBinder.Eval(Container.DataItem, "name") %>'>
                 </asp:TextBox>
             </EditItemTemplate>
             <FooterTemplate>
                 <asp:TextBox ID="txtAddName" runat="server" Width="100px">
                 </asp:TextBox>
             </FooterTemplate>
         </asp:TemplateField>

         <asp:TemplateField HeaderText="Designation">
             <ItemTemplate>
                 <asp:Label ID="lblDesignation" runat="server"
                     Text='<%#DataBinder.Eval(Container.DataItem, "designation") %>'>
                 </asp:Label>
             </ItemTemplate>
             <EditItemTemplate>
                 <asp:TextBox ID="txtEditDesignation" runat="server"
                     Text='<%#DataBinder.Eval(Container.DataItem, "designation") %>'>
                 </asp:TextBox>
             </EditItemTemplate>
             <FooterTemplate>
                 <asp:TextBox ID="txtAddDesignation" runat="server" Width="150px">
                 </asp:TextBox>
             </FooterTemplate>
         </asp:TemplateField>

         <asp:TemplateField HeaderText="City">
             <ItemTemplate>
                 <asp:Label ID="lblCity" runat="server"
                     Text='<%#DataBinder.Eval(Container.DataItem, "city") %>'>
                 </asp:Label>
             </ItemTemplate>
             <EditItemTemplate>
                 <asp:TextBox ID="txtEditCity" runat="server"
                     Text='<%#DataBinder.Eval(Container.DataItem, "city") %>'>
                 </asp:TextBox>
             </EditItemTemplate>
             <FooterTemplate>
                 <asp:TextBox ID="txtAddCity" runat="server" Width="80px">
                 </asp:TextBox>
             </FooterTemplate>
         </asp:TemplateField>

         <asp:TemplateField HeaderText="Country">
             <ItemTemplate>
                 <asp:Label ID="lblCountry" runat="server"
                     Text='<%#DataBinder.Eval(Container.DataItem, "country") %>'>
                 </asp:Label>
             </ItemTemplate>
             <EditItemTemplate>
                 <asp:TextBox ID="txtEditCountry" runat="server"
                     Text='<%#DataBinder.Eval(Container.DataItem, "country") %>'>
                 </asp:TextBox>
             </EditItemTemplate>
             <FooterTemplate>
                 <asp:TextBox ID="txtAddCountry" runat="server" Width="80px">
                 </asp:TextBox>
             </FooterTemplate>
         </asp:TemplateField>

         <asp:TemplateField HeaderText="Action">
             <ItemTemplate>
                 <asp:ImageButton ID="imgbtnEdit" runat="server" CommandName="Edit"
                     ImageUrl="~/Images/icon-edit.png" Height="32px" Width="32px"/>
                 <asp:ImageButton ID="imgbtnDelete" runat="server" CommandName="Delete"
                     ImageUrl="~/Images/Delete.png"/>
             </ItemTemplate>
             <EditItemTemplate>
                 <asp:ImageButton ID="imgbtnUpdate" runat="server" CommandName="Update"
                     ImageUrl="~/Images/icon-update.png"/>
                 <asp:ImageButton ID="imgbtnCancel" runat="server" CommandName="Cancel"
                     ImageUrl="~/Images/icon-Cancel.png"/>
             </EditItemTemplate>
             <FooterTemplate>
                 <asp:LinkButton ID="lbtnAdd" runat="server" CommandName="ADD"
                     Text="Add" Width="80px">
                 </asp:LinkButton>
              </FooterTemplate>
          </asp:TemplateField>

      </Columns>
  </asp:GridView>

And this is the aspx.cs file:
SqlConnection conn = new SqlConnection("Data Source=localhost\\sqlexpress;Database=Northwind;User Id=sa ;Password=1234");
    protected void Page_Load(object sender, EventArgs e)
    {
        BindData();
    }

    void BindData() {

        DataSet ds = new DataSet();
        DataTable FromTable = new DataTable();
        string cmd = "select * from EmployeeDetails";

        SqlDataAdapter adp = new SqlDataAdapter(cmd, conn);
        adp.Fill(ds);
        FromTable = ds.Tables[0];

        if (FromTable.Rows.Count > 0)
        {
            gvEmployeeDetails.DataSource = FromTable;
            gvEmployeeDetails.DataBind();
        }
        else {
            FromTable.Rows.Add(FromTable.NewRow());
            gvEmployeeDetails.DataSource = FromTable;
            gvEmployeeDetails.DataBind();
            int TotalColumns = gvEmployeeDetails.Rows[0].Cells.Count;
            gvEmployeeDetails.Rows[0].Cells.Clear();
            gvEmployeeDetails.Rows[0].Cells.Add(new TableCell());
            gvEmployeeDetails.Rows[0].Cells[0].ColumnSpan = TotalColumns;
            gvEmployeeDetails.Rows[0].Cells[0].Text = "No records Found";
        }
    }
    protected void gvEmployeeDetails_RowUpdating(object sender, GridViewUpdateEventArgs e)
    {

///dont post this part It works
    }
    protected void gvEmployeeDetails_RowEditing(object sender, GridViewEditEventArgs e)
    {
        gvEmployeeDetails.EditIndex = e.NewEditIndex;
        BindData();
    }
    protected void gvEmployeeDetails_RowDeleting(object sender, GridViewDeleteEventArgs e)
    {

    }
    protected void gvEmployeeDetails_RowCommand(object sender, GridViewCommandEventArgs e)
    {

        if (e.CommandName.Equals("ADD"))
        {
            TextBox txtAddEmpID = (TextBox)gvEmployeeDetails.FooterRow.FindControl("txtAddEmpID");
            TextBox txtAddName = (TextBox)gvEmployeeDetails.FooterRow.FindControl("txtAddName");
            TextBox txtAddDesignation = (TextBox)gvEmployeeDetails.FooterRow.FindControl("txtAddDesignation");
            TextBox txtAddCity = (TextBox)gvEmployeeDetails.FooterRow.FindControl("txtAddCity");
            TextBox txtAddCountry = (TextBox)gvEmployeeDetails.FooterRow.FindControl("txtAddCountry");

            conn.Open();
            string cmdstr = "insert  EmployeeDetails values(@empid,@name,@designation,@city,@country)";
            SqlCommand cmd = new SqlCommand(cmdstr, conn);
            cmd.Parameters.AddWithValue("@empid", txtAddEmpID.Text);
            cmd.Parameters.AddWithValue("@name", txtAddName.Text);
            cmd.Parameters.AddWithValue("@designation", txtAddDesignation.Text);
            cmd.Parameters.AddWithValue("@city", txtAddCity.Text);
            cmd.Parameters.AddWithValue("@country", txtAddCountry.Text);
            cmd.ExecuteNonQuery();
            conn.Close();
            BindData();
        }
    }
    protected void gvEmployeeDetails_RowCancelingEdit(object sender, GridViewCancelEditEventArgs e)
    {
        gvEmployeeDetails.EditIndex = -1;
    }

A: You are binding the gridview on the page load, so every time the page loads the text and other controls gets cleared.
Can you bind data only if not ispostback and check?
protected void Page_Load(object sender, EventArgs e)
    {
    if(!IsPostBack)
    {
        BindData();
    }
    }

Regarding your question,
You have a link button with Command name Edit. This is the name of the command which grid view uses to trigger the edit mode for the selected row. Youn can add any type of command controls here, as far as the command name is "Edit", the edit mode will be triggerred. If you dont add this control, and set AutoGenerateEditButton=true, then by default gridview will generate and edit button, with "Edit" as the command name.


text:
Q: Combining two arrays and transformation using Jolt I am having a tough time using Jolt mapping trying to transform the input to the necessary form
Input JSON
{
  "data": [
    {
      "name": "Alcohol",
      "collection_id": 123,
      "properties": [
        {
          "name": "Tax",
          "property_id": "00001"
        },
        {
          "name": "Expenditure",
          "property_id": "00002"
        }
      ],
      "attributes": [
        {
          "name": "alcohol_tax",
          "attribute_id": "00011"
        },
        {
          "name": "alcohol_expenditure",
          "attribute_id": "00022"
        }
      ]
    }
  ]
}

Output JSON
[
    {
        "name": "Alcohol",
        "collection_id": 123,
        "details": [{
                "property_name": "Tax",
                "property_id": "00001",
                "attribute_id": "00011"
            },
            {
                "property_name": "Expenditure",
                "property_id": "00002",
                "attribute_id": "00022"
            }
        ]
    }
]

I have tried a couple of ways to combine the arrays using a few rules but with little success.
One of the rules
[{
    "operation": "shift",
    "spec": {
      "data": {
        "*": {
          "name": "&1.name",
          "collection_id": "&1.collection_id",
          "attributes": {
            "*": {
              "attribute_id": "&1.attribute_id[]"
            }
          },
          "properties": {
            "*": {
              "name": "&1.myname[]",
              "property_id": "&1.property_id[]"
            }
          }
        }
      }
    }
}]

is adding all the attributes and properties to all the collections.I do not know why this happens as I thought &1.property_id[] would only add items in that particular collection to the array and not all collections. Any help/clues on why this is happening would be truly appreciated.

A: See solution below:

*

*[0] creates the wrapping array

*[&1] uses the position of the respective arrays so the results are combined in details the important part is wrapping square brackets so its treated as array rather than literal.

[
  {
    "operation": "shift",
    "spec": {
      "data": {
        "*": {
          "name": "[0].name",
          "collection_id": "[0].collection_id",
          "attributes": {
            "*": {
              "attribute_id": "[0].details.[&1].attribute_id"
            }
          },
          "properties": {
            "*": {
              "name": "[0].details.[&1].name",
              "property_id": "[0].details.[&1].property_id"
            }
          }
        }
      }
    }
  }
]

Produces the following:
[
  {
    "name": "Alcohol",
    "collection_id": 123,
    "details": [
      {
        "attribute_id": "00011",
        "name": "Tax",
        "property_id": "00001"
      },
      {
        "attribute_id": "00022",
        "name": "Expenditure",
        "property_id": "00002"
      }
    ]
  }
]


text:
Q: I am trying to install and use ProtoBuf for Windows .NET C# and I am having problems I just installed protobuf for Java and that is working great.
I am now trying to install protobuf for .NET 4.0 for C# language.
First of all the protobuf website does not have any install instructions.
I downloaded the latest binaries, which are mostly dlls.
Where do I put these dlls?
Also there is a protoc compiler but it only has an output option for C++, not C#.
Where is there a C# option?
I created a test file, which is an exact copy of the example on this page and I am getting errors(Error 1 - expected top level statement)?
https://code.google.com/p/protobuf-net/wiki/GettingStarted
    [ProtoContract]
class Person {
    [ProtoMember(1)]
    public int Id {get;set;}
    [ProtoMember(2)]
    public string Name {get;set:}
    [ProtoMember(3)]
    public Address Address {get;set;}
}
[ProtoContract]
class Address {
    [ProtoMember(1)]
    public string Line1 {get;set;}
    [ProtoMember(2)]
    public string Line2 {get;set;}
}

A: You need to download protobuf project from below link :
Proto Buf C# project Download Link
Install Package manager steps :
enter link description here
If Package manager is not available in you VS IDE. then down load from below link :
Package manager console download link
To generate protobuf Library for C#: follow below steps :
1) Open downloaded project in Visual studio
2) Goto package manager and type below command
  PM> Install-Package protobuf-net

3) Above command will generate libraries for protobuf.
      (i) Google.ProtocolBuffers
      (ii) Google.ProtocolBuffers.Serialization
I hope this helps :)


text:
Q: Nomenclature concordance in R I have to do what is called a nomenclature concordance in R for categorizing product codes, which requires a right join operation from one version of product codes to a new version (through a one to many or less commonly many to one correspondence table):

  #Dataset:
  products<-c("030799","030789","219090")
  tradevalue<-c("150","50","75")
  df<-data.frame(products,tradevalue)

  #Correspondance table:
  products <- c("030799","030799","030799","030789","030789","219090")
  products.new <-c("030749","030784","030788","030783","030787","219090")

  #the new trade value has to be divided by the number of new generated rows
  tradevalue.new<-df$tradevalue / ???

  #so here it would be divided by 3, 2 and 1 for the examples above
  tradevalue.new<-c("50","50","50","25","25","75")

  concord<-data.frame(products, products.new, tradevalue.new)

  new <-right_join(df,concord)

So instead of the original 3 rows in df, there are now 6 rows in new, but the total trade value for each product remains the same but is equally distributed to the new product categories in the new version, but the divisor is the number of new lines for each product.
Can you please help?

A: Starting with numerical data,
df <- structure(list(products = c("030799", "030789", "219090"), tradevalue = c(150, 50, 75)), class = "data.frame", row.names = c(NA, -3L))
concord <- structure(list(products = c("030799", "030799", "030799", "030789", "030789", "219090"), products.new = c("030749", "030784", "030788", "030783", "030787", "219090"), tradevalue.new = c(50, 50, 50, 25, 25, 75)), class = "data.frame", row.names = c(NA, -6L))

we can do
library(dplyr)
right_join(df, concord, by = "products") %>%
  group_by(products) %>%
  mutate(tradevalue.new2 = tradevalue / n()) %>%
  ungroup()
# # A tibble: 6 x 5
#   products tradevalue products.new tradevalue.new tradevalue.new2
#   <chr>         <dbl> <chr>                 <dbl>           <dbl>
# 1 030799          150 030749                   50              50
# 2 030799          150 030784                   50              50
# 3 030799          150 030788                   50              50
# 4 030789           50 030783                   25              25
# 5 030789           50 030787                   25              25
# 6 219090           75 219090                   75              75

If there is a risk that one product in df will be repeated, then you can pre-define a row id:
df %>%
  mutate(rn = row_number()) %>%
  right_join(concord, by = "products") %>%
  group_by(rn) %>%
  mutate(tradevalue.new2 = tradevalue / n()) %>%
  ungroup()
# # A tibble: 6 x 6
#   products tradevalue    rn products.new tradevalue.new tradevalue.new2
#   <chr>         <dbl> <int> <chr>                 <dbl>           <dbl>
# 1 030799          150     1 030749                   50              50
# 2 030799          150     1 030784                   50              50
# 3 030799          150     1 030788                   50              50
# 4 030789           50     2 030783                   25              25
# 5 030789           50     2 030787                   25              25
# 6 219090           75     3 219090                   75              75