text:
Q: Extract a specific string from text file and then to create HTTP request I'm trying to extract a specific string value from a text file (file1.txt) and then to create HTTP GET request with the extracted string (url address), the HTTP response should be saved as a new HTML file in the directory.
The string I'm trying to extract is a value of a specific key.
For example: "display_url":"test.com" (extract "test.com" and then to create http request)
My txt file content:
{"created_at":"Thu Nov 15 11:35:00 +0000 2018","id":15292802,"id_str":325802","text":"test8  https://t.co/ZtCsuk7Ek2   #osining","source":"\u003ca href=\"http://twitter.com\" rel=\"nofollow\"\u003eTwitter Web Client\u003c/a\u003e","truncated":false,"in_reply_to_status_id":null,"in_reply_to_status_id_str":null,"in_reply_to_user_id":null,"in_reply_to_user_id_str":null,"in_reply_to_screen_name":null,"user":{"id":961508561217052675,"id_str":"961508561217052675","name":"Online S","screen_name":"osectraining","location":"Israel","url":"https://www.test.co.il","description":"test","translator_type":"none","protected":false,"verified":false,"followers_count":2,"friends_count":51,"listed_count":0,"favourites_count":0,"statuses_count":7,"created_at":"Thu Feb 08 07:54:39 +0000 2018","utc_offset":null,"time_zone":null,"geo_enabled":false,"lang":"en","contributors_enabled":false,"is_translator":false,"profile_background_color":"000000","profile_background_image_url":"http://abs.twimg.com/images/themes/theme1/bg.png","profile_background_image_url_https":"https://abs.twimg.com/images/themes/theme1/bg.png","profile_background_tile":false,"profile_link_color":"1B95E0","profile_sidebar_border_color":"000000","profile_sidebar_fill_color":"000000","profile_text_color":"000000","profile_use_background_image":false,"profile_image_url":"http://pbs.twimg.com/profile_images/961510231346958336/d_KhBeTD_normal.jpg","profile_image_url_https":"https://pbs.twimg.com/profile_images/961510231346958336/d_KhBeTD_normal.jpg","profile_banner_url":"https://pbs.twimg.com/profile_banners/961508561217052675/1518076913","default_profile":false,"default_profile_image":false,"following":null,"follow_request_sent":null,"notifications":null},"geo":null,"coordinates":null,"place":null,"contributors":null,"is_quote_status":false,"quote_count":0,"reply_count":0,"retweet_count":0,"favorite_count":0,"entities":{"hashtags":[{"text":"osectraining","indices":[33,46]}],"urls":[{"url":"https://t.co/ZtCsuk7Ek2","expanded_url":"http://test.com","display_url":"test.com","indices":[7,30]}],"user_mentions":[],"symbols":[]},"favorited":false,"retweeted":false,"possibly_sensitive":false,"filter_level":"low","lang":"en","timestamp_ms":"1542281700508"}
My code:
import re
with open('file1') as f:
found = []
for line in f.readlines():
    found += re.findall(r'"display_url":\s(\w+)\s', line)
print(found)

A: Please note that indentation is critical in Python.  It's not clear to me if you have made a mistake in your code indentation, or just a mistake in formatting your posted question.  Having said that...
You need to do four things to accomplish the task:

*

*Read file1.txt from disk.

*Parse the contents of the file to find the display_url

*Call the URL to get a response

*Write the response to disk

Your code attempts to do steps 1 and 2, but there are a few problems.  The first issue is that your text file has an error in it.  It is missing a closing quotation mark for this key-value pair: "id_str":"325802".
If you fix that, you then need to fix the indentation of your code so that f is available when you try to use it. Finally, I don't think the regex approach is really the way to go here.
You can read the file and parse it to a Python dictionary easily.  Finding the information you want requires that you know the structure of the JSON, here is one way you could do it:
import json

with open('./file1.txt', 'r') as f:
    lines = f.readlines()
    text = ''.join(lines)

dictionary = json.loads(text)
entities = dictionary.get('entities')
urls = entities.get('urls')[0]
display_url = urls.get('display_url')
print(display_url)

Now you need to figure out steps 3 and 4, which are really the easy part compared to step 2.

A: From your text, it looks like that your file has JSON data. So you can load JSON instead of reading lines and then you can easily get the value of display_url.
Ex.
import json
with open('file1') as f:
    data = json.load(f)

urls = [x["display_url"] for x in data["entities"]["urls"]]


text:
Q: jQuery .attr() not responding as expected I have a text field that holds a difference between days. I need to use it calculate something on my page. However, for some reason it is coming back as undefined when I do a console.log(). Any ideas?
<script>
        $(document).on('change', '#unitselector', function()
        {
            var unit = $('select option:selected').text();
            var rate = $(this).val();
            var tax = $('select option:selected').attr('label');
            var depart=$('#departdate').val();
            var arrival = $('#arrivaldate').val();
            var dataString = {unit:unit, depart:depart, arrival:arrival};
            console.log(dataString);
            //console.log($('.extracharges').serialize());
            $.ajax({
                type: "POST",
                url: "classes/unit_info.php",
                data: dataString,
                cache: false,
                success: function(html)
                {
                    $('.unitinfolist').html(html);
                }
            });

            var days = $('#days').attr('name');
            var days2 = $('#days').attr('value');
            console.log('days: '+days);
            console.log('days: '+ days2 );
            $('.rentalcharges').find('#rent').val(rate*days);
        });
    </script>

and the PHP
$arrive = $_POST['arrival'];
$leave = $_POST['depart'];

$a = date_create($arrive);
$d = date_create($leave);
$diff = date_diff($d,$a);

echo '<input type="text" id="days" value="'.$diff->d.'" name="'.$diff->d.'" />';

A: The ajax call is asynchronous so even though you have the logging code written after the ajax call you are logging the values before they have been returned from the server.
Move your code into the ajax success handler like so:
<script>
        $(document).on('change', '#unitselector', function()
        {
            var unit = $('select option:selected').text();
            var rate = $(this).val();
            var tax = $('select option:selected').attr('label');
            var depart=$('#departdate').val();
            var arrival = $('#arrivaldate').val();
            var dataString = {unit:unit, depart:depart, arrival:arrival};
            console.log(dataString);
            //console.log($('.extracharges').serialize());
            $.ajax({
                type: "POST",
                url: "classes/unit_info.php",
                data: dataString,
                cache: false,
                success: function(html)
                {
                    $('.unitinfolist').html(html);
                    var days = $('#days').attr('name');
                    var days2 = $('#days').attr('value');
                    console.log('days: '+days);
                    console.log('days: '+ days2 );
                    $('.rentalcharges').find('#rent').val(rate*days);
                }
            });

        });
    </script>

redpajama_set_name: RedPajamaStackExchange


text:
Q: Flexible hierarchy with boost::variant The question is a modified code provided by @sehe as part of his answer to my previous question. This modification include the parent of each node. Sample structure is Store->Shelves->Products. I want to have parent in each node. The code compiles just fine, but the "parent" member of the node is apparently destroyed. I'll appreciate the help in figuring out why. Thanks!
    #include <iostream>
    #include <sstream>
    #include <algorithm>
    #include <string>
    #include <vector>
    #include <boost/variant.hpp>
    #include <boost/format.hpp>

    namespace GenericDomain {

        namespace Tag {
            struct Store{};
            struct Shelf{};
            struct Product{};
        }

        template <typename Kind> struct Node;

        using Store = Node<Tag::Store>;
        using Shelf = Node<Tag::Shelf>;
        using Product = Node<Tag::Product>;

        using Tree = boost::variant<
            boost::recursive_wrapper<Product>,
            boost::recursive_wrapper<Store>,
            boost::recursive_wrapper<Shelf>
        >;

        template <typename Kind> struct Node {
            std::string name;
            std::vector<Tree> children;
            Kind kind;
            Tree* parent;
            Node(std::string ofname, Tree* ofparent) : name(ofname), parent(ofparent) {}
        };

        std::ostream& operator<<(std::ostream& os, Tag::Store)   { return os << "Store"; }
        std::ostream& operator<<(std::ostream& os, Tag::Shelf)   { return os << "\tShelf"; }
        std::ostream& operator<<(std::ostream& os, Tag::Product) { return os << "\t\tProduct"; }

        struct vstName : public boost::static_visitor<const std::string&>
        {
            template<typename T> const std::string& operator()(T& p) const {
                return p.name;
            }
        };

        template <typename Kind> std::ostream& operator<<(std::ostream& os, Node<Kind> const& n) {
            os << Kind{} << ": " << n.name << "\n";
            if (n.parent == nullptr)
                os << "root\n";
            else {
                vstName visitorName;
                std::string parentname = boost::apply_visitor(visitorName, *n.parent);
                os << "parent of " << parentname << "\n";
            }
            for (auto& child : n.children) os << child;
            return os;
        }

        std::string test1()
        {
            std::vector<Tree> stores;
            for (int s = 0; s < 2; ++s)
            {
                stores.emplace_back(Tree(Store((boost::format("store %1%") % s).str(), nullptr)));
                Tree& store = *stores.rbegin();
                std::vector<Tree>& shelves = boost::get<Store>(store).children;
                for (int sh = 0; sh < 2; ++sh) {
                    shelves.push_back(Tree(Shelf((boost::format("shelf %1%-%2%") % s %sh).str(), &store)));
                    Tree& shelf = *shelves.rbegin();
                    std::vector<Tree>& products = boost::get<Shelf>(shelf).children;
                    for (int pr = 0; pr< 2; ++pr)
                        products.push_back(Tree(Product((boost::format("product %1%-%2%-%3%") % s %sh %pr).str(), &shelf)));
                }
            }

            std::ostringstream oss;
            std::for_each(begin(stores), end(stores),
                [&](const Tree& p){oss << p; });
            return oss.str();
        }

    };
int main(int argc, char *argv[])
{
    std::cout << GenericDomain::test1();
    return 1;
}


text:
Q: Sitecore Maxmind lookup task I want Sitecore to only perform a Maxmind lookup after a visitor has matched a certain pattern card. I can see plenty of references to the "DNS lookup task" within the comments of Sitecore.Analytics.Config, but I can't seem to track it down to see if it's possible to mess with it.
Can someone point me in the right direction?

A: As I see it the GeoIPLookup is triggered in the StartTracking pipeline in the UpdateGeoIpData processor. It calls into the lookup provider asynchronious.
So I guess you can replace this processor with your own inheriting from this one, and then add your conditions. In that way you would have something like:
public class UpdateGeoProcessor : UpdateGeoIpData
  {
    public override void Process(StartTrackingArgs args)
    {
      if (true) //Put your condition here
      {
        base.Process(args);
      }
    }
  }

Then in your config file you should have something like this:
  <startTracking>
        <processor type="Sitecore.Analytics.Pipelines.StartTracking.RaiseStartTracking,Sitecore.Analytics" />
        <processor type="Sitecore.Analytics.Pipelines.StartTracking.InitializeTracker,Sitecore.Analytics" />
        <processor type="yyy.UpdateGeoProcessor,yyy" />
        <processor type="Sitecore.Analytics.Pipelines.StartTracking.TrackerInitialized,Sitecore.Analytics" />

As fare as I can see, that should handle it, but I have been unable to test it thouroughly.


text:
Q: Avoid auto-instantiation of managed bean when injected as @ManagedProperty I have a requestscoped bean which can receive its data from three different viewscoped beans (from 3 different pages). The beans are JSF Managed Beans.
When I use ManagedProperty in the request scoped for 3 different view scoped beans, it instantiates the view scoped beans which is what I do NOT want. I want to simply know from which bean it is being called from and then call a specific method (different) for each bean.
How can I check which bean is instantiated and in scope so I can call the correct bean's method?

A: Looks like it's pretty simple. I was reading one of Balus's posts. I simply used ManagedProperty(value="#{viewScope.managedBeanName}") . It did not instantiate. For the inscope, it gave me the created bean :). Happy


text:
Q: How do I figure out what I need to know? I am a novice programmer who is trying to teach myself to code, specifically in C#. I've taken on a project from a friend of mine and I am not sure what I need to know to get the project done. I suppose the issue is I don't know what I need to know to even get the project started.
I do have many of the basics of object oriented programming, classes, methods and what-not, but when I sit down to code-I don't know where to begin looking to accomplish even basic tasks. I don't know syntax or what the language is capable of with the tools provided. I have read some books, but they mostly seem to be about the concepts and theories about OOP within C# with minimal syntax.
I guess the question is where do I look to learn the syntax-is there some sort of repository of classes and methods that I am missing with examples of how to use the tools it contains? I am stuck in a place of not knowing where to go/look next.
Thanks for any help

A: Getting started with Visual C#.

A: One of the things I usually recommend to Junior Developers on my projects who are looking for a better picture of how things work is to get familiar with your F10/F11 keys in Visual Studio by stepping through open source projects written in C#.
Pick something you find interesting from Codeplex or Sourceforge or Google code (there's a topic here about good code to read) and download the source code. Open it in Visual Studio and choose "Debug -> Step Into". From there, let the debugger be your guide through the code.
F11 lets you dig deeper, SHIFT+F11 steps you back a level.
It really can teach you a lot about how functioning code is structured because it leads you through the flow and provides a pretty good tour of functionality in the code.
It also works well with books and other materials because, when you see something you don't understand, you can go looking for a better explanation.
This is something I do myself quite often to familiarize myself with a given codebase, whether it's open source or a paying project with existing code.

A: I don't use C# myself but for just getting a handle on the syntax of a language as well as basic programming techniques you almost can't go wrong with the O'Reilly books.  You might want to check out their Learning C# book.

A: As a general rule, split the project into multiple task. If you still don't know how to start with each task, then further split it into smaller subtask.
Until you can say, "Ah, I can code this task", do it and move on to the next task.

A: I started with the C# Station tutorials. "Getting started with Visual C#" gives me the creeps...

A: MSDN.  Go straight to the horses mouth.


text:
Q: What's This Blue Cube Icon in the View Controller Scene Graph New to XCode, and trying to get my head around the various things in this IDE. So my question is, what are the two blue cube thingys which I've circled in the image below?
This screenshot is taken from XCode 7, in case that matters.

A: It's static Section of UITableView


text:
Q: HTML being stripped or not working as it should I have a website where users will enter chatrooms with HTML codes (depicting avatars and pictures, their names, sometimes links, etc) but since updating the server and php to 7.3 even with converting UTF-8 it all seems to work, except for quotes and ? marks in links and things like that breaking it seemingly being picked up as code or not reading it right? I feel like I am missing something simple that was changed.
An example below.
....Name Here....

...Name...

Random Saying and Quote

-

this is just one example with all " " stripped, ' ' stripped, because otherwise it will break it. This code works fine except for the ? in the link which is simply from an SMF forum. If I use a URL shortener for the link that removes the ? it works as it should.

EDIT
To clarify, if I put quotes in there, it won't be displayed right at all, and it will change the codes they input to something random like

or if I have the link in there like it is now with a question mark in it.
I appreciate the clarification. To give more context to this, markup has been fixed and corrected on the pages. Users comes to the website, click on the name of a chatroom they would like to enter into, then enter in their desired name and enter into the rooms (displayed in an iframe chatbox top and bottom) (html is allowed to be entered here, here comes the issue)
When they do, this is displayed correctly, UNLESS, they have quotes, apostrophes, or links with question marks in it or try and use any kind of html "code" like target="_new"

A: The quotes are not removed by updating server or php. Look at the history of commands that you have executed on the server, it seems that you ran a command that removes the quotes from a directory, it is a possibility.


text:
Q: AttributeError: 'function' object has no attribute 'views' Hello I'm learning Django framework for Web applications
I'm trying to build basic blog from tutorial
and I'm stuck with the error:
AttributeError is telling me that  'function' object has no attribute 'views'.

I don't know where I have problem in my files so I will include here some code of my files.
There is my urls.py
from django.conf.urls import url
from django.contrib import admin
import WarblerTest

urlpatterns = {
    url(r'^admin/', admin.site.urls),
    (r'^$', WarblerTest.blog.views.index),
    url(
        r'^blog/view/(?P<slug>[^\.]+).html',
        WarblerTest.blog.views.view_post,
        name='view_blog_post'),
    url(
        r'^blog/category/(?P<slug>[^\.]+).html',
        WarblerTest.blog.views.view_category,
        name='view_blog_category'),
}

There is my views.py
from django.shortcuts import render
from blog.models import Blog, Category
from django.shortcuts import render_to_response, get_object_or_404

def index(request):
    return render_to_response('index.html', {
        'categories': Category.objects.all(),
        'posts': Blog.objects.all()[:5]
    })

def view_post(request, slug):
    return render_to_response('view_post.html', {
        'post': get_object_or_404(Blog, slug=slug)
    })

def view_category(request, slug):
    category = get_object_or_404(Category, slug=slug)
    return render_to_response('view_category.html', {
        'category': category,
        'posts': Blog.objects.filter(category=category)[:5]
    })

There is my models.py
from django.db import models
from django.db.models import permalink

# Create your models here.

class Blog(models.Model):
    title = models.CharField(max_length = 100,unique = True)
    slug = models.CharField(max_length = 100,unique = True)
    body = models.TextField()
    posted = models.DateField(db_index = True,auto_now_add = True)

    def __unicode__(self):
        return '%s' % self.title

    @permalink
    def get_absolute_url(self):
        return ('view-blog-post',None, {'slug' : self.slug})

class Category(models.Model):
    title = models.CharField(max_length = 100,db_index = True)
    slug = models.SlugField(max_length = 100,db_index = True)

    def __unicode__(self):
        return '%s' % self.title

    @permalink
    def get_absolute_url(self):
        return ('view_blog_category', None, { 'slug': self.slug })

And there is my tracback error
Unhandled exception in thread started by <function check_errors.<locals>.wrapper at 0x03853B28>
Traceback (most recent call last):
  File "C:\Users\Tornike\AppData\Local\Programs\Python\Python36-32\lib\site-packages\django\utils\autoreload.py", line 2
26, in wrapper
    fn(*args, **kwargs)
  File "C:\Users\Tornike\AppData\Local\Programs\Python\Python36-32\lib\site-packages\django\core\management\commands\run
server.py", line 121, in inner_run
    self.check(display_num_errors=True)
  File "C:\Users\Tornike\AppData\Local\Programs\Python\Python36-32\lib\site-packages\django\core\management\base.py", li
ne 374, in check
    include_deployment_checks=include_deployment_checks,
  File "C:\Users\Tornike\AppData\Local\Programs\Python\Python36-32\lib\site-packages\django\core\management\base.py", li
ne 361, in _run_checks
    return checks.run_checks(**kwargs)
  File "C:\Users\Tornike\AppData\Local\Programs\Python\Python36-32\lib\site-packages\django\core\checks\registry.py", li
ne 81, in run_checks
    new_errors = check(app_configs=app_configs)
  File "C:\Users\Tornike\AppData\Local\Programs\Python\Python36-32\lib\site-packages\django\core\checks\urls.py", line 1
4, in check_url_config
    return check_resolver(resolver)
  File "C:\Users\Tornike\AppData\Local\Programs\Python\Python36-32\lib\site-packages\django\core\checks\urls.py", line 2
4, in check_resolver
    for pattern in resolver.url_patterns:
  File "C:\Users\Tornike\AppData\Local\Programs\Python\Python36-32\lib\site-packages\django\utils\functional.py", line 3
5, in __get__
    res = instance.__dict__[self.name] = self.func(instance)
  File "C:\Users\Tornike\AppData\Local\Programs\Python\Python36-32\lib\site-packages\django\urls\resolvers.py", line 313
, in url_patterns
    patterns = getattr(self.urlconf_module, "urlpatterns", self.urlconf_module)
  File "C:\Users\Tornike\AppData\Local\Programs\Python\Python36-32\lib\site-packages\django\utils\functional.py", line 3
5, in __get__
    res = instance.__dict__[self.name] = self.func(instance)
  File "C:\Users\Tornike\AppData\Local\Programs\Python\Python36-32\lib\site-packages\django\urls\resolvers.py", line 306
, in urlconf_module
    return import_module(self.urlconf_name)
  File "C:\Users\Tornike\AppData\Local\Programs\Python\Python36-32\lib\importlib\__init__.py", line 126, in import_modul
e
    return _bootstrap._gcd_import(name[level:], package, level)
  File "<frozen importlib._bootstrap>", line 978, in _gcd_import
  File "<frozen importlib._bootstrap>", line 961, in _find_and_load
  File "<frozen importlib._bootstrap>", line 950, in _find_and_load_unlocked
  File "<frozen importlib._bootstrap>", line 655, in _load_unlocked
  File "<frozen importlib._bootstrap_external>", line 678, in exec_module
  File "<frozen importlib._bootstrap>", line 205, in _call_with_frames_removed
  File "C:\Users\Tornike\Desktop\WarblerTest\WarblerTest\urls.py", line 8, in <module>
    (r'^$', WarblerTest.blog.views.index),
AttributeError: 'function' object has no attribute 'views'

A: In your main project urls.py, remove the import WarblerTest import and replace it with from blogs import views.
Then update your url patterns to use the views module that you imported. Note that urlpatterns should be a list (square brackets [...] not curly braces {...} as you have. Every item should be a url(...) rather than a tuple (...) to avoid problems in Django 1.10+.
from blogs import views

urlpatterns = [
    url(r'^admin/', admin.site.urls),
    url(r'^$', views.index),
    url(r'^blog/view/(?P<slug>[^\.]+).html', views.view_post, name='view_blog_post'),
    url(r'^blog/category/(?P<slug>[^\.]+).html', views.view_category, name='view_blog_category'),
]


text:
Q: Two objects, one "Is not a function" At the bottom of the code, I build two instances of Nodes that both use the .getChildren function defined but I get Uncaught TypeError: t2.getChildren is not a function but I define it clearly in my Node object constructor. Also, why is it saying this for t2 and not t1.
function Node(value) {

    // based on graph theory, we give
    this.value = value;
    this.children = [];
    this.parent = null;

    // set and get functions
    this.setParent = function(node) {
        this.parent = node;
    };

    this.getParent = function() {
        return this.parent;
    };

    this.addChild = function(node) {
        node.setParent(this);
          this.children[this.children.length] = node;
    };

    this.getChildren = function() {
        return this.children;
    };

}

// check Identical

var subTreeFinder = function (t1,t2) {

  // base cases

  if (t2==null) {
    return true; // empty trees are subtrees to all trees
  }

  if (t1==null){
    return false; // a non-empty tree can't fit in an empty tree
  }

  if (checkIdentical(t1,t2)) {
    return true;
  }

  var t1Children = t1.getChildren();
  var t2Children = t2.getChildren();

  return subTreeFinder(t1Children.every(subTreeFinder) || t2Children.every(subTreeFinder));
}

// check Identical
    var checkIdentical = function (t1,t2) {

      // base case
      if (t1==null && t2 == null) {
        return true;
      }

      if (t1 != null && t2 != null) {

        var t1Children = t1.getChildren();
        var t2Children = t2.getChildren();

        // an obvious case and time saver
        if (t1Children.length != t2Children.length){
          return false;
        }

        // recursive call. for every arr. element in both sets of kids check if we recurrsively get back true
        if (t1.value == t2.value && t1Children.every(checkIdentical) && t2Children.every(checkIdentical) ) {
          return true;
        }

      }

      // here: either one is null and the other ins't, so false.
      return false;

    }

// The actual Trees

var dom = new Node('a'); // root
dom.addChild(new Node('b'));
dom.addChild(new Node('c'));

var vdom = new Node('x'); // root
vdom.addChild(new Node('y'));
vdom.addChild(new Node('z'));

console.log(subTreeFinder(dom, vdom));

// console.log(dom); // Should read entire Demo Tree object (unfold to see contents)

A: Your code has wrong implementation of Array.prototype.every.
Check the right syntax here: https://developer.mozilla.org/en-US/docs/Web/JavaScript/Reference/Global_Objects/Array/every
Please find below: corrected code
function Node(value) {

    // based on graph theory, we give
    this.value = value;
    this.children = [];
    this.parent = null;

    // set and get functions
    this.setParent = function(node) {
        this.parent = node;
    };

    this.getParent = function() {
        return this.parent;
    };

    this.addChild = function(node) {
        node.setParent(this);
          this.children[this.children.length] = node;
    };

    this.getChildren = function() {
        return this.children;
    };

}

// check Identical

var subTreeFinder = function (t1,t2) {
console.error(t1, t2)
  // base cases

  if (t2==null) {
    return true; // empty trees are subtrees to all trees
  }

  if (t1==null){
    return false; // a non-empty tree can't fit in an empty tree
  }

  if (checkIdentical(t1,t2)) {
    return true;
  }
debugger;
  var t1Children = t1.getChildren();
  var t2Children = t2.getChildren();

  return subTreeFinder(t1Children.every(function(element) {subTreeFinder(element)}) || t2Children.every(function(element) {subTreeFinder(element)}));
}

// check Identical
    var checkIdentical = function (t1,t2) {

      // base case
      if (t1==null && t2 == null) {
        return true;
      }

      if (t1 != null && t2 != null) {

        var t1Children = t1.getChildren();
        var t2Children = t2.getChildren();

        // an obvious case and time saver
        if (t1Children.length != t2Children.length){
          return false;
        }

        // recursive call. for every arr. element in both sets of kids check if we recurrsively get back true
        if (t1.value == t2.value && t1Children.every(checkIdentical) && t2Children.every(checkIdentical) ) {
          return true;
        }

      }

      // here: either one is null and the other ins't, so false.
      return false;

    }

// The actual Trees

var dom = new Node('a'); // root
dom.addChild(new Node('b'));
dom.addChild(new Node('c'));

var vdom = new Node('x'); // root
vdom.addChild(new Node('y'));
vdom.addChild(new Node('z'));

console.log(subTreeFinder(dom, vdom));

A: You miss the API of Array#every, where the callback has as first parameter the actual item and as second paramter the index of the actual item.
The index is not an instance of Node. Therefore the method getChildren is not available.


text: Q: CenturyLink Modem and Wifi with Google WiFi CenturyLink is my ISP. They provided a modem with built in WiFi. Currently I am using Netgear for my in-house wifi and am planning to replace it with Google. Being a mesh network, can I have the same connection to the CenturyLink modem with Google as I do now with my Netgear and still use the CenturLink wifi also? Basically, my set up, is I am either hardwired to the modem or using the built in wifi for all my PCs and the NetGear for all my entertainment systems. I want the same reult when google is installed. I did try to mesh google and netgear together, but all that got me was an afternoon of rebuilding my wifi back on netgear.


text:
Q: Django storages or avatar sets https on my urls so I get certificate errors I have set my server up with django-storages and django-avatar. When I go to view my site, none of my css or images loads. When I inspect the url i see it is a https and that is causing a certificate error. If I remove the s to make it a normal http then it works fine. What setting have I messed up that is causing the issue?
Django 1.4.5
django-storages
django-avatar

import os
PROJECT_ROOT = os.path.dirname(__file__) + '/'

MEDIA_ROOT = PROJECT_ROOT + 'media/'
MEDIA_URL = 'http://static.XXXX.com.s3.amazonaws.com/'
STATIC_ROOT = PROJECT_ROOT + 'static/'
STATIC_URL = 'http://static.XXXX.com.s3.amazonaws.com/'
STATIC_DOC_ROOT = PROJECT_ROOT + 'static/'

DEFAULT_FILE_STORAGE = 'storages.backends.s3boto.S3BotoStorage'

AWS_ACCESS_KEY_ID = 'XXXX'
AWS_SECRET_ACCESS_KEY = 'XXXX'
AWS_STORAGE_BUCKET_NAME = 'static.XXXX.com'
AWS_QUERYSTRING_AUTH = False
AWS_S3_SECURE_URLS = False

#AVATAR
AVATAR_DEFAULT_SIZE = 80
AVATAR_THUMB_FORMAT = "PNG"
AVATAR_THUMB_QUALITY = 90
AVATAR_HASH_FILENAMES = False
AVATAR_HASH_USERDIRNAMES = False
AVATAR_GRAVATAR_BACKUP = False
AVATAR_DEFAULT_URL = MEDIA_URL + 'avatars/default.png'

I have used storages (on the same shared server) before with no issue so it leads me to believe that it is avatar that is the issue. Any pointers would be greatly appreciated.
EDIT:
linked files that are using {{ MEDIA_URL }} on the front end are fine
Images that were uploaded using the avatar are not showing due to the https
admin styles and images are not showing due to https
If it helps the images that are not showing are in a section that requires users to be logged in?
...I am just checking other images now
EDIT 2:
Other images (log & bg image) are ok , but are loaded via a css file on s3

A: I have fixed the issue. The way I did it was by replacing:
DEFAULT_FILE_STORAGE = 'storages.backends.s3boto.S3BotoStorage'

with:
DEFAULT_FILE_STORAGE = 'storages.backends.s3.S3Storage'
from S3 import CallingFormat
AWS_CALLING_FORMAT = CallingFormat.SUBDOMAIN


text:
Q: How do I update the cookie JSESSIONID with HttpOnly by working directly on Http Headers? Here is the big picture
I want to append "HttpOnly" to the JSESSIONID Cookie, but I want to do this by hand, meaning:
//create a new cookie
StringBuilder updatedCookie = new StringBuilder("JSESSIONID").append("=")
                .append(sessionId).append("; Path=").append("/")
                .append("; HttpOnly");

//save the cookie
response.setHeader("SET-COOKIE", updatedCookie.toString());

This is done in a Servlet Filter, that is mapped to all the site (the filter has the url pattern as "/*")

*

*How can I make this filter run only once ? That is, at the login, or

*Do I really have to run at each request and check if this cookie has been already marked and skip if the answer is "yes" ?

Any suggestions ?
PS:

*

*Don't tell me to upgrade to Servlet 3.0 because I can't do that right now

*Ignore the improper use of the StringBuilder and missing variable sessionId

A:
How can I make this filter run only once ? That is, at the login

Not possible. The session might already have been created beforehand.
In theory, your best place is HttpSessionListener#sessionCreated(), but this doesn't provide the HttpServletResponse object to you in any way, so you're lost.

Do I really have to run at each request and check if this cookie has been already marked and skip if the answer is "yes" ?

Yes. This should however be particularly cheap.


text:
Q: C# Console Application - Using Methods to Pass Arguments I have an application assignment from school that I have been working on and have gotten stuck on. I am not understanding some of the concepts to complete my program. It is simple and I have the basic structure down. Could someone assist me in understanding and completing my program? Below is the listed information:
The following is the overall application assignment:
Write a program to display the average of some numbers.  Your program will consist of three user defined methods named GetNums(), CalcAvg(), and DspAvg().  In GetNums() prompt for and read in 3 real numbers from the keyboard.  After reading in the numbers, call CalcAvg() passing the three numbers as input.  CalcAvg() must RETURN (use the return statement) the average of the 3 numbers. After calling CalcAvg(), call DspAvg() to display the average and the three numbers entered.  Your program must not contain any variables with class-wide scope (all variables must be declared inside a method). All method calls (GetNums(), CalcAvg(), and DspAvg() must be called from main()). Using proper passing is important.
Your output should closely resemble the following.
The average of 10.20, 89.50, and 17.60 is 39.10.
Round the average to two decimal places. Display all values with two decimal places.
GetNums() will have three arguments, all pass by out. CalcAvg() will have three arguments, all pass by copy. Do not use four! DspAvg() will have four arguments, all pass by copy.
Below is the following code I have written, but have gotten stuck, based on the requirements above.
static void Main(string[] args)
        {
            int nu1, nu2, nu3, cavg;

            GetNums();
            CalcAvg();
            DspAvg();
        }

        static void GetNums()
        {
            Console.Write("Please enter nu1: ");
                nu1 = int.Parse(Console.ReadLine());

            Console.Write("Please enter nu2: ");
                nu2 = int.Parse(Console.ReadLine());

            Console.Write("Please enter nu3: ");
                nu3 = int.Parse(Console.ReadLine());

                CalcAvg(DspAvg);
        }

        static void CalcAvg()
        {

        }

        static void DspAvg()
        {

        }

    }
}

A: You can't declare variables in one method and use them in another method. the second method doesn't know the variables in the first method.
As the specification said you need your GetNums() to have 3 parameters passed by out
static void GetNums(out decimal num1, out decimal num2, out decimal num3)

Start from here. If you need more help please let me know :)

A: Well, we won't do your homework for you, but I can give you a few pointers. Your Main should only call GetNums(). GetNums() should call CalcAvg() passing in the numbers read from the console not the DspAvg() function. Finally pass the returned value from CalcAvg() to DspAvg() to display the result to the console.
Start writing some code and if you are getting errors, then we will be able to help you more.

A: You are not using parameters as described in the assignment. Here is an example of using an out parameter with one method and sending it into another method and returning a value:
double parameter, result;
methodOne(out parameter);
result = methodTwo(parameter);

The methods:
static void methodOne(out double x) {
  x = 42;
}

static double methodTwo(double x) {
  return x;
}

That should get you started on how you need to modify your methods.

A: I will provide some suggestions, but this a very good introductory programming problem. I would very much recommend trying to solve this problem on your own as it uses basic programming concepts that you will use in the future.

*

*Your variables nu1, nu2, nu3, and cavg should be double values. An int can not be used to store decimal values. (Note: to get a value with 2 decimal places, you should use the Math.Round method)
double nu1, nu2, nu3, cavg;

*You seem to be stuck on how to pass paramaters to a method. For example, when you call the CalcAvg method in your main method, you should be passing the 3 values you read from the console into the method.
static void Main(string[] args){
    CalcAvg(nu1,nu2,nu3);
}

static void CalcAvg(double nu1, double nu2, double nu3){
}

By doing this, you can now manipulate the values within your CalcAvg method.

*Finally, once you have passed values into a method and manipulated them, you will want to return these values from the method. This can be done with the return statement. You can then call this method by passing in your paramaters and storing the returned value in another variable.
static void Main(string[] args){
    double cavg;
    cavg = CalcAvg(nu1,nu2,nu3);
}

static double CalcAvg(double nu1, double nu2, double nu3){
    double cavg;
    return cavg;
}

These three principles should help you complete this assignment. I STRONGLY recommend you do this assignment on your own and not copy the complete answer off of this or any other website. Learning these principles correctly will help you further down the road in your academic career. Good luck :)

A: I've made a few assumptions here. But I've gone ahead to give you a "working" app for you to consider
static void Main(string[] args)
    {
        int nu1, nu2, nu3, cavg;

        GetNums(out nu1, out  nu2, out nu3);
        double average = CalcAvg(nu1, nu2, nu3);
        DspAvg(average);

    }

    static void GetNums(out int nu1, out int nu2, out int nu3)
    {
        Console.Write("Please enter nu1: ");
        nu1 = int.Parse(Console.ReadLine());

        Console.Write("Please enter nu2: ");
        nu2 = int.Parse(Console.ReadLine());

        Console.Write("Please enter nu3: ");
        nu3 = int.Parse(Console.ReadLine());

    }

    static double CalcAvg(int nu1, int nu2, int nu3)
    {
        return (nu1 + nu2 + nu3) / 3;
    }

    static void DspAvg(double average)
    {
        Console.WriteLine(Math.Round(average, 2));
    }


text:
Q: how to use foreach with array object global $wpdb, $bp;
$result = $wpdb->get_results("SELECT user_id FROM wp_bp_xprofile_data WHERE value = '$_POST[language]' OR value = '$_POST[budget]' OR value = '$_POST[style]'LIMIT 0 , 30");
print_r($result);

The output is:
Array ( [0] => stdClass Object ( [user_id] => 2 )
        [1] => stdClass Object ( [user_id] => 2 )
        [2] => stdClass Object ( [user_id] => 2 )
        [3] => stdClass Object ( [user_id] => 4 ) )

I want the value as comma separated string.

A: get_results() will return an object. You can simply loop through the object and access the id using object notation, like so:
$arr = array();
foreach ($result as $k => $id) {
    $arr[] = $id->user_id;
}
$string = implode(',', $arr);

Alternatively, you can use get_col() instead:
$result = $wpdb->get_col("SELECT user_id
FROM wp_bp_xprofile_data
WHERE value = '$_POST[language]' OR value = '$_POST[budget]'
OR value = '$_POST[style]'LIMIT 0 , 300");

And now, to get the comma-separated string, use implode():
$string = implode(',', $result);

A: Use get_col of wpdb when you have to get one column
$result = $wpdb->get_col("SELECT user_id FROM wp_bp_xprofile_data WHERE value = '$_POST[language]' OR value = '$_POST[budget]' OR value = '$_POST[style]'LIMIT 0 , 30");

echo  implode(",",$result);
or

echo  join(",",$result);

A: hier is a possible solution;
<?php
    global $wpdb, $bp;
    $result = $wpdb->get_results("SELECT user_id FROM wp_bp_xprofile_data WHERE
                value = '$_POST[language]' OR value = '$_POST[budget]'
                OR value = '$_POST[style]'LIMIT 0 , 30");
    $str_ids = '';
    foreach($result as $r) {
         $str_ids .= ('' == $str_ids) ? '' : ', ';
         $str_ids .= $r->user_id;
    }
    print_r($str_ids);

A: Try this:
$str=implode(",",json_decode(json_encode($result),true));


text:
Q: Using Awesome window manager on CentOS 7 Awesome works fine on Fedora 19, so it should work on CentOS 7, right? Well, I tried and failed to get it to work.  After a long time, I managed to compile it from source and set GDM to boot from an ~/.xinitrc.  However, all I got was the window manager starting but none of the keybinds (keyboard or mouse) were working at all.
I am looking for a usable step by step installation procedure.

A: For Starters, I would remove the source you compiled, then add the official YUM Repo for Fedora, using the Steps from this post. Afterwards, since the repo you just added contains AwesomeWM, use YUM to install it.  See Here.

Reasoning:
It's nearly impossible to mix a source based package with a system based on binary packages, as you easily create a version mismatch.  Consider the following:

*

*Binary package Version A depends on and only works with dependency Version B.  Dependency Version B uses Library C.

*Connecting the Logic in 1, Binary Package Version A, also implicitly depends on Library C.

*You built dependency Version B with library Version D (If C = 1.0, D = 1.1)

*Dependency Version B built successfully, but Binary Package Version A is still linked to Library Version C, therefore Binary Package A, now loads unresolved symbols, because the symbols in Library Version C were replaced with newer symbols in Version D.

*Library Version D, superseded Library Version C, therefore the developer decided not to link his new Version D to Version C.

*To Fix this, every package on the system, that is linked to library Version C, must be recompiled using Library Version D.

You're Stuck Here because all the packages on a Binary System were prepackaged, and some or all of them will break, when compiled from source
You may be able to fix this by finding newer versions of all packages using Library Version D, but from experience, this is very unlikely, which is why I use Gentoo.

Update from Deleted Comments
I was asked to explain how to handle an out of date repo, and what to do if the repo expires, since CentOS, and Fedora are on radically different release schedules.
As per your questions in now deleted comments below, when adding a repository:

*

*If support for that repository ends, add the repository  that superseded it. i.e., Fedora 19's repo will be replaced by Fedora 20.

*After updating to the new repository, you must decide as a user which direction to take, as you will have version number mismatches between packages in the new repo. For Example in CentOS Library Version A will have been superseded by Library Version B in Fedora.  Having Added Fedora as a repo, if a package you want exists in Fedora, but NOT in CentOS, and it is asking for a newer version of a package, you must either a.) see if the same package exists in the CentOS Testing repo, or b.) allow the install to install the package from the Fedora repo.  In this way, you will have a mixed or hybrid install.  If you add the CentOS Testing repo in the same way you added the Fedora Repo above, I believe YUM will ask you which package you want to use, if the same package exists in both.

*If there is a Stable Library Version B in Fedora, and a Testing Library Version B in CentOS, use the Testing Version in CentOS, as that version is "native" to your OS.  Whenever possible, you want to install versions native to your OS, even if they are in Testing.  By doing so, if the package doesn't work you report a bug to your OS maintainers, so that the package stays in Testing until the bug is fixed before being moved to Stable

A: ⚠ All the answers here are OUTDATED and SHOULD NOT BE USED!!!

Awesome can be installed from source with a little tweaking.
; cat /etc/centos-release
CentOS Linux release 7.6.1810 (Core)
; awesome --version
awesome v4.2-dirty (Human after all)
 • Compiled against Lua 5.1.4 (running with Lua 5.1)
 • D-Bus support: ✔
 • execinfo support: ✔
 • xcb-randr version: 1.6
 • LGI version: 0.9.2


text:
Q: Is there any option handle popup using java with selenium which has HTML properties but hasn't any ok/accept/done button? I'm automating using java selenium
I open flipkart.com in google chrome and as soon as I click on grocery it is asking for verify delivery Pincode but there is no any ok/done button to perform the task. if I open the site manually same Pincode popup is coming and I enter the Pincode then I hit on Enter button it gets open.
I've tried using action class to hit on Enter button however IllegalArgumentException occurring

A: I have checked mentioned place and it seems that 'Submit' button is activated after a moment after typed code and some validation in background. You might need to add some wait for button to be clickable like here.
Then you can try clicking with xpath like:
//div[text() = 'Submit']

(As there are no many characteristic attributes around).
As for 'IllegalArgumentException' your code sample might be necessary.


text:
Q: How the list of application with tray icons is created
*

*There is C# application with trayIcon.

*In the windows settings the mode "show icon and notification" is set.

*Application is restarted ->
3.1 The new instance icon is hiden.
3.2 The setup window contains 2 items of my app  and the new has setup "show notification only"
The questions:
a) how this list is formed?
b) Where I am wrong?


text:
Q: How would one go about proving that the rationals are not the countable intersection of open sets? I'm trying to prove that the rationals are not the countable intersection of open sets, but I still can't understand why
$$\bigcap_{n \in \mathbf{N}} \left\{\left(q - \frac 1n, q + \frac 1n\right) : q \in \mathbf{Q}\right\}$$
isn't a counter-example. Any ideas? Thanks!

A: If by $\{ (q-1/n, q+1/n): q\in \mathbf{Q}\}$ you mean
$$ \bigcup_{q\in\mathbf{Q}} (q-1/n, q+1/n) $$
you will find that for each fixed $n$, that set is equal to $\mathbf{R}$, independently of $n$. So the intersection you wrote down is equal to $\mathbf{R}$
The usual proof that $\mathbf{Q}$ is not a countable intersection of open sets uses the Baire Category Theorem. The Irrational numbers can be written as a countable intersection of open, dense subsets:
$$ \mathbf{R}\setminus \mathbf{Q} = \bigcap_{q\in \mathbf{Q}} \mathbf{R}\setminus\{q\} $$
Since $\mathbf{Q}$ is dense, any open set containing it would necessarily be an open dense subset of $\mathbf{R}$. So if $\mathbf{Q}$ were to be able to be written as a countable intersection $\cap_{n\in \mathbf{N}}A_n$ with each $A_n$ open, $\mathbf{Q}$ would be a countable intersection of open, dense subsets of $\mathbf{R}$.
But then we would have
$$ \emptyset = (\mathbf{R}\setminus\mathbf{Q}) \cap \mathbf{Q} $$
is a countable intersection of open dense subsets, which contradicts the Baire Category Theorem.

A: The right way to do this is via the Baire Category Theorem, but it may be helpful to also give a more-or-less explicit construction.  Let $U_n, \ n=1,2,\ldots$ be a sequence of open sets, each containing the rationals $\mathbb Q$. I will find a member of $\bigcap_{n=1}^\infty U_n$ that is not in $\mathbb Q$. Let $r_n, \ n=1,2,\ldots$ be an enumeration of the rationals.  I will construct two sequences $a_n$ and $b_n, \ n= 1,2,\ldots$ such that
$a_n < a_{n+1} < b_{n+1} < b_n$, $(a_n, b_n) \subset U_n$, and $r_n \notin (a_n, b_n)$.  Namely, given $a_n$ and $b_n$, we can find a rational $c \ne r_{n+1}$ in $(a_n, b_n)$ and take $a_{n+1} = c - \delta$ and $b_{n+1} = c + \delta$ where $\delta>0$ is small enough that $(c-\delta, c+\delta) \subset U_{n+1}$, $c - \delta > a_n$, $c + \delta < b_n$ and  $\delta < |r_{n+1} - c|$.  Now the sequence $a_n$ is bounded above and increasing, so it has a limit $L$.  By construction, $L \in (a_n, b_n) \subset U_n$ for each $n$, i.e. $L \in \bigcap_{n=1}^\infty U_n$,   Moreover, $L \ne r_n$ for all $n$, so $L \notin \mathbb Q$, as required.


text:
Q: error: invalid input syntax for type timestamp I using pg node module to connect to PostgreSQL, and I am trying to execute this query:
  const res = await client.query(`SELECT number_transactions FROM transaction.city_unique_dates WHERE date_day_timestamp = TIMESTAMP '$1:value-$2:value-$3:value'`,
  ['2014', '04', '12'])
  console.log(res)

But I am getting the following error:
error: invalid input syntax for type timestamp: "$1:value-$2:value-$3:value"

Does anyone have an idea what's going wrong with timestamp ?
I am familiar with Node.js but less familiar with postgres
https://node-postgres.com/

A: You have to try this:
const res = await client.query(`SELECT number_transactions FROM
transaction.city_unique_dates WHERE date_day_timestamp = TIMESTAMP("2014-04-12")`)
console.log(res)


text:
Q: Use CreateProcess with environment variables set via a bat file I'm executing an external application using the CreateProcess function, in order which such application be executed I need run a .bat file before to set some environments variables. The issue is when i call CreateProcess to run the bat file and then execute CreateProcess again for run the external app the environment variables are not used. The question is how i can use the environment variables set in the bat file when I execute CreateProcess function the second time?

A: If the initial createprocess batch file is simply to setup the environment variables, create the enviornment variable block instead and pass it directly via the CreateProcess() call.
Some sample code is available here for getting/setting environment variables and for passing a block to CreateProcess()  http://www.delphidabbler.com/articles?article=6

A: You can use CreateProcess() to run the OS's cmd.exe program to execute multiple commands at one time, eg:
TCHAR szCmd[(MAX_PATH * 3) + 16] = {0};
TCHAR szPathToCmdExe[MAX_PATH+1] = {0}
GetEnvironmentVariable(TEXT("COMSPEC"), szPathToCmdExe, MAX_PATH+1);
wsprintf(szCmd, TEXT("\"%s\" /C \"%s && %s\""), szPathToCmdExe, szPathToBat, szPathToProgram);
CreateProcess(NULL, szCmd, ...);

A: If you execute the other application from the batch file it would have those environment variables set.  You could pass the executable name as a parameter to the batch file.   When you set environment variables within the batch file, they only exist until that batch file exits.


text:
Q: Ruby to C# expression how to convert to C#, the following Ruby expression:
  @fields.map(&:bit_size).reduce(&:+)

A: map is called Select in .NET, and reduce is called Aggregate. You can just translate it literally:
fields.Select(field => field.bitSize).Aggregate((a, b) => a + b);


text:
Q: Ubuntu 14.10 + SDCARD not mounted Upgraded from 14.04 to 14.10 and the SD card does not mount anymore.
What is the fix ? In 14.04 the exFAT fuse modules were installed and working. After the upgrade seeing that it can't see my files on SD I have removed the exFAT fuse and re-installed but that did not help.

A: This is a known bug of util-linux (libblkid1) that has already been fixed upstream but not in Ubuntu yet.
Please tag yourself as an affected user to speed up the bugfixing process:
https://bugs.launchpad.net/bugs/1389021

A: Is your cardreader kompatible with your SD-Card? If its possible, test your Card/Reader combi at other operating system (maybe Windows?) to see whether the card is mounting.

A: I encountered the same problem. Two 64GB exfat SD-Cards did not trigger the usual pop-up from the device notifier when inserted into the card reader.
The card reader did work before the upgrade from 14.04 to 14.10 with exactly the same cards.
I put one of the cards back into the camera where I originally did use them. It was mounted and all photos where still present.
So, the card still works too.
Then I connected the camera via USB and failed too, with an error message I didn't spend any time at all investigating.
I popped the card back into the card reader and looked at dmesg. It showed that the drive was present and the card found:
[185803.737955] sd 6:0:0:0: [sdd] 123860992 512-byte logical blocks: (63.4 GB/59.0 GiB)
[185803.741323]  sdd: sdd1

So I tried to mount the card on the terminal/console.
This resulted in following error message:
mount: /dev/sdd1: more filesystems detected. This should not happen,
       use -t <type> to explicitly specify the filesystem type or
       use wipefs(8) to clean up the device.

OK, I mounted it using -t exfat, and succeeded.
Mounting manually on the terminal/console is a viable workaround, but it is not really pretty and should not happen on a modern OS.
I'm really disappointed with the little nags 14.10 is showing so far. Nothing I wasn't able to overcome, but something I haven't seen in a while on Ubunut/Kubuntu


text:
Q: Issue using cocos2dx ui::TextField : textfield is not proper show in android device
textfield only show top upper side in android  my textfield is working
  proper in ios device but android device it is display upper top side i
  have attach screenshot

auto namewithPlates =  ui::Scale9Sprite::create("text_field.png");
        namewithPlates->setAnchorPoint(Point(.53,.5));

        auto tempplt =  ui::Scale9Sprite::create("text_field.png");
        tempplt->setScale(ratinaScaleX);

        f_editemail = ui::EditBox::create(tempplt->getBoundingBox().size, namewithPlates);

        f_editemail->setPosition(Point(plates->getPosition().x,signwithPlates->getPosition().y-signwithPlates->getBoundingBox().size.height/2 -tempplt->getBoundingBox().size.height/2));//added 11 Aug 2015s

        f_editemail->setFont(fRockoUltraFLFBold, 20*ratinaScaleX);//Added 11 Aug 2015
        f_editemail->setPlaceholderFont(fRockoUltraFLFBold, 20*ratinaScaleX);//Added 11 Aug 2015
        f_editemail->setPlaceHolder("Email");
        f_editemail->setPlaceholderFontColor(Color3B::RED);
        f_editemail->setFontColor(TextColor);////Added 11 Aug 2015
        mainLayer->addChild(f_editemail);
        f_editemail->setLocalZOrder(4);//added 10 Aug 2015
        f_editemail->setReturnType(ui::EditBox::KeyboardReturnType::DONE);
    auto namewithPlates =  ui::Scale9Sprite::create("text_field.png");
        namewithPlates->setAnchorPoint(Point(.53,.5));

        auto tempplt =  ui::Scale9Sprite::create("text_field.png");
        tempplt->setScale(ratinaScaleX);

        f_editemail = ui::EditBox::create(tempplt->getBoundingBox().size, namewithPlates);

        f_editemail->setPosition(Point(visibleSize/2));//added 11 Aug 2015s

        f_editemail->setFont(fRockoUltraFLFBold, 20*ratinaScaleX);//Added 11 Aug 2015
        f_editemail->setPlaceholderFont(fRockoUltraFLFBold, 20*ratinaScaleX);//Added 11 Aug 2015
        f_editemail->setPlaceHolder("Email");
        f_editemail->setPlaceholderFontColor(Color3B::RED);
        f_editemail->setFontColor(TextColor);////Added 11 Aug 2015
        mainLayer->addChild(f_editemail);
        f_editemail->setLocalZOrder(4);//added 10 Aug 2015
        f_editemail->setReturnType(ui::EditBox::KeyboardReturnType::DONE);
    }

1.image1 is ios screenshot
2.image2 is android device


text:
Q: Google Calendar: How to check guest is not busy and available to book through google calendar I am exploring to write google calendar api integration through google scripts or apis.
Is there a way I can check a guest is available before I book an event ?

A: I did this in google script using freebusy api like this
  var resource = {
    timeMin: timeMin,
    timeMax: timeMax,
    items: [
      {
        id: calendarId
      }
    ]
  };

  var response = Calendar.Freebusy.query(resource);
  return response.calendars[calendarId]['busy'].length == 0;


text:
Q: Superscript in CSS only? How can I get superscript done, only in CSS?
I have a stylesheet where I mark the external links with a superscript character, but I'm having a hard time getting the character aligned correctly.
What I have currently, looks like this:
a.external:after {
  font-size: 50%;
  vertical-align: top;
  content: "+";
}

but it doesn't work.
Naturally, I'd use the -tag, only if content would allow for HTML...

A: This is another clean solution:
sub, sup {vertical-align: baseline; position: relative; font-size: 70%;} /* 70% size of its parent element font-size which is good. */
sub {bottom: -0.6em;} /* use em becasue they adapt to parent font-size */
sup {top: -0.6em;} /* use em becasue they adapt to parent font-size */

In this way you can still use sup/sub tags but you fixed their idious behavior to always screw up paragraph line height.
So now you can do:

This is a line of text.

This is a line of text, with sub text.

This is a line of text, with sup text.

This is a line of text.

And your paragraph line height should not get screwed up.
Tested on IE7, IE8, FF3.6, SAFARI4, CHROME5, OPERA9
I tested using a p {line-height: 1.3;} (that is a good line height unless you want your lines to stick too close) and it still works, cause "-0.6em" is such a small amount that also with that line height the sub/sub text will fit and don't go over each other.
Forgot a detail that might be relevant I always use DOCTYPE in the 1st line of my page (specifically I use the HTML 4.01 <!DOCTYPE html PUBLIC "-//W3C//DTD HTML 4.01 Transitional//EN" "http://www.w3.org/TR/html4/loose.dtd">). So I don't know if this solution works well when browser is in quirkmode (or not standard mode) due to lack of DOCTYPE or to a DOCTYPE that does not triggers Standard/Almost Standard mode.

A: You can do superscript with  vertical-align: super, (plus an accompanying font-size reduction).
However,  be sure to read the other answers here, particularly those by paulmurray and cletus, for useful information.

A: If you are changing the font size, you might want to stop shrinking sizes with this rule:
sup sub, sub sup, sup sup, sub sub{font-size:1em !important;}

A: I was working on a page with the aim of having clearly legible text, with superscript elements NOT changing the line's top and bottom margins - with the following observations:
If for your main text you have line-height: 1.5em for example, you should reduce the line-height of your superscript text for it to appear correctly. I used line-height: 0.5em.
Also, vertical-align: super works well in most browsers but in IE8 when you have a superscript element present, the rest of that line is pushed down. So instead I used vertical-align: baseline together with a negative top and position: relative to achieve the same effect, which seems to work better across browsers.
So, to add to the "homegrown implementations":
.superscript {
    font-size: .83em;
    line-height: 0.5em;
    vertical-align: baseline;
    position: relative;
    top: -0.4em;
}

A: Honestly I don't see the point in doing superscript/subscript in CSS only.  There's no handy CSS attribute for it, just a bunch of homegrown implementations including:
.superscript { position: relative; top: -0.5em; font-size: 80%; }

or using vertical-align or I'm sure other ways.  Thing is, it starts to get complicated:

*

*CSS superscript spacing on line height;

*Beware CSS for Superscript/Subcript on why you arguably shouldn't style superscript/subscript with CSS at all;

The second point is worth emphasizing.  Typically superscript/subscript is not actually a styling issue but is indicative of meaning.
Side note: It's worth mentioning this list of entities for common mathematical superscript and subscript expressions even though this question doesn't relate to that.
The sub/sup tags are in HTML and XHTML.  I would just use those.
As for the rest of your CSS, the :after pseudo-element and content attributes are not widely supported.  If you really don't want to put this manually in the HTML I think a Javascript-based solution is your next best bet.  With jQuery this is as simple as:
$(function() {
  $("a.external").append("+");
};

A: The CSS property font-variant-position is under consideration and may eventually be the answer to this question. As of early 2017, only Firefox supports it, though.
.super {
    font-variant-position: super;
}

See MDN.

A: try
.aftersup {
 font-size: 1em;
 margin: left;
 vertical-align: .7em;
}

or plain "after"
.after {
 font-size: 1em;
 margin: left;
 vertical-align: .7em;
}

".a.external:after" could be simplified
or
.after {
 font-size: 50%;
 margin: left;
 vertical-align: .7em;
}

using "font size 50%" - 50% of what size? this might not work well if not used within some tag defining text size previous to superscript...
if you use "font-size: 1em;"  then the font size is set for sure, without reference to a tag that defines link text size, unless link text is set at 100% and superscript is 50% of that 100%.
Using "font-size: 1em;" actually sets font size baseline.
Set "vertical-align" size smaller, if you want superscript font to be smaller than link text
Set "vertical-align" size same as font size, if you want superscript font to be same size as link text
To align with link text, you need to set "margin" same as link text (left, center, right, justified).
.text {
  font-size: 1em;
  margin: left;
}
.aftersup {
  font-size: 1em;
  margin: left;
  vertical-align: .7em;
}

It should be something like below example links with superscript

https://stackoverflow.com/questions/501671/superscript-in-css-only<aftersup>+</aftersup>

or

https://stackoverflow.com/questions/501671/superscript-in-css-only<aftersup>You got this</aftersup>

or
https://stackoverflow.com/questions/501671/superscript-in-css-only<aftersup>+</aftersup>

or
https://stackoverflow.com/questions/501671/superscript-in-css-only<aftersup>You got this</aftersup>

As in...
Superscript in CSS only?+
or
Superscript in CSS only?You got this

A: http://htmldog.com/articles/superscript/ Essentially:
position: relative;
bottom: 0.5em;
font-size: 0.8em;

Works well in practice, as far as I can tell.

A: The following is taken from Mozilla Firefox's internal html.css:
sup {
  vertical-align: super;
  font-size: smaller;
  line-height: normal;
}

So, in your case it would be something, like:
.superscript {
  vertical-align: super;
  font-size: smaller;
  line-height: normal;
}

A: The CSS documentation contains industry-standard CSS equivalent for all HTML constructs. That is: most web browsers these days do not explicitly handle SUB, SUP, B, I and so on - they (kinda sorta) are converted into SPAN elements with appropriate CSS properties, and the rendering engine only deals with that.
The page is Appendix D. Default style sheet for HTML 4
The bits you want are:
small, sub, sup { font-size: .83em }
sub             { vertical-align: sub }
sup             { vertical-align: super }

A: Check out: http://www.cssdesignpatterns.com/Chapter%2012%20-%20ALIGNING%20CONTENT/Vertical-aligned%20Content/example.html
if looks like you want "vertical-align:text-top"

A: I am not sure if this is related but I have solved my problem with  ² HTML entities as I wasn't able to add any other html tags inside a  tag. So the idea was using ASCII codes instead of css or HTML tags.

A: .superscript {
  position: relative;
  top: 5px;
  font-size: 90%;
  vertical-align: super;
}

A: Here's the exact way sup uses:
.superscript{
    vertical-align:super;
    font-size:smaller;
}

Found this via google chrome inspect element.

A: Related or maybe not related, using superscript as a HTML element or as a span+css in text might cause problem with localization - in localization programs.
For example let's say "3rd party software":
3rd party software
3rd party software

How can translators translate "rd"? They can leave it empty for several cyrrilic languages, but what about of other exotic or RTL languages?
In this case it is better to avoid using superscripts and use a full wording like "third-party software".
Or, as mentioned here in other comments, adding plus signs in superscript via jQuery.


text:
Q: AngularJS Custom Filter in ng-repeat doesn't get pushed Objects I have a problem with my custom filter function in angular.
This is the filter function:
.filter('itemFilter', function($rootScope) {

        return function(input) {
            var filtered = [];
            angular.forEach(input, function(item) {
                if(item.user_id === $rootScope.userData._id && item.active === true){
                    filtered.push(item);
                }
            });
            //console.log(filtered);
            return filtered;
        }

    });

The filter does what it should do, but when i want to push a new Object in the item Array, the filter does not get the new Object. The new Item is pushed in the array correctly, though.
This is where the item is pushed in the DB and in the rootScope. The function is located inside a factory and called in the controller.
Function in the factory:
var addItem = function(item){
            $http.post("http://localhost:3333/items", item)
                .success(function (response) {
                    $rootScope.items.push(item);
                    $log.debug(response);
                })
                .error(function (err){
                    $log.error("item was not added: "+err);
                });
        };

Call of the function in the controller:
    $scope.itemObj = {"user_id": $rootScope.userData._id, "group_id": $rootScope.userData.group_id};

    $scope.addItem = function() {
        console.log($scope.itemObj);
        dataFactory.addItem($scope.itemObj);
        $modalInstance.close();
        $scope.itemObj = {"user_id": $rootScope.userData._id, "group_id": $rootScope.userData.group_id};
    };

The whole array with all items is located in the rootScope.
This is the part where I call the ng-repeat:

        {{item.amount}}
        {{item.name}}
        {{item.price | currency:"EUR€ "}}
        {{item.list}}
        Edit
        Delete

            Bought

NO

YES

Is there any way to tell the filter, that a new item has been added to the array? After reloading the page, everything works fine, because the filter gets the whole items array.

A: I think i fixed the problem.
Instead of pushing the 'item' into the array I am now pushing the 'response' into it.
var addItem = function(item){
        $http.post("http://localhost:3333/items", item)
            .success(function (response) {
                $rootScope.items.push(response);
                $log.debug(response);
            })
            .error(function (err){
                $log.error("item was not added: "+err);
            });
    };

The pushed response has an now '_id'-value (which is generated by the MonogDB). I am not sure if the missing id was the problem.
Maybe you have an answer for that.
Thanks anyway for the quick responses.


text:
Q: Bootstrap: extra width on exact same div I'm trying to fix a peculiar problem I'm having in Bootstrap 3. It's my first time using it, so maybe I'm missing something.
Basically, at the bottom of my page I have a news section which is correctly displayed on all but "extra small" devices.
This is how it looks on small to large devices:

And this is what it looks like on an extra small device:

As you can see, the top div is now larger than the bottom ones, for no apparent reason (I think). It is 30 pixels wider.
Even when removing all of the blue div's content, it remains wider, so it's not the elements inside.
Here's my HTML:

 News

        from us
        <form class="form-articles">

            Number of articles:
            <select class="form-control" id="sel1">
              <option value="3">3</option>
              <option value="5">5</option>
              <option value="10">10</option>
              <option value="all">Alle</option>
            </select>

        </form>

New order mechanism!

            Lorem ipsum dolor sit amet, consectetur adipisicing elit. Aliquam, minus, eum quam adipisci saepe, unde asperiores nesciunt blanditiis similique nisi explicabo. Deserunt alias maxime nemo cupiditate, veritatis recusandae quasi nostrum.

01/09/2015

Open every day in August

             Lorem ipsum dolor sit amet, consectetur adipisicing elit. Enim consectetur, voluptatibus maiores totam delectus tempora exercitationem ad numquam, cupiditate, nisi quo expedita veniam repudiandae! Nam ipsum aperiam, recusandae maiores at.

01/08/2015

And here's my (relevant) CSS:
.rowspacer {
  margin-top: 40px;
}

.bs-callout {
  -moz-border-bottom-colors: none;
  -moz-border-left-colors: none;
  -moz-border-right-colors: none;
  -moz-border-top-colors: none;
  /*border-color: #eee;*/
  border-color: #E1E1E1;
  border-image: none;
  border-radius: 3px;
  border-style: solid;
  border-width: 1px 1px 1px 5px;
  margin-bottom: 7px;
  padding: 20px;
  background-color: #fff;
}

.bs-callout-danger {
  border-left-color: #d9534f;
}

.bs-callout-blueborder {
  border-left-color: #325d88;
}

.news-subtitle {
  margin-left: 19px;
}

.form-articles {
  margin-top: 22px;
}

Thanks!

A: Your bs-callout markup isn't consistent. Your first callout is the bootstrap column, whereas the other 2 are descendants of their column.
Put your first callout within the column, as a new element:

 News

      from us
      <form class="form-articles">

          Number of articles:
          <select class="form-control" id="sel1">
            <option value="3">3</option>
            <option value="5">5</option>
            <option value="10">10</option>
            <option value="all">Alle</option>
          </select>

      </form>

New order mechanism!

        Lorem ipsum dolor sit amet, consectetur adipisicing elit. Aliquam, minus, eum quam adipisci saepe, unde asperiores nesciunt blanditiis similique nisi explicabo. Deserunt alias maxime nemo cupiditate, veritatis recusandae quasi nostrum.

01/09/2015

Open every day in August

         Lorem ipsum dolor sit amet, consectetur adipisicing elit. Enim consectetur, voluptatibus maiores totam delectus tempora exercitationem ad numquam, cupiditate, nisi quo expedita veniam repudiandae! Nam ipsum aperiam, recusandae maiores at.

01/08/2015

JSFiddle

A: jsfiddle

 News

        from us
        <form class="form-articles">

            Number of articles:
            <select class="form-control" id="sel1">
              <option value="3">3</option>
              <option value="5">5</option>
              <option value="10">10</option>
              <option value="all">Alle</option>
            </select>

        </form>

New order mechanism!

            Lorem ipsum dolor sit amet, consectetur adipisicing elit. Aliquam, minus, eum quam adipisci saepe, unde asperiores nesciunt blanditiis similique nisi explicabo. Deserunt alias maxime nemo cupiditate, veritatis recusandae quasi nostrum.

01/09/2015

Open every day in August

             Lorem ipsum dolor sit amet, consectetur adipisicing elit. Enim consectetur, voluptatibus maiores totam delectus tempora exercitationem ad numquam, cupiditate, nisi quo expedita veniam repudiandae! Nam ipsum aperiam, recusandae maiores at.

01/08/2015

Css
.rowspacer {
  margin-top: 40px;
}

.bs-callout {
  -moz-border-bottom-colors: none;
  -moz-border-left-colors: none;
  -moz-border-right-colors: none;
  -moz-border-top-colors: none;
  /*border-color: #eee;*/
  border-color: #E1E1E1;
  border-image: none;
  border-radius: 3px;
  border-style: solid;
  border-width: 1px 1px 1px 5px;
  margin-bottom: 7px;
  padding: 20px;
  background-color: #fff;
}

.bs-callout-danger {
  border-left-color: #d9534f;
}

.bs-callout-blueborder {
  border-left-color: #325d88;
}

.news-subtitle {
  margin-left: 19px;
}

.form-articles {
  margin-top: 22px;
}


text:
Q: Change mouse cursor while left mouse button is pressed? I need to change the mouse cursor while the left mouse button is pressed. Unfortunately changes to the mouse cursor are ignored until the left mouse button is released. Is there any workaround to this? Thanks for any hint!
(I'm using WPF and C#)
EDIT:
Sample Project:
http://cid-0432ee4cfe9c26a0.skydrive.live.com/self.aspx/%c3%96ffentlich/WpfApplication5.zip
(just run it, instructions are shown in the application)
Code for the sample:
XAML:
<Window x:Class="WpfApplication5.MainWindow"
    xmlns="http://schemas.microsoft.com/winfx/2006/xaml/presentation"
    xmlns:x="http://schemas.microsoft.com/winfx/2006/xaml"
    Title="MainWindow" Height="350" Width="695" Loaded="Window_Loaded">
<Grid>
    <Button Content="Button1" Height="287" HorizontalAlignment="Left" Margin="12,12,0,0" Name="button1" VerticalAlignment="Top" Width="235" />
    <Button Content="Button2" Height="287" HorizontalAlignment="Left" Margin="284,12,0,0" Name="button2" VerticalAlignment="Top" Width="278" MouseMove="button2_MouseMove" />
</Grid>

Window class:
public partial class MainWindow : Window
{
    public MainWindow()
    {
        InitializeComponent();
    }

    private void button2_MouseMove(object sender, MouseEventArgs e)
    {
        Cursor = Cursors.Cross;
    }

    private void Window_Loaded(object sender, RoutedEventArgs e)
    {
        button1.Content="Step1: Left click on this button, \nhold down the left mouse button";
        button2.Content = "(Make sure you don't hover this\n button before hovering Button1.\n Default application cursor\n is the normal arrow cursor)\n\n Step 2: Keep on holding the left mouse \nbutton, hover this button\n\nThe cursor won't change. (It will change after the \nleft mouse button was released)";
    }
}

A: I would recommend using Preview* events where possible for visual changes, as it will keep your logic nicely separated. Also, it is best (IMHO) to use the Mouse.OverrideCursor property to change the cursor temporarily.
For example:
void Window_Loaded(object sender, RoutedEventArgs e)
{
    // ...
    button1.PreviewMouseLeftButtonDown += Button1_PreviewMouseLeftButtonDown;
    button1.PreviewMouseLeftButtonUp += Button1_PreviewMouseLeftButtonUp;
}

void Button1_PreviewMouseLeftButtonDown(object sender, MouseButtonEventArgs e)
{
    Mouse.OverrideCursor = Cursors.Cross;
    Mouse.Capture(button1);
}

void Button1_PreviewMouseLeftButtonUp(object sender, MouseButtonEventArgs e)
{
    Mouse.Capture(null);
    Mouse.OverrideCursor = null;
}

A: In left mouse down handler you can have following code.
try
{
   Cursor = Cursors.WaitCursor;
}
catch(Exception ex)
{
}
finally
{
   Cursor = Cursors.Default;
}

You can reset to Default cursor as per your requirement.


text:
Q: Evento Boton Java Eclipse alguien me podría ayudar para la inserción de un evento clic y pueda darme acceso a otra ventana donde guarde dicha variable.
despues de ejecutar el codigo se abre la ventana donde se escribe el usuario, se da aceptar abre el jfilechooser para cargar archivos, pero en la consola me da un error.
¿donde sería más apropiado poner el evento de clic?
agradezco si alguien me podría orientar :d
private void initialize() {
    frame = new JFrame();
    frame.setBounds(200, 200, 500, 400);
    frame.setDefaultCloseOperation(JFrame.EXIT_ON_CLOSE);

    DemoJFileChooser panel = new DemoJFileChooser();

    JPanel user = new JPanel();
    frame.add(user);
    placeComponents(user);
    frame.setVisible(true);

    frame.getContentPane().add(panel,"Center");
    frame.setSize(panel.getPreferredSize());
    frame.setVisible(true);
}
private static void placeComponents(JPanel user){

    user.setLayout(null);

    JLabel userLabel = new JLabel("Usuario");
    userLabel.setBounds(10, 10, 80, 25);
    user.add(userLabel);

    JTextField userText = new JTextField(20);
    userText.setBounds(100, 10, 160, 25);
    user.add(userText);
}

public class DemoJFileChooser extends JPanel
   implements ActionListener {

    private static final long serialVersionUID = 1L;

    JPanel user = new JPanel();

    JLabel message = new JLabel("");
    JButton go;

    JFileChooser chooser;
    String choosertitle;

  public DemoJFileChooser() {
    go = new JButton("INGRESAR");
    go.addActionListener(this);
    add(user);
    add(go);
    add(message);
  }

En el segundo codigo guarde el nombre que ingrese el usuario
public class App extends Window {
private static String path;
public static void daemon() throws Exception{
    System.out.println("Conecting to server ....");
    RSync rsync = new RSync();
    //VARIABLE QUE SE GUARDA DESDE EL OTRO CODIGO
    String variable="";
    rsync.setOptions(new String[]{"-avz","-e","ssh",path,variable+"@192.168.2.219:rsync"});
    ConsoleOutputProcessOutput output = new ConsoleOutputProcessOutput();
    output.monitor(rsync.builder());
}


text:
Q: Why do we hate fun at Stack Exchange? Fun is Important™. Yet, we at Stack Exchange tend to hate it (edit it out, close it as not useful, etc.), unless it's in "irrelevant" places like chat and the comments section.
As long as it doesn't detract from the question at hand (meaning, the question minus the fun would still be valid) or otherwise impede the site's ability to function, why should we actively (or even passively) punish the programmer's/sysadmin's/whoever's sense of humor?
Some users (like myself) enjoy a small bit of humor in a question to break up the monotony. Dealing with the same boring flags in the VLQ queue is boring.

For the sake of argument, let's define fun as:

*

*Our Lord and Savior, Jeff Atwood

*[insert pop culture reference]

*Hamsters (although this is a joke question itself, so it's slightly different)

*Anything extra to make things less boring.

A: I think that canonical article thoroughly explaining these matters based on real experience of running Stack Overflow is The Trouble With Popularity by Jeff Atwood:

we discovered that these posts become so popular over time that they truly start to drown out everything else on the site...

*

*Broken windows. Every 'fun' post users see is an open invitation for them to participate in the fun by adding their own fun question or answer. The stuff spreads like kudzu! Pretty soon the entire site is overrun with nothing but that kind of fun. And even if you grandfather a few in, you'll enjoy neverending requests asking why their fun question or answer has to be removed, while this one over here is allowed to remain.

*Opportunity cost. Every minute spent participating in an entertaining 'fun' post is time that someone could have spent asking or answering a substantive question, something practical that solves an actual problem for hundreds or thousands of people. Entertainment, within reason, is by no means a bad thing -- but I experience almost physical pain when I think about a brilliant topic expert spending 10 minutes on one of our sites deciding which hilarious cartoon is their favorite.

A: Like @JourneymanGeek said, it just shouldn't get too much in the way of actual content. This site is a little bit (although certainly not quite) like a wiki. Can you imagine if Wikipedia was full of jokes all over the place?
I've found that people generally don't have a problem with a few jokes here and there. For example, the last sentence of this question at Biology SE. Nobody tried to remove that. Or this question from SF&F. It's the third higest scoring question in the history of that site. Those are just two of countless examples. People write jokes into posts all the time. As long as it doesn't take away too much attention from the actual post, it's usually not a problem.
Moreover, there's comments. Having fun is far from "hated" in comments.

Answer link.
People make jokes and have fun in comments all the time. Sure, sometimes they are deleted or moved to chat, but that doesn't prevent you from having fun while they're still there. And often, as in the example above, they get to stay.
So, people don't hate fun here. As a matter of fact, I think we generally rather like it. Just not if it gets significantly in the way of content.

A: The simple answer is because most people are not that funny. The occasional antic or funny satire would be a nice diversion… if it weren't for the human compulsion for everyone to join in. That is how memes start. Once it gets started, it's hard to stop — and soon you have everyone trying to one-up the next guy.
Stack Exchange is supposed to be an information-rich resource, not an entertainment club. Personal flourishes, grandstanding, and pandering to the crowd have a tendency to draw attention (and votes) away from the actual content.
These distractions were eliminated from Stack Exchange from the earliest days (e.g. why we standardized user flair instead of allowing free-form signature blocks). It was an answer to traditional threaded discussion forums where it is all-too-easy for folks to wander off on a tangent — and maybe finally arrive at the correct answer somewhere at the bottom of page 11.
This high-signal, low-noise premise and architecture is central to what makes Stack Exchange "work". That is by design.

A: The 'core' of a quality question is the facts - it's counter productive if the main issue on hand is overwhelmed by a bunch of unnecessary information or a tide of comments. I don't want to read your life story. I want the essential information so that I can answer your question, and hopefully get myself some lovely imaginary internet points.
If you write a question that's awesome and has humour in places which the target audience gets, it's likely to be better received. So, questions with minor jokes in them good. Jokes with minor questions in them bad. Questionable jokes with minors in them... No Just No.
It's pretty hard to write a question, like the one above as a joke
From my experience (and I have a reasonable amount of it), it's pretty hard to do.
Answers on the other hand have some room for humour, especially used for what's called a teaching moment. I've slipped in memes (which some users flagged. On a site where I'm a mod, and I chose to let someone else handle it - question deleted, for unrelated reasons), and done other funny stuff but even then no noise is good noise
So, we hate fun where it's in the way of the primary role of the site.
If you can write a funny question, with minimal noise, you're clearly on the way to a good many repcaps.

A: Getting to the top of the sites in reputation is work, and tremendous work. Not only a lot of work of writing answers, but also a lot of work to accustoming its standards and customs, what includes also a lot of network-building.
This results that the top users of most sites have a specific mindset, what is tuned for get to a high reputation fast. "High reputation" means here both the reputation as points, and the reputation in the sense of the acceptance of the other top users.
This results that the mindset of the top users of the sites have a surprisingly low diversity: talking to them, I had often the feeling that I am talking actually to the same person.
It is like if you would talk to a professional sportsman. You could talk with him a lot about his sport, but he probably wouldn't find your jokes about his sport funny.
They tend to be also highly protective, territorial.
Particularly in @gnat's answer can you see this: He feels himself in a world, where fun has to be forbidden, or the site will sink in the mess of fun.


text:
Q: Finding first and last occurence of substring and replace them with re.sub()  import re

    def x(s):
        if re.match(r'^o|non', s):
            return re.sub(r'o|non', '', s, count=1)
        elif re.search(r'e|er|est$', s):
            return re.sub(r'(.*)e|er|est', r'\1''', s)

So if the string starts with 'o' or 'non' the first occurence of one of those two will be replaced by ''. Or if the string ends with e, er or est that ending will be replaced by ''.
How can I write all this into one, so that if the string starts with 'non' and end with 'est' it will replace both of those and return the middle of the string. Also, I can't get this (r'(.*)e|er|est', r'\1''', s) to work, it only replaces the last e even if the string ends with 'est'. Am I missing something or is the '|' not the way to go?

A: You do not have to check for a mach first and you can chain both substitutions. Finally the end of a string is indicated by a $ in regular expressions
 re.sub(r'e$|est$|er$' , '', re.sub(r'^o|^non','',s))


text:
Q: Vector version of do for/while loop I'd like to be able to write a cleaner way of doing the following:
I have a data.frame P (5000rows x 4cols) and would like to find the median values in columns 2,3 and 4 when the time-stamp in column 1 falls into a set range determined by a vector TimeStamp (in seconds).
dput(TimeStamp)
c(18, 138, 438, 678, 798, 1278, 1578, 1878, 2178)

dput(head(P))
structure(list(Time = c(0, 5, 100, 200, 500, 1200), SkinTemp = c(27.781,
27.78, 27.779, 27.779, 27.778, 27.777), HeartRate = c(70, 70,
70, 70, 70, 70), RespirationRate = c(10, 10, 10, 10, 10, 10)), .Names = c("Time",
"SkinTemp", "HeartRate", "RespirationRate"), row.names = c(NA,
6L), class = "data.frame")

e.g.
for x<i<y in P[,1]
     find median of all values in P[,2], P[,3] and P[,4]
     Put median values into a new matrix with headers SkinTemp, HeartRate and RespirationRate
end

A: You can try:
aggregate(P[,-1],list(Time=findInterval(P$Time,TimeStamp)),median)
#  Time SkinTemp HeartRate RespirationRate
#1    0  27.7805        70              10
#2    1  27.7790        70              10
#3    2  27.7790        70              10
#4    3  27.7780        70              10
#5    5  27.7770        70              10

You want to divide the Time values according to the interval they fall into. There is an R function that does this: findInterval. So, we calculate the interval for each Time value and then aggregate the values of the other columns and calculate the median.

A: Another option would be to use the cut function
P$new <- cut(P$Time, breaks = c(-Inf, TimeStamp, Inf))
aggregate(. ~ new, P, median)

#             new   Time SkinTemp HeartRate RespirationRate
#1      (-Inf,18]    2.5  27.7805        70              10
#2       (18,138]  100.0  27.7790        70              10
#3      (138,438]  200.0  27.7790        70              10
#4      (438,678]  500.0  27.7780        70              10
#5 (798,1.28e+03] 1200.0  27.7770        70              10


text:
Q: What can we say about term by term derivative of power series at boundary points? Can a power series be differentiated term by term at the end point provided the power series converges at one of its endpoints and the derived series also converges at that end point.And if a power series is not convergent at one of its endpoints,then can the derived series be convergent at that point.If not,then why?
Can we prove it using only knowledge of differentiation,I was thinking something like domain of derived function is a subset of the domain of function.Is it correct?
Can I use the fact that $f$ is a function differentiable on $(a,b)$ and $f $ is defined on $[a,b]$ such that $\lim_{x\to b} f'(x)$ exists then $f$ is differentiable at $b$ and $f'(b)=\lim_{x\to b} f'(x)$.By the way is this statement true if $f$ is not continuous at $b$.I think true because We can use L Hospital's rule here.
Now if the derived power series were convergent at the end $R$ say.Now extend $f$ to $(-R,R]$ by assigning any value at $R$,not necessarily a continuous extension.Now $f'$ has limit at $R$ by Abel's theorem.So by the above theorem $f$ is differentiable at $R$ and $f'(R)=\lim_{x\to R} f'(x)=\sum{na_nR^{n-1}}$.Since,f is differentiable at $R$, $f$ is continuous at $R$.But we had assigned an arbitrary value at $R$.So $f$ need not be continuous at $R$,thus we have a contradiction.So,the derived series is not convergent at $R$.


text:
Q: Mysql select query to get FIND_IN_SET The following query works good.
SELECT FIND_IN_SET('b','a,b,c,d');
// output -> 2

I need to fetch the record having multiple options. Just for an example,
SELECT FIND_IN_SET('b,c','a,b,c,d');
// output -> ??????????

Please how do i get the record with multiple selection option "b,c" in "a,b,c,d".

A: mysql function find_in_set can search only for one string in a set of strings.
the second its not a string in set of  strings
take a look here
edit:
to change the mode
This can be done in two ways...
1- Open your "my.ini" file within the MySQL installation directory, and look for the text "sql-mode".
Find:
Code:
Set the SQL mode to strict sql-mode="STRICT_TRANS_TABLES,NO_AUTO_CREATE_USER,NO_ENGINE_SUBSTITUTION"
Replace with:
Code:
Set the SQL mode to strict sql-mode="NO_AUTO_CREATE_USER,NO_ENGINE_SUBSTITUTION"
Or
2- You can run an SQL query within your database management tool, such as phpMyAdmin:
Code:
 SET @@global.sql_mode= '';


text:
Q: I have no idea on how to check for matching numbers I'm fairly new to C# and was tasked recently with creating a basic lottery program that allows the user to enter six numbers, this is then checked against a table that displays 52 weeks worth of lottery numbers each with 6 numbers. I have this portion of the code done however there is another task that requires me to choose the week in which the user had the most matches and this is where my code skills are really lacking. Any help is appreciated and thanks in advance.
static void Main(string[] args)
{
    int[] thelottery = new int[52];
    int[] usernumbers = new int[6];
    Random rnd = new Random();

    Console.Write("Please enter six numbers for the lottery: \n");
    usernumbers[0] = Convert.ToInt32(Console.ReadLine());
    usernumbers[1] = Convert.ToInt32(Console.ReadLine());
    usernumbers[2] = Convert.ToInt32(Console.ReadLine());
    usernumbers[3] = Convert.ToInt32(Console.ReadLine());
    usernumbers[4] = Convert.ToInt32(Console.ReadLine());
    usernumbers[5] = Convert.ToInt32(Console.ReadLine());

    Console.WriteLine("\nYour numbers are: ");
    for (int i = 0; i < 6; i++)
    {
        Console.Write("{0} ", usernumbers[i]);
    }

    Console.Write("\n\nPress any key to view the results of the lottery: ");
    Console.ReadKey();

    for (int limit  = 0; limit < 52; limit++)
    {
        for (int weeks = 0; weeks < 6; weeks++)
        {
            thelottery[weeks] = rnd.Next(49) + 1;
            Console.Write("\t{0} ", thelottery[weeks]);

        }
        Console.WriteLine();
    }

    Console.WriteLine("\n\nYour week with the most matches was...");

    Console.WriteLine("\n\nPress any key to continue: ");
    Console.ReadKey();
}

A: Break the problem down into simple steps. You need to know which week the user had the most matches.
To do that you need to know

*

*How many matches the user had each week?

*What was the highest number of matches for that year (and which week it was in)?

Think about what data you need. In a simple program like this, I would probably store the number of matches against the week number i.e.
week 1 : 0 matches
week 2 : 3 matches
week 4 : 6 matches... Woohoo!
and so on.
In C#, the easiest way to do this is to use a Dictionary<int, int>.
That should be enough for you to figure out the rest yourself.

A: In the case you need a reference solution:
    Console.Write("\n\nPress any key to view the results of the lottery: ");
    Console.ReadKey();

    int best_week = 0;
    int best_matches = 0;

    /* Compute lottery numbers for 52 weeks */
    for (int limit  = 0; limit < 52; limit++)
    {
        /* Compute the 6 lottery numbers for this week */
        for (int weeks = 0; weeks < 6; weeks++)
        {
            thelottery[weeks] = rnd.Next(49) + 1;
            Console.Write("\t{0} ", thelottery[weeks]);
        }

        /* Compute the amount of matches for this week. */
        int matches = 0;
        //Check each usernumber with each lottery number for a match
        for(int i=0; i < 6; i++)
        {
            //e.g. for i=0, check how many times usernumbers[0] appears in thelottery[].
            for(int j=0; j < 6; j++)
            {
                if(usernumbers[i] == thelottery[j])
                    matches++;
            }
        }

        /* Did we have more matches this week than previosuly recorded? */
        if(matches > best_matches){
            /* yes, remember the new best week and the number of matches. */
            best_week = limit;
            bist_matches = matches;
        }

        Console.WriteLine();
    }
    /* Here, the result of the best week and the best matches is avaiable! */

A: Think this kind of problem is perfect for BitArray's And method.
Basically the usernumbers would be a BitArray instance, and you would have a list with the last 52 BitArray lotterynumbers.
static void Main(string[] args)
{
    List<BitArray> lotterynumbers = GetLastWinningNumbers();
    BitArray usernumbers = new BitArray(MAX_LOTTERY_NUMBER);

    Console.Write("Please enter six numbers for the lottery: \n");
    for (int i = 0; i < 6; i++)
        usernumbers[Convert.ToInt32(Console.ReadLine())] = true;

    BitArray bestmatches = new BitArray(MAX_LOTTERY_NUMBER);
    BitArray bestweek = bestmatches;
    foreach (BitArray weeknumbers in lotterynumbers)
    {
        BitArray currentmatches = usernumbers.And(weeknumbers);
        if (currentmatches.Count > bestmatches.Count)
        {
            bestmatches = currentmatches;
            bestweek = weeknumbers;
        }
    }

    Console.WriteLine("\n\nYour week with the most matches was...");
    foreach (int number in bestweek)
    {
        Console.Write(number);
        Console.Write(' ');
    }

    Console.WriteLine("\n\nPress any key to continue: ");
    Console.ReadKey();
}


text:
Q: Moving existing segue(s) I want to swap out one view controller for another in an existing XCode iOS storyboard, but I'd rather not recreate the segues going to it.  Is it possible to move or adjust the destination of an existing segue?

A: I believe you do need to create the new segue(s), but that's as easy as control-dragging between the source of the segue and your new scene. And if your code is doing anything that requires the storyboard id (such as prepareForSegue or performSegue), then just apply the same storyboard id for your new segue and you don't need to change your code. If you're using a custom segue, you can just use the same segue class, so you don't need to change the code just because the destination changed. And if the source of your segue is a button or something like that, when you make the segue to the new scene, your old segue is automatically removed, so that simplifies the process, too.
In short, you probably do need to recreate the segues, but you probably don't need to change your code too much to support that.


text:
Q: How tell if CSS class is recognized? I have a simple React weather app I am experimenting around with.
The "table" and "table-hover" css classes used below are bootstrap classes.

      City
      Temperature (K)

As a test, I changed as follows:

      City
      Temperature (K)

As expected, the formatting breaks.
However, in my debugging tools (I am using Firefox), I don't have any indication as to whether the CSS class being used is valid or not. How can I get this feedback from my browser's devtools?

A: OK, this is pretty simple. As mentioned in the comments above,

*

*Open Firefox devtools

*Right-click and select "Inspect Element"

*On the right side of devtools under the Inspector tab, there is another group of tabs. By default, "Rules" should display all rules that are applied to the element.

*All css classes that are applied should display here (there is a search bar to help filter as well)


text:
Q: std::find_if gives "conditional expression of type 'void' is illegal" error I have the following function:
float Mesh::getTerrainHeight(Vector3f playerPos) {
    auto testIterator = std::find_if(meshVerticesFloats.begin(), meshVerticesFloats.end(), [&](Vector3f pos)
    {
        //check the X axis
        if (abs(playerPos.GetX() - pos.GetX()) < playerScale + vertexScale / 1.0f) {
            //check the Z axis
            if (abs(playerPos.GetZ() - pos.GetZ()) < playerScale + vertexScale / 1.0f) {
                return;
            }
        }
    });
    if (testIterator != meshVerticesFloats.end()) {
        int testIndex = std::distance(meshVerticesFloats.begin(), testIterator);
        return meshVerticesFloats[testIndex].GetY();
    }
    else {
        return 10000.0f;//test value - no mesh vertex y value is ever 10000
    }
}

When I run I get the following error message:
2>c:\visual_studio_2017\vc\tools\msvc\14.16.27023\include\algorithm(174): error C2451: conditional expression of type 'void' is illegal

Is there something wrong with my std::find_if logic?

A: The predicate should return something that can be converted to bool. More precisely (cppreference):

p - unary predicate which returns true for the required element.
The expression p(v) must be convertible to bool for every argument v of type (possibly const) VT, where VT is the value type of InputIt, regardless of value category, and must not modify v. Thus, a parameter type of VT&is not allowed, nor is VT unless for VT a move is equivalent to a copy (since C++11).

Yours returns nothing:
return;

You probably wanted this instead:
 if (abs(playerPos.GetX() - pos.GetX()) < playerScale + vertexScale / 1.0f) {
     //check the Z axis
     if (abs(playerPos.GetZ() - pos.GetZ()) < playerScale + vertexScale / 1.0f) {
         return true;
     }
 }
 return false;

I don't know if this will give the correct result, thats up to you, but it "fixes" the error.
PS I suppose Vector3f is not your type, hence you should pass a const Vector3f& to the predicate, because std::find_if requires that a move should be equivalent to a copy when you use Vector3f as parameter for the predicate (see above).