text:
Q: CGI program timeout when reading/writing, respectively, from/to stdin/stdout I have tested this program from the shell, and it works correctly when redircting stdin from a file.  However, when operating as a CGI program, it times out (TimeForCGI hiawatha webserver setting is set to 30 seconds).  This program is contained in just one file.  It should be noted that this program was written only to physically verify what I have been reading about C.G.I., and I chose C (or anything else that generates a binary executable) so I can be sure that these things have been untouched by any interpreter, as might be done to facilitate their abstractions.
#define _GNU_SOURCE
#include <stdio.h>
#include <stdlib.h>
#include <string.h>
#include <errno.h>
#include <error.h>

int main (void);

int
main
(void)
{
  static char buf[BUFSIZ];
  size_t size;

  if (setvbuf (stdout, NULL, _IOFBF, BUFSIZ) != 0)
    error (EXIT_FAILURE, errno, "setvbuf(), stdout");
  if (setvbuf (stdin, NULL, _IOFBF, BUFSIZ) != 0)
    error (EXIT_FAILURE, errno, "setvbuf(), stdin");
  if (setvbuf (stderr, NULL, _IOLBF, BUFSIZ) != 0)
    error (EXIT_FAILURE, errno, "setvbuf(), stderr");
  printf ("Content-Type: text/plain\n\n");
  if (fflush (stdout) == EOF)
    error (EXIT_FAILURE, errno, "fflush()");
  for (;;)
    {
      size = fread (buf,1, BUFSIZ, stdin);
      if (size == 0)
        {
          if (feof (stdin) != 0)
            goto quit;
          else
            error (EXIT_FAILURE, errno, "fread(), stdin");
        }
      size = fwrite (buf, 1, size, stdout);
      if (size == 0)
        error (EXIT_FAILURE, errno, "write(), stdout");
    }
 quit:
  fflush (stdout);
  return EXIT_SUCCESS;
}

Here is the corresponding html form;

    <title>Form</title>

    <form action="form-process.cgi" method="post">
      input_a: <input name="input_a" type="text">

      input_b: <input name="input_b" type="text">

      <input type="submit" value="Submit">
    </form>

A: Your program attempts to read from its standard input until it reaches its end.  That's fine when you redirect the input from a file, but it is inappropriate for a CGI program.  The web server in which the CGI runs is not obligated to signal end-of-file on the input when the end of the request body is reached.  If it does not, then your program will block indefinitely in fread().
There are several reasons why EOF might not be signaled at the end of the request body.  The RFC explicitly postulates the presence of extension data, but it is also plausible that the server connects the CGI's standard input directly to the network socket on which the request is coming in.  EOF will not normally be detected there until and unless the client closes its end of the connection, which many clients do not do between requests, and which many of the rest do not do until after they have received the response.
Accordingly, the CGI specifications in RFC 3875 say "the script MUST NOT attempt to read more than CONTENT_LENGTH bytes, even if more data is available" (section 4.2).  The CONTENT_LENGTH is conveyed to the script via an environment variable of that name, provided that the request specifies one.  Your CGI must not read more bytes than the variable specifies, and it must not read any bytes if the content length is not specified at all.  On the other hand, it is at the CGI's not required to read the whole request body, or any of it at all.

A: In the meantime I have done this;
#define _GNU_SOURCE
#include <stdio.h>
#include <stdlib.h>
#include <string.h>
#include <errno.h>
#include <error.h>
#include <dstralg.h>

int main (void);

int
main
(void)
{
  int l;
  int i;

  if (setvbuf (stdin, NULL, _IOFBF, BUFSIZ)!= 0)
    error (EXIT_FAILURE, errno, "sevbuf(), stdin");
  if (setvbuf (stdout, NULL, _IOFBF, BUFSIZ)!= 0)
    error (EXIT_FAILURE, errno, "sevbuf(), stdout");
  printf ("Content-Type: text/plain\n\n");
  l = atoi (getenv ("CONTENT_LENGTH"));
  for (i = 0; i < l; ++i)
    putchar (getchar ());
  return EXIT_SUCCESS;
}

which exhibits the desired behavior.  The full buffering greatly reduces the overhead of processing one character at a time, and is only a function call once getchar and putchar have been unwound (assuming libc has been dynamically linked).  As this is only experimental code using data from Hiawatha, which I trust, I didn't bother checking the return values of getchar and putchar being  error conditions.  Nor did I bother to check if CONTENT_LENGTH was NULL or "".  In practice, I would use a domain specific interpretted language, such as PHP, for small projects with light traffic.  I would probably use C/C++ for demanding workloads, although FastCGI can improve performance by the lighter operation of opening and closing connection to a unix domain socket in place of the heavier operation of forking a child process with the expense of creating page tables and all the other process management book keeping.

A: The following code, from your last post, should do also:
#define _GNU_SOURCE
#include <stdio.h>
#include <stdlib.h>
#include <string.h>
#include <errno.h>
#include <error.h>
#include <dstralg.h>

int main (void);

int
main
(void)
{
    int l;
    int i;

    printf ("Content-Type: text/plain\n\n");
    l = atoi (getenv ("CONTENT_LENGTH"));
    for (i = 0; i < l; ++i)
        putchar (getchar ());
    fflush(stdout);
    return EXIT_SUCCESS;
}

and without the final fflush(stdout); also, because you are going to exit(2) inmediately, after last putchar(3);, and that will make stdio to flush all buffers remaining.


text:
Q: Filter a given Column(count) based on timestamp Column in Pandas Dataframe
*

*I have a Pandas Dataframe which looks like below

*

*I want my Output or Visualization Plots which tell:

*During which Hour, how many Jobs have failed,completed (count)

A: First filter by boolean indexing only rows filled by Failed and then use crosstab with DataFrame.plot.bar:
df1 = df[df['Status'].eq('Failed')]
out = pd.crosstab(df1['Hour'], df1['Job'])

out.plot.bar()

A: import pandas as pd

df = pd.read_csv('./data.csv')

# status
status = set(df['Status'])
dfStatus = {s: df[df['Status'] == s] for s in status}

# hours
hours = set(df['Hour'])
dfStatusPerHour = {}

# calculate them explicitly
for s in status:
    dfStatusPerHour[s] = {h: dfStatus[s][dfStatus[s]['Hour'] == h].shape[0] for h in hours}

# show results
for s in status:
    print(f"{s} : {dfStatusPerHour[s]}")

redpajama_set_name: RedPajamaStackExchange


text:
Q: Objective-C: Singleton I'm trying to make a singleton but I keep running into an error and am not sure what I am doing wrong:
Here's my .h file:
#import <Foundation/Foundation.h>

@interface ColorMaker : NSObject {

}

+(ColorMaker* )sharedColorMaker;

- (UIColor* ) setColor : (float) red : (float) green : (float) blue;

@end

Here's the .m
#import "ColorMaker.h"

@implementation ColorMaker

+(ColorMaker *)sharedColorMaker {

static ColorMaker* sharedColorMaker;

@synchronized(self) {

    if (!sharedColorMaker)

        sharedColorMaker = [[ColorMaker alloc] init];

    return sharedColorMaker;

}

}

- (UIColor* ) setColor:(float)red :(float)green :(float)blue {

float newRed = red/255;
float newGreen = green/255;
float newBlue = blue/255;

UIColor* colorToReturn = [UIColor colorWithRed:newRed green:newGreen blue:newBlue alpha:1.0];

return colorToReturn;
}

@end

in viewcontroller, viewDidLoad:
- (void)viewDidUnload {
[super viewDidUnload];

ColorMaker* thisColorMaker = [ColorMaker sharedColorMaker];
}

keep getting "Use of undeclared identifier ColorMaker" error.


text:
Q: Show loading status In my sample application using JSF2.0 + Richfaces3.3.3.
I want to show loading status for all a4j action.
It means, when i click button, then show loading status in modal panel.
Otherwise, When i click button, show loading status and at the same time no more a4j action for before complete that process.
After complete that process, i do other action or click same button.
In my following sample code, i show loading status for button action. but i can multiple click same button during loading time.
So i need to prevent any action during loading time.
<f:view>
   <html>
      <head>
          <meta http-equiv="Content-Type" content="text/html; charset=UTF-8">
      </head>
      <body>
            <h:form id="sampleForm" binding="#{Sample.initForm}">

            <a4j:commandButton value="Sample"
                               action="#{Sample.sampleButtonAction}"/>

            <a4j:status>
                <f:facet name="start">
                    <h:graphicImage value="ai.gif" alt="ai"/>
                </f:facet>
            </a4j:status>

        </h:form>
</body>
</html>
</f:view>

Sample.java
package myapp.beans;
import javax.faces.component.html.HtmlForm;

public class Sample
{
    private HtmlForm initForm;

   public String sampleButtonAction()
   {
    System.out.println("Sample Button assigned....");

    for(int i=1; i<=10; i++)
    {
        try
        {
            Thread.sleep(1000);
        }
        catch (InterruptedException ex)
        {
            System.out.println("Exception occured....");
        }
    }
    return null;
}

public HtmlForm getInitForm(){

    return initForm;
}

public void setInitForm(HtmlForm initForm){
    this.initForm = initForm;
}
}

Help me,
Thanks in advance

A: <a4j:status
    onstart="#{rich:component('procesoEsperaPopupPanel')}.show(); return false;"
    onstop="#{rich:component('procesoEsperaPopupPanel')}.hide(); return false;">
</a4j:status>

<rich:popupPanel id="procesoEsperaPopupPanel" autosized="true" moveable="true">
    <h:graphicImage name="ai.gif" alt="ai"/>
</rich:popupPanel>

A: Try this
<h:form id="sampleForm" binding="#{Sample.initForm}">

  <a4j:commandButton value="Sample" action="#{Sample.sampleButtonAction}"/>

    <a4j:status
         onstart="javascript:Richfaces.showModalPanel('progressWaitModalPanel');"
           onstop="javascript:Richfaces.hideModalPanel('progressWaitModalPanel');">

     </a4j:status>

    <rich:modalPanel  id="progressWaitModalPanel" autosized="true" moveable="true" >
           <h:graphicImage value="ai.gif" alt="ai"/>
    </rich:modalPanel>

 </h:form>


text:
Q: Have error output include last couple lines of code Is it possible, and if so, how would you make error output include the last couple lines of code? I know about GNU g++'s support for __LINE__ and __FUNC__ but those only give the line number as an int and the function name as a string - I'd like to dump the function that failed's code or at least the last several commands executed by the program.
I was thinking maybe write a m4 script that would parse through the code base and inject string structures of the functions they're put in (excluding themselves, of course).
Any other/better ideas?

A: Do not change your code at all.  Use __LINE__ and __FUNC__ and post process the error output.  That is, run your program as my-prog > $(tty) 2>&1 | post-process where post-process has access to your code base and can generate the desired text.  You might want to modify the code slightly by adding tags to make it easier for post-process to find the function name and line number.


text:
Q: database sharding on mysql I need to do database sharding(horizontal) based on MySQL. My database schema is as following:

*

*I have tables A,B,C

*A,B is Global(which need not to be sharding)

*C have huge data so it need to be sharding to achieve write scalability.

*I will have several sharding,each contains one copy of A,B, and a subset of C.

My questions are:

*

*How could i keep A,B on all sharding consistent,i.e, replicate A,B on all sharding so that they should have exactly same data. Or just store the Global Tables on single DB and cache via memcached?

*How to do high availability for each sharding,i.e, if one sharding  crashed due to unknown reasons how could i do fail over.Through MySQL backup or master-master AP mode replica?

*How to do load balance for Global tables A,B on the multiple shardings?

Note that i will not use MySQL read replicas in this case.

A: It is possible for you to do this yourself rather than using commercial products like dbShards or ScaleBase but you will end up building the same thing and it isn't trivial.
To answer your question though, it makes sense to replicate A and B across all shards so you either need your application to duplicate the writes across all shards or you will need some replication technology to do this. I don't think you can easily configure MySQL replication to do this.
To load balance you will need your client to randomly choose a shard when running queries against these tables, just like you'll need your client to determine which shard to use when accessing table C.
For HA you will want to have master/slave setup for each shard so that you can failover in the case of losing a master shard.
Regards,
Andy Grove
Chief Architect
http://www.dbshards.com

A: *

*Keep Global Tables A,B on Global DB,saying that DB1. Which all data need to be cached via memcached.

*HA via mysql master-master replica. Only write to the Active server.

*Since Global data on DB1, so no necessary to do load balance. Just getGlobalDBConnection() is enough.

A: You have asked multiple questions in your single question - Sharding, High Availability and Load Balancing. These are vast topics in themselves.
There are lot of resources available on Internet on these technologies. I suggest you should first read about them and you can always come back on StackOverflow if you are unclear on some concept or you get stuck somewhere in implementing these.
Thanks.
EDIT:
I would like to share a link which I just found:
How to implement MySQL Sharding
Hope it helps.

A: I work for ScaleBase, which is a maker of a complete scale-out solution an "automatic sharding machine" if you like, analyzes the data and SQL stream, splits the data across DB nodes, load-balances reads, and aggregates results in runtime – so you won't have to!
ScaleBase supports and maintains global tables transparently and safely, also enable high availability over replicated MySQLs for each "shard", read-repl and failover are configurable and automatic.
True, it's a commercial product, but developing it all in-house is such a pain... And even after all that pain it'll never be a complete as ScaleBase with the support for the application and the administration around it.
I invite you to see a demo of everything you wrote in your 1,2,3 in 5 mins.
Also, take a look on my post in http://database-scalability.blogspot.com/ about Pinterest, then and now...
I hoped I helped!


text:
Q: .NET Is it possible to share large in-memory collection between processes? I have a console application which runs hundred times a day and reads same data from large files (say 50 files with total size of 3-4 Gb).
I am thinking of making a Windows service which will cache the data in memory to speed the access and also control life time of the data (as set of those 50 files may vary from day to day).
I am going to implement shared memory mapped files so the console application will read files from memory written by the service...
However there is another consideration. The data read is converted to .NET objects every time.
So my question - is there a way to share not files but .NET objects (List) in memory?
P.S. the data is series of bytes serialised manually

A: I would just implement this as a service that provides a socket-server, and have the console exe just connect to the service and make a request over TCP/IP, getting the response back. Pretty easy to setup, since you already (per the question) have serialization sorted, and very scalable. The service can then keep everything running happily in memory. You can even have the client and server be the same exe - just check Environment.UserInteractive when it starts to decide whether to be a client vs a server.
One note: keep the bandwidth low, and avoid a chatty API; meaning: don't have the client do lots of thinking then make 200 requests; just have it package up the entire request and ship it to the server. Let the server worry about that all locally, avoiding lots of network traffic.

A:
is there a way to share not files but .NET objects (List) in memory?

Being picky - no, no way, allocated object is on a specific process.
You can uise thigns like remoting, but then you basically marshal access between processes.
You can share non-managed space (shared memory), but this can not contain .NET objects - requires marshalling into those.

A: *

*if you are running this app hundred times per day and you are looking for a way to keep the "data" in memory why don't you keep you the application running instead of close it and restart it again?

*You could create a windows service that load the files in memory and does the elaboration on them. Of course if you stop or restart the service it will need to reload the data

*Another solution would be that instead of keeping in memory objects (which it can be done only using .Remoting or something similar) why don't you import the files into a Data Base which will speed up the process and it can be easily shared between processes?

A: To my knowledge, you can't directly share the collections between multiple .NET processes, but will have to marshal the data across process boundaries. This has a fair amount of CPU overhead, and will consume memory for the objects in both the cache-process and the client.
You could probably achieve something somewhat better with memory mapped files, but that still doesn't allow you to directly map .NET objects on the shared memory - but you say that "the data is series of bytes serialised manually", so it might be a close enough fit?
I don't quite grok the .NET memory mapped files, the great thing from native code is that you simply treat files as memory pointers, whereas with .NET MMF you need to call accessor methods, and thus do memory copying into .NET objects(?)... but it could probably perform better than reading the files over and over.


text:
Q: Form hidden input So, I want to input a value inside the form which is hidden. This value will be a an id of a current user, thus the user doesnt need to input anything.
Till now I did this code in the form but still, the id is being inputted as NULL:
echo $this->Form->hidden("id",
[
    "options" => $currentUserr
]);

$currentUser is the Id of the current user in the website. How can I place that value inside the DB ?

A: Your input must have the name attribute. Once done, you can retrieve all your request parameters, even the hidden fields.

A: I think you can do it like
echo $this->Form->input("id",['type'=>'hidden',
"options" => $currentUser]);

You can take notes from http://book.cakephp.org/2.0/en/core-libraries/helpers/form.html
BUT - that said - you shouldnt actually use either one of those. And omit any fields that serve no real purpose for the view and its form. Instead you should inject those fields into the data array prior to saving. See http://www.dereuromark.de/2010/06/23/working-with-forms/

A: You can try like this
 //First you get hidden field value

    $current_user_id = $this->request->data("id");

//and then save that data to database table

  $this->User->save(array('id' => $current_user_id));


text:
Q: Can agile help a lone developer who codes as a hobby? Agile development is a very useful methodology. Is it realistic to apply this to a lone developer who codes as a hobby (I also code for a living in a team where I have learnt agile from)? Things like stories, scheduled retrospectives, etc, can be useful (Even if I am asking myself things)?
Thanks

A: Yes, Agile is a lot about Getting Things Done (the real meaning, not the book, see below). It's about getting trough procrastination too. I've found that Agile methodologies tend to solve mostly psychological problems. In fact, most problems we encounter in software development are not technical, but psychological.
I have many projects where I'm the only one involved, and yet I've my own backlog, sprint backlog, my own information radiator, I apply the same "done" definition rules, reviews, retrospectives, ...
But no, I'm not doing standups meeting alone or with my cat :)
I've read many books about productivity improvements before I discovered agile methodologies. And what I've observed is that agile is very similar to them.
For exemple, Scrum is a lot about Getting Things Done, and others well known books on the subject.
That book certainly saved my life at a certain point. So get it and read it. It will helps you "get it", I mean, understanding what Agile means. Trying to do Agile not understanding it will leads you to failure.

A: Certainly, though some of the practices may not apply or may feel a bit silly.
Breaking your work into stories and timeboxing your development can definitely help even if your all alone.
Test-Driven-Development is really an individual process anyway, and certainly is useful as a solo developer.
Pair-programming would require schizophrenia however.  Daily standup meetings would probably go much more quickly...
There was some talk of this on Ward's Wiki years ago, which might be worth a look.

A: Is it realistic to apply this to a lone developer who codes as a hobby (I also code for a living in a team where I have learnt agile from)? Things like stories, scheduled retrospectives, etc, can be useful (Even if I am asking myself things)?
Definitely yes and it worked for me. I have tried doing it myself and it definitely makes me more productive. A good way to try it without the need of buying a whole lot of office supplies is using ScrumWorks (google danube) which is freeware for the basic version. You can add products, releases, user stories. tasks, and see burn down charts etc.
Doing a retrospective by yourself would be a little weird and it may make people in your house think you are losing your marbles while you talk to yourself out loud but that is just my opinion. What I do is I write down the Retrospective notes on a soft document and attach it to the Sprint or a Backlog in ScrumWorks.
Hoping this will help you.


text:
Q: Delphi Classes to XML representation: Using Delphi XE:
XML data binding wizard generates Delphi class based on XML/XSD - works great.
BUT I also need to go the other way: Convert Delphi classes into XML. I don't find any support for that in XE. (I know this is quite simple to accomplish with C#, .NET, but obviously, since Delphi doesn't really support Reflection it's a lot more difficult than with C#)
One option I do have it is write the class in C# with SharpDevelop and use the MS utility (which I believe is a free download) to generate XML from the C# code. I also have VS 2005 that supports this, but it's not installed and I'd prefer not get to involved with it).
Anyone have a suggestion as to how to go about getting this done: Straight from Delphi to XML/XSD? An open source tool would be nice, or some good units that will do this.

A: The NativeXml and OmniXML open source libraries can convert Delphi objects to XML (not XSD). They support object serialization and deserialization even with Delphi versions before 2010.
So it would be possible to use them in a first step to create a XML file, which then can be passed to the Data Binding Wizard for Delphi class code generation.

A: Robert Love wrote an article in late 2009 covering that topic: Xml Serialization - Basic Usage. It uses the "new" RTTI available as of Delphi 2010.


text:
Q: Interfacing AutoCAD with JAVA Any idea on interfacing with AutoCAD through a JAVA program. I am looking for a solution that can directly interface with an AutoCAD session (even start one), the way it works with the .NET extensions of AutoCAD. Or any way to work with ObjectARX through JAVA, definitely not writing a complete JNI wrapper over it.
Added: We are looking for something in open-source. In case there is none, we are ready to create one in open-source if someone can lend a helping hand explaining how it can be done. We have taken a look at JNA and JaWin. JNA clubbed with JNI might help but is too ugly. JaWin on the other hand has not been updated in the past 4 years, so sort of skeptical using it.

A: The only thing I can think of is to use a Java <-> .Net bridge like JNBridge. I've used this in other scenarios and it works fine. Never done any work with Java and AutoCad though so there might be other cheaper solutions.

A: If you are trying to interact with the AutoCAD application you will have a tough time.
If you want to interact with the dwg files themselves there is the Open Design Alliance which has libraries that allow working with dwg files without AutoCAD.

A: You can try to use the JavaBeans ActiveX bridge and the COM Automation to open AutoCAD and manipulate it.
That said, JavaBeans ActiveX bridge hasn't evolved in a while (I used it back in 2003) and Autodesk is seriously investing in .Net for everything related to extensions and automation in AutoCAD.

A: We are working on a similar project. What we are doing is writing the integration code in C#, and the business logic for our project in Java.
We are utilizing a C++ bridge that utilizes JNI to take Java calls down to C++, and then translates them back up to C#, and vice versa.  Each function that needs to go from C# to Java has to be implemented in the bridge code.  This is fairly involved, and there are some issues with getting the unmanaged C++ code to work with the C#, as well as the standard overhead of translating Jstrings into C# Strings and the like. The result is relatively fast, after we did some optimizations to insure that we aren't starting and stopping the JVM for each call into the Java layer.
We previously used COM objects which were called by the AutoCAD plugin, so that would be another approach.


text:
Q: What is the use of legacy URL routing mechanism in Joomla 1.5 I came across this option of enabling it in the Legacy plugin of Joomla. Now I know that Legacy Plugin is used to make older templates of Joomla compatible with the new one. But what is Legacy URL Routing Mechanism. Please answer it in easily understood language - I am a noob.

A: The Legacy plugin is actually used for most 1.0 extensions, not just templates. This was supposed to be a temporary solution for running 1.0 extensions on 1.5 sites until developers had a chance to rewrite the extensions for the newer MVC architecture. J!1.0 used a different routing system for search engine friendly URLs which is not compatible with the 1.5 routing system. In order for extensions running in Legacy mode to have SEF URLs you would need to enable this option in the plugin.
That being said, I wouldn't use an extension that requires legacy mode at all. Not only is there a small performance hit, but code that old has potential for security issues. It's been 3 years, it should have been rewritten by now. Not to mention there is no Legacy mode in 1.6 so there are no upgrade options for that extension.


text:
Q: How can I go back to the start of while loop, without breaking it? I have a while loop containing many if's:
public ArrayList<Position> findPath(Position destination) {
        boolean pathToDestinationCreated = false;
        boolean xReached = false;
        boolean yReached = false;
        int reachableX = 0;
        int reachableY = 0;
        int reachableXY = 0;

        int isUnreachable = 0;
        Position myPos = myPlayer().getPosition();
        ArrayList<Position> finalPath = new ArrayList<Position>();
        if (destination != null) {
            Position toAdd;
            while (!pathToDestinationCreated) {
                if (myPos.getX() != destination.getX() && myPos.getY() != destination.getY()) {
                    if (myPos.getX() < destination.getX() && myPos.getY() < destination.getY()) {
                        toAdd = new Position(myPos.getX() + 1, myPos.getY() + 1, myPos.getZ());
                        if (canReach(toAdd)) {
                            finalPath.add(toAdd);
                            myPos = toAdd;
                            isUnreachable = 0;
                        } else {
                            isUnreachable = 1;
                        }
                    } else if (myPos.getX() > destination.getX() && myPos.getY() < destination.getY()) {
                        toAdd = new Position(myPos.getX() - 1, myPos.getY() + 1, myPos.getZ());
                        if (canReach(toAdd)) {
                            finalPath.add(toAdd);
                            myPos = toAdd;
                            isUnreachable = 0;
                        } else {
                            isUnreachable = 1;
                        }
                    } else if (myPos.getX() > destination.getX() && myPos.getY() > destination.getY()) {
                        toAdd = new Position(myPos.getX() - 1, myPos.getY() - 1, myPos.getZ());
                        if (canReach(toAdd)) {
                            finalPath.add(toAdd);
                            myPos = toAdd;
                            isUnreachable = 0;
                        } else {
                            isUnreachable = 1;
                        }
                    } else if (myPos.getX() < destination.getX() && myPos.getY() > destination.getY()) {
                        toAdd = new Position(myPos.getX() + 1, myPos.getY() - 1, myPos.getZ());
                        if (canReach(toAdd)) {
                            finalPath.add(toAdd);
                            myPos = toAdd;
                            isUnreachable = 0;
                        } else {
                            isUnreachable = 1;
                        }
                    }
                }

I'm gonna skip the rest of the code because a wall of text isn't going to help.
I'd like to go back to the beginning of my while loop, whenever finalPath.add(toAdd) is invoked. How would I do this?


text:
Q: How can I get python in the command prompt on Windows? I have just installed Python on my Windows 7. I thought that after that I will be able to run python on the command prompt but it is not the case. After the installation I also found out that I can run the python command shell. This is nice. But what should I do if I want to save my program in a file and then I want to run this program (in Linux, for example, I typed "python file_name.py" in the command line).

A: You need to add the python bin directory to your path. Follow the instructions here and add c:\python26\bin to the path (unless you installed python in a non-default location).

A: Is python.exe in your windows path? Try to look at the PATH environment variable and see if the installation folder of python is listed there.

A: You need to update your environment variables to include the path to the Python executable.
On XP you can do this by right clicking on "My Computer" -> Properties and then going to the "Advanced" tab.


text:
Q: docker-compose - Multiple containers with same service I would like to create 2 containers with almost same settings except environment variables.
Tried severals things without success especially the .override.yml (passing multiple .yml to docker-compose overriding the previous one).
# docker-compose.yml
version: '3.7'
services:
  web:
    image: nginx
    container_name: test-web
    ports:
      - 80:80

Now the other one
# docker-compose.override.yml
version: '3.7'
services:
  web:
    container_name: dupe-web
    ports:
      - 8080:80

Doing :
$ docker-compose -f docker-compose.yml -f docker-compose.override.yml up -d
Recreating test-web ... done

Kills me the test-web container and starts the new one name dupe-web.
Is there a way to have both launched using same service?
In my case I would like to create two containers:

*

*one for developers

*one for staging (almost same settings except env as said)

Any help would be welcome.

A: If you name the service the same, you override it. So your file name docker-compose.override.yml is actually very fitting.
I think that's logical and desired. How else would you be able to override, and what would be the name of the service in the second file? Compose had to choose one for you in some way. After all, it wouldn't make sense, imo.
You can use YAML anchors/overrides for your needs, but they have to be in the same file for that to work.
name: example
services:
  web: &web
    image: nginx
    container_name: test-web
    ports:
      - 80:80
  web2:
    <<: *web
    container_name: dupe-web
    ports:
      - 8080:80

I would also recommend removing the container name.
name: example
services:
  test-web: &web
    image: nginx
    ports:
      - 80:80
  dupe-web:
    <<: *web
    ports:
      - 8080:80

If you run docker compose config you can see the normalized spec:
name: example
services:
  dupe-web:
    image: nginx
    networks:
      default: null
    ports:
    - mode: ingress
      target: 80
      published: "8080"
      protocol: tcp
  test-web:
    image: nginx
    networks:
      default: null
    ports:
    - mode: ingress
      target: 80
      published: "80"
      protocol: tcp
networks:
  default:
    name: example_default


text:
Q: Calling StartActivityForResult() in Activity for multiple times for scanner I have two button in my activity to scan. But how can i differentiate between each one in on activityForResult? I know I should be using StartActivityforResult() and pass a number for each scan but I couldn't figure out how to do it with integrator.
  ibBinScan.setOnClickListener(new View.OnClickListener() {
            @Override
            public void onClick(View v) {
                scan();
            }
        });

  ibNumberScan.setOnClickListener(new View.OnClickListener() {
            @Override
            public void onClick(View v) {
                scan();
            }
        });

    public void scanNow() {
        IntentIntegrator integrator = new IntentIntegrator(InboundActivity.this);
        integrator.setCaptureActivity(Portait.class);
        integrator.setOrientationLocked(false);
        integrator.setBeepEnabled(false);
        integrator.setBarcodeImageEnabled(false);
        integrator.setDesiredBarcodeFormats(IntentIntegrator.ALL_CODE_TYPES);
        integrator.setPrompt("Scan Barcode");
        integrator.initiateScan();
    }

    @SuppressLint("SetTextI18n")
    @Override
    public void onActivityResult(int requestCode, int resultCode, @Nullable Intent data) {
        IntentResult result = IntentIntegrator.parseActivityResult(requestCode, resultCode, data);

        if (result != null) {
            if (requestCode == 1) {}
            if (requestCode == 2) {}

        } else super.onActivityResult(requestCode, resultCode, data);
    }

A: you can use :
integrator.setRequestCode(REQUEST_CODE);

A: IntentIntegrator fro zxing does have a request code setter for Intent. Try this way :-
public static final int REQ_CODE1=23;
public static final int REQ_CODE2=25;

public void scanNow(int requestCode) {
    IntentIntegrator integrator = new IntentIntegrator(InboundActivity.this);
    integrator.setCaptureActivity(Portait.class);
    integrator.setOrientationLocked(false);
    integrator.setBeepEnabled(false);
    integrator.setBarcodeImageEnabled(false);
    integrator.setDesiredBarcodeFormats(IntentIntegrator.ALL_CODE_TYPES);
    integrator.setPrompt("Scan Barcode");
    integrator.setRequestCode(requestCode)
    integrator.initiateScan();
}

@Override
public void onActivityResult(int requestCode, int resultCode, @Nullable Intent data) {
    super.onActivityResult(requestCode, resultCode, data);
    if((requestCode==REQ_CODE1 || requestCode==REQ_CODE2) && resultCode==RESULT_OK){
        IntentResult result = IntentIntegrator.parseActivityResult(requestCode, resultCode, data);
        if(requestCode==REQ_CODE1){

        }else(requestCode==REQ_CODE2){

        }
    }else{

    }
}


text:
Q: Convergence of a sum of series I was reading the famous "Calculus" by Spivak and at the beginning of the chapter on infinite series, he states: "It's an easy exercise to prove that if both $\displaystyle \sum_{k=1}^{\infty}a_n$ and $\displaystyle \sum_{k=1}^{\infty}b_n$ exist, then $\displaystyle \sum_{k=1}^{\infty}a_n+b_n$=$\displaystyle \sum_{k=1}^{\infty}a_n$+$\displaystyle \sum_{k=1}^{\infty}b_n$". So I did it then. But after some pages he states that a rearrengament of the terms may change the limit. Then he proves that if $\displaystyle \sum_{k=1}^{\infty}|a_n|$ converges, any rearrengment of the terms wil converge to the same value. And so I started to think...How did I prove the asertion at the beginning of the chapter? It was just changing the order! Since $\displaystyle \sum_{k=1}^{\infty}a_n+b_n$ indeed means $\lim a_1+b_1+a_2+b_2+...+a_n+b_n$, it should(I thought) be the same than $\lim a_1+a_2+...+a_n+b_1+b_2+...+b_n=\displaystyle \sum_{k=1}^{\infty}a_n$+$\displaystyle \sum_{k=1}^{\infty}b_n$. So, where is the mistake? Should it be proved in another way?

A: By definition, the series $\sum_{n=1}^{\infty}a_n$ exists and equals $A$ if and only if $$\lim_{n \to \infty}S_n=A$$where $S_n$ denotes the $n^{\text{th}}$ partial sum (i.e. $S_1=a_1$, $S_2=a_1+a_2$, etc.). Note that the $S_n$ form a sequence of real numbers. Now, assume that $\sum_{n=1}^{\infty}a_n=A$ and $\sum_{n=1}^{\infty}b_n=B$. We wish to show that $\sum_{n=1}^{\infty}(a_n+b_n)=A+B$. In other words, we wish to show that the limit of the partial sums of $\sum_{n=1}^{\infty}(a_n+b_n)$ is $A+B$. Let $S_{n}^A$ and $S_{n}^B$ denote that partial sums of $\sum_{n=1}^{\infty}a_n$ and $\sum_{n=1}^{\infty}b_n$ respectively. Fix $\epsilon>0$. By convergence, we know that there exists an $N\in \mathbb{N}$ such that $$n> N \Rightarrow |S_{n}^A-A|<\frac{\epsilon}{2}, |S_{n}^B-B|<\frac{\epsilon}{2}$$Now, note that the $n^{\text{th}}$ partial sum  of $\sum_{n=1}^{\infty}(a_n+b_n)$ is equivalent to $S_{n}^A+S_{n}^B$ (i.e. $S_n^{A+B}=S_n^A+S_n^B$, where $S_{n}^{A+B}$ denotes the $n^{\text{th}}$ partial sum of $\sum_{n=1}^{\infty}(a_n+b_n)$).

Now, using the same $N$ as above we have that for $n>N$, $$|S_n^{A+B}-(A+B)|=|(S_n^A-A)+(S_n^B-B)|\leq |S_n^A-A|+|S_n^B-B|<\frac{\epsilon}{2}+\frac{\epsilon}{2}=\epsilon$$Thus, by the definition of convergence, the sequence $S_{n}^{A+B}$ of partial sums of $\sum_{n=1}^{\infty}(a_n+b_n)$  converges to $A+B$ and therefore $\sum_{n=1}^{\infty}(a_n+b_n)=A+B$

A: In other words, you did not make any mistake. We know for all $K$:
$$ \underbrace{\sum_{n=1}^K [a_n + b_n]}_{r_K} = \underbrace{\sum_{n=1}^K a_n}_{w_K} + \underbrace{\sum_{n=1}^K b_n}_{z_K} $$
So $r_K = w_K + z_K$ for all $K$.
You do not know yet if $r_K$ has a limit as $K\rightarrow\infty$, but if you are told that $w_K$ and $z_K$ both have a finite limit, we know by basic limit facts that
$$\lim_{K\rightarrow\infty} r_K = \lim_{K\rightarrow\infty}w_K + \lim_{K\rightarrow\infty} z_K$$
The reason this does not have any divergence problems, even if $a_n = (-1)^n/n$, is that you are still taking the values $\{w_1, w_2, w_3, ...\}$ and $\{z_1, z_2, z_3, ...\}$ in the same relative order, both when they are grouped together and when they are grouped separately.

Another way of interpreting this that may help:  Suppose $\{a_n\}_{n=1}^{\infty}$ is a real valued sequence such that $\sum_{n=1}^{\infty}|a_n|=\infty$. This does not necessarily mean that every different ordering for summing the $a_n$  terms will lead to a different sum.  Many different orders will in fact lead to the same sum. In particular, suppose  you fix an order $\{a_1, a_2, a_3, ...\}$.  You now separate the terms into two groups without changing the relative ordering within each group: Suppose the first group pulls out a subsequence of the $a_n$ terms that happen to sum to a finite number $x$ (in that relative order). Suppose the remaining terms (which form the second group) also happens to sum to a finite number $y$ (in that relative order).  Then  the original sum will converge to $x+y$ in any order that alternates between the first and second groups, provided that you are not changing the relative ordering within each group.
For example, you can sum the first 4 terms of group 1, then the first 8 terms of group 2, then the next 3 terms of group 1, then the next 100 terms of group 2, and so on. It will give you the same result $x+y$, provided your way of alternating eventually includes all terms and preserves the relative ordering of terms for each group.


text:
Q: C# Late binding command COM obj commands fails due to desired copy back setting I know I should write this in Vb.net but for my own reasons I'm attempting late binding against a Com Object in C# .net framework 3.5. The error I'm getting is "DISP_E_BADCALLEE" and I'm only getting that based on when the copybacks I want are set to true. Am I dealing with a security issue? My research lead me to try dropping "[assembly: AllowPartiallyTrustedCallers()]" in the AssemblyInfo file but that didn't do the trick. I dropped some details in a condensed version of the code below. It's failing on the 4th step. I'd appreciate your help. Thanks.
                //step 1
        _atlDirectorObject = Activator.CreateInstance(Type.GetTypeFromProgID("atlDirectorObject.atlDirector"));
        //step 2
        object[] parms = { "3270", 1, true, true, 0, _atl3270Tool, _ErrMsg };
        Boolean[] CopyBack2 = new Boolean[7];
        CopyBack2[5] = true;  //atl3270Tool
        CopyBack2[6] = true;  //ErrMsg

        Microsoft.VisualBasic.CompilerServices.NewLateBinding.LateCall(_atlDirectorObject, _atlDirectorObject.GetType(), "CreateTool", parms, null, null, CopyBack2, false);
        _atl3270Tool = parms[5];

        //step 3
        // now using _atl3270Tool we navigate mainframe screens
        object[] parms3 = { Screen, SubScreen, _Number, _ErrMsg };
        Microsoft.VisualBasic.CompilerServices.NewLateBinding.LateCall(_atl3270Tool, _atl3270Tool.GetType(), "ShowScreen", parms3, null, null, null, false);

        //>>>>>>>>>>>>>>CODE FAILS ON THIS STEP<<<<<<<<<<<<
        //step 4
        Boolean[] CopyBack4 = new Boolean[5];
        CopyBack4[3] = true; //screentext
        CopyBack4[4] = true; //_errmsg
        object ScreenText = String.Empty;
        object[] parms4 = { Row, Col, Length, ScreenText, _ErrMsg};
        Microsoft.VisualBasic.CompilerServices.NewLateBinding.LateCall(_atl3270Tool, _atl3270Tool.GetType(), "ReadScreen", parms4, null, null, CopyBack4, false)

        // if it were working the code would read screen data into parms4[3] object
        // If CopyBack4[3 and/or 4] are set to true = error
        // Is just CopyBack4[0,1,2] are true = no error but no result
        //Errors out with "Invalid callee. (Exception from HRESULT: 0x80020010 (DISP_E_BADCALLEE))"

        return Convert.ToString(parms4[3]);

A: ScreenText should be set to null, not string.empty


text:
Q: Redirect / reload browser I want to display popup window that closes once user is auhenticated and redirects user to home page. For backward compatibility login page can display in browser and not in popu window.
index.jsp
<%--@elvariable id="USER" type="cz.literak.demo.oauth.model.entity.User"--%>
<c:if test="${not empty USER}">

        Logged as ${USER.firstName} ${USER.lastName}, Logout
        <c:if test="${not USER.areRegistered('TW,FB,GG')}">
            Improve Login
        </c:if>

</c:if>
<c:if test="${empty USER}">

        Login

</c:if>

Once authenticated, popup/browser is redirected to logged.jsp. It shall redirect main window to home page and close popup window, if login.jsp was opened in it.

It seems to be working with one exception. If browser already displays index.jsp, then nothing happens. I tried location.reload(true), but it caused infinite loop in popup instead.
How can I make it work? Thanks

A: You can use;

Edit:
Another possible solution:
When user logged in, just refresh parent window. In your system, you need to check if user logged in or not in an interceptor like something. When parent window refreshed, if user logged in, it will be redirected to registered area, else it will redirected to login page if current page is registered page. In your loggedin.jsp, you can only use;


text:
Q: QML C++ Signals-Slot not overloaded I have spent the whole day on this code and couldn't figure out what is the problem.
This is the error:
* ISO C++ forbids declaration of 'cppReturnAnswer' with no type [-fpermissive]

* 'int HandleTextField::cppReturnAnswer(QVariant)' cannot be overloaded

* with 'void HandleTextField::cppReturnAnswer(QVariant)'

And this the code:
//handletextfield.h
class HandleTextField : public QObject
{
    Q_OBJECT
public:
signals:
    void cppReturnAnswer(QVariant data); // ERROR HERE
public slots:
    std::string text;
    QString color = QString::fromStdString(text);
    emit cppReturnAnswer(QVariant(color)); // ERROR HERE
};

which is used respectively in program
// in .. handletextfield.cpp
...
void HandleTextField::handleSubmitTextField(const QString &in)
{   qDebug() << "c++: HandleTextField::handleSubmitTextField:" << in;

    text="green";
    QString color = QString::fromStdString(text);
    emit cppReturnAnswer(QVariant(color));
}

// in main.cpp
...
QObject *topLevel = engine.rootObjects().at(0);
QQuickWindow *window = qobject_cast<QQuickWindow *>(topLevel);
// connect - from QML to C++ ---- WORKS NICE
QObject::connect(window, SIGNAL(submitTextField(QString)),
                     &handleTextField, SLOT(handleSubmitTextField(QString)));
// connect - from C++ to QML  ---- NOT WORKING
QObject::connect(&handleTextField,
                 SIGNAL(cppReturnAnswer(QVariant)),
                 window,
                 SLOT(qmlUpdateData(QVariant)));

// in main.qml
...
function qmlUpdateData(text){
    // hack(msg designer:: imperative code not supported in Qt Quick)
    page.color=text // gotdata from C++ backend
}

Any suggestions and comments are highly appreciated.


text:
Q: How to integrate using integrate.simpson over a portion of a sample I am trying to integrate a function over the first 16 frames. Currently it integrates each every frame for the entire 32 frames. I am trying to set the interval to be from 0 to 16 by using the x-axis parameter. However, I keep getting the "ValueError: If given, length of x along axis must be the same as y" error. Here is the code.
       # Calculates area under curve of average trace and adds it to area array
for cell in range(cells_total):
    for sample in range(samples_total):
        average_trace = np.mean(data[cell,sample],axis=0)
        areas_under_curves[cell,sample] = integrate.simpson(average_trace[:,0],32)

return areas_under_curves

average_trace.shape gives the output (32,). The individual values range from 0 to 0.001.
Any advice?


text:
Q: UITextField not working inside a UITabBarController with IOS5 Are there any restrictions on a UITextField when placed inside a tabview which not the main interface. In other words
Working fine scenario
1. A tab based application, with one of the view having a UITextField.
2. The tabview is the main interface for the application.
This works fine without any glitches
Not-working so fine scenario.
1. A tab based application, but the tab view is not the mainview.
2. There is another view MainWindow.xib with some intro animation, which then calls and shows the tabview.
3. UITextfield in such tabviews does'nt seem to work - especially in IOS5. Both methods work fine till IOS 4.3
4. The textfield is visible, but tapping it does not show any keyboard, if i call becomeFirstResponder via code, the keyboard is shown but is not responsive.
Any suggestions
The code is pretty standard
in the AppDelegate
- (BOOL)application:(UIApplication *)application didFinishLaunchingWithOptions:(NSDictionary *)launchOptions
{

    tabViewController = [[tabView alloc] initWithNibName:@"tabView" bundle:nil];
    [self.window addSubview:tabViewController.view];
     //self.window.rootViewController=tabViewController
    [self.window makeKeyAndVisible];
    return YES;
}

tabViewController has a ProfileViewController with a simple textfield.
The textfield works fine if i do this
- (BOOL)application:(UIApplication *)application didFinishLaunchingWithOptions:(NSDictionary *)launchOptions
{

tabViewController = [[tabView alloc] initWithNibName:@"tabView" bundle:nil];
profileView=[[Profile alloc] initWithNibName:@"Profile" bundle:nil];
//calling the view directly without using a tab view
[self.window addSubview:profileView.view];
[self.window makeKeyAndVisible];
return YES;

}
Is there something else that needs to be done for IOS5 when the tab view is not the main interface? I have been cracking my head at this for a few days, all my apps with a UITextfield  inside a tabview are not usable in ios5. Any help is highly appreciated
Edit: Uploaded the project file http://www.mediafire.com/?xjuc4udlph78saj - XCode 4.2 on Lion
It is a simple project with two options, Creating a tabbarcontroller from the delegate itself, and i also have a view(tabView) with a tabbarcontroller. There are 2 views for the tabbar FirstViewController & SecondViewController.
In the AppDelegate.m if using method 1(create UITabBarController inside AppDelegate, all is well). If i choose to add a subview of tabView, the uitextfield does not work.
I have not really handled the releasing of objects, since this is test project and it is only for proof of concept.
Thanks

A: After hours of searching, fiddling and experimenting. I have found out the solution.
This seems to happen when there are more than one UIWindow in the application.
In my case, i was diong this

*

*AppDelegate starts off with its own UIWindow  Once i have played some
startup animations, i try to display another view with a
tabbarcontroller, and ofcoures a window to hold the UITabBarController
The second window (even after setting it to makeKeyAndVisible) seems
to be blocking keyboard events fore UITextField inside the
UITabBarController.
The following has worked for me:
Rather than having the second view with its own window, i had it with a UITabBarController, and a UIView/UIWindow(this is for the sake of having a default view for the nib file). And when i needed to show the tabbarview i have used this
[[[UIApplication sharedApplication] keyWindow] setRootViewController:TabBar]

I am not sure of a better way, but that have worked for me. In short, i have found that having another UIWindow inside the app causes issues with becomeFirstResponder.


text:
Q: Which HTTP Method is used to send SOAP messages? Which HTTP Method is used to send SOAP messages?
I guess, if you are working at the servlet level,you could define the HTTP method(would there still be restrictions?).
But if all that is hidden, and I'm using a simple JAX WS webservice, which HTTP method would(should??) the request and response messages have?

A: I think JAX-WS and most other implementations use post for transmitting requests
you can verify it by capturing the request in TCP IP monitor


text: Q: using esp32 as i2c slave but raspberry is not detecting I was connecting esp32 to raspberry pi as i2c slave but raspberry not detecting esp32 on i2cdetect -y 1. please help me if anyone have any solution


text:
Q: this is from npm selfcore , this script is good for 2 hours and then stop working without errors... how can I resolve this script is  good for 2 hours and then stop working without errors... how can I resolve
import selfcore from "selfcore";
const client = new selfcore('Token')
const gateway = new selfcore.Gateway('Token');
gateway.on("message",(m) => {
    if(m.channel_id  === ""){
    let content = m.content ? m.content : {embeds : [m.embeds[0]]};
    client.sendWebhook("URL",m.channel_id + content);
    };

});


text:
Q: Install Whonix on Ubuntu 18.04.1 I followed the instructions for installing Whonix on Linux and I got stuck at installing Virtualbox from Debian backports. I get the following errors after step 3 (here):
W: GPG error: http://cdn-fastly.deb.debian.org/debian stretch-backports InRelease: The following signatures couldn't be verified because the public key is not available: NO_PUBKEY 8B48AD6246925553 NO_PUBKEY 7638D0442B90D010
E: The repository 'http://http.debian.net/debian stretch-backports InRelease' is not signed.
N: Updating from such a repository can't be done securely, and is therefore disabled by default.
N: See apt-secure(8) manpage for repository creation and user configuration details.

I tried to replace the recommended line
sudo su -c "echo -e 'deb http://http.debian.net/debian stretch-backports main contrib' > /etc/apt/sources.list.d/backports.list"

with
sudo su -c "echo -e 'deb http://ftp.debian.org/debian stretch-backports main' > /etc/apt/sources.list.d/backports.list"

I got that information from the Debian website:
https://backports.debian.org/Instructions/
Note:
I removed the old backports.list before adding the new with following command:
sudo rm /etc/apt/sources.list.d/backports.list

Well I get quite the same error with the recommended instructions on the Debian site. I wonder now, what to do. Can't I just install virtualbox from the Ubuntu repo? It's a little confusing, since the references on the whonix page at the end of the line "Package virtualbox should be installed from Debian backports." are not working. The browser is just jumping at the top of the site.

A: These instructions are for Debian. Backports only required in case of Debian since VirtualBox is unavailable in stretch.
Please install VirtualBox using the usual mechanisms of your Linux distribution.


text:
Q: In Excel (Mac), how to modify the Legend to include content from multiple columns In Office 365 Excel for Mac, I have a simple bar chart showing growth percentage for various entities. The names for each data point that are in the legend are picked up from the first column, but I would like to reformat the legend labels to add content from another column.
Right now, the horizontal axis labels, which is used for the Legend, is selected as follows:
='Current Quarter'!$B$26:$B$43
The B column contains simple strings; in my case, social media handles ( "IndigenousYouth" for example). I am trying to get it to show the content of that column, followed by a space, followed by the open parenthesis, followed by the C column, followed by the closed parenthesis. In other words:
Indigenous Youth (250,509)
The end result would be a legend where each label would be followed by the main current value for it (in parentheses).
How can I edit the axis label text to make this work?

A: I'm putting this as an answer, although it arrived in a comment to the question, because it solves the problem.
The easiest way to achieve this goal is to simply create another column in the table and use a formula to build the text for the legend label as desired:
 =B1&" ("&C1&")"

This would result in that particular column showing the data from columns B and C formatted specifically:
Column B (Column C)
Then simply pick this new column as the source for the legend. Depending on how the data in these columns is formatted, you may need some additional formatting parameters in the formula, but the beauty is that you have complete flexibility of excel formulas to get any kind of data and formatting that you can then present in charts, as axis or legend labels.


text:
Q: When a fully charged capacitor is used to charge another capacitor, how does voltage disappear? I understand that the voltages of both capacitors must be equal, but how does some of the voltage end up disappearing after calculating the charge of each capacitor here:
How does charge redistribute when a charged capacitor is connected to an uncharged capacitor?
The total voltage between the two capacitors has been reduced. Why is this?

A: Calculations, based on conservation of charge, show that, for a charged capacitor, A, connected to an identical, initially uncharged, capacitor, B, the new voltage between the plates of A or B is half the original voltage between the plates of A.
I assume that you can do calculations of this type, but are seeking a more intuitive reason for the voltage falling. You need to start with a good concept of voltage, or, in this case, potential difference (pd). The pd between the plates of a capacitor is the work you would need to do to take a small 'test' charge, $q$, from one plate to the other, divided by $q$. In other words
$$\text{pd between plates}=\frac{\text{work needed}}{q}.$$
That's what potential difference or voltage means!
When you have connected the capacitors together, A has lost (to B) half the charge on each of its plates. This halves the electric field strength in the gap between the plates. It therefore halves the force on $q$. So the work needed to take $q$ from one plate to the other is halved – so the potential difference is halved!
Charge and energy are conserved quantities (though energy can be transferred from one 'form' to another). Voltage is not a conserved quantity, so there's nothing odd about what happens to the voltage when you connect capacitors together. What is, at first sight, odd, is that the total energy stored in A and B together is half what you started with, in A. Half the energy has gone missing! But energy is never lost or gained, only transferred! Can you figure out what has happened to 'the missing half'?


text:
Q: Why does the latest version of the forge viewer break my onClick listener? Summary
The most recent version of the forge viewer (6.6.0) throws an "unexpected token" error in my console and some of my $(button).on('click') event will not longer bind in my custom panels (the requested model does load despite the errors)
What I've tried
I backed the viewer off to version 6.5.0 and my code works, I also removed all code except the initialization logic and I still get the console errors.
I also have tried every method of binding the event I can think of and none work in the latest viewer version ($(document).on('click', 'myButton', this.onMyButtonClick), $('#myButton).click(this.onMyButtonClick), $('myButton').bind('click', this.onMyButtonClick), $('myButton').on('click', this.onMyButtonClick))
Code
Viewer links
<link rel="stylesheet" href="https://developer.api.autodesk.com/modelderivative/v2/viewers/6.*/style.min.css" type="text/css">
<script src="https://developer.api.autodesk.com/modelderivative/v2/viewers/6.*/viewer3D.min.js"></script>

Initialization logic
const options = {
    env: `AutodeskProduction`,
    getAccessToken: getForgeToken
  };
  const documentId = `urn:${urn[`urn_string`]}`;

  Autodesk.Viewing.Initializer(options, function onInitialized() {
    Autodesk.Viewing.Document.load(documentId, onDocumentLoadSuccess, onDocumentLoadFailure);
  });

  function onDocumentLoadSuccess(doc) {
      $(`.navbar-div`).css(`margin-bottom`,`10px`);
      const viewable = Autodesk.Viewing.Document.getSubItemsWithProperties(doc.getRootItem(), {
        'type': `geometry`,
        'role': `2d`
      }, true);
      if (viewable.length === 0) {
        return;
      }

      const initialViewable = viewable[0];
      const svfUrl = doc.getViewablePath(initialViewable);
      const modelOptions = {
        sharedPropertyDbPath: doc.getPropertyDbPath()
      };

      const viewerDiv = document.getElementById(`viewer`);
      viewer = new Autodesk.Viewing.Private.GuiViewer3D(viewerDiv);

      viewer.start(svfUrl, modelOptions, onLoadModelSuccess, onLoadModelError);
  }

Broken click event
class MyExtension extends Autodesk.Viewing.Extension {
    constructor(viewer) {
      super();
      Autodesk.Viewing.Extension.call(this, viewer);
    }
    createPanel() {
      const Panel = new Autodesk.Viewing.UI.DockingPanel(NOP_VIEWER.container, `myPanel`, `Title`);
      $(Panel.container).append(*some html*);
      Panel.setVisible(true);
      $(`#myPanel`).find(`.docking-panel-close`).remove();
      $(`#myPanel`).find(`.docking-panel-title`).append(myButton);
      $(`#myButton`).click(this.onMyButtonClick.bind(this));
    }
    onMyButtonClick() {
        alert('here');
    }
  }

Autodesk.Viewing.theExtensionManager.registerExtension(`myExtension`, MyExtension);

Errors and screenshots
Error message in console
SyntaxError: Unexpected token (
    at Object.E [as doOperation] (84a694cc-2244-4f8f-90ea-4d32694ed224:13)
    at t.value (84a694cc-2244-4f8f-90ea-4d32694ed224:13)
    at 84a694cc-2244-4f8f-90ea-4d32694ed224:13

Uncaught (in promise) {msg: "Error while importing 'userFunction'."}

Panel header with button

A: EDIT:
Tested and worked on major browsers with the button in the title panel now - live sample here. Will let Engineering know that this is breaking change but I doubt they'd discourage putting controls there
    class MyExtension extends Autodesk.Viewing.Extension {
    constructor(viewer) {
      super(viewer);
      this.createPanel()

    }
    createPanel() {
      const Panel = new Autodesk.Viewing.UI.DockingPanel(NOP_VIEWER.container, `myPanel`, `Title`);
      Panel.setVisible(true);
      $(`#myPanel`).height('100').offset({ top: 10, left: 30 }).find(`.docking-panel-close`).remove();
      $(`#myPanel`).append($('<button/>').text('Test').mousedown(this.onMyButtonClick.bind(this)))
    }
    onMyButtonClick(e) {
        e.stopPropagation();
        alert('here')
    }
  }


text:
Q: vb.net - Populating a combobox with multiple properties from object Using vb.net (vs2005), how do I populate a combo box with multiple property values from an object? Right now I'm iterating a collection of objects and adding the name property of each object to the combo box. I'd like to add multiple properties from the object to the list. For now, I'd be happy if they appeared comma separated in the list.

A: Private _items As New List(Of Person)  'you will need to fill this with data!'

Private Sub Populate()

  For i As Integer = 0 To _items.count - 1
    lst.items.add(_items(i).Name & ", " & _items(i).Age)
  Next

End Sub

This will populate your listbox (which i have called lst) something like this:
Dave, 18
John, 21
Morgan, 23
Jen, 19

A: If this is a winforms environment, override the ToStirng() method, and simply add the whole object to the items collection.

A: You can either override the method by yourself.
Or you are lazy like me.
Try this multi column combo box
http://demos.telerik.com/aspnet-ajax/combobox/examples/functionality/multicolumncombo/defaultcs.aspx


text:
Q: Print one word per line I tried almost everything, sed, awk, tr, but...
I'm trying to output a file containing this
 2079 May 19 13:37 temp.sh
 1024 May 23 17:09 mirrad
 478 May 26 14:48 unzip.sh

like this
 2079
 May
 19
 13:37
 .
 .
 .

So each string will be printed out one at the time in a variable.

A: Another simple one liner using xargs
xargs -n 1 <file

where -n explanation from man page:-
-n max-args, --max-args=max-args
       Use at most max-args arguments per command line.  Fewer than
       max-args arguments will be used if the size (see the -s
       option) is exceeded, unless the -x option is given, in which
       case xargs will exit.

will produce output as
#!/bin/bash
$ xargs -n1 <tmp.txt
2079
May
19
13:37
temp.sh
1024
May
23
17:09
mirrad

with -n value as 2 it gives
#!/bin/bash
$ xargs -n2 <tmp.txt
2079 May
19 13:37
temp.sh 1024
May 23
17:09 mirrad

Note
The suggestion with xargs only works for a simple input as shown in OP. As such the solution doesn't work for huge files (needing high in memory processing) or in files containing lines with quotes. See other answers involving awk for the same.

A: another awk
$ awk -v OFS='\n' '{$1=$1}1' file

A: with awk
awk 'BEGIN{RS=" "} 1' file

output
2079
May
19
13:37
temp.sh
1024
May
23
17:09
mirrad
478
May
26
14:48
unzip.sh

A: Get the arguments for printf from the file:
printf "%s\n" $(<file)

A: Just one cat and tr can do this easily
cat input.txt|tr ' ' "\n"

or
EDIT:
the better one, without UUOC
tr ' ' "\n" < input.txt

A: I'll go ahead and answer this since I flagged it with the wrong duplicate question.
Use tr:
echo "Mary had a little lamb" | tr ' ' '\n'

In the command above you are replacing ' ' with a newline, '\n'.
Use sed:
echo "Mary had a little lamb" | sed 's/ /\n/g'

If you have multiple spaces you want to turn into a single newline, use s/  */\n/g instead.  That is / followed by two spaces then an *.


text:
Q: Modular invertibility of a primitive matrix
Question.
  If a matrix $A$ has a primitive characteristic polynomial modulo $p$, how to prove it is invertable modulo $p$.

Due to my prior question I know that if a matrix is invertable modulo a prime number $p$, it will be invertable mod $p^a\,,a\in\mathbb{N}$. Now I'm trying to find out what matrices are modular invertable. It seems that the above statement is true.

A: Given a square matrix $A$ over the integers, compute $\det(A)$.  If $\det(A)=0$, then $A$ will not be invertible mod p for any prime $p$.  However, if $\det(A)=n$, then $A$ will be invertible mod p for every prime $p$ that does NOT divide $n$.
Since the determinant of $A$ is (up to a sign) the constant term of the characteristic polynomial, the condition we care about is not primativity, but just whether zero is a root.  However, since primitive polynomials are irreducible, zero cannot be a root unless it is the only root, in which case $A$ would have been the $1\times 1$ zero matrix, which does not have an inverse.


text:
Q: How do I modify the response body in an actix-web 1.0 middleware? I'd like to modify the response body in Actix-Web. I've implemented the v1.0.0 middleware but I've not been successful in changing the response body so far.
I've tried two basic approaches: return a new ServiceResponse and use the method chains on ServiceResponse to attempt to set a new body. Both approaches have resulted in varying kinds of compiler errors and move violations that I haven't been able to resolve. While I'm new to Rust, other members of my team are more experienced and weren't able to work though these challenges either. I have not been able to find any examples that are on point.
Here is my implementation of call().
fn call(&mut self, req: ServiceRequest) -> Self::Future {
    let content_type = req.get_header_value("content-type");

    println!(
        "Request Started: {}; content type: {};",
        req.path(),
        content_type
    );

    Box::new(self.service.call(req).and_then(move |mut res| {
        match res.response().error() {
            Some(e) => {
                println!(
                    "Response: Error Code: {}; content type: {};",
                    res.status(),
                    content_type
                );

                dbg!(e);

                // I'd really like to modify the response body here.

                return Ok(res);
            }
            None => {
                println!("Middleware detected the response is not an error. ");
                return Ok(res);
            }
        }
    }))
}

I'd like to modify the response body to be the text "fredbob". If I can get that far, I can accomplish the rest of what I want to do.
Complete code:
use actix_service::{Service, Transform};
use actix_web::http::StatusCode;
use actix_web::{dev::ServiceRequest, dev::ServiceResponse, Error, HttpResponse};
use futures::future::{ok, FutureResult};
use futures::{Future, Poll};

use serde::Serialize;
use serde_json;

pub trait Headers {
    fn get_header_value(&self, name: &str) -> String;
}

impl Headers for ServiceRequest {
    fn get_header_value(&self, name: &str) -> String {
        self.headers()
            .get(name)
            .unwrap()
            .to_str()
            .unwrap()
            .to_string()
    }
}

// There are two step in middleware processing.
// 1. Middleware initialization, middleware factory get called with
//    next service in chain as parameter.
// 2. Middleware's call method get called with normal request.
pub struct SayHi;

// Middleware factory is `Transform` trait from actix-service crate
// `S` - type of the next service
// `B` - type of response's body
impl<S, B> Transform<S> for SayHi
where
    S: Service<Request = ServiceRequest, Response = ServiceResponse<B>, Error = Error>,
    S::Future: 'static,
    B: 'static,
{
    type Request = ServiceRequest;
    type Response = ServiceResponse<B>;
    type Error = Error;
    type InitError = ();
    type Transform = SayHiMiddleware<S>;
    type Future = FutureResult<Self::Transform, Self::InitError>;

    fn new_transform(&self, service: S) -> Self::Future {
        ok(SayHiMiddleware { service })
    }
}

pub struct SayHiMiddleware<S> {
    service: S,
}

fn is_error(status: StatusCode) -> bool {
    status.as_u16() >= 400
}

impl<S, B> Service for SayHiMiddleware<S>
where
    S: Service<Request = ServiceRequest, Response = ServiceResponse<B>, Error = Error>,
    S::Future: 'static,
    B: 'static,
{
    type Request = ServiceRequest;
    type Response = ServiceResponse<B>;
    type Error = Error;
    type Future = Box<Future<Item = Self::Response, Error = Self::Error>>;

    fn poll_ready(&mut self) -> Poll<(), Self::Error> {
        self.service.poll_ready()
    }

    fn call(&mut self, req: ServiceRequest) -> Self::Future {
        let content_type = req.get_header_value("content-type");

        println!(
            "Request Started: {}; content type: {};",
            req.path(),
            content_type
        );

        Box::new(self.service.call(req).and_then(move |mut res| {
            match res.response().error() {
                Some(e) => {
                    println!(
                        "Response: Error Code: {}; content type: {};",
                        res.status(),
                        content_type
                    );

                    dbg!(e);

                    // I'd really like to modify the response body here.

                    return Ok(res);
                }
                None => {
                    println!("Middleware detected the response is not an error. ");
                    return Ok(res);
                }
            }
        }))
    }
}

A: The posted solutions above no longer work in later versions of Actix. In 4.0.0-beta.14, in your middleware you can capture the Request via:
let mut request_body = BytesMut::new();
while let Some(chunk) = req.take_payload().next().await {
    request_body.extend_from_slice(&chunk?);
}

let mut orig_payload = Payload::empty();
orig_payload.unread_data(request_body.freeze());
req.set_payload(actix_http::Payload::from(orig_payload));

And you can capture the response via:
let _body_data =
    match str::from_utf8(&body::to_bytes(res.into_body()).await?){
    Ok(str) => {
        str
    }
    Err(_) => {
        "Unknown"
    }
};

Note: pulling the Request/Response will imply that you consume the Request/Response, so you need to alter it and create a new Request/Response.
You can then return a new response:
let new_request = res.request().clone();

let new_response = HttpResponseBuilder::new(StatusCode::BAD_REQUEST)
          .insert_header((header::CONTENT_TYPE, "application/json"))
          .body("New body data");

Ok(ServiceResponse::new(
    new_request,
    new_response
))

I posted a full example here:
How to print a response body in actix_web middleware?

A: You can try one of these two approaches. Both of them work for me:

*

*Use map_body method from ServiceResponse:

let new_res = res.map_body(|_head, _body| {
    ResponseBody::Other(Body::Message(Box::new("fredbob")))
});

return Ok(new_res);

*Access to the HttpRequest, clone it, and build a new ServiceResponse:

let new_res = ServiceResponse::new(
    res.request().clone(),
    HttpResponse::Ok().body("fredbob").into_body(),
);

return Ok(new_res);

Hope it helps!


text:
Q: How to synchronize time in Azure App Service Is there any way to synchronize time with Network Time Protocol (NTP) or some other standard when using Azure App Service?

A: Thanks for asking question! Azure App Service is PaaS and synchronizes the clocks based on the hosting platform.
You may refer to doc might be helpful: https://learn.microsoft.com/en-us/archive/blogs/benjaminperkins/time-sync-synchronization-on-an-azure-app-service


text:
Q: 3D Infinite Cone line intersection formula EDIT: Would be awesome if someone could explain in a comment what really goes on. We basically found out the answer by coincidences.
I'm trying to do line tests against an infinitely large cone,  but I'm having trouble understanding what I'm doing wrong. I do get some sort of cone like object to show, but it looks... wrong.
    EDIT: This is the solution for line-testing a infinite cone.
    double Cone::lineTest(double lineOrigin[3],double dir[3],double maxDistance)

    {
    //Returns the distance from line origin to the collision point
    //The object is located at 0,0,0 so the difference is the lineOrigin
         double a = pow(D[0], 2) + pow(D[1], 2) - pow(D[2], 2);
         double b = 2*(O[0]*D[0] + O[1]*D[1] - O[2]*D[2]);
         double c = pow(O[0], 2) + pow(O[1], 2) - pow(O[2], 2);
         double d = b * b - 4*a*c;

         if(d < 0)
             { return MAX_DISTANCE; }
         d = sqrt(d);
         double sol1 = (-b - d)/(2.0*a);
         if(sol1 > 0)
             return sol1;

    return MAX_DISTANCE;
    }


text:
Q: How can I merge 2 rows in an innodb table I've taken over the development of a web app that uses a mysql innodb database. The client has a lot of duplicate records in the db on accident. I'm building a merge tool to keep one record and push the other's associated data to it.
So, for example because of a typo, I might have.
entity_id    entity_cat    common_name
--------------------------------------
abcdefg      customer      John Doe
hijklmn      customer      Jon Doe

I then have a bunch of tables that are linked to entity_id. I want to delete 'hijklmn', and have all of the associated data in other tables change their 'customer_entity_id' to 'abcdef'.
The problem is, the relationships all have on delete cascade. Is there any way for me to merge these two records without losing any data?

A: With regards to your ON DELETE CASCADE issue, you can temporarily disable all foreign key constraints for the purpose of your query with the script template below:
ALTER TABLE `entities` NOCHECK CONSTRAINT ALL

-- commit query here

ALTER TABLE `entities` CHECK CONSTRAINT ALL

A: If you update all of the records before you do the delete, then there shouldn't be any cascade at all:
update other_table_1 set entity_id='abcdefg' where entity_id='hijklmn';
update other_table_2 set entity_id='abcdefg' where entity_id='hijklmn';
update other_table_3 set entity_id='abcdefg' where entity_id='hijklmn';
...
delete from user_table where entity_id='abcdefg'


text:
Q: How can I map a login to a database using T-SQL (not SSMS) I'm writing a program that requires me to assign all permissions and everything in code. I have gotten stuck in this part:

I just want to do the equivalent of clicking the little box under "Map" for the msdb database and assigning that user to SqlAgentUser role. I need a user to be able to add/edit SQL Server Agent jobs. I can get the settings right using SSMS but I can't for the life of me figure out how to do it in raw SQL.
I've looked into ALTER LOGIN but I'm not seeing anything that does what I need. I suspect I just don't know the correct terms to Google. I don't normally do this sort of thing.
Any help is much appreciated!

A: If you want to change the current\default database to a different one try:
alter login <loginname> with default_database = <dbname>;

Now, create a user for above login created
 use <dbname>;
 create user <username> from login <loginname>;

And now you can assign roles to the above create user for the login as below:
use <dbname>
exec sp_addrolemember 'db_owner', '<username>';

A: USE msdb;
GO
CREATE USER shims FROM LOGIN shims;
GO
ALTER ROLE SqlAgentUserRole ADD MEMBER shims;
GO

Also, for future reference, any time you know how to do something in the UI but not in a script, this is what the Script option on most dialogs is for - it will show you what script SSMS would have executed:


text:
Q: Laravel CRUD delete not working on foreign key I have a foreign relationship with category_id column in database but while deleting i get error.
This is my code for delete:
  public function destroy($id)
{
    $category = Category::find($id);
    $category->delete();
    Session::flash('success', 'The category was successfully deleted.');
    return redirect()->route('categories.index');
}

Error i seen is :
SQLSTATE[23000]: Integrity constraint violation: 1451 Cannot delete or update a parent row: a foreign key constraint fails (`fitilicious`.`products`, CONSTRAINT `products_category_id_foreign` FOREIGN KEY (`category_id`) REFERENCES `categories` (`id`)) (SQL: delete from `categories` where `id` = 2)

Please help.

A: My bet is on the foreign key being set to ON DELETE RESTRICT instead of CASCADE.

Cannot delete or update a parent row: a foreign key constraint fails (fitilicious.products, CONSTRAINT products_category_id_foreign FOREIGN KEY (category_id) REFERENCES categories (id)) (SQL: delete from categories where id = 2)

This tells us that there is a row in table "products" which is referencing the category you are attempting to delete.

*

*ON DELETE CASCADE will also delete the product.

*ON DELETE RESTRICT will prevent deletion of a non-empty category

*ON DELETE SET NULL will delete the category and set category_id to NULL in products table

Each has its uses, but you need to choose which one you need.


text:
Q: Terminal shows me "Revert currently in progress." Problem
I can't catch what this message on my terminal means to me.
The time I got this message is when I type git status.
On branch develop
Revert currently in progress.
  (run "git revert --continue" to continue)
  (use "git revert --skip" to skip this patch)
  (use "git revert --abort" to cancel the revert operation)

nothing to commit, working tree clean

Why this happened
I am creating an app all by myself. The problem happened when I used git revert.
This is an image of my commit of my remote repository.
I'm sorry some characters includes Japanese.

First, I noticed that something caused a huge problem to my project on commit [Clean]... (id:0844060) after Merge #119.
Eventually, I decided to do git revert so I typed git revert 463b703 and git revert e9a31bb; the former was my mistake though.
After I went back to previous commit, I completed fixing my problem and then I did git push again. That has no problems.
However, I just found the above message when I did git status after git push origin develop.
I just would like you to tell me what happens to me and means. Should I do something to delete message? And what should I have done after git revert ?
Thank you very much.
=================              =================             =============
Edit 1
I did git reflog and then I got these messages.
0478591 (HEAD -> master, origin/master) HEAD@{0}: checkout: moving from develop
to master
b0b58fa (origin/develop, develop) HEAD@{1}: commit: `[Add] Give_Item詳細画面の追
加
0478591 (HEAD -> master, origin/master) HEAD@{2}: checkout: moving from master t
o develop
0478591 (HEAD -> master, origin/master) HEAD@{3}: checkout: moving from develop
to master
0478591 (HEAD -> master, origin/master) HEAD@{4}: checkout: moving from master t
o develop
0478591 (HEAD -> master, origin/master) HEAD@{5}: commit: [Fix] Gitバグ修正
e9a31bb HEAD@{6}: revert: Revert "[Add]PickUp_Place Delte機能Validation実装"
463b703 HEAD@{7}: revert: Revert "[Clean] コードリファクタリング(destructureing)
"
d3abc8d HEAD@{8}: checkout: moving from develop to master
0844060 HEAD@{9}: checkout: moving from develop to develop
0844060 HEAD@{10}: checkout: moving from master to develop
d3abc8d HEAD@{11}: pull: Fast-forward
5a248fc HEAD@{12}: checkout: moving from develop to master
0844060 HEAD@{13}: commit: [Clean] コードリファクタリング(destructureing)
c038eda HEAD@{14}: commit: [Add]PickUp_Place Delte機能Validation実装
3955b04 HEAD@{15}: commit: [Add] PickUp_List Delteボタン実装
5a22d02 HEAD@{16}: commit: [fix] PickUp_Placeのフィルター修正

=================              =================             =============
Edit 2
I did git status again. It looks like the message is gone...?
user@MacBook-Air-4 [12:17:36] [~/Desktop/my_project/extra_exchange] [master]
-> % git status
On branch master
Your branch is up to date with 'origin/master'.

nothing to commit, working tree clean
user@MacBook-Air-4 [12:17:39] [~/Desktop/my_project/extra_exchange] [master]
-> % git checkout develop
Switched to branch 'develop'
user@MacBook-Air-4 [12:18:21] [~/Desktop/my_project/extra_exchange] [develop]
-> % git status
On branch develop
nothing to commit, working tree clean

==== ==== ==== ====
Edit3
I did git push, this is the result of it.
user@MacBook-Air-4 [12:54:04] [~/Desktop/my_project/extra_exchange] [develop]
-> % git push origin HEAD
Enumerating objects: 13, done.
Counting objects: 100% (13/13), done.
Delta compression using up to 4 threads
Compressing objects: 100% (7/7), done.
Writing objects: 100% (7/7), 670 bytes | 670.00 KiB/s, done.
Total 7 (delta 5), reused 0 (delta 0)
remote: Resolving deltas: 100% (5/5), completed with 5 local objects.
To https://github.com/Toshiyuki023Hori/extra_exchange.git
   b0b58fa..8951723  HEAD -> develop
user@MacBook-Air-4 [12:54:24] [~/Desktop/my_project/extra_exchange] [develop]
-> % gs
On branch develop
nothing to commit, working tree clean

A: git revert tries to reverse the effect of commits specified as an argument. This can be problematic sometimes and can generate merge conflicts(when two people have changed same section of some files and git is not sure which change to pick up). If you know about what files you need to change in order to revert the specified commit. You should try to fix conflicts and do:
git status
...
# Check files pointed out by git for conflicts
# Make changes to files with conflict
git add files/with/conflict
git revert --continue

If you're not sure how to proceed and want to revert back to previous state. You need to abort the revert(already suggested in comments):
git revert --abort


text:
Q: Symfony2 formbuilder - birthday field - different classes for days, month and years I have the problem that my Symfony2 form build birthday birthday with bootstrap renders the selects in boxes over the full with.
Is there a posiblity to give days, month and years options on the way to give them different classes in the Twig Template? So I can give them custom widths.
Thanks in Advance.
Michael

A: You can accomplish that in your template.
For example, I have something like:
{{ form_label(form.birthdate) }}
{{ form_widget(form.birthdate.year, { 'attr' : { 'class': 'year-class' }}) }}
{{ form_widget(form.birthdate.month, { 'attr' : { 'class': 'month-class' }}) }}
{{ form_widget(form.birthdate.day, { 'attr' : { 'class': 'day-class' }}) }}
{{ form_errors(form.birthdate) }}


text:
Q: How do i split an array of elements based on inner value element? As an input have an associate array like this:
$array[0]['id'] = 0;
$array[0]['name'] = 'first name';
$array[0]['phone'] = '+1 515 111 111';
$array[0]['for_id'] = 1;

$array[1]['id'] = 1;
$array[1]['name'] = 'first name1';
$array[1]['phone'] = '+1 515 222 222';
$array[1]['for_id'] = 1;

$array[2]['id'] = 0;
$array[2]['name'] = 'first name2';
$array[2]['phone'] = '+1 515 333 333';
$array[2]['for_id'] = 1;

$array[3]['id'] = 0;
$array[3]['name'] = 'first name3';
$array[3]['phone'] = '+1 515 444 444';
$array[3]['for_id'] = 2;

$array[4]['id'] = 0;
$array[4]['name'] = 'first name4';
$array[4]['phone'] = '+1 515 555 555';
$array[4]['for_id'] = 2;

$array[5]['id'] = 0;
$array[5]['name'] = 'first name5';
$array[5]['phone'] = '+1 515 666 666';
$array[5]['for_id'] = 2;

How do I split it in N separate arrays based on same value of $array[]['for_id']?
Like $array1 will contain all elements from $array where $array[]['for_id'] == 1; and $array2 with $array[]['for_id'] == 2;?

A: Just iterate over the array and collect every item with the same for_id in a new array.
$t = array();
foreach ($array as $item) {
    if (!isset($t[$item['for_id']]) {
        $t[$item['for_id']] = array();
    }

    $t[$item['for_id']][] = $item;
}

A: here is a similar way to Philipps' but doing exactly what you want, i.e. getting the name of the variable to match the for_id key value
$array[0]['id'] = 0;
$array[0]['name'] = 'first name';
$array[0]['phone'] = '+1 515 111 111';
$array[0]['for_id'] = 1;

$array[1]['id'] = 1;
$array[1]['name'] = 'first name1';
$array[1]['phone'] = '+1 515 222 222';
$array[1]['for_id'] = 1;

$array[2]['id'] = 0;
$array[2]['name'] = 'first name2';
$array[2]['phone'] = '+1 515 333 333';
$array[2]['for_id'] = 1;

$array[3]['id'] = 0;
$array[3]['name'] = 'first name3';
$array[3]['phone'] = '+1 515 444 444';
$array[3]['for_id'] = 2;

$array[4]['id'] = 0;
$array[4]['name'] = 'first name4';
$array[4]['phone'] = '+1 515 555 555';
$array[4]['for_id'] = 2;

$array[5]['id'] = 0;
$array[5]['name'] = 'first name5';
$array[5]['phone'] = '+1 515 666 666';
$array[5]['for_id'] = 2;

foreach($array as $arr){
    $int = $arr['for_id'];
    $arrName  = 'array' . $int;

    if(!isset($$arrName ))
    {
        $$arrName =array();
    }
    array_push($$arrName, $arr);

}

echo 'First array ' . json_encode($array1);
echo 'Second array ' . json_encode($array2);


text:
Q: Python: Modularized Programming to find Circumference, Diameter, and Area from circles Radius I have to create a modularized program that can find out the Diameter, Circumference, and Area of a circles radius. I'm sure many of you can notice I kind of winged this from a example given from my teacher. Instead of people pointing out the fact that I coded this wrong could you please give me reasons for what I should do so I can better understand this concept. Thanks
def main():
    Radius = 0
    Diameter = 0
    Circumference = 0
    Area = 0

    Radius = GetRadius(Radius)
    Diameter = SetDiameter(Radius,Diameter)
    Circumference = SetCircumference(Radius,Circumference)
    Area = SetArea(Radius,Area)
    ShowResults(Radius,Diameter,Circumference,Area)

def GetRadius(myradius):
    myradius = float(input("Enter your radius: "))
    return myradius

def SetDiameter(myradius,mydiameter):
    mydiameter = myradius * 2
    return mydiameter

def SetCircumference(myradius,mycircumference):
    PIE = 3.14159
    mycircumference = 2 * PIE * myradius
    return mycircumference

def SetArea(myradius,myarea):
    PIE = 3.14159
    myarea = PIE * myradius ^ 2
    return myarea

def ShowResults(Radius,Diameter,Circumference,Area):
    print("The Diameter is",mydiameter)
    print("The Circumference is",mycircumference)
    print("The Area is",myarea)

main()

A: myarea = PIE * myradius ^ 2
In Python, the exponentiation operator is **.
myarea = PIE * myradius ** 2
(In fact, don't expect ^ to ever be exponentiation in a programming language. It is usually the bitwise xor operator.)

A: The first thing I suggest is you remove the parameters you want to return from the argument lists:
def SetDiameter(myradius,mydiameter):
    mydiameter = myradius * 2
    return mydiameter

Should be
def SetDiameter(myradius):
    mydiameter = myradius * 2
    return mydiameter

If you return the value from the function you don't need to include it in the argument list. This important in understanding how python works.
I don't know what your original assignment is, but the best way to improve your skills and this short program would probably be to add a circle class. You should definitely read this:
http://docs.python.org/2/tutorial/classes.html


text:
Q: Mock AMQPTemplate inside TestSuite I am running JUnits as a TestSuite. One of the JUnit class is for for testing the code which publishes the messages to RabbitMQ. I am supposed to mock the code to publish the messages to MQ. How can I do that? Is it possible to simply change the RabbitTemplate configuration inside configuration xml itself?
Class with business logic:
public class SomeClassImpl implements SomeClass {

@Autowired
@Qualifier("amqpTemplate")
private AmqpTemplate amqpTemplate;

public void someMethod(){
    ...
    amqpTemplate.convertAndSend(exactTargetQueue, etMsg);
    ...
}

A: Yes
<bean id="rabbitAdmin" class="org.mockito.Mockito" factory-method="mock">
    <constructor-arg value="org.springframework.amqp.rabbit.core.RabbitTemplate"/>
</bean>


text:
Q: Every activity in my app is added to app drawer Well, just like the title suggests, every activity within my application is being added to the app drawer.... Im really hating this new ADT. First it was a problem with the app name appearing as the first activity name, now all the activities are showing up on the application list. If I go to uninstall it only shows 1. Anyone else having this problem and has figured out a work around?

A: for future cases specifically you can change in the android manifest under :
<intent-filter>
  <category android:name="android.intent.category.LAUNCHER" />
</intent-filter>

change to:
<intent-filter>
  <category android:name="android.intent.category.DEFAULT" />
</intent-filter>

This will remove the activities' icon from the app drawer. As the OP says: sometimes the wizard puts this in the manifest for you.

A: Ok, figured it out... Everytime you create a new activity through the adt wizard (New -> Android Activity) it creates the code in your manifest for you.... the problem is that it added intent filters to it as well. Just remove those and they dont show up.... stupid adt.

A: I know when I am using IntelliJ as my IDE for Android programming, there is a box you can check when using the wizard to create a new Activity that says "Mark as start-up Activity".
Be aware of these types of things because that is what caused me to have the same problem you had Shaun.
I wouldn't completely erase the intent filters, simply have only the Activity you want as the "start-up" Activity marked as the "Launcher" in the Manifest file. All other Activities get "Default".


text:
Q: answer the phone If I get the call from a job agent, at first, he/she will introduce himself/herself and the agent company name. But, English is not my mother language, I am not sensitive about the person name and other particular name, so, what should I answer the phone politely?

A: It sounds like you want to be polite and to ask them to repeat their name and where they are calling from.
"Thank you very much for calling."
"I'm sorry, I didn't catch your name and your company."
The first statement is polite. The second politely asks them to state their name and company name again.


text:
Q: Angularjs 4, how can I use ngfor to show 3 consecutive items in the same tag? As I mentioned in the question, I have a table and I use ngFor to show all item in the array. For now I am doing it by:

    {{item}}

However, I want three consecutive items in the same div (or the same line, and the next three on the next line). How can I do it?

A: I would group them in the component:
@Component({
  template: `

      <ng-container *ngFor="let el of group">
          {{ el }}
      </ng-container>

  `,
  selector: 'test'
})
export class TestComponent implements OnInit {
  public grouped: number[][] = [];

  // Don't make it zero
  private numPerGroup = 3;

  ngOnInit(): void {
    let testArray: number[] = [0, 1, 2, 3, 4, 5, 6, 7, 8, 9, 10];
    let group: number[];

    for (let i = 0; i < testArray.length; i++) {
      if (!(i % this.numPerGroup)) {
        this.grouped.push(group = []);
      }

      group.push(testArray[i]);
    }
  }
}

A: Stole the answer from this question: Angular 5 display *ngfor horizontally
Use the Angular Flex-Layout package and you can add this as the template to Frank Modica's answer and it should work:

 {{el}}

A: The easiest way to do that is with a css grid
component:

    {{item}}

css:
  .grid-container {
    display: grid;
    grid-template-columns: repeat(3, auto);
  }

https://stackblitz.com/edit/angular-cyskpw


text:
Q: I know how to write and if statement as a formula, but not in a script I know next to nothing about writing scripts in Google Sheets, but I'm hoping to learn!
I've gotten a cell to increase by 1 when I click a drawing, but I need for the cell to go back to 1 after it gets to 12.  So it continually counts from 1 up to 12.
I have this as the original script.  I know how to write and if statement as a formula, but not in a script.  Can anyone help?
function incrementup() {
  if (U38<13) {
      SpreadsheetApp.getActiveSheet().getRange('U38').setValue(SpreadsheetApp.getActiveSheet().getRange('U38').getValue() + 1);
  } else {
SpreadsheetApp.getActiveSheet().getRange('U38').setValue(SpreadsheetApp.getActiveSheet().getRange('U38').1);

}
}

A: The scripts (Google Apps Scripts) for Google Sheets are written in JavaScript.
The syntax for an if statement is
if condition statement

References

*

*https://developers.google.com/apps-script/overview

*https://developer.mozilla.org/en-US/docs/Web/JavaScript/Reference/Statements/if...else

A: Ooooh.  I figured it out (probably a lot messier than it needs to be)...
function incrementup() {
  if (SpreadsheetApp.getActiveSheet().getRange('U38').getValue()<12) {
      SpreadsheetApp.getActiveSheet().getRange('U38').setValue(SpreadsheetApp.getActiveSheet().getRange('U38').getValue() + 1);
  } else {
    SpreadsheetApp.getActiveSheet().getRange('U38').setValue(SpreadsheetApp.getActiveSheet().getRange('U38').getValue() *0 + 1);
  }
}


text:
Q: What is the role of libc(glibc) in our linux app? When we debug a program using gdb, we usually see functions with strange names defined in libc(glibc?). My questions are:

*

*Is libc/glibc the standard implementation of some standard C/C++ functions like strcpy,strlen,malloc?

*Or, is it not only of the first usage as described above, but also an wrapper of Unix/Linux system calls like open,close,fctl? If so, why can't we issue syscalls directly, without libc?

*Does libc only consist of one lib (.a or .so) file, or many lib files (in this case, libc is the general name of this set of libs)? Where do these lib file(s) reside?

*What is the difference between libc and glibc?

A: It's the "standard library".  It's exactly like "MSVCRTL" in the Windows world.
The Gnu standard library ("glibc") is the implementation of libc most commonly (almost universally?) found on Linux systems.  Here are the relevant files on an old SusE Linux system:
ls -l /lib =>
-rwxr-xr-x  1 root root 1383527 2005-06-14 08:36 libc.so.6

ls -l /usr/lib =>
-rw-r--r--  1 root root 2580354 2005-06-14 08:20 libc.a
-rw-r--r--  1 root root     204 2005-06-14 08:20 libc.so

This link should answer any additional questions you might have (including references to the full and complete GLibc source code):

*

*http://sourceware.org/glibc/wiki/HomePage

A: With regard to the first two, glibc is both the C standard library (e.g, "standard C functions") and a wrapper for system calls. You cannot issue system calls directly because the compiler doesn't know how -- glibc contains the "glue" which is necessary to issue system calls, which is written in assembly. (It is possible to reimplement this yourself, but it's far more trouble than it's worth.)
(The C++ standard library is a separate thing; it's called libstdc++.)
glibc isn't a single .so (dynamic library) file -- there are a bunch, but libc and libm are the most commonly-used two. All of the static and dynamic libraries are stored in /lib.
libc is a generic term used to refer to all C standard libraries -- there are several. glibc is the most commonly used one; others include eglibc, uclibc, and dietlibc.

A: libc implements both standard C functions like strcpy() and POSIX functions (which may be system calls) like getpid().  Note that not all standard C functions are in libc - most math functions are in libm.
You cannot directly make system calls in the same way that you call normal functions because calls to the kernel aren't normal function calls, so they can't be resolved by the linker.  Instead, architecture-specific assembly language thunks are used to call into the kernel - you can of course write these directly in your own program too, but you don't need to because libc provides them for you.
Note that in Linux it is the combination of the kernel and libc that provides the POSIX API.  libc adds a decent amount of value - not every POSIX function is necessarily a system call, and for the ones that are, the kernel behaviour isn't always POSIX conforming.
libc is a single library file (both .so and .a versions are available) and in most cases resides in /usr/lib.  However, the glibc (GNU libc) project provides more than just libc - it also provides the libm mentioned earlier, and other core libraries like libpthread.  So libc is just one of the libraries provided by glibc - and there are other alternate implementations of libc other than glibc.

A: You can check the detailed information about "libc" and "glibc" from the man pages on your linux sytem by typing "man libc" on the shell, copied as below;
LIBC(7)      Linux Programmer's Manual      LIBC(7)

NAME
       libc - overview of standard C libraries on Linux

DESCRIPTION
       The term "libc" is commonly used as a shorthand for the "standard C library", a library of standard functions that can be
       used by all C programs (and sometimes by programs in other languages).  Because of some history (see below), use  of  the
       term "libc" to refer to the standard C library is somewhat ambiguous on Linux.

   glibc
       By  far  the most widely used C library on Linux is the GNU C Library ⟨http://www.gnu.org/software/libc/⟩, often referred
       to as glibc.  This is the C library that is nowadays used in all major Linux distributions.  It is  also  the  C  library
       whose details are documented in the relevant pages of the man-pages project (primarily in Section 3 of the manual).  Doc‐
       umentation of glibc is also available in the glibc manual, available via the command info libc.  Release 1.0 of glibc was
       made in September 1992.  (There were earlier 0.x releases.)  The next major release of glibc was 2.0, at the beginning of
       1997.

       The pathname /lib/libc.so.6 (or something similar) is normally a symbolic link that points to the location of  the  glibc
       library,  and executing this pathname will cause glibc to display various information about the version installed on your
       system.

   Linux libc
       In the early to mid 1990s, there was for a while Linux libc, a fork of glibc 1.x created by  Linux  developers  who  felt
       that  glibc  development  at  the  time  was  not  sufficing for the needs of Linux.  Often, this library was referred to
       (ambiguously) as just "libc".  Linux libc released major versions 2, 3, 4, and 5 (as well as many minor versions of those
       releases).  For a while, Linux libc was the standard C library in many Linux distributions.

       However, notwithstanding the original motivations of the Linux libc effort, by the time glibc 2.0 was released (in 1997),
       it was clearly superior to Linux libc, and all major Linux distributions that had been using  Linux  libc  soon  switched
       back to glibc.  Since this switch occurred long ago, man-pages no longer takes care to document Linux libc details.  Nev‐
       ertheless, the history is visible in vestiges of information about Linux libc that remain in some manual pages,  in  par‐
       ticular, references to libc4 and libc5.