text:
Q: Combine Categories & Custom Taxonomy I want to combine the category URL with a taxonomy.
So for example now the URL is: domain.com/category/?district=citycentre
I want to make this URL like this: domain.com/category/citycentre
Is this possible?

A: For following post type and taxonomy:
/**
 * Register restaurant post type
 */
function wpse_287682_register_restaurant_post_type() {

    $labels = array(
        'name' => __( 'Restaurants' ),
        'singular_name' => __( 'Restaurant' ),
        'add_new' => __( 'Add new' ),
        'add_new_item' => __( 'Add new' ),
        'edit_item' => __( 'Edit' ),
        'new_item' => __( 'New' ),
        'view_item' => __( 'View' ),
        'search_items' => __( 'Search' ),
        'not_found' => __( 'Not found' ),
        'not_found_in_trash' => __( 'Not found Restaurants in trash' ),
        'parent_item_colon' => __( 'Parent' ),
        'menu_name' => __( 'Restaurants' ),

    );

    $args = array(
        'labels' => $labels,
        'hierarchical' => false,
        'supports' => array( 'title', 'editor' ),
        'taxonomies' => array(),
        'public' => true,
        'show_ui' => true,
        'show_in_menu' => true,
        'show_in_nav_menus' => false,
        'publicly_queryable' => true,
        'exclude_from_search' => true,
        'has_archive' => true,
        'query_var' => true,
        'can_export' => true,
        'rewrite' => array( 'slug' => 'restaurant' ),
        'capability_type' => 'post',
    );

    register_post_type( 'restaurant', $args );
}

add_action( 'init', 'wpse_287682_register_restaurant_post_type' );

/**
 * Register district taxonomy
 */
function wpse_287682_register_district_taxonomy() {

    $labels = array(
        'name'              => __( 'Districts' ),
        'singular_name'     => __( 'District' ),
        'search_items'      => __( 'Search Districts' ),
        'all_items'         => __( 'All Districts' ),
        'parent_item'       => __( 'Parent District' ),
        'parent_item_colon' => __( 'Parent District:' ),
        'edit_item'         => __( 'Edit District' ),
        'update_item'       => __( 'Update District' ),
        'add_new_item'      => __( 'Add New District' ),
        'new_item_name'     => __( 'New District Name' ),
        'menu_name'         => __( 'District' ),
    );

    $args = array(
        'hierarchical'      => true,
        'labels'            => $labels,
        'show_ui'           => true,
        'show_admin_column' => true,
        'query_var'         => true,
        'rewrite'           => array( 'slug' => 'district' ),
    );

    register_taxonomy( 'district', array( 'restaurant' ), $args );
}

add_action( 'init', 'wpse_287682_register_district_taxonomy', 0 );

You can add this kind of rewrite rule.
/**
 * Add custom rewrite rule for restaurant post type and district taxonomy.
 *
 * Remember to flush rewrite rules to apply changes.
 */
function wpse_287682_add_restaurant_district_rewrite_rule() {
    add_rewrite_rule('restaurant/district/([^/]+)/?$', 'index.php?post_type=restaurant&district=$matches[1]', 'top');
}

add_action('init', 'wpse_287682_add_restaurant_district_rewrite_rule');

Your link for citycenter district will be:
http://example.com/restaurant/district/citycenter/.
Remember to flush rewrite rules after code update.


text:
Q: Compare Time.now in Rails but ignore year? I have the following code in my Rails 3 application:
  scope :active, lambda {
    where("starts_at <= ? AND ends_at >= ?", Time.now.utc, Time.now.utc)
  }
  scope :since, lambda { |hide_time|
    where("updated_at > ? OR starts_at > ?", hide_time.utc, hide_time.utc) if hide_time
  }

  def self.display(hide_time)
    active.since(hide_time)
  end

However, I want to return the results regardless of whether the year matches the current year or not. So long as the day and month match it's fine. Is this possible?
The starts_at and ends_at columns are datetime formatted. So they will automatically include a year even if I dont set one in the form:
<%= f.datetime_select :starts_at, :order => [:day, :month], :discard_year => true %>

Any pointers would be appreciated.

A: As Old Pro points out in the comments this does pose a problem with leap years.  You likely want to split each dayofyear into MONTH(x) AND DAYOFMONTH(x) instead.

You can use the dayofyear function
https://dev.mysql.com/doc/refman/5.5/en/date-and-time-functions.html#function_dayofyear
scope :active, lambda {
    where("dayofyear(starts_at) <= dayofyear(?) AND
      dayofyear(ends_at) >= dayofyear(?)", Time.now.utc, Time.now.utc)
  }
  scope :since, lambda { |hide_time|
    where("dayofyear(updated_at) > dayofyear(?) OR
      dayofyear(starts_at) > dayofyear(?)", hide_time.utc, hide_time.utc) if hide_time
  }

in mssql it's

datepart(dayofyear,date)

in postgres it's

extract(DOY from date)

in sqlite3 it's

strftime("%j",date)

redpajama_set_name: RedPajamaStackExchange


text:
Q: sftp - how to only copy files from folder that don't exist in destination folder I am wondering if it's possible to get files with sftp, but prevent it from re-downloading files that already exist in the destination folder?

A: sftp has limited capabilities. Nonetheless, the get command has an option which may do the trick: get -a completes partial downloads, so if a file is already present on the client and is at least as large as the file on the server, it won't be downloaded. If the file is present but shorter, the end of the file will be transferred, which makes sense if the local file is the product of an interrupted download.
The easiest way to do complex things over SFTP is to use SSHFS. SSHFS is a filesystem that uses SFTP to make a remote filesystem appear as a local filessytem. On the client, SSHFS requires FUSE, which is available on most modern unices. On the server, SSHFS requires SFTP; if the server allows SFTP then you can use SSHFS with it.
mkdir server
sshfs server.example.com:/ server
rsync -a server/remote/path /local/path/
fusermount -u server

Note that rsync over SSHFS can't take advantage of the delta transfer algorithm, because it's unable to compute partial checksums on the remote side. That's irrelevant for a one-time download but wasteful if you're synchronizing files that have been modified. For efficient synchronization of modified files, use rsync -a server:/remote/path /local/path/, but this requires SSH shell access, not just SFTP access. The shell access can be restricted to the rsync command though.

A: You can use the -a flag for the get command:
$ sftp example.com
sftp> get -a hello.txt

You can specify * to download the entire directory of course.
However, there are a few caveats.

*

*This doesn't work on OS X. It may not work on other systems. I've tested it on Ubuntu 15.04.

*The option is meant to resume interrupted downloads. If your file has changed, the result wil be a corrupted download.

A better option would be using rsync:
rsync example.com:hello.txt

This will always give you the file as it is on the server, only transfering the differences between the local and the remote copy if they differ, and it's universally available.


text:
Q: Weather web part for SharePoint 2019 on-premises Modern Page How to add Weather web part for SharePoint 2019 on-premises Modern Page because it is required to be used in Internal SharePoint server 2019 - Modern Site.

A:
The Weather web part is not available in SharePoint Server 2019.

It is available only for SharePoint in Microsoft 365 (online) & Office for business
Documentation: Show the weather on your page


text:
Q: How to manage historical externals in SVN I have some projects which use a few externals (libraries) that are likely to change overtime. I try and keep the project clean with the trunk/branches/tags pattern, and when I make a tag (or release), I'd like to freeze the entire source in time, that is, the externals as they were at that time.
I can think of two ways to do this:

*

*I could set the externals to point to a specific revision, but that seems a bit of a hassle, unless there is an automation (some nice shell command to make all externals point to the latest revision at that moment?)

*I could localize the externals, if again there is some nice automation that would grab the current external and "localize" it, i.e. making it a permanent hard copy in the project.

Do such things exist with TortoiseSVN? Or am I corrupting the system somehow?

A: As far as I know TortoiseSVN doesn't provide such sophisticated functionality. You need to implement own scripts for checking these externals/changing them, i.e. what you've called automation.
Actually, we have the same inconveniences in our projects. We have a project tree (trunk - our working sources) with externals to tags (other teams working sources), they have own tags, and, moreover, we have a tags of our project tree of course. So, we have nested externals of 3, 4 and more orders. What we have done at this moment is the perl script (calls svn command line tool and process its result) which checks recursively whether all externals in our project tree tag are externals to tags or not (it is our own rule - in tags all externals must be to tags). The main point in this checking is that if at least one of externals points to trunk - the main idea behind our project tree would become pointless (based on the another important rule - never make changes in tags). As a rule it is a  problematic to get that particular state of sources if these rules are violated (and as a result even inability to build application from these sources).
Summing up, I'd recommend developing own concepts, rules and use scripts for automation where it's possible.


text:
Q: Using negative conditions, how to remove whitespaces except line and paragraph breaks One simple way to remove whitespaces in my case is to do like this -

<textarea id="thetext" lines="8" style="width: 100%; height: 8em;">

  hello,          how are you

i'm    fine

And i hope the same from you

</textarea>

<button onclick="whitespaces()">Vanish</button>

However I'm trying to achieve the same objective with negative condition. That is by using minus or something like that. As i'm new to js, i'm not familiar with negative conditions. So can anyone tell me how to use negative condition in this case. The code should look something like this -
function whitespaces() {
    var input = document.getElementById("thetext");
    input.value = input.value.replace(all whitespaces [\s] minus linebreak [\n] and paragraph breaks [\n\n])
}

A: SOLUTION 1
You can use the following regular expression to match all whitespace characters except newlines.
[^\S\r\n]

That is, not-not-whitespace (the capital S complements) or not-carriage-return or not-newline. Distributing the outer not (i.e., the complementing ^ in the character class) with De Morgan's law, this is equivalent to "whitespace but not carriage return or newline." Including both \r and \n in the pattern correctly handles all of Unix (LF), classic Mac OS (CR), and DOS-ish (CR LF) newline conventions.

From this stackoverflow answer.
SOLUTION 2
In javascript you can also use a replacer function to check each match and return the replacement string only if it meets certain conditions. The replacer function here checks for each whitespace whether it is a line break.

<textarea id="thetext" lines="8" style="width: 100%; height: 8em;">

  hello,          how are you

i'm    fine

And i hope the same from you

</textarea>

<button onclick="whitespaces()">Vanish</button>

SOLUTION 3
Another possible solution is to first replace all the paragraph breaks and line breaks by some bogus text (without whitespaces). Then do the whitespace replacement. After that convert the bogus texts back to paragraph and line breaks. (Note that since paragraphs are double line breaks, you do not need the line with the paragraph break replacement.)

<textarea id="thetext" lines="8" style="width: 100%; height: 8em;">

  hello,          how are you

i'm    fine

And i hope the same from you

</textarea>

<button onclick="whitespaces()">Vanish</button>


text:
Q: WPF Smith HTML editor is changing all my HTML tags to upper case I'm building WPF application that's using the Smith HTML Editor. The application is MVVM and I've got the Smith control bound to a field with HTML content. Everything is working ok, except that the IsDirty implementation that I'm working on gets triggered if you click in or even mouse over the HTML control. I looked a little closer and found that as soon as the control looses focus it changes all my tags to upper case (thus the app sees the field as changed and sets the model to dirty.)
I'm having a hard time putting my hands on any documentation for this control, but so far I haven't been able to find anywhere to control this behaviour.
Here's the XAML for the control:
<smith:HtmlEditor Name="fldcomments" Height="320" BindingContent="{Binding Path=Student.Comments, Mode=TwoWay }"/>

I'd appreciate any hints.

A: So this is kludgey as hell, but it's the best I came up with. I used NUglify to extract the plain text and added that as a comparison for my field setter function. Here's the code for the function:
protected void SetField<T>(ref T field, T value, string propertyName)
    {

           if (!EqualityComparer<T>.Default.Equals(field, value))
            {
                IsDirty = true;

            if ((propertyName == "Comments") && (value != null) && (field != null))
            {

                var ugField = Uglify.HtmlToText((value as string));
                var ugValue = Uglify.HtmlToText(field as string);
                string strField = Regex.Replace(ugField.Code, @"\s+", string.Empty);
                string strValue = Regex.Replace(ugValue.Code, @"\s+", string.Empty);

                if (strField == strValue)
                { IsDirty = false; }
            }

                field = value;

                OnPropertyChanged(propertyName);
            }

        }

I had to add the regex.replace to get rid of some extra whitespace that the HTMLToText function left in there.
I'm not proud, but it works. Still very open to a better solution.


text:
Q: Symfony 4: Cannot access admin roles. Access Denied I'm learning Symfony 4 and try to make follow Symfony 4 Documentation to create an app.
I do follow this article to make admin roles.
But when I access path /admin, it's always "Access Denied."
I read many article in Symfony Documentation page and StackOverflow but can not found the way to solve it. Here is my setting
//config/packges/security.yaml

security:

    encoders:
        App\Entity\User:
            algorithm: bcrypt
    providers:
        our_db_provider:
            entity:
                class: App\Entity\User
        in_memory:
            memory:
                users:
                    admin:
                        password: admin123
                        roles: 'ROLE_ADMIN'
    firewalls:
        dev:
            pattern: ^/(_(profiler|wdt)|css|images|js)/
            security: false
        main:
            pattern:    ^/
            http_basic: ~
            provider: our_db_provider
            form_login:
              login_path: login
              check_path: login
              default_target_path: index
              always_use_default_target_path: true

            logout:
              path:   /logout
              target: /index

    access_control:
        - { path: ^/login, roles: IS_AUTHENTICATED_ANONYMOUSLY }
        - { path: ^/admin, roles: ROLE_ADMIN }

And here is the Symfony Debug log:

Uncaught PHP Exception Symfony\Component\Security\Core\Exception\AccessDeniedException: "Access Denied." at C:\xampp\htdocs\aimer-mvc\vendor\symfony\security\Http\Firewall\AccessListener.php line 68

Please help me. Thank you so much!

A: If you want to test your app with admin / admin123, you have to allow in_memory provider in your firewall :
only for http_basic :
security:

    encoders:
        App\Entity\User:
            algorithm: bcrypt
    providers:
        our_db_provider:
            entity:
                class: App\Entity\User
        in_memory:
            memory:
                users:
                    admin:
                        password: admin123
                        roles: 'ROLE_ADMIN'
    firewalls:
        dev:
            pattern: ^/(_(profiler|wdt)|css|images|js)/
            security: false
        main:
            pattern:    ^/
            http_basic:
                provider: in_memory
            provider: our_db_provider
            form_login:
              login_path: login
              check_path: login
              default_target_path: index
              always_use_default_target_path: true

            logout:
              path:   /logout
              target: /index

    access_control:
        - { path: ^/login, roles: IS_AUTHENTICATED_ANONYMOUSLY }
        - { path: ^/admin, roles: ROLE_ADMIN }

for form_login as well :
security:

    encoders:
        App\Entity\User:
            algorithm: bcrypt
    providers:
        both_providers:
            chain:
                providers: [in_memory, our_db_provider]
        our_db_provider:
            entity:
                class: App\Entity\User
        in_memory:
            memory:
                users:
                    admin:
                        password: admin123
                        roles: 'ROLE_ADMIN'
    firewalls:
        dev:
            pattern: ^/(_(profiler|wdt)|css|images|js)/
            security: false
        main:
            pattern:    ^/
            http_basic: ~
            provider: both_providers
            form_login:
              login_path: login
              check_path: login
              default_target_path: index
              always_use_default_target_path: true

            logout:
              path:   /logout
              target: /index

    access_control:
        - { path: ^/login, roles: IS_AUTHENTICATED_ANONYMOUSLY }
        - { path: ^/admin, roles: ROLE_ADMIN }

See https://symfony.com/doc/current/security/multiple_user_providers.html for examples...


text:
Q: How to start an Node.JS Web-App To start a new project/webapp on Node.js, I need:

*

*Folder Structure;

*Libraries (Express, RequireJS, Mocha, Bower, ...);

*Software Phases - Build, Compile, Testing, ...;

*...

Which is the best Stack for Large-Scale projects on Javascript/Node.js?
Thanks in advance for your help!

A: First thing's first, keep it simple. Every new tool you add is another dependency, and another potential stress point for the project. With that in mind, some good tools, methodologies, and best-practices for server-side javascript development are:
Folder Structure
This doesn't really matter. Just do what makes sense to you, and what you think will make sense to others if you plan to have collaborators. Search github for Node.JS projects and see how they're structured. I found one good example: https://github.com/thomasdavis/backbonetutorials/tree/gh-pages/examples/nodejs-mongodb-mongoose-restify
Libraries
The libraries you use is going to greatly depend on what type of project you're working on. Does the REST API hit a database? Is it MongoDB, redis, MySQL, Neo4J, ... ? You're going to need an interface for that.
Express is a great framework. (I believe it can start a project for you even.)
Technologies
Have you considered Coffee/Clojure-script? This extra step at compile time can save you a lot of headaches later on. Your code will also be more readable to others. Jslint is another great tool to verify javascript code. Also, I have to suggest using git for version control. If you aren't: learn it, master it, use it. http://www.git-legit.org/
Methods
Your software development strategy will be dependent on what tools you end up using as well as your own personal choices with regard to how you like to write software. I would suggest using Jenkins to continuously integrate your code, and some sort of test framework to ensure what you write is right.


text:
Q: Google Docs - Script to Upload a List of Substitutions / Replace With Google Docs has a pre-defined list of Substitutions/Replacements (under Tools -> Preferences -> Substitutions). It allows you to add custom words one by one.
Is there a way (script) to bulk upload/add a list of  custom substitutions/replacements?


text:
Q: SF short story - The annual(?) power station trip A man hikes through an abandoned town to an industrial building. He sweats and slightly injures himself doing several tasks by hand that normally would require a forklift. He throws a switch and watches in accomplishment/marvel as the town has electricity again for 80+ seconds. This may be a personal best. Then he hikes away again.
The title of this short story is on the tip of my brain and it's really bugging me.  What is it?
Known incorrect guesses:

*

*Walter Miller - A Canticle For Leibowitz

*Ray Bradbury - Powerhouse

A: That would be "Lucifer" by Roger Zelazny, collected in "The Doors of His Face, The Lamps of His Mouth".

"Do you hear that?" he called out, shaking his fist at
  anything."Ninety three seconds! I made you live for ninety three
  seconds!"
Then he covered his face against the darkness and was silent.
After a long while he descended the stairway, walked the belt, and
  moved through the long hallway and out of the Building. As he headed
  back toward the mountains he promised himself - again - that he would
  never return.


text:
Q: Deserialize XML with XmlSerializer where XmlElement names differ but have same content I would like to deserialize an XML File to a class with several subclasses. The XML looks like this:
<?xml version="1.0" encoding="utf-8"?>
<Objects>
    <Group index="1">
        <de>
            <GroupName>ANTRIEB</GroupName>
        </de>
        <en>
            <GroupName>missing translation!</GroupName>
        </en>
        <Level>2</Level>
    </Group>
    <Group index="2">
        <de>
            <GroupName>BREMSEN</GroupName>
        </de>
        <Level>3</Level>
    </Group>
</Objects>

Deserializing the XML to classes would be no problem, if there wouldn't be those language tags. Sure, I could create a property for every language tag possible. But the list of languages possible should be dynamic (e.g. read from an config file).
This is the reason why i would like to deserialize those language tags and their content into a Dictionary which uses the language as key and a model for the content.
My models look like this:
[XmlRoot("Objects")]
public class DeactivationsXml
{
    [XmlElement("Group")]
    public DeactivationsGroup[] Groups { get; set; }
}

[Serializable()]
public class DeactivationsGroup
{
    [XmlIgnore]
    public Dictionary<string, GroupName> GroupNames { get; set; } = new Dictionary<string, GroupName>();

    public int Level { get; set; }

    [XmlAttribute]
    public byte index { get; set; }
}

public class GroupName
{
    [XmlElement("GroupName")]
    public string Name { get; set; }
}

I searched for a long time to address this problem, but couldn't find a solution. I'm pretty sure, that it's not possible to solve this Problem just with attributes.
Does some hybrid aproach exist in order to combine the Deserialization of an XML File in combination with manual deserialization of all XmlElements which could not be automatically deserialized?
A good and extensible solution for my problem would be great, because the XML structure is complex (same Problem several times with different content etc.).
I can't change the structure of the XML, so please don't point this out.
Approaches
IXmlSerializable
I tried to implement the IXmlSerializable Interface on the DeactivationsGroup class in order to search with a list of given languages for XmlElements with those names and deserialize the content of those XmlElements.
But this approach didn't work out, because you have to map all properties manually.
IExtensibleDataObject
The Interface is only supported by a DataContractSerializer. In the worst case i could use this interface to deserialize after Deserializing, if no other solution is found..
OnDeserialization
This Attribute is not supported by XmlSerializer, but would provide the functionality i possibly need.
XmlAnyElement
I guess this is the best option at this point. Does some callback exist after deserialization finished in order to automate this?
Executable Code
Here's the whole code so far.
public void Parse()
{
    string xml = "<?xml version=\"1.0\" encoding=\"utf-8\"?>" +
"    <Objects>" +
"       <Group index=\"1\">" +
"           <de>" +
"               <GroupName>ANTRIEB</GroupName>" +
"           </de>" +
"           <en>" +
"               <GroupName>missing translation!</GroupName>" +
"           </en>" +
"           <Level>2</Level>" +
"       </Group>" +
"       <Group index=\"2\">" +
"           <de>" +
"               <GroupName>BREMSEN</GroupName>" +
"           </de>" +
"           <Level>3</Level>" +
"       </Group>" +
"    </Objects>";

    XmlSerializer serializer = new XmlSerializer(typeof(DeactivationsXml));

    using (TextReader fileStream = new StringReader(xml))
    {
        var result = (DeactivationsXml)serializer.Deserialize(fileStream);
    }
}

[XmlRoot("Objects")]
public class DeactivationsXml
{
    [XmlElement("Group")]
    public DeactivationsGroup[] Groups { get; set; }
}

[Serializable()]
public class DeactivationsGroup
{
    [XmlIgnore]
    public Dictionary<string, GroupName> GroupNames { get; set; } = new Dictionary<string, GroupName>();

    public int Level { get; set; }

    [XmlAttribute]
    public byte index { get; set; }
}

public class GroupName
{
    [XmlElement("GroupName")]
    public string Name { get; set; }
}

A: You can adopt the approach from this answer and add a surrogate XmlElement [] property, marked with [XmlAnyElement], that performs a nested (de)serialization on the key/value pairs of the Dictionary<string, GroupName> property, binding the dictionary keys to the element names.
Note that, while the documentation for XmlAnyElementAttribute states

Specifies that the member (a field that returns an array of XmlElement or XmlNode objects) contains objects that represent any XML element that has no corresponding member in the object being serialized or deserialized.

In fact the attribute can be applied to a property as well.  Thus a (de)serialization callback is not required since the nested serialization can be performed inside the getter and setter for the surrogate property itself.  It can also be applied to members returning an array of XElement objects instead of XmlElement if you prefer the new LINQ-to-XML API.
In this approach, your DeactivationsGroup would look like:
[Serializable()]
public class DeactivationsGroup
{
    public DeactivationsGroup() { this.GroupNames = new Dictionary<string, GroupName>(); }

    [XmlIgnore]
    public Dictionary<string, GroupName> GroupNames { get; set; }

    public int Level { get; set; }

    [XmlAttribute]
    public byte index { get; set; }

    [XmlAnyElement]
    [Browsable(false), EditorBrowsable(EditorBrowsableState.Never), DebuggerBrowsable(DebuggerBrowsableState.Never)]
    public XElement[] XmlGroupNames
    {
        get
        {
            return GroupNames.SerializeToXElements(null);
        }
        set
        {
            if (value == null || value.Length < 1)
                return;
            foreach (var pair in value.DeserializeFromXElements<GroupName>())
            {
                GroupNames.Add(pair.Key, pair.Value);
            }
        }
    }
}

Making use of the following extension methods and classes:
public static class XmlKeyValueListHelper
{
    const string RootLocalName = "Root";

    public static XElement [] SerializeToXElements<T>(this IEnumerable<KeyValuePair<string, T>> dictionary, XNamespace ns)
    {
        if (dictionary == null)
            return null;
        ns = ns ?? "";
        var serializer = XmlSerializerFactory.Create(typeof(T), RootLocalName, ns.NamespaceName);
        var array = dictionary
            .Select(p => new { p.Key, Value = p.Value.SerializeToXElement(serializer, true) })
            // Fix name and remove redundant xmlns= attributes.  XmlWriter will add them back if needed.
            .Select(p => new XElement(ns + p.Key, p.Value.Attributes().Where(a => !a.IsNamespaceDeclaration), p.Value.Elements()))
            .ToArray();
        return array;
    }

    public static IEnumerable<KeyValuePair<string, T>> DeserializeFromXElements<T>(this IEnumerable<XElement> elements)
    {
        if (elements == null)
            yield break;
        XmlSerializer serializer = null;
        XNamespace ns = null;
        foreach (var element in elements)
        {
            if (serializer == null || element.Name.Namespace != ns)
            {
                ns = element.Name.Namespace;
                serializer = XmlSerializerFactory.Create(typeof(T), RootLocalName, ns.NamespaceName);
            }
            var elementToDeserialize = new XElement(ns + RootLocalName, element.Attributes(), element.Elements());
            yield return new KeyValuePair<string, T>(element.Name.LocalName, elementToDeserialize.Deserialize<T>(serializer));
        }
    }

    public static XmlSerializerNamespaces NoStandardXmlNamespaces()
    {
        var ns = new XmlSerializerNamespaces();
        ns.Add("", ""); // Disable the xmlns:xsi and xmlns:xsd lines.
        return ns;
    }

    public static XElement SerializeToXElement<T>(this T obj)
    {
        return obj.SerializeToXElement(null, NoStandardXmlNamespaces());
    }

    public static XElement SerializeToXElement<T>(this T obj, XmlSerializerNamespaces ns)
    {
        return obj.SerializeToXElement(null, ns);
    }

    public static XElement SerializeToXElement<T>(this T obj, XmlSerializer serializer, bool omitStandardNamespaces)
    {
        return obj.SerializeToXElement(serializer, (omitStandardNamespaces ? NoStandardXmlNamespaces() : null));
    }

    public static XElement SerializeToXElement<T>(this T obj, XmlSerializer serializer, XmlSerializerNamespaces ns)
    {
        var doc = new XDocument();
        using (var writer = doc.CreateWriter())
            (serializer ?? new XmlSerializer(obj.GetType())).Serialize(writer, obj, ns);
        var element = doc.Root;
        if (element != null)
            element.Remove();
        return element;
    }

    public static T Deserialize<T>(this XContainer element, XmlSerializer serializer)
    {
        using (var reader = element.CreateReader())
        {
            object result = (serializer ?? new XmlSerializer(typeof(T))).Deserialize(reader);
            return (T)result;
        }
    }
}

public static class XmlSerializerFactory
{
    // To avoid a memory leak the serializer must be cached.
    // https://stackoverflow.com/questions/23897145/memory-leak-using-streamreader-and-xmlserializer
    // This factory taken from
    // https://stackoverflow.com/questions/34128757/wrap-properties-with-cdata-section-xml-serialization-c-sharp/34138648#34138648

    readonly static Dictionary<Tuple<Type, string, string>, XmlSerializer> cache;
    readonly static object padlock;

    static XmlSerializerFactory()
    {
        padlock = new object();
        cache = new Dictionary<Tuple<Type, string, string>, XmlSerializer>();
    }

    public static XmlSerializer Create(Type serializedType, string rootName, string rootNamespace)
    {
        if (serializedType == null)
            throw new ArgumentNullException();
        if (rootName == null && rootNamespace == null)
            return new XmlSerializer(serializedType);
        lock (padlock)
        {
            XmlSerializer serializer;
            var key = Tuple.Create(serializedType, rootName, rootNamespace);
            if (!cache.TryGetValue(key, out serializer))
                cache[key] = serializer = new XmlSerializer(serializedType, new XmlRootAttribute { ElementName = rootName, Namespace = rootNamespace });
            return serializer;
        }
    }
}

Sample fiddle.  And another demonstrating a case with XML namespaces and attributes.

A: Try following using xml linq
using System;
using System.Collections.Generic;
using System.Linq;
using System.Text;
using System.Xml;
using System.Xml.Linq;

namespace ConsoleApplication1
{
    class Program
    {
        const string FILENAME = @"c:\temp\test.xml";
        static void Main(string[] args)
        {
            XDocument doc = XDocument.Load(FILENAME);
            DeactivationsGroup.GroupNames = doc.Descendants("Group").Select(x => new {
                languages = x.Elements().Where(y => y.Element("GroupName") != null).Select(y => new DeactivationsGroup() {
                   name = (string)y.Element("GroupName"),
                   level = (int)x.Element("Level"),
                   index = byte.Parse((string)x.Attribute("index")),
                   language = y.Name.LocalName
                })
            }).SelectMany(y => y.languages)
            .GroupBy(x => x.name, y => y)
            .ToDictionary(x => x.Key, y => y.FirstOrDefault());

        }
        public class DeactivationsGroup
        {
            public static Dictionary<string, DeactivationsGroup> GroupNames { get; set; }

            public string name { get; set; }
            public int level { get; set; }

            public byte index { get; set; }

            public string language { get; set; }
        }

    }
}

A: This is easily done as follows.
Use your set of classes.
Set event handler on the serializer:
var serializer = new XmlSerializer(typeof(DeactivationsXml));
serializer.UnknownElement += Serializer_UnknownElement;

The code in this handler is very simple:
private void Serializer_UnknownElement(object sender, XmlElementEventArgs e)
{
    var group = (DeactivationsGroup)e.ObjectBeingDeserialized;
    group.GroupNames.Add(e.Element.Name, new GroupName { Name = e.Element.InnerText });
}

Fiddle.


text:
Q: Datas are not printed in the view in .Net MVC I have a .Net MVC application and I have to build a frontend with JQuery, DevExpress. I have a database with datas of people and I should list them on the page.
Here is the code I tried:
The controller:
 [HttpGet]
 public JsonResult GetAllPeople()
 {
     var result = context.Persons.Select(m => m)
     return new JsonResult(Ok(result));
 }

And the cshtml file:
@section Scripts {
    <script>

        var peopleList;
        function callback(response) {
            peopleList = response['value'];
        }

        $.ajax({
            type: "GET",
            url: "/Persons/GetAllPeople",
            dataType: "json",
            success: function (result) {
                console.log(result);
                callback(result);
            },
            error: function (error) {
                console.log(error);
            }
        });

        $(() => {
            $('#gridContainer').dxDataGrid({
                dataSource: peopleList,
                columns: ['lastName', 'firstName', 'address', 'dateOfBirth'],
                showBorders: true,
            });
        });
    </script>
}

After debugging the code I can see that the 'result' object is not empty and in the 'value' field I can see the datas of the persons. While running, on the frontend the column's names are printed but the datas. Can you help me to print all the datas instead of nothing?


text:
Q: PHP create folder, upload file and allow delete file best security measure I am developing an application that allows users to upload images. The script creates multiple sizes of the image and stores them in folders with a session ID e.g. /uploads/skj28cnkjck783wo/thumbnails before renaming the folder to a unique name once the user hits submit/next/go.
I need to allow users to have the ability to remove individual files but wondering what the best secure way of doing this would be. If I base the delete off the session ID surely users would be able to change this and remove files that don't belong to them.
I was thinking I could store user information and the object reference in a table and do a lookup to ensure that user has access to remove that file or store the files in a folder with the user ID which is unique based on DB entry but wondering what the experts think. I have done some Google searching but all have flaws.
I am running IIS7 as the web server.
Thanks

A: Try to store relations "userName(or userID)"->"UserFile" in separate table. This is the best secure way, bacause OS (Windows in your case) can detect only one user - owner of web service (IIS or Apache, etc.)

A: It is you who manipulates the files, not the user himself.
The user gives the file name (or perhaps some file id) in his GET or POST request.

*

*Disallow relative paths by rejecting all inputs that contain slashes. It's easy if you don't allow subfolders.

*If you allow subfolders, reject all that have ../ etc.

*You can keep files by changing their names (like flickr does), and keeping data of the filename (to show to the user) and the owner. If owner and user do not match, reject.


text:
Q: stale? method in rails. What does it do? I don't understand the documentation here
The point of confusing is this for me: Why do you set etag or last_modified on the response? Isn't the client the one sending an etag and a if-modified-since header? Once the server (or proxy server) receives these client headers, isn't the server checking to see if the resource's etag and modified date match? The documentation suggest that the request is generated from scratch and not the data? Also, why are we setting the etag and last_modified on the response? Isn't it set by the client?

stale?(options) protected Sets the etag and/or last_modified on the
  response and checks it against the client request. If the request
  doesn't match the options provided, the request is considered stale
  and should be generated from scratch. Otherwise, it's fresh and we
  don't need to generate anything and a reply of "304 Not Modified" is
  sent.
Parameters:
:etag :last_modified :public By default the Cache-Control header is
  private, set this to true if you want your application to be cachable
  by other devices (proxy caches).

What is it going? So some client request is coming in with an etag (some hash) and we check to see if that request is equal to the options in our controller that we set using stale? Here is my controller:
format.json_v20150501 do
          expires_in 30.minutes, public: true
          if stale?(last_modified: last_modified_for_models(recipes), etag: etag_for_models(recipes))
            render json: recipes,
              compact: true,
              serializer: PaginationSerializer,
              each_serializer: Api::V20150315::RecipeSerializer
          end
        end

I don't get what is happening...

A: stale? checks the options provided (those args) to determine whether the object has been modified and therefore needs to be regenerated (in case of cacheing).
regarding the etags, reading this might be helpful: http://blog.bigbinary.com/2016/03/08/rails-5-switches-from-strong-etags-to-weak-tags.html?utm_source=rubyweekly&utm_medium=email


text:
Q: Varargs with inheritance in Java Suppose I have a class Foo like so:
public class Foo<T> {
    protected T invoke(Object... args);
}

Now suppose I add this:
public class Bar<T, Arg> extends Foo<T> {
    public T invoke(Arg arg);
}

Does this mean that I cannot create a Bar<T, Object[]> since it would create two invoke() methods with "essentially" the same signature?  Or would Bar.invoke() safely hide Foo.invoke() in this case (as Bar.invoke() is, runtime-wise, taking Object rather than the Object[] of Foo.invoke())?
Related to this: is forwarding Bar.invoke() to Foo.invoke() safe and fine?

A: Bar.invoke does not override Foo.invoke. If you call just bar.invoke with no arguments you'll get the foo.invoke called.
But you'll get a compile time error (reference to invoke is ambiguous) if you construct a Bar object: Bar<Object, Object[]> bar = new Bar<Object, Object[]>() and then invoke bar.invoke(new Object[]{}) because the 2 invoke methods have the same erasure at runtime.


text:
Q: Sharepoint calculated columns i have predefined list of data, which contains data for each date, now i would like to sum each column on a week basis (to retrieve weekly sum of data for each column)
I tried using week number formula for each day how ever i cannot sum the data using the week number

A: I don't know what your "Week number" formula is.
I suppose that you have a "Week number" calculated field with the formula below to get the week number of the date in the year.
INT(([date]-DATE(YEAR([date]),1,1)+(TEXT(WEEKDAY(DATE(YEAR([a2]),1,1)),"d")))/7)

It would be better to get the week of the date if you have different years of date.
For example: form Monday to Sunday
=CONCATENATE(TEXT([date]-(WEEKDAY([date],2)-1),"mm/dd/yyyy")," - ",TEXT([date]+(7-WEEKDAY([date],2)),"mm/dd/yyyy"))

To get sum values based on the week, you can create/modify a list view and group by "Week" or "Week number" field. It will group items together based on the "Week"/"Week number" value.
Then, sum value.

Result:

A: Calculated columns can only calculate (selected) fields from the item itself. It's a little unclear to me if you want to calculate across several items. If that is the case the suggestion from JoannaW_MSFT is the easiest way to sum - however it's hardly the prettiest way to do it.
Another way would be to write a simple javascript which uses the rest API to retrieve all list items and do a sum on them. I does require a bit more work on your end, and if not familiar with rest and/or javascript it can be a bit daunting/frustrating at first.
If you decide to use the rest API i suggest you start here: https://docs.microsoft.com/en-us/sharepoint/dev/sp-add-ins/working-with-lists-and-list-items-with-rest


text:
Q: What part(s) of our profile gets synced? I've registered to different SE sites, and got different about mes for at least 2 of them. Now, if I want to change my display name for all the sites except one but keep all the about mes intact, is there an easy way to do that? Should I use the old school copy/paste?

A:
is there an easy way to do that?

No, not at the moment, I'm afraid.

Should I use the old school copy/paste?

That's your best bet right now.


text:
Q: Restoring iomanip in Visual Studio after getting C2059 error Currently learning C++ using Visual Studio and I've a simple code that won't compile but runs fine with g++ in Linux. I noticed there's an error code of C2059 in iomanip and saw this line:
_NODISCARD _MRTIMP2 _Smanip<streamsize> __cdecl (streamsize); // This should be setprecision(streamsize) I believe(?)
_NODISCARD _MRTIMP2 _Smanip<streamsize> __cdecl setw(streamsize);

Which suggests that I may have accidentally edited it. Is there a way to restore iomanip (or any other external dependency that one might accidentally alter for that matter) to default in VS? I've tried creating a new project to no avail.

A: I suggest that you could change __cdecl (streamsize); to __cdecl setprecision(streamsize);.
If it doesn't work, I suggest that you could reinstall VS.
Here is the iomaip.h:
// iomanip standard header
#pragma once
#ifndef _IOMANIP_
#define _IOMANIP_
#ifndef RC_INVOKED
#include <istream>

#include <type_traits>

#include <xlocmon>
#include <xloctime>

 #pragma pack(push,_CRT_PACKING)
 #pragma warning(push,3)
 #pragma push_macro("new")
 #undef new

_STD_BEGIN
        // TEMPLATE STRUCT _Fillobj
template<class _Elem>
    struct _Fillobj
    {   // store fill character
    _Fillobj(_Elem _Ch)
        : _Fill(_Ch)
        {   // construct from fill character
        }

    _Elem _Fill;    // the fill character
    };

        // TEMPLATE FUNCTION setfill
template<class _Elem> inline
    _Fillobj<_Elem> setfill(_Elem _Ch)
    {   // return a _Fillobj manipulator
    return (_Fillobj<_Elem>(_Ch));
    }

template<class _Elem,
    class _Traits,
    class _Elem2> inline
    basic_istream<_Elem, _Traits>&
        operator>>(basic_istream<_Elem, _Traits>& _Istr,
            const _Fillobj<_Elem2>& _Manip)
    {   // set fill character in input stream
    static_assert(is_same<_Elem, _Elem2>::value,
        "wrong character type for setfill");

    _Istr.fill(_Manip._Fill);
    return (_Istr);
    }

template<class _Elem,
    class _Traits,
    class _Elem2> inline
    basic_ostream<_Elem, _Traits>&
        operator<<(basic_ostream<_Elem, _Traits>& _Ostr,
            const _Fillobj<_Elem2>& _Manip)
    {   // set fill character in output stream
    static_assert(is_same<_Elem, _Elem2>::value,
        "wrong character type for setfill");

    _Ostr.fill(_Manip._Fill);
    return (_Ostr);
    }

        // TEMPLATE STRUCT _Monobj
template<class _Money>
    struct _Monobj
    {   // store reference to monetary amount
    _Monobj(_Money& _Val_arg, bool _Intl_arg)
        : _Val(_Val_arg), _Intl(_Intl_arg)
        {   // construct from monetary amount reference and int'l flag
        }

    _Money& _Val;   // the monetary amount reference
    bool _Intl;     // international flag

    private:
        _Monobj& operator=(const _Monobj&);
    };

        // TEMPLATE FUNCTION get_money
template<class _Money> inline
    _Monobj<_Money> get_money(_Money& _Val_arg,
        bool _Intl_arg = false)
    {   // return a _Monobj manipulator
    return (_Monobj<_Money>(_Val_arg, _Intl_arg));
    }

template<class _Elem,
    class _Traits,
    class _Money> inline
    basic_istream<_Elem, _Traits>&
        operator>>(basic_istream<_Elem, _Traits>& _Istr,
            const _Monobj<_Money>& _Manip)
    {   // get monetary amount from input stream
    typedef basic_istream<_Elem, _Traits> _Myis;
    typedef istreambuf_iterator<_Elem, _Traits> _Iter;
    typedef money_get<_Elem, _Iter> _Mymget;

    ios_base::iostate _State = ios_base::goodbit;
    const typename _Myis::sentry _Ok(_Istr);

    if (_Ok)
        {   // state okay, extract monetary amount
        const _Mymget& _Mget_fac = _USE(_Istr.getloc(), _Mymget);
        _TRY_IO_BEGIN
        _Mget_fac.get(_Iter(_Istr.rdbuf()), _Iter(0), _Manip._Intl,
            _Istr, _State, _Manip._Val);
        _CATCH_IO_(_Istr)
        }

    _Istr.setstate(_State);
    return (_Istr);
    }

        // TEMPLATE FUNCTION put_money
template<class _Money> inline
    _Monobj<const _Money>
        put_money(const _Money& _Val_arg,
            bool _Intl_arg = false)
    {   // return a _Monobj manipulator
    return (_Monobj<const _Money>(_Val_arg, _Intl_arg));
    }

template<class _Elem,
    class _Traits,
    class _Money> inline
    basic_ostream<_Elem, _Traits>&
        operator<<(basic_ostream<_Elem, _Traits>& _Ostr,
            const _Monobj<_Money>& _Manip)
    {   // put monetary amount to output stream
    typedef basic_ostream<_Elem, _Traits> _Myos;
    typedef ostreambuf_iterator<_Elem, _Traits> _Iter;
    typedef money_put<_Elem, _Iter> _Mymput;

    ios_base::iostate _State = ios_base::goodbit;
    const typename _Myos::sentry _Ok(_Ostr);

    if (_Ok)
        {   // state okay, insert monetary amount
        const _Mymput& _Mput_fac = _USE(_Ostr.getloc(), _Mymput);
        _TRY_IO_BEGIN
        if (_Mput_fac.put(_Iter(_Ostr.rdbuf()), _Manip._Intl,
            _Ostr, _Ostr.fill(), _Manip._Val).failed())
                _State |= ios_base::badbit;
        _CATCH_IO_(_Ostr)
        }

    _Ostr.setstate(_State);
    return (_Ostr);
    }

        // TEMPLATE STRUCT _Timeobj
template<class _Elem,
    class _Ptr>
    struct _Timeobj
    {   // store reference to tm object and format
    _Timeobj(_Ptr _Tptr_arg, const _Elem *_Fmt_arg)
        : _Tptr(_Tptr_arg), _Fmtfirst(_Fmt_arg)
        {   // construct from tm pointer and format pointer
        for (_Fmtlast = _Fmtfirst; *_Fmtlast != 0; ++_Fmtlast)
            ;   // find end of format string
        }

    _Ptr _Tptr; // the tm struct pointer
    const _Elem *_Fmtfirst; // format string start
    const _Elem *_Fmtlast;  // format string end
    };

        // TEMPLATE FUNCTION get_time
template<class _Elem> inline
    _Timeobj<_Elem, struct tm *>
        get_time(struct tm *_Tptr_arg, const _Elem *_Fmt_arg)
    {   // return a _Timeobj manipulator
    return (_Timeobj<_Elem, struct tm *>(_Tptr_arg, _Fmt_arg));
    }

template<class _Elem,
    class _Traits,
    class _Elem2> inline
    basic_istream<_Elem, _Traits>&
        operator>>(basic_istream<_Elem, _Traits>& _Istr,
            const _Timeobj<_Elem2, struct tm *>& _Manip)
    {   // get time information from input stream
    typedef basic_istream<_Elem, _Traits> _Myis;
    typedef istreambuf_iterator<_Elem, _Traits> _Iter;
    typedef time_get<_Elem2, _Iter> _Mytget;

    static_assert(is_same<_Elem, _Elem2>::value,
        "wrong character type for get_time");

    ios_base::iostate _State = ios_base::goodbit;
    const typename _Myis::sentry _Ok(_Istr);

    if (_Ok)
        {   // state okay, extract time amounts
        const _Mytget& _Tget_fac = _USE(_Istr.getloc(), _Mytget);
        _TRY_IO_BEGIN
        _Tget_fac.get(_Iter(_Istr.rdbuf()), _Iter(0), _Istr, _State,
            _Manip._Tptr, _Manip._Fmtfirst, _Manip._Fmtlast);
        _CATCH_IO_(_Istr)
        }

    _Istr.setstate(_State);
    return (_Istr);
    }

        // TEMPLATE FUNCTION put_time
template<class _Elem> inline
    _Timeobj<_Elem, const struct tm *>
        put_time(const struct tm *_Tptr_arg, const _Elem *_Fmt_arg)
    {   // return a _Timeobj manipulator
    return (_Timeobj<_Elem, const struct tm *>(_Tptr_arg, _Fmt_arg));
    }

template<class _Elem,
    class _Traits,
    class _Elem2> inline
    basic_ostream<_Elem, _Traits>&
        operator<<(basic_ostream<_Elem, _Traits>& _Ostr,
            const _Timeobj<_Elem2, const struct tm *>& _Manip)
    {   // put time information to output stream
    typedef basic_ostream<_Elem, _Traits> _Myos;
    typedef ostreambuf_iterator<_Elem, _Traits> _Iter;
    typedef time_put<_Elem2, _Iter> _Mytput;

    static_assert(is_same<_Elem, _Elem2>::value,
        "wrong character type for put_time");

    ios_base::iostate _State = ios_base::goodbit;
    const typename _Myos::sentry _Ok(_Ostr);

    if (_Ok)
        {   // state okay, insert monetary amount
        const _Mytput& _Tput_fac = _USE(_Ostr.getloc(), _Mytput);
        _TRY_IO_BEGIN
        if (_Tput_fac.put(_Iter(_Ostr.rdbuf()), _Ostr, _Ostr.fill(),
            _Manip._Tptr, _Manip._Fmtfirst, _Manip._Fmtlast).failed())
            _State |= ios_base::badbit;
        _CATCH_IO_(_Ostr)
        }

    _Ostr.setstate(_State);
    return (_Ostr);
    }
        // TEMPLATE STRUCT _Quote_in
template<class _Elem,
    class _Traits,
    class _Alloc>
    struct _Quote_in
    {   // store reference to string
    typedef basic_string<_Elem, _Traits, _Alloc> _Mystr;

    _Quote_in(_Mystr& _Str_obj,
        _Elem _Delim_obj, _Elem _Escape_obj)
        : _Str(_Str_obj),
            _Delim(_Delim_obj), _Escape(_Escape_obj)
        {   // construct from string, delimiter, and escape
        }

    _Mystr& _Str;   // reference to string
    _Elem _Delim;   // delimiter element
    _Elem _Escape;  // escape element

    _Quote_in& operator=(const _Quote_in&) = delete;
    };

        // TEMPLATE STRUCT _Quote_out
template<class _Elem,
    class _Traits,
    class _Sizet>
    struct _Quote_out
    {   // store pointer/length for string
    _Quote_out(const _Elem *_Ptr_obj, _Sizet _Size_obj,
        _Elem _Delim_obj, _Elem _Escape_obj)
        : _Ptr(_Ptr_obj), _Size(_Size_obj),
            _Delim(_Delim_obj), _Escape(_Escape_obj)
        {   // construct from string, delimiter, and escape
        }

    const _Elem *_Ptr;  // pointer to string
    _Sizet _Size;   // length of string
    _Elem _Delim;   // delimiter element
    _Elem _Escape;  // escape element

    _Quote_out& operator=(const _Quote_out&) = delete;
    };

        // TEMPLATE FUNCTION quoted
template<class _Elem> inline
    _Quote_out<_Elem, void, size_t>
        quoted(const _Elem *_Ptr,
            _Elem _Delim = _Elem('"'),
            _Elem _Escape = _Elem('\\'))
    {   // return a _Quote_out manipulator for pointer/length
    size_t _Size = 0;
    for (; _Ptr[_Size] != _Elem(0); ++_Size)
        ;
    return (_Quote_out<_Elem, void, size_t>(_Ptr, _Size, _Delim, _Escape));
    }

template<class _Elem,
    class _Traits,
    class _Alloc> inline
    _Quote_out<_Elem, _Traits,
        typename basic_string<_Elem, _Traits, _Alloc>::size_type>
        quoted(const basic_string<_Elem, _Traits, _Alloc>& _Str,
            _Elem _Delim = _Elem('"'),
            _Elem _Escape = _Elem('\\'))
    {   // return a _Quote_out manipulator for string
    typedef _Quote_out<_Elem, _Traits,
        typename basic_string<_Elem, _Traits, _Alloc>::size_type> _Qobj;
    return (_Qobj(_Str.c_str(), _Str.size(), _Delim, _Escape));
    }

template<class _Elem,
    class _Traits,
    class _Alloc> inline
    _Quote_in<_Elem, _Traits, _Alloc>
        quoted(basic_string<_Elem, _Traits, _Alloc>& _Str,
            _Elem _Delim = _Elem('"'),
            _Elem _Escape = _Elem('\\'))
    {   // return a _Quote_in manipulator
    return (_Quote_in<_Elem, _Traits, _Alloc>(_Str, _Delim, _Escape));
    }

    // quoted INSERTER
template<class _Elem,
    class _Traits,
    class _QuTraits,
    class _Sizet> inline
    basic_ostream<_Elem, _Traits>&
        operator<<(basic_ostream<_Elem, _Traits>& _Ostr,
            const _Quote_out<_Elem, _QuTraits, _Sizet>& _Manip)
    {   // put quoted string to output stream
    static_assert(is_void<_QuTraits>::value
        || is_same<_QuTraits, _Traits>::value,
        "quoted() traits must match basic_ostream traits");

    typedef basic_ostream<_Elem, _Traits> _Myos;

    const _Elem *const _Last = _Manip._Ptr + _Manip._Size;

    _Sizet _Size = _Manip._Size + 2;    // allow for delimiters
    for (const _Elem *_Ptr = _Manip._Ptr; _Ptr != _Last; ++_Ptr)
        if (_Traits::eq(*_Ptr, _Manip._Delim)
            || _Traits::eq(*_Ptr, _Manip._Escape))
            ++_Size;    // count escapes

    ios_base::iostate _State = ios_base::goodbit;
    _Sizet _Pad = _Ostr.width() <= 0 || (_Sizet)_Ostr.width() <= _Size
        ? 0 : (_Sizet)_Ostr.width() - _Size;
    const typename _Myos::sentry _Ok(_Ostr);

    if (!_Ok)
        _State |= ios_base::badbit;
    else
        {   // state okay, insert characters
    _TRY_IO_BEGIN
        if ((_Ostr.flags() & ios_base::adjustfield) != ios_base::left)
            for (; 0 < _Pad; --_Pad)    // pad on left
                if (_Traits::eq_int_type(_Traits::eof(),
                    _Ostr.rdbuf()->sputc(_Ostr.fill())))
                    {   // insertion failed, quit
                    _State |= ios_base::badbit;
                    break;
                    }

        if (_State == ios_base::goodbit
            && _Traits::eq_int_type(_Traits::eof(),
                _Ostr.rdbuf()->sputc(_Manip._Delim)))   // put delimiter
            _State |= ios_base::badbit;

        for (const _Elem *_Ptr = _Manip._Ptr; _Ptr != _Last; ++_Ptr)
            {   // put (possibly escaped) element
            if ((_Traits::eq(*_Ptr, _Manip._Delim)
                || _Traits::eq(*_Ptr, _Manip._Escape))
                && _State == ios_base::goodbit
                && _Traits::eq_int_type(_Traits::eof(),
                    _Ostr.rdbuf()->sputc(_Manip._Escape)))  // put escape
                {   // insertion failed, quit
                _State |= ios_base::badbit;
                break;
                }
            if (_State == ios_base::goodbit
                && _Traits::eq_int_type(_Traits::eof(),
                    _Ostr.rdbuf()->sputc(*_Ptr)))   // put element
                {   // insertion failed, quit
                _State |= ios_base::badbit;
                break;
                }
            }
        if (_State == ios_base::goodbit
            && _Traits::eq_int_type(_Traits::eof(),
                _Ostr.rdbuf()->sputc(_Manip._Delim)))   // put delimiter
            _State |= ios_base::badbit;

        if (_State == ios_base::goodbit)
            for (; 0 < _Pad; --_Pad)    // pad on right
                if (_Traits::eq_int_type(_Traits::eof(),
                    _Ostr.rdbuf()->sputc(_Ostr.fill())))
                    {   // insertion failed, quit
                    _State |= ios_base::badbit;
                    break;
                    }
        _Ostr.width(0);
        _CATCH_IO_(_Ostr)
        }

    _Ostr.setstate(_State);
    return (_Ostr);
    }

template<class _Elem,
    class _Traits,
    class _Alloc> inline
    basic_ostream<_Elem, _Traits>&
        operator<<(basic_ostream<_Elem, _Traits>& _Ostr,
        const _Quote_in<_Elem, _Traits, _Alloc>& _Manip)
    {   // put quoted string to output stream
    typedef basic_string<_Elem, _Traits, _Alloc> _Mystr;
    const _Mystr& _Ref = _Manip._Str;
    return (_Ostr << _STD quoted(_Ref, _Manip._Delim, _Manip._Escape));
    }

    // quoted EXTRACTOR
template<class _Elem,
    class _Traits,
    class _Alloc> inline
    basic_istream<_Elem, _Traits>& operator>>(
        basic_istream<_Elem, _Traits>& _Istr,
        const _Quote_in<_Elem, _Traits, _Alloc>& _Manip)
    {   // get quoted string from input stream
    typedef basic_istream<_Elem, _Traits> _Myis;
    typedef basic_string<_Elem, _Traits, _Alloc> _Mystr;
    typedef typename _Mystr::size_type _Sizet;

    ios_base::iostate _State = ios_base::goodbit;
    bool _Changed = false;
    const typename _Myis::sentry _Ok(_Istr);

    while (_Ok)
        {   // state okay, extract characters
        _TRY_IO_BEGIN
        _Sizet _Size = 0 < _Istr.width()
            && (_Sizet)_Istr.width() < _Manip._Str.max_size()
                ? (_Sizet)_Istr.width() : _Manip._Str.max_size();
        typename _Traits::int_type _Meta = _Istr.rdbuf()->sgetc();
        typename _Traits::int_type _Delim =
            _Traits::to_int_type(_Manip._Delim);
        typename _Traits::int_type _Escape =
            _Traits::to_int_type(_Manip._Escape);

        if (!_Traits::eq_int_type(_Meta, _Delim))   // no leading delimiter
            return (_Istr >> _Manip._Str);
        _Manip._Str.clear();
        _Meta = _Istr.rdbuf()->snextc();    // discard leading delimiter

        for (; !_Traits::eq_int_type(_Meta, _Delim) && 0 < _Size;
            _Meta = _Istr.rdbuf()->snextc(), --_Size)
            if (_Traits::eq_int_type(_Traits::eof(), _Meta))
                {   // end of file, quit
                _State |= ios_base::eofbit;
                break;
                }
            else if (!_Traits::eq_int_type(_Meta, _Escape))
                _Manip._Str.append(1,
                    _Traits::to_char_type(_Meta));  // add element
            else if (_Traits::eq_int_type(_Traits::eof(),
                _Meta = _Istr.rdbuf()->snextc()))
                {   // escaped end of file, quit
                _State |= ios_base::eofbit;
                break;
                }
            else
                _Manip._Str.append(1,
                    _Traits::to_char_type(_Meta));  // add escaped element

        if (!_Traits::eq_int_type(_Meta, _Delim))
            _State |= ios_base::failbit;    // no trailing delimiter, fail
        else
            {   // discard trailing delimiter
            _Changed = true;
            _Istr.rdbuf()->snextc();
            }
        _CATCH_IO_(_Istr)
        break;
        }

    _Istr.width(0);
    if (!_Changed)
        _State |= ios_base::failbit;
    _Istr.setstate(_State);
    return (_Istr);
    }

        // TEMPLATE STRUCT _Smanip
template<class _Arg>
    struct _Smanip
    {   // store function pointer and argument value
    _Smanip(void (__cdecl *_Left)(ios_base&, _Arg), _Arg _Val)
        : _Pfun(_Left), _Manarg(_Val)
        {   // construct from function pointer and argument value
        }

    void (__cdecl *_Pfun)(ios_base&, _Arg); // the function pointer
    _Arg _Manarg;   // the argument value
    };

template<class _Elem,
    class _Traits,
    class _Arg> inline
    basic_istream<_Elem, _Traits>& operator>>(
        basic_istream<_Elem, _Traits>& _Istr, const _Smanip<_Arg>& _Manip)
    {   // extract by calling function with input stream and argument
    (*_Manip._Pfun)(_Istr, _Manip._Manarg);
    return (_Istr);
    }

template<class _Elem,
    class _Traits,
    class _Arg> inline
    basic_ostream<_Elem, _Traits>& operator<<(
        basic_ostream<_Elem, _Traits>& _Ostr, const _Smanip<_Arg>& _Manip)
    {   // insert by calling function with output stream and argument
    (*_Manip._Pfun)(_Ostr, _Manip._Manarg);
    return (_Ostr);
    }

        // INSTANTIATIONS
_MRTIMP2 _Smanip<ios_base::fmtflags> __cdecl resetiosflags(ios_base::fmtflags);
_MRTIMP2 _Smanip<ios_base::fmtflags> __cdecl setiosflags(ios_base::fmtflags);
_MRTIMP2 _Smanip<int> __cdecl setbase(int);
_MRTIMP2 _Smanip<streamsize> __cdecl setprecision(streamsize);
_MRTIMP2 _Smanip<streamsize> __cdecl setw(streamsize);
_STD_END
 #pragma pop_macro("new")
 #pragma warning(pop)
 #pragma pack(pop)
#endif /* RC_INVOKED */
#endif /* _IOMANIP_ */

/*
 * Copyright (c) by P.J. Plauger. All rights reserved.
 * Consult your license regarding permissions and restrictions.
V6.50:0009 */


text:
Q: DISTINCT ON in subquery by SQLAlchemy I have a problem with query by ORM SQLAlchemy.
I need to write subquery like this
SELECT DISTINCT ON (e.type) e.type AS e_type, e.num AS e_num
FROM e ORDER BY e.type

by ORM SQLAlchemy, but when I've used .subquery().alias("q") in my query, DISTINCT ON was compiled to DISTINCT. Why and how am I fix it?

Without .subquery():
db.session.query(E.type, E.num).distinct(E.type).order_by(E.type)

compile to
SELECT DISTINCT ON (e.type) e.type AS e_type, e.num AS e_num FROM e ORDER BY e.type

With .subquery():
db.session.query(E.type, E.num).distinct(E.type).order_by(E.type).subquery().alias("q")

compile to
SELECT DISTINCT e.type AS e_type, e.num AS e_num FROM e ORDER BY e.type


text:
Q: boostrap relative footer goes up when zoom out window i've got a site (asp.net and bootstrap) the problem is that i have a relative positioned footer that goes up when resize the window (or when see from mobile device) i can add margin to the content of the page to prevent this problem (but i will have much white space wich is very horrible)
here's my footer:

FEATURES

User Guides

FAQ

Shortcuts

Glossary

Forum

SERVICES

User Guides

FAQ

Shortcuts

Glossary

Forum

ABOUT US

User Guides

FAQ

Shortcuts

Glossary

Forum

and the css:
.footer
{
    position:relative;
    color: white;
    background-color:#242424;
    padding: 8px 0px 0px 0px;
    margin: 0px auto;
    text-align: center;
    line-height: normal;
    margin-bottom:0;

bottom:0;
    border-top: 5px solid #242424;

    -webkit-transition: border-color 1s ease;
    -moz-transition: border-color 1s ease;
    -o-transition: border-color 1s ease;
    -ms-transition: border-color 1s ease;
     transition: border-color 1s ease;

}

.footer:hover
{
    border-color: #77008F;

    }

100% zoom:

50% zoom:

25% zoom (here's the problem-->see white space below the footer):

A: At the end i solved adding an element "spacer" and a js function:
in the html:

the js:
function aggiustaPiede()
        {

            var spacer = document.getElementById("spacer");
            var contenuto = document.getElementById("getAltezza");
            //alert(spacer.clientHeight);
            var diff = document.documentElement.clientHeight - contenuto.offsetHeight;
            var hhh = spacer.clientHeight;
            spacer.style.height = hhh + diff+ "px";

        }

it simply check if the document height is greater than the content of the page if yes it will increase the height of the spacer to the difference.

A: There is white space under your footer since the body of your site is not enough to push the footer down at the bottom. You can set the min-height of your content and footer to be equal to 100%. However you should make sure to also set
html, body {
    height: 100%;
}

since these are the parent divs of your content

A: From w3schools

Fixed/Sticky Footer Example

The footer is placed at the bottom of the page.

Your Footer


text:
Q: Return NULL JavaScript I don't understand why I am getting alert "Empty" when I type some numbers or leave a empty? Can you help me?
My Code:
    </script>

               <script type="text/javascript">
                   function tell() {
                       var v = true;
                       if (document.getElementsByName("TextBox33").length == 0)
                       alert("Empty");
                           v = false;

                       return v;
                   }
</script>

<asp:LinkButton ID="LinkButton1" runat="server" CausesValidation="True" CommandName="Insert" OnClientClick="javaScript: return tell();"

<asp:TextBox ID="TextBox33" onkeypress="return isNumberKey(event)" runat="server" Text='<%# Bind("imei") %>'></asp:TextBox>

I am adding more html:
<asp:DetailsView ID="DetailsView1" runat="server" DefaultMode="Insert" AutoGenerateRows="False" DataKeyNames="id" DataSourceID="SqlDataSource1" Height="50px" Width="286px" OnItemInserting="DetailsView1_ItemInserting" OnDataBound="DetailsView1_DataBound" OnItemInserted="DetailsView1_ItemInserted">

        <asp:TemplateField HeaderText="IMEI" SortExpression="imei">
            <EditItemTemplate>
                <asp:TextBox ID="TextBox3" runat="server" Text='<%# Bind("imei") %>'></asp:TextBox>
            </EditItemTemplate>
            <InsertItemTemplate>
                <asp:TextBox ID="TextBox33" onkeypress="return isNumberKey(event)" CssClass="TextBox33" runat="server" Text='<%# Bind("imei") %>'></asp:TextBox>
            </InsertItemTemplate>
            <ItemTemplate>
                <asp:Label ID="Label4" runat="server" Text='<%# Bind("imei") %>'></asp:Label>
            </ItemTemplate>
        </asp:TemplateField>

A: You're calling getElementsByName which returns al array of DOM elements. You're then taking the length of that, which will always be more than 0 because the element exists.
Try adding a [0] after the getElementsByName call, and then change .text to .value.
Also so you're aware, you need to put the alert and v = false inside brackets. You can only skip brackets if you're executing one statement.
Here's the revised code:
if (document.getElementById("TextBox33").value.length == 0){
    alert("Oh no I'm empty!");
    v = false;
}

Update: I also just noticed that you didn't actually give the textbox a name of TextBox33, you gave it an ID. I've updated the code.


text:
Q: Subtracting from an Integer within a do-while loop I'm generally new to programming and just started programming in Java a few days ago so I'm not sure if what I'm trying to accomplish is even possible with the way my program is coded.
I'm basically writing a program that asks for a "Strength" value between 0 and 9. It asks you to choose a weapon ((1) Knife is the only one available). It takes that information and generates a random damage ratio between 1-3 plus what ever number your strength is and is supposed to keep subtracting that value from 20 until it hit 0 then quits.
The problem is that I'm stuck in a loop. It subtracts the value from 20, but starts over and keeps subtracting from 20 again rather than storing the subtracted number.
Does anyone have any advice on how something like this would be accomplished? Any help is very much appreciated. This is my code so far....
package untitledgame;

import java.util.Random;
import java.util.Scanner;

public class UntitledGame {

    public static void main(String[] args){

        int pStrength, wKnife, damage, enemyDamage;

        Scanner in = new Scanner(System.in);  //used for next to int inputs

        System.out.println("Choose Your Strength (0-9)");
        pStrength = in.nextInt();
        System.out.println("Your Strength Is "+pStrength);

        System.out.println("Choose Your Weapon; (1)Knife");
        wKnife = in.nextInt();

        System.out.println("Press ENTER to battle...");
        Scanner scanner = new Scanner(System.in);  //waits for users to continue
        scanner.nextLine();

        if (wKnife == 1){

        do {

            int enemyHP = 20;

            Random rn = new Random();  //Random generator
            wKnife = rn.nextInt(3) + 1;  //Randomly generates knife damage

            damage = wKnife + pStrength;  //Damage logic
            System.out.println("Attack with knife has done: " );  //Knife damage
            System.out.print(+damage);
            System.out.print(" damage." );

            System.out.println("");

            enemyDamage = enemyHP - damage;  // Remaing HP

            System.out.println("Enemy has ");
            System.out.print(+enemyDamage);
            System.out.print(" HP left.");

            System.out.println("");

            System.out.println("Press Enter to Attack...");
            scanner.nextLine();

        }
            while (enemyDamage > 0);

            System.out.println("Enemy has been defeated.");

        }

    }

}

A: Declare this int enemyHP = 20; outside the do-while loop. Right now, you're resetting enemyHP to 20 every single time you iterate through the loop.
Also, you should not recreate your Random within the do-while loop. Do that before entering the do block.
There are other issues with the logic that Jonah Haney deals with in his answer.

A: Declare int enemyHP = 20 before the beginning of the loop. Then your loop is missing the following line:
enemyHP = enemyHP - damage;

Also, it seems that you want the loop to keep running until the enemy has been defeated. If that is the case, then your condition should check to see if enemyHP has been drained all the way, like this:
}
    while (enemyHP > 0);    //instead of while (enemyDamage > 0);

EDIT
This is what your code SHOULD look like. I am not saying you should copy it straight into your project. I am saying that you should take a look at the differences and it will help you see the logic problems in your own code:
public static void main(String[] args){

    int pStrength, wKnife, damage, enemyDamage;

    Scanner in = new Scanner(System.in);  //used for next to int inputs

    System.out.println("Choose Your Strength (0-9)");
    pStrength = in.nextInt();
    System.out.println("Your Strength Is " + pStrength);

    System.out.println("Choose Your Weapon; (1)Knife");
    wKnife = in.nextInt();

    System.out.println("Press ENTER to battle...");
    in.nextLine();
    in.nextLine();

    Random rn = new Random();  //Random generator
    int enemyHP = 20;

    if (wKnife == 1){

        do {
            System.out.println("Press Enter to Attack...");
            in.nextLine();

            wKnife = rn.nextInt(3) + 1;   //Randomly generates knife damage
            damage = wKnife + pStrength;  //Damage logic

            System.out.println("Attack with knife has done: " + damage + " damage.");  //Knife damage

            enemyHP -= damage;            // Calculate Remaining HP
            System.out.println("Enemy has " + enemyHP + " HP left.");

        } while (enemyHP > 0);

        System.out.println("Enemy has been defeated.");
        in.close();
    }
}

A: You'll want to initialize your enemyHP variable OUTSIDE of the do-while loop, or it will reset enemyHP back to 20 every time it loops.


text:
Q: How to pass a javascript confirm answer into Grails controller? I have an actionSubmit that right now does some work once the user hits the submit button. I want to be able to have the user click the button and have a confirm (Cancel/OK) show up and the user answers it. The submission should take place either way, but I'd like to pass the results of the confirm box to the controller to act on.
Basically the action will need to happen, but the user's answer to the confirm (Cancel/OK box) will drive some side effect. The wording of the confirm box will say something like "Press OK to clear this field, press cancel to leave it be", but the button they clicked will still do its job.
Can anyone help me with this? Right now we just have an actionSubmit:
 <g:actionSubmit class="save" action="selectTurn"
 value="Select Current Player" />

So the "Select Current Player" is the option they're pressing. The end result will be to show this confirm box only in a certain case (I think I have a solution to that), and then the user will be asked "Would you like to clear this thing?" like I described above, and either result still selects a current player, with Cancel leaving the thing not cleared and OK clearing the thing, all can be done inside the controller/method save.selectTurn.
Does that make sense?

A: You can use Javascript by adding an onclick event like the examples below:
Generated by Scaffolding:
onclick="return confirm('${message(code: 'default.button.delete.confirm.message', default: 'Are you sure?')}');"

Simple:
onclick="return confirm('Are you sure?');"


text:
Q: How to pass arguments to :simple_one_for_one GenServer to initialize state I am trying to set up a supervision tree for a scheduler application (note using Elixir 1.5 syntax). The application should work so that:

*

*Application boots with a registry & the scheduler supervisor

*The SchedulerSupervisor boots, and allows children to be dynamically added via the start_child callback. This takes the initialisation args that are used to build the schedule state.

*The Scheduler, on initialisation, registers its name to the Registry, and initialises with a struct that holds the state (Scheduler then has functions from manipulating schedules, but that isn't relevant to the issue I'm having).

If I don't pass any arguments, I can get this working - the Schedules created are not registered, and I have to modify the state after creation. As soon as I try to add arguments, the system errors out - I know it's just a syntax misunderstanding on my part, but I cannot for the life of me figure out what I'm doing wrong. I haven't found the docs terribly helpful here, and I've tried copying and modifying examples from GH, GH Gists and from articles online, but I cannot get it to work.
Current setup - ideally I would want to pass id, period and targets as arguments to start_child, but can't even get it working with a single argument, so just sticking with the one until I can get it running:
The Application:
defmodule Assay.Application do
  use Application

  def start(_type, _args) do
    children = [
      {Assay.SchedulerSupervisor, []},
      {Registry, keys: :unique, name: Assay.Scheduler.Registry}
    ]

    opts = [strategy: :one_for_all, name: Assay.Supervisor]
    Supervisor.start_link(children, opts)
  end
end

The Supervisor:
defmodule Assay.SchedulerSupervisor do
    use Supervisor

    @name Assay.SchedulerSupervisor

    def start_link(_args) do
        Supervisor.start_link(__MODULE__, :ok, name: @name)
    end

    def start_schedule(id) do
        Supervisor.start_child(@name, [id])
    end

    def init(_) do
        Supervisor.init([Assay.Scheduler], [strategy: :simple_one_for_one, name: @name])
    end
end

The GenServer (only relevant initialisation functions shown)
defmodule Assay.Scheduler do
    use GenServer
    alias Assay.Scheduler
    require Logger

    defstruct targets: [], period: 60_000, id: nil, active: false

    def start_link(id) do
        GenServer.start_link(__MODULE__, [id], [name: via_tuple(id)])
    end

    def init([id]) do
        Logger.info "starting a new #{__MODULE__} with id #{id}"
        {:ok, %Scheduler{id: id}}
    end
end

edit: actual error might help - I can see that the args are wrong, I just can't figure out why:
{:error,
 {:EXIT,
  {:undef,
   [{Assay.Scheduler, :start_link, [[], 1], []},
    {:supervisor, :do_start_child_i, 3, [file: 'supervisor.erl', line: 381]},
    {:supervisor, :handle_call, 3, [file: 'supervisor.erl', line: 406]},
    {:gen_server, :try_handle_call, 4, [file: 'gen_server.erl', line: 636]},
    {:gen_server, :handle_msg, 6, [file: 'gen_server.erl', line: 665]},
    {:proc_lib, :init_p_do_apply, 3, [file: 'proc_lib.erl', line: 247]}]}}}

A: For :simple_one_for_one supervisors, Supervisor.start_child calls the start function with the arguments given to it with the arguments specified in the Child Specification. When using Supervisor.init, the child specification is taken from the module's child_spec/1 function in Elixir 1.5. Since you're using GenServer and not specifying a custom start function and [] is passed to child_spec/1, this defaults to [[]] which means your function ends up being called with two arguments, [] and 1 if the id is 1 and you get an undefined function error.
You can fix this by explicitly saying you don't want the GenServer to provide any arguments to the start function in child_spec by changing
use GenServer

to
use GenServer, start: {__MODULE__, :start_link, []}

Now the function will be called correctly, with only one argument, which will be the id.
IO.inspect Assay.SchedulerSupervisor.start_link []
IO.inspect Assay.SchedulerSupervisor.start_schedule 12

will print:
{:ok, #PID<0.82.0>}
[info]  starting a new Elixir.Assay.Scheduler with id 12
{:ok, #PID<0.83.0>}


text:
Q: A value of type 'Map' can't be assigned to a variable of type 'HashMap' flutter I am having a HashMap of <String, dynamic> and i would like to populate the map. The problem i am having is that its telling me the map is not of type dynamic. Below is my code
        HashMap<String, dynamic> stuff1 = {"id": 1, "region": "North",
          "shippingAddress": "Flyover", "list": []};

How can i create a HashMap of <String, dynamic>, i know some would suggest using HashMap<String, Object> stuff but i am having a list like below

List<HashMap<String, dynamic>>? stuffList;

which has data being populate from a server, but i just want to add stuff1 to the top of the list and i would like to add it with a HashMap of <String, dynamic> because if i add with <String, Object> it won't work

A: Dart Map literals (e.g. {"id": 1, "region": "North", ...} create objects that conform to the abstract Map interface.  By default, the constructed objects are LinkedHashMap instances, but the static (known at compile-time) type of the literal is just Map.
Map is the abstract base type for a number of implementations (such as LinkedHashMap and HashMap).  In general, you cannot directly assign a base type where a derived (more specific) type is expected; that might not be safe.  You also can't just cast the object (which is LinkedHashMap) to a HashMap; neither LinkedHashMap nor HashMap derives from the other.
If you really want an unordered HashMap, you must use a HashMap constructor.  For example:
  HashMap<String, dynamic> stuff1 = HashMap.of({
    "id": 1,
    "region": "North",
    "shippingAddress": "Flyover",
    "list": [],
  });

Alternatively consider using a regular Map (which, again, by default is a LinkedHashMap), which already is hash-based but which additionally maintains insertion order.

A: Try to explicitly instantiate HashMap
final Map<String, dynamic> stuff1 = HashMap()..addAll({"id": 1, "region": "North", "shippingAddress": "Flyover", "list": []});

The other solution might be possible is to as HashMap<String, dynamic> as the end of stuff1
  Map<String, dynamic> stuff1 = {"id": 1, "region": "North", "shippingAddress": "Flyover", "list": []} as HashMap<String, dynamic>;


text:
Q: PhoneGap how to refresh/reload page using one page app Currently, I have a one page app that uses handlebars templates. It has a search function that is controlled by a specific class for that page, the page is /#page/1 then when you click a search result, it takes you to a different page which is controlled by a seperate external class called /#exhibitors/432 (the exhibitor ID is the number at the end).
When i click to go back, and PhoneGap loads the search page (#page/1) in iOS/Safari, unless i reload the entire HTML page using location.reload(), the app will cache the search that was first entered, and it wont take new input.
I have tried to use location.hash to add a random string to the end of the hash, but it will only work when I reload the entire HTML page using location.reload() when the back button is clicked.
There is no issue with Android/Chrome.
Any feedback as to how to reload the HTML and load back the search page which is at #page/1 I would appreciate that. I have tried using location.href = url/#page/1, but it will load the page with none of the dynamic data.

A: More thoughts on this topic:
1) Rule of thumb is to avoid re-loading the whole HTML page. So how could we achieve this? In your HTML page, you should have a specific DIV, which you manipulate as you see fit. For example, on /#page/1, you should set the content of that DIV whatever #page/1 is supposed to do and when user hits search, then search content should be shown in that field. (Please notice that, I am talking about UI side of things. Actual search could be done by some other service and you can make an AJAX call for that service from your page).
2) You will be listening to all sorts of events (e.g. /#page/1, user hitting search button, server returning search results, or server returning an error message etc). And depending on what is going on, you should decorate that DIV accordingly.
Example HTML:
<!DOCTYPE html>

    <meta http-equiv="Content-Type" content="text/html; charset=UTF-8"/>
    <meta name="format-detection" content="telephone=no"/>
    <meta name="viewport"
          content="user-scalable=no, initial-scale=1, maximum-scale=1, minimum-scale=1, width=device-width, height=device-height"/>

    <title>Example</title>

In above HTML, I play with the div with id "content". Here is how:
document.addEventListener("deviceready", letGetGoing, false);

...

function letsGetGoing(){
   $('content').html(useTemplateNamed('page1Template'));
   $('.search').on('change', switchToSearch);
}

function switchToSearch(){
   $('content').html(useTemplateNamed('search'));
   $('.submit').on('change', verifyAndSendToServer);
}
...

Above is a pseudo code. I wrote it just to give you an idea.
I hope it helps.


text:
Q: Basic TCP client on Linux, OSX and Windows I want to make a TCP client that works on Windows, Linux and osx (most important) in C. The code that I've found on SO might work on linux but not on osx and vice versa. So what do I need to make sure that it works on all three?
Thanks!

A: Assuming you are planning to write your code to use the BSD sockets API, you'll find that most TCP client code that works on Linux will work on MacOS/X with little or no modification, and vice versa.
Getting the code to work under Windows as well is a little bit trickier, as required #includes are different, and there are a number of cases where Windows' TCP stack (aka WinSock) behaves a little bit differently than that the TCP stacks of the other two OS's.  That said, Windows does support most of the BSD sockets API, and with a bit of #ifdef-ing you can come up with a program that will compile and run correctly on all three OS's.  You'll need to test and debug on all three OS's, of course; never assume that just because something works on one OS that it will work everywhere.
Depending on your program's particular needs (and your interests), it may well make sense to follow Duck's advice and find a networking library that has already done the above-described work for you; but if you prefer to "roll your own", that is doable too.  A good approach when writing to the BSD sockets API is:  whenever you find a piece of code that you have to write differently for different OS's, hide the implementations of that code snippet inside a function together (with an #ifdef so that the right code gets compiled under each OS), so that the rest of your program doesn't have to remember how to deal with that unpleasant detail anymore.  Do that enough times and you'll end up the proud maintainer of your own cross-platform networking library ;)
I'd recommend getting your program working under Linux and/or OS/X first, and once you're happy with it, then porting it over to Windows.  Some "gotchas" to watch out for when porting your network code to Windows:

*

*Under Windows, you #include windows.h or winsock2.h to get the network definitions you need.  (If you want the newer WinSock2 API, you have to include winsock2.h, and always do it before any #include of windows.h, or you'll get the wrong API version... it's a real circus)

*Under Windows you have to call WSAStartup() before doing any networking stuff (if you forget, all your networking calls will error out)

*Under MacOS/X and Linux, file descriptors and sockets are largely interchangeable (i.e. you can select() on STDIN_FILENO, etc).  Under Windows, they are not.

*Under MacOS/X and Linux, you can find out why a call failed by checking errno.  Under Windows, you call WSAGetLastError() instead.

*Under MacOS/X and Linux, you destroy a socket with close().  Under Windows you do it with closesocket().

*Under MacOS/X and Linux, you can (if you choose) call read() and write() on your TCP socket to receive/send data (respectively).  Under Windows, that won't work, you must call send() and recv() only.   (send() and recv() will work under MacOS/X and Linux too)

*To set a socket to non-blocking mode under Windows, you have to call ioctlsocket(fd, FIONBIO, &mode).  Under MacOS/X and Linux, you call instead fcntl(fd, F_SETFL, flags).

*More fun Windows-networking gotchas can be read at the WinSock Lame List.


text:
Q: HTML AGILITY PACK Parsing Div Blocks I need to parse items from an internet-shop—I need their name and price. Each item-block is located in a different div within a div-catalog of these items.
So I tried this, and it kinda works, but I would prefer to parse both name and price in 1 loop. How might I do so? Thanks!
        var url = "http://bestaqua.com.ua/catalog/filtry-obratnogo-osmosa";
        HtmlWeb web = new HtmlWeb();
        HtmlDocument HtmlDoc = web.Load(url);
        var RootNode = HtmlDoc.DocumentNode;
        foreach (HtmlNode node in
HtmlDoc.DocumentNode.SelectNodes("//div[@class='catalog_blocks']"))
        {
            foreach (HtmlNode item_name in
node.SelectNodes("//div[@class='catalog_blocks-item-name']"))
            {
                    string name = item_name.InnerText;
                    System.Diagnostics.Debug.Write("NAME :" + name + "\n" );
            }
            foreach (HtmlNode item_price in
node.SelectNodes("//span[@class='price-new']"))
            {
                string price = item_price.InnerText;
                System.Diagnostics.Debug.Write("PRICE: " + price + "\n");
            }
        }

A: Since SelectNodes is using an XPATH-expression, you could just use a union in your class filter using "|", which will result in a single collection to loop over.
Note that you would then still need to check which element you've actually selected within the for-loop.


text:
Q: meteor connect to remote mongodb error self signed certificate I want to connect my meteor app to mongodb cloud in scalegrid.
MONGO_URL=mongodb://admin:PASSWORD@SG-Brain-77777.servers.mongodirector.com:27017/admin?ssl=true meteor run

but got error like this :
W20200510-10:53:22.340(7)? (STDERR) MongoNetworkError: failed to connect to server [sg-brain-77777.servers.mongodirector.com:27017] on first connect [Error: self signed certificate
W20200510-10:53:22.340(7)? (STDERR)     at TLSSocket.onConnectSecure (_tls_wrap.js:1473:34)
W20200510-10:53:22.340(7)? (STDERR)     at TLSSocket.emit (events.js:311:20)
W20200510-10:53:22.340(7)? (STDERR)     at TLSSocket.EventEmitter.emit (domain.js:482:12)
W20200510-10:53:22.340(7)? (STDERR)     at TLSSocket._finishInit (_tls_wrap.js:916:8)
W20200510-10:53:22.340(7)? (STDERR)     at TLSWrap.ssl.onhandshakedone (_tls_wrap.js:686:12) {
W20200510-10:53:22.340(7)? (STDERR)   name: 'MongoNetworkError',
W20200510-10:53:22.341(7)? (STDERR)   [Symbol(mongoErrorContextSymbol)]: {}
W20200510-10:53:22.341(7)? (STDERR) }]

error happen after I add
import '../imports/api/posts'; in main.js
---- EDITED from meteor forum
I have mongodb database cluster in scalegrid, but I can't connect to it with just like this :
MONGO_URL=mongodb://admin:password@SG-Brain-77777.servers.mongodirector.com:27017/admin?ssl=true meteor run

I tried to use simple mongo connection in terminal
mongo mongodb://admin:password@SG-Brain-77777.servers.mongodirector.com:27017/admin?ssl=true

and stil cant connect with same error :
SSL peer certificate validation failed: self signed certificate
and I tried to make it like this :
mongo mongodb://admin:password@SG-Brain-77777.servers.mongodirector.com:27017/admin?ssl=true --ssl --sslCAFile ./.crt

and it works!!!
the problem now, i cant add --ssl --sslCAFile ./.crt in MONGO_URL like this, because it makes error :
MONGO_URL=mongodb://admin:password@SG-Brain-77777.servers.mongodirector.com:27017/admin?ssl=true --ssl --sslCAFile ./.crt meteor run

how to add ssl cert to mongo url?

new update I tried :
MONGO_URL=mongodb://admin:password@SG-Brain-77777.servers.mongodirector.com:27017/admin?ssl=true,ssl_ca_certs=./.crt meteor run

and got error :
MongoNetworkError: failed to connect to server [sg-brain-77777.servers.mongodirector.com:27017] on first connect [MongoNetworkError: connection 0 to sg-brain-77777.servers.mongodirector.com:27017 closed

A: The Solution:
You need to specify the MongoDB SSL CA Certificate in Meteor settings.
Step by Step Guide:

*

*Login to Scalegrid and select the cluster for your Meteor app.

*Scroll to the bottom, and click Get SSL CA Cert

*Copy the text into a new file private/scalegrid-cert.pem

NOTE: it's safe to commit private/scalegrid-cert.pem to your repo
  because it contains a public key. Bear in mind some .pem files
  include private keys
  and should never be added to a repo.

*Add the following to your Meteor settings environment variable

  "packages": {
    "mongo": {
      "options": {
        "tls": true,
        "tlsCAFileAsset": "scalegrid-cert.pem"
      }
    }
  }

NOTE: it's "tlsCAFileAsset": "scalegrid-cert.pem"not "tlsCAFileAsset": "private/scalegrid-cert.pem". See the docs for why.

A: The correct way to specify TLS/SSL options in the connection URI string is different from how it is specified for the mongo shell.
You have two options if you want to specify this on the connection string itself.

*

*You can use the tlsCAFile option in the connection string. See - https://docs.mongodb.com/manual/reference/connection-string/#urioption.tlsCAFile
This would help you specify the file path to the CA certificate file.

*The other option is to use the tlsAllowInvalidCertificates. See - https://docs.mongodb.com/manual/reference/connection-string/#urioption.tlsAllowInvalidHostnames If this is set to true, then you wouldn't need to specify the CA cert file at all.
Note that both these options are available only for MongoDB 4.2 and above. Also, read the documentation warning about tlsAllowInvalidCertificates.