text:
Q: Parallel->Series switches for capacitor bank, only one charges Here's my goal: To create a capacitor bank to dump a load in to a load resistor/inductor, pulsed, without using switches and keeping it as isolated as I can from myself.
Here is what I have so far:

VG2 a square wave simply at around 10Hz, J1 being a net.
My thoughts (I tried with PNP and NPN with 10k Rs at base at first): Have the capacitors charge at full voltage in parallel, the control voltage (VG2) allowing this by opening a path for both to charge side by side.
When the control voltage goes to zero, the N channel fets will turn off (C2's path to ground) and also the diode's (ignore why it is there for now, but to prevent it from recharging C1 during discharge phase I believe) and connect the two in series to make the intended C1+C2=~240V on the load.
What I simulated:

C1 seems to be fine, but does not discharge.
C2 starts at negative (going down slightly)
Load seems to continuously have a voltage (no path to flow?)
I wonder if the fets or BJTs last time simply do not switch or work as I suspect, would they perform as I intend? Is there a more straightforward way of doing this parallel->series switching to isolate myself a little better?

A: You are using your transistors incorrectly. In fact, I think that the only transistor which behaves as a switch in your circuit is T2.
Note that a transistor, NMOS for example, will conduct while \$V_{GS}>V_T\$. You are biasing your NMOS transistors in such a way that the potentials at source terminals is much higher than at gate terminals.
I believe that the reason you see a constant voltage on the load is because T3 and T4 are conducting when \$VG_2=5V\$, and T1 and T5 are conducting when \$VG_2=-5V\$ (in all cases due to wrong biasing). You can easily check my guesses in simulation by measuring the currents.
Furthermore, take a look at transistors' datasheets - the voltages in your circuit exceed the max ratings for the transistors.
The component you are trying to implement is called "Charge Pump" - there are many standard implementations you can find on the internet. A short (but not complete) overview may be found here.


text:
Q: knockout observable array binding to view when there is a delay in assigning value not happening I have a knockout observable array whose value assignment changes after a set value of time but do not see this reflecting in the view. Could someone tell where I am doing it wrong? I would expect the output to show
•   GRE 1111
•   TOEFL 111
but it shows
•   GRE2 222
•   TOEFL2 22
jsFiddle link: https://jsfiddle.net/4r37x9y5/
HTML:

console.clear();

function viewModel() {

this.plans = ko.observableArray([]);

    var plans1 = [
        { id: 'GRE', count: '1111' },
        { id: 'TOEFL', count: '111' },
        ];

            var plans2 = [
        { id: 'GRE2', count: '222' },
        { id: 'TOEFL2', count: '22' },
        ];

        this.plans = plans2;
        //this.plans = plans1;

        setTimeout(function(){
        console.log("In timeout before assigning plans");
      this.plans = plans1;
      console.log(this.plans);
      }, 2000);

}

ko.applyBindings(viewModel());
// The above line equals:
// viewModel(); // updates window object and returns null!
// ko.applyBindings(); // binds window object to body!

A: There are couple of issues here. As mentioned by you in the comments, you are not binding an object with observables. You are simply adding a global variable plans. If knockout can't find a property in the viewModel, it will use the window object's property. That's why it works the first time

*

*You need to change viewModel as a constructor function and use new viewModel() to create an object or an instance.

*observables should be read and updated by calling them as functions. So, this.plans(plans1). If you set this.plans = plans2, it will simply overwrite the observable with a simple array without the subscribers to update the UI when the property changes

*You need to use correct this inside setTimeout. Either by creating a self = this variable outside or using an arrow function as a callback

function viewModel() {
  this.plans = ko.observableArray([]);

  var plans1 = [{ id: "GRE", count: "1" }, { id: "TOEFL", count: "1" }];
  var plans2 = [{ id: "GRE2", count: "2" }, { id: "TOEFL2", count: "2" }];

  this.plans(plans2) // call it like a function

  setTimeout(() => {
    console.log("In timeout before assigning plans");
    this.plans(plans1)
  }, 2000);
}

ko.applyBindings(new viewModel()); // new keyword to create an object

redpajama_set_name: RedPajamaStackExchange


text:
Q: Python 3.x email.message library: trying to remove specific header content such as bcc The library functions for reading headers from an RFC822 compliant file are working just fine for me, for example:
    allRecips = []
    for hdrName in ['to', 'cc', 'bcc']:
        for i in email.utils.getaddresses(msg.get_all(hdrName, [])):
            r = {
                'address': {
                    'name': i[0],
                    'email': i[1]
                }
            }
            allRecips.append(r)

I now want to remove the bcc recipients from the msg structure in the above example. I looked at del_param() for this, but couldn't figure out what to pass in.
Is there a good way to delete any bcc headers that may be present (1 or more)?

A: I found a way to do it.  The trick was to work backwards through the array of headers using reversed(), to avoid issues where content 'moves' in the array.
# Remove any bcc headers from the message payload. Work backwards, as deletion changes later indices.
for i in reversed(range(len(msg._headers))):
    hdrName = msg._headers[i][0].lower()
    if hdrName == 'bcc':
        del(msg._headers[i])

A: a list has the remove method which searches for the item so the order is not important.
I believe you could accomplish the goal using this code:
for header in msg._headers:
    if header[0].lower() == 'bcc':
        msg._headers.remove(header)


text:
Q: regex expression that matches phrase, unless its already prefixed I'm cleaning up a large C++ code base where I need all variables of type "vector" need to be changed to "std::vector".  Skipping over #include  and comments in the code.  And most importantly, if the expression is already written as "std::vector", don't convert it to "std::std::vector"
That is:
#include <vector>
vector<Foo> foolist;
typedef vector<Foo> FooListType;
std::vector<Foo> otherfoolist;
int main()
{
    // this vector is for iteration
    for (vector <Foo>::iterator itor = foo.begin...)

Converts to
#include <vector>
std::vector<Foo> foolist;
typedef std::vector<Foo> FooListType;
std::vector<Foo> otherfoolist;
int main()
{
    // this vector is for iteration
    for (std::vector<Foo>::iterator itor = foo.begin...)

So far, I have this narrowed down to two sed commands
sed -r 's/vector\s{0,1}</std::vector</g' < codefile > tmpfile
sed 's/std::std/std/' < tmpfile > codefile

The first sed matches "vector< and "vector <" and converts either to "std::vector<".
The second sed fixes the side effect of converting "std::vector<" into "std::std::vector<".
How can merge the two different regex expressions above so I can have a single sed command that fixes the code correctly.
I've tried reading online about lookahead and lookbehind, but my eyes are starting to burn out.

A: You can make the first regexp also match a possible std:: by using
sed -r 's/[std:]*vector\s{0,1}</std::vector</' < codefile > tmpfile

btw: you can make the changes in place by adding -i and just passing the file as command line parameter:
sed -i -r 's/[std:]*vector\s{0,1}</std::vector</' codefile

A: This might work for you (GNU sed):
sed -i 's/\(^\|[^<:]\)\(vector\s*<\)/\1std::\2/g' file

A: If your sed version does not support extended regular expressions, you can use perl:
perl -lane ' if (!/^\s*#include/) {s!(?:std::)?vector!std::vector!g;} print; ' < codefile > tmpfile
this will work in cases like this:  vector<vector<Foo>> otherfoolist;
see this answer also: https://stackoverflow.com/a/6157705/390913


text:
Q: How to convert resources file extension to use in sql server 2008 How to convert a .resources extension file to use in sql server 2008.I have a file with extension '.resources'. (MS ACCESS DB)

A: You can use SSIS tools or Import\Export Wizard on SQL Server.


text:
Q: Bypassing SSL certificate verification using Flask, gunicorn, gevent I am getting CERTIFICATE_VERIFY_FAILED errors because when I make a openurl request with urllib, it is checking the https certificates, and as my endpoint is using a self signed certificate (using our companies internal CA), they are obviously failing the verification check.
I know I can use requests, or create my own context, however it is a third party library that is making the call, and I can't change how that happens. As its just an internal app, I couldn't care less about the verification, so I am just happy to skip verification on all https requests.
The internet suggests the easiest way to do this is, is to create an env variable PYTHONHTTPSVERIFY=0, or to monkey patch the ssl library with
# Set prior to pretty much everything

import ssl
if hasattr(ssl, '_create_unverified_context'):
    ssl._create_default_https_context = ssl._create_unverified_context

So this is working fine until I go to run things using gunicorn which is configured to use gevent workers. I am also stuck using python 2.7.18
Wondering if anyone has any solutions, or ideas?

A: So after a lot of headache I have worked out the problem arises because when gunicorn spins up the gevent workers, they call gevent.monkey.patch_all() after my app is initialised. Unfortunately this overwrites my monkey patches (done in my app init) and resets things.
I thought this should still be ok, because the PYTHONHTTPSVERIFY=0 is still set, and the SSL lib should see that, and ignore verification. HOWEVER! the SSL lib that gevent replaces (monkey patches) the system one with is an old version and it doesn't look for the ENV variable.
So, I needed a way to further monkey patch (ssl._create_default_https_context = ssl._create_unverified_context) AFTER the gevent monkey patching!
Fortunately gunicorn provides a hook to do this, and we can setup a function in the config file to do it for us. My gunicorn config looks something like this:
bind = '0.0.0.0:8080'
accesslog = 'gunicornaccess.log'
errorlog = 'gunicornerror.log'
loglevel = 'DEBUG'
timeout = 240000
pidfile = 'gunicorn.pid'
debug = True
worker_class = 'gevent'
workers = 8
threads = 4

def post_worker_init(worker):
   import ssl
   ssl._create_default_https_context = ssl._create_unverified_context

I mean monkey patching is bad idea in general, but this is the only way I could get it work. Hopefully this saves someone else the headache I went through to get here.


text:
Q: Can the Bernstein concentration inequality bound for matrices be improved when we have a sequence of diagonal matrices? I am using the Bernstein inequality for the sum of independent random Hermitian matrices presented in the following paper by Joel A.Tropp (page 96, theorem 6.6.1) which states the following:
Consider a finite sequence $\{X_k\}$ of independent, random, Hermitian matrices with dimension $d$.
Assume that $E(X_k) =0$ and $ \lambda_{max}(X_k) \leq L$ for each index $k$.  Introduce the random matrix $Y =\sum_{k} X_k$.
Let $v (Y)$ be the matrix variance statistic of the sum: $v(Y)= \|EY^2\| = \|\sum_{k} EX^{2}_{k}\|$
Then for all $t \geq 0$
$$P\{\lambda_{max}(Y) \geq t\} \leq d·\exp \left(\frac{−t^2/2}{v(Y)+Lt/3}\right).$$
For the problem I am working on, the sequence of random matrices $\{X_k\}$ are also diagonal matrices, I am therefore wondering if that information can be used to improve the bound of the inequality.
Also what if each of the matrices where not only diagonal but also only had one non-zero diagonal element?
In other word what if the matrix $X_k$ has a value on the $kk$ diagonal position and zeros everywhere else for all $k \in \{1,..,d\}$.
Thank you


text:
Q: How to animate rigidbody objects in Unity I'm creating a game in which I need to move an object straight up, and when it hits another object they are connected with joint. That's why I need to have rigidbodies attached to both of them. The problem is that when I use animation to do this, collision is not detected, and unity tends to crash. Is there any proper way of "animating" rigidbody objects? Or maybe I should choose a different approach?

A: Set Rigidbody.isKinematic to true on the rigid bodies just before animating them. This will allow you to move (animate) the rigid bodies by changing the transform.position and other properties while allowing collisions with other non-kinematic bodies(rigid bodies with isKinematic set to false) and joint constraints to work properly. When the animation has completed and you want the bodies to be affected by physics again, set isKinematic to false.
Refer to the documentation for isKinematic for more information and a ragdoll example.


text:
Q: QT platform plugin "windows" So I am working on my Diploma Thesis, and so far everything went fine.
So this week I installed Win8.1 on my PC and installed QT, implemented some things and wanted to send the release version of my program to my company.
I compiled the hole thing, copied it to my release folder and i got an error.
"This application failed to start because it could not find or load the Qt platform    plugin "windows"."
I googled and found out that I have add a folder named "platforms". Said and done. Same error.  I also tried to copy the hole plugins folder to my release folder. Same error.
I really need help because my boss isn't happy about giving in work too late.
I hope someone can help me.

A: Do you also have "qminimal.dll" placed in your platforms directory?
Edit:
Sorry, "qminimal.dll" was not displayed in my previous post.

A: I found the Problem!
Previously i used the dll's from my old QT installation. I just copied the ones from the new Installtion into a folder and the exe. I don't even need the qwindow.dll now.
BUT! I works now... :)
Is there a way, that I create my own DLL, just for my Application?
But still thanks for your help!


text:
Q: Rewrite to hide default doc in IIS 8 I have a site that uses index.cfm for the default page of the whole site. Varibles are passed in the url as value pars seperated by forward slashes.
Example:
www.domain.com/index.cfm/show_register/memberType_Buyer/membershipLevel_Vip
www.domain.com/index.cfm/show_register/memberType_seller/membershipLevel_Standard
www.domain.com/index.cfm/show_items/category_bike/id_123

I would like to "hide" index.cfm in the url but have it still work.
I have tried using a many different rules I have found (the latest being)
<rewrite>
    <rule name="Default Document" stopProcessing="true">
        <match url="(.*)index.cfm" />
        <conditions logicalGrouping="MatchAll">
            <add input="{REQUEST_METHOD}" pattern="^POST$" negate="true" />
            <add input="{PATH_INFO}" pattern="^.*(index.cfm/).*$" negate="true" />
            <add input="{QUERY_STRING}" pattern=".+" ignoreCase="false" negate="true" />
        </conditions>
        <action type="Redirect" url="{R:1}" appendQueryString="true" redirectType="Permanent" />
    </rule>
</rewrite>

But I can't seem to get it to work correctly.  I feel like since index.cfm is the default document for the site I might be in some kind of infinite loop.
Where am I going wrong?
UPDATE:
I have rewrite installed.

This is what the I am seeing in IIS

This is what the browser is displaying

I did get this rewrite to work but now it is adding "index.cfm" to everything include files like /js/global.js and /css/site.css
        <rules>
            <rule name="Default Document">
                <match url="\/(.*)" />
                <action type="Rewrite" url="index.cfm{R:0}" />
            </rule>
        </rules>

So although I am getting closer I am not quite there.

A: This rewrite rule will do that for you:
<rule name="Default Document" stopProcessing="true">
    <match url=".*" />
    <conditions logicalGrouping="MatchAll">
        <add input="{REQUEST_METHOD}" pattern="^POST$" negate="true" />
        <add input="{PATH_INFO}" pattern="^/index.cfm" negate="true" />
        <add input="{REQUEST_FILENAME}" matchType="IsFile" negate="true" />
        <add input="{REQUEST_FILENAME}" matchType="IsDirectory" negate="true" />
    </conditions>
    <action type="Rewrite" url="/index.cfm/{R:0}" />
</rule>

It will rewrite requests:
www.domain.com/show_register/memberType_Buyer/membershipLevel_Vip to www.domain.com/index.cfm/show_register/memberType_Buyer/membershipLevel_Vip


text:
Q: Reverse integer bitwise without using loop I want to write a program which reverses the bits of an integer.
Ex 11000101 to 10100011
I know how to solve this using a loop, but I came across solutions that do it using byte shift:
num>>4|num<<4

I don't understand how does this work. Can somebody hep me with this?

A: As mentioned, it's not reversing the bits, just the nibbles. But you can decompose a real bit-reversal to something like that as well, like this (not tested):
// swap nibbles
x = x >> 4 | x << 4;
// swap groups of 2
x = (x >> 2) & 0x33 | (x & 0x33) << 2;
// swap groups of 1
x = (x >> 1) & 0x55 | (x & 0x55) << 1;

You can of course extend that pattern to reverse a wider number. Every additional step doubles the width of the number it reverses, which makes this method far more scalable than moving every bit to its position one by one. To reverse a 64bit number, this algorithm takes only 6 "steps" (at 5 operations for all but 1 step, so roughly 30 operations) whereas the bit-by-bit algorithm takes 64 steps (at 3 operations per step except one, so 191 operations).
You can reorder the steps, if you want.

A: 1100 0101
>> 4 means we are shifting the bits by 4 to the right:
0000 1100
<< 4 means we are shifting the bits by 4 to the left:
0101 0000
| is the or operation:
0000 1100
↓↓↓↓ ↓↓↓↓ |
0101 0000
---------
0101 1100

As you see, the program changed the two blocks of 4 bits.

A: That's not reversing the bits, it's swapping the nybbles (4-bit units). In other words, it will turn:
1100 0101 (abcd efgh)

into:
0101 1100 (efgh abcd)

and it will do so only if the data type is actually 8 bits (otherwise num << 4 places some bits left of the eight rightmost ones. A safer way to do it is to ensure all other bits are cleared before shifting:
((num & 0xf0) >> 4) | ((num & 0x0f) << 4)

For a precis on how bitwise operators work, see this excellent answer.
The equivalent expression for a full bit reversal, hgfe dcba, is the rather monstrous:
  ((num & 0x01) << 7)
| ((num & 0x02) << 5)
| ((num & 0x04) << 3)
| ((num & 0x08) << 1)
| ((num & 0x10) >> 1)
| ((num & 0x20) >> 3)
| ((num & 0x40) >> 5)
| ((num & 0x80) >> 7)

which extracts and shifts each of the eight bits.
There are also optimisations that can handle groups of non-contiguous bits in one operation, such as:
num = ((num & 0xf0) >> 4) | ((num & 0x0f) << 4) // abcdefgh -> efghabcd
num = ((num & 0xcc) >> 2) | ((num & 0x33) << 2) // efghabcd -> ghefcdab
num = ((num & 0xaa) >> 1) | ((num & 0x55) << 1) // ghefcdab -> hgfedcba

These work by grabbing the non-contiguous bits and moving them left or right, with the mask values showing which bits get affected:
0xf0, 0x0f -> 1111-0000, 0000-1111, shift by 4
0xcc, 0x33 -> 1100-1100, 0011-0011, shift by 2
0xaa, 0x55 -> 1010-1010, 0101-0101, shift by 1

The first bit mask in each line extracts the bits to shift right, the second grabs the bits to shift left. The two results are then recombined. To take the second one as an example, say you have the bits abcdefgh beforehand and you evaluate the expression ((num & 0xcc) >> 2) | ((num & 0x33) << 2):
(num&0xcc)>>2     (num&0x33)<<2
-------------     -------------
  abcdefgh          abcdefgh
  11001100          00110011        'and' with mask
  --------          --------
  ab00ef00          00cd00gh
  00ab00ef          cd00gh00        shift right/left
          \        /
           00ab00ef
           cd00gh00                 'or' them together
           --------
           cdabghef

Hence you can see how the actions of bit extraction, shifting and recombination allow you to reverse the order of sections within the value:
ab   cd   ef   gh
  \ /       \ /
   X         X
  / \       / \
cd   ab   gh   ef

I suggest you try a similar experiment with the third operation num = ((num & 0xaa) >> 1) | ((num & 0x55) << 1), you'll see it also acts as expected, reversing individual bits in each group of two.

A: If your integers are in range 0..255, it is acceptable to tabulate all 256 reversed values. (You can tabulate just nibbles but that would be a poor man's solution.)
For larger values, swap and simultaneously reverse the bytes using that table. You can do the swap by a combination of masks and shifts, or by mapping four bytes onto the int.

A: A recursive method for reversing the order of the bits in an integer -- call with the value to be reversed and the width of the value.
procedure int REVERSEBITS( int VALUE; int WIDTH ) {
  if WIDTH==1 then {
    return VALUE;
  } else {

    // intermediate values may help make the algorithm more understandable
    int HalfWidth = WIDTH >> 1;  // number of bits to be swapped at this level
    int HalfMask = HalfWidth-1;  // mask for left or right half of the value
    int RightHalfValue = VALUE & HalfMask;  // extract right half from value
    int LeftHalfValue = (VALUE >> HalfWidth) & HalfMask;  // extract left half

    // call reversing function on the two halves separately then swap the results
    return (REVERSEBITS(RightHalfValue, HalfWidth) << HalfWidth)
                | REVERSEBITS(LeftHalfValue, HalfWidth);
  }
}

Or, shorten the function by replacing all intermediate values with their definitions (optimizing compilers will usually produce the same code either way)
procedure int REVERSEBITS( int VALUE; int WIDTH ) {
  if WIDTH==1 then {
    return VALUE;
  } else {
    return (REVERSEBITS((VALUE & ((WIDTH>>1)-1)), (WIDTH>>1)) << (WIDTH>>1))
        | REVERSEBITS(((VALUE >> (WIDTH>>1)) & ((WIDTH>>1)-1)), (WIDTH>>1));
  }
}

Simplify the function code slightly by changing the functional definition, i.e. call with the value to be reversed and HALF the width of the value
procedure int REVERSEBITS( int VALUE; int WIDTH ) {
  if WIDTH==0 then {
    return VALUE;
  } else {
    return (REVERSEBITS((VALUE & (WIDTH-1)), (WIDTH >> 1)) << WIDTH)
        | REVERSEBITS(((VALUE >> WIDTH) & (WIDTH-1)), (WIDTH >> 1));
  }
}


text:
Q: how to pass arguments to a function without invoking it directly I am working on a database manager for an app. At a certain point I want to save some data like this:
//call the saveBillEvent
DatabaseManager.saveBillEvent(model, callbackfunc);

//accepts billeventmodel object
DatabaseManager.prototype.saveBillEvent = function(billEventModel, callback){
     db.transaction(
        RekeningDelen.DatabaseManager.databaseInstance,
        RekeningDelen.DatabaseManager.saveBillEventSQL,
        function(error) {
            console.log(error);
            console.log('transaction failed billeventspersons table creation ');
        },
        function(transactionId, result) {
            console.log("transcation success billeventspersons, set firstappboot to false");
            store.setItem("firstAppBoot", "false");
        }
    );
}

The saveBillEvent contains a transaction which at a given moment calls the saveBillEventSQL.
DatabaseManager.prototype.saveBillEventSQL = function(billEventModel, callback) {
  //here i need the billEventModel to create the SQL
    db.executeSql(
        transactionId,
        getAllBillEventsSQL,
        null,
        function(transactiondId, results) {
           //here i want to call the callback
            console.log('billevent saved ' + results);

        },
        function(response) {
            alert('fail1');
            console.log("SELECT billEvent query failed " +  response);
        }
    );
}

This function contains the final callback, which should call the passed callback, for a certain query and also needs the billEventModel to create the query. Thus the billEventModel and the callback should be passed to this function, but that's not possible since the transaction triggers it at a specific moment.
So my question is how to deal with this A(with params)->B(has params, but cant pass through)->C(needs params) problem?
I hope you all can understand my question, if not add a comment.


text: Q: ERROR in /home/lyffy/ngproject/cfp1/src/app/skeleton/skeleton.component.ts (2,8): Module '"./lodash/index"' has no default export. ERROR in /home/lyffy/ngproject/cfp1/src/app/skeleton/skeleton.component.ts (2,8): Module '"/home/lyffy/ngproject/cfp1/node_modules/@types/lodash/index"' has no default export. what's the solution guys please !!!!!


text:
Q: Why is this tutorial example of a shader not displaying any geometry as it is supposed to? This is an example from: http://pyopengl.sourceforge.net/context/tutorials/shader_1.xhtml
It is creating a vbo, binging it, and running it with a shader, but somewhere along the way, something is not working properly. :\
from OpenGLContext import testingcontext
BaseContext = testingcontext.getInteractive()

from OpenGL.GL import *

from OpenGL.arrays import vbo

from OpenGLContext.arrays import *

from OpenGL.GL import shaders

class TestContext( BaseContext ):

    def OnInit( self ):
        VERTEX_SHADER = shaders.compileShader("""#version 330
        void main() {
                     gl_Position = gl_ModelViewProjectionMatrix * gl_Vertex;
                     }""", GL_VERTEX_SHADER)

        FRAGMENT_SHADER = shaders.compileShader("""#version 330
        void main() {
                 gl_FragColor = vec4( 0, 3, 6, 1 );
                 }""", GL_FRAGMENT_SHADER)

        self.shader = shaders.compileProgram(VERTEX_SHADER,FRAGMENT_SHADER)

        self.vbo = vbo.VBO(
                        array( [
                            [  0, 1, 0 ],
                            [ -1,-1, 0 ],
                            [  1,-1, 0 ],
                            [  2,-1, 0 ],
                            [  4,-1, 0 ],
                            [  4, 1, 0 ],
                            [  2,-1, 0 ],
                            [  4, 1, 0 ],
                            [  2, 1, 0 ],
                        ],'f')
                      )

        def Render( self, mode):
            shaders.glUseProgram(self.shader)
        try:
            self.vbo.bind()

            try:
                glEnableClientState(GL_VERTEX_ARRAY);
                glVertexPointerf(self.vbo)
                glDrawArrays(GL_TRIANGLES, 0, 9)
            finally:
                self.vbo.unbind()
                glDisableClientState(GL_VERTEX_ARRAY);
        finally:
                shaders.glUseProgram(0)

if __name__ == "__main__":
    TestContext.ContextMainLoop()

Running this sample in the normal py 2.7 interactive terminal produces the following:
OpenGLContext.scenegraph.basenodes:Unable to load node implementation for
MMImageTexture: 'module' object has no attribute 'MMImageTexture'

In both cases, a window is produced, but there is no geometry displayed.
Is the basenodes issue indicating that MMImageTexture was a custom basenode and hasn't been created properly? I followed everything in the tut to the letter as far as I can tell. :\ So annoying...so annoying. Prease Helps Me's! :P
My system specs are win7, 4gb ram, corei5, 630m GeForce GT, using python 2.7 and python portable.


text:
Q: Javascript - remove a string in the middle of a string Thank you everyone for your great help !
Sorry, I have to edit my question.
What if the "-6.7.8" is a random string that starts with "-" and has two "." between random numbers?  such as "-609.7892.805667"?
===============
I am new to JavaScript, could someone help me for the following question?
I have a string AB.CD.1.23.3-609.7.8.EF.HI
I would like to break it into two strings: AB.CD.1.2.3.EF.HI (remove -609.7.8 in the middle) and AB.CD.6.7.8.EF.HI (remove 1.23.3- in the middle).
Is there an easy way to do it?
Thank you very much!

A: var s = "AB.CD.1.23.3-609.7.8.EF.HI";
var a = s.replace("-609.7.8","");
var b = s.replace("1.23.3-","");
console.log(a); //AB.CD.1.23.3.EF.HI
console.log(b); //AB.CD.609.7.8.EF.HI

A: You could use

     str.replace();
     var str = "AB.CD.1.2.3-6.7.8.EF.HI";
     var str1 = str.replace("-6.7.8",""); // should return "AB.CD.1.2.3.EF.HI"
     var str2 = str.replace("1.2.3-",""); // should return "AB.CD.6.7.8.EF.HI"

A: Use split() in String.prototype.split
var myString = "AB.CD.1.23.3-609.7.8.EF.HI";
var splits1 = myString.split("-609.7.8");
console.log(splits1);
var splits2 = myString.split("1.23.3-");
console.log(splits2);

A: With regular expressions:
s = 'AB.CD.1.23.3-609.7.8.EF.HI'
var re = /([A-Z]+\.[A-Z]+)\.([0-9]+\.[0-9]+.[0-9]+)-([0-9]+\.[0-9]+.[0-9]+)\.([A-Z]+\.[A-Z]+)/
matches = re.exec(s)
a = matches[1] + '.' + matches[2] + '.' + matches[4] // "AB.CD.1.23.3.EF.HI"
b = matches[1] + '.' + matches[3] + '.' + matches[4] // "AB.CD.609.7.8.EF.HI"


text:
Q: Symfony Bundle: how to avoid using __DIR__ to build the path to Doctrine mappings I'm finding myself dealing with the same problem in multiple bundles I've wrote.
The problem is that in my BundleNameBundle class I have to create the path to then load the mappings of Doctrine.
To do this I do something like:
/**
 * {@inheritdoc}
 */
public function build(ContainerBuilder $container)
{
    parent::build($container);

    $modelDir = realpath(__DIR__ . '/Resources/config/doctrine/mappings');
    $mappings = [
        $modelDir => 'SerendipityHQ\Bundle\QueuesBundle\Model',
    ];

    $ormCompilerClass = DoctrineOrmMappingsPass::class;
    if (class_exists($ormCompilerClass)) {
        $container->addCompilerPass(
            $this->getYamlMappingDriver($mappings)
        );
    }

    $container->addCompilerPass(new DaemonDependenciesPass());
}

Complete code here.
As you can see I use __DIR__ to get the path to the folder where the mappings are.
Now, Sensio Insights is alerting me that "Absolute path constants DIR and FILE should not be used".
Ok, but how can I solve this problem? Is there some alternative way to build the path to the mappings?

A: You can use $this->path. It returns the same result as __DIR__


text:
Q: Percent Increase between old and new values - kindof... I'd like to check if a formula I have been using is wrong.
I am studying and came across the following in how to calculate the percent increase/decrease of a value:

% increase = Increase ÷ Original Number × 100

For example if I buy a product for 2 and sell it for 4, the formula is:

(4-2)/2 x100 = 100% increase.

I get all of this. My issue is that I was using another formula until I came across this one (which is obviously wrong in this context) and I am amazed I have had it wrong for so many years; I feel as if it is a valid formula which I was taught a long time ago and maybe I am just applying it wrong, it is:

new value /orginal value x100

So in this example we would have:

4/2x100 = 200%

My question is, in what context do you use this forumla (if at all)?
Sorry for the somewhat vague question, it's just I can't remember how I aquired this formula; my memory is usually very good, which is why I feel as if it is used in some context and I have just mixed it up with something else.
Thanks,


text:
Q: How to prevent ARSCNView from rotating during orientation change I am using ARKit and I want to allow the users to use the app in both portrait and landscape mode.
I would like all UI controls to rotate on orientation change except for the ARSCNView.
I tried to transform the sceneView in the opposite direction but that didn't work.
override func viewWillTransition(to size: CGSize, with coordinator: UIViewControllerTransitionCoordinator) {
        super.viewWillTransition(to: size, with: coordinator)

        let targetRotation = coordinator.targetTransform
        let inverseRotation = targetRotation.inverted()

        coordinator.animate(alongsideTransition: { (context) in
            self.sceneView.transform = self.sceneView.transform.concatenating(inverseRotation)
            context.viewController(forKey: UITransitionContextViewControllerKey.from)
        }, completion: nil)

    }

How can I prevent the scene view of the ARKit session from rotating while allowing all other UI controls to rotate on orientation change?

A: You cannot specify device rotation rules on view basis. It has to be set on view controller basis. This is how iOS works. Thus, to achieve what you need you have to handle this by yourself. For example, if you're showing your ARSCNView as a full screen view, then you can present it inside a custom UIViewController sub-class, and set the rotation configuration for that controller.
Setting the supported view rotations for a specific view controller can be implemented in many ways, below are some of them.

Approach #1:
You can set the supported view orientations for any UIViewController by overriding your app delegate's method application:supportedInterfaceOrientationsForWindow:.
Sample code:
// this goes into your AppDelegate...
// Basically, this checks the current visible view controller  type  and  decide
// what orientations your app supports based on that view controller type (class)
func application(_ application: UIApplication, supportedInterfaceOrientationsFor window: UIWindow?) -> UIInterfaceOrientationMask {
    let visibleViewController = self.topViewController(withRootViewController: window?.rootViewController)

    // Support only portrait orientation for a specific view controller
    if visibleViewController is SomeViewController {
        return .portrait
    }

    // Otherwise, support all orientations (standard behaviour)
    return .allButUpsideDown
}

// This simple helper method is to extract the exact visible  view  controller  at
// the moment, as `window.rootViewController` could have some container controller
// like `UINavigationController` or so that holds more controllers into it
private func topViewController(withRootViewController rootViewController: UIViewController?) -> UIViewController? {
    if let rootViewController = rootViewController as? UITabBarController {
        return rootViewController.selectedViewController
    } else if let rootViewController = rootViewController as? UINavigationController {
        return rootViewController.visibleViewController
    } else if let presentedViewController = rootViewController?.presentedViewController {
        return topViewController(withRootViewController: presentedViewController)
    }
    return rootViewController
}

Reference:
application:supportedInterfaceOrientationsForWindow: method documentation

Approach #2:
Sub-class your UINavigationController and override the following property:
override var supportedInterfaceOrientations: UIInterfaceOrientationMask {
    return self.topViewController?.supportedInterfaceOrientations ?? .all
}

Now this always looks into your view controller's supportedInterfaceOrientations and set the supported orientations based on the return value. Doing this enables you to simply override this in any view controller you want, setting some custom value.
For example, in SomeViewController you could simply add:
override var supportedInterfaceOrientations: UIInterfaceOrientationMask {
    return .portrait
}

Reference:
supportedInterfaceOrientations property documentation

Approach #3:
If you don't want to sub-class your UINavigationController like in approach #2 above, you can set your SomeViewController as the navigation controller delegate implementing navigationControllerSupportedInterfaceOrientations(:)
Sample code:
override func viewDidLoad() {
    super.viewDidLoad()

    // ...

    self.navigationController?.delegate = self
}

// MARK: - UINavigationControllerDelegate

func navigationControllerSupportedInterfaceOrientations(_ navigationController: UINavigationController) -> UIInterfaceOrientationMask {
    return navigationController.topViewController?.supportedInterfaceOrientations ?? .all
}

Reference:
Matt's answer here


text:
Q: Infinite Sigma algebra contains infinite sequence of nonempty disjoint sets I realize this question has been answered but I wonder if this argument would work.
Proof:
If the infinite Sigma algebra X contains an infinite sequence of strictly nested nonempty sets, then we are done.
Otherwise, take the set of all maximal strict nests in X, then the smallest element of these nests are disjoint from each other. If there are infinitely many then we are done.
Otherwise, delete those small elements from each set in X and repeat the process above. Since the process can be repeated infinitely many times and the resulting smallest set in each nest form a disjoint set, the proof is finished.

A: EDIT: your argument does indeed work, although it could be written a bit clearer (e.g. justify why smallest elements of nests exist, and what you mean by "repeat the process infinitely many times" - this isn't hard and is a bit tedious, but it makes for a more complete proof).

Here's another nice way to attack the problem:
Call our $\sigma$-algebra $\mathbb{S}$. Say that a set $A$ is splitting if $A\in\mathbb{S}$ and $$\{A\cap B: B\in\mathbb{S}\}$$ is infinite. (Note that this is equivalent to $\{B: B\in\mathbb{S}, B\subseteq A\}$ being infinite.) That is, $A$ is splitting if it has infinitely many "pieces" in the $\sigma$-algebra. Note that most natural $\sigma$-algebras contain all singletons; for such a $\sigma$-algebra, "splitting" is the same as "infinite and in the $\sigma$-algebra." Note that since the $\sigma$-algebra is finite, the whole underlying set is splitting (finite $\sigma$-algebras, by contrast, have no splitting sets).
Now the crucial fact is the following:

$(*)\quad$ If $A\in\mathbb{S}$ is splitting, then $A$ can be partitioned as $A=B\sqcup C$ where $B, C\in\mathbb{S}$ are nonempty and $C$ is splitting.

(Of course this partition will not in general be unique, and of course both pieces can be splitting.) Note that if $(*)$ is true, we're done: we build a sequence of strictly decreasing sets in $\mathbb{S}$ $X=A_0\supsetneq A_1\supsetneq A_2\supsetneq ...$ (here "$X$" denotes the whole space), and so the sets $B_i=A_i\setminus A_{i+1}$ are disjoint elements of $\mathbb{S}$.
So can you prove $(*)$? HINT: first show that any splitting $A$ has a proper subset which is an element of $\mathbb{S}$; now show that if $D\cup E$ is splitting and $D, E\in\mathbb{S}$, then at least one of $D$ and $E$ is splitting.


text:
Q: Why I can't write "mailto:" in DataNavigateUrlFields? In GridView, I am tring to use HyperLinkField,I am trying to write 'mailto:' into it DataNavigateUrlFields parameter, but it renders to nothing: .... Why?

A: There was some time discussion on MSDN forum. The result of this disscusion was to using BoundField instead of HyperLinkField
UPDATE
I found it in my notes. the working code is following:
<asp:BoundField DataField="Email"
    DataFormatString="{0}"
    HtmlEncodeFormatString="false"
    HeaderText="Email" SortExpression="Email" />

And the discussion is here: How to create mailto: in gridview?

A: There seems to be an issue using HyperLinkField with mailto.
References:

*

*http://forums.asp.net/t/1014242.aspx/1

*http://www.itjungles.com/dotnet/hyperlinkfield-mailto
Suggested workaround is to use a BoundField instead:
<asp:BoundField DataField="SendTo"
    DataFormatString="{0}"
    HtmlEncodeFormatString="false" HeaderText="Email" SortExpression="SendTo" />

Or, alternatively, a HyperLink control within a template field:
<asp:TemplateField
HeaderText="E-mail"
SortExpression="Email">

<ItemTemplate>

<asp:HyperLink
ID="HyperLink1"
runat=server
Text='<%# Eval("Email") %>'
NavigateUrl='<%# Eval("Email", "mailto:{0}") %>'
/>

</ItemTemplate>
</asp:TemplateField>


text:
Q: Why when I use JsonIdentityInfo, I retrieve my parent's entity data only on the first occurence of the query returned values? I have two entities, one called Famille which is the parent entity and the other one called Variante which is the child entity.
I want, when I retreive all my Variantes, to get the corresponding Famille informations (all the fields).
To do that, I use the  @JsonIdentityInfo annotation.
But, unfortunately, the JSON returned by my service only return the Famille informations only for the first occurence of Famille.
Does anybody know how to return Famille informations for each occurence ?
This is my Famille entity :
@Table(name="famille")
@Data
@Entity
@JsonIdentityInfo(generator= ObjectIdGenerators.PropertyGenerator.class, property="id")
public class Famille implements Serializable {
    private static final long serialVersionUID = 1L;

    private int id;
    private String nom;
    private String couleur;
    private int position;
    private List<Variante> variantes;

    public Famille(int id) {
        this.id = id;
    }

    public Famille() {
    }

    @Id
    @GeneratedValue(strategy = IDENTITY)
    @Column(name="id")
    public int getId() {
        return id;
    }

    @Column(name="nom")
    public String getNom() {
        return nom;
    }

    @Column(name="couleur")
    public String getCouleur() {
        return couleur;
    }

    @Column(name="position")
    public int getPosition() {
        return position;
    }

    @OneToMany(mappedBy = "famille", cascade = CascadeType.ALL)
    //@JsonManagedReference
    @JsonIgnore
    public List<Variante> getVariantes() {
        return variantes;
    }

//I don't show the setters

}

And this is my Variante entity :
@Table(name="variante")
@Entity
@Data
@JsonIdentityInfo(generator= ObjectIdGenerators.PropertyGenerator.class, property="id")
public class Variante implements Serializable {

    private int id;
    private String nom;
    private Famille famille;
    private List<Affaire> affaires;

    public Variante(int id) {
        this.id = id;
    }

    public Variante() {
    }

    @Id
    @GeneratedValue(strategy = GenerationType.IDENTITY)
    @Column(name = "id")
    public int getId() {
        return id;
    }

    @Column(name="nom")
    public String getNom() {
        return nom;
    }

    @ManyToOne(fetch = FetchType.LAZY)
    @JoinColumn(name = "id_famille")
    //@JsonManagedReference
    public Famille getFamille() {
        return famille;
    }

    @OneToMany(mappedBy = "variante", cascade = CascadeType.ALL)
    @JsonIgnore
    public List<Affaire> getAffaires() {
        return affaires;
    }

    //I don't show the setters
}

This is my FamilleRestServices :
@CrossOrigin("*")
@RestController
public class FamilleRestServices {

    @Autowired
    private FamilleRepository familleRepository;

    @GetMapping(value = "/listFamilles")
    public List<Famille> listFamilles(){return familleRepository.findAll(Sort.by("Position").ascending());}
}

And finally my VarianteRestServices :
@CrossOrigin("*")
@RestController
public class VarianteRestServices {

    @Autowired
    VarianteRepository varianteRepository;

    @GetMapping(value = "/listVariantes")
    public List<Variante> listVariantes(){return varianteRepository.findAll();}

    @GetMapping(value = "/listVariantesByFamille/{idFamille}")
    public List<Variante> listVariantesByFamille(@PathVariable(name="idFamille") int idFamille){
        return varianteRepository.findVarianteByIdFamille(idFamille);
    }

    @GetMapping(value="/varianteByAffaire/{idAffaire}")
    public Variante varianteByAffaire(@PathVariable(name="idAffaire") int idAffaire){
        return varianteRepository.findVarianteByIdAffaire(idAffaire);
    }

    @PostMapping(value = "/listVariantes")
    public Variante save(@RequestBody Variante v){return varianteRepository.save(v);}

}

When I go to the adress : "localhost:8080/listVariantes" , this is the JSON that is returned by the page :
[
{
id: 1,
nom: "E2",
famille: {
id: 1,
nom: "ARRIEL1",
couleur: "32cd32",
position: 1,
hibernateLazyInitializer: { }
}
},
{
id: 2,
nom: "S1",
famille: 1
},
{
id: 3,
nom: "D",
famille: 1
},
{
id: 4,
nom: "M",
famille: 1
},
{
id: 5,
nom: "C2",
famille: 1
},
{
id: 6,
nom: "K1",
famille: 1
},
{
id: 7,
nom: "B",
famille: 1
},
{
id: 8,
nom: "C",
famille: 1
},
{
id: 9,
nom: "A",
famille: 1
},
{
id: 10,
nom: "C2",
famille: {
id: 2,
nom: "ARRIEL2",
couleur: "2b78e4",
position: 2,
hibernateLazyInitializer: { }
}
},
{
id: 11,
nom: "S2",
famille: 2
},
{
id: 12,
nom: "D",
famille: 2
},
{
id: 13,
nom: "C",
famille: 2
},
{
id: 14,
nom: "S1",
famille: 2
},
{
id: 15,
nom: "C1",
famille: 2
},
{
id: 16,
nom: "B",
famille: 2
},
{
id: 17,
nom: "E",
famille: 2
},
{
id: 18,
nom: "B1",
famille: {
id: 7,
nom: "ARRIUS2",
couleur: "ff9900",
position: 5,
hibernateLazyInitializer: { }
}
},
{
id: 19,
nom: "A",
famille: {
id: 11,
nom: "MAKILA2",
couleur: "999999",
position: 10,
hibernateLazyInitializer: { }
}
}
]


text:
Q: Mapping nested member by id Assume I have a User object - can be fetched via /api/users/:id
{
    "id": 3,
    "name": "John",
    "age": 26,
    "computer": 1
}

The computer property describes the type of the computer he owns - can be fetched
via /api/computers - returns array of computer types. I map this object to the Computer object
[{
    "id": 0,
    "name" : "stationary"
},
{
    "id": 1,
    "name": "laptop"
}]

Is there any way I can tell RestKit to automatically map the Computer object by the ID in the result? i.e when I GET the user from RestKit, RestKit will automatically initiate a new GET (behind the scene) in order to get the real Computer object from the server (rather than just represent it as an ID)
i.e
User *someUser = ...; // GET with restkit
someUser.computer = ...; // a Computer object with properties .name and .id

EDIT
This is available while using Core Data as seen here. It is unclear whether one can achieve the same without using core data..

A: The link you refer to is for existing connecting objects to new objects in a response, not triggering a GET request as a result of new object creation.
Triggering the GET is not a provided feature of RestKit so you need to implement that logic yourself.


text:
Q: $\int e^{\cos(x)} \cos(nx)\ dx$ using the residue theorem I am trying to evaluate the following integral using the residue theorem:
$$\int_0^{2\pi} e^{ \cos(\theta)} \cos(n\theta) d\theta$$
I have already evaluated $\int_0^{2\pi} e^{e^{-i\theta}} e^{i n\theta} d\theta$ using the residue theorem by making the substitution $z = e^{i\theta}$ and then finding the coefficient of the $z^{-1}$ term in the Laurent series expansion. Now, however, this no longer works, so any help would be appreciated.
Thank you.

A: $$\int_0^{2\pi} e^{ \cos(\theta)} \cos(n\theta) d\theta=\operatorname{Re}\left(\int_0^{2\pi} e^{ \cos(\theta)+in\theta} d\theta\right)$$
Let $z=e^{i\theta}$. Then,
$$\int_0^{2\pi} e^{ \cos(\theta)+in\theta} d\theta=\dfrac{1}{i}\oint_{|z|=1}\dfrac{dz}{z}e^{(z+z^{-1})/2}z^n=\dfrac{1}{i}\sum^\infty_{k=0}\dfrac{1}{2^kk!}\oint_{|z|=1}dz\dfrac{e^{z/2}}{z^{k+1-n}}$$
Use the fact that the integrand is anayltic in the unit circle when $0\leq k\leq n-1$. This will help you evaluate the integral. The last equation occurs since
$$\sum^\infty_{k=0}\dfrac{1}{2^kk!}\dfrac{e^{z/2}}{z^{k}}={e^{(z+z^{-1})/2}}=e^{z/2}e^{z^{-1}/2}=e^{z/2}\sum^{\infty}_{k=0}\dfrac{z^{-k}}{2^kk!}$$


text:
Q: Cannot get Fedora 35 to log errors I recently got myself a Fedora VM to do coding with and I cannot get Apache to log errors
My httpd.conf is still pretty default and so is my PHP.
sudo tail -f /var/log/httpd/error_log output:
AH00558: httpd: Could not reliably determine the server's fully qualified domain name, using fe80::ef21:ea50:d362:afe9%ens33. Set the 'ServerName' directive globally to suppress this message
[Tue Aug 30 18:06:08.311018 2022] [lbmethod_heartbeat:notice] [pid 5172:tid 5172] AH02282: No slotmem from mod_heartmonitor
[Tue Aug 30 18:06:08.316093 2022] [mpm_event:notice] [pid 5172:tid 5172] AH00489: Apache/2.4.54 (Fedora Linux) configured -- resuming normal operations
[Tue Aug 30 18:06:08.316107 2022] [core:notice] [pid 5172:tid 5172] AH00094: Command line: '/usr/sbin/httpd -D FOREGROUND'
[Tue Aug 30 18:14:21.328254 2022] [mpm_event:notice] [pid 5172:tid 5172] AH00492: caught SIGWINCH, shutting down gracefully
[Tue Aug 30 18:14:22.415182 2022] [suexec:notice] [pid 5669:tid 5669] AH01232: suEXEC mechanism enabled (wrapper: /usr/sbin/suexec)
AH00558: httpd: Could not reliably determine the server's fully qualified domain name, using fe80::ef21:ea50:d362:afe9%ens33. Set the 'ServerName' directive globally to suppress this message
[Tue Aug 30 18:14:22.422270 2022] [lbmethod_heartbeat:notice] [pid 5669:tid 5669] AH02282: No slotmem from mod_heartmonitor
[Tue Aug 30 18:14:22.425068 2022] [mpm_event:notice] [pid 5669:tid 5669] AH00489: Apache/2.4.54 (Fedora Linux) configured -- resuming normal operations
[Tue Aug 30 18:14:22.425082 2022] [core:notice] [pid 5669:tid 5669] AH00094: Command line: '/usr/sbin/httpd -D FOREGROUND'

I already set Apache LogLevel to info and in php.ini I set it to log errors and not output them and also enabled HTML errors
Please let me know if you need anything else.


text:
Q: How to route MediaPlayer1 to wired headset and MediaPlayer2 to BT headset? I'm trying to play two files at the same time and route one to wired headset and the other to the BT headset.  Is this even possible? Any ideas how I can achieve this? I'm targeting OS 2.3 and greater.

A: You can try creating two MediaPlayers with different stream types:
btPlayer = new MediaPlayer(...);
wiredPlayer = new MediaPlayer(...);
...
btPlayer.setAudioStreamType(AudioManager.STREAM_VOICE_CALL);
wiredPlayer.setAudioStreamType(AudioManager.STREAM_MUSIC);
...

Of cause you'll need to put extra code to redirect btPlayer to bluetooth headset. For this you'll need to use startBluetoothSco() and setBluetoothScoOn().
Also note, that audio can be redirected to bluetooth headset only on AudioManager.STREAM_VOICE_CALL. But if you are using a2dp bluetooth device, you can redirect audio to this device in AudioManager.STREAM_MUSIC stream as well.


text:
Q: Solve for value without using Solver I currently have the following in excel for other users.

The Number column does not change. Users will input values in Multiplier 1 and Multiplier 2 columns and they will get a value in Outcome column.
Is there an automatically way where the user can also input a value in Outcome column and the Multiplier 1 column will change?
Currently Number and Outcome column are protected, will I need to unprotect the Outcome column?

A: I recommend you use some VBA code using the Sub Worksheet_Change(ByVal Target as range) in the worksheet.
If the user enters a value in D2 it will put the formula "=D2/(A2*C2)" in B2
If the user enters a value in B2 it will put the formula "=A2*B2*C2" in D2
Option Explicit
Private Sub Worksheet_Change(ByVal Target As Range)
Application.EnableEvents = False
If Target.Cells.Count > 1 Then Exit Sub
On Error GoTo LastLine
If Not Intersect(Target, Range("D2")) Is Nothing Then
    Range("B2").Formula = "=D2/(A2*C2)"
ElseIf Not Intersect(Target, Range("B2")) Is Nothing Then
    Range("D2").Formula = "=A2*B2*C2"
End If
LastLine:
Application.EnableEvents = True
End Sub

A: This can be done.   Begin by noticing that your formula is so simple that you
 Can easily solve for multiplier1 as a function of:
outcome divided by (number times multiplier2)
Next get tricky by adding a 1 pixel wide column that will contain your formula
 for outcome to the right of (now an input not a formula) the original
outcome column.
Similarly add a 1 pixel wide col to the right of multiplier1 that contains
 your new formula for multiplier1. Adjust data validation on original input
cells for multiplier1 and outcome to allow only one of the two to be
entered at a time (use isblank function appropriately in  an excel custom data
validation rule for each cell).
Finally right align the two 1 pixel wide cells so that their calculated values
 appear within the corresponding enterable cells when they are blank.
 Yes it's tricky but it works.
Sorry this is just an outline but I have used this in an application and it
works great.   No vba, so undo redo don't break. Try it you'll like it.


text:
Q: Programming a weekly task Android I'm trying to schedule on Android a specific part of my code to be run every week (or every number of days, but set manually...). The thing is: I've been looking to the AlarmManager class, but I don't know if maybe the problem is that I don't know how to use it or what, but I don't know how to schedule part of my code to be launched every week.
Any help please?

A: I'd have a running thread that sleeps for the time that is set manually, remember that this time should be passed as milliseconds.
To model the time, I'd use the Calendar class, because is easier to user the constants it has, like Calendar.DAY_OF_WEEK. Yo can look on how to use this constants for the purpose you have.


text:
Q: Spectral energy distribution fitting tools or routines I have observed magnitudes and fluxes for an object in different wavelengths from optical to mm. Now I need a tool, routine or something like that to fit a spectral energy distribution (SED) and derive some physical parameters from the fit.
I'm looking for a ready tool which can be run remotely or installed locally.
Mind you, I'm aware of this: http://caravan.astro.wisc.edu/protostars/

A: There certainly are, but it depends on what the object is?
For example, I have used the `flared disk' model of Dullemond Dominik & Natta (2001) to model the SED of hot dust around a sgB[e] star
http://www.mpia.de/homes/dullemon/ppdisks.html
where at optical wavelengths emission is dominated by a ~25kK stellar source but at 10 microns it is due to hot dust (~1000K) that forms in a equatorial disk around the central B[e] star and a cold dust component (~100K) that dominates the long-wavelength emission. CMFGEN will also model the SED for hot stars, LBVs, Wolf-Rayets etc., but the underlying physical conditions are very different, while a QSO would be very different again - and it's really the geometry, distribution and composition of material that affect the SED of an object, so different objects require different models. Short of the basic approach of fitting one or more Black Body models, I don't think there's a one-size-fits-all approach.


text:
Q: How to merge multiple csv files on common columns and keep the non common ones as separate columns? I have three csv files which contains data about covid 19. The first csv has information about number of confirmed cases, the second one has information about number of deaths and the third one has information about number of recovery.
So this is how the dataframes looks like
import pandas as pd

df1 = pd.read_csv('/Users/sr/covid_csvs/confirmed.csv')

df2 = pd.read_csv('/Users/sr/covid_csvs/deaths.csv')

df3 = pd.read_csv('/Users/sr/covid_csvs/recovery.csv')

print(df1.head(5))

  Province/State Country/Region      Lat     Long     Date  Confirmed
0            NaN    Afghanistan  33.0000  65.0000  1/22/20          0
1            NaN        Albania  41.1533  20.1683  1/22/20          0
2            NaN        Algeria  28.0339   1.6596  1/22/20          0
3            NaN        Andorra  42.5063   1.5218  1/22/20          0
4            NaN         Angola -11.2027  17.8739  1/22/20          0

print(df2.head(5))

  Province/State Country/Region      Lat     Long     Date     Deaths
0            NaN    Afghanistan  33.0000  65.0000  1/22/20          0
1            NaN        Albania  41.1533  20.1683  1/22/20          0
2            NaN        Algeria  28.0339   1.6596  1/22/20          0
3            NaN        Andorra  42.5063   1.5218  1/22/20          0
4            NaN         Angola -11.2027  17.8739  1/22/20          0

print(df3.head(5))

  Province/State Country/Region      Lat     Long     Date  Recovery
0            NaN    Afghanistan  33.0000  65.0000  1/22/20         0
1            NaN        Albania  41.1533  20.1683  1/22/20         0
2            NaN        Algeria  28.0339   1.6596  1/22/20         0
3            NaN        Andorra  42.5063   1.5218  1/22/20         0
4            NaN         Angola -11.2027  17.8739  1/22/20         0

Now I want to merge all the three dataframes such that I get the below result
  Province/State Country/Region      Lat     Long     Date  Confirmed  Deaths Recovery
0            NaN    Afghanistan  33.0000  65.0000  1/22/20          0       0        0
1            NaN        Albania  41.1533  20.1683  1/22/20          0       0        0
2            NaN        Algeria  28.0339   1.6596  1/22/20          0       0        0
3            NaN        Andorra  42.5063   1.5218  1/22/20          0       0        0
4            NaN         Angola -11.2027  17.8739  1/22/20          0       0        0

So I tried doing something like below
df_merged = pd.concat([df1, df2, df3])
df_merged.to_csv('merged.csv', sep=',', encoding='utf-8', index=False)

But I do not get the required csv. How do I do this?

A: Idea is create MultiIndex by DataFrame.set_index for each DataFrame, then concat with axis=1 and last remove index=False in to_csv:
cols = ['Province/State', 'Country/Region','Lat','Long','Date']

dfs = [df1, df2, df3]
df_merged = pd.concat([x.set_index(cols) for x in dfs], axis=1)
df_merged.to_csv('merged.csv', sep=',', encoding='utf-8')

Or convert MultiIndex to column and then use index=False in to_csv:
cols = ['Province/State', 'Country/Region','Lat','Long','Date']

dfs = [df1, df2, df3]
df_merged = pd.concat([x.set_index(cols) for x in dfs], axis=1).reset_index()
df_merged.to_csv('merged.csv', sep=',', encoding='utf-8', index=False)


text:
Q: Create  &  dynamically while in loop jquery I have this jquery code that loops through all rows on my table1.
$('#table_1').find('tr').each(function (i, el) {
   var $tds = $(this).find('td');
   var test1 = $tds.eq(0).text();
   var test2 = $tds.eq(1).text();
   var test3 = $tds.eq(2).text();
   console.log (test1 + test2 + test3);
});

And this is the table where I will pass the values of rows from table1. What I need to do is to dynamically add rows and pass the value within this table until the loop ends. How can I do it using jquery?

       FROM:
      Blah Blah Blah Blah

       ADDRESS:
      Blah Blah Blah Blah

       CONTACT NUMBER:
      Blah Blah Blah Blah

       TO:
      Blah Blah Blah Blah

       ADDRESS:
      Blah Blah Blah Blah

       BARANGAY:
      Blah Blah Blah Blah

       CITY & PROVINCE:
      Blah Blah Blah Blah

       CONTACT NUMBER:
      Blah Blah Blah Blah

       PRODUCT & PRICE
      Blah Blah Blah Blah

I hope someone could help me.

A:

$("#AddRow").on("click", function() {
  $("#tbl").append("
Blah	Bll
")
  for (let i = 0; i < 3; i++) {
    $("#tbl").append("
BlahLoop	Bll Loop
")
  }
})

<button id=AddRow>Click To Add
</button>

       FROM:
      Blah Blah Blah Blah

       ADDRESS:
      Blah Blah Blah Blah

       CONTACT NUMBER:
      Blah Blah Blah Blah

       TO:
      Blah Blah Blah Blah

       ADDRESS:
      Blah Blah Blah Blah

       BARANGAY:
      Blah Blah Blah Blah

       CITY & PROVINCE:
      Blah Blah Blah Blah

       CONTACT NUMBER:
      Blah Blah Blah Blah

       PRODUCT & PRICE
      Blah Blah Blah Blah

A: You can dynamically solve this as it is below.
From the table_1 iterate the value and push it in a array, then by using a button on click you can append those table details in the another table as it is below
//Assume array "value" consists of table_1 data.

    let value = ['Bathri','Coimbatore','23'];
    let header = ["Name","Address","Age"];

    $("#AddRow").on("click", function() {

    for(let v=0; v < 3; v++){
     $("#tbl").append("
"+header[v]+"	"+value[v]+"
")
    }

    })

<button id=AddRow>Click To Add
</button>

       FROM:
      Blah Blah Blah Blah

       ADDRESS:
      Blah Blah Blah Blah

       CONTACT NUMBER:
      Blah Blah Blah Blah

       TO:
      Blah Blah Blah Blah

       ADDRESS:
      Blah Blah Blah Blah

       BARANGAY:
      Blah Blah Blah Blah

       CITY & PROVINCE:
      Blah Blah Blah Blah

       CONTACT NUMBER:
      Blah Blah Blah Blah

       PRODUCT & PRICE
      Blah Blah Blah Blah


text:
Q: Protect central app.config I have an application which is executed when a user logs out. This is achieved via GPO. The application needs access to a database.
My App.config contains the connection string. I tried to encrypt it using aspnet_regiis but I just read that this works only per machine. While it worked on mine flawless it of course crashed on other machines.
I can not find another way on how to protect the connection string in this scenario. I have no setup so I can not execute aspnet_regiis on the local machine. How do you usually handle this problem?
Could you deploy the key for encrypting the App.config via GPO? Where do I find that key?

A: It's very hard if not impossible to achieve this.
See: http://www.grouppolicy.biz/2013/11/why-passwords-in-group-policy-preference-are-very-bad/
You will need to create a service that recieves the requests and communicates with the database, this service will be run on your server and thus you can keep your connectionstring safe.
One way would be to create a webpage that recieves postdata from the clients.


text:
Q: cant install jockey-gtk i am trying to install jockey on lubuntu to resolve an issue with my ATH-AR5BXB63 wifi card and get this....
linuxtop@linuxtop-HP-G6000-Notebook-PC:~$ sudo apt-get install jockey-gtk
[sudo] password for linuxtop:
Reading package lists... Done
Building dependency tree
Reading state information... Done
Note, selecting 'ubuntu-drivers-common' instead of 'jockey-gtk'
ubuntu-drivers-common is already the newest version.
0 to upgrade, 0 to newly install, 0 to remove and 89 not to upgrade.
linuxtop@linuxtop-HP-G6000-Notebook-PC:~$

no idea what it is trying to do but any help would be appreciated

A: Are you running Ubuntu 14.04? If that's the case, jockey is not being used anymore, that's why is telling you that ubuntu-drivers-common are already installed.
I'm not sure which is the default package manager in Lubuntu, but in the standard ubuntu you can run software-properties-gtk and navigate to the drivers tab. It has the same functions that jockey-gtk use to manage.


text:
Q: Asymptotic behaviour of $K$-Bessel function in transition range It is known that the famous mistake of Iwaniec-Sarnak in their paper of $L^\infty$ norm of eigenfunction of non-cocompact arithmetic surfaces in lemma (A1) is because of they did not consider the bump of $K$-Bessel function at transition range.

*

*First, I do not understand which part of the proof (sketched below) is flawed.
An eigenfunction of $SL_2(\mathbb{Z})\backslash\mathcal{H}^2$ with eigenvalue $1/4+t^2$  looks like $$\phi(z)=\sqrt{y}\sum_{n\neq0}a_nK_{it}(2\pi|n|y)e(nx).$$ First they proved a bound of sum of Fourier coefficients (Ramanujan on average) which is $(t>0)$
$$
\sum_{n\le N}|a_n|^2\ll e^{\pi t}(t+N).
$$
Then, I guess that they are using a Cauchy-Schwarz inequality and an asymptote that for $t>2\pi|n|y$ $$e^{\pi t}|K_{it}(2\pi|n|y)|^2\ll (t^2-|n|^2y^2)^{-1/2},$$to deduce final final bound. The above inequality can be found here lemma 2.3 and 2.4. Isn't the above asymptote correct?

2)It is mentioned in Sarnak's letter to Morawetz (equation 43) that $K_{it}$ has a bump of size $t^{1/6}$ near $y=t$. Do we know precise asymptote of $K_{it}$ uniformly in $y$ and $t$ so that the above argument can be rectified?

A: For a published account of the corrected proof, see Section 10 in Blomer-Holowinsky: Bounding sup-norms of cusp forms of large level, Invent. Math. 179 (2010), 645-681. See especially pages 679-680, where you can also find the precise asymptotics of $K_{it}$ in the transitional range.
Actually, a few years ago, a colleague of mine asked me about the same thing. What follows is my email response in slightly edited form (I am too busy to re-read carefully):
There are several problems with Lemma A.1 and its proof. The problems arose from not using correctly the asymptotics of $K_{ir}(y)$ in the transitional range $y\approx r$. For $|y-r|<r^{1/3}$ the function is about $e^{-\pi r/2} r^{-1/3}$ times a phase, while for $|y-r|>r^{1/3}$ it is about $e^{-\pi r/2} |y^2-r^2|^{-1/4}$ times a phase, with the additional remark that for $y$ large the exponential decay kicks in. As a consequence:

*

*The display below (A.2) is wrong: $r^{-1}$ should be lowered to $r^{-4/3}$. This is not a big problem, since if we integrate from $r/2$ (instead from $r$), then the bound
is OK (I learned these things from papers by Strömbergsson). In other words, in the line before (A.3) one should set $N=r/(4\pi Y)$. Actually (A.3) is too weak for this
purpose, as explained below. Instead the following should be used, which is known by deeper methods:
$$ \sum_{0<|n|<N} |\rho(n)|^2 \ll e^{\pi r} r^\epsilon N. \tag{1}$$

*The last display on p.316 is wrong. In fact for fixed $b\geq 0$ one has
$$ \sum_{n\neq 0} |n|^b |K_{ir}(2\pi|n|y)|^2 \ll e^{-\pi r} (r/y)^b (r^{-2/3}+1/y), $$
and this is best possible for $2\pi y < r+O(1)$, e.g. the first term in the parantheses comes from $2\pi|n|y$ very close to $r$. This shows that the last display on p.316
should read
$$ |\phi(z)|^2 \ll Y^{-2} (Y+r) (y^{-1}r+Y)^2 (yr^{-2/3}+1). $$
For the choice $Y=r/(2\pi y)$ this gives
$$ |\phi(z)|^2 \ll (Y+r) (yr^{-2/3}+1), $$
which is too weak eventually. Using (1) above in place of (A.3), one gets
$$ |\phi(z)|^2 \ll r^\epsilon Y (yr^{-2/3}+1), $$
i.e.,
$$ \phi(z) \ll r^\epsilon (r^{1/6} + (r/y)^{1/2}) {\|\phi\|}_2. \tag{2}$$
This is a bit weaker than Lemma A.1. In fact this is the correct version of Lemma A.1 since $\max_{0\leq x\leq 1}|\phi(x+ir/(2\pi))|$ is about $r^{1/6}{\|\phi\|}_2$.
Much the same correction is explained on pp.38-40 of Sarnak's letter to Morawetz.
A bit more detail is given in the Blomer-Holowinsky paper, on p.679. Actually, the bound on top of p.680 is only justified for $t>1$ and $y>1$, but it is valid for all
$y>0$ and all forms (including forms violating the Selberg conjecture).
Added. For a generalization of (2) to spherical Hecke-Maass forms over an arbitrary number field, see Lemma 9 in this paper. Note that $\phi$ in that lemma satisfies ${\|\phi\|}_2=1$. Note also that (1) above was (*) in an earlier version of this post.


text:
Q: very magic regex that will allow me to replace these images? I'm using vim daily for manipulating text and to write code. However, every time I have to perform any substitution, or do any kind of regex work, it drives me crazy, and I have to switch to sublime. I'd like to know, what's the correct way of turning this:

into
<img src="<%= image_path("whatever.png") %>"/>
<img src="<%= image_path("x.png") %>"/>

In sublime, I can use this as the regex for search: src="(.*?.png)" and this as the regex for substitution: src="<%= asset_path("\1") %>". In vim, if I do this: :%s/\vsrc="(.*?.png)/src="<%= asset_path("\1") %>"/g I get:
E62: Nested ?
E476: Invalid command

What am I not doing right?

A: As @nhahtdh stated Vim's dialect of regex uses \{-} as the non-greedy quantifier. If you use the very magic flag it is just {-}. So your command turns into:
:%s/\vsrc="(.{-}.png)/src="<%= asset_path("\1") %>"/g

However you didn't escape the . in .png so:
:%s/\vsrc="(.{-}\.png)/src="<%= asset_path("\1") %>"/g

But we can still do better! By using \zs and \ze we can avoid retyping the src=" bit. \zs and \ze mark the start and end of the match where the substitution will occur.
:%s/\vsrc="\zs(.\{-}\.png)"/<%= image_path("\1") %>"/g

However we still are not done because we can take it one step further if we carefully choose where we put \zs and \ze then we can use vim's & in the substitution. It is like \0 in Perl's regex syntax. Now we don't need any capture groups which nullifies the need for the very magic flag.
:%s/src="\zs.\{-}\.png\ze"/<%= image_path("&") %>/g

For more help see the following documentation:
:h /\zs
:h /\{-
:h s/\&

A: According to this website, the syntax for lazy quantifier in vim is different from the syntax used in Perl-like regex.
Let me quote the website:

                                                          */\{-*
\{-n,m}   matches n to m of the preceding atom, as few as possible
\{-n}     matches n of the preceding atom
\{-n,}    matches at least n of the preceding atom, as few as possible
\{-,m}    matches 0 to m of the preceding atom, as few as possible
\{-}      matches 0 or more of the preceding atom, as few as possible
          {Vi does not have any of these}

          n and m are positive decimal numbers or zero

                                                        *non-greedy*
If a "-" appears immediately after the "{", then a shortest match
first algorithm is used (see example below).  In particular, "\{-}" is
the same as "*" but uses the shortest match first algorithm.

A: :%s/"\(.*\)"/"<%= image_path("\1") %>"/g
The double quotes are out main pattern. Everything we want to capture gets thrown into a group \( \) so we can later relate to it via \1.

If you use very magic, you have to escape the =, thus \vsrc\=(.*).png". So using your way the answer is:
:%s/\vsrc\="(.*\.png)"/src="<%= image_path("\1") %>"/g

It's easy to see if you :set hlsearch and then play around with /. :)


text:
Q: Suggest some journals that I can try to publish my paper in? A little bit about myself: I'm in my senior year of high school, and I have a passion for majoring in math. Recently, I have written a paper that explores some consequences that result from FLT.
My question is that I want to publish it somewhere, but I am not familiar with lists of journals. Because the results are pretty trivial, I assume it is meant for lower-end journals? It would be great if you can suggest me some.
Thank you for reading, here is the link to the paper: https://www.scribd.com/document/422435256/On-the-Rationality-and-Transcendentality-of-Solutions-to-the-Equation-x-n-y-n-z-n

A: First, congratulations. I took a quick look at your paper. I think your characterization as "pretty trivial" is a little too modest, but not much. So you will probably not be able to publish in a widely read high quality journal.
I suggest you try some of the links at this search for publish high school math research


text:
Q: How to check what type my video card is and its memory size? I need to install some programs that require minimal size of video card memory, how do I get the size and possibly what vendor and type of my video card?
Output of lspci  | grep VGA  | cut -d " " -f 1 | xargs lspci -vv -s :
00:02.0 VGA compatible controller: Intel Corporation 2nd Generation Core Processor Family Integrated Graphics Controller (rev 09) (prog-if 00 [VGA controller])
    Subsystem: Elitegroup Computer Systems Device 9981
    Control: I/O+ Mem+ BusMaster+ SpecCycle- MemWINV- VGASnoop- ParErr- Stepping- SERR- FastB2B- DisINTx+
    Status: Cap+ 66MHz- UDF- FastB2B+ ParErr- DEVSEL=fast >TAbort- <TAbort- <MAbort- >SERR- <PERR- INTx-
    Latency: 0
    Interrupt: pin A routed to IRQ 44
    Region 0: Memory at f0000000 (64-bit, non-prefetchable) [size=4M]
    Region 2: Memory at d0000000 (64-bit, prefetchable) [size=256M]
    Region 4: I/O ports at 1800 [size=64]
    Expansion ROM at <unassigned> [disabled]
    Capabilities: <access denied>
    Kernel driver in use: i915

A: Run this command from a Terminal:
  lspci  | grep VGA  | cut -d " " -f 1 | xargs lspci -vv -s

This will show you a verbose sheet about your video card.


text:
Q: Ping problem with Windows Server machine We installed 3 computer using windows server 2003 .
Only one computer is pingable from outside. However I am able to ping any machine on the network from all the 3 computers . I feel that the service that runs PING  is not running on The 2 machines ...although it can ping outside servers ....Can anyone tell me ?
Rgds
Nishant

A: It is most likely that this error is firewall related. Most firewalls prevent Echo requests (ping) by default. If you are using windows firewall, you need to go into the the firewall settings utility in control panel, go to the advanced tab then click the settings button in the ICMP section. You then need to tick the box that says 'Allow incoming echo requests'

A: The most obvious one is Windows Firewall - disable it in control panel if you don't need it (I'd advise against this TBH) or add an exception (in the 'Exceptions' tab funnily enough)


text:
Q: XNA Collision detection on a list of objects I'm trying to detect collision on a list of enemy objects, however it's only working on the last created object. I've tried both :
for (int i = 0; i < enemies.Count; i++)
{
    if (IntersectsPixel(player.rectangle, player.textureData, enemies[i].rectangle, enemies[i].textureData))
    {
        touched = true;
    }
    else
    {
        touched = false;
    }
}

And :
foreach (Enemy enemy in enemies)
{
    if (IntersectsPixel(player.rectangle, player.textureData, enemy.rectangle, enemy.textureData))
    {
        touched = true;
    }
    else
    {
        touched = false;
    }
}

Both of which I'm putting in the Update method. The enemies are created every few seconds so i know the detection works, but once the next one appears, the last one stops working...

A: you check last item only, you must break loop, when IntersectsPixel true and process the object
for (int i = 0; i < enemies.Count; i++)
{
    if (IntersectsPixel(player.rectangle, player.textureData, enemies[i].rectangle, enemies[i].textureData))
    {
        touched = true;
        break;
    }
}

or use linq to collect all thus objects:
var resTrue = enemies.Where(x=>x.IntersectsPixel(player.rectangle, player.textureData, enemies[i].rectangle, enemies[i].textureData)).ToList();
var resFalse = enemies.Where(x=>!x.IntersectsPixel(player.rectangle, player.textureData, enemies[i].rectangle, enemies[i].textureData)).ToList();

A: Why don't you implement a property bool Touched in class Enemy?
That way, you could change your code like this:
if (/*check for collision*/)
    enemy.Touched = true;

Better yet, instead of Touched, implement a method OnTouched(/*arguments*/), so you can do this:
if (/*check for collision*/)
    enemy.OnTouched(/*arguments*/); // Which would perform any and all necessary actions on the touched object


text:
Q: How does the Python's range function work? If I write
for i in range(5):
      print i

Then it gives 0, 1, 2, 3, 4
Does that mean Python assigned 0, 1, 2, 3, 4 to i at the same time?
However if I wrote:
for i in range(5):
      a=i+1

Then I call a, it only gives 5
But if I add ''print a'' it gives 1, 2, 3, 4, 5
So my question is what is the difference here?
Is i a string or a list or something else?
Or maybe can anyone help me to sort out:
for l in range(5):
    #vs,fs,rs are all m*n matrixs,got initial values in,i.e vs[0],fs[0],rs[0] are known
    #want use this foor loop to update them
    vs[l+1]=vs[l]+fs[l]
    fs[l+1]=((rs[l]-re[l])
    rs[l+1]=rs[l]+vs[l]
#then this code gives vs,fs,rs

If I run this kind of code, then I will get the answer only when l=5
How can I make them start looping?
i.e l=0 got values for vs[1],fs[1],rs[1],
then l=1 got values for vs[2],rs[2],fs[2]......and so on.
But python gives different arrays of fs,vs,rs, correspond to different value of l
How can I make them one piece?

A: for i in range(5):

is the same as
for i in [0,1,2,3,4]:

A: range(x) returns a list of numbers from 0 to x - 1.
>>> range(1)
[0]
>>> range(2)
[0, 1]
>>> range(3)
[0, 1, 2]
>>> range(4)
[0, 1, 2, 3]

for i in range(x): executes the body (which is print i in your first example) once for each element in the list returned by range().
i is used inside the body to refer to the "current" item of the list.
In that case, i refers to an integer, but it could be of any type, depending on the objet on which you loop.

A: A "for loop" in most, if not all, programming languages is a mechanism to run a piece of code more than once.
This code:
for i in range(5):
    print i

can be thought of working like this:
i = 0
print i
i = 1
print i
i = 2
print i
i = 3
print i
i = 4
print i

So you see, what happens is not that i gets the value 0, 1, 2, 3, 4 at the same time, but rather sequentially.
I assume that when you say "call a, it gives only 5", you mean like this:
for i in range(5):
    a=i+1
print a

this will print the last value that a was given. Every time the loop iterates, the statement a=i+1 will overwrite the last value a had with the new value.
Code basically runs sequentially, from top to bottom, and a for loop is a way to make the code go back and something again, with a different value for one of the variables.
I hope this answered your question.

A: When I'm teaching someone programming (just about any language) I introduce for loops with terminology similar to this code example:
for eachItem in someList:
    doSomething(eachItem)

... which, conveniently enough, is syntactically valid Python code.
The Python range() function simply returns or generates a list of integers from some lower bound (zero, by default) up to (but not including) some upper bound, possibly in increments (steps) of some other number (one, by default).
So range(5) returns (or possibly generates) a sequence: 0, 1, 2, 3, 4 (up to but not including the upper bound).
A call to range(2,10) would return: 2, 3, 4, 5, 6, 7, 8, 9
A call to range(2,12,3) would return: 2, 5, 8, 11
Notice that I said, a couple times, that Python's range() function returns or generates a sequence.  This is a relatively advanced distinction which usually won't be an issue for a novice.  In older versions of Python range() built a list (allocated memory for it and populated with with values) and returned a reference to that list.  This could be inefficient for large ranges which might consume quite a bit of memory and for some situations where you might want to iterate over some potentially large range of numbers but were likely to "break" out of the loop early (after finding some particular item in which you were interested, for example).
Python supports more efficient ways of implementing the same semantics (of doing the same thing) through a programming construct called a generator.  Instead of allocating and populating the entire list and return it as a static data structure, Python can instantiate an object with the requisite information (upper and lower bounds and step/increment value) ... and return a reference to that.
The (code) object then keeps track of which number it returned most recently and computes the new values until it hits the upper bound (and which point it signals the end of the sequence to the caller using an exception called "StopIteration").  This technique (computing values dynamically rather than all at once, up-front) is referred to as "lazy evaluation."
Other constructs in the language (such as those underlying the for loop) can then work with that object (iterate through it) as though it were a list.
For most cases you don't have to know whether your version of Python is using the old implementation of range() or the newer one based on generators.  You can just use it and be happy.
If you're working with ranges of millions of items, or creating thousands of different ranges of thousands each, then you might notice a performance penalty for using range() on an old version of Python.  In such cases you could re-think your design and use while loops, or create objects which implement the "lazy evaluation" semantics of a generator, or use the xrange() version of range() if your version of Python includes it, or the range() function from a version of Python that uses the generators implicitly.
Concepts such as generators, and more general forms of lazy evaluation, permeate Python programming as you go beyond the basics.  They are usually things you don't have to know for simple programming tasks but which become significant as you try to work with larger data sets or within tighter constraints (time/performance or memory bounds, for example).
[Update: for Python3 (the currently maintained versions of Python) the range() function always returns the dynamic, "lazy evaluation" iterator;  the older versions of Python (2.x) which returned a statically allocated list of integers are now officially obsolete (after years of having been deprecated)].

A: The range function wil give you a list of numbers, while the for loop will iterate through the list and execute the given code for each of its items.
for i in range(5):
      print i

This simply executes print i five times, for i ranging from 0 to 4.
for i in range(5):
      a=i+1

This will execute a=i+1 five times. Since you are overwriting the value of a on each iteration, at the end you will only get the value for the last iteration, that is 4+1.
Useful links:
http://www.network-theory.co.uk/docs/pytut/rangeFunction.html
http://www.ibiblio.org/swaroopch/byteofpython/read/for-loop.html

A: It is looping, probably the problem is in the part of the print...
If you can't find the logic where the system prints, just add the folling where you want the content out:
for i in range(len(vs)):
    print vs[i]
    print fs[i]
    print rs[i]


text:
Q: How do we punctuate an abbreviation followed by a colon? When making bullet points of details about something, do we punctuate the abbreviation?
Is it this way?

The details of the Vehicle are given below:

*

*Vehicle Chassis No.: [dot and colon with no space]

*Vehicle Chassis No. [dot only]

*Vehicle Chassis No. : [dot and colon with space]

Which one them is right?

A: The abbreviated form No. comes from the word 'numero'. Note the 'dot' after the letter 'o'. It's 'No.' (with dot) and not 'No' (without dot).
Now, the pattern you follow seems to be listing the credential of a vehicle. Generally, we put colons in such context. For instance...

Name: Mr. Narendra Modi  Age: 65 years  Address: xyz... and so on...

As you see that such listing happens with the colon and the dot is indeed necessary to abbreviate numero (to avoid reading it 'No - negation'), it'd be dot and colon with no space in between.
About space:
You do not put a space before a colon, but you do need a space after one.  Source: http://www.learnenglish.de/punctuation/punctuationtext.html#colon
So, you may write like:

Vehicle Owner: Mr. Tim Cook  Vehicle Chassis No.: XYZ1234ABC  Vehicle Type: SUV  and so on...

A: If I am sending email updates for a play named "Into the Woods Junior", I would send it with the subject line, "Into the Woods Jr.: Box Office & Scheduling Update"
I think the colon should come after an abbreviation but to be honest I was never really sure.


text:
Q: insert into Hashtable> I am not sure why I am getting the error under my put:
The method put(Character, List<Boolean>) in the type
Hashtable<Character,List<Boolean>> is not applicable for the arguments (char, boolean)

I think I have all the matching types
Here is my code
    Hashtable<Character, List<Boolean>> charCheck =
         new Hashtable<Character, List<Boolean>>();
    List<Boolean> used = new ArrayList<Boolean>();
    //Set<String> nonDuplicate = new Set<String>();
    // make a hashtable of characters used
    char[] charArray = str.toCharArray();
    for (char c : charArray) {
        charCheck.put(c, used.add(false));

A: The List#add method in Java returns a boolean indication of whether the value ws successfully added to the List or not.
You should separate adding a new List to your Map from adding a new element to it:
Hashtable<Character, List<Boolean>> charCheck = new Hashtable<Character, List<Boolean>>();
char[] charArray = str.toCharArray();

for (char c : charArray) {
    List<Boolean> used = charCheck.get(c);

    // If the char isn't in the map yet, add a new list
    if (used == null) {
        used = new ArrayList<Boolean>();
        charCheck.put (c, used);
    }

    used.add(false);
}

A: You need to treat each ArrayList separately, i.e. have one ArrayList per Character key.
List<Boolean> used;

char[] charArray = str.toCharArray();

for (char c : charArray) {

    used = charCheck.get(c); // Get the list of values for this character

    if (used == null) { // No values stored so far for this character
        used = new ArrayList<Boolean>(); // Create a new (empty) list of values
        charCheck.put(c, used); // Add the empty list of values to the map
    }

    used.add(false); // Add the value for this character to the value list
}

Also, I would suggest using a HashMap instead of a Hashtable:
HashMap<Character, List<Boolean>> charCheck = new HashMap<Character, List<Boolean>>();


text:
Q: How to run the most basic of Vaadin applications I've been attempting to create an out-of-the-box Vaadin application and have thus far been unsuccessful.
Using IntelliJ IDEA 14, added the correct Vaadin maven archetype and have created the application.
I end up with three project folders (production, ui and widgetset) where, according to the tutorials, I would have expected only a few files under src. Anyway.
So now when I try to deploy under Tomcat I get the infamous

Requested resource
  [/VAADIN/widgetsets/com.vaadin.DefaultWidgetSet/com.vaadin.DefaultWidgetSet.nocache.js]
  not found from filesystem or through class loader.

error. Enough articles on how to change the web.xml file to solve that. However, I have no web.xml file to alter.
I also don't need to add any client js so I don't really need any of that stuff, I just need server-side Vaadin.
Can I get rid of the whole WidgetSet dependency, thereby also getting rid of this error and just run the most basic of server-side Vaadin applications without all the fancy things?
I've tried commenting out all references to client compiler, widgetset and everything else my puny knowledge of Java allows me to and have lost days in the process.
Some genius insight would be awesome. Thanks in advance.

A: So I get you have a rough idea on how Vaadin works. Here's a bit of background info just to clear some things up and maybe give the relevant info to others interested as well.
GWT idea is that you do an app in Java and run it through the GWT compiler. Out comes javascript that you can run in the browser directly. The compiler itself is most of what GWT is. The options for readymade functionality in terms of widgets or components is quite slim. It is more of a 'do it yourself' mentality where they let the GWT users or other framework makers fill the widget/graphical gap.
Vaadin uses GWT but in a bit different way than most frameworks built on GWT. Just as other GWT extending frameworks, Vaadin includes a set of widgets that gives you the the possibility to build most parts of your apps without the need to modify the widgets. The thing Vaadin does differently is that it precompiles the widgets and on top of it and gives you a communication manager that allows you to steer the widgets from a server. This key difference is here that when in almost all other GWT frameworks you have to run the GWT compiler after every single UI change you do, in Vaadin you don't have to because the server steers the layouting and widgets with JSON messages. In Vaadin you compile when you change the behavior of a widget, and not when you use it.
Because Vaadin doesn't require you to 'GWT compile' the application all the time, it can provide you with a precompiled widgetset for your basic needs. This is called DefaultWidgetSet. It is enough as far as you don't do client side changes or use any add-ons found in the root directory.
And then to the actual problem. The archetype that you are using came out a week ago. I don't know which tutorial you are referring to but my bet is that it is still referring to the old archetype and it should be updated.  Normally you should be able to get it to run the app with these steps:

*

*create the project with archetype

*run mvn install in the root folder

*run mvn jetty:run in the ui folder (or alternatively deploy ui into another servlet container, like tomcat, through your IDE)

Because you get the error message that you posted, it indicates that the application is in fact trying to use the precompiled version, which is fine, but for some reason it can't find it. It should come from the widgetset module, from the vaadin-client-compiled dependency in it:
<dependency>
  <groupId>com.vaadin</groupId>
  <artifactId>vaadin-client-compiled</artifactId>
  <version>${vaadin.version}</version>
</dependency>

${vaadin.version} can be defined globally (as you should have there) or then you can type in the version number in there directly, like 7.3.7.
For some reason it doesn't seem to find this. If it is not there, add it to the widgetset pom.xml, and run mvn install in widgetset (or parent, both are fine). Then go to ui and start up the server again with mvn jetty:run.
I'm not sure but my guess here is that the archetype has a custom widgetset and doesn't depend on the precompiled widgetset. After that you've wanted the default widgetset instead of a custom one and removed the annotation for the widgetset in the UI class, but you have not added the dependency for the default widgeset.
As your use-case is very simple, the archetype in question might be a bit overkill. You have no reason to have the project split up in ui and widgetset if you don't develop client side and a module for building a production-ready deployment package (production module) is certainly out of scope at this point. So in that sense widgetset, production and parent -modules are completely irrelevant for you.
If you want a simpler project structure you could clone my git repo found here: https://github.com/Peppe-/hello-world. It has the old Vaadin default single-module archetype as a base but I ripped out everything that is not needed to develop purely server side with no fuss. pom.xml went down from about 200 rows of declarations to 80, but it also means that you have to add stuff back if you want additional features into use. Like the compiler, or if you want to adds css (modify theme). You can get it and run it with these command:
git clone https://github.com/Peppe-/hello-world.git
cd hello-world
mvn jetty:run

Or after the first step you can import it into IDEA and run it from there. Additionally rename the package (by renaming the folders within src) if you want to use your own package name.
Sorry I got a bit carried away and rambled on. Please ask any and all questions if I missed something.