text:
Q: Creating a layout which follows text box width So I'm trying to get the following layout which consists of three elements, an outer shell (div), a text box and a circle element:

But the problem I'm having is that I want the outer shell div width to scale based on the width of the textbox, meaning if the width of the textbox is smaller, then it would scale down as well.

Right now, i have the following in HTML:

Two issues is that, the circle i defined in CSS is not showing up which i wanted to get like the above, second is that the outer shell is not following the width of the textbox.

html, body {
    height: 100%;
}

.main {
    border: 1px solid black;
    height: 50%;
    width: 50%;
    display: flex;
    justify-content: center;
    align-items: center;
}

.outer_shell {
    border: 1px solid black;
    border-radius: 40px;
}

.circle {
    width: 20%;
    height: 20%;
    background: blue;
}

#text_in {
    width: 50%;
    height: 100%;
}
<!DOCTYPE html>

    <meta charset="UTF-8">
    <meta name="viewport" content="width=device-width, initial-scale=1.0">
    <link rel="stylesheet" href="style.css">
    <title>Document</title>

            <input type = "text" id = "text_in">

A: I did some experimentation with the provided code and I found that the HTML appeared okay. The error was found in the CSS file. The following code snippet should work:

html, body {
    height: 100%;
}

.main {
    border: 1px solid black;
    height: 50%;
    width: 50%;
    display: flex;
    justify-content: center;
    align-items: center;
}

.outer_shell {
    border: 1px solid black;
    border-radius: 40px;
    display: inline-flex;
    width: fit-content;
}

.circle {
    width: 20px;
    background: blue;
    border-radius: 50%;
    padding: 1px;
}

#text_in {
    width: 200px;
    height: 100%;
    margin-left: 5px;
    margin-right: 10px;
    float: right;
}
<!DOCTYPE html>

    <meta charset="UTF-8">
    <meta name="viewport" content="width=device-width, initial-scale=1.0">
    <link rel="stylesheet" href="style.css">
    <title>Document</title>

            <input type = "text" id = "text_in">

A: First of all, love your drawing.
You should use
width: fit-content
for your outer_shell


text:
Q: using an Azure Service Bus Queue and BrokeredMessage.ScheduledEnqueueTimeUtc to renew subscriptions I have a subscription model, and want to perform renew-related logic like issue new invoice, send emails, etc.  For example, user would purchase the subscription today, and the renewal is in a year's time.  I've been using an Azure Queue recently, and think it would apply for such a renewal.
Is it possible to use the Azure Queue by pushing messages using BrokeredMessage.ScheduledEnqueueTimeUtc (http://msdn.microsoft.com/en-us/library/microsoft.servicebus.messaging.brokeredmessage.scheduledenqueuetimeutc.aspx) for such long term scheduled messages?
I've used it for shorter-term, like sending notifications in 1 minute time and it works great.
This way, I can have even multiple processes listening to the queue, and be sure that only one process would perform the renewal logic.  This would solve a lot of locking-related problems, as that is kind of built-in the Azure Queue via leasing and related features.

A: Yes, you can use it for long-term scheduling, scheduled messages have the same guaranties as normal ones. But there are few things you need to be aware of:

*

*ScheduledEnqueueTimeUtc is a time when message is going to be available (within hundreds of miliseconds) on the queue but not necessary delivered, this depends on load and state of the queue. So it's fine for business processes but not for time sensitive (milliseconds) usage. Not a problem in your case, unless your subscription cancellation is really time sensitive.

*It affects your storage quota ( Not really a problem with current quotas, but if you think about years this might be a problem)

*As far as I'm aware you can't access scheduled messages before ScheduledEnqueueTimeUtc, they are invisible.

Extremely awesome source of informations on azure messaging
From technological perspective it's fine but in your case I would also think about other potential problems if you think about years:

*

*Message versioning

*What happens when you would like to change Azure to something else (AWS?)

*What if you decide to change in next year Azure Service Bus for NServiceBus

redpajama_set_name: RedPajamaStackExchange


text:
Q: Entity Framework 4 - checking to see if an entity is attached In NHibernate we override Equals() and GetHashCode() to calculate entity equality.
Is the same necessary in Entity Framework?
The reason I ask is we are using EF4 with POCOs and are in the process of implementing a caching layer. The problem we have is when checking to see if an item is already attached to the object context. Currently this evaluates to false, even when the entity already exists in the current object context.

A: Maybe this code will give you some ideas. Im not using POCOs, but common points are the same I think.
Here is sample Update method which checks if Context has entity attached before performing updating routine.
 public T Update(T entity)
 {
      if (entity == null) throw new ArgumentNullException("entity");
      var key = ObjectContext.CreateEntityKey(ObjectContext.GetEntitySet<T>().Name, entity);
      if (ObjectContext.IsAttached(key))
      {
          ObjectContext.ApplyCurrentValues(key.EntitySetName, entity);
      }
      else
      {
          ObjectContext.AttachTo(ObjectContext.GetEntitySet<T>().Name, entity);
          ObjectContext.ObjectStateManager.ChangeObjectState(entity, EntityState.Modified);
      }
      return entity;
 }

internal static EntitySetBase GetEntitySet<TEntity>(this ObjectContext context)
 {
      var container = context.MetadataWorkspace.GetEntityContainer(context.DefaultContainerName, DataSpace.CSpace);
      var baseType = GetBaseType(typeof(TEntity));
      var entitySet = container.BaseEntitySets
                .Where(item => item.ElementType.Name.Equals(baseType.Name))
                .FirstOrDefault();

      return entitySet;
 }

internal static bool IsAttached(this ObjectContext context, EntityKey key)
 {
      if (key == null)
      {
          throw new ArgumentNullException("key");
            }
          ObjectStateEntry entry;
          if (context.ObjectStateManager.TryGetObjectStateEntry(key, out entry))
          {
                return (entry.State != EntityState.Detached);
          }
           return false;
 }

  private static Type GetBaseType(Type type)
  {
       var baseType = type.BaseType;
       if (baseType != null && baseType != typeof(EntityObject))
       {
            return GetBaseType(type.BaseType);
       }
       return type;
  }

Hope this can help you a bit=)


text:
Q: Nutch 1.11 crawl Issue I have followed the tutorial and configured nutch to run on Windows 7 using Cygwin and i'm using Solr 5.4.0 to index the data
But nutch 1.11 is having problem in executing a crawl.
Crawl Command
$ bin/crawl -i -D solr.server.url=http://127.0.0.1:8983/solr /urls /TestCrawl 2
Error/Exception
Injecting seed URLs /apache-nutch-1.11/bin/nutch inject /TestCrawl/crawldb /urls
    Injector: starting at 2016-01-19 17:11:06
    Injector: crawlDb: /TestCrawl/crawldb
    Injector: urlDir: /urls
    Injector: Converting injected urls to crawl db entries.
    Injector: java.lang.NullPointerException
    at java.lang.ProcessBuilder.start(ProcessBuilder.java:1012)
    at org.apache.hadoop.util.Shell.runCommand(Shell.java:445)
    at org.apache.hadoop.util.Shell.run(Shell.java:418)
    at org.apache.hadoop.util.Shell$ShellCommandExecutor.execute(Shell.java:650)
    at org.apache.hadoop.util.Shell.execCommand(Shell.java:739)
    at org.apache.hadoop.util.Shell.execCommand(Shell.java:722)
    at org.apache.hadoop.fs.RawLocalFileSystem.setPermission(RawLocalFileSystem.java:633)
    at org.apache.hadoop.fs.RawLocalFileSystem.mkdirs(RawLocalFileSystem.java:421)
    at org.apache.hadoop.fs.FilterFileSystem.mkdirs(FilterFileSystem.java:281)
    at org.apache.hadoop.mapreduce.JobSubmissionFiles.getStagingDir(JobSubmissionFiles.java:125)
    at org.apache.hadoop.mapreduce.JobSubmitter.submitJobInternal(JobSubmitter.java:348)
    at org.apache.hadoop.mapreduce.Job$10.run(Job.java:1285)
    at org.apache.hadoop.mapreduce.Job$10.run(Job.java:1282)
    at java.security.AccessController.doPrivileged(Native Method)
    at javax.security.auth.Subject.doAs(Subject.java:422)
    at org.apache.hadoop.security.UserGroupInformation.doAs(UserGroupInformation.java:1548)
    at org.apache.hadoop.mapreduce.Job.submit(Job.java:1282)
    at org.apache.hadoop.mapred.JobClient$1.run(JobClient.java:562)
    at org.apache.hadoop.mapred.JobClient$1.run(JobClient.java:557)
    at java.security.AccessController.doPrivileged(Native Method)
    at javax.security.auth.Subject.doAs(Subject.java:422)
    at org.apache.hadoop.security.UserGroupInformation.doAs(UserGroupInformation.java:1548)
    at org.apache.hadoop.mapred.JobClient.submitJobInternal(JobClient.java:557)
    at org.apache.hadoop.mapred.JobClient.submitJob(JobClient.java:548)
    at org.apache.hadoop.mapred.JobClient.runJob(JobClient.java:833)
    at org.apache.nutch.crawl.Injector.inject(Injector.java:323)
    at org.apache.nutch.crawl.Injector.run(Injector.java:379)
    at org.apache.hadoop.util.ToolRunner.run(ToolRunner.java:70)
    at org.apache.nutch.crawl.Injector.main(Injector.java:369)
Error running:
/home/apache-nutch-1.11/bin/nutch inject /TestCrawl/crawldb /urls
Failed with exit value 127.

A: I can see there are multiple problems with your command, try this:
bin/crawl -i -Dsolr.server.url=http://127.0.0.1:8983/solr/core_name path_to_seed crawl 2

The first problem is that there is a space when you pass the solr parameter. The second problem is that the solr url should include the core name as well.

A:
hadoop-core jar file is needed when you are working with nutch

*

*with nutch 1.11 compatible hadoop-core jar is 0.20.0

*
please download jar from this link :
  http://www.java2s.com/Code/Jar/h/Downloadhadoop0200corejar.htm

*
paste that jar into "C:\cygwin64\home\apache-nutch-1.11\lib" folder and it will run
  successfully.


text:
Q: Objective-c: asl_log alternatives I'm trying to implement GTMLogger
But I'm getting deprecated API in the following lines:
client_ = asl_open(NULL, [facility UTF8String], 0);
if (client_ != NULL) asl_close(client_);
asl_log(client_, NULL, level, "%s", [msg UTF8String]);

All the regarding asl. Any of you knows and asl or how to get to work GTMLogger ?
I'll really appreciate your help.


text:
Q: MySQL issues when setting up a VM with Vagrant/chef-solo on OS X I've installed VirtualBox, Vagrant and chef-solo on my MBP laptop running Mountain Lion. I've downloaded recipes from opscode and have 'vagrant up' working. The VM is successfully create and I get a mostly working LAMP stack.
Where I am stuck is creating a database and user to access the database.
What I've done:
Created a development folder that includes Vagrantfile and the directory cookbooks. In cookbooks I have
README.md
apache2
apt
aws
build-essential
database
hnnapp
mysql
openssl
php
postgresql
xfs
xml

'hnnapp' contains my own recipe to launch my virtual machine. I used knife to initialize the folder and then edited metadata.rb to include
depends "apt"
depends "apache2"
depends "database"
depends "mysql"
depends "xml"
depends "openssl"
depends "php"
depends "build-essential"

and in recipes/default.rb I have include
include_recipe "apt"
include_recipe "apache2"
include_recipe "xml"
include_recipe "openssl"
include_recipe "database::mysql"
include_recipe "mysql"
include_recipe "mysql::client"
include_recipe "mysql::server"
include_recipe "mysql::ruby"
include_recipe "php"
include_recipe "php::module_mysql"
include_recipe "apache2::mod_php5"
include_recipe "apache2::mod_rewrite"

apache_site "default" do
    enable true
end

mysql_database node['hnnapp']['database'] do
    connection  ({:host => 'localhost', :username => 'root', :password => node['mysql']['server_root_password']})
    action :create
end

mysql_database_user node['hnnapp']['db_username'] do
    connection  ({:host => 'localhost', :username => 'root', :password => node['mysql']['server_root_password']})
    password node['hnnapp']['db_password']
    database_name node['hnnapp']['database']
    privileges [:select, :update, :insert, :cretae, :delete]
    action :create
end

Finally, my Vagrantfile includes
config.vm.provision :chef_solo do |chef|
    chef.add_recipe "hnnapp"
    chef.json = {
      "hnnapp" => {
        "db_password" => "test",
        "db_username" => "testuser",
        "database" => 'testdatabase'
      },
      "mysql" => {
        "server_root_password" => "098f6bcd4621d373cade4e832627b4f6",
        "server_debian_password" => "098f6bcd4621d373cade4e832627b4f6",
        "server_repl_password" => "098f6bcd4621d373cade4e832627b4f6"
      }
    }
  end

When I 'vagrant ssh' into the VM I see apache, php and mysql is installed. MySQL has no other databases except for test and information schema. I can use 'mysql' to get into mysql client, but I have no privileges to create any databases or users. sudo mysql doesn't work either.
I'd like to find out two things:

*

*Am I going about this the right way? Putting the right commands in the right files?

*What mistakes do I have in my scripts.

A: Does it make any difference if you add :grant to your actions in the mysql_database_user block?
action [:create, :grant]
I found this tutorial quite helpful with provisioning mysql with a user and privileges, although I am still a bit confused with the directory structure of chef-solo.
http://misheska.com/blog/2013/06/23/getting-started-writing-chef-cookbooks-the-berkshelf-way-part2/


text:
Q: SetCancelable and Back Button (android) I have an app and When the user presses BACK Button, it shows dialog, the dialog cannot be cancelled so I set it setCancelable(false)
but I want to dismiss the dialog when the user presses BACK button Again.
(
if the user presses Back Button, Show dialog.
if the user presses Back Button again , dismiss dialog
)
My Code below
private boolean dialogshown = false;
private AlertDialog d;
public boolean onKeyDown(int keycode, KeyEvent e) {
  if(keycode == KeyEvent.KEYCODE_BACK)
    if(!dialogshown) {
        d = new AlertDialog.Builder(MainActivity.this).create();
        d.setButton(AlertDialog.BUTTON_POSITIVE, "Cancel",
                new DialogInterface.OnClickListener() {
                    public void onClick(DialogInterface dialog, int which) {
                        dialog.dismiss();
                        dialogshown = false;
                    }
                });
        d.setButton(AlertDialog.BUTTON_NEGATIVE, "Exit",
                new DialogInterface.OnClickListener() {
                    public void onClick(DialogInterface dialog, int which) {
                        finish();
                        System.exit(0);
                    }
                });
        d.setCancelable(false);
        d.show();
        dialogshown = true;
    } else {
        try{ d.dismiss(); }catch (Exception exc){Toast.makeText(this,"Error back",Toast.LENGTH_LONG).show();}
    }
return super.onKeyDown(keycode, e);
}

The problem is when I press Back button it shows a dialog, but when I press it again Nothing Happens

A: Try this code :
AlertDialog alertDialog;
     public void onBackPressed() {
            if(alertDialog == null || !alertDialog.isShowing()){
                alertDialog = = new AlertDialog.Builder(context)
                .setTitle("Delete entry")
                .setMessage("Are you sure you want to delete this entry?")
                .setPositiveButton(android.R.string.yes, new DialogInterface.OnClickListener() {
                    public void onClick(DialogInterface dialog, int which) {
                        // continue with delete
                    }
                })
                .setNegativeButton(android.R.string.no, new DialogInterface.OnClickListener() {
                    public void onClick(DialogInterface dialog, int which) {
                        // do nothing
                    }
                })
                .setIcon(android.R.drawable.ic_dialog_alert)
                .show();
            }else{
                alertDialog.cancel();
            }
}

No need to maintain any extra variable to do this.
Hope it will help you :)

A: Put a boolean for dialog is open or not.
isDialogOpen = false

And override the backpress. When user pressed this method will called.
    @Override
    public void onBackPressed() {
    if(isDialogOpen==false){
                d.show();
                 isDialogOpen == true;
            }
            else {
                isDialogOpen == false;
                d.dismiss();
                finish();
            }
     }

I hope this will solve your problem.
edit: thanks akyirem samuel


text:
Q: Get text between `` and `` into an ArrayList I need to get some specific text out of a string and get that into an arraylist, but I have no idea where to start.
The string looks like this:
String exampleString = "some text I don't know
the text I want to get

Some more text I want to get
 some text I don't know"

But the problem is that I don't know how many text sections there are with
 text
 it's even possible that there aren't any of those sections at all.
So could anyone tell me how to get the texts between those
 and
 and how to get those into an arraylist.
Thank you so much!
UPDATE: What I do know about the text from which I said "some text I don't know" is that it doesn't contain
 or

A: Assuming there's no embedded tags you can do something like this:
private List<String> getText(String text){

    List<String> result = new ArrayList<String>();

    String[] sections = text.split("
");
    int i = 0;
    for (String s : sections) {
        i = s.indexOf("
");
        if (i >= 0)
           results.add(s.substring(0, i));
    }
    return result;
}

Example of code running when
say:
text = "test text here
 item one
 and then another item
 item 2
 and then some stuff."

So the first thing to explain is:
String[] sections = text.split("<pre");

This defines a new array of strings and assigns it to the result of a call to the String split function of "text"
This function breaks the string up in to sections delimited by "
" so you get:
sections[0] = "test text here"
sections[1] = "item one
 and then another item"
sections[2] = "item 2
 and then some stuff."

so as you can see from that all we now need to do is remove anything after "
" which is where the next bit comes in:
for (String s : sections)

Is the start of a "for each" loop that assigns the String s to each element of the array sections in turn.
So for each of the 3 strings above we do this:
 i = s.indexOf("
");
    if (i >= 0)
       results.add(s.substring(0, i));

So if the string contains
 then take a substring from the begining up until the "
" and add it to our results. Since sections[1] and sections[2] so contain it they will end up in the results.
I hope this helps?

Here's how i'd implement JavaJugglers solution to avoid using while (true):
private List<String> getText(String text){
    List<String> result = new ArrayList<String>();

    int indexStart = text.indexOf("
");
    int indexEnd = text.indexOf("
");
    while (indexStart >= 0 && indexEnd > indexStart) {
        result.add(text.substring(indexStart + 5, indexEnd));
        text = text.substring(indexEnd + 6);
        indexStart = text.indexOf("
");
        indexEnd = text.indexOf("
");
    }

    return result;
}

A: try {
    Pattern pattern = Pattern.compile("
(.+?)
");
    Matcher matcher = pattern.matcher(yourText);

    while (matcher.find()) {
        //  matcher.group() will contain the match from the previous find() statement
    }
}
catch(Exception ex){}

edited: corrected regex syntax

A: If you know for sure the HTML will be well-formed, you can start by using simple String methods:
String foo = "some text I don't know
the text I want to get

Some more text I want to get
 some text I don't know";
int preStart = foo.indexOf("
");
int preEnd = foo.indexOf("
", preStart);

if (preStart > -1 && preEnd > preStart)
{
    String inBetweenTags = foo.substring(preStart + 5, preEnd);
    System.out.println(inBetweenTags);
}

http://ideone.com/OkE9B
Otherwise use an HTML parser.

A: Here goes a simple solution:
private List<String> getText(String text){

    List<String> result = new ArrayList<String>();

    while(true){
        int indexStart = text.indexOf("
");
        int indexEnd = text.indexOf("
");
        if(indexStart >= 0 && indexEnd >= 0 && indexEnd > indexStart){
            result.add(text.substring(indexStart + 5, indexEnd));
            text = text.substring(indexEnd + 6);
        }
        else{
            break;
        }

    }
    return result;
}

Please keep in mind that you could change this function to be more generic, like passing the String to search as a parameter and calculate the substring offsets dynamically. I don't recommend you to use regular expressions because you may have Strings like:

text
more text
some more text

with nested "pre" tags.


text:
Q: Zend Framework - DbAdapter Issue I am adapting my Zend Framework to work with phpass as according to: http://jonathanstreet.com/blog/adding-phpass-to-zend-framework/
Following his steps, i encountered this error with his Acai_Auth_Adapter_DbTable:
Exception information:

Message: No entry is registered for key 'DbAdapter'

How do i resolve this? Many thanks.

A: You have to define the database adapter, which the class Acai_Auth_Adapter_DbTable should use by storing a database adapter in Zend_Registry with the key DbAdapter. The best place to do that is your Bootstrap.php:
protected function _initDb()
{
  // add code to create a `Zend_Db_Adapter_xxx`
  Zend_Registry::set('DbAdapter') = $dbAdapter;
}

How to set up the database adapter you find under Zend Framework: Documentation: Zend_Db_Adapter.
Another way is to pass the database adapter as parameter:
// create a database adapter
$authAdapter = new Acai_Auth_Adapter_DbTable( $dbAdpater ):

I would recommend the first way, because then you can access your database adapter anywhere in your application with Zend_Registry::get('DbAdapter').

A: assuming your database adapter is setup in your application.ini similar to:
resources.db.adapter = "pdo_Mysql"
resources.db.params.username = "music"
resources.db.params.password = "music"
resources.db.params.dbname = "music"
resources.db.isDefaultTableAdapter = true // add this line to make this adapter default, important if using more then one adapter.

in your bootstrap.php you can create a new method similar to:
 protected function _initDbAdapter() {//can be named anything as long as it starts with _init
        $db = new Zend_Config($this->getOptions('db'));//get all db adapter resources
        Zend_Registry::set('DbAdapter', $db); //save to Zend_registry key DbAdapter
    }

ByteNudger is correct on how use the registry:
$authAdapter = new Acai_Auth_Adapter_DbTable( $dbAdpater );
However there is a way to avoid all this bootstrap business. If you are only using one database adapter try:
//This will pass in the currently default adapter, if you only have one adapter...
$authAdapter = new Acai_Auth_Adapter_DbTable(Zend_Db::getDefaultAdapter);

Hope this helps.


text:
Q: Direction: rtl, Date alignment issue When I use direction:rtl for the Arabic view, the details on the date are not in showing incorrect order.
E.g. in ltr it's showing like 03 February 2016 but in rtl it's wrongly aligned as February 2016 03.

div {
  font-size: 20px;
}

  03 February 2016

Is there any way to rectify it. Or it's just the natural way of showing date in the Arabic view?

A: Answering your next question:

    03 February 2016

A: You can change this behavior by adding Unicode Character 'LEFT-TO-RIGHT EMBEDDING' (U+202A) and ending it by POP.

03 February 2016

A: 03 February 2016 solution works good for chrome. But it changes the output as 'mm ddyyyy' in firefox and IE.
Following works consistently in chrome, firefox and IE.

    15 May 2017

If you are working with angular js and want to apply the solution in date formatter then, you can write as below:

   {{ 1463725737789 | date: 'dd MMM yyyy'}}

Input in angular expression should be valid javascript date object. Given input '1463725737789' is time in milliseconds.

A: this is common, if you use direction RTl you can view mirror image of text, so if you use arabic data it shows perfect.

A: You can also use the dir attribute to assign rtl directionality. It makes your code much cleaner and easy to read.

div[dir='rtl'] {
  float: left;
}

/*Only supported in Firefox*/
:dir(rtl) {
  float: left;
}

  15 January 2020


text:
Q: How to get nearest DateTime from 2 tables
In SQLite, I want to build a query to get the nearest datetime for 'tag' entries against a 'tick' list:
CREATE TABLE Tick    (
     id integer primary key,
     dt varchar(20)
    );

INSERT INTO Tick (id, dt) VALUES
( 1, '2018-10-30 13:00:00'),
( 2, '2018-10-30 14:00:00'),
( 3, '2018-10-30 15:00:00'),
( 4, '2018-10-30 16:00:00'),
( 5, '2018-10-30 17:00:00'),
( 6, '2018-10-30 18:00:00'),
( 7, '2018-10-30 19:00:00'),
( 8, '2018-10-31 05:00:00'),
( 9, '2018-10-31 06:00:00'),
(10, '2018-10-31 07:00:00');

CREATE TABLE Tag    (
     id integer primary key,
     dt varchar(20)
    );

INSERT INTO Tag (id, dt) VALUES
(100, '2018-10-30 16:08:00'),
(101, '2018-10-30 17:30:00'),
(102, '2018-10-30 19:12:00'),
(103, '2018-10-31 04:00:00'),
(104, '2018-10-31 13:00:00');

The following query gives me the good match (based on diff) but I'm unable to get Tick columns:
SELECT Tag.dt,
       (SELECT ABS(strftime('%s',Tick.dt) - strftime('%s',Tag.dt)) as diff
        FROM Tick
        ORDER BY diff ASC
        LIMIT 1
       ) as diff from Tag

I tried the following but I receive an error on Tag.dt in ORDER BY:
SELECT
     Tag.id, Tag.dt,
     Tick.id, Tick.dt,
     abs(strftime('%s',Tick.dt) - strftime('%s',Tag.dt)) as Diff FROM Tag   JOIN Tick   ON Tick.dt =    (SELECT Tick.dt
    FROM Tick
    ORDER BY abs(strftime('%s',Tick.dt) - strftime('%s',Tag.dt)) ASC
    limit 1)

The result I would like to have is something like:
TagID,DateTimeTag        ,TickID,DateTimeTick
    100,2018-10-30 16:08:00,     4,2018-10-30 16:00:00
    101,2018-10-30 17:30:00,     6,2018-10-30 18:00:00
    102,2018-10-30 19:12:00,     7,2018-10-30 19:00:00
    103,2018-10-31 04:00:00,     8,2018-10-31 05:00:00
    104,2018-10-31 13:00:00,    10,2018-10-31 07:00:00

Edited later...
Based on forpas's answer, I was able to derive something without using the ROW_COUNTER() keyword which I can't use in FME.  I also set a maximum delta time difference (10000 sec) to find a match:
SELECT t.TagId, t.Tagdt, t.TickId, t.Tickdt, MIN(t.Diff)
FROM
(
SELECT
     Tag.id as TagId, Tag.dt as Tagdt,
     Tick.id as TickId, Tick.dt as Tickdt,
     abs(strftime('%s',Tick.dt) - strftime('%s',Tag.dt)) as Diff
FROM Tag, Tick
WHERE Diff < 10000
) AS t
GROUP BY t.TagId

Thanks again!

A: Use ROW_NUMBER() window function:
SELECT t.tagID, t.tagDT, t.tickID, t.tickDT
FROM (
  SELECT t.*,
    ROW_NUMBER() OVER (PARTITION BY t.tagID, t.tagDT ORDER BY t.Diff) AS rn
  FROM (
    SELECT Tag.id tagID, Tag.dt tagDT, Tick.id tickID, Tick.dt tickDT,
      ABS(strftime('%s',Tick.dt) - strftime('%s',Tag.dt)) as Diff
    FROM Tag CROSS JOIN Tick
  ) AS t
) AS t
WHERE t.rn = 1

See the demo.
Rsults:
| tagID | tagDT               | tickID | tickDT              |
| ----- | ------------------- | ------ | ------------------- |
| 100   | 2018-10-30 16:08:00 | 4      | 2018-10-30 16:00:00 |
| 101   | 2018-10-30 17:30:00 | 5      | 2018-10-30 17:00:00 |
| 102   | 2018-10-30 19:12:00 | 7      | 2018-10-30 19:00:00 |
| 103   | 2018-10-31 04:00:00 | 8      | 2018-10-31 05:00:00 |
| 104   | 2018-10-31 13:00:00 | 10     | 2018-10-31 07:00:00 |

A: Create a temp_table query to get the differences of time stamps of the cross product of Tick and Tag tables and select the min value for each of the Tick table id s.
The two temp_table queries are identical.
Note that this query may not be efficient as it takes full cross product across the two tables
SELECT temp_table.tid, temp_table.tdt, temp_table.tiid, temp_table.tidt, temp_table.diff
FROM
(SELECT Tag.id AS tid, Tag.dt AS tdt, Tick.id AS tiid, Tick.dt AS tidt, abs(strftime('%s',Tick.dt) - strftime('%s',Tag.dt)) as diff
FROM tag, tick) temp_table

WHERE temp_table.diff =

(SELECT MIN(temp_table2.diff) FROM
    (SELECT Tag.id AS tid, Tag.dt AS tdt, Tick.id AS tiid, Tick.dt AS tidt, abs(strftime('%s',Tick.dt) - strftime('%s',Tag.dt)) as diff
    FROM tag, tick) temp_table2
    WHERE temp_table2.tid = temp_table.tid
)

group by temp_table.tid


text:
Q: Scaling horizontally I know next to nothing about having more than one server work together. Right now I've been playing around with the cloud servers offering from rackspace.
All the time when people talk about these types of "cloud" servers, they make it sound like it's so easy to scale. Now it is easy to scale vertically. But I'm talking horizontally. I know with cloud servers you can save the image of your server and spin up a new server with exactly the same image. How do you make use of having more than one server? How do you insure database integrity in you application? People make it sound so simple and like you can just add a couple here and take a couple there.
Also, with cloud servers you can scale from 256mb to around 16gb. At what point is it better to scale horizontally rather than vertically? I'd imagine there's one bottleneck would be the disk, and scaling horizontally would be better so you could have more disks. But maybe I'm wrong and you're supposed to scale vertically all the way and then horizontally?

A: You don't say anywhere the nature of your application, but I'll guess it's a database-backed website.
To get the easiest horizontal scalability, you need to develop with 'shared nothing' in mind.  That means that all the content and state of the app must either be static (icons, JS, HTML, templates, such), or external to your application (usually database, storage if you manage user files).
to get there, first separate in 'tiers': the backend storage, the middle (web app), the frontend (ideally just a load balancer)
If you get this right, you can add as much webapp servers as you want hitting the same database server.  Of course, after a point, the database will become the bottleneck.  A well-designed app should use a fast cache to avoid hitting the DB unless necessary.  memcached is great here, because you can add an instance to each webapp server while still holding a unified set of key/value pairs. That buys you a lot of scalability.


text:
Q: Prove that $f_n(x)=\frac{x}{n}$, $n=1,2,\ldots$ does not converge uniformly on $\mathbb{R}$
Prove that $f_n(x)=\frac{x}{n}$, $n=1,2,\ldots$ does not converge uniformly on
  $\mathbb{R}$.

It's clear this function converges pointwise to $0$ function. We have to show that there is $\epsilon>0$ such that for any $N\in \mathbb{N}$ there are $n>N$ and $x$ such that $|\frac{x}{n}|\ge \epsilon$. Choose $\epsilon=1$. However big $N$ is, we can choose $x>N+1$ so we have $|x|\ge n$ if $n=N+1$.
Is this correct?

A: Definition: We say a sequence of functions $\left\{ f_n \right\}$, $n = 1,2,3,\dots$ converges uniformly on a set $S$ to a function $f$ if for every $\epsilon > 0$ there is an integer $N$ such that $n \geq N$ implies $$|f_n - f| < \epsilon$$ for all $x \in S$.
Solution: As you point out, the sequence of functions $f_n = \displaystyle \frac{x}{n}$, $n=1,2,3,\dots$ converges pointwise to $0$ on $\mathbb{R}$. So we are trying to show that $f_n$ does not converge uniformly to $f = 0$ on $\mathbb{R}$.
You have the right idea for approaching the problem. According to the definition, to show that $\displaystyle f_n = \frac{x}{n}$ does not converge uniformly on $\mathbb{R}$, we must only find a single $\epsilon > 0$ for which the condition:
" there is an integer $N$ such that $n \geq N\implies |f_n - f| < \epsilon$ for all $x \in \mathbb{R}$ "
does not hold.
As you suggest, let us take $\epsilon = 1$ (note our choice of $\epsilon$ is arbitrary) and suppose that $f_n$ does converge uniformly. If $f_n$ converges uniformly, then by the definition, there is an integer $N$ such that $n \geq N$ implies $$\displaystyle \left| \frac{x}{n} \right| < 1$$ for all $x \in \mathbb{R}$. This would mean that, for example, $$\displaystyle \left| \frac{x}{N} \right| < 1$$ for any $x \in \mathbb{R}$. But this is a contradiction since for any $x \geq N$ $$ \displaystyle \left| \frac{x}{N} \right| \geq 1 $$
Therefore $f_n = \frac{x}{n}$ cannot be uniformly convergent on $\mathbb{R}$.
The most crucial part of the definition is the order in which we are allowed to fix $N$ and $x$. For pointwise convergence, the order is reversed: we fix $x$ and then we are allowed to find an $N$ which satisfies the $\epsilon$ condition. For uniform convergence however, the definition requires that we choose $N$ first and then that the $\epsilon$ condition holds for any $x$. This is another way of saying that the choice of $N$ must be "independent of $x$" for uniform convergence and this is precisely why the condition fails for $f_n = \displaystyle \frac{x}{n}$.

A: $f_n$ is an odd function. Let us prove that the sequence does not converge uniformly at $[0,+\infty)$.
$$\sup_{x\in\mathbb R^+}f_n(x)\ge f_n(n)=1$$
thus
$$\lim_{n\to+\infty}\sup_{\mathbb R^+}f_n\neq 0$$

A: Geometric idea: as $f_n\to 0$ pointwise, the uniform convergence will imply that for all $\epsilon > 0$ the graph of $f_n$ is contained in the band $\Bbb R\times(-\epsilon,\epsilon)$ for $n$ large enough. But this is false for all $\epsilon$ and all $n$ because the graph of $f_n$ is a straight line with slope $1/n\ne0$.
A drawing done with Desmos (https://www.desmos.com/calculator):


text:
Q: How to add custom column to magento cms page grid How is it possible to add custom colunm with data from another table to magento cms page grid?

A: There is UI component called Magento/Cms/view/adminhtml/ui_component/cms_page_listing.xml
You need to extend it in your custom module ({your namespace}/{your_module_name}/view/adminhtml/ui_component/cms_page_listing.xml)
Here is section about UI components http://devdocs.magento.com/guides/v2.0/ui-components/ui-component.html


text:
Q: Postgres Concate: Date + Timestamp + Integer of 7 How can I combine these two columns and add integer of 7 to it? In postgres.
Both columns are in the table a_event.
start_time is a timestamp without time zone data type.
start_date is a date data type.
so far I have:
SELECT start_time || start_date AS start_date_time
FROM a_event;

This works but it shows:
    2015-03-06 21:17:162015-02-06
How can I get it to simply show:
2015-03-06 13:17:16 with an added 7 days so: 2015-03-13 in the desired result.

A: The || operator concatenates two strings, so the 'start_time' and 'start_date' columns are converted to text and then concatenated to give the result you see.
You want to add 7 days to the starting date. That is simply:
SELECT start_date + 7 AS start_date_time
FROM a_event;

On a date data type the + operator adds a number of days.
If you want to keep the starting time information, the solution is slightly more complex:
SELECT start_time + interval '7 days' AS start_date_time
FROM a_event;

The timestamp data type records microseconds since 01-01-1970, so you have to explicitly indicate that you want to add an interval of 7 days (and not 7 microseconds).


text:
Q: Can't Access File In file:///android_asset I have a file myfile.vtpk in my application's "Assets" folder.
I'm trying to load this file file in my application using the following:
            Uri vtpkUri = new Uri("file:///android_asset/myfile.vtpk");
            ArcGISVectorTiledLayer vtpkLayer = new ArcGISVectorTiledLayer(vtpkUri);

            MyMapView.Map.OperationalLayers.Add(vtpkLayer);

I get no error, but the file is never loaded.
How can I access this file in Android?
Thanks!

A: Since a file in your Assets folder is compiled into your APK, there is no "Uri" for a file in your assets folder, or any file in your APK for that matter. If you need to be able to pass a Uri, you would want to copy the Asset to your Document or other folder for your app and then get the Uri.
First create a method to take an read stream and write write stream and write your asset to a file:
private void ReadWriteStream(Stream readStream, Stream writeStream)
{
    int Length = 256;
    Byte[] buffer = new Byte[Length];
    int bytesRead = readStream.Read(buffer, 0, Length);
    // write the required bytes
    while (bytesRead > 0)
    {
          writeStream.Write(buffer, 0, bytesRead);
           bytesRead = readStream.Read(buffer, 0, Length);
    }
    readStream.Close();
    writeStream.Close();
}

Then get the read stream from the asset:
AssetFileDescriptor afd = Assets.OpenFd("filenameinAssetsfolder.ext");
var readStream = afd.CreateOutputStream();

Then create the path for the file and the write stream:
// This will be your final file path
var pathToWriteFile =
    Path.Combine (System.Environment.GetFolderPath
    (System.Environment.SpecialFolder.Personal),
    "filenametowrite.ext");
FileStream writeStream =
    new FileStream(pathToWriteFile,
    FileMode.OpenOrCreate,
    FileAccess.Write);

And finally call the copy method created above:
ReadWriteStream(readStream, writeStream);

Now you should be able to access the file with the path in pathToWriteFile.
EDIT: As per the comment below, try the following instead of getting an AssetFileDescriptor first. Replace:
AssetFileDescriptor afd = Assets.OpenFd("filenameinAssetsfolder.ext");
var readStream = afd.CreateOutputStream();

with:
Stream readStream = Assets.Open("filenameinAssetsfolder.ext");


text:
Q: Program for Chocolatey package not have silent installation mode 1. Summary
I want to create Chocolatey package for The Wonderful Icon program, official download page. But I can not install this program in silent mode.
Yes, The Wonderful Icon — old program, but it perfectly work in my Windows 10.

2. Not helped
The Wonderful Icon — not my program, I don't know installer for it.

*

*I install and run Universal Silent Switch Finder program as recommend Chocolatey manual. Universal Silent Switch Finder show, that executable file of The Wonderful Icon is «Self-Extracting WinZip archive»:

I find in Stack Overflow answers that for Self-Extracting WinZip archive we can use /auto flag. But it not helped for me.

*I try to use different flags — /S, /s, -s, /VERYSILENT, -q, but I have not success.

3. Settings
My chocolateyinstall.ps1 file:
$ErrorActionPreference = 'Stop';

$packageName= 'The Wonderful Icon'
$toolsDir   = "$(Split-Path -parent $MyInvocation.MyCommand.Definition)"
$url        = 'http://www.thewonderfulicon.com/wondicon.exe'
$url64      = ''

$packageArgs = @{
  packageName   = $packageName
  unzipLocation = $toolsDir
  fileType      = 'exe'
  url           = $url
  url64bit      = $url64

  softwareName  = 'The Wonderful Icon*'

  checksum      = ''
  checksumType  = 'sha256'
  checksum64    = ''
  checksumType64= 'sha256'

  silentArgs   = '/auto'
}

Install-ChocolateyPackage @packageArgs

4. Questions

*

*May I install The Wonderful Icon in silent mode in Chocolatey?

*If no, may I add package in Chocolatey without silent installation mode?

Thanks.

A:

*Not helped
I find in Stack Overflow answers that for Self-Extracting WinZip archive we can use /auto flag. But it not helped for me.

This is what makes Windows installers so much like the wild west. It's not always easy to find the silent installation arguments. And it may not even exist.

*Questions

  May I install The Wonderful Icon in silent mode in Chocolatey?

Yes, you absolutely can have the program available in an unattended fashion with Chocolatey. There are multiple methods of working to get an unattended install, some are better than others.
From best to worst:

*

*Work with installer's silent arguments

*Find ways to set registry keys, files, or hidden tricks to ensure a program is silent on install, upgrade, and uninstall.

*Repackage the software installer as an MSI using a tool designed for this (requires distribution rights for a public repository like Chocolatey).

*Find the runtime binaries and use them instead (requires distribution
rights for any public repository like Chocolatey.org).

*Use something like AHK (AutoHotKey) or AutoIT to work around the programs inability to be silent. AHK/AutoIT should be considered a last resort when nothing else will work.

If you have distribution rights, then I might order it 1, 4, 3, 2, 5.

If no, may I add package in Chocolatey without silent installation mode?

If you are asking if you can add this to the community package repository, aka https://chocolatey.org/packages, then it is probably better to ask that question in the "Open Chat" window that you see in the bottom right hand corner of the site.


text:
Q: A word that means "apparently" but with less conviction? Example:

The circular window was apparently made to match the shape of the
  sun.

Here apparently expresses doubt, but with a certain level of conviction: that was the intent of the person who designed the window.  Is there a word similar to apparently but with less level of conviction? Almost as if the conclusion were a rough guess? Or something that the speaker made up?

A: Seemingly is what you're looking for.

Seemingly vs. apparently
Apparently:

*

*Is used when you have read or been told something, although you are not certain it is true.
  Apparently it's going to rain today.

*Is used when the situation is different than what you thought it was.
  You know I told you Alice's party was on the 13th? Well, I just saw her and it's apparently on the 14th. How do you like that?
Seemingly:

*

*Appearing to be something, especially when this is not true.
  He remains confident and seemingly untroubled by his recent problems.

*According to the facts that you know.
  The factory closure is seemingly inevitable.
(Quora)

A: It changes the sentence form, but suggests or implies.

The circular shape of the window suggests it was made to match the shape of the sun.

A: If some irony is acceptable, I like allegedly.

A: Supposedly:

used to show that you do not believe that something you have been told is true:
  Well, the tickets are supposedly in the mail. ( -- Cambridge Dictionaries Online)

A: Ostensibly:

"As appears or is stated to be true, though not necessarily so"

'Apparently' as defined in the OED:

"As far as one knows or can see"

...only implies the converse.
So in my mind 'ostensibly' has a larger measure of doubt.

A: Possibly
This might seem a strange fit, but it does convey less certainty and conviction.
"Apparently she's gone to the movies."
"Possibly she's gone to the movies."
"Apparently he stole it."
"Possibly he stole it."

A: I could go with presumably, which goes beyond "this may be what they were trying to do, but I don't know if they achieved it" to cast doubt even upon the inferred intent itself.

The circular window was presumably made to match the shape of the sun.

A: The choice depends on the level of skepticism or sarcasm you want to inject...
In order of preference I would offer:

*

*ostensibly

*putatively

*purportedly

*allegedly

A: The straightforward way to express this:

The circular window might have been made to match the shape of the sun.

Bonus: eliminates an adverb.

A: Likely  would indicate that the speaker is making a guess but is fairly certain about it.

A: I might use purportedly, were it for something recent, but if it concerned something 400 years old then: the window, according to legend, was made to fit the shape of the sun.

A: The circular window gave the illusion of being made to match the shape of the sun.

Definition of "illusion" from MW: a misleading image presented to the
vision; perception of something objectively existing in such a way as
to cause misinterpretation of its actual nature; something that looks
or seems different from what it is, something that is false or not
real but that seems to be true or real.
Example: Everyone knows that vertical stripes can be very slimming and give the illusion of height.

You may also replace illusion by "impression".

A: How about on the face of it?

The circular window, on the face of it, was made to match the shape of
  the sun.

A: I'll put forth the more rarely used supposably, which is the adverb form of supposable.

:  capable of being supposed :  conceivable
Merriam-Webster

It connotes less conviction because it sounds like a made-up word (arguably because it was implied to be made-up when used in the TV show Friends).


text:
Q: prolog,very simple dcg syntax I am trying to understand the basic syntax of prolog and dcg but it's really hard to get ahold of proper information on  the really basic stuff. Take a look at the code below, I basically just want to achieve something like this:
Output = te(a, st).

Code:
    test(te(X,Y)) --> [X], test2(Y).
    test2(st(_X)) --> [bonk].

    ?- test(Output, [a, bonk],[]).
    Output = te(a, st(_G6369)).

Simply what I want to do is to add the the word 'st' at the end, and the closest way I've managed is by doing this but unfortunately st is followed a bunch of nonsense, most likely because of the singleton _X. I simply want my Output to contain like: te(a, st).

A: If you want to accept input of the form [Term, bonk] and obtain te(Term,st) you should change test/2 to accept bonk a return st:
test(te(X,Y)) --> [X], test2(Y).
test2(st) --> [bonk].

?-  test(Output, [a, bonk],[]).
Output = te(a, st).

A: As you said, st is followed by "a bunch of nonsense" because of _X (basically, _G6369 is the internal 'name' of the variable and since the variable remains uninstantiated prolog displays it; try print(X), X=3, print(X).
Anyway, you can simply remove (_X) since you can have anything you want as an argument:
test(te(X,Y)) --> [X], test2(Y).
test2(st) --> [bonk].

Of course, if you don't actually have bonk's in your input and you simply want to add a st at the end you can simplify it even more:
test(te(X,st)) --> [X].

Or if you have bonk's:
test(te(X,st)) --> [X,bonk].

Finally, it is generally suggested to use phrase/3 or phrase/2 instead of adding the arguments manually.


text:
Q: why am I getting this error when compiling an mfc application? I have this code:
void CALLBACK CTestTimeUpDlg::MyTimerProc(
   HWND hWnd,      // handle of CWnd that called SetTimer
   UINT nMsg,      // WM_TIMER
   UINT_PTR nIDEvent,   // timer identification
   DWORD dwTime    // system time
)
{
    const int m_TimerValue=0;
    double timeValueSec=m_TimerValue/1000.0;
    CString valueString;
    valueString.Format(L"%3.3f",timeValueSec);
    m_TimerDisplayValue.SetWindowTextW(valueString);
}

void CTestTimeUpDlg::OnBnClickedButtonStart()
{
    m_TimerValue=0;
    m_Timer = SetTimer(1, 1, &CTestTimeUpDlg::MyTimerProc);

}

but when I compiled it, I am getting this error:
 'CWnd::SetTimer' : cannot convert parameter 3 from 'void (__stdcall CTestTimeUpDlg::* )(HWND,UINT,UINT_PTR,DWORD)' to 'void (__stdcall *)(HWND,UINT,UINT_PTR,DWORD)'

the code is similar to the code from Microsoft documentation:
http://msdn.microsoft.com/en-us/library/49313fdf.aspx

A: You should make CTestTimeUpDlg::MyTimerProc static. However, by doing this, you can't access instance members such as m_TimerDisplayValue.
You shouldn't use callback in this case. Set lpfnTimer NULL, as the first timer in the sample of the link. That way, the timer posts the message WM_TIMER, and you can handle it by your non-static member function.
ADD:
Seems the document (plus my words above) is lacking in explanation.
Do as followings to implement a handler of WM_TIMER.
Declare handler in your class declaration:
afx_msg void OnTimer(UINT_PTR nIDEvent);

In your cpp file, add message mapping:
BEGIN_MESSAGE_MAP(CTestTimeUpDlg, ...)
    ON_WM_TIMER()
END_MESSAGE_MAP()

and implementation:
void CTestTimeUpDlg::OnTimer(UINT_PTR nIDEvent)
{
    // your code here...
}


text:
Q: CSS float: left not working here Trying to get this image below:

But here's what I have instead:

I am using this code as follows:
HTML:

Exhibiting Opportunities

The Opportunity Finance Network Conference is a great place to connect with decision makers across the industry.  Reserve your booth space now—contact Katie Kirchner for more information.

Sponsorship Opportunities

Reserve your slot now to be a part of the CDFI industry's premier event!  The OFN Conference provides our partners with an unparalleled platform to connect with CDFIs, increase awareness of their organizations' work, and support and strengthen the practice of opportunity finance.

CSS:
.floatleft
{
    float: left;
}

.floatright
{
    float: right;
}

.sidespadding
{
    padding-left: 1.2em;
    padding-right: 1.2em;
}

.clear
{
    clear: both;
}

Can't get the text to float to the left of the actual image, like the image in the first pic.  OMG, what am I missing here?  Webpage here:  http://opportunityfinance.net/Test/2013conf/index.html

A: Get rid of your padding, your % is greater than 100% with padding.
Or you can apply box-sizing http://www.w3schools.com/cssref/css3_pr_box-sizing.asp
If you want space you can always add margin left or right but make sure your percentage calculates to 100% at the end
So
div 1 30% width with 5% margin right for example
div 2 65% width
So total = 100%
there are other ways to accomplish this but you get the idea now

A: Padding adds to the total width, making it 65% + 2.4em
If backward compatibility with older versions of IE is not an issue you can use CSS calc
Otherwise you have to wrap some div in order to create padding inside the element you want.


text:
Q: MKMapView MKTileOverlay - Determine currently visible tiles I'm trying to find a reliable method for determining the MKTileOverlayPath of the tiles currently visible in a MKMapView at any given instant (as the user zooms in/out and pans). My application displays dynamic content from a server which is queried by MKTileOverlayPath.
Is there a way to determine this directly from the MKMapView or MKTileOverlay classes?
So far I've been trying to calculate the tilepaths using the code below. It works OK when the user pans or double-clicks to zoom-in. However, when pinching to zoom in/out (where the zoom-level can be continuous) the tiles calculated using this method are sometimes not correct - specifically the y coordinates seem to be one off.
I'm struggling to figure out why the code doesn't work correctly with the pinch zoom levels so I'm wondering if there is an alternative way to determine the currently visible tiles. I've tried implementing a dummy MKTileOVerlay to intercept the requested tiles but this it's not clear from that which are currently in view at any given time.
Any tips would be greatly appreciated.
- (NSMutableArray *)tilesInMapRect:(MKMapRect)rect zoomScale:(MKZoomScale)scale
{

    NSInteger z = [self zoomLevel];

    NSInteger minX = floor((MKMapRectGetMinX(rect) * scale) / TILE_SIZE);
    NSInteger maxX = floor((MKMapRectGetMaxX(rect) * scale) / TILE_SIZE);
    NSInteger minY = floor((MKMapRectGetMinY(rect) * scale) / TILE_SIZE);
    NSInteger maxY = floor((MKMapRectGetMaxY(rect) * scale) / TILE_SIZE);

    NSMutableArray *tiles = nil;

    for (NSInteger x = minX; x <= maxX; x++) {
        for (NSInteger y = minY; y <= maxY; y++) {

            NSString *tileString = [NSString stringWithFormat:@"z%ix%iy%i",z,x,y];
            if (!tiles) {
                tiles = [NSMutableArray array];
            }
            [tiles addObject:tileString];
        }
    }

    return tiles;
}

- (NSUInteger) zoomLevel {
    return (21 - round(log2(self.mapView.region.span.longitudeDelta * MERCATOR_RADIUS * M_PI / (180.0 * self.mapView.bounds.size.width))));
}


text:
Q: Setting dropdownlist values from selected value I have a dropdownlist which contains some values such as "Hot water" and "Electricity" in C# ASP.Net. What I would like to do is if the user selects one of these values and clicks on a button, then it would set the values of a second dropdownlist to certain values. e.g. if "Hot Water" was chosen and next was clicked then the values in dropdownlist2 would be "Radiator" and "Heating controls". But if "Electricity" was chosen then the values in dropdownlist2 would be "No Power" and "Sockets". My code so far:
protected void NextButton1_Click(object sender, EventArgs e)
{
    option1 = DropDownList1.SelectedValue.ToString();
    TextBox1.Text = option1;
    DropDownList2.Visible = true;
    if (DropDownList1.SelectedValue == "Hot Water")
    {
        DropDownList2.SelectedValue = "Heating controls";
        DropDownList2.SelectedValue = "Underfloor Heating";
    }
}

A: I hope I understood you with the following:
if(DropDownList1.SelectedValue == "Hot Water"){
    DropDownList2.Items.Clear();
    DropDownList2.Items.Add("Radiator");
    DropDownList2.Items.Add("Heating Controls");
}
if(DropDownList1.SelectedValue == "Electricity"){
    // Do the same like above but for the values in Electricity
}

A: First check whether the Hot Water or Electricity is selected in the dropdownlist1 in Nextclick button code like this.
if(dropdownlist1.SelectedValue == "Hot Water")
{
    drodownlist2.Items.Add(new ListItem("Radiator","Radiator")); //First parameter take datatextfield and second parameter take datavaluefield.
    drodownlist2.Items.Add(new ListItem("Heating Controls","Heating Controls"));
}
else
{
    drodownlist2.Items.Add(new ListItem("No Power","No Power"));
    drodownlist2.Items.Add(new ListItem ("Sockets","Sockets"));
}

A: Don't think you can multi-select in a dropdown list so use a asp:ListControl or asp:CheckBoxList instead.
If you want a dropdown multiselect there are plenty of JS controls that will do that for you.
eg: https://harvesthq.github.io/chosen/
Once you update your code for a list than everything should work fine.


text:
Q: update listview in android as Adapter is defined in separate class As I have gone through number of questions to how can I refresh my listview in my app but still not able to get how to do it.
Number of suggestion given in Posts that I can use mylist.NotifydataSetCahnged() but I still couldn't able to resolve where to apply it. As my adapter is defined in the separate activity.
I have a textview and a plus button on each row of the List item.
On clicking plus button, I want it that without refreshing whole activity it asynchronously update the value in respective textview. And the plus button click event is declared in my baseadapter class separately.
I don't know how to update my listview as I'm calling intent on each click of plus button to refresh my listview.
Do help me out.
public class MyOrderList extends Activity {

    public Cursor food_items = null;
    private String item_name;
    private String item_descrp;
    private String item_price;
    private ArrayList<ItemDetails> image_details;

    private String item_id;
    private Cursor order_item;
    private Button order_btn;
    private Button cancel_btn;
    private SQLiteDatabase db;

    private AlertDialog mydialog;
    protected String table_no;
    protected String order_no;
    protected int quantity;
    protected int itemid;
    protected Cursor temp_item;
    public float Total = 0;
    private ListView lv1;
    public int bill_count = 100;
    private Cursor fav_item;
    private String table_name;
    private Calendar c;
    private TextView Title_txt;
    private String device_id;
    private String print_order_items = "";
    private String col_name;

    public static String APP_ID = "346381592110362"; // Replace your App ID

    public Facebook facebook;
    public AsyncFacebookRunner mAsyncRunner;
    String FILENAME = "AndroidSSO_data";
    public SharedPreferences mPrefs;
    private AlertDialog noItemalert;
    private Dialog checkOut;
    private Cursor mac;
    private String Main_table = "T1";

    /** Called when the activity is first created. */
    @Override
    public void onCreate(Bundle savedInstanceState) {
        super.onCreate(savedInstanceState);
        setContentView(R.layout.layout_myorder_view);
        db = openOrCreateDatabase("restaurant", MODE_WORLD_READABLE, null);
        c = Calendar.getInstance();

        // ----initilaizee facebook objects-
        facebook = new Facebook(APP_ID);

        mAsyncRunner = new AsyncFacebookRunner(facebook);
        SessionStore.restore(facebook, this);

        SessionEvents.addAuthListener(new SampleAuthListener());
        SessionEvents.addLogoutListener(new SampleLogoutListener());
        table_name = getIntent().getStringExtra("table_name");
        // WifiManager wifiManager = (WifiManager)
        // getSystemService(Context.WIFI_SERVICE);
        // WifiInfo wInfo = wifiManager.getConnectionInfo();
        // String macAddress = wInfo.getMacAddress();
        //
        // Log.d("IMEI no.", macAddress);
        // mac = db.rawQuery("select * from imei_tbl where imei_code='"
        // + macAddress + "'", null);
        // mac.moveToFirst();
        // if (mac != null)
        // Main_table = mac.getString(1);

        lv1 = (ListView) findViewById(R.id.myorder_lv);
        Title_txt = (TextView) findViewById(R.id.myorder_total);
        Title_txt.setText("Total :" + Total);

        order_btn = (Button) findViewById(R.id.myorder_btn);
        cancel_btn = (Button) findViewById(R.id.myorder_backbtn);

        cancel_btn.setOnClickListener(new View.OnClickListener() {

            @Override
            public void onClick(View v) {
                Intent intent = new Intent(MyOrderList.this,
                        FoodCategoryTabs.class);
                Bundle extras = new Bundle();
                extras.putString("category_id", "food_category");
                extras.putString("category_name", "food_category_id");
                intent.putExtras(extras);
                startActivity(intent);

            }
        });

        // ----------------on order click--------------
        order_btn.setOnClickListener(new View.OnClickListener() {

            @Override
            public void onClick(View v) {
                int flagx = 0;
                if (food_items.getCount() != 0)
                    showpopup();
                else
                    checkOutPopUp(flagx);

            }

        });

    }

    protected void showpopup() {
        final int flag = 1;

        mydialog = new AlertDialog.Builder(this)
                .setTitle("My Order Alert")
                .setMessage(
                        "Thank you Dear Customer, Your Order will processed soon Would you like to proceed further...")
                .setPositiveButton("Ok", new AlertDialog.OnClickListener() {

                    public void onClick(DialogInterface dialog, int which) {

                        continueFunction();
                        checkOutPopUp(flag);
                    }
                })
                .setNeutralButton("Discard", new AlertDialog.OnClickListener() {
                    public void onClick(DialogInterface dialog, int which) {
                        mydialog.dismiss();

                    }
                })

                .create();
        mydialog.show();
    }

    protected void checkOutPopUp(final int flag_value) {
        checkOut = new AlertDialog.Builder(MyOrderList.this)
                .setTitle("CheckOut Alert !")
                .setMessage(
                        "Would you like to continue to add items or checkout..")
                .setPositiveButton("Continue",
                        new AlertDialog.OnClickListener() {

                            public void onClick(DialogInterface dialog,
                                    int which) {

                                Intent intent = new Intent(MyOrderList.this,
                                        FoodCategoryTabs.class);
                                Bundle extras = new Bundle();
                                extras.putString("category_id", "food_category");
                                extras.putString("category_name",
                                        "food_category_id");
                                intent.putExtras(extras);
                                startActivity(intent);

                            }

                        })
                .setNegativeButton("Checkout",
                        new AlertDialog.OnClickListener() {
                            public void onClick(DialogInterface dialog,
                                    int which) {
                                if (flag_value != 0) {
                                    Toast.makeText(getApplicationContext(),
                                            "checkout click", Toast.LENGTH_LONG)
                                            .show();
                                    DBConnection dbConnection = new DBConnection(

                                    getApplicationContext());
                                    try {

                                        dbConnection.createSocket();
                                        dbConnection.dataOutputStream
                                                .writeUTF("3");
                                    } catch (Exception e) {

                                    }

                                    db.delete(table_name, "order_id=100", null);

                                    Cursor fav_cursor = db.rawQuery(
                                            "select * from temp_favourite_tbl",
                                            null);
                                    fav_cursor.moveToFirst();
                                    int length = fav_cursor.getCount();
                                    try {
                                        dbConnection.dataOutputStream
                                                .write(length);
                                    } catch (IOException e1) {
                                        // TODO Auto-generated catch block
                                        e1.printStackTrace();
                                    }

                                    if (fav_cursor != null) {
                                        do {
                                            try {
                                                String query = "insert into favourite_tbl values('";
                                                query = query
                                                        + fav_cursor
                                                                .getString(0)
                                                        + "','"
                                                        + fav_cursor
                                                                .getString(1)
                                                        + "')";
                                                dbConnection.dataOutputStream
                                                        .writeUTF(query);
                                            } catch (Exception e) {

                                            }

                                        } while (fav_cursor.moveToNext());
                                    }
                                    db.execSQL("DROP TABLE IF EXISTS temp_favourite_tbl");
                                    db.execSQL("create table if not exists temp_favourite_tbl(item_id varchar2,user_id varchar2,primary key(item_id))");
                                }
                                if (HeaderFooterActivity.facebook != null) {
                                    if (HeaderFooterActivity.facebook
                                            .isSessionValid()) {
                                        ContentValues cv = new ContentValues();
                                        cv.put("login_txt", "Login");
                                        cv.put("username", "");
                                        cv.put("user_id", "");
                                        db.update("login_tbl", cv, null, null);

                                        HeaderFooterActivity.mAsyncRunner
                                                .logout(getApplicationContext(),
                                                        new LogoutRequestListener());

                                    }
                                } else {

                                    Log.d("logout me exeption", "");
                                }

                                Intent intent = new Intent(MyOrderList.this,
                                        GridViewMenu.class);

                                startActivity(intent);

                            }
                        })

                .create();
        checkOut.show();

    }

    @Override
    protected void onResume() {
        // TODO Auto-generated method stub
        super.onResume();
        table_name = getIntent().getStringExtra("table_name");
        getFoodItems(table_name);
        // calculateOrder();
        final ListView lv1 = (ListView) findViewById(R.id.myorder_lv);
        MyOrderAdapter ad = new MyOrderAdapter(this, image_details, table_name);
        ad.notifyDataSetChanged();
        lv1.setAdapter(ad);
    }

    public void continueFunction() {
        try {
            Cursor customer_order = db.rawQuery(
                    "select bill_no from auto_bill", null);
            customer_order.moveToFirst();

            String bill_no = Main_table + customer_order.getCount();
            DBConnection dbConnection = new DBConnection(
                    getApplicationContext());
            dbConnection.createSocket();

            dbConnection.dataOutputStream.writeUTF("2");

            dbConnection.dataOutputStream
                    .writeUTF("insert into auto_bill(bill_no) values('"
                            + bill_no + "')");
            db.execSQL("insert into auto_bill(bill_no) values('" + bill_no
                    + "')");

            System.out.println("passed");

            dbConnection.dataOutputStream
                    .writeUTF("insert into CUSTOMER_BILL(table_no,bill_no,status,price,day,month,year) values('"
                            + Main_table
                            + "','"
                            + bill_no
                            + "','UNPAID',"
                            + Total
                            + ",'"
                            + c.get(Calendar.DAY_OF_MONTH)
                            + "','"
                            + (c.get(Calendar.MONTH) + 1)
                            + "','"
                            + c.get(Calendar.YEAR) + "')");
            Log.d("Month", "" + c.get(Calendar.MONTH));
            ArrayList<String> specialReq = new ArrayList<String>();
            ArrayList<String> quantityList = new ArrayList<String>();
            ArrayList<String> itemNameList = new ArrayList<String>();
            String tempItemId = null;
            Cursor cursor_order = db
                    .rawQuery(
                            "select item.Item_name, order_tbl.special_request,order_tbl.quantity from item, order_tbl where order_tbl.item_id=item.item_code",
                            null);
            cursor_order.moveToFirst();
            if (cursor_order != null) {
                do {

                    itemNameList.add(cursor_order.getString(0));
                    quantityList.add(cursor_order.getInt(2) + "");

                    specialReq.add(cursor_order.getString(1));
                } while (cursor_order.moveToNext());
                dbConnection.dataOutputStream.write(itemNameList.size());
                for (int l = 0; l < itemNameList.size(); l++) {
                    dbConnection.dataOutputStream.writeUTF(Main_table);
                    dbConnection.dataOutputStream.writeUTF(itemNameList.get(l));
                    dbConnection.dataOutputStream.writeUTF(specialReq.get(l));
                    dbConnection.dataOutputStream.writeUTF(quantityList.get(l));
                }
            }

        } catch (Exception e) {
            // TODO Auto-generated catch block
            e.printStackTrace();
            Log.d("EDC", "" + e);
        }

        db.delete(table_name, col_name + " = '" + order_no + "'", null);

    }

    public void getFoodItems(String tableName) {

        food_items = db.rawQuery("select * from " + tableName, null);
        food_items.moveToFirst();
        image_details = getFavResults();
        if (food_items.getCount() != 0) {
            Log.d("count khali nahi h", "bilkl nai h");

            calculateOrder();

        }

    }

    public void calculateOrder() {
        Cursor order;

        Cursor customer_order;
        String bill_no;

        int count;
        Cursor favourite_cursor;

        try {
            DBConnection dbcon = new DBConnection(getApplicationContext());
            db = dbcon.getConnection();
            food_items.moveToFirst();

            col_name = food_items.getColumnName(0);
            Log.d("----------------col_name", col_name);

            if (food_items != null) {
                food_items.moveToFirst();
                Log.d("----------------col_name", "" + food_items.getCount());
                order_no = food_items.getString(0);

                do {
                    order = db.rawQuery(
                            "select item_price,item_name from item where item_code='"
                                    + food_items.getString(1) + "'", null);
                    order.moveToFirst();
                    quantity = food_items.getInt(3);
                    Total += quantity * order.getInt(0);
                    Title_txt.setText("Total :" + Total);
                    Log.d("-------to", "" + Total);
                } while (food_items.moveToNext());
            }

        } catch (Exception e) {
            Log.d("dialog error", e.toString());
        }

    }

    private ArrayList<ItemDetails> getFavResults() {
        ArrayList<ItemDetails> results = new ArrayList<ItemDetails>();

        try {
            if (food_items != null) {
                Log.d("order_tbl ID", "" + food_items.getString(1));
                do {
                    fav_item = db.rawQuery(
                            "select * from item where item_code='"
                                    + food_items.getString(1) + "'", null);
                    fav_item.moveToFirst();
                    item_id = fav_item.getString(1);
                    item_name = fav_item.getString(0);
                    item_descrp = fav_item.getString(2);
                    item_price = fav_item.getString(17);
                    ItemDetails item_details = new ItemDetails();
                    item_details.setName(item_name);
                    item_details.setItem_id(item_id);
                    item_details.setItemDescription(item_descrp);
                    item_details.setPrice(item_price);
                    item_details.setImage(fav_item.getBlob(10));
                    item_details.setcount(food_items.getInt(3));
                    results.add(item_details);
                } while (food_items.moveToNext());

            }
        } catch (Exception e) {
            Log.d("Coooooool Errorrrrrrrrrrrr", e.toString());
        }
        db.close();
        return results;
    }

//-----and myOrderAdapter class----------------------------

public class MyOrderAdapter extends BaseAdapter {

    @Override
    public void notifyDataSetChanged() {
        // TODO Auto-generated method stub
        super.notifyDataSetChanged();
    }

    private static ArrayList<ItemDetails> itemDetailsrrayList;

    private Integer[] imgid = { R.drawable.coffee, R.drawable.coffee,
            R.drawable.coffee, R.drawable.coffee, R.drawable.coffee,
            R.drawable.coffee };

    private LayoutInflater l_Inflater;

    private Context context;

    private String table_name;

    public MyOrderAdapter(Context context, ArrayList<ItemDetails> results,
            String table_name) {
        itemDetailsrrayList = results;
        l_Inflater = LayoutInflater.from(context);
        this.context = context;
        this.table_name = table_name;

    }

    public int getCount() {
        return itemDetailsrrayList.size();
    }

    public Object getItem(int position) {
        return itemDetailsrrayList.get(position);
    }

    public long getItemId(int position) {
        return position;
    }

    public View getView(int position, View convertView, ViewGroup parent) {
        ViewHolder holder = new ViewHolder();
        if (convertView == null) {
            convertView = l_Inflater.inflate(R.layout.layout_myorder, parent,
                    false);

            holder.txt_itemName = (TextView) convertView
                    .findViewById(R.id.myorder_titletag);

            holder.txt_itemPrice = (TextView) convertView
                    .findViewById(R.id.myorder_price);
            holder.txt_itemQuantity = (TextView) convertView
                    .findViewById(R.id.myorder_quantity);
            holder.itemImage = (ImageView) convertView
                    .findViewById(R.id.myorder_food_img);
            holder.plusBtn = (ImageButton) convertView
                    .findViewById(R.id.myorder_plus_btn);
            holder.minusBtn = (ImageButton) convertView
                    .findViewById(R.id.myorder_minus_btn);
            holder.removeBtn = (Button) convertView
                    .findViewById(R.id.myorder_remove_btn);
            holder.edittext = (TextView) convertView
                    .findViewById(R.id.myorder_edit_txt);

            holder.plusBtn.setOnClickListener(new View.OnClickListener() {

                private SQLiteDatabase db;
                private ItemDetails item_list;
                private ContentValues cv;
                int count = 1;

                @Override
                public void onClick(View v) {
                    item_list = itemDetailsrrayList.get((Integer) v.getTag());
                    count = item_list.getcount();
                    count++;

                    try {
                        DBConnection dbcon = new DBConnection(context);
                        db = dbcon.getConnection();
                        cv = new ContentValues();
                        cv.put("quantity", count);
                        db.update(table_name, cv,
                                "item_id='" + item_list.getItem_id() + "'",
                                null);
                        Intent intent = new Intent(context
                                .getApplicationContext(), MyOrderList.class);
                        intent.putExtra("table_name", table_name);
                        context.startActivity(intent);
                    } catch (Exception e) {
                        Log.d("Count", "" + e);
                    }

                }
            });

            holder.minusBtn.setOnClickListener(new View.OnClickListener() {

                private SQLiteDatabase db;
                private ItemDetails item_list;
                private ContentValues cv;
                int count;

                @Override
                public void onClick(View v) {

                    item_list = itemDetailsrrayList.get((Integer) v.getTag());
                    count = item_list.getcount();

                    if (count > 1)
                        count--;
                    else
                        count = 1;

                    try {
                        DBConnection dbcon = new DBConnection(context);
                        db = dbcon.getConnection();
                        cv = new ContentValues();
                        cv.put("quantity", count);
                        db.update(table_name, cv,
                                "item_id='" + item_list.getItem_id() + "'",
                                null);
                        Intent intent = new Intent(context
                                .getApplicationContext(), MyOrderList.class);
                        intent.putExtra("table_name", table_name);
                        context.startActivity(intent);

                    } catch (Exception e) {
                        Log.d("Count", "" + e);
                    }

                }
            });

            holder.removeBtn.setOnClickListener(new View.OnClickListener() {

                private SQLiteDatabase db;

                private ItemDetails item_list;
                private ContentValues cv;

                @Override
                public void onClick(View v) {

                    try {
                        item_list = itemDetailsrrayList.get((Integer) v
                                .getTag());

                        DBConnection dbcon = new DBConnection(context);
                        db = dbcon.getConnection();

                        db.delete(table_name,
                                "item_id='" + item_list.getItem_id() + "'",
                                null);
                        db.close();

                        Intent intent = new Intent(context
                                .getApplicationContext(), MyOrderList.class);
                        intent.putExtra("table_name", table_name);
                        context.startActivity(intent);

                    } catch (Exception e) {
                        Log.d("errorrrrrr", e.toString());
                    }

                }
            });

            convertView.setTag(holder);
        } else {
            holder = (ViewHolder) convertView.getTag();
        }

        holder.txt_itemName
                .setText(itemDetailsrrayList.get(position).getName());
        holder.txt_itemQuantity.setText("Quantity");

        holder.txt_itemPrice.setText("Rs :"
                + itemDetailsrrayList.get(position).getPrice());
        holder.itemImage.setImageBitmap(itemDetailsrrayList.get(position)
                .getImage());

        holder.edittext.setText(Integer.toString(itemDetailsrrayList.get(
                position).getcount()));

        holder.plusBtn.setTag(position);
        holder.minusBtn.setTag(position);

        holder.removeBtn.setText("Remove");
        holder.removeBtn.setTag(position);

        return convertView;
    }

    public class ViewHolder {

        public TextView edittext;
        public TextView txt_itemQuantity;
        public ImageButton minusBtn;
        public ImageButton plusBtn;
        public Button removeBtn;

        TextView txt_itemName;
        TextView txt_itemDescription;
        TextView txt_itemPrice;
        ImageView itemImage;

        public ViewHolder() {
            // TODO Auto-generated constructor stub
        }

    }
}

A: I have done that a few times defining my adapter in a separate class and refreshing it's data. Not sure if it's the right way, but at least it's working like a charm for me.
The thing which I am doing is that I clear all my ArrayList's which I am using to populate the list view, than add all the new items and set adapter.notifySetDataChanged(); to my adapter.
Here is a sample :
if I populate my list view like this in onCreate for example :
ArrayList<String> ids = new ArrayList<String>();
ids.add("one");
ids.add("two");
ids.add("three");

ListView lview = (ListView) findViewById(R.id.mylist);
CustomAdapter adapter = new CustomAdapter(ids);
lview.setAdapter(adapter);

and for example if I want to update my listview on button click ar any other event I simply do this :
   ids.clear();
   ids.add("four");
   ids.add("five");
   ids.add("six");

   adapter.notifySetDataChanged();

and voala! : )

A: whenever you want to update a listview or a gridview
you have to create a new adapter with an updated array.
listView.setAdapter(new adapter());
listView.invalidateViews();


text:
Q: jQuery plugin options when loaded via AJAX When loading a plugin via ajax I am unable to pass options to it. However, if I pass the options to the plugin when the plugin is included normally (along with the rest of the page rather than ajax) it works fine.
// Get the script
$.getScript('/js/gallery.min.js')
 .done(function() {

     // Initiate scroll plugin on load
     $('.section-gallery').smoothDivScroll({
         manualContinuousScrolling: true,
         autoScrollingMode: 'onStart'
     });
});

The plugin itself is working, but only gets the default value, not with the options I wish to pass with it.
The script I am loading uses the plugin Smooth Div Scroll
Update:
There is a link to a codepen of it here: http://cdpn.io/Hopgm However, it actually seems to work there :/ so maybe it's a localhost thing. Oddly, another plugin I'm loading seems to work, and this one works occasionally. I have tried adding a timeout, but that didn't work. @Dean.DePue - I'm not sure what you mean.


text:
Q: $d\pi(X)$ is skew-symmetric. What does it mean? This is from a lemma in Lang $SL_2$

If $\pi$ is a unitary representation of G, and $X \in \mathfrak g$, then $d\pi(X)$ is skew symmetric on $H_\pi^\infty$

What does skew symmetric mean here? And why does it follow straight from definition of the derived representation?
My understanding is that it should mean:
$$\langle d\pi(X)v,w\rangle = -\langle v,d\pi(X)w\rangle$$
where $v, w \in H_\pi^\infty$. But it is not obvious to me why this should follow from the definition of the derived representation as the Lie derivative, i.e. as $d/dt \pi(\exp(tX)v$ evaluated at zero.

A: If $X$ is in the Lie algebra, then you know that $$\langle \exp(tX)v,\exp(tX)w\rangle$$ is constant, that is, it does not depend on $t$. Differenttiate with respect to $t$, and evaluate at $t=0$.


text:
Q: Why does C# remove my second xml namespace attribute when building this XmlDocument? I have the code:
using System;
using System.Collections.Generic;
using System.Linq;
using System.Text;
using System.Threading.Tasks;
using System.Xml;

namespace XmlNameSpacingTesting
{
    class Program
    {
        static void Main(string[] args)
        {
            XmlDocument output = new XmlDocument();
            XmlNode baseNode = output.CreateElement("idat");
            XmlAttribute xmlnsAttribute = output.CreateAttribute("xmlns:xsi");
            xmlnsAttribute.Value = "http://www.w3.org/2001/XMLSchema-instance";
            baseNode.Attributes.Append(xmlnsAttribute);
            XmlAttribute xsiAttribute = output.CreateAttribute("xsi:noNamespaceSchemaLocation");
            xsiAttribute.Value = "C:\\sub.xsd";
            baseNode.Attributes.Append(xsiAttribute);
            output.AppendChild(baseNode);
            // DumbSubNode
            XmlNode firstNode = output.CreateElement("Sub-Node1");
            firstNode.InnerText = "Single Sub-Node";
            baseNode.AppendChild(firstNode);
            output.Save("Test.xml");
        }
    }
}

I would expect an output of:
<idat xmlns:xsi="http://www.w3.org/2001/XMLSchema-instance" xsi:noNamespaceSchemaLocation="C:\sub.xsd">
  <Sub-Node1>Single Sub-Node</Sub-Node1>
</idat>

But I get an output of:
<idat xmlns:xsi="http://www.w3.org/2001/XMLSchema-instance" noNamespaceSchemaLocation="C:\sub.xsd">
  <Sub-Node1>Single Sub-Node</Sub-Node1>
</idat>

On the XmlAttribute xsiAttribute it's taking away the "xsi:" and I don't know why. Any help?

A: Change your xsiAttribute to include the Schema namespace.
XmlAttribute xsiAttribute = output.CreateAttribute("xsi:noNamespaceSchemaLocation", "http://www.w3.org/2001/XMLSchema-instance");
xsiAttribute.Value = "C:\\sub.xsd";

This will produce the correct XML:
<idat xmlns:xsi="http://www.w3.org/2001/XMLSchema-instance" xsi:noNamespaceSchemaLocation="C:\sub.xsd">
   <Sub-Node1>Single Sub-Node</Sub-Node1>
</idat>

The xsi prefix attribute is defined in Namesapce http://www.w3.org/2001/XMLSchema-instance. If you don't specify the URI namespace then it will be considered as unidentified attribute for xsi and so the xsi was removed.
For more information see https://www.w3.org/TR/xmlschema-1/#xsi.noNamespaceSchemaLocation

A: had a quick scan read try this
  XmlAttribute xsiAttribute = output.CreateAttribute("xsi:" + "noNamespaceSchemaLocation");
and do let me know if it has work
cheers bud


text:
Q: How to look ahead one element (peek) in a Python generator? I can't figure out how to look ahead one element in a Python generator. As soon as I look it's gone.
Here is what I mean:
gen = iter([1,2,3])
next_value = gen.next()  # okay, I looked forward and see that next_value = 1
# but now:
list(gen)  # is [2, 3]  -- the first value is gone!

Here is a more real example:
gen = element_generator()
if gen.next_value() == 'STOP':
  quit_application()
else:
  process(gen.next())

Can anyone help me write a generator that you can look one element forward?

See also: Resetting generator object in Python

A: The Python generator API is one way: You can't push back elements you've read. But you can create a new iterator using the itertools module and prepend the element:
import itertools

gen = iter([1,2,3])
peek = gen.next()
print list(itertools.chain([peek], gen))

A: >>> gen = iter(range(10))
>>> peek = next(gen)
>>> peek
0
>>> gen = (value for g in ([peek], gen) for value in g)
>>> list(gen)
[0, 1, 2, 3, 4, 5, 6, 7, 8, 9]

A: Just for fun, I created an implementation of a lookahead class based on the suggestion by
Aaron:
import itertools

class lookahead_chain(object):
    def __init__(self, it):
        self._it = iter(it)

    def __iter__(self):
        return self

    def next(self):
        return next(self._it)

    def peek(self, default=None, _chain=itertools.chain):
        it = self._it
        try:
            v = self._it.next()
            self._it = _chain((v,), it)
            return v
        except StopIteration:
            return default

lookahead = lookahead_chain

With this, the following will work:
>>> t = lookahead(xrange(8))
>>> list(itertools.islice(t, 3))
[0, 1, 2]
>>> t.peek()
3
>>> list(itertools.islice(t, 3))
[3, 4, 5]

With this implementation it is a bad idea to call peek many times in a row...
While looking at the CPython source code I just found a better way which is both shorter and more efficient:
class lookahead_tee(object):
    def __init__(self, it):
        self._it, = itertools.tee(it, 1)

    def __iter__(self):
        return self._it

    def peek(self, default=None):
        try:
            return self._it.__copy__().next()
        except StopIteration:
            return default

lookahead = lookahead_tee

Usage is the same as above but you won't pay a price here to use peek many times in a row. With a few more lines you can also look ahead more than one item in the iterator (up to available RAM).

A: A simple solution is to use a function like this:
def peek(it):
    first = next(it)
    return first, itertools.chain([first], it)

Then you can do:
>>> it = iter(range(10))
>>> x, it = peek(it)
>>> x
0
>>> next(it)
0
>>> next(it)
1

A: If anybody is interested, and please correct me if I am wrong, but I believe it is pretty easy to add some push back functionality to any iterator.
class Back_pushable_iterator:
    """Class whose constructor takes an iterator as its only parameter, and
    returns an iterator that behaves in the same way, with added push back
    functionality.

    The idea is to be able to push back elements that need to be retrieved once
    more with the iterator semantics. This is particularly useful to implement
    LL(k) parsers that need k tokens of lookahead. Lookahead or push back is
    really a matter of perspective. The pushing back strategy allows a clean
    parser implementation based on recursive parser functions.

    The invoker of this class takes care of storing the elements that should be
    pushed back. A consequence of this is that any elements can be "pushed
    back", even elements that have never been retrieved from the iterator.
    The elements that are pushed back are then retrieved through the iterator
    interface in a LIFO-manner (as should logically be expected).

    This class works for any iterator but is especially meaningful for a
    generator iterator, which offers no obvious push back ability.

    In the LL(k) case mentioned above, the tokenizer can be implemented by a
    standard generator function (clean and simple), that is completed by this
    class for the needs of the actual parser.
    """
    def __init__(self, iterator):
        self.iterator = iterator
        self.pushed_back = []

    def __iter__(self):
        return self

    def __next__(self):
        if self.pushed_back:
            return self.pushed_back.pop()
        else:
            return next(self.iterator)

    def push_back(self, element):
        self.pushed_back.append(element)

it = Back_pushable_iterator(x for x in range(10))

x = next(it) # 0
print(x)
it.push_back(x)
x = next(it) # 0
print(x)
x = next(it) # 1
print(x)
x = next(it) # 2
y = next(it) # 3
print(x)
print(y)
it.push_back(y)
it.push_back(x)
x = next(it) # 2
y = next(it) # 3
print(x)
print(y)

for x in it:
    print(x) # 4-9

A: This will work -- it buffers an item and calls a function with each item and the next item in the sequence.
Your requirements are murky on what happens at the end of the sequence.  What does "look ahead" mean when you're at the last one?
def process_with_lookahead( iterable, aFunction ):
    prev= iterable.next()
    for item in iterable:
        aFunction( prev, item )
        prev= item
    aFunction( item, None )

def someLookaheadFunction( item, next_item ):
    print item, next_item

A: Instead of using items (i, i+1), where 'i' is the current item and i+1 is the 'peek ahead' version, you should be using (i-1, i), where 'i-1' is the previous version from the generator.
Tweaking your algorithm this way will produce something that is identical to what you currently have, apart from the extra needless complexity of trying to 'peek ahead'.
Peeking ahead is a mistake, and you should not be doing it.

A: Ok - two years too late - but I came across this question, and did not find any of the answers to my satisfaction. Came up with this meta generator:
class Peekorator(object):

    def __init__(self, generator):
        self.empty = False
        self.peek = None
        self.generator = generator
        try:
            self.peek = self.generator.next()
        except StopIteration:
            self.empty = True

    def __iter__(self):
        return self

    def next(self):
        """
        Return the self.peek element, or raise StopIteration
        if empty
        """
        if self.empty:
            raise StopIteration()
        to_return = self.peek
        try:
            self.peek = self.generator.next()
        except StopIteration:
            self.peek = None
            self.empty = True
        return to_return

def simple_iterator():
    for x in range(10):
        yield x*3

pkr = Peekorator(simple_iterator())
for i in pkr:
    print i, pkr.peek, pkr.empty

results in:
0 3 False
3 6 False
6 9 False
9 12 False
...
24 27 False
27 None False

i.e. you have at any moment during iteration access to the next item in the list.

A: Using itertools.tee will produce a lightweight copy of the generator; then peeking ahead at one copy will not affect the second copy. Thus:
import itertools

def process(seq):
    peeker, items = itertools.tee(seq)

    # initial peek ahead
    # so that peeker is one ahead of items
    if next(peeker) == 'STOP':
        return

    for item in items:

        # peek ahead
        if next(peeker) == "STOP":
            return

        # process items
        print(item)

The items generator is unaffected by modifications to peeker. However, modifying seq after the call to tee may cause problems.
That said: any algorithm that requires looking an item ahead in a generator could instead be written to use the current generator item and the previous item. This will result in simpler code - see my other answer to this question.

A: For sake of completeness, the more-itertools package (which should probably be part of any Python programmer's toolbox) includes a peekable wrapper that implements this behavior. As the code example in the documentation shows:
>>> p = peekable(['a', 'b'])
>>> p.peek()
'a'
>>> next(p)
'a'

However, it's often possible to rewrite code that would use this functionality so that it doesn't actually need it. For example, your realistic code sample from the question could be written like this:
gen = element_generator()
command = gen.next_value()
if command == 'STOP':
  quit_application()
else:
  process(command)

(reader's note: I've preserved the syntax in the example from the question as of when I'm writing this, even though it refers to an outdated version of Python)

A: An iterator that allows peeking at the next element and also further ahead. It reads ahead as needed and remembers the values in a deque.
from collections import deque

class PeekIterator:

    def __init__(self, iterable):
        self.iterator = iter(iterable)
        self.peeked = deque()

    def __iter__(self):
        return self

    def __next__(self):
        if self.peeked:
            return self.peeked.popleft()
        return next(self.iterator)

    def peek(self, ahead=0):
        while len(self.peeked) <= ahead:
            self.peeked.append(next(self.iterator))
        return self.peeked[ahead]

Demo:
>>> it = PeekIterator(range(10))
>>> it.peek()
0
>>> it.peek(5)
5
>>> it.peek(13)
Traceback (most recent call last):
  File "<pyshell#68>", line 1, in <module>
    it.peek(13)
  File "[...]", line 15, in peek
    self.peeked.append(next(self.iterator))
StopIteration
>>> it.peek(2)
2
>>> next(it)
0
>>> it.peek(2)
3
>>> list(it)
[1, 2, 3, 4, 5, 6, 7, 8, 9]
>>>

A: Although itertools.chain() is the natural tool for the job here, beware of loops like this:
for elem in gen:
    ...
    peek = next(gen)
    gen = itertools.chain([peek], gen)

...Because this will consume a linearly growing amount of memory, and eventually grind to a halt.  (This code essentially seems to create a linked list, one node per chain() call.)  I know this not because I inspected the libs but because this just resulted in a major slowdown of my program - getting rid of the gen = itertools.chain([peek], gen) line sped it up again.  (Python 3.3)

A: Python3 snippet for @jonathan-hartley answer:
def peek(iterator, eoi=None):
    iterator = iter(iterator)

    try:
        prev = next(iterator)
    except StopIteration:
        return iterator

    for elm in iterator:
        yield prev, elm
        prev = elm

    yield prev, eoi

for curr, nxt in peek(range(10)):
    print((curr, nxt))

# (0, 1)
# (1, 2)
# (2, 3)
# (3, 4)
# (4, 5)
# (5, 6)
# (6, 7)
# (7, 8)
# (8, 9)
# (9, None)

It'd be straightforward to create a class that does this on __iter__ and yields just the prev item and put the elm in some attribute.

A: w.r.t @David Z's post, the newer seekable tool can reset a wrapped iterator to a prior position.
>>> s = mit.seekable(range(3))
>>> s.next()
# 0

>>> s.seek(0)                                              # reset iterator
>>> s.next()
# 0

>>> s.next()
# 1

>>> s.seek(1)
>>> s.next()
# 1

>>> next(s)
# 2

A: cytoolz has a peek function.
>> from cytoolz import peek
>> gen = iter([1,2,3])
>> first, continuation = peek(gen)
>> first
1
>> list(continuation)
[1, 2, 3]

A: In my case, I need a generator where I could queue back to generator the data I have just got via next() call.
The way I handle this problem, is to create a queue. In the implementation of the generator, I would first check the queue: if queue is not empty, the "yield" will return the values in queue, or otherwise the values in normal way.
import queue

def gen1(n, q):
    i = 0
    while True:
        if not q.empty():
            yield q.get()
        else:
            yield i
            i = i + 1
            if i >= n:
                if not q.empty():
                    yield q.get()
                break

q = queue.Queue()

f = gen1(2, q)

i = next(f)
print(i)
i = next(f)
print(i)
q.put(i) # put back the value I have just got for following 'next' call
i = next(f)
print(i)

running
python3 gen_test.py

0
1
1

This concept is very useful when I was writing a parser, which needs to look the file line by line, if the line appears to belong to next phase of parsing, I could just queue back to the generator so that the next phase of code could parse it correctly without handling complex state.

A: For those of you who embrace frugality and one-liners, I present to you a one-liner that allows one to look ahead in an iterable (this only works in Python 3.8 and above):
>>> import itertools as it
>>> peek = lambda iterable, n=1: it.islice(zip(it.chain((t := it.tee(iterable))[0], [None] * n), it.chain([None] * n, t[1])), n, None)
>>> for lookahead, element in peek(range(10)):
...     print(lookahead, element)
1 0
2 1
3 2
4 3
5 4
6 5
7 6
8 7
9 8
None 9
>>> for lookahead, element in peek(range(10), 2):
...     print(lookahead, element)
2 0
3 1
4 2
5 3
6 4
7 5
8 6
9 7
None 8
None 9

This method is space-efficient by avoiding copying the iterator multiple times. It is also fast due to how it lazily generates elements. Finally, as a cherry on top, you can look ahead an arbitrary number of elements.

A: An algorithm that works by "peeking" at the next element in a generator could equivalently be one that works by remembering the previous element, treating that element as the one to operate upon, and treating the "current" element as simply "peeked at".
Either way, what is really happening is that the algorithm considers overlapping pairs from the generator. The itertools.tee recipe will work fine - and it is not hard to see that it is essentially a refactored version of Jonathan Hartley's approach:
from itertools import tee
# From https://docs.python.org/3/library/itertools.html#itertools.pairwise
# In 3.10 and up, this is directly supplied by the `itertools` module.
def pairwise(iterable):
    # pairwise('ABCDEFG') --> AB BC CD DE EF FG
    a, b = tee(iterable)
    next(b, None)
    return zip(a, b)

def process(seq):
    for to_process, lookahead in pairwise(seq):
        # peek ahead
        if lookahead == "STOP":
            return
        # process items
        print(to_process)