text:
Q: Implementing Zero Or One to Zero Or One relationship in EF Code first by Fluent API I have two POCO classes:
Order Class:
public class Order
{
    public int Id { get; set; }
    public int? QuotationId { get; set; }
    public virtual Quotation Quotation { get; set; }
    ....
}

Quotation Class:
public class Quotation
{
    public int Id { get; set; }
    public virtual Order Order { get; set; }
    ....
}

*

*Each Order may be made from  one or zero quotation, and

*each quotation may cause an order.

So I have an "one or zero" to "one or zero" relation, how can I implement this, in EF Code first by Fluent API?

A: See http://msdn.microsoft.com/en-us/data/jj591620 EF Relationships
An excellent Book
http://my.safaribooksonline.com/book/-/9781449317867
Here is a post from developer from Dec 2010.  But still relevant
http://social.msdn.microsoft.com/Forums/uk/adonetefx/thread/aed3b3f5-c150-4131-a686-1bf547a68804
The above article is a nice summary or the possible combinations here.
A solution where dependant Table has key from Primary table is possible.
If you Want Independent Keys where both are Principals in a PK/FK scenario, i dont think you can do it in Code first with Fluent API. If they share a Key, You are OK.
1:1 optional assumes the dependent uses the key from Primary.
But since you need to save one of the tables before the other. You can check one of the Foreign Keys with code. OR add teh second Foreign to Database after Code first has created it.
You will get close. But EF will complain about conflicting Foreign keys if you want both to be Foreign keys.  Essentially the A depends on B depends A EF doesnt like, even if the columns are nullable and technically possible on the DB.
Here use this test program to try it. Just comment in an out the Fluent API stuff to try some options.
    I could NOT get EF5.0 to work with INDEPENDENT PK/FK  0:1  to 0:1
    But of course there are reasonable compromises as discussed.
using System.Data.Entity;
using System.Linq;
namespace EF_DEMO
{
class Program
{
    static void Main(string[] args) {
        var ctx = new DemoContext();
        var ord =  ctx.Orders.FirstOrDefault();
        //. DB should be there now...
    }
}
public class Order
{
public int Id {get;set;}
public string Code {get;set;}
public int? QuotationId { get; set; }   //optional  since it is nullable
public virtual Quotation Quotation { get; set; }
  //....
}
public class Quotation
{
 public int Id {get;set;}
 public string Code{get;set;}
// public int? OrderId { get; set; }   //optional  since it is nullable
 public virtual Order Order { get; set; }
 //...
}
public class DemoContext : DbContext
{
    static DemoContext()
    {
    Database.SetInitializer(new DropCreateDatabaseIfModelChanges<DemoContext>());
    }
    public DemoContext()
        : base("Name=Demo") { }
    public DbSet<Order> Orders { get; set; }
    public DbSet<Quotation> Quotations { get; set; }

    protected override void OnModelCreating(DbModelBuilder modelBuilder)
    {
       modelBuilder.Entity<Order>().HasKey(t => t.Id)
                    .HasOptional(t => t.Quotation)
                    .WithOptionalPrincipal(d => d.Order)
                    .Map(t => t.MapKey("OrderId"));  // declaring here  via MAP means NOT declared in POCO
        modelBuilder.Entity<Quotation>().HasKey(t => t.Id)
                    .HasOptional(q => q.Order)
            // .WithOptionalPrincipal(p => p.Quotation)  //as both Principals
            //        .WithOptionalDependent(p => p.Quotation) // as the dependent
            //         .Map(t => t.MapKey("QuotationId"));    done in POCO.
            ;
    }
}
}

A: Adapted from this answer, try this.
First, fix your classes:
public class Order
{
  public int Id {get; set;}
  public virtual Quotation Quotation { get; set; }
  // other properties
}

public class Quotation
{
  public int Id {get; set;}
  public virtual Order Order { get; set; }
  // other properties
}

Then use the fluent API like that:
modelBuilder.Entity<Quotation>()
.HasOptional(quote => quote.Order)
.WithRequired(order=> order.Quotation);

Basically, for 1:1 or [0/1]:[0/1] relationships, EF needs the primary keys to be shared.

A: By changing pocos to:
public class Order
{
    public int OrderId { get; set; }
    public virtual Quotation Quotation { get; set; }
}
public class Quotation
{
    public int QuotationId { get; set; }
    public virtual Order Order { get; set; }
}

and using these mapping files:
public class OrderMap : EntityTypeConfiguration<Order>
{
    public OrderMap()
    {
        this.HasOptional(x => x.Quotation)
            .WithOptionalPrincipal()
            .Map(x => x.MapKey("OrderId"));
    }
}

public class QuotationMap : EntityTypeConfiguration<Quotation>
{
    public QuotationMap()
    {
        this.HasOptional(x => x.Order)
            .WithOptionalPrincipal()
            .Map(x => x.MapKey("QuotationId"));
    }
}

we will have this DB(that means 0..1-0..1):

with special thanks to (Vahid Nasiri)

A: @Masoud's procedure was:
modelBuilder.Entity<Order>()
            .HasOptional(o => o.Quotation)
            .WithOptionalPrincipal()
            .Map(o => o.MapKey("OrderId"));

modelBuilder.Entity<Quotation>()
            .HasOptional(o => o.Order)
            .WithOptionalPrincipal()
            .Map(o => o.MapKey("QuotationId"));

It gives:

By changing the code to:
modelBuilder.Entity<Order>()
            .HasOptional(o => o.Quotation)
            .WithOptionalPrincipal(o=> o.Order);

It gives:

A:
public class OfficeAssignment
{
    [Key]
    [ForeignKey("Instructor")]
    public int InstructorID { get; set; }
    [StringLength(50)]
    [Display(Name = "Office Location")]
    public string Location { get; set; }

    public virtual Instructor Instructor { get; set; }
}

The Key Attribute
There's a one-to-zero-or-one relationship  between the Instructor and the OfficeAssignment entities. An office assignment only exists in relation to the instructor it's assigned to, and therefore its primary key is also its foreign key to the Instructor entity. But the Entity Framework can't automatically recognize InstructorID as the primary key of this entity because its name doesn't follow the ID or classnameID naming convention. Therefore, the Key attribute is used to identify it as the key:

https://www.asp.net/mvc/overview/getting-started/getting-started-with-ef-using-mvc/creating-a-more-complex-data-model-for-an-asp-net-mvc-application

A: using DataAnnotations:
public class Order
{
       [Key]
       public int Id {get; set;}

       public virtual Quotation Quotation { get; set; }
}

public class Quotation
{
     [Key, ForeignKey(nameof(Order))]
     public int Id {get; set;}

     public virtual Order Order { get; set; }
}

A: (Note that this is using EF 6.4.4.)
It's fairly straightforward to specify, as long as you don't want foreign key properties:
modelBuilder
.Entity<Order>()
.HasOptional(o => o.Quotation)
.WithOptionalPrincipal(q => q.Order);

modelBuilder
.Entity<Quotation>()
.HasOptional(q => q.Order)
.WithOptionalDependent(o => o.Quotation);

Notice here the usage of both WithOptionalPrincipal and WithOptionalDependent. This should give you a single foreign key column on the dependent side (Quotation in the example), but with no foreign key properties. If you want the foreign key on the other side, switch "Dependent" and "Principal" around.
(Note that it is not necessary to have both definitions above; WithOptionalDependent will imply the other side is the principal and vice-versa, so you can use only one of them if you wanted, but I find specifying the relationships from both sides helps prevent errors by double declaring things; any conflict will result in a model error to let you know you missed something.)
While there is an index on the foreign key column, the index does not have a unique constraint. While it is possible to add your own unique constraint (which would require a Key IS NOT NULL filter), it doesn't seem to work and you will get exceptions when updating relationships in some cases. I think this is related to the "swapping problem" where EF will perform its updates in separate queries, so enforcing uniqueness would prevent EF from "moving" a key in two steps.
EF seems to handle the association itself internally, without a unique DB constraint:

*

*On either side, assigning an already used reference results in the other usage of the reference being removed automatically. (So if it is already the case that A1 <=> B1 when you opened the context, and then you write A1 => B2, then A1 <=> B1 is removed and A1 <=> B2 is added, regardless of which side you're on.)

*If you try to create a duplicate key by assigning the same reference more than once, EF will throw an exception saying "multiplicity constraint violation". (So in the same context, you wrote both A1 => B1 and A2 => B1, or some similar conflicting mapping.)

*If you update the DB manually to create a duplicate key situation, when EF encounters this it will throw an exception saying "A relationship multiplicity constraint violation occurred...this is a non-recoverable error."

It does not seem possible in EF6 to map a property to the foreign key column (at least with Fluent API). Attempting to do so results in a non-unique column name exception since it tries to use the same name for both the property and the association separately.
Note also that it is technically incorrect to have two foreign keys (ie: one on both sides). Such an arrangement would actually be two 0..1 to 0..1 associations since there would be nothing to say that keys on both ends should match. This could maybe work if you enforce the relationship some other way, through the UI and/or possibly a database constraint of some kind.
I also notice that there may be a misunderstanding/miscommunication of exactly what a 0..1 to 0..1 association is. What this means, from my understanding and the way EF seems to consider it as well, is that it is a 1 to 1 association that is optional on both sides. So, you can have objects on either side with no relationship. (Whereas a 1 to 0..1 assocation, objects on one side could exist without a relationship, but objects on the other side would always need an object to relate to.)
But 0..1 to 0..1 does not mean that you can have the association travel in one direction and not the other. If A1 => B1, then B1 => A1 (A1 <=> B1). You cannot assign B1 to A1 without also making A1 relate to B1. This is why it is possible for this association to use only a single foreign key. I think some people may be trying to have an association in which this is not true (A1 relates to B1 but B1 does not relate to A1). But that is really not one association but two 0..1 to 0..1 associations.


text:
Q: Strange behaviour of WebActivities under Firefox OS 1.2 I am writting a firefox os application and I found a strange problem. I have two web activities (open a link on a projects tab and sending an e-mail on the users tab ) what are work correctly under the Firefox OS 1.1 simulator but not work under the appmanager+firefox OS 1.2 simulator. In additional it did not work under my Keon phone with FFOS 1.2 prerelease.
Do you have any idea? Thanks.

A: Might not be the most optimal way but try something like:
function sendEmail(toEmail, subject, body) {
  var createEmail = new MozActivity({
    name : "new",
    data : {
      type : "mail",
      url : "mailto:" + toEmail + "?&subject=" + subject + "&body=" + body + "",
    }
  });
}
function processUsers() {
    if (xhr.readyState == 4 && xhr.status == 200) {
      var obj = jQuery.parseJSON(xhr.responseText);
      for (var i = 0; i < obj['users'].length; i++) {
        if (obj['users'][i].email != null) {
            var myLi = document.createElement('li');
            myLi.innerHTML = "
" + obj['users'][i].name+ "
" + "
" + obj['users'][i].email; "
";
            var em =obj['users'][i].email;
            var sb = '';
            var bd = '';
            myLi.onclick = (function(em, sb, bd) {
                return function(){ sendEmail(em, sb, bd) }
            })(em, sb, bd);
          $('#resultsUsers').append(myLi);
        } else {
          $('#resultsUsers').append("

" + obj['users'][i].name + "

");
        }
      }
      usersAreLoaded = true;
    } else {
      console.log("did not get data " + xhr.status);
    }
}

A: Inline JavaScript code inside onclick etc will not run in privileged apps, see the docs about app CSP (content security policy):

Inline scripts are banned. You may not use script attributes like
  onclick="" or onload="".

redpajama_set_name: RedPajamaStackExchange


text:
Q: PHP Segmentation fault during preg_replace I'm using Magento and got PHP Segmentation fault during rollback database from admin. I make and investigation and see that the reason is such line:
preg_replace("/'(\\'|\\\\{2}|[^'])*'/", '', $sql);

$sql string is big enough, I'm attaching it.
https://drive.google.com/file/d/0B9UbKYbywcABOTRSVG5KRl9La0k/edit?usp=sharing
You may use such script to reproduce the problem:
<?php
    $test = file_get_contents('test.txt');
    $sql = preg_replace("/'(\\'|\\\\{2}|[^'])*'/", '', $test);

May be somebody knows about this problem and can help me to solve it?
P.S. Class that directly causes the problem is abstract class Zend_Db_Statement 204:208

A: I've been struggling with this myself, and stumbled upon this thread which recommends changing a php.ini value:
http://zend-framework-community.634137.n4.nabble.com/Fixing-Zend-Db-Statement-stripQuoted-seg-faults-on-large-SQL-strings-in-ZF-1-x-td4648143.html
[PCRE]
pcre.recursion_limit = 1000

Works like a charm for me. Hope this helps!
Edit: also available in convenient .htaccess format:
php_value pcre.recursion_limit 1000

A: Base on this article: http://man.he.net/man3/pcrestack
You can try to modify the regexp to use less stack.
I would try something similar for example:
preg_replace("/'([^']+|\\'|\\\\{2})*'/", '', $sql);

Or here: https://bugs.php.net/bug.php?id=61579
They mention these two alternatives also:
"/'(\\\\'|\\\\{2}|[^']+)*'/"

"/'[^'\\\\]*(?:\\\\.[^'\\\\]*)*'/"


text:
Q: how can make my object stop? I can make my object stop. Once I press w,a,s or d it moves but doesnt stop. When I press one of the directions it moves but it doesnt stop. I need it to stop when I release the key. All types of help will be appreciated. Heres my code:
while (running == 1):
    screen.fill(white)
    for event in pygame.event.get():
        if (event.type == pygame.QUIT):
            running = 0
        elif (event.type == pygame.KEYDOWN):
            if (event.key == pygame.K_d):
                dir = "R"
            elif (event.key == pygame.K_a):
                dir = "L"
            elif (event.key == pygame.K_s):
                dir = "D"
            elif (event.key == pygame.K_w):
                dir = "U"
            elif (event.key == pygame.K_ESCAPE):
                sys.exit(0)
            elif (event.key == pygame.K_SPACE):
                shot=True
                xbul=xgun
                ybul=ygun
            #if key[K_SPACE]:
                #shot = True

    #OBJECT'S MOVEMENTS
    if (dir == "R" and xgun<595):
        xgun = xgun + 3
        pygame.event.wait
    elif (dir == "L" and xgun>0):
        xgun = xgun - 3
        pygame.event.wait
    elif (dir == "D" and ygun<460):
        ygun = ygun + 3
        pygame.event.wait
    elif (dir == "U" and ygun>0):
        ygun = ygun - 3

    screen.blit(gun, (xgun,ygun))
    #PROJECTILE MOTION
    #key = pygame.key.get_pressed()

    if shot == True:
        xbul = xbul + 3
        screen.blit(bullet, (xbul, ybul))

    if xbul>600:
        shot=False

    pygame.display.flip()
    time.sleep(0.01)

A: You should catch pygame.KEYUP and stop the current movement.

A: Use pygame.key.get_pressed()
That is
key = pygame.key.get_pressed()
if key[pygame.K_d]:
    dir = "R"
elif key[pygame.K_a]:
    dir = "L"
elif key[pygame.K_s]:
    dir = "D"
elif key[pygame.K_w]:
    dir = "U"
elif key[pygame.K_ESCAPE]:
    sys.exit(0)
elif key[pygame.K_SPACE]:
    shot = True
    xbul = xgun
    ybul = ygun
else:         # If none of the keys is pressed, Stop.
    dir = 'S'


text:
Q: Dynamic load items in a list using thymeleaf + angular + bootstrap Hi guys I continue with my code and I have a problem that someone can maybe help me to fix it.
I'm using UI Bootstrap with angular and thymeleaf and I have problems to comunicate each. I want this:

So this table is loading dynamic from Thymeleaf but the name provider need to change.
Here is the code:
<accordion-group heading="{{providerGroup}}" th:attr="ng-repeat=\''+ providerGroup in ${@provider.getProviders().keySet()}+'\')'">
                {{providerName}}
            </accordion-group>

everything is working fine except that I dont know why thymeleaf dont read it.
Any help?

A: <accordion close-others="oneAtATime">

            <accordion-group th:attr="heading=${provider}" ng-model="providerSelected">
                {{providerSelected}}

                <button class="btn btn-default btn-sm" ng-click="addItem()">Add Item</button>

{{item}}

            </accordion-group>

        </accordion>

Enjoy it!


text:
Q: Python telnet connection closes I'm trying to send some commands via telnet to a server. This has been done by hand many times, but I was asked to automate it using python.
My code starts like this:
import telnetlib

HOST = "xxx.xxx.xxx.xxx"
PORT = xx

print("connecting...")
tn = telnetlib.Telnet(HOST, PORT)
tn.read_until(b"250")
print("connection established!\nsending ehlo...")
tn.write(b"EHLO test.com")
tn.read_until(b"250")
print("response received")
...

If I enter the commands by hand, it works. But the script aborts after a few minutes with the following output:
connecting...
connection established!
sending ehlo...
Traceback (most recent call last):
  File "telnet_test.py", line 11, in <module>
    tn.read_until(b"250")
  File "/usr/lib/python3.6/telnetlib.py", line 327, in read_until
    return self.read_very_lazy()
  File "/usr/lib/python3.6/telnetlib.py", line 403, in read_very_lazy
    raise EOFError('telnet connection closed')
EOFError: telnet connection closed

According to the output my telnet connection got closed, but I can't see why!?
Maybe important: After launch the output says connecting... for a few minutes, and then the rest of the output including the exception get's printed.
Is the read_until() function blocking longer than necessary, so my connection timouts? And how do I solve this?

A: credits to user molbdnilo
I needed to add a newline character on every command.
So tn.write(b"EHLO test.com") becomes tn.write(b"EHLO test.com\n")


text:
Q: Why is $ F_{|x|}(x) \equiv F_{x}(x)-F_{x}(-x) $? I don't fully understand the jump from
$\quad F_{|X|}(x)= Pr[-x \leq X \leq x]$
to
$\quad F_{|x|}(x) \equiv F_{x}(x)-F_{x}(-x) \quad$
maybe someone can give an intuitive explanation.

A: Since $F(x)=P(X\leq x )$ we have that
$$P(-x\leq X\leq x)=F(x)-F(-x)$$


text:
Q: Program not working properly when inputting a 2-digit number const ps = require("prompt-sync");
const prompt = ps();
console.log("\nFinding The Maximum Number In The Array");
console.log("---------------------------------------");
let length = prompt("Enter the length of the array: ");
let temp = 0;
let maxnum;

    let array = [];
    for(let i=0; i<length;i++){
        let num = prompt(i+":");
        array[i] = num;
}

console.log("\nlength: " + length);
for(let o=0; o < length ; o++ ){

        if(array[o] > temp){
            temp = array[o];
        }
        if(o == (length-1)){
           maxnum = temp;
           console.log("\ncurrent max " + maxnum);
        }
    }

console.log("The maximum number is: "+ maxnum);

Works properly when comparing 1-digit numbers; 1,2,3,7 for example.
Its output is 7 for the max number. But when adding 10 to the list, the program
will still output 7.

A: prompt gets you string values, and when you compare the string value 10 to 7, then 7 is considered the greater one, because string comparison happens character by character, from left to right.
Use array[i] = parseInt(num); to convert those string values into actual integer values first.
https://developer.mozilla.org/en-US/docs/Web/JavaScript/Reference/Global_Objects/parseInt

A: Because prompt gets you a string, it is comparing the values alphabetically. Just as the character "C" could be considered greater than the character "A", the text character "7" is also greater than the text character "1". So just as the word "APPLE" would be sorted alphabetically before "CAT", even though "APPLE" is longer, so is the text string "10" sorted alphabetically before the text string "7". In fact, the text "1000000" would also come before the text "7" when sorted alphabetically.
To solve, you must convert the text string to a number first, which can be achieved with parseInt(). A convenient place to do this would be immediately after you retrieve the string input from the user, as in array[i] = parseInt(num);.

A: You have to store the values as an integer in your array while accepting input at the prompt. Or else the values will be considered as type string by default.
You can use parseInt(yourInput);.


text:
Q: To thread or not to thread I'm building a rather simple application that performs a few seperate HTTPWebRequests, each on their own timer. It's not likely I will need to have more than 3 seperate requests running at a time.
If a Timer Tick fires while another HTTPWebRequest is in progress, what happens to the event fired by the Timer Tick? Should I add Threading?

A: The answer is almost always - no, don't use threads just because you can.
Consider making asynchronous calls first as it is easier to write correct code for. It is likely more efficient use of resources (as threads are not unlimited resource) if you need additional arguments.
Links:

*

*How to use HttpWebRequest (.NET) asynchronously?

*Use async methods of WebClient like WebClient.DownloadStringAsync

A: When Timer.Tick fires it's handler will be scheduled for execution in Thread Pool and most likely, executed in another thread.


text:
Q: Compiler Unaware of Provided Methods of Trait I'm using the prost crate in a very "hello world" way, with a basic ProtoBuf file:
foo.proto
syntax = "proto3";
package foo;

message Foo {
    string mystring = 1;
}

I can verify the types that prost produces at compile time by inspecting ./target/PROJECT/build/PROJECT-{some hash}/out/foo.rs:
foo.rs
#[derive(Clone, PartialEq, ::prost::Message)]
pub struct Foo {
    #[prost(string, tag="1")]
    pub mystring: ::prost::alloc::string::String,
}

See that the prost::Message trait gets derived? Its docs claim I have tons of functions at my disposal for this trait, but only the two required ones, encoded_len() and clear(), can be called without error. Any of the provided ones (those with default implementations) result in a cannot find function in this scope error.
main.rs
use prost::Message;

pub mod foo {
    include!(concat!(env!("OUT_DIR"), "/foo.rs"));
}

fn main() {
    let f = foo::Foo { mystring: "bar".to_string() };
    let v = encode_to_vec(&f);
}

cargo run

error[E0425]: cannot find function `encode_to_vec` in this scope
   |
   |     let v = encode_to_vec(&f);
   |             ^^^^^^^^^^^^^ not found in this scope

And, worryingly, this warning implies it's not even looking at the trait it needs to:

warning: unused import: prost::Message

(edit) For reference:
Cargo.toml
[package]
name = "testing"
version = "0.1.0"
edition = "2018"

[dependencies]
prost = { version = "0.7.0", features = ["std"] }

[build-dependencies]
prost-build = "0.7.0"

A: encode_to_vec is not a free function. You need to call it as one of

*

*f.encode_to_vec()

*foo::Foo::encode_to_vec(&f)

*Message::encode_to_vec(&f)

*<foo::Foo as Message>::encode_to_vec(&f)
The first method is the most normal, but the other ones may produce useful error messages when you get confused about what's going on.

[Edit:] Well, encode_to_vec was added in prost 0.8.0, so with 0.7.0, it won't be usable.


text:
Q: confusion about Galera cluster work with spread toolkit I get interested in Galera cluster.
The Galera team claims they have flexible adaptor based design for variety of GCS.
http://galeracluster.com/products/technology/ Their website said "many gcs implementations can be adapted, we have experimented with spread and our in-house implementations: vsbes and gemini"
But I can barely find any resource online about the implementation of combining spread(a distributed toolkit) with Galera cluster.
When I setup a small galera cluster, it can work well. When I updated one Mysql, the other mysqls also got the update.
I am confused why Galera need to work with spread and how to do that.
Anyone has experience with how to implement spread with Galera?
Thanks a lot.

A: The Galera defined their gcs as gcomm by default, which I think it was developed by Galera. We can define another toolkit as their gcs. The gcs is defined in the part called backend scheme. And then you can implement all functionality via other gcs, let's say Spread.


text:
Q: In python socketio RuntimeWarning: coroutine 'initial' was never awaited despite writing an await statement python3 client.py
/home/aijax/.local/lib/python3.6/site-packages/socketio/client.py:592: RuntimeWarning: coroutine 'initial' was never awaited
  self._handle_event(pkt.namespace, pkt.id, pkt.data)
connection established
despite of having the await I'm getting the error
PS: I have little to no knowledge of Async-io of python I kinda have finish this task overnight for a school proj
my client.py
import socketio
import time

sio = socketio.Client()
val={"num":35}

@sio.event
def connect():
    print('connection established')

@sio.event
def disconnect():
    print('disconnected from server')

@sio.event
async def initial(sid):
    global val,sio
    print("hey there!! ")
    await sio.emit('clientUpdate',val)

@sio.event
async def serverAggregate(avg):
    global val
    val["num"] = (avg["num"] + val["num"])/2
    # print(val)
    print("kaada ",avg)
    time.sleep(4)
    await sio.emit('clientUpdate',val)
    # await

sio.connect('http://0.0.0.0:8080')
# sio.wait()
# sio.my_message()

sio.wait()

My task is to create a server and many clients which send a number to server and server aggregates that and sends it back to the client and perform a local update and send back the number
my server.py
from aiohttp import web
import socketio
import time
import threading

# creates a new Async Socket IO Server
sio = socketio.AsyncServer()
users_count=0 #num of clients
temp_count=users_count
avg={"num":0}
temp_sum=0
initFlag=True
# Creates a new Aiohttp Web Application
# app = web.Application()
async def handle(request):
    print(request)
    name = request.match_info['name']
    text = "Hello, " + name
    return web.Response(text=text)

app = web.Application()
sio.attach(app)

async def resetter():
    global avg,temp_sum,users_count,temp_count,sio
    avg = temp_sum/users_count
    temp_count = users_count
    temp_sum = 0
    print("broadcast requests to clients")
    time.sleep(2)
    await sio.emit('serverAggregate',avg,broadcast = True, include_self = False)

@sio.on('clientUpdate')
async def serverAggregate(sid, data):
    global temp_count,users_count,initFlag,sio,resetter

    if initFlag:
        temp_count=users_count
        initFlag=False

    temp_count=temp_count -1
    if(temp_count==0):
        await resetter()
    else:
        print("message ", data)
        global temp_sum
        temp_sum = temp_sum + data["num"]
        print("message ", data)

@sio.event
async def connect(sid, environ):
    global users_count,sio
    print("connect ", sid)
    users_count=users_count+1
    # time.sleep(3)
    # print("say something")
    time.sleep(2)
    await sio.emit('initial')
    # await sio.emit('intialize', broadcast = True, include_self = False)

@sio.event
def disconnect(sid):
    global users_count
    print('disconnect ', sid)
    users_count=users_count-1

app.add_routes([web.get('/', handle),
                web.get('/{name}', handle)])

# app.router.add_static('/static', 'static')
class BgProc(threading.Thread):

    def __init__(self, sio):

        # calling superclass init
        threading.Thread.__init__(self)
        # self.text = text
        self.sio = sio

    def run(self):
        time.sleep(5)
        print("sending broadcast to all clients ")
        self.sio.emit("initial",broadcast = True, include_self = False)

if __name__ == '__main__':
    web.run_app(app)

A: You are using the socketio.Client() class which is the standard Python client. If you want to write an asyncio application, you must use socketio.AsyncClient().


text:
Q: Meaning of the verb "to vendor" Several technical articles write about vendor using it as a verb:
https://www.python.org/dev/peps/pep-0518/#configparser quoth:

While one could standardize on what Python 3 accepts and simply vendor the backport of the configparser module

while https://github.com/sdispater/poetry#installation states

Poetry provides a custom installer that will install poetry isolated from the rest of your system by vendorizing its dependencies

Both merriam-webster and cambridge only list the noun vendor, and not the verb.
What do they mean?

A: In the context of software development, "vendoring" and derivatives is a made-up verb used in some languages and platforms to refer to techniques and tools to package software dependencies; specifically to import (or make easily importable) trusted snapshots of objects into a project without needing to depend on third-party resources to retrieve them again.
For example, you can think of "vendor" as representing a named local location (eg. a directory called "vendor") for storing assets from third-parties ("vendors" in the normal sense, though they may be internal or external to the organisation), and vendoring as the act of placing items into this vendor repository.
https://go.googlesource.com/proposal/+/master/design/25719-go15vendor.md
https://en.wiktionary.org/wiki/vendor


text:
Q: Solve these two multivariable equations simultaneously. How can I solve the following system of equations? $$\begin{cases}3x^2 + y + 2xy^2 - 3&=0\\ x(1+2yx)&=0 \end{cases}$$
Not sure how to go about this.

A: Hint:

$x(1+2yx)=0$ means that $x=0$ or $1+2yx=0$. Can you proceed further?

A: $$(1) 3x^2 + y + 2xy^2 - 3=0\\(2)x(1+2xy)=0\\multiply (1)-by-x\\3x^3 + yx + 2x^2y^2 - 3x=0\\3x^3-3x+y(x(1+2y))=0\overset{x(1+2xy)=0}{\rightarrow} \\3x(x^2-1)+y(0)=0\\3x(x^2-1)=0\\x=0,1,-1\\now\\x=0\overset{(1)}{\rightarrow}y-3=0\\x=1\overset{}{\rightarrow}y=\frac{-1}{2}\\x=-1\overset{}{\rightarrow}y=\frac{+1}{2}$$


text:
Q: How can I delete an item from a list using CInt and Split in VB.net I want to delete an item from a list and from a database. This is the code I used:
Dim nr As Integer
        Dim s As String
        s = lstPatiënten.ToString
        nr = CInt(s.Split("-"c)(0))
        For Each d In patienten
            If d.nr = nr Then
                If patientenDB.PatientVerwijderen(d) > 0 Then
                    initGetPatienten()
                End If
            End If
        Next

But it don't work.. The error is:

Conversion from string "System.Windows.Forms.ListBox, It" to type
  'Integer' is not valid.

But when I type Nr = 83 (83 is my UserID for a patiënt) it worked.
Can somebody please help me?

A: You need to change s = lstPatiënten.ToString to s = lstPatiënten.SelectedItem.ToString. Give that a whirl and let me know if it works.
Listbox.SelectedItem


text:
Q: Most Ideal Way for Handling JSON Data Fetch I'm building an app for iOS devices and would like the app to be able to fetch potentially large amounts of data from a MySQL database using a PHP file that returns a JSON object.
For testing purposes I had model data inside my controller. To begin to use a MVC architecture I want to come up with a way for my model to fetch this data from the database and then allow my controller to display it after being fetched.
For example, say I have a collection of groceries which I can fetch within my Groceries object using my initWithJSON method. And I wanted to fetch this using AFNetworking.
[
  {
    "item": "eggs",
    "color": "white",
    "shape": "oval",
  },
  {
    "item": "bread",
    "color": "brown",
    "shape": "rectangle"
  },
  {
    "item": "cheerios",
    "color": "green/orange",
    "shape": "circle"
  }
]

Would I fetch the JSON inside my Groceries object and then create an array and push each grocery item to the array? And then in my controller would I create my Groceries object and call initWithJSON and then have my Groceries.groceryList array list which was filled with the JSON data. Then populate the UITable in my view with my controller?
What's the industry standard way of approaching this method?

A: AfNetworking has a AFJSONSerializer so you can have a parser class that receive data from afnetworking, iterates over all data received and sends each grocery json to Grocery class, which can have an update method to check if this grocery exist, and updates it, and a insert method for new groceries.


text:
Q: My Sites default Pages library I am wondering if it is possible to turn on the default 'Pages' library for the My Sites Host Collection.  I am currently the My Site Host Collection administrator with Design and Full Control.  I know this because when browsing My Site's 'About Me' page, when I click on my name on the Ribbon I can see the 'Personalise this Page' and when I click on the cog I can see 'Edit Page', 'Add a Page', 'Design Manager' etc.
So I continue to 'Add a Page', give it a name, and click OK.  The page gets created and I get re-directed to it, ready to edit it.  However if I then navigate away from this page, there is no way for me to navigate back to it because no default 'Pages' library exists when I click on 'Site Contents'.
How can I enable this library so I may provision a new page that everyone will have access to from their My Site, which they will then be able to personalise.
I have tried turning on various features via 'Site Collection Features' and 'Manage Site Features' from 'Site Settings' with no luck.  The only additions are a greater selection of web parts I'm able to put on a page.
I have activated in both of the above options:
'SharePoint Server Standard Site Features'
'SharePoint Server Publishing'
'SharePoint Server Enterprise Site Features'


text:
Q: What is the effect of UIP_CONF_BUFFER_SIZE in contiki_conf.h file I am working on contiki for some time, and recently I faced a weird problem where I noticed that the cooja mote fails to receive any data packet larger than 57 bytes, for z1 mote the limit is something around 96 - 97 bytes (in cooja simulator) and in real hardware(mbxxx target) I've observed that this limit is 92 bytes. Anyone else faced similar situation, is this has something to do with platform specific configuration, and how do I change this? I've looked into contiki_conf.h file and found UIP_CONF_BUFFER_SIZE parameter. What is the effect if this parameter is changed?

A: I figured it out and it seems like the maximum IP payload handled by the uip stack. Thus it sums up the 40 byte IP header + 8 byte UDP header + UDP payload size. Same would hold for TCP connections. So for example if th UIP_CONF_BUFFER_SIZE is set to 140, and if we ping the mote with an effective IP packet size more than 140, the mote will fail to respond!


text:
Q: How to extract rows based on two conditions Hi I have a dataset d1.
import pandas as pd
d1 = {
'customers': pd.Series([1, 1, 1, 2, 2, 3, 3, 4, 4]),
'channel': pd.Series(['a', 'a', 'b', 'c', 'a', 'a', 'b', 'b', 'c']),
'freq': pd.Series([3, 3, 3, 2, 2, 2, 2, 2, 2])
}
d1=pd.DataFrame(d1)

I want to get list of customers who have used only two distinct channels and channels 'a' is mandatory.
For ex.. 1st customer has used two distinct channels 'a'& 'b'
2nd customer had used 'a' & 'c' 3rd customer used 'a' & 'b'. But customer 4 has not used channel 'a' and so on....
Thanks in advance

A: This is a little convuluted but basically we perform multiply filters on the df using groupby, filtering and 2 levels of boolean indexing:
In [140]:
    d1[d1.customers.isin(d1[d1.channel=='a'].customers)].groupby('customers').filter(lambda x: x['channel'].nunique() == 2)
Out[140]:
  channel  customers  freq
0       a          1     3
1       a          1     3
2       b          1     3
3       c          2     2
4       a          2     2
5       a          3     2
6       b          3     2

Breaking this down:
In [141]:
# filter out just those that have channel a
d1[d1.channel=='a']
Out[141]:
  channel  customers  freq
0       a          1     3
1       a          1     3
4       a          2     2
5       a          3     2
In [144]:
# we want these customer ids
d1[d1.channel=='a'].customers
Out[144]:
0    1
1    1
4    2
5    3
Name: customers, dtype: int64
In [146]:
# perform an additional filtering so we only want customers who have channel a
d1[d1.customers.isin(d1[d1.channel=='a'].customers)]
Out[146]:
  channel  customers  freq
0       a          1     3
1       a          1     3
2       b          1     3
3       c          2     2
4       a          2     2
5       a          3     2
6       b          3     2

The above is then groupby'd on customer and then we can apply a filter where the number of unique (nunique) customers is equal to 2

A: To take it a bit more slowly, e.g. if you plan to complicate the filtering logic further, this is an alternative (and admittedly less elegant) approach which tries not to be a one-liner:
def func(x):
    vals = x['channel'].value_counts()
    if 'a' in vals and len(vals) == 2:
        return True
    return False

mask = d1.groupby('customers').apply(func)
print mask

Output:
customers
1             True
2             True
3             True
4            False
dtype: bool

Now it depends on how you want the output to be:
# Get a list of customers, like
# [1, 2, 3]
target_customers = [k for k, v in mask.to_dict().iteritems() if v]

# Get a slice of the original DataFrame
print d1[d1['customers'].isin(target_customers)]


text:
Q: Hartman-Grobman theorem on a manifold Consider a dynamical system $\Sigma$ on a manifold $M$ of dimension $d$ embedded in $\mathbb{R}^n$, where $d<n$. Let $x\in M$ be an equilibrium point and suppose we wish to determine the stability of $x$. Let $L$ denote the linearization matrix of $\Sigma$ at $x$. Suppose that there are eigenpairs $(\lambda_i,v_i)$ of $L$ with $\lambda_i<0$ such that $\{v_1,\ldots,v_n\}$ is a basis for the tangent space $T_xM$ at $x$. Is there a version of the Hartman-Grobman theorem which allows us to conclude that $x$ is asymptotically stable?
In other words, if the linearization is done in the embedding space, can we (for the purpose of stability analysis) consider the linearized system at $x$ to be constrained to the tangent space $T_xM$?


text:
Q: Unrecognized option "csrf_provider" under "security.firewalls.main.form_login" despite csrf enabled After setting up the FOSUser Bundle I have experienced this error

Unrecognized option "csrf_provider" under "security.firewalls.main.form_login"

Now I know how to use google and the two main things that could cause the problem are

*

*Not enabling the csrf_protection in config.yml

*Not properly setting the csrf_provider in security.yml
The problem here is the fact that both of these options are properly set for me.
Here is the config.yml
imports:
    - { resource: parameters.yml }
    - { resource: security.yml }
    - { resource: services.yml }

# Put parameters here that don't need to change on each machine where the app is deployed
# http://symfony.com/doc/current/best_practices/configuration.html#application-related-configuration
parameters:
    locale: en

framework:
    #esi:             ~
    #translator:      { fallbacks: ["%locale%"] }
    secret:          "%secret%"
    router:
        resource: "%kernel.root_dir%/config/routing.yml"
        strict_requirements: ~
    form:            ~
    csrf_protection:
        enabled: true
    validation:      { enable_annotations: true }
    #serializer:      { enable_annotations: true }
    templating:
        engines: ['twig']
    default_locale:  "%locale%"
    trusted_hosts:   ~
    trusted_proxies: ~
    session:
        # http://symfony.com/doc/current/reference/configuration/framework.html#handler-id
        handler_id:  session.handler.native_file
        save_path:   "%kernel.root_dir%/../var/sessions/%kernel.environment%"
    fragments:       ~
    http_method_override: true
    assets: ~
    php_errors:
        log: true

# Twig Configuration
twig:
    debug:            "%kernel.debug%"
    strict_variables: "%kernel.debug%"

# Doctrine Configuration
doctrine:
    dbal:
        driver:   pdo_mysql
        host:     "%database_host%"
        port:     "%database_port%"
        dbname:   "%database_name%"
        user:     "%database_user%"
        password: "%database_password%"
        charset:  UTF8
        # if using pdo_sqlite as your database driver:
        #   1. add the path in parameters.yml
        #     e.g. database_path: "%kernel.root_dir%/../var/data/data.sqlite"
        #   2. Uncomment database_path in parameters.yml.dist
        #   3. Uncomment next line:
        #path:     "%database_path%"

    orm:
        auto_generate_proxy_classes: "%kernel.debug%"
        naming_strategy: doctrine.orm.naming_strategy.underscore
        auto_mapping: true

# Swiftmailer Configuration
swiftmailer:
    transport: "%mailer_transport%"
    host:      "%mailer_host%"
    username:  "%mailer_user%"
    password:  "%mailer_password%"
    spool:     { type: memory }

fos_user:
    db_driver: orm
    firewall_name: main
    user_class: AppBundle\Entity\User

And security.yml
security:
    encoders:
        FOS\UserBundle\Model\UserInterface: bcrypt

    role_hierarchy:
        ROLE_ADMIN:       ROLE_USER
        ROLE_SUPER_ADMIN: ROLE_ADMIN

    providers:
        fos_userbundle:
            id: fos_user.user_provider.username

    firewalls:
       main:
           pattern: ^/
           form_login:
               provider: fos_userbundle
               csrf_provider: security.csrf.token_manager
               # csrf_provider: form.csrf_provider
               # my syomfony is 3.1 I believe
           logout:       true
           anonymous:    true

    access_control:
        - { path: ^/login$, role: IS_AUTHENTICATED_ANONYMOUSLY }
        - { path: ^/register, role: IS_AUTHENTICATED_ANONYMOUSLY }
        - { path: ^/resetting, role: IS_AUTHENTICATED_ANONYMOUSLY }
        - { path: ^/admin/, role: ROLE_ADMIN }

I will also throw in the routing.yml which is the one from the FOS bundle setup
app:
    resource: "@AppBundle/Controller/"
    type:     annotation

fos_user_security:
    resource: "@FOSUserBundle/Resources/config/routing/security.xml"

fos_user_profile:
    resource: "@FOSUserBundle/Resources/config/routing/profile.xml"
    prefix: /profile

fos_user_register:
    resource: "@FOSUserBundle/Resources/config/routing/registration.xml"
    prefix: /register

fos_user_resetting:
    resource: "@FOSUserBundle/Resources/config/routing/resetting.xml"
    prefix: /resetting

fos_user_change_password:
    resource: "@FOSUserBundle/Resources/config/routing/change_password.xml"
    prefix: /profile

And with all that I'm still getting this issue. It's happeing upon clearing the cache in console so...clearing the cache isn't really a fix to this issue.
Has anyone else experienced this issue?

A: Replace csrf_provider with csrf_token_generator in your security.yml file, this will fix your problem!
Check this link for more information https://symfony.com/doc/master/bundles/FOSUserBundle/index.html#step-4-configure-your-application-s-security-yml


text:
Q: Do python codes need to be changed moving from ArcGIS 10.2 to 10.3 What changes (if any) do I need to make to my python scripts to migrate from ArcGIS10.2 to ArcGIS 10.3

A: The general rule we (esri) have when moving from version to version is dont break backwards compatibility. This means that a script written in an old version should run in a newer version.
Generally you can see items that have changed by looking in the Whats new for a given release. You'll notice that with all the tool changes parameters have either been updated with new options, or new parameters have been appended to the end. This means your script will continue to run. You do not need to modify anything to take these changes into account.
You mentioned the difference between 9.3 and 10. Yes, the arcpy module was added then. However old scripts that still used arcgisscripting did and still do continue to work.
I'll stop short of saying there has never been or never will be a change that breaks something. But I honestly can't come up with anything off the top of my head. In conclusion, your script you have today should continue to work just fine in the upgrade.
(This post doesn't count for moving from 10.x to Pro where the versions of Python different and somethings in Python are not backwards compatible. There is also changes to arcpy.mapping. Everything that did change and you need to be updated is documented in the Pro migration help)
(Edit) Per the couple comments on things that have changed: I cannot offer a reason why, my best guess was a bug was logged to change the behavior of a specific item. If something wasn't working the way it was intended and was causing an issue, we'd fix it (so I guess that serves as an example where we wouldn't gauaranteed backwards compatibility). Something we wouldn't do (as a far out example) would be to change the parameter order just 'because'.


text:
Q: forbidden chromatic polynomial We wish to show below chromatic polynomial are not exist; It means that we couldn't find any graph that has one of these chromatic polynomial
1-  $\ k^5 - 4k^4 + 8k^3 - 4k^2 +k$
2- $\ k^4 - 3k^3 + k^2$
3- $\ k^7 - k^6 + 1$
The chromatic polynomial is a polynomial:
$\pi_{k}(G)$ := the number of graph colorings with k color
It counts the number of graph colorings as a function of the number of colors
here k is the number of colors
For example:
$\pi_{k}(k_{n})$ = k(k-1)...(k-(n-1))
note that $\chi(k_{n})$ = n
in below link you could see more examples of chromatic polynomial
http://mathworld.wolfram.com/ChromaticPolynomial.html
and we can find a chromatic polynomial of a graph recursively
If G is simple, then
$\pi(G) = \pi(G - e) - \pi(G. e)$ for any edge of G.
for simple graphs we can go more in detail... the coefficient of the largest element is 1 and the other elements have none positive and none negative coefficient. and the constant element is -m.
while;
m = |E(G)|

A: First, I should correct one of your statements. It is not the constant term that equals $-m$, but the coefficient of the highest-degree-but-one term. That is, if the graph has $n$ vertices and $m$ edges, then the chromatic polynomial (which has degree $n$) has the term $-mk^{n-1}$.
If a graph has at least one edge, then it has no $1$-colorings. Thus, the chromatic polynomial evaluated at $1$ must be $0$. Equivalently, the sum of all the coefficients must be $0$.
Now, looking at the polynomials, the numbers of edges for a corresponding graph are $4$, $3$, and $1$ respectively. Thus, the sum of the coefficients must be $0$ in each case. But the polynomials have coefficient sums $2$, $-1$, and $1$ respectively, so we would have a contradiction if any of them were the chromatic polynomial of a graph.
Other arguments can be made. For instance, the constant term of a chromatic polynomial is always $0$, which excludes the third polynomial you listed.


text:
Q: Unpack C++ array to arguments on a function call I'm implementing a library capable of understanding Godot's RPC requests.
From the RPC request, I have made an array of arguments of arbitrary size. The arguments are all of the same type, Variant. Each Variant contains a type enum and casting overloading to return the proper type, be it an int or a const char*, etc.
Now, I'd like to have the library accept registrations of function points, or std::function instances, etc. The library should be able to unpack this array Variant* to arguments on the registered function.
i.e.
std::function<void(int, float, const char*)> foo;

Variant* args = ...;
size_t numArgs = ...;

/**
 * For example,
 * if (args[0].type == VAR_INT) {
 *     int arg_int = (int)args[0];
 * }
 * would be valid.
 */

foo(args...);

Is there a way to make this possible?


text:
Q: NoRM MongoDB : Build complex filters or add filters to existing queries How to build multicriterial queries in Norm driver adding extra filters to one existing base query? Thanks.
var coll= mongo.GetCollection<TaggedContents>();
var coll2 = coll.AsQueryable().Where(x=> x.ID==ID && x.Name=="Name");
var coll3 = coll2.AsQueryable().Where(x=> x.TagId==tagId && x.TagName=="TagName");

A: That looks like a candidate for the LINQ Union operator, roughly the SQL equivalent of "AND" or "OR"


text:
Q: UIview while loading didFinishLaunchingWithOptions I have an application in which the didFinishLaunchingWithOptions of my app delegate register for push notifications. This registration is taking little time, so at launching the app. i need to wait with a blank screen till it register. This waiting time i need to show a "please wait..." message, how can i do this? I have added a UIView before the registration code in didFinishLaunchingWithOptions but it only shows after registration. Plz help

A: Perhaps I'm misinterpreting your question, but it sounds like you're doing some sort of blocking activity in your -[UIApplication didFinishLaunchingWithOptions:] method. You should restructure your code such that you use an asynchronous strategy, so that you don't need to spend a long time waiting inside the didFinishLaunchingWithOptions method. Nothing will be displayed until after that method has completed execution anyway.
When you say your are registering for push notifications, perhaps you could be more specific and post an example of your method implementation? Simply calling -[UIApplication registerForRemoteNotificationTypes:] is non-blocking, so it would not cause the symptom you describe above.
It is important to perform any processing that could take time, such as synchronous network I/O, on a background thread to avoid blocking the main thread, which takes care of the user interface.

A: The iPhone Human Interface Guidelines suggest providing a default image which looks similar to your first view, which .  Many Apple apps do this.  See here:
Launch Images
I would try this before going so far as to have a "please wait" message.

A: Show a UIAlertView and UIActivityIndicatorView and then use performSelector:withObject:afterDelay: with delay 0.0 to invoke your register code. The indicator will be first animating and your register code can run in the same thread. The delay 0.0 allows a little short break for the indicator to start its animation redrawing process first.


text:
Q: android- make a listview grow upwards only Im creating an in app chat and I cant figure out how to keep the listview I have implemented to keep from growing down below the edittext box I set up to take user chat. Whats happening now is that new lines add to the listview just fine but after the list grows large enough it starts to add to itself below the edittext box. I find that pretty annoying and imagine a user would too so my question is:
How can I keep a listview from growing downwards.
Id like for new fields/text to add to the bottom of the listview but be placed ontop of the edittext just like any normal chat would do.

A: It's very easy, simply set the transcriptMode. If you do it from XML, you have the choice between normal and alwaysScroll:
http://developer.android.com/reference/android/widget/AbsListView.html#attr_android:transcriptMode
This is how the built-in Google Talk and SMS/MMS applications are implemented (they use the normal transcript mode.)


text:
Q: How can we obtain equations of motion from $\iota_{X_{H}}\omega =dH$? I don't know if this is an obvious result and I am just missing a trick, so please forgive me, but how do we obtain equations of motion from the following equation.
\begin{equation}
\iota _{X_{H}}\omega =dH
\end{equation}
Where $\omega$ is a non-degenerate, closed symplectic 2-form, $X_H$ is a Hamiltonian vector field and $H$ is a Hamiltonian function. I can see how Hamilton's ODEs or the Hamilton-Jacobi equation can be solved to give the equations of motion, but not in this case. I am assuming that this equation can actually be used to find equations of motion?
A great example would be a simple system like the harmonic oscillator or even a free particle! :)

A: This equation reduces to the Hamiltonian-Jacobi equations in certain specific examples.
The Hamiltonian formalism in symplectic geometry, which you've written above, is dependent on the fact that for a symplectic manifold $(M, \omega)$ and a smooth function $H : M \rightarrow \mathbb{R}$, there exists a unique vector field $X_H$ satisfying
$$\iota_{X_H} \omega = d H$$,
which is the equation you've written. The Hamiltonian dynamics on $(M, \omega)$ associated with the Hamiltonian function $H : M \rightarrow \mathbb{R}$ is the dynamical system where all points follow integral curves of the vector field $X_H.$ What makes this interesting is that the value of the function $H$ is conserved along the integral curves of $X_H$—corresponding to the idea that $H$ is conserved along the dynamical paths. This corresponds to the way that conservation of energy gives rise to your standard Hamilton-Jacobi equations.
This is all a bit abstract, but if we reduce it to the example of phase space, the Hamiltonian-Jacobi equations arise naturally.
To describe a physical system with $n$ degrees of freedom, we let our manifold be $M = \mathbb{R}^{2n}.$ We label $M$ with the coordinates $(q^1, \dots, q^n, p^1, \dots, p^n)$—the standard position-momentum phase space coordinates of the Hamiltonian formalism with which you're already familiar.
We define the symplectic form on $M$ to be $\omega = \sum\limits_{i=1}^n d q^{i} \wedge d p^{i}.$ You can verify for yourself that this form is symplectic. The idea is that the symplectic form tells us how the position and momentum coordinates should be paired with each other.
Now suppose we have a smooth function $H : M \rightarrow \mathbb{R}$ (this is the standard Hamiltonian with which you are familiar—it takes in a configuration in phase space and spits out the associated energy).
Now, our claim is that the dynamics should follow the integral curves of the vector field $X_H.$ So we write the vector field $X_H$ as $\left( \frac{d q^1}{dt}, \dots, \frac{d q^n}{dt}, \frac{d p^1}{dt}, \dots, \frac{d p^n}{dt}\right)$, since it should be the "time derivative" of our desired curve. We also know that $X_H$ is the unique curve satisfying $\iota_{X_H} \omega = d H.$ Well, let's evaluate each side of this separately.
$$\iota_{X_H} \omega = \iota_{X_H} \sum\limits_{i=1}^n d q^{i} \wedge d p^{i} = \sum\limits_{i=1}^n \left[ (d q^{i} \cdot X_H) d p^{i} - (d p^{i} \cdot X_H) d q^{i} \right] = \sum\limits_{i=1}^n \left[ \frac{d q^i}{dt} d p^i - \frac{d p^i}{dt} d q^{i} \right].$$
$$d H = \sum\limits_{i=1}^n \left[ \frac{\partial H}{\partial q^i} d q^i + \frac{\partial H}{\partial p^i} d p^i \right]$$
Equating the two sides (that is, demanding that $X_H$ satisfies our original equation), we find
$$\sum\limits_{i=1}^n \left[ \frac{\partial H}{\partial q^i} d q^i + \frac{\partial H}{\partial p^i} d p^i \right] = \sum\limits_{i=1}^n \left[ \frac{d q^i}{dt} d p^i - \frac{d p^i}{dt} d q^{i} \right],$$
or, equivalently,
$$\frac{\partial H}{\partial q^i} = - \frac{d p^i}{d t}$$
and
$$\frac{\partial H}{\partial p^i} = \frac{d q^i}{d t}.$$
So we've recovered the Hamilton-Jacobi equations using the formula you originally gave.
So the formula $\iota_{X_H} \omega = dH$ is really just a more general form of the Hamilton-Jacobi equation. It is powerful in that it can be used to define dynamics that are similar to our standard physical Hamiltonian dynamics on more complicated, non-trivially curved manifolds. It also gives us room to use some really neat geometric tools (for example, Lie derivatives) in discussing Hamiltonian systems.
EDIT:
I am adding this edit to address a question you asked in the comments:

How do we guarantee the uniqueness of the vector field for a given Hamiltonian?

This follows almost immediately from the nondegeneracy of the symplectic form $\omega$, along with some basic linear algebra. The fact that $\omega$ is nondegenerate means that there is no nonzero vector field $Y$ such that $\iota_Y \omega = 0.$
We may treat $\omega$ as a map between vector fields and dual vector fields. For any vector field $Y$, $\iota_Y \omega$ is a dual vector field. For example, we have $\iota_{x_H} \omega = d H$ (and $dH$ is a dual vector field).
So given any vector field, $\omega$ gives us a corresponding dual vector field. The nondegeneracy condition on $\omega$ amounts to telling us that this map has trivial kernel and is this injective. That is, $\iota_Y \omega = 0$ if and only if $Y = 0.$
A basic theorem in linear algebra states that if a map between vector spaces of the same dimension is injective, then it is surjective. Since a vector space and its dual vector space have the same dimension, the map given by $Y \mapsto \iota_Y \omega$ is bijective. It therefore has a well-defined inverse. This amounts to saying that for any dual vector field $\xi$, there exists a unique vector field $Y$ satisfying $\iota_Y = \xi.$
The uniqueness of the vector field $X_H$ for a given Hamiltonian is a special case of this result.


text:
Q: Is it possible to have a new title tag for each accordion heading? My site hosts a large quantity of information with categories/subcats/sub-subcats (tabs) and then info divided into questions and answers in accordion format.
I would like to have a different title tag and/or URL for each level
E.g. Animals/reptiles/snakes/how-do-you-catch-a-snake (how do you catch a snake is an accordion heading).
Is this possible?

A: Multiple <title> tags are not allowed, but you could modify the document.title property using javascript. For example, this would work:
$('#animals, #reptiles, #snakes, #how-do-you-catch-a-snake').click(function(e) {
    //assuming selected tabs get a .selected class
    if (!$(this).hasClass('selected')) {
        $(this).addClass('selected');
        //Assuming you want to make the `<title>` the same as the tab's contents
        document.title = this.innerHTML;
    } else {
        $(this).removeClass('selected');
    }
});

That makes a whole bunch of assumptions, but without code provided, I can't really give you a more fitting code. This should give you a general idea about how this could work though.


text:
Q: If $f:X\to\mathbb{C}$ is integrable, is it $|\int f|\le \int |f|$? Let $(X,S,\mu)$ be a measurable space. We say that $f:X\to\mathbb{C}$ is integrable if $Im(f)$ and $Re(f)$ are integrable, and we put $\int f :=\int Im(f)+i\int Re(f)$.
Is it true that $|\int f|\le \int |f|$?
I don't see if this is true, because:
$|\int f| = \sqrt{(\int Im(f))^2+(\int Re(f))^2}$ and $\int |f|=\int \sqrt{Im(f)^2+Re(f)^2}$
Could this be false?
Thanks.

A: Suppose that $\int f = r e^{i\theta}$.  Then
$$ \left|\int f\right| = \text{Re}\left(e^{-i\theta} \int f\right) = \int \text{Re}(e^{-i\theta} f) \le \int |f| .$$


text:
Q: SWRevealViewController - Reveal not showing nav menu I'm following this tutorial and I'm at the point (about halfway down) where I add this bit of code to some sort of controller:
if self.revealViewController() != nil {
    menuButton.target = self.revealViewController()
    menuButton.action = "revealToggle:"
    self.view.addGestureRecognizer(self.revealViewController().panGestureRecognizer())
}

Now, I'm a little confused on where this piece of code goes. I currently have it in my "front" view (the one that shows when the menu is closed). However, when I click my menu button, nothing happens.
Here is what my current storyboard looks like (there is a white menu button left of "Home" on the home screen, hard to see):

And here is my current viewDidLoad function inside HomeViewController.Swift:
override func viewDidLoad() {
        super.viewDidLoad()

        if self.revealViewController() != nil {
            print("reveal")
            menuButton.target = self.revealViewController()
            menuButton.action = "revealToggle:"
            self.view.addGestureRecognizer(self.revealViewController().panGestureRecognizer())
        }

        if webView != nil {
            print("webview is not null")
            webView!.scrollView.bounces = false

            let path = NSBundle.mainBundle().pathForResource("find_it_myself", ofType: "html", inDirectory: "assets/html/home")
            let serviceDeskPath = NSBundle.mainBundle().pathForResource("ServiceDeskNumbers", ofType: "json", inDirectory: "assets/data")
            let serviceDeskData = NSData(contentsOfMappedFile: serviceDeskPath!)
            let serviceCenterPath = NSBundle.mainBundle().pathForResource("ITSC Live Room Locations", ofType: "json", inDirectory: "assets/data")
            let serviceCenterData = NSData(contentsOfMappedFile: serviceCenterPath!)

            let newStr = NSString(data: serviceDeskData!, encoding: NSUTF8StringEncoding)
            let newerStr = NSString(data: serviceCenterData!, encoding: NSUTF8StringEncoding)

            NSLog(String(webView!.URL))

            NSLog("path: " +  path!)
            let requestURL = NSURL(fileURLWithPath: path!)
            print("request is not null")
            let request = NSURLRequest(URL:requestURL)

            let theConfiguration = WKWebViewConfiguration()
            theConfiguration.userContentController.addScriptMessageHandler(self, name: "interOp")

            webView!.loadRequest(request)
        }
        else{

            print("webview is null")
        }

    }

A: I'll post my solution just in case. The reveal was actually working, but only with the sliding gesture, not by pressing the menu button.
I added a button press function for the menuButton, with a revealToggle function call to the library from the GitHub project (SWRevealViewController).
@IBAction func menuButtonPressed(sender : AnyObject){
        self.revealViewController().revealToggle(menuButton)
    }

A: All this code:
menuButton.target = self.revealViewController()
menuButton.action = "revealToggle:"

means is that invoke method (revealToggle:) on RevealViewController, which means you should have a method in ReleavelViewController with that name and should do what you want to do there (if that's intended). Ideally you should have some thing like this:
menuButton.target = self
menuButton.action = "revealToggle:"

And then:
func revealToggle(sender: AnyObject) {
    //present your view controller
    self.pushViewController(self.revealViewController(), animated: true)
}

It's very confusing what you are trying to do here. You'r revealVC shows navigation controller on some event and menu controller on some other event. From what you have explained it seems, your home controller is the one which presents revealVC but there doesn't seem to be a segue for that? Did you mean to make your navigation controller "initial controller"?


text:
Q: How can I pass optional arguments as optional arguments? I have the following environments which are being used in my document.
As you can see, a lot of unnecessary complexity is being added by my arcane optional argument handling using \IfValueTF.
Is there a way to simplify this code such that expl3 'does what I'm thinking'?
I'd like to be able to express the logic with something like \begin{displayquote}[#1], where #1 retains its value/no-value status when it's passed to displayquote.
\documentclass{article}
\usepackage{expl3,xparse,csquotes} \ExplSyntaxOn

\NewDocumentEnvironment { citeverse } { o } {
  \IfValueTF{#1}
    {\begin{displayquote}[#1]}
    {\begin{displayquote}}
} {
  \end{displayquote}
}

\NewDocumentEnvironment { citeverse* } { o } {
  \IfValueTF{#1}
    {\begin{citeverse}[#1]}
    {\begin{citeverse}}

  % make square paragraph
  \setlength{\parindent}{0pt}
  \setlength{\parskip}{.5\baselineskip}
  \setlength{\parfillskip}{0pt}
  \setlength{\emergencystretch}{.5\textwidth}
} {
  \end{citeverse}
}

\NewDocumentEnvironment { pageverse } { o } {
  \thispagestyle{empty}
  \null
  \vfill
  \IfValueTF{#1}
    {\begin{citeverse}[#1]}
    {\begin{citeverse}}
} {
  \end{citeverse}
  \vfill
  \null
}

\NewDocumentEnvironment { pageverse* } { o } {
  \IfValueTF{#1}
    {\begin{citeverse*}[#1]}
    {\begin{citeverse*}}
} {
  \end{citeverse*}
}

\ExplSyntaxOff
\begin{document}
\begin{citeverse}
Easy come, easy go.
\end{citeverse}

\begin{citeverse}[Winston Churchill]
You have enemies?  Good.
That means you've stood up for something,
  sometime in your life.
\end{citeverse}

\begin{citeverse*}
A bird in the hand beats two in the bush.
In other news, this needs to be made longer
  to really show off the square paragraph functionality.
\end{citeverse*}

\begin{citeverse*}[Benjamin Disraeli]
Action may not always bring happiness;
  but there is no happiness without action.
\end{citeverse*}

\begin{pageverse}
Coming with quotations is hard.
\end{pageverse}

\begin{pageverse}[Abraham Lincoln]
Tact is the ability to describe others as they see themselves.
\end{pageverse}

\begin{pageverse*}
This is supposed to be a really long quotation---one that fills an entire page,
  but I've completely run out of axioms to use!
I can only take comfort in the trend that axioms are short and pithy.
\end{pageverse*}

\begin{pageverse*}[Albert Einstein]
Only one who devotes himself to a cause with
  his whole strength and soul can be a true master.
For this reason mastery demands all of a person.
\end{pageverse*}
\end{document}

A: You can abstract the construction:
\documentclass{article}
\usepackage{expl3,xparse,csquotes}

\ExplSyntaxOn

\NewDocumentCommand{\DefineSubEnvironment}{ m m m m m m }
 {
  \NewDocumentEnvironment { #1 } { o }
   {
    #3
    \IfValueTF{##1}{\begin{#2}[##1]}{\begin{#2}}
    #4
   }
   {
    #5
    \end{#2}
    #6
   }
 }

\DefineSubEnvironment { citeverse } { displayquote }
  { } % pre begin
  { } % after begin
  { } % pre end
  { } % after end

\DefineSubEnvironment { citeverse*} { citeverse }
  { } % pre begin
  {   % after begin
   % make square paragraph
   \setlength{\parindent}{0pt}
   \setlength{\parskip}{.5\baselineskip}
   \setlength{\parfillskip}{0pt}
   \setlength{\emergencystretch}{.5\textwidth}
  }
  { } % pre end
  { } % after end

\DefineSubEnvironment { pageverse } { citeverse }
  {   % prebegin
   \clearpage
   \thispagestyle{empty}
   \vspace*{\fill}
  }
  { } % after begin
  { } % pre end
  {   % after end
   \vspace*{\fill}
   \clearpage
  }

\DefineSubEnvironment { pageverse* } { citeverse* }
  { } % pre begin
  { } % after begin
  { } % pre end
  { } % after end

\ExplSyntaxOff

\begin{document}
\begin{citeverse}
Easy come, easy go.
\end{citeverse}

\begin{citeverse}[Winston Churchill]
You have enemies?  Good.
That means you've stood up for something,
  sometime in your life.
\end{citeverse}

\begin{citeverse*}
A bird in the hand beats two in the bush.
In other news, this needs to be made longer
  to really show off the square paragraph functionality.
\end{citeverse*}

\begin{citeverse*}[Benjamin Disraeli]
Action may not always bring happiness;
  but there is no happiness without action.
\end{citeverse*}

\begin{pageverse}
Coming with quotations is hard.
\end{pageverse}

\begin{pageverse}[Abraham Lincoln]
Tact is the ability to describe others as they see themselves.
\end{pageverse}

\begin{pageverse*}
This is supposed to be a really long quotation---one that fills an entire page,
  but I've completely run out of axioms to use!
I can only take comfort in the trend that axioms are short and pithy.
\end{pageverse*}

\begin{pageverse*}[Albert Einstein]
Only one who devotes himself to a cause with
  his whole strength and soul can be a true master.
For this reason mastery demands all of a person.
\end{pageverse*}
\end{document}


text:
Q: PC Restarts Without Giving Any Warning My PC restarts without giving any warning.  I'm using Windows 7 Ultimate 64-bit.  My OS starts well.  After running for some minutes, it restarts.  I couldn't find any reason.
My hardware:

*

*Processor: Intel core-i5 2400m 3.2 GHz

*Motherboard: Intel DH67CL

*Graphics Card: MSI GTX560 2GB DDR5 twin frozr dual oc

*Power supply: Thermaltake 650W smart power

*RAM: 10GB

*HDD: Samsung 1TB 7200rpm

A: I had a similar problem, it turned out to be a problem with the cooling system. Your laptop may be shutting itself down as soon as it detects the CPU reaching critical temperatures to prevent any damage.

A: At best you have a faulty PSU cable (Kettle Plug) or wall socket.
More likely, you have a faulty PSU (Power Supply), they're practically consumables. The cheaper they are the less efficient and less long they last.
(A 650W PSU is under spec for your rig - it will be at a high load, so it will be running above its ideal temperature range.)
Another possible is a faulty motherboard, which is routing the power. Less likely, but most annoying if it's the case.
You need to get your hardware checked by someone who know's what they are doing basically.
Edit: Overheating possible to, you may have an extremely dusty PC.
You should use canned air or an air hose to clean out your PC, if you have never done this before especially so.
You need to pay attention to the airflow near your computer as well, for example if your computer is in an enclosed space or near a hot object like a TV.

A: Possibly your system is overheating and the sudden restarts without warning is just your pc trying to save itself.

A: Probably you have a problem of temperature. removes the processor clean this area, new appliance and thermal pulp test your system.
If the problem continues check the power supply, check bios and install updates to news.


text:
Q: Menu siding from top and push the page down I need some help please.
I'm trying to make a menu that pushes the page down when clicked and displays the specific sub-menu.
The menu should be above the page with a height of 50px. If i'm using height the content won't be pushed down.
When I click on first link i should get the sub menu for that link. If I push the second link the first submenu should be replaced with the second set of sub menu links.
Right now it's all messed up and I cant get it to work. I dont know much about javascript, as you can see here:
jQuery(document).ready(function(){
    jQuery(".menu-item-has-children").click(function(){
        jQuery(this).children(".sub-menu").slideToggle();
    });
});

Thank you in advance for all your time.
https://jsfiddle.net/tjkr6L08/

A: Take a look at https://jsfiddle.net/tjkr6L08/1/
Javascript
jQuery(document).ready(function() {
  jQuery(".menu-item-has-children").click(function() {

    jQuery(".opened").slideUp().removeClass("opened");
    jQuery(this).children(".sub-menu").slideToggle().addClass("opened");

  });
});

CSS
.sub-menu {
  display: none;
  position:absolute;
  top:40px;
  left:0;
  right:0;
}

So your issue is 50% css, 50% javascript. What you want is to make a reference to previously opened submenu, so you can close it. To make things align properly, the menu can be absolute;
So the above is the quickest possible solution - might not be the best, but will give you an idea how to proceed.

A: you can use the bootstrap collapse class instead of toggle in java script once see the documentation of the bootstrap Collapse

  .menu-menu-top-container {
  width: 100%;
  text-align: center;
  position: static;
  height: 50px;
}

.menu-top li {
  display: inline-block;
  padding:5px;
}
<!DOCTYPE html>

  <meta name="viewport" content="width=device-width, initial-scale=1">
  <link rel="stylesheet" href="https://maxcdn.bootstrapcdn.com/bootstrap/3.3.7/css/bootstrap.min.css">

Companie

 Cariere

Contact

Echipa

Echipa

Implicare socială

Misiune și Valori

Calitate și certificări

Despre noi?

Echipa Copy

Echipa

Implicare socială

Misiune și Valori

Calitate și certificări

Despre noi?


text:
Q: How to split an array from a text file by a comma, only getting one array index displayed in Listbox? First of all I would like to thank anyone willing to help ahead of time. My issue here is that when I attempt to populate my listbox with items in my array, I am getting only "General" added as a listbox item instead of the actual strings in the array. I'm rather new to programming so I apologize if this is an obvious error in my code, although I'm assuming it probably is.
This is my code:
Private Sub frmSalesSummary_Load(sender As Object, e As EventArgs) Handles
MyBase.Load
    Dim info() As String = IO.File.ReadAllLines("info.txt")
    Dim splitChar As Char = ","
    Dim infoString As String
    For i = 0 To info.GetUpperBound(0)
        infoString = info(i).Split(splitChar)
        lstSummary.Items.Add(infoString(i))
    Next
End Sub

The text file contains this for testing "alex,General,7,$105.00" on the first line.
There may be frequent edits to this question as I am actively trying to figure this out myself as well. Apologies.

A: 'info' is your line (comma delimited)
'infoString' is an array of the words that are separated by the Split
So if you want to add a single item from that split you would use
infoString(0) for the name, infoString(1) for the Rank, etc...
So you're taking each line, splitting it and to add the name to the listbox you only need to add infoString(0) because that element of the array holds the name from splitting it out from the line.
Try
lstSummary.Items.Add(infoString(0))

If you're wanting a list like:
alex
General
7
$105.00

You could create another loop inside your current loop and use the iterator for the index.
For i = 0 to info.GetUpperbound(0)
   infoString = info(i).Split(splitChar)
   For x = 0 to infoString.GetUpperBound(0)
      lstSummary.Items.Add(infoString(x))
   Next
Next

This would take each Line, split it and then add the info from each line to the listbox... Keep in mind, you would have the 4 you showed, then the next line would put the next 4 pieces of information until you run out of lines in your text file.
Still not quite sure if that is exactly what you're trying to do, if this still isn't the case, you might mock up some picture of what you're expecting along with information as to whether or not there is more of this information in the text file.

A: A small tip. You should never use controls to store the data you're using. Store it as a list of PersonDetails objects, or whatever you want to call them.
You can declare the PersonDetails object like this ..
Private Class PersonDetails
    Public Property Name As String
    Public Property Category As String
    Public Property Type As Integer
    Public Property Amount As Decimal
End Class

And the list of them like this
Dim PersonSummaryList As New List(Of PersonDetails)

Your form load event reads the text file and for each line, creates a new PersonDetails object and adds it to the list of PersonDetails and then adds the names to a ListBox
Private Sub frmSalesSummary_Load(sender As Object, e As EventArgs) Handles MyBase.Load
    Dim info() As String = IO.File.ReadAllLines("info.txt")
    Dim splitChar As Char = ","c
    Dim infoString() As String
    For i As Integer = 0 To info.GetUpperBound(0)
        infoString = info(i).Split(splitChar)
        'remove the commas and $ signs
        infoString(3) = infoString(3).Replace("$"c, "")
        Dim newPerson As New PersonDetails
        newPerson.Name = infoString(0)
        newPerson.Category = infoString(1)
        newPerson.Type = Integer.Parse(infoString(2))
        Decimal.TryParse(infoString(3), newPerson.Amount)
        PersonSummaryList.Add(newPerson)
    Next

End Sub

In your ListBox, all you will see is a list of names, and when you click on an item, the code below will find the object that matches the name you selected and display whatever properties you want in a MessageBox, but of course you can do whatever you want with the tempPerson object.
Private Sub LstSummary_SelectedIndexChanged(sender As Object, e As EventArgs) Handles LstSummary.SelectedIndexChanged
    Dim tempPerson As PersonDetails = PersonSummaryList.Find(Function(x) x.Name = LstSummary.SelectedItem.ToString)
    MessageBox.Show("Name :" & tempPerson.Name & vbCrLf & "Amount :" & tempPerson.Amount)
End Sub


text:
Q: PaintCode button press in view using objective-c? So I used PaintCode to make a popup view. I used two canvases for it, the main one for the popup and another for a x close button. I want to be able to detect when that x is tapped so I can close the view. The paint code files are a class of type NSObject and I am using another UIView class to call the function. The x button is implemented as follows:
//// Symbol Drawing
CGRect symbolRect = CGRectMake(194, 12, 17, 17);
CGContextSaveGState(context);
CGContextClipToRect(context, symbolRect);
CGContextTranslateCTM(context, symbolRect.origin.x, symbolRect.origin.y);

[PinView drawCanvas2WithFrame: CGRectMake(0, 0, symbolRect.size.width, symbolRect.size.height) resizing: PinViewResizingBehaviorStretch];
CGContextRestoreGState(context);

Thanks in advance.


text:
Q: Region bounded by the parabola $\, y=x^2\;$ and the line $\, y=16\;$ What is the volume of the solid generated when R is rotated about $y = 17$? Let R be the region bounded by the parabola $ \, y=x^2\;$ and the line $\, y=16\;. $
What is the volume of the solid generated when R is rotated about the line $\, y=17 \; ?
$
So there's outer radius, and inner radius. What's my outer radius? $17-16 = 1$?
And inner radius is just $x^2 - 16$?
So the formula for integration is is  $\pi \cdot 1^2 + \pi \cdot (x^2 - 16)^2$
Right? And then the intervals are between $- \sqrt{17}$ and $\sqrt{17}$
But the answer I get: $\frac{4004 \sqrt(17) \pi}{15}$ seems to be wrong...
p.s. Okay, it has a hole in it, outer radius (actual thing I'm finding) - inner radius (the hole).

A: Notice:
$$\text{Outer radius }=r_o=17-x^2\qquad\text{and}\qquad\text{Inner radius }=r_i=17-16=1$$
Then, since $y=x^2$ meets the line $y=16$ at $(-4,16)$ and $(4,16)$, we have
\begin{align*}
V&=\int_{-4}^{4}\pi (r_o^2-r_i^2)\,\mathrm d x\\
 &=\pi\int_{-4}^{4} \left[(17-x^2)^2-1^2\right]\,\mathrm d x\\
\end{align*}

A: Outer radius $R$ should be the distance from the curve furthest from the axis of rotation and the axis. In your case, $R=17-x^2.$  Inner radius, $r$ is the distance between the curve closest to the axis of rotation and the axis. In your case, $r=17-16=1.$  The integral for your volume then is
$$\pi\int_{-4}^4(R^2-r^2)dx.$$
Can you take it from here?


text:
Q: Applying AJAX on asp.net form I have the following code for a Form in ASP.NET.
I want to apply AJAX on it. How would I do this?

In this form, I also have a gridview on the same page showing the entries which I make using form. I don't want the page to reload when I press save button.

<form id="form1" action="~/studentForm.aspx" runat="server">

                    Name

                        <asp:TextBox ID="txtName" runat="server" class="form-control" Width="202px"></asp:TextBox>

                        <asp:RequiredFieldValidator ID="RequiredFieldValidator1" runat="server" ControlToValidate="txtName" ErrorMessage="Enter Your Name " ForeColor="#CC0000" SetFocusOnError="True" Style="text-align: right; font-weight: 700; color: #FF0000" ToolTip="Enter Name" ValidationGroup="saveUser">Required</asp:RequiredFieldValidator>

                    AGE

                        <asp:TextBox ID="txtAge" runat="server" class="auto-style14" Width="202"></asp:TextBox>

                        <asp:RequiredFieldValidator ID="RequiredFieldValidator2" runat="server" ControlToValidate="txtAge" ErrorMessage="Enter Your Age" ForeColor="#CC0000" CssClass="auto-style2" SetFocusOnError="True" ToolTip="Enter Age" ValidationGroup="saveUser">Required</asp:RequiredFieldValidator>

                        <asp:RangeValidator ID="RangeValidator1" runat="server" ControlToValidate="txtAge" ErrorMessage="Age Must Be Between 18 and 60" ForeColor="#CC0000" MaximumValue="60" MinimumValue="18" Style="text-align: right; font-weight: 700; color: #FF0000" ToolTip="Enter Age Between 18 and 60" Type="Integer" ValidationGroup="saveUser">Invalid Age</asp:RangeValidator>

                    Department

                        <asp:DropDownList ID="ddlDepartment" runat="server" class="form-control btn btn-primary dropdown-toggle" Width="202px">
                            <asp:ListItem Value="-1">Select Departement</asp:ListItem>
                            <asp:ListItem>COMMERCE</asp:ListItem>
                            <asp:ListItem>LAW</asp:ListItem>
                            <asp:ListItem>IT</asp:ListItem>
                            <asp:ListItem>BBA</asp:ListItem>
                        </asp:DropDownList>

                        <asp:RequiredFieldValidator ID="RequiredFieldValidator3" runat="server" ControlToValidate="ddlDepartment" ErrorMessage="Enter Your Departement" ForeColor="#CC0000" InitialValue="-1" CssClass="auto-style2" SetFocusOnError="True" ToolTip="Select Drpartement" ValidationGroup="saveUser">Required</asp:RequiredFieldValidator>

                    Gender

                        <asp:RadioButton ID="rdBtnMale" runat="server" class="radio-inline" Checked="True" GroupName="gender" Text="Male" />
                        <asp:RadioButton ID="rdBtnFemale" runat="server" class="radio-inline" GroupName="gender" Text="Female" />

                    Subjects

                        <asp:CheckBoxList ID="CheckBoxList2" runat="server" RepeatDirection="Horizontal" Width="298px">
                            <asp:ListItem>Physics</asp:ListItem>
                            <asp:ListItem>Chemistry</asp:ListItem>
                            <asp:ListItem>Biology</asp:ListItem>
                        </asp:CheckBoxList>

                        <asp:Button ID="btnSave" runat="server" class=" btn btn-success" OnClick="btnSave_Click" Text="Save" Width="105px" ValidationGroup="saveUser" />
                        <input id="btnReset" class="btn btn-warning" type="reset" value="Cancel" style="width: 105px" />

A: In Asp.Net you can use the Update Panel:

    <form id="form1" runat="server">

        <asp:ScriptManager ID="ScriptManager1" runat="server">
        </asp:ScriptManager>
        <asp:UpdatePanel ID="UpdatePanel1" runat="server">
            <ContentTemplate>
               [your code here]
            </ContentTemplate>
        </asp:UpdatePanel>

    </form>


text:
Q: How to scroll to next section of page when Bootstrap carousel scrolled to it's last child horizontally HTML

lorem

lorem

lorem

JS
$('#slider').bind('mousewheel', function(e){
    e.preventDefault();

    if(e.originalEvent.wheelDelta /120 > 0) {
        $(this).carousel('prev');
    }
    else if ($("#slider .carousel-inner .carousel-item:last").hasClass("active")) {
        e.stopPropagation();
    }
    else{
        $(this).carousel('next');
    }
});

Here, the mouseweel event listener is moving the Bootstrap carousel to the next slider. How to scroll the page to the next section when the carousel reached it's last slide. Thanks in advance!

A: Instead of e.stopPropagation(); you should use $('#slider').off('mousewheel');. However, there are couple of things to note here as well:

*

*First off, .bind() has been deprecated as of jQuery 3.0, thus you should not use it any more. Use .on() instead to bind event listeners.

*Second, the mousewheel event has the delta value available as it's second argument. So instead of using e.originalEvent.wheelDelta you could simply use that.

*The .carousel-inner part in the css selector of the else if is  unnecessary, as #slider .carousel-item already targets the required elements.

*FYI: The wheelDelta / 120 division is completely useless in this situation as you compare the result to zero.

So your script could look something like this:
$('#slider').on('mousewheel', function(e, delta) {
    e.preventDefault();

    if (delta > 0) {
        $(this).carousel('prev');
    }
    else if ($("#slider .carousel-item:last").hasClass("active")) {
        // e.stopPropagation();
        $('#slider').off('mousewheel');
    }
    else {
        $(this).carousel('next');
    }
});

Working snippet ahead:

$('#slider').on('mousewheel', function(e, delta) {
    e.preventDefault();
    if (delta > 0) {
        $(this).carousel('prev');
    }
    else if ($("#slider .carousel-item:last").hasClass("active")) {
        // e.stopPropagation();
        $('#slider').off('mousewheel');
    }
    else {
        $(this).carousel('next');
    }
});
body {
    height: 200vh;
    background-color: #E6E6FA !important;
}

#slider {
    background-color: grey;
}

lorem

lorem

lorem

<link href="https://maxcdn.bootstrapcdn.com/bootstrap/4.0.0-beta.2/css/bootstrap.min.css" rel="stylesheet"/>


text:
Q: PInvoke for GlobalMemoryStatusEx on Windows CE Do not vote this down if you don't work on or know about Windows CE and the Compact Framework. Thanks.
Anybody know if this function is available on WinCE and (if so) what the DLL is? I've tried to PInvoke this from "coredll.dll" and "kernel.dll". The Win32 version comes from "kernel32.dll".
[return: MarshalAs(UnmanagedType.Bool)]
[DllImport("kernel.dll")] // and "coredll.dll" also doesn't work
public static extern bool GlobalMemoryStatusEx([In,Out] MEMORYSTATUSEX lpBuffer);

The above function fails when I try and use it with an exception "Can't find PInvoke DLL 'kernel.dll'."
PS: I use loads of PInvoked functions such as this one:
[DllImport("coredll.dll")]
public static extern IntPtr SendMessage(IntPtr hWnd, int nMsg, IntPtr wParam, IntPtr lParam);

A: There's only the GlobalMemoryStatus call, not the extended (...Ex) version. It is located in coredll.dll, see http://pinvoke.net/default.aspx/coredll.GlobalMemoryStatus

A: Have implemented the answer suggested by C.Evenhuis and it works well. Here's the code for anyone who might need this in future:
// Structure to allow getting memory usage
public struct MEMORYSTATUS
{
        public int nLength;
        public int nMemoryLoad;
        public uint uTotalPhys;
        public uint uAvailPhys;
        public uint uTotalPageFile;
        public uint uAvailPageFile;
        public uint uTotalVirtual;
        public uint uAvailVirtual;
}

[DllImport("coredll", EntryPoint="GlobalMemoryStatus", SetLastError = false)]
public static extern void GlobalMemoryStatus(out MEMORYSTATUS memCE);

MEMORYSTATUS mem = new MEMORYSTATUS();
mem.nLength = Marshal.SizeOf(typeof(MEMORYSTATUS));
GlobalMemoryStatus(out mem);
// Label1.Text = (mem.uAvailPhys.ToString() + "Bytes");

A: I'm using in this way.
/// <summary>
/// https://msdn.microsoft.com/en-us/library/ee488368.aspx
/// This structure contains information about current memory availability. The GlobalMemoryStatus function uses this structure.
/// </summary>
[StructLayout(LayoutKind.Sequential)]
public struct MemoryStatus
{
    /// <summary>
    /// Specifies the size, in bytes, of the MEMORYSTATUS structure.
    /// Set this member to sizeof(MEMORYSTATUS) when passing it to the GlobalMemoryStatus function.
    /// </summary>
    public int Length;
    /// <summary>
    /// Specifies a number between zero and 100 that gives a general idea of current memory use, in which zero indicates no memory use and 100 indicates full memory use.
    /// </summary>
    public uint MemoryLoad;
    /// <summary>
    /// Indicates the total number of bytes of physical memory.
    /// </summary>
    public uint TotalPhys;
    /// <summary>
    /// Indicates the number of bytes of physical memory available.
    /// </summary>
    public uint AvailPhys;
    /// <summary>
    /// Indicates the total number of bytes that can be stored in the paging file.
    /// This number does not represent the physical size of the paging file on disk.
    /// </summary>
    public uint TotalPageFile;
    /// <summary>
    /// Indicates the number of bytes available in the paging file.
    /// </summary>
    public uint AvailPageFile;
    /// <summary>
    /// Indicates the total number of bytes that can be described in the user mode portion of the virtual address space of the calling process.
    /// </summary>
    public uint TotalVirtual;
    /// <summary>
    /// Indicates the number of bytes of unreserved and uncommitted memory in the user mode portion of the virtual address space of the calling process.
    /// </summary>
    public uint AvailVirtual;
    [DllImport("coredll.dll")]
    private static extern void GlobalMemoryStatus(ref MemoryStatus ms);
    public static string GetMemoryStatus()
    {
        var retValue = new StringBuilder();
        MemoryStatus ms = GlobalMemoryStatus();
        retValue.AppendLine(string.Format("Memory Load {0} %", ms.MemoryLoad));
        retValue.AppendLine(string.Format("Total Phys {0} Kb", ms.TotalPhys / 1024));
        retValue.AppendLine(string.Format("Avail Phys {0} Kb", ms.AvailPhys / 1024));
        retValue.AppendLine(string.Format("Tota PFile {0} bytes", ms.TotalPageFile));
        retValue.AppendLine(string.Format("Avai PFile {0} bytes", ms.AvailPageFile));
        retValue.AppendLine(string.Format("Total Virt {0} Kb", ms.TotalVirtual / 1024));
        retValue.AppendLine(string.Format("Avail Virt {0} Kb", ms.AvailVirtual / 1024));
        return retValue.ToString();
    }

    public static MemoryStatus GlobalMemoryStatus()
    {
        MemoryStatus ms = new MemoryStatus();
        ms.Length = Marshal.SizeOf(ms);
        GlobalMemoryStatus(ref ms);
        return ms;
    }
    public static uint GetMemoryLoad()
    {
        var ms = GlobalMemoryStatus();
        return ms.MemoryLoad;
    }
}

You can check in WinBase.h of your Windows CE SDK
typedef struct _MEMORYSTATUS {
    DWORD dwLength;
    DWORD dwMemoryLoad;
    DWORD dwTotalPhys;
    DWORD dwAvailPhys;
    DWORD dwTotalPageFile;
    DWORD dwAvailPageFile;
    DWORD dwTotalVirtual;
    DWORD dwAvailVirtual;
} MEMORYSTATUS, *LPMEMORYSTATUS;

VOID
WINAPI
GlobalMemoryStatus(
    __inout LPMEMORYSTATUS lpBuffer
    );

Because is _inout in SDK. I have used "ref" parameter modifier.
this is all about.


text:
Q: How to correctly style drop-down menu I ran into problems while styling drop-down menu. Everything is working fine but I have absolute positioning in my CSS (which works) but it of course doesn't work properly when I change my screen resolution. I am more programmer than a designer.
Here is my menu:

        Galerie

            Starší pokoje

            Novější pokoje

And here is the relevant CSS
#submenu {
   display: none;
   padding: 0px;
   margin-top: 5em;
   margin-left: 27.5em;
   position: absolute;
   left: 0px;
}
.nav a {
   border-right: 2px solid #161616;
   color: #CCC;
   float: left;
   font: bold 1em Verdana,sans-serif;
   line-height: 51px;
   padding: 0 20px;
}

And piece of jQuery which does the drop out
$(document).ready(function() {
    $("#menu").hover(function() {
        $("#submenu").fadeIn();
        },
    function() {
        $("#submenu").fadeOut();
    });
});

How can I improve this to be it more browser and resolution independent?
Edit
When I increase or decrease resolution of my display or try to look at it on bigger screen, the the drop-down menu is moved to either left or right side depending on the resolution.  Which is obviously something I don't. Here is the link, it's not finished.

A: The #menu must have a position:relative;
This way, the #submenu will have position:absolute; according to the #menu and inside of it, left:0px; means it will stick on the left border of the #menu and this is what you want, no need for a margin-left and a margin-top, just add top:30px; and test it if its positioned correctly under Galerie, maybe you'll need to increase the top or decrease it.
#menu
{
    position:relative;
}
#submenu {
   display: none;
   padding: 0px;
   position: absolute;
   left: 0px;
   top:30px; //find the best value
}

UPDATE
When I said that the #menu must have a position:relative; I thought that the #menu is a div that only contains the  Galerie, if this is not the case, if the #menu contains all the 4 links: Uvod .. Cenik.. etc... then of course it will stick at the beginning.
What you need to do is to add a special div container for the Galerie, means...

   Uvod
   Cenik

       Galerie

          ......

   Kontakt

Now, the position:relative; must be set for #galerieParent.

A: There are a number of issues here. I've modified the layout to be more inline with the way most developers set up this type of menu. I've also reversed most of your IDs and classes, which are being used in such a way as to almost guarantee duplicate IDs.
This may not be an ideal answer to your question, but I think there's some helpful information in it.
http://jsfiddle.net/mrPse/8/
#nav {
    position: relative;
}
#nav a {
    border-right: 2px solid #161616;
    color: #CCC;
    float: left;
    font: bold 1em Verdana, sans-serif;
    line-height: 51px;
    padding: 0 20px;
}
#nav > li {position: relative; display: inline-block;}
#nav li ul li a {border-right: 0;}
.submenu {
    display: none;
    padding: 0px;
    margin-top: 3em;
    position: absolute;
    left: auto;
    width: 180px;
}
.submenu li a {border-right: 0;}

Úvod

Ceník

        Galerie

Starší pokoje

Novější pokoje

Kontakt

$(".menu").hover(function () {
    $(this).children(".submenu").fadeIn();
}, function () {
    $(this).children(".submenu").fadeOut();
});

A: You need to add some CSS
#menu {position:relative;}

and change
#submenu {margin-left:14.5em;}

adjust as needed.


text:
Q: Почему блоки не плавающие и не принимают ширину указанную для класса grid4 Использую CSS фреймворк 960gs.  В этой системе сеток все классы grid_... начиная от grid_1 до grid_12 имеют свойство float: left.
Для grid_1 установлена ширина в 60px и внешние отступы с обоих сторон по 10px, того блок с классом grid_1 будет занимать пространство 80px, grid_2 - 160px, grid_3 - 240px, grid4 - 320px соответственно и т.д. grid_12 и container_12 занимают пространство в 960px.
Вопрос: почему блоки #column1, #column2, #column3 не плавают влево и не занимают 320px каждый?

ul {
  text-align: center;
}

li {
  display: inline;
  margin-right: 3px;
}

a {
  color: #000;
}

#nav,
#characteristic,
#footer {
  background-color: lightgrey;
  padding: 20px;
  margin-top: 20px;
  text-align: center;
}

#characteristic {
  height: 120px;
  margin-bottom: 20px;
}

#column1,
#column2,
#column3 {
  margin-bottom: 20px;
  background-color: lightgrey;
  text-align: center;
  padding: 20px;
}

.clear {
  clear: both;
}

Логотип

Домой

Товары

Услуги

О нас

Контакты

    Характеристики

    Колонка1

    Колонка2

    Колонка3

A: Импортировал файл css c главной страницы https://960.gs/css/master.min.css и (если посмотреть в код) видно что width приписал фиксированый для grid_4 300px + у вас есть приписаны padding :20px; что уже больше 1200px как указано для container_12

@import url("https://960.gs/css/master.min.css");
ul {
    text-align: center;
   }
   li {
    display: inline;
    margin-right: 3px;
   }
   a {
    color: #000;
   }
   #nav, #characteristic, #footer {
    background-color: lightgrey;
    padding: 20px 0;
    margin-top: 20px;
    text-align: center;
   }
   #characteristic {
    height: 120px;
    margin-bottom: 20px;
   }
   #column1, #column2, #column3 {
    margin-bottom: 20px;
    background-color: lightgrey;
    text-align: center;
    padding: 20px 0;
   }
   .clear {
    clear: both;
   }

Логотип

Домой

Товары

Услуги

О нас

Контакты

    Характеристики

    Колонка1

    Колонка2

    Колонка3