text:
Q: C++: conversions of lvalue references and rvalue references I wonder which parts of the standard specify that in the following code segment:
#include <memory>

class A { };

class B : public A { };

int main()
{
    std::unique_ptr<B> bptr = std::make_unique<B>(); // (a)
    std::unique_ptr<A> aptr = std::move(bptr);       // (b)
    std::unique_ptr<A> &aptr_r = bptr;               // (c)
    std::unique_ptr<A> &&aptr_rr = std::move(bptr);  // (d)
    return 0;
}

(d) compiles and (c) does not. Please include the relevant parts of the standard in your answer or refer to them appropriately. Just for reference, Ubuntu clang version 3.6.2-1 (tags/RELEASE_362/final) (based on LLVM 3.6.2) gives me
error: non-const lvalue reference to type 'unique_ptr<A>' cannot
       bind to a value of unrelated type 'unique_ptr<B>'
       std::unique_ptr<A> &aptr_r = bptr;
                           ^        ~~~~

and gcc (Ubuntu 5.2.1-22ubuntu2) 5.2.1 20151010 gives me
error: invalid initialization of reference of type 'std::unique_ptr<A>&'
       from expression of type 'std::unique_ptr<B>'
       std::unique_ptr<A> &aptr_r = bptr;
                                    ^

Edit:
To make my question more clear, let me add
class C { };

std::unique_ptr<C> cptr = std::make_unique<C>(); // (e)
std::unique_ptr<A> &&aptr_rr2 = std::move(cptr); // (f)

What is keeping (f) from compiling when (d) does? Obviously A and C are unrelated, but where is that detected when the std::unique_ptr constructor used to construct the temporary for both (d) and (f) is
template<class U, class E>
unique_ptr(unique_ptr<U, E> &&u);

A: The key difference between your cases lies in the fact that rvalue references can bind indirectly (via a temporary), while non-const lvalue references cannot. In both (c) and (d), the initializer is not similar or convertible to the type referred to as determined in  [dcl.init.ref]/(5.1), therefore [dcl.init.ref]/(5.2) must apply - immediately ruling out (c):

Otherwise, the reference shall be an lvalue reference to a
  non-volatile const type (i.e., cv1 shall be const), or the reference
  shall be an rvalue reference.

Note also that unique_ptr<A> and unique_ptr<B> are distinct, unrelated types, regardless of how A and B are related.
You can observe that rule with scalars, too:
int&& i = 0.f; // Ok
int& i = 0.f; // Not ok


text:
Q: How does Spring for Python compare with Spring for Java I am an avid fan of the Spring framework for Java (by Rod Johnson).
I am learning Python and was excited to find about Spring for Python.
I would be interested in hearing the community's views on the comparison of
these two flavours of Spring. How well does it fit Python's paradigms etc.

A: Dependency injection frameworks are not nearly as useful in a dynamically typed language. See for example the presentation Dependency Injection: Vitally important or totally irrelevant? In Java the flexibility provided by a dependency injection framework is vital, while in Python it usually results in unneeded complexity.
This doesn't mean that the principles are wrong. See this example how to achieve loose coupling between classes by using simple idioms:
# A concrete class implementing the greeting provider interface
class EnglishGreetingProvider(object):
    def get_greeting(self, who):
        return "Hello %s!" % who

# A class that takes a greeting provider factory as a parameter
class ConsoleGreeter(object):
    def __init__(self, who, provider=EnglishGreetingProvider):
        self.who = who
        self.provider = provider()
    def greet(self):
        print(self.provider.get_greeting(self.who))

# Default wiring
greeter = ConsoleGreeter(who="World")
greeter.greet()

# Alternative implementation
class FrenchGreetingProvider(object):
    def get_greeting(self, who):
        return "Bonjour %s!" % who
greeter = ConsoleGreeter(who="World", provider=FrenchGreetingProvider)
greeter.greet()

A: DISCLOSURE: I am the project lead for Spring Python, so you can consider my opinion biased.
I find that several of the options provided by Spring Python are useful including: aspect oriented programming, dependency injection, remoting, security, and easy database access.
Aspect oriented programming is, as they say, easier to implement off the cuff with python than java. But Spring Python makes it easy enough to add to existing python modules without editing their source code. The other solutions require meta-programming or modifying the original source code. I've already had one person visit our forums asking how to add an interceptor to a PyGame application, so he could unobtrusively "tap" some code.
Many people quickly assume "dependency injection" or "IoC" instantly means "XML configuration files". Not the case. While we support an XML configuration, just leap directly into using python decorators.
I already know about one company that is using Spring Python as a key piece of their system. They are interested in making improvements, adding new features, and generally using it as a piece of their solution. They have also experimented with running it inside jython, in case that piques your interest.
At the end of the day, my suggestion is to examine all the features, and see if any of them suit your needs. Whether this is adding needless complexity or succinct value can only be determined by you. You don't have to use everything; only what you need. To get some more info on what is available, I invite you to view Introduction to Spring Python, that I presented at SpringOne Americas 2008 conference.

A: Good stuff.  I have used Spring Java, Spring Dot Net and now starting with Spring Python.  Python has always been pretty easy to use for programmers; I think, especially since it's easy to write.  I found Spring Dot Net to be a bit confusing, but both Spring Java and Python seem to be similar.  I'm sure they have their differences, but so far at least I'm not all so confused with the Python implementation of Spring.

redpajama_set_name: RedPajamaStackExchange


text:
Q: Order state when creating shipping label I have created a script that automatically create UPS shipping labels when a certain orders have the status "ready_for_ups".
However I'm unsure to which "state" I should assign this to. Is it "pending" or "processing".
Almost all of our payments are done with credit card and a few with bank wire transfer.

A: *

*Pending = not paid yet

*Processing = Paid not shipped/Shipped not paid

So I would go with processing


text:
Q: Haskell: Alternative, non-circular definition of Redex? I got quite confused about what is and is not a redex in Haskell, so I spent some time on it, but I would like feedback whether I got it right.
I found this definition of a redex, and it is circular;

Etymology : From "reducible expression"
Definition: Redex (plural redexes): (mathematics) Something to be reduced according to the rules of a formal system.

http://en.wiktionary.org/wiki/redex
The above definition presumes one knows how to reduce. So to me this is like saying "Bluish is the quality of looking blue", which is also circular.
Then I found a blog post that defines redex as follows;

Any subgraph that matches a rule is called a reducible expression, or redex for short.

https://hackhands.com/lazy-evaluation-works-haskell/
That's much better but, taken literally it means that it is implementation specific, which seems odd. In other words, if I can define myfunc in two different ways with different evaluation trees, the definition of what is a redex would differ. I don't think that is true.
It seems that the important thing is the evaluation parse tree and, in turn, the definition of what is a primitive. I could not find a definition of Haskell primitives, but I found a possibly  incomplete list: "Important Haskell primitive functions" http://www.cs.sjsu.edu/faculty/smithj/oldclass/152f11/haskell-primitives.html
Is there a real definition of Haskell primitives that I have missed?
Moving on, the list helps identify some examples of primitives and non-primitives.

-- Primitive:  *, / , div
-- Not-Primitive (not on the list): mul

Putting this all together, it says that a primitive function evaluation is reducible, being a leaf node on the evaluation tree. The reduction reduces from a function call to a data point.
Thus, how is this definition ?

Redex: In Haskell, evaluation proceeds with the base case that any primitive function application constitutes a leaf node of the evaluation tree. Such leaves are reducible from function applications into pure data elements. Thus we define all leaf nodes as reducible expressions, or "redexs" for short.

thank you!
Edit; Here are some examples I'm  trying to accommodate, that I believe true.
The first is from Graham Hutton , Programming in Haskell.

-- Consider these cases;
-- 1.An expression using a function
mult ::(Int, Int)-> Int -- pg.126
mult (x,y) = x*y
mult(1+2, 3+4)
-- This has 3 redexes, one for each argument and one for the call, per the book
-- 2.Now consider using '*', a primitive, instead of mul, a function,
7 + (6*8)
-- This has one redex, only the 6*8, per discussions.
-- 3.Finally, contrast to all primitives without any parentheses to indicate a new evaluation level
1 + 2*3
-- This should have zero redexes, I believe, since they are only primitive expressions which can be evaluated all at once.

A: A redex in a functional language, once you get past the syntax (i.e. translating 1 + 2 from infix into (+) 1 2) is just anything that looks like f x -- i.e. a function and an argument such that the function has not been applied to the argument.
One shouldn't worry about which things are and aren't "primitive" functions
And in fact, contra-Hutton, I'd say that 1+2 has two redexes, since it is actually uncurried, and so the "desugared" form is ((+) 1) 2.


text:
Q: How to deploy custom webparts, html and javascript files to office 365 I have created a custom web part file (dwp file)
It is basically a content editor web part which I exported after pointing it to a HTML file
Now I want to deploy the following files in folders as mentioned below
 dwp files -> _catalogs/wp
 HTML files-> style library/HTML
 JS files  -> style library/JS

Currently I am manually navigating to these folders and uploading them
How can I do this via Powershell, CSOM or any other tool from my system?

A: I use a console application built using CSOM to upload files, you can use it to upload files to SharePoint library as below. Here, I am uploading html files to a Style Library folder called HTML. It iterates through a folder in local machine and uploads all files to HTML folder of Style library.
You can modify it to upload to JS folder as well as change the URLs to upload to master page gallery.
ClientContext context = new ClientContext("http://SiteCollectionurl");
string[] files = Directory.GetFiles("C:\Repository\HTML");
foreach (string filePath in files)
{
    string fileName = Path.GetFileName(filePath);
    string fileUrl = string.Format("{0}/{1}", "/Style Library/HTML/", fileName);
    using (FileStream fs = new FileStream(filePath, FileMode.Open))
    {
        Microsoft.SharePoint.Client.File.SaveBinaryDirect(context, fileUrl, fs, true);
    }
}


text:
Q: opacity get back default value using jquery Hi all I have this script and I want when I'll click other .circle opacity get back default value 1

$(this).find('.circle').click(function(){
    $(this).animate({"opacity":"0"},200);
});

A: You can set all .circle elements opacity to 1 before animating. For example:
$(this).find('.circle').click(function(){
    $('.circle').css( 'opacity', '1' );
    $(this).animate({"opacity":"0"},200);
});

A: Try this:
var $circles = $(this).find('.circle');
$circles.click(function(){
    $circles.animate({"opacity":"1"},200);

    $(this).animate({"opacity":"0"},200);
});

Edit: cleaned up the code

A: The posted solutions cause that when you click on a selected circle, it blinks.

If you want when click on a selected circle it don't blinks and changes happen only when you switch from one circle to another circle try this:
$(this).find('.circle').click(function(){
    if (!$(this).hasClass('current')){
        $('.circle.current').animate({"opacity":"1"},200);
        $('.circle').removeClass('current');
        $(this).addClass('current');
        $(this).animate({"opacity":"0"},200);
    }
});

Check JSFiddle Demo


text:
Q: How do i use the VLC to auto replay as loop? VLC how can i apply auto loop of the given content while using with options? Following did not work to loop.
private void start() {

    frame.setVisible(true);
    String mrl = "file:///home/sun/Downloads/t1.avi";
    // fails
//    String[] options = {
//      "--loops",
//      "--repeat",};

    ///Applications/VLC.app/Contents/MacOS/VLC -vv qtcapture:// --sout='#transcode{vcodec=h264,vb=768,fps=25.0,scale=1}:standard{access=udp,mux=ts{dts-delay=9000},dst=239.0.0.5}'

    //mediaPlayer.playMedia(mrl, options);
    //String[] options = {"--loops"};
    // no luck fails too
    mediaPlayer.playMedia(mrl,
            ":sout ':standard{loop}'");

  }

A: I believe you had a typo; the documented option is "--loop".
The following is all that is needed:
vlc --loop video.mp4

To do this from Java, you could:
public class Player {
    public static final void main(String args[]) {
        try {
            Runtime.getRuntime().exec("vlc --loop "+args[0]);
        } catch (Exception e) {
            System.out.println(e.toString());
        }
    }
}

and then:
java Player filename.mp4

A: If you use VLCJ, I suggest that you to call mediaPlayer.setRepeat(true); It works in my  VLCJ project as follows:
mediaPlayer.setRepeat(true);
mediaPlayer.setPlaySubItems(true);
mediaPlayer.playMedia(mrl, options);

Tested with with JRE 1.6 32-bit:

*

*VLCJ 1.2.0 + VLC engine libVLC 1.1.11 (Windows 32-bit)

*VLCJ 2.1.0-SNAPSHOT + nightly build VLC engine libVLC 2.1.0 (Windows 32-bit)

A: In the latest version, no need for complex scripting.
Click on TOOLS > PREFERENCES.
Look bottom left of interface,
"Show settings" radio button should be set to "ALL".
Look at left Panel, click on "Playlist".
Check/Tick "Repeat All" CHECKBOX.


text:
Q: Extracting array from JSON type body in Spring I want to extract an array from the request body in postman. This is my Request Body:
{
        "productid": 1,
        "ordernum": 9,
        "actionid": 1,
        "typeid": 2,
        "Data":["abc","xyz"]
}

I'm using Spring boot and want to extract the ["abc,"xyz"] array and assign it to a String[] array. How can this be done.
This is a snippet of my mapping function.
@PostMapping("/testingpost")
    public Data addRow(@RequestBody DataRequest request) {
         String[] responseArr = ??
    }

A: Assuming that DataRequest is modeled after the JSON message as specified in your question:
public class DataRequest {
    @JsonProperty("productid")
    private Integer productId;

    [...]

    @JsonProperty("Data")
    private String[] data;

    // getters and setters

    [...]
}

You should be able to simply return the Data array using the corresponding attribute as follows:
@PostMapping
public String[] something(@RequestBody DataRequest request) {
    return request.getData();
}


text:
Q: Updating to Python 3 on Kubuntu 11.04 -- do/should I uninstall previous versions? Is this going to break anything?  Is there anything I would need to keep in mind if I do uninstall the older versions?

A: Personally, I would keep both around (and when upgrading to Ubuntu 11.04, I did). The problem is that there are still a lot of libs which are only in Python 2.x. The good news is that they are decreasing in number/prominence, but too much relies on the older way of doing things to reliably remove it.
If you feel more courageous than I, install a Py3k version and then change the #!/usr/bin/env python variable to reflect Py3k and then see what breaks (and I am almost positive something will), but personally, I am perfectly fine using #!/usr/bin/env python3 for a while longer.
I HIGHLY recommend that you keep a 2.6 >= Python < 3 version around for a while though, because I will bet money that it will break things if you remove it.

A: You can't remove Python 2, Ubuntu will stop working. Python 3 is however a separate package and can be installed in parallell. Since Python3's exe is called 'python3' this doesn't have any negative effects.


text:
Q: How do I webscrape content in a div using beautiful soup (Python)? I am trying to scrape the languages (stored in the div as illustrated in the image), and I feel like I am doing correctly; however, the call just returns nothing. I have tried the following and none seem to work.
mult_languages = soup.find_all("div", class_ = "C-b-Cd-Pg-ta")
mult_languages = soup.find_all("div", class_ = "f-rd ta ta-kd-xg")
mult_languages = soup.find_all("div", class_ = "ta-x)

How should I go about this? Thanks!
This is the html (webpage is the chrome webstore and I am trying to access the languages)

A: try this :
mult_languages = soup.find_all(lambda tag: tag.name == 'div' and tag.get('class') == ['ta-x'])
print(mult_languages)

DEMO:
 from bs4 import BeautifulSoup
  text = """
  <div class="C-b-Cd-Pg-ta" style="position: absolute; visibility: hidden; left: 523px; top: 260.271p

      "Bahasa Indonesia, Bahasa Melayu, Deutsch, English, Filipino, Français, Kiswahili, Nederlands, polski, português (Brasil), português (Portugal), română, slovenský, slovenščina, suomi, svens hºC,  (*), * (*), 8, "

  """
  soup = BeautifulSoup(text)
  x = soup.find_all(lambda tag: tag.name == 'div' and tag.get('class') == ['ta-x'])

  print(x)
  # [

  #     "Bahasa Indonesia, Bahasa Melayu, Deutsch, English, Filipino, Français, Kiswahili, Nederlands, polski, português (Brasil), português (Portugal), română, slovenský, slovenščina, suomi, svens hºC,  (*), * (*), 8, "
  #
]


text:
Q: Codeigniter: validation problem For some reason a user can login with any password, first I thought I forgot to check for the password but I didn't... and I just cant find the problem
here is the model:
/*#######################################################*/
    function validate()
/*#######################################################*/
    {
        $this->db->where('username', $this->input->post('username'));
        $this->db->where('password', md5($this->input->post('password')));
        $q = $this->db->get('user_extra');

        if($q->num_rows() == 1):
            return true;
        else:
            return false;
        endif;
    }//end of function validate()

The controller
/*#######################################################*/
        function validate_credentials()
/*#######################################################*/
        {
            $this->load->model('membership_model');

            $this->load->library('form_validation');

            $this->form_validation->set_rules('username', 'Name', 'trim|required');
            $this->form_validation->set_rules('password', 'password', 'trim|required');
            if(!$this->membership_model->validate()):
                $this->form_validation->set_message('check_login', 'Login not correct, please try again.');
            endif;

            if($this->form_validation->run() == FALSE):
                $this->index();
            else:
                $this->membership_model->userinfo($this->input->post('username'));
                //should redirect to last view
                redirect($this->session->flashdata('redirect_url'));
            endif;
        }// end of validate_credentials()

A: why dont you create a callback function in the validation string?
Put this function within the same controller
/*##############PRIVATE FUNCTION WITHIN THE SAME CONTROLLER###########*/
    function validate($username,$password) //if you use php 5 i would set this method to  private one
/*#######################################################*/
    {
        $this->db->where('username', $username);
        $this->db->where('password', md5($password));
        $q = $this->db->get('user_extra');

        if($q->num_rows() <= 1)
            return true;
        return false;

    }//end of function validate()

And the rule line:
$this->form_validation->set_rules('username', 'Name', 'trim|required|callback_validaion[password]');

A: Why not just use a caalback as part of the form validation?
e.g.
$this->form_validation->set_rules('password', 'Password', 'prep_for_form|required|xss_clean|callback_password_check');

and the callback function ...
function password_check($value) { /* call model and query database to get password */   if ($value == $password_from_model))    {       return TRUE;    }   else    {       $this->form_validation->set_message('password_check', 'You have not used the correct %s.');         return FALSE;   } }

A: I tried with callback function but it doesn't work for some reason so I just moved the if-statement below in the else-statement of the validation->run(), this is the code:
$this->form_validation->set_rules('username', 'Name', 'trim|required|xss_clean');
            $this->form_validation->set_rules('password', 'password', 'trim|required|xss_clean');

            if($this->form_validation->run() == FALSE):
                redirect(base_url().'login/index/error');
            else:
                if($this->membership_model->validate()):
                    $this->membership_model->userinfo($this->input->post('username'));
                    //should redirect to last view
                    redirect('home/index');
                else:
                    redirect(base_url().'login/index/error');
                endif;
            endif;


text:
Q: Change/Add payload existing TCP packages? I want to change the payload of all existing outgoing packets, so all packets that have "wordA" in it will be changed to "wordB", this will be done by a regex match.
I tried Python's scapy, but I don't know how to get it working.
PS: There won't be any wifi involved in here. Options that require port forwarding are depreciated.

A: import re
text = re.sub("\bwordA\b", "wordB", text)


text:
Q: Real time SQL database updates between multiple VB.NET clients I'm using a SQL database and I'm writing a VB.NET client application. This application is used on multiple computers at the same time. If one of the clients makes an update to the database I would like to have the other clients to be aware of the update.

A: If you are using MS SQL Server you could perhaps use Service Broker notifications to push a notification to the clients when the data gets updated. This is not something I have personal experience of using though.

A: *

*Ensure that your table has a DateUpdated column

*When reading the table save the dateUpdated value into a memory variable

*When updating the table include DateUpdated <=

*Check the number of rows updated in step 3.

*If step 4 returns 0 it means somebody else updated the tale while the current user was looking at the data.

Note that this is only applicable if you're interested in detecting updates when you're saving the data. If you'd want the client applicatiob to be notified if the record currently displayed has been updated then, as somebody else mentioned, you'll have to use some kind of notification services.

A: After looking around I found some good information about Service Broker. I also read the following;
"Query Notification is designed for data that does not change frequently. It is also best used in server-side applications (such as ASP.NET or remoting) rather than client-side applications (such as a Windows Forms application). Remember that each request for a notification is registered in SQL Server. If you have masses of client applications each requesting a notification, this can create a resource problem on your server. Microsoft's recommendation is that for client-side applications, you limit your use of query notification to not more than ten concurrent users."
This is my concern, because I have about 10 tables which are updated pretty frequeuntly (every 5 sec.).
Maybee somebody has experience with using Service Broker notifications for more frequently changing data.
Thank you very much!
Marcel

A: I have the same issue.
My solution was to create a audit table!
The audit table contain all table name and another column with date time.
When user change data, is also update the datetime in audit table.
All user check every 4 seconds the audit table. If one of the table was updated, the user reload the entire table how was updated.
Sorry for my english.


text:
Q: Hypergraph partitioning and bipartite graph partitioning Are hypergraph partitioning, and bipartite graph partitioning related, or equivalent, given that hypergraphs can be represented as bipartite graphs?
In the first case, we want to partition the set of vertices only based on edge information.
In the second case, we want to partition both the set of vertices (left nodes in the bipartite graph) and the set of edges (right nodes in the bipartite graph).
From this perspective, the problems seem different. But maybe existing bipartite partitioning methods allow to control the number of partitions on the right nodes (edges) to be 1, and hence reduce one problem to the other?
Is there an application, where clearly we need to use one versus the other, and cannot do the other way around? I know lots of people seem to use bipartite graph partitioning to co-cluster documents and topics. What would be the interpretation of using hypergraph clustering on documents, using documents as nods and topics as edges as topics, or the other way around?
Also, does any one know of easy-to-use software, and corresponding algorithms, that try to solve both problems?


text:
Q: How to get picked 3d object (instead of just the clicked face)? Three.js has examples of getting the clicked face of an object and subsequently highlighting that face. I was wondering how to get the entire object instead of just the face.
Example:
I have many asteroids all rendered in a single buffer. How can I get the clicked asteroid object?
* Update *
I think I found a way to achieve object 'picking'. Essentially, I keep a list of the objects in memory. When a object is picked I use that object's point information to do a collision detection against all the objects in the list. The object that is the closest to the intersected point should, in theory, be the object I need.

A: There's a good example here
You can achieve that using raycaster to project rays and detect intersections.
This is the part of the code you need for object picking.
// find intersections

            raycaster.setFromCamera( mouse, camera );

            var intersects = raycaster.intersectObjects( scene.children );

            if ( intersects.length > 0 ) {

                if ( INTERSECTED != intersects[ 0 ].object ) {

                    if ( INTERSECTED ) INTERSECTED.material.emissive.setHex( INTERSECTED.currentHex );

                    INTERSECTED = intersects[ 0 ].object;
                    INTERSECTED.currentHex = INTERSECTED.material.emissive.getHex();
                    INTERSECTED.material.emissive.setHex( 0xff0000 );

                }

            } else {

                if ( INTERSECTED ) INTERSECTED.material.emissive.setHex( INTERSECTED.currentHex );

                INTERSECTED = null;

            }

            renderer.render( scene, camera );

UPDATE 1:
If all your objects are merged into a single BufferGeometry:

*

*Have a look at this example: webgl_interactive_buffergeometry

*That will show you how to pick faces, not objects. So my guess is:
 //pseudo code
 foreach( object in bufferGeometry){
     foreach(face in object){
        face.addAttribute ( name[object], attribute[object] )
     }
 }

So creating a custom attribute for each of your object and passing it to its faces, you could:

*

*intersect a face

*Get its custom attribute

*Select all faces with that attribute -> the object
I haven't tested it but I guess it should work, let me know :)


text:
Q: Bootstrap Typeahead local, prefetch, or remote is required I try to get this example of twitters typeahead to run but i am getting the error in chromes console:

Uncaught Error: one of local, prefetch, or remote is required jquery-1.9.1.js:507

I am using typeayhead 0.9.1 (Nuget-Package). Is this a version problem? All examples set the source and not local/prefetch/remote in the request.
EDIT: Turned out that Twitter Bootstrap Typeahead and Twitter Typeahead are two different libraries.

A: This only means you need to give a list in which Typeahead will search for completion value.
You must really pass at least one data source (prefetch or remote) or a data set (local).
https://github.com/twitter/typeahead.js#jquerytypeaheaddatasets

Also, should be noted that Twitter typeahead and Twitter Bootstrap typeahead ain't the same plugin. They have different API. The article you read speak about Twitter Bootstrap typeahead: http://twitter.github.io/bootstrap/javascript.html#typeahead but you used it as Twitter typeahead!


text:
Q: Android View below another in FrameLayout not work I have such code:
<?xml version="1.0" encoding="utf-8"?>
<androidx.drawerlayout.widget.DrawerLayout xmlns:android="http://schemas.android.com/apk/res/android"
    xmlns:app="http://schemas.android.com/apk/res-auto"
    android:id="@+id/drawer_layout"
    android:layout_width="match_parent"
    android:layout_height="match_parent"
    android:background="#000">

    <FrameLayout
        android:id="@+id/content_frame"
        android:layout_width="match_parent"
        android:layout_height="match_parent">

        <Button
            android:layout_width="wrap_content"
            android:layout_height="wrap_content"
            android:text="center map"
            android:padding="15dp"
            android:background="@drawable/button"
            android:layout_gravity="center_horizontal|center_vertical"
            android:textColor="#FFF" />

        <pl.jawegiel.endlessblow.other.GameSurface
            android:id="@+id/gameSurface"
            android:layout_width="match_parent"
            android:layout_height="wrap_content" />

        (...)

        </RelativeLayout>
    </FrameLayout>

    <androidx.recyclerview.widget.RecyclerView
        android:id="@+id/left_rv"
        android:layout_width="200dp"
        android:layout_height="match_parent"
        android:layout_gravity="start"
        android:background="#22FFFFFF"
        android:choiceMode="singleChoice"
        android:divider="#080"
        android:dividerHeight="2dp"
        app:layoutManager="androidx.recyclerview.widget.LinearLayoutManager" />

    <androidx.recyclerview.widget.RecyclerView
        android:id="@+id/right_rv"
        android:layout_width="200dp"
        android:layout_height="match_parent"
        android:layout_gravity="end"
        android:background="#99FFFFFF"
        android:choiceMode="singleChoice"
        android:divider="#080"
        android:dividerHeight="2dp"
        app:layoutManager="androidx.recyclerview.widget.LinearLayoutManager" />

</androidx.drawerlayout.widget.DrawerLayout>

The problem is that my Button is not below GameSurface.
I put this Button as first one counting on that it will be below GameSurface but it does not work.
How to achieve that?

A: You need to change FrameLayout to another kind of ViewGroup. FrameLayout is a a type of ViewGroup where one View is on top of another one. Like Layers in a cake.
Putting one below another is not possible in FrameLayout
The easiest solution might be to change FrameLayout with LinearLayout and of course, remember to add android:orientation attribute to it.
NOTE: I suggest you to learn ConstraintLayout, which can replace nearly every type of nested ViewGroups including FrameLayout and RelativeLayout :-)

A: This you can't achieve with FrameLayout, this is because FrameLayout is usually used to show only one child. Even tho it can show more child views they are just placed on top of each other. This is explained in the answer above. Each ViewGroup has its own pros and cons and the best Layout for this is LinearLayout. LinearLayout can place your child's one below another or one next to another, based on android:orientation attribute you can use. Values are vertical and horizontal. You understand from that which one should be used here.
Therefore, what you need to do is simply change your FrameLayout to LinearLayout. So this is how it looks in my XML:
 <LinearLayout
        android:id="@+id/content_frame"
        android:layout_width="match_parent"
        android:gravity="center_vertical"
        android:orientation="vertical"
        android:layout_height="match_parent">

After that, you just place your child views in order you want to show them. So, in my case I have an ImageView and a Button, placed in that order, like this:
<LinearLayout
    android:id="@+id/content_frame"
    android:layout_width="match_parent"
    android:gravity="center_vertical"
    android:orientation="vertical"
    android:layout_height="match_parent">

    <ImageView
        android:id="@+id/gameSurface"
        android:src="@drawable/ic_user"
        android:layout_width="200dp"
        android:layout_gravity="center_horizontal"
        android:layout_height="200dp" />

    <com.google.android.material.button.MaterialButton
        android:layout_width="wrap_content"
        android:layout_height="wrap_content"
        android:text="center map"
        android:layout_marginTop="20dp"
        android:padding="15dp"
        android:layout_gravity="center_horizontal|center_vertical"
        android:textColor="#000" />
</LinearLayout>

Then I get this:


text:
Q: Macro won't parse the expression the same recursively I'm creating a recursive Rust macro that can extract a bang ! from the beginning of an expression.
I can do that just fine like this
macro_rules! test {
    (!$e:expr) => {
        println!(stringify!($e));
    };
}

fn main() {
    test!(!'a'); //Outputs: 'a'
}

But has soon as I try to call it from within the macro itself, it no longer works and I get complier errors.
macro_rules! test {
    (@process, !$e:expr) => {
        println!(stringify!($e));
    };

    ($e:expr) => {
        test!(@process, $e);
    };
}

fn main() {
    test!(!'a');
}

no rules expected the token `!'a'`

I don't think this is a typo because I can directly call it without issue on the second example. Is Rust caching the expression and then not reevaluating it? Can I somehow force Rust to reevaluate it, or is something else happening here?

A: This is because !'a' gets parsed as an expression $e, and when $e is passed through, it's passed as a whole expression, no longer as a token sequence (so the latter macro invocation will not see !). You can work around this by capturing it as a raw token sequence instead:
macro_rules! test {
    (@process, !$e:expr) => {
        println!(stringify!($e));
    };

    ($($e:tt)*) => {
        test!(@process, $($e)*);
    };
}


text:
Q: Load Balancing Cluster not working with Apache HTTP Server 2.4.6 and JBoss EAP 7 I am certifying my application on JBoss EAP 7. My application works on standalone mode but in cluster mode, my application gets deployed but I am unable to login. I am again re-routed to login url.
I have setup cluster using mod_cluster.
There is no error log in Load Balancer Server logs neither on individual nodes of the cluster.
In my test environment, my load balancer and 2 server nodes are on same machine. I have given JBoss nodes different ports and instance-ids to differentiate the nodes.
I am sharing my mod_cluster.conf and JBoss standalone-ha.xml extracts from one of the nodes in cluster.
Following are the snippets in standalone-ha.xml file:
Modcluster settings are:
    <subsystem xmlns="urn:jboss:domain:modcluster:2.0">
    <mod-cluster-config advertise-socket="modcluster" proxies="proxy1" balancer="testcluster" advertise="true" connector="ajp">
        <dynamic-load-provider>
            <load-metric type="busyness"/>
        </dynamic-load-provider>
    </mod-cluster-config>
</subsystem>

Undertow settings are:
    <subsystem xmlns="urn:jboss:domain:undertow:3.1" instance-id="node1">
    <buffer-cache name="default"/>
    <server name="default-server">
        <ajp-listener name="ajp" socket-binding="ajp"/>
        <http-listener name="default" socket-binding="http" redirect-socket="https"/>
         <host name="default-host" alias="localhost">
            <location name="/" handler="welcome-content"/>
            <filter-ref name="server-header"/>
            <filter-ref name="x-powered-by-header"/>
        </host>
    </server>
   <servlet-container name="default">
        <jsp-config/>
        <websockets/>
    </servlet-container>
    <handlers>
        <file name="welcome-content" path="${jboss.home.dir}/welcome-content"/>
    </handlers>
    <filters>
        <response-header name="server-header" header-name="Server" header-value="JBoss-EAP/7"/>
        <response-header name="x-powered-by-header" header-name="X-Powered-By" header-value="Undertow/1"/>
    </filters>
</subsystem>

Contents of Socket Binding Group are:
<socket-binding-group name="standard-sockets" default-interface="public" port-offset="${jboss.socket.binding.port-offset:0}">
    <socket-binding name="management-http" interface="management" port="${jboss.management.http.port:9990}"/>
    <socket-binding name="management-https" interface="management" port="${jboss.management.https.port:9993}"/>
    <socket-binding name="ajp" port="${jboss.ajp.port:8009}"/>
    <socket-binding name="http" port="${jboss.http.port:8080}"/>
    <socket-binding name="https" port="${jboss.https.port:8443}"/>
    <socket-binding name="jgroups-mping" interface="private" port="0" multicast-address="${jboss.default.multicast.address:230.0.0.4}" multicast-port="45700"/>
    <socket-binding name="jgroups-tcp" interface="private" port="7600"/>
    <socket-binding name="jgroups-tcp-fd" interface="private" port="57600"/>
    <socket-binding name="jgroups-udp" interface="private" port="55200" multicast-address="${jboss.default.multicast.address:230.0.0.4}" multicast-port="45688"/>
    <socket-binding name="jgroups-udp-fd" interface="private" port="54200"/>
    <socket-binding name="modcluster" port="0" multicast-address="224.0.1.105" multicast-port="23364"/>
    <socket-binding name="txn-recovery-environment" port="4712"/>
    <socket-binding name="txn-status-manager" port="4713"/>
    <outbound-socket-binding name="mail-smtp">
        <remote-destination host="localhost" port="25"/>
    </outbound-socket-binding>
    <outbound-socket-binding name="proxy1">
    <!-- host and port number of the load-balancer.  -->
        <remote-destination host="x.x.x.x" port="81"/>
    </outbound-socket-binding>
 </socket-binding-group>

Contents of mod_cluster.conf are as follows:
LoadModule proxy_cluster_module modules/mod_proxy_cluster.so
LoadModule cluster_slotmem_module modules/mod_cluster_slotmem.so
LoadModule manager_module modules/mod_manager.so
LoadModule advertise_module modules/mod_advertise.so

MemManagerFile "//httpd2.4.6Home/var/cache/mod_cluster"

<IfModule manager_module>
    Listen 81
    <VirtualHost *:81>
    <Directory />
        Require all granted
    </Directory>
    <Location />
        Require all granted
    </Location>
    <Location /mod_cluster_manager>
        SetHandler mod_cluster-manager
        Require all granted
    </Location>
        KeepAliveTimeout 60
        MaxKeepAliveRequests 0
        ManagerBalancerName testcluster
        AdvertiseFrequency 5
        ServerAdvertise on
        EnableMCPMReceive
    </VirtualHost>
</IfModule>

A: Basically you have two options - either create a cluster using JBoss own domain mode or extend you standalone configuration to contain required elements for session replication and sso.
In domain mode, most of the configurations are already present in EAP7 - just extend domain-full-ha profile.
Required changes include enabling distributable flag in your web app web.xml - simply add <distributable/> to your web.xml.
Next add single sign on flag to your undertow system:
  <host name="default-host" alias="localhost">
     <location name="/" handler="welcome-content"/>
     <filter-ref name="server-header"/>
     <filter-ref name="x-powered-by-header"/>
     <single-sign-on/>    <!-- FIXME:  enable SSO here -->
   </host>

And enable cache container required for clustered SSO to work - this requires Infinishpan subsystem, which you might now have, if you only extended standalone-ha profile. If you do not see Infinispan subsystem, have a look at standalone-full of standalone-full-ha profiles. If you do not have it already, add web cache:
 /subsystem=infinispan/cache-container=web/distributed-cache=concurrent:add
 /subsystem=infinispan/cache-container=web/distributed-cache=concurrent/store=file:add

Again, if you use full-ha profile of either standalone or domain mode, you will probably have these already.
Also you do not mention, if you use JBoss security domain for authorization or not. In case you use some custom auth mechanism, make sure you set the session cookie or tokens correctly - for correct domain and context etc.


text:
Q: How do I enable digest auth for Jetty fronting Elastic Search We've gotten Jetty running the HTTP front end of Elastic Search with BASIC authentication. We would like to use DIGEST authentication instead, but the Jetty documentation is hard to reconcile with the Jetty Elastic Search documentation; in particular, we're not sure where in the configuration chain we need to set the authentication method (the "auth-method" node in the Jetty docs).
FYI, we are using the stock jetty.xml, jetty-hash-auth.xml, and jetty-restrict-all.xml files.
FYI, we did see the word "BASIC" in the jetty-restrict-all.xml file, but changing that to "DIGEST" did not seem to enable digest authentication.
Has anybody been able to get this combination to work?


text:
Q: Implementing intrinsicContentSize correctly for sizes that depend on solved internal layout I have a solution that seems to be working, but I want to make sure that it's safe and using the tool as intended.  I can distill my problem down to this scenario - I have a UIView that contains multiple UILabels, stacked vertically.  Each label can be filled with arbitrary text that wraps and expands the label vertically.  The auto-layout constraints to stack the labels within the view is trivial.  What I'd like to do is have the UIView communicate its preferred height (the height of the view should fit all of the labels) to its owner via intrinsicContentSize.  However, the internal layout needs to be solved before I can return the appropriate height.  My understanding is that the solver is guaranteed to be complete after returning from [super layoutSubviews], this is what I'm doing:
- (void)layoutSubviews
{
    [super layoutSubviews];

    // solver's complete, now we can measure?
    [self invalidateIntrinsicContentSize];
}

My intrinsicContentSize implementation refers to the last label's frame to figure out the height.  This all seems to work for my current case, but it's making me nervous.  It seems to be that the solver asks for the intrinsicContentSize of the current view while it's laying out its internals.  I won't go into detail, but I ran into a case in which this pattern spun into an infinite loop.  I was able to fix this issue by tweaking some of my layout code - this did not inspire confidence.
Is there a better way to do this?  This seems like a common thing to want to do and when I started working on the problem I thought this was what intrinsicContentSize was for.  The implementations of intrinsicContentSize that I've seen have always been trivial - hardcoded size for a dimension, or measuring a single view that does not depend on a solved, internal layout.
Note, I can't just use measure the labels via the NSString sizeWith... methods because the internal layout is too complex.
Note, I explored using systemLayoutSizeFittingSize:, but calling this from intrinsicContentSize results in an infinite loop.
Any response would be appreciated!  Thanks in advance!

A: I'd like to update this thread and close out this question - I think there's still value here for other folks just starting with AutoLayout that might have a similar misunderstanding.  It's important to understand the real purpose of intrinsicContentSize - this is not how typical views communicate their preferred size to their parent views.  If a view uses AutoLayout to layout its children then it will use the constraints that define its internal layout to inform its parent of its size - specifically, it's going to be the constraints that relate the child views to their parent that are going to help define the parents size.  This is actually the part of AutoLayout that is both magical and frustrating - it's the sum of all of these constraints (both internal and external to your view) that result in the layout.  Intrinsic size is really only necessary for cases in which your view does not use AutoLayout to define its size (such as the classic case of a UILabel or UIImageView).
I think that early iOS bugs/inconsistencies related to multi-line text were what lead me down the road to intrinsicContentSize.  Multi-line text is still not perfect, but hopefully better in iOS10.

A: Here is the solution I came up with for this problem.
If you want to provide an intrinsicContentSize for a NSView that encapsulates other NSView instances, then there are two possibilities. Either all subviews have intrinsicContentSize values and you can work from those, otherwise there is at least one NSViewNoInstrinsicMetric value somewhere and you need to rely on the layout result of those subviews to compute your intrinsicContentSize.
In the second case, your intrinsicContentSize depends on the frame values of its subviews and you need to react to any changes to those frames, just like a label reacts to any change to the text it contains. You can do that using the NSViewFrameDidChangeNotification. Here is how I did it in my custom NSView subclass :
- (void)didAddSubview:(NSView *)subview
{
    [super didAddSubview:subview];
    subview.postsFrameChangedNotifications = YES;
    [[NSNotificationCenter defaultCenter] addObserver:self selector:@selector(subviewFrameDidChange:) name:NSViewFrameDidChangeNotification object:subview];
    [self setNeedsUpdateConstraints:YES];
    [self invalidateIntrinsicContentSize];
}

- (void)willRemoveSubview:(NSView *)subview
{
    [super willRemoveSubview:subview];
    [[NSNotificationCenter defaultCenter] removeObserver:self name:NSViewFrameDidChangeNotification object:subview];
    [self setNeedsUpdateConstraints:YES];
    [self invalidateIntrinsicContentSize];
}

- (void)subviewFrameDidChange:(NSNotification*)notif
{
    [self invalidateIntrinsicContentSize];
}


text:
Q: PHP Post email Sending email multiple times I have a script that sends an email with information stored in sessions - the info is collected from a form a user fills out. (the form 'action' is pointed to the code below)
However, when the submit button is clicked twice on the form for example, 2 emails are sent and when clicked 3 times, 3 emails are sent.
I want to make sure that only 1 email is sent and if any session is empty no email is to be sent:
<?php

session_start();

if(isset($_POST['email'])) {

$email_to = "recipient@emailaddress.com";
$email_subject = "My Subject";

$machine = implode(",", $_SESSION['machinesesh']); //required
$machine_type = implode(" ", $_SESSION['typesesh']);; // required
$address = $_SESSION['addresssesh']; //required
$county = $_SESSION['countysesh']; //required
$postcode = $_SESSION['postcodesesh']; //required
$workplace = implode(', ', $_SESSION['worksesh']); //required
$serving = implode(', ', $_SESSION['peoplesesh']);
$company_name = $_SESSION['namesesh']; // required
$visitorname = $_POST['yourname']; // required
$email_from = $_POST['email']; // required
$telephone = $_POST['telephone']; // not required

$email_message = "New email alert .\n\n";

function clean_string($string) {
  $bad = array("content-type","bcc:","to:","cc:","href");
  return str_replace($bad,"",$string);
}

$email_message .= "Name: ".clean_string($visitorname)."\n";
$email_message .= "Company: ".clean_string($company_name)."\n";
$email_message .= "Address Line 1: ".clean_string($address)."\n";
$email_message .= "County: ".clean_string($county)."\n";
$email_message .= "Postcode: ".clean_string($postcode)."\n";
$email_message .= "Machine(s) Wanted: ".clean_string($machine)."\n";
$email_message .= "Environment: ".clean_string($workplace)."\n";
$email_message .= "Serving: ".clean_string($serving)."\n";
$email_message .= "Email: ".clean_string($email_from)."\n";
$email_message .= "Telephone: ".clean_string($telephone)."\n";

// create email headers
$headers = 'From: sendaddress@email.com' . "\r\n".
'Reply-To: '.$email_from."\r\n" .
'X-Mailer: PHP/' . phpversion();
@mail($email_to, $email_subject, $email_message, $headers);

header("Location: http://www.example.com?tag=$machine");

?>

A: How about settings an $_SESSION["emailsent"] = 1; ? Before you send the email, check if the variable exists AND if it is set to 1! In this case you know, that in this session the email is only sent once!

A: You can try to erase the session after sending the email. The next time the form is submitted, it should check if session value is set or not. If not set, then it should not send email again.


text:
Q: How to factorize an operator? This may be very simple, but it's late in the night... I have two methods:
public IQueryable<Post> GetNotSticky()
{
   return Get().Where(p => p.Type != PostType.Sticky);
}

And the inverse
public IQueryable<Post> GetSticky()
{
   return Get().Where(p => p.Type == PostType.Sticky);
}

As you can see, the operator is the only difference. How to factorize this DRY violation into a nice common method? It feels simple, but right now the solution eludes me.

A: public IQueryable<Post> GetWithSticky(bool isSticky)
{
   return Get().Where(p => (p.Type == PostType.Sticky) == isSticky);
}


text:
Q: How to deal with air gapped builds when using vcpkg I'm in the process of creating a custom registry hosted in Azure DevOps.
The plan going forward will be to host some third party libraries as well as our own libraries in this custom registry.
Each project will then be using manifests in order to declare all dependencies and their required versions.
So far everything works as expected. I've already created a port out of one of our libraries and I'm currently distributing it via our custom registry.
Now the part I'm unsure how to handle.
At my company we do an "air gapped" build which means the source code is taken to some machine on a private network with no internet connection where the build is performed.
This is of course problematic as the air gapped machine will not have access to the custom ports registry we're hosting on ADO, nor will it have access to the repos hosting those projects we're distributing via our custom registry.
I'm trying to figure out a solution to this issue.
My first thought was to tell the Air Gap team to first clone the required repos to a USB stick. Then we could configure Visual Studio to use overlay-ports which would use the source that was cloned on to the USB stick and a custom port file. I have no idea if this would actually work.
I'm curious what other folks have done who might be in a similar situation?
Does anyone have any ideas on how I could handle this scenario using vcpkg?


text:
Q: C++ STL algorithm (list sort) OpenMP/multithreaded implementations I was attempting to accelerate one of the kernels of my code which at its essence boils down to a sort (I am running this on a CPU with several cores).
I discovered from this post (STL algorithms and concurrent programming) that some of these algorithms can be accelerated, for example, using OpenMP (see below).
I got quite decent speedup using __gnu_parallel::sort
E.g.
__gnu_parallel::sort(std::begin(X), std::end(X), [](X a, X b){ return a.member > b.member;});

It turns out that std::list is a much better container for my data. But this does not seem to have a parallel/multithreaded implementation for sort.
The post linked above is was dated 2010. I was wondering what the most current wisdom is on this.

A: In the case of Microsoft (prior to Visual Studio 2015), std::list::sort uses an array of lists, where array[i] is either an empty list or a list of size 2 to the power i (1,2,4,8, ... ). Nodes are taken from the original list one at a time and merged into the array, then the array is merged to form a single sorted list. Assuming compare overhead isn't excessive, this is a memory bound process, and multi-threading won't help due to the overhead of scanning a list to split up the list, nearly doubling the number of memory read operations. Here is example code for this type of list sort with the restriction that the compare is < not <=, so the operands have to be reversed to keep the sort stable.
#define NUMLISTS 32                     /* number of lists */
NODE * SortList(NODE *pList)
{
NODE * aList[NUMLISTS];                 /* array of lists */
NODE * pNode;
NODE * pNext;
int i;
    if(pList == NULL)                   /* check for empty list */
        return NULL;
    for(i = 0; i < NUMLISTS; i++)       /* zero array */
        aList[i] = NULL;
    pNode = pList;                      /* merge nodes into array */
    while(pNode != NULL){
        pNext = pNode->next;
        pNode->next = NULL;
        for(i = 0; (i < NUMLISTS) && (aList[i] != NULL); i++){
            pNode = MergeLists(aList[i], pNode);
            aList[i] = NULL;
        }
        if(i == NUMLISTS)
            i--;
        aList[i] = pNode;
        pNode = pNext;
    }
    pNode = NULL;                       /* merge array into one list */
    for(i = 0; i < NUMLISTS; i++)
        pNode = MergeLists(aList[i], pNode);
    return pNode;
}

NODE * MergeLists(NODE *pSrc1, NODE *pSrc2)
{
NODE *pDst = NULL;                      /* destination head ptr */
NODE **ppDst = &pDst;                   /* ptr to head or prev->next */
    if(pSrc1 == NULL)
        return pSrc2;
    if(pSrc2 == NULL)
        return pSrc1;
    while(1){
        if(pSrc2->data < pSrc1->data){  /* if src2 < src1 */
            *ppDst = pSrc2;
            pSrc2 = *(ppDst = &pSrc2->next);
            if(pSrc2 == NULL){
                *ppDst = pSrc1;
                break;
            }
        } else {                        /* src1 <= src2 */
            *ppDst = pSrc1;
            pSrc1 = *(ppDst = &pSrc1->next);
            if(pSrc1 == NULL){
                *ppDst = pSrc2;
                break;
            }
        }
    }
    return pDst;
}

update - Visual Studio 2015 and later switched to using iterators instead of lists for the merge sort, which eliminates allocation issues like no default allocator, and since the merging is done via splice() all on the same list, it provides exception safety (if a user compare throws an exception, the list is reordered, but all the nodes are there, assuming splice never throws an exception). VS2015 also switched to a top down merge sort, but a bottom up merge sort based on iterators could have been used. I'm not sure why the switch to top down was done, as it is about 40% slower for a large list (well beyond cache size) with randomly scattered nodes. Example iterator based code. Each iterator in the array points to the first node of a run of size 2 to the power i, or it is equal to list.end(), to indicate an empty run. The end of a run will be the first prior non "empty" entry in the array or a local variable iterator (all runs in the array are adjacent runs). All merges involve adjacent runs. The merge function takes 3 parameters, an iterator to the first node of the left run, a iterator to the first node of the right run, which is also the end of the left run, and an iterator to the end of the right run (which may be an iterator to the first node of the following run or list.end()).
template <typename T>
typename std::list<T>::iterator Merge(std::list<T> &ll,
                    typename std::list<T>::iterator li,
                    typename std::list<T>::iterator ri,
                    typename std::list<T>::iterator ei);

// iterator array size
#define ASZ 32

template <typename T>
void SortList(std::list<T> &ll)
{
    if (ll.size() < 2)                  // return if nothing to do
        return;
    std::list<T>::iterator ai[ASZ];     // array of iterators
    std::list<T>::iterator li;          // left   iterator
    std::list<T>::iterator ri;          // right  iterator
    std::list<T>::iterator ei;          // end    iterator
    size_t i;
    for (i = 0; i < ASZ; i++)           // "empty" array
        ai[i] = ll.end();
    // merge nodes into array
    for (ei = ll.begin(); ei != ll.end();) {
        ri = ei++;
        for (i = 0; (i < ASZ) && ai[i] != ll.end(); i++) {
            ri = Merge(ll, ai[i], ri, ei);
            ai[i] = ll.end();
        }
        if(i == ASZ)
            i--;
        ai[i] = ri;
    }
    // merge array into single list
    ei = ll.end();
    for(i = 0; (i < ASZ) && ai[i] == ei; i++);
    ri = ai[i++];
    while(1){
        for( ; (i < ASZ) && ai[i] == ei; i++);
        if (i == ASZ)
            break;
        li = ai[i++];
        ri = Merge(ll, li, ri, ei);
    }
}

template <typename T>
typename std::list<T>::iterator Merge(std::list<T> &ll,
                             typename std::list<T>::iterator li,
                             typename std::list<T>::iterator ri,
                             typename std::list<T>::iterator ei)
{
    std::list<T>::iterator ni;
    (*ri < *li) ? ni = ri : ni = li;
    while(1){
        if(*ri < *li){
            ll.splice(li, ll, ri++);
            if(ri == ei)
                return ni;
        } else {
            if(++li == ri)
                return ni;
        }
    }
}

A: Since C++ 17 you may consider parallel sort algorithms std::sort(std::execution::par, ...


text:
Q: How to convert a CLOB type column to LONG type column in Oracle DB I need a way to convert a CLOB type column to LONG type column in Oracle DB without losing data or creating another new table . I am not able to edit types in Oracle SQL Developer
Is there a way with cursors or something ?
Please Help
Thanks

A: Looks like creating a new column , porting contents of the old column to new column or creating a new table is the only way .
Thanks all !


text:
Q: Excel VBA Data Export Here is the code I have written to export data from access to excel but can not see any records.
Sub copyFromRecordset()

    Set conn = New ADODB.Connection
    Set wipData = New ADODB.Recordset

    conn.ConnectionString = conStr
    conn.Open

    With wipData
        .ActiveConnection = conn
        .Source = "WipBin"
        .LockType = adLockReadOnly
        .CursorType = adOpenForwardOnly
        .Open
    End With

    Worksheets.Add
    Range("A2").copyFromRecordset wipData

    wipData.Close
    conn.Close

End Sub

please advice

A: Why not Simply use the DoCmd.TransferSpreadsheet method
DoCmd.TransferSpreadsheet acExport, , "TABLE name", "filelocation"

https://msdn.microsoft.com/en-us/vba/access-vba/articles/acspreadsheettype-enumeration-access


text:
Q: How to print a text progress bar when some text was in front of it in python 3? Well, I mean this, here's my code:
def progress():
    for i in range(100):
        print('{0}\b\b'.format(i), end='', flush=True)
        time.sleep(0.1)

print('progress bar test: {0} finished!'.format(progress()))

I want the output like this:
progress bar test: 1.2.3..(and then print 'finished!')

but however I got this out put:
1.2.3...
progress bar test: None finished!

This is the question. And I also want to know if the number was smaller than 10, will the \b\b delete the in front text?

A: You function is not returning a value so you see None which is returned by default. You can return "finished" when your loop completes:
import time
def progress():
    for i in range(3):
        print('{0}.'.format(i), end='', flush=True)
        time.sleep(0.1)
    return "finished!"

print('progress bar test: {0}'.format(progress()))

If you want to be able to change the return value just pass in an arg:
def progress(end):
    for i in range(3):
        print('{0}.'.format(i), end='', flush=True)
        time.sleep(0.1)
    return end

print('progress bar test: {0} '.format(progress("finished!")))


text:
Q: Error handling on local network LAN Why, in the case of local networks, they judged that it is not necessary to systematically have a transmission protocol in DATA link layer to repeat the transmission of lost frames? And how are errors solved in this case?

A: Retransmission of data is left to the upper-layer protocols or applications, and not all of them do that. That leaves it up to the application to decide if it really needs all the data. There are multiple reasons:

*

*Once upon a time, back when network protocols were being developed,
the physical layer was often far less reliable than it is today, and
retransmission could have used all the resources of a link.

*Layer-2 protocols are mostly developed by the IEEE, independently of
any other organization, but the upper level protocols are mostly
developed by the IETF, two completely separate standards bodies. Even the IETF standards leave reliability to higher layers. For instance UDP, an unreliable transport protocols, was developed before TCP, a reliable transport protocol. It was thought that applications could handle reliability, but a reliable transport protocol was added later as a standard.

*Most of the time it is better if garbled data are dropped sooner in
the path, letting the reliable protocol or application miss them and
ask for any missing data sooner.

*Not all applications require dropped data to be retransmitted, and
some applications, e.g. real-time applications, can suffer due to retransmission,
which would cause out-of-order data delivery. Imagine if you are on a
phone call (VoIP), and the dropped data were received after data
already delivered. That would garble your call. Unreliable protocols
deliver data faster than reliable protocols, and that may be the
overriding factor for an application. Why force retransmitted data
and out-of-order data delivery on applications? If an application
needs that service, it can use a transport protocol
which provides that, or it can handle that on its own.

Errors in the Data-Link layer are considered corrupt frames and simply dropped, rather than waste processing power and bandwidth for possibly unnecessary retransmission.


text:
Q: C# using reflection to access Window properties How do you use reflection to access properties of Window objects?
Here's a minimal example:
.xaml file:
<Window x:Class="WpfApplication1.MainWindow"
        xmlns="http://schemas.microsoft.com/winfx/2006/xaml/presentation"
        xmlns:x="http://schemas.microsoft.com/winfx/2006/xaml"
        Title="MainWindow">
    <TextBox x:Name="Textbox" Text=""/>
</Window>

code behind file:
public class A
{
    public int Prop { get; set; }
}

public partial class MainWindow : Window
{
    public MainWindow()
    {
        InitializeComponent();
        this.Test.Text = "blah";

        PropertyInfo p1 = this.GetType().GetProperty("Textbox");
        PropertyInfo p2 = new A().GetType().GetProperty("Prop");
    }
}

p1 is null (p2 isn't as expected). Why is it so? Is the Window type some kind of a special object? Or is it because the type of Textbox is generated as an internal field?
    #line 5 "..\..\MainWindow.xaml"
    [System.Diagnostics.CodeAnalysis.SuppressMessageAttribute("Microsoft.Performance", "CA1823:AvoidUnusedPrivateFields")]
    internal System.Windows.Controls.TextBox Textbox;

A: All named elements become internal fields, after XAML is compiled. This:
<TextBox x:Name="Textbox" Text=""/>

ultimately transforms to this:
internal TextBox TextBox;

Hence, to obtain metadata you have to call GetField this way:
GetType().GetField("NameInXaml", BindingFlags.Instance | BindingFlags.NonPublic);

A: As you found out yourself, Textbox is a field, not a property. In addition, it is not public, so you should try the following:
FieldInfo f1 = this.GetType().GetField("Textbox", BindingFlags.NonPublic | BindingFlags.Instance);


text:
Q: angular set $scope.value in controller function is not working I am trying to set a angular variable value in controller function which is created by a directive. Somehow it is not working for some unknown reasons. The value is displayed when set independently but doesn't work when i try to assign value in a controller function.
My code is as below,
<!doctype html>

<meta charset="UTF-8" />

{{Details}}

             <collection collection='testdata'></collection>

Please help me to understand where i am making mistake and how it can be rectified.
Please help. Many thanks in advance.

A: The problem is that you are nesting MyController-controller when you create the directives in this circular way. The result is that the $scope.Details gets set on the specific nested scope instead of the one which is presenting the value in the view.
You can solve this by $emit the change which will send the new value upstream and finally reach the presenting scope value.
Here's an example

var mainApp = angular.module("mainApp", [])

mainApp.directive('collection', function () {
    return {
        restrict: "E",
        replace: true,
        scope: {collection: '=', showFn : '&'},
        template: "
<member ng-repeat='member in collection' member='member'></member>
"
    }
})

mainApp.directive('member', function ($compile) {
    var NewChild = "
{{member.TagName}}
";

    return {
        restrict: "E",
        replace: true,
        scope: {member: '=', ShowHideCtrlFunc : '&', ShowDetailsCtrlFunc : '&'},
        template: NewChild,
        controller: 'MyController',
        link: function (scope, element, attrs) {
            var collectionSt = '<collection collection="member.children"></collection>';
            if (angular.isArray(scope.member.children)) {
                    $compile(collectionSt)(scope, function(cloned, scope)   {
                        element.attr('xml-path', scope.member.TagPath);
                        element.append(cloned);
                     });
                    scope.ShowDetailsFunc = function() {
                        scope.ShowDetailsCtrlFunc(element);
                    }

            }
        }

    }
})

mainApp.controller('MyController', function ($scope) {
    $scope.testdata = [{"TagName":"MyRootNode","TagPath":">MyRootNode","children":[{"TagName":"LandXML","TagPath":">MyRootNode>ChildItems>LandXML","children":[{"TagName":"Units","TagPath":">MyRootNode>ChildItems>ChildItems[1]>Units","children":[{"TagName":"Imperial","TagPath":">MyRootNode>ChildItems>ChildItems[1]>ChildItems[1]>Imperial","children":[]},{"TagName":"Project","TagPath":">MyRootNode>ChildItems>ChildItems[1]>Project","children":[]},{"TagName":"Application","TagPath":">MyRootNode>ChildItems>ChildItems[1]>Application","children":[{"TagName":"Author","TagPath":">MyRootNode>ChildItems>ChildItems[1]>ChildItems[2]>Author","children":[]},{"TagName":"Alignments","TagPath":">MyRootNode>ChildItems>ChildItems[1]>Alignments","children":[]},{"TagName":"Roadways","TagPath":">MyRootNode>ChildItems>ChildItems[1]>Roadways","children":[{"TagName":"Roadway","TagPath":">MyRootNode>ChildItems>ChildItems[1]>ChildItems[3]>Roadway[1]","children":[]},{"TagName":"Roadway","TagPath":">MyRootNode>ChildItems>ChildItems[1]>ChildItems[3]>Roadway[2]","children":[]},{"TagName":"Roadway","TagPath":">MyRootNode>ChildItems>ChildItems[1]>ChildItems[3]>Roadway[3]","children":[]},{"TagName":"Roadway","TagPath":">MyRootNode>ChildItems>ChildItems[1]>ChildItems[3]>Roadway[4]","children":[]},{"TagName":"Roadway","TagPath":">MyRootNode>ChildItems>ChildItems[1]>ChildItems[3]>Roadway[5]","children":[]}]}]}]}]},{"TagName":"Surfaces","TagPath":">MyRootNode>ChildItems>Surfaces","children":[{"TagName":"Surface1","TagPath":">MyRootNode>ChildItems>ChildItems[2]>Surface1","children":[]},{"TagName":"Surface2","TagPath":">MyRootNode>ChildItems>ChildItems[2]>Surface2","children":[]}]}]}]

    $scope.Details = "defalut value";
    $scope.ShowDetailsCtrlFunc = function(element) {
            console.log("in function ShowDetailsCtrlFunc");
            var myxmlpath = angular.element(element).attr("xml-path")
            var detail = getObjects($scope.testdata, 'TagPath', myxmlpath)[0].TagName;
            console.log(detail);
            $scope.$emit('detailSelected',detail);
            //event.stopImmediatePropagation();
      };
      $scope.$on('detailSelected',function($event, message){
      $scope.Details = message;
    });
});
function getObjects(obj, key, val) {
    var objects = [];
    for (var i in obj) {
        if (!obj.hasOwnProperty(i)) continue;
        if (typeof obj[i] == 'object') {
            objects = objects.concat(getObjects(obj[i], key, val));
        } else if (i == key && obj[key] == val) {
            objects.push(obj);
        }
    }
    return objects;
}
<!doctype html>

<meta charset="UTF-8" />

{{Details}}

             <collection collection='testdata'></collection>


text:
Q: Using self for property return in python class I come from a javascript background which I think is the reason I have this question in the first place.
Is there any difference when using self to refer to properties of a class in method definitions.
E.G.
class Foo:
  _bar = 15;

  def getBar(self):
    return self._bar;

vs.
class Foo:
  _bar = 15;

  def getBar(self):
    return _bar;

I guess I could rephrase the question by saying what are the effects of using self when referring to properties inside the class. I.E. What if, for some strange reason, I wanted to return a global _bar variable inside of getBar() instead?

A: Your second code doesn't return the class attribute. It will return the global _bar if it exists, or raise a NameError exception otherwise. This is because the class scope is not automatically looked up from methods - only function scope and global scope is looked up when looking up variables.
You can return a class attribute (i.e. one which is shared between all instances) with either return Foo._bar or return self._bar.
To return an instance attribute you need to return self._bar


text:
Q: Verification: Hessian of the following composition. I was hoping that someone could verify the steps of computing a Hessian matrix.
I have the following function, $F:\mathbb{R}^n\to\mathbb{R}$,
$$F({\bf x}) = \sum_{i=1}^mf(g(A_i^T{\bf x}))$$
where each $A_i\in\mathbb{R}^{n\times n_i}$ translates ${\bf x}$ into some subvector of ${\bf x}$, for example, $A_1^T{\bf x} = (x_1,x_5,x_6,x_{10})$ (Notice that $A_i$ just consists of zeros and ones). Other functions are defined as $f:\mathbb{R}\to\mathbb{R}$ and $g:\mathbb{R}^{n_i}\to\mathbb{R}$.
I want to determine the Hessian, denoted $\nabla^2_{{\bf x}} F({\bf x})$.
Gradient
I have computed the gradient to be
\begin{align*}
\nabla_{\bf x}F({\bf x}) &= \sum_{i=1}^m \frac{\partial}{\partial {\bf x}}f(g(A_i^T{\bf x}))
\end{align*}
which component-wise is
\begin{align*}
[\nabla_{\bf x}F({\bf x})]_k&= \sum_{i=1}^mf'(g(A_i^T{\bf x}))\sum_{j=1}^{n_i}\frac{\partial g({\bf v})}{\partial v_j}\frac{\partial v_j}{\partial x_k}\\
\end{align*}
where ${\bf v} = A_i^T{\bf x}$.
Is the work so far correct? It seems to be dimensionally consistent. The term, $\frac{\partial v_j}{\partial x_k} = \frac{\partial [A_i^T{\bf x}]_j}{\partial x_k}$, can be simplified to read
\begin{align*}
\frac{\partial v_j}{\partial x_k} = \frac{\partial [A_i^T{\bf x}]_j}{\partial x_k} = [A_i{\bf e}_j]_k
\end{align*}
where ${\bf e}_j\in\mathbb{R}^{n}$ is a zero column vector with a $1$ in the $j^{th}$ position.
Hessian
To start, the Hessian is given by the expression
\begin{align*}
\nabla^2_{\bf x}F({\bf x}) &= \sum_{i=1}^m \frac{\partial^2}{\partial {\bf x}^2}f(g(A_i^T{\bf x}))
\end{align*}
which component-wise, differentiating the gradient, becomes
\begin{align*}
[\nabla^2_{\bf x}F({\bf x})]_{kl}&= \frac{\partial}{\partial x_l}\sum_{i=1}^mf'(g(A_i^T{\bf x}))\sum_{j=1}^{n_i}\frac{\partial g({\bf v})}{\partial v_j}[A_i{\bf e}_j]_k\\
&= \sum_{i=1}^m\frac{\partial f'(g(A_i^T{\bf x}))}{\partial x_l}\sum_{j=1}^{n_i}\frac{\partial g({\bf v})}{\partial v_j}[A_i{\bf e}_j]_k\\
&\qquad\qquad+ \sum_{i=1}^mf'(g(A_i^T{\bf x}))\sum_{j=1}^{n_i}\frac{\partial}{\partial x_l}\left[\frac{\partial g({\bf v})}{\partial v_j}[A_i{\bf e}_j]_k\right].
\end{align*}
Notice that the term $\frac{\partial g({\bf v})}{\partial v_j}$ is a function of ${\bf x}$. So, applying the product rule/chain rule, we obtain
\begin{align*}
[\nabla^2_{\bf x}F({\bf x})]_{kl}&= \sum_{i=1}^mf''(g(A_i^T{\bf x}))\left(\sum_{j=1}^{n_i}\frac{\partial g({\bf v})}{\partial v_j}[A_i{\bf e}_j]_k\right)\left(\sum_{j=1}^{n_i}\frac{\partial g({\bf v})}{\partial v_j}[A_i{\bf e}_j]_l\right)\\
&\qquad+\sum_{i=1}^mf'(g(A_i^T{\bf x}))\sum_{j=1}^{n_i}\frac{\partial^2 g({\bf v})}{\partial x_l\partial v_j}[A_i{\bf e}_j]_k
\end{align*}
where the term $\frac{\partial^2 g({\bf v})}{\partial x_l\partial v_j}$ is only non-zero if $[A_i^T{\bf x}]_j = x_l$.
Is the above work correct? Is there any way to verify its correctness other than rechecking each step?


text:
Q: Critical Number real life applications I've studying a lot Critical Number/Point and I have to give a presentation about it.
I am searching real life applications to explain the concept, but it's difficult to find.
Anyone here can give me some real life applications examples about critical number?

A: There are many problems in physics that use this concept. For example, when two atoms come together to form a molecule. They come closer to each other because the energy of the system is smaller if they share electrons. But if they are too close, the electrons cannot screen the nuclei. The two nuclei will repel, so at very short distances the energy is increased. The energy as a function of distance has a minimum (critical point), so the nuclei will be at that particular distance. Google atomic potential.


text:
Q: Equivalent to exclusion constraint composed of integer and range I need to have something equivalent to this exclusion constraint
drop table if exists t;
create table t (
    i int,
    tsr tstzrange,
    exclude using gist (i with =, tsr with &&)
);
ERROR:  data type integer has no default operator class for access method "gist"
HINT:  You must specify an operator class for the index or define a default operator class for the data type.

I guess the problem is obvious from the error message. How to do it?

A: You need to install the additional module btree_gist to make it work. The module installs the missing operator class.
Details in this related answer:

*

*Exclusion constraint on a bitstring column with bitwise AND operator
More at this answer on dba.SE:

*

*PostgreSQL EXCLUDE USING error: Data type integer has no default operator class


text:
Q: Read an excel uploaded through FileUpload I have an ASP.NET web application that has a fileupload control to allow users to upload an excel file for it to read.
I'm using an OleDBConnection and I feel like my connection string or querystring is wrong since the app keeps throwing OleDBExceptions at me (ouch!). What would be a good way to save or access the uploaded files?
Here's the connection string:
olcon.ConnectionString = @"Provider=Microsoft.ACE.OLEDB.12.0;Data Source=" + Server.MapPath(fileupFile.FileName) + ";Extended Properties=Excel 12.0";

Query string:
OleDbCommand olcmd = new OleDbCommand("SELECT * FROM [Sheet1$]", olcon);

A: I suspect the issue is rooted in the call to Server.MapPath(fileupFile.FileName). The FileName property is a convenience property to indicate the original file name of the content being uploaded to the server. It doesn't necessarily indicate the location or the name of the file when (and if) you save it on the server.
It would seem that you still need to receive the file on the server side and save it to disk. There are several ways to do so. The SaveAs() method is perhaps the easiest, but you also have the FileBytes and FileContent properties which give you access to the uploaded file as a byte array or a stream, respectively.
If you first save the document to your hard drive and then construct your connection string, I believe that will resolve the issue.
Here is a simple example of saving an uploaded file. Assume that the "~/Documents" folder has granted the IIS worker process write permissions (or that you use impersonation and your authenticated user has write permissions):
var targetfilepath = Path.Combine(Server.MapPath(~/Documents), fileupFile.FileName);
fileupFile.SaveAs(targetfilepath);

var connstring = "Provider=Microsoft.ACE.OLEDB.12.0;Data Source=" + targetfilepath + ";Extended Properties=Excel 12.0";
// ...

Good luck.
By the way, and you may already know, there is an excellent reference on Excel 2007 connection string properties at connectionstrings.com: http://connectionstrings.com/excel-2007


text:
Q: Is there a way to distinguish normal loop termination from break termination in Rust? Idiomatic for/else in rust:
In Python, I can use for/else to check whether or not a for loop terminated at a break statement or finished 'normally':
prod = 1
for i in range(1, 10):
    prod *= i
    if prod > 123:
        break
else:
    print("oops! loop terminated without break.")

Is there a similar way to do that in Rust? This is the closest I have come, but it is not particularly similar.
let mut prod = 1u64;
let mut found = false;
for i in 1..10 {
    prod *= i;
    if prod > 123 {
        found = true;
        break;
    }
}
if !found {
    println!("oops! loop terminated without break.");
}

There seems to be a discussion about this on rust internals; however, that is more about future possibilities than what is idiomatic.
In Python, idiomatic code is called pythonic - is there a similar word for idiomatic Rust code?

A: A simple None initialized value provides a reasonably convenient way to do this:
let mut prod = 1u64;
let mut value = None;
for i in 1..10 {
    prod *= i;
    if prod > 123 {
        value = Some(prod);
        break;
    }
}
if value.is_none() {
    println!("oops! loop terminated without break.");
}

A: Since Rust 1.65, you can break out of blocks, optionally with a value. Cases like that were even mentioned in the RFC as a motivation:
let value = 'found: {
    for i in 1..2 {
        prod *= i;
        if prod > 123 {
            break 'found Some(prod);
        }
    }
    println!("oops! loop terminated without break.");
    None
};

Playground.

A: I don't know how idiomatic it is but sometimes I write this:
fn main() {
    let mut prod = 1u64;
    let value = 'found: loop {
        for i in 1..2 {
            prod *= i;
            if prod > 123 {
                break 'found Some(prod);
            }
        }
        println!("oops! loop terminated without break.");
        break 'found None;
    };
    //Here value is Option<u64> with the result.
}

That is, an outer labelled loop that can be broken from inside when you are ready. You can even give it a type with the break label value` syntax.

A: Usually you can translate to some iterator pattern instead of the for loop:
fn main() {
    let mut prod = 1u64;
    if let Some(i) = (1..10)
        .filter_map(|i| {
            prod *= i;
            if prod > 123 {
                Some(i)
            } else {
                None
            }
        })
        .next()
    {
        println!("item found for {i}");
    }
}

Playground

A: I have seen people use a temporal locale function, Javascript style:
fn main() {
    let mut prod = 1u64;
    let value = (|| {
        for i in 1..10 {
            prod *= i;
            if prod > 123 {
                return Some(prod);
            }
        }
        println!("oops! loop terminated without break.");
        None
    })();
}

You define a temporary function and immediately call it, this way you can have return inside. This trick is also used to propagate errors with ?, while the try {} statement is not stable.

A: How about this?
let result = {
    for i in 1..10 {
        prod *= i;
        if prod > 123 {
            Ok(())
        }
    }
    Err(())
}


text:
Q: Using Apache CXF with Aegis databinding and JAX-WS front-end I'm new to the web services. Trying to learn something related to Apache CXF. Can anyone please give me an example (along with configuration, so that it can run on any application server say Tomcat) that uses Aegis data binding with JAX-WS as front-end?
I.e. the web service should use Aegis data binding with JAX-WS as front-end. The web service client may use any binding, any front-end, or it may be a simple standalone application also.


text:
Q: Why does Java 8 generate a numerically named file in the current directory? Noticed an odd behavior that started after moving from Java 7 to Java 8 (HotSpot 64-Bit Server) on Red Hat Linux.  The problem happens for one particular user, whose jobs typically run in batch and who cannot log on at a signon prompt.  Each time a command such as "java -jar hello.jar" is run by this user, a 32 KB binary file with a numeric filename (such as 18362 or 24339) is created in the current directory.
The first several readable phrases from one of the numeric files look like the following:
8J0sun.rt._sync_Inflations8J0sun.rt._sync_Deflations@J8sun.rt._sync_ContendedLockAttempts8J0sun.rt._sync_FutileWakeups0J(sun.rt._sync_Parks@J8sun.rt._sync_EmptyNotifications8J0sun.rt._sync_Notifications8J0sun.rt._sync_SlowEnter8J0sun.rt._sync_SlowExit8J0sun.rt._sync_SlowNotify8J0sun.rt._sync_SlowNotifyAll8J0sun.rt._sync_FailedSpins@J8sun.rt._sync_SuccessfulSpins8J0sun.rt._sync_PrivateA8J0sun.rt._sync_PrivateB@J8sun.rt._sync_MonInCirculation8J0sun.rt._sync_MonScavenged8J0sun.rt._sync_MonExtant
We now have over 6,000 32 KB files with a numeric filename in the directory from which the "java" command is launched.
This is on a production server.  We don't have the same problem on a development server.  However, the user in question has the ability to log onto the development server (say with putty) -- whereas the user can't do that on the production server.
I'd like to know what causes the creation of all these files and how to prevent it.

A: Searching on a couple of the symbols in the "readable" line seems to point to hsperfdata artifacts; see this Github hsperfdata parser project. They are very likely safe to remove after java exits.
Note: If these are hsperfdata artifacts, the numbers are process identifiers. You might have these lying around on the development system in the usual temporary directories.
(Original hypothesis that the leftover files might be class file artifacts extracted from the JAR file removed.)


text:
Q: DataContractJsonSerializer.ReadObject sometimes throws: The token " was expected but found 'Â' I have an issue that occurs for our customers, but doesn't occur for any of the developers when using the same application version and data.
DataContractJsonSerializer.ReadObject throws this exception:

Deserialising: There was an error deserializing the object of type {type}.
The token '"' was expected but found 'Â'.

This exception is not thrown when any of the developers or I attempt to reproduce it, but consistently occurs on the client systems. Everyone is using Windows 7 64bit.
My best guess is that this is a text encoding issue, as a UTF-8 byte pair of 0xC2,0x?? would end up as  if converted to Windows 1252 or ISO 8859-1.
The conversion to UTF-8 is being done in code:
string content = GetSerialised();
byte[] result = Encoding.UTF8.GetBytes(content);
using (var s = new MemoryStream(result))
{
    var outputSerialiser = new DataContractJsonSerializer(typeof(T), null, int.MaxValue, true, null, false);
    return (T) outputSerialiser.ReadObject(s);
}

The content is displayed with the error message, so we're able to verify that it is valid JSON text. It does contain a ¦ quoted in a JSON string (that's 0xC2,0xA6 in UTF-8, so a likely culprit for the corrupted character).
So we have valid JSON in a .Net string instance, we convert it using UTF8.GetBytes, but when DataContractJsonSerializer.ReadObject reads it we get a corruption.
Any idea why this is happening? Why does it occur on some machines and not others?

A: This is due to a bug in the DataContractJsonSerializer.ReadObject(Stream) method that's fixed in a patch to .Net 4.0 - the developers have the patch but our users do not, which is why we didn't get it.
The bug appears if you have lots of non-ANSI characters in a single serialised object.
I wrote a simple app to check for the issue:
// Create a JSON string with more non-ANSI characters than can be handled
char test = (char) 0x6cd5;
string content = "\"" + new string(test, 2048) + "\"";

// Use a MemoryStream
byte[] result = Encoding.UTF8.GetBytes(content);
using (var s = new MemoryStream(result))
{
    var outputSerialiser = new DataContractJsonSerializer(typeof(string));

    // This line will throw the exception
    string output = (string) outputSerialiser.ReadObject(s);
}

None of the developer machines throw an exception here, but our clients' PCs do.
The fix is to use a buffered JSON reader instead of a MemoryStream:
using (var jsonReader = JsonReaderWriterFactory.CreateJsonReader(result, XmlDictionaryReaderQuotas.Max))
{
    var outputSerialiser = new DataContractJsonSerializer(typeof(string));
    string output = (string) outputSerialiser.ReadObject(jsonReader);
}


text:
Q: Screen keeps freezing, then kernel panic I have a Hp DV6-3079tx.
It has a ATI Radeon graphics chip.
The system seems to randomly freeze up, sometimes it will unfreeze, other times it will un-freeze, freeze, then go black.
Looking in the full log with this exerpt.
Jul  3 16:15:23 hailwood-ubu kernel: [ 4211.907266] ------------[ cut here ]------------
Jul  3 16:15:23 hailwood-ubu kernel: [ 4211.907303] WARNING: at /build/buildd/linux-2.6.38/drivers/gpu/drm/radeon/radeon_fence.c:248 radeon_fence_wait+0x36f/0x3e0 [radeon]()
Jul  3 16:15:23 hailwood-ubu kernel: [ 4211.907309] Hardware name: HP Pavilion dv6 Notebook PC
Jul  3 16:15:23 hailwood-ubu kernel: [ 4211.907314] GPU lockup (waiting for 0x0005418F last fence id 0x00054188)
Jul  3 16:15:23 hailwood-ubu kernel: [ 4211.907318] Modules linked in: usb_storage uas cryptd aes_x86_64 aes_generic binfmt_misc parport_pc ppdev snd_hda_codec_hdmi snd_hda_codec_idt snd_hda_intel snd_hda_codec snd_hwdep snd_seq_midi arc4 snd_pcm snd_rawmidi ath9k snd_seq_midi_event snd_seq snd_timer radeon snd_seq_device hp_wmi ttm mac80211 sparse_keymap uvcvideo ath9k_common ath9k_hw i7core_edac ath psmouse snd edac_core videodev joydev v4l2_compat_ioctl32 cfg80211 serio_raw drm_kms_helper drm soundcore snd_page_alloc i2c_algo_bit hp_accel lis3lv02d video input_polldev lp parport usbhid hid ahci r8169 libahci
Jul  3 16:15:23 hailwood-ubu kernel: [ 4211.907393] Pid: 1592, comm: gnome-shell Not tainted 2.6.38-8-generic #42-Ubuntu
Jul  3 16:15:23 hailwood-ubu kernel: [ 4211.907398] Call Trace:
Jul  3 16:15:23 hailwood-ubu kernel: [ 4211.907409]  [<ffffffff81065cef>] ? warn_slowpath_common+0x7f/0xc0
Jul  3 16:15:23 hailwood-ubu kernel: [ 4211.907417]  [<ffffffff81065de6>] ? warn_slowpath_fmt+0x46/0x50
Jul  3 16:15:23 hailwood-ubu kernel: [ 4211.907447]  [<ffffffffa03076df>] ? radeon_fence_wait+0x36f/0x3e0 [radeon]
Jul  3 16:15:23 hailwood-ubu kernel: [ 4211.907456]  [<ffffffff81087f30>] ? autoremove_wake_function+0x0/0x40
Jul  3 16:15:23 hailwood-ubu kernel: [ 4211.907486]  [<ffffffffa0307fc1>] ? radeon_sync_obj_wait+0x11/0x20 [radeon]
Jul  3 16:15:23 hailwood-ubu kernel: [ 4211.907499]  [<ffffffffa01cdb0d>] ? ttm_bo_wait+0xfd/0x1b0 [ttm]
Jul  3 16:15:23 hailwood-ubu kernel: [ 4211.907512]  [<ffffffffa01d07e6>] ? ttm_bo_move_accel_cleanup+0x1c6/0x260 [ttm]
Jul  3 16:15:23 hailwood-ubu kernel: [ 4211.907542]  [<ffffffffa030827f>] ? radeon_move_blit.clone.0+0x11f/0x180 [radeon]
Jul  3 16:15:23 hailwood-ubu kernel: [ 4211.907572]  [<ffffffffa0308595>] ? radeon_move_ram_vram.clone.2+0x125/0x150 [radeon]
Jul  3 16:15:23 hailwood-ubu kernel: [ 4211.907580]  [<ffffffff81124507>] ? vma_prio_tree_next+0x47/0x70
Jul  3 16:15:23 hailwood-ubu kernel: [ 4211.907592]  [<ffffffffa01d33db>] ? ttm_eu_list_ref_sub+0x3b/0x60 [ttm]
Jul  3 16:15:23 hailwood-ubu kernel: [ 4211.907622]  [<ffffffffa03087a8>] ? radeon_bo_move+0x1e8/0x1f0 [radeon]
Jul  3 16:15:23 hailwood-ubu kernel: [ 4211.907635]  [<ffffffffa01ce89e>] ? ttm_bo_handle_move_mem+0x12e/0x3d0 [ttm]
Jul  3 16:15:23 hailwood-ubu kernel: [ 4211.907647]  [<ffffffffa01cf982>] ? ttm_bo_move_buffer+0x142/0x160 [ttm]
Jul  3 16:15:23 hailwood-ubu kernel: [ 4211.907659]  [<ffffffffa01d33db>] ? ttm_eu_list_ref_sub+0x3b/0x60 [ttm]
Jul  3 16:15:23 hailwood-ubu kernel: [ 4211.907671]  [<ffffffffa01cfa36>] ? ttm_bo_validate+0x96/0x120 [ttm]
Jul  3 16:15:23 hailwood-ubu kernel: [ 4211.907700]  [<ffffffffa030974c>] ? radeon_bo_list_validate+0x7c/0xe0 [radeon]
Jul  3 16:15:23 hailwood-ubu kernel: [ 4211.907735]  [<ffffffffa03225d6>] ? radeon_cs_parser_relocs+0x236/0x270 [radeon]
Jul  3 16:15:23 hailwood-ubu kernel: [ 4211.907770]  [<ffffffffa0322a61>] ? radeon_cs_ioctl+0xa1/0x1e0 [radeon]
Jul  3 16:15:23 hailwood-ubu kernel: [ 4211.907778]  [<ffffffff81134b53>] ? vma_link+0xc3/0x100
Jul  3 16:15:23 hailwood-ubu kernel: [ 4211.907795]  [<ffffffffa00b3384>] ? drm_ioctl+0x3e4/0x4c0 [drm]
Jul  3 16:15:23 hailwood-ubu kernel: [ 4211.907830]  [<ffffffffa03229c0>] ? radeon_cs_ioctl+0x0/0x1e0 [radeon]
Jul  3 16:15:23 hailwood-ubu kernel: [ 4211.907840]  [<ffffffff8117648f>] ? do_vfs_ioctl+0x8f/0x360
Jul  3 16:15:23 hailwood-ubu kernel: [ 4211.907847]  [<ffffffff811767f1>] ? sys_ioctl+0x91/0xa0
Jul  3 16:15:23 hailwood-ubu kernel: [ 4211.907855]  [<ffffffff8100c002>] ? system_call_fastpath+0x16/0x1b
Jul  3 16:15:23 hailwood-ubu kernel: [ 4211.907860] ---[ end trace ff6b61aa2bd9f6b5 ]---
Jul  3 16:15:23 hailwood-ubu kernel: [ 4211.909135] radeon 0000:01:00.0: GPU softreset
Jul  3 16:15:23 hailwood-ubu kernel: [ 4211.909140] radeon 0000:01:00.0:   GRBM_STATUS=0xF5702828
Jul  3 16:15:23 hailwood-ubu kernel: [ 4211.909145] radeon 0000:01:00.0:   GRBM_STATUS_SE0=0xFC000005
Jul  3 16:15:23 hailwood-ubu kernel: [ 4211.909151] radeon 0000:01:00.0:   GRBM_STATUS_SE1=0x00000007
Jul  3 16:15:23 hailwood-ubu kernel: [ 4211.909156] radeon 0000:01:00.0:   SRBM_STATUS=0x20000AC0
Jul  3 16:15:23 hailwood-ubu kernel: [ 4211.909187] radeon 0000:01:00.0:   GRBM_SOFT_RESET=0x00007F6B
Jul  3 16:15:23 hailwood-ubu kernel: [ 4211.909294] radeon 0000:01:00.0:   GRBM_STATUS=0x00003828
Jul  3 16:15:23 hailwood-ubu kernel: [ 4211.909299] radeon 0000:01:00.0:   GRBM_STATUS_SE0=0x00000007
Jul  3 16:15:23 hailwood-ubu kernel: [ 4211.909304] radeon 0000:01:00.0:   GRBM_STATUS_SE1=0x00000007
Jul  3 16:15:23 hailwood-ubu kernel: [ 4211.909309] radeon 0000:01:00.0:   SRBM_STATUS=0x200000C0
Jul  3 16:15:23 hailwood-ubu kernel: [ 4211.910317] radeon 0000:01:00.0: GPU reset succeed
Jul  3 16:15:23 hailwood-ubu kernel: [ 4211.951371] radeon 0000:01:00.0: WB enabled
Jul  3 16:15:23 hailwood-ubu kernel: [ 4211.968136] [drm] ring test succeeded in 2 usecs
Jul  3 16:15:23 hailwood-ubu kernel: [ 4211.968153] [drm] ib test succeeded in 3 usecs
Jul  3 16:15:34 hailwood-ubu kernel: [ 4223.287726] radeon 0000:01:00.0: GPU lockup CP stall for more than 10020msec

It looks like my graphics chip is having some issues.
Can anyone tell me what is happening?

A: Reboot using a LiveCD and choose the option Memory Check, also check the GPU temperature when running intensive work.

A: You can try a different version of Ubuntu...
What version of Ubuntu are you running?
I have one graphics card that's decently old, and apparently the only set of good drivers work in Ubuntu 8.04 or some ridiculously old version like that.  Admittedly I haven't dug into the problem to see if there is a fix to make them work with the current version, but at the moment I'm running the most recent Ubuntu with inferior graphics because I'm using the default drivers for it.
Also, don't forget the memory check and GPU temperature, as suggested by juancarlospaco.  This could indicate hardware failure/malfunction.


text:
Q: Deploying a new database on a new server, an msbuild ssdt rookie issue I have this issue, but I don't know which user to should I give dbo permission when the one making deployments to the server is the sqlpackage with msbuild and not an actual user.
*** Could not deploy package.
 Error SQL72014: .Net SqlClient Data Provider: Msg 262, Level 14, State 1, Line 1 CREATE DATABASE permission denied in database 'master'.
 Error SQL72045: Script execution error.  The executed script:
 CREATE DATABASE [$(DatabaseName)]
 ON
 PRIMARY(NAME = [$(DatabaseName)], FILENAME = N'$(DefaultDataPath)$(DefaultFilePrefix)_Primary.mdf')
 LOG ON (NAME = [$(DatabaseName)_log], FILENAME = N'$(DefaultLogPath)$(DefaultFilePrefix)_Primary.ldf') COLLATE SQL_Latin1_General_CP1_CI_AS

Things I've already tried:

*

*Give full permissions to NETWORKSERVICE

*Give full permissions to SYSTEM

*Checked the TCP/IP Connection properties (just in case, but unuseful since the problem says permissions...)

*@EDIT: Give sysadmin permissions to DOMAIN\MY_COMPILER_COMPUTER$

I hope this is an easy one for those experienced with this.


text:
Q: How can I manage duplicate methods for multiple models? For example, I would like to have a method name 'owner' which returns the owner of the article or comment on two models, Article, and Comment.
Rather than adding
def owner
    user
end

to every model, is there a way to manage multiple models with 1 method?

A: There are several ways to handle this:

*

*include a module containing the method in each model

*add the instance method to the ActiveRecord Base

*add a method_missing which is more or less the same principle as above but a bit more hacky
The pros of 1 is that it includes the method only in the model you want but yo have to include a line...
The pros of 2 & 3 is that you'll have no need to include the module but every model will have it, even if not relevant.


text:
Q: How to optmize integrals in numba? I am trying to implement the Galerkin discontinous method in Python to solve Partial Differential Equations. This method involves solving a large number of systems of ordinary differential equations with the form

where the matrix $M^i$ is definied by the $L^2$ product, i.e. each entry of the matrix is an integral of the product of two functions $N_k$, and $N_l$, that is

where $I_i=[-1,1]$.
To do these integrals, I have defined the function DotProduct(G, H) as follows
from scipy.integrate import quad

def DotProduct(G, H):
    F = lambda x:G(x)*H(x)
    w = quad(F, -1.0, 1.0)[0]
return w

The use of this function is as follows
f01 = lambda x: 0.5*(1-x)
f11 = lambda x: 0.5*(1+x)
Integral = DotProduct(f01, f11)
print(Integral)

My problem is that 90% of the execution time of the code is dedicated to calculating these integrals.
I've read about speeding up the computation time for integrals using numba, but have had no success implementing it in the function DotProduct(G, H).
Does anyone have any advice?

A: Almost all SciPy function are not yet supported by Numba. This includes quad. That being said, the function called by quad could be accelerated by Numba. The point is you cannot use lambda functions the way you do too because it is also not supported by Numba. You need to move f01 and f11 in the jitted function.
import numba as nb
from scipy.integrate import quad

@nb.njit
def F(x):
    G = lambda x: 0.5*(1-x)
    H = lambda x: 0.5*(1+x)
    return G(x) * H(x)

def DotProduct():
    w = quad(F, -1.0, 1.0)[0]
    return w

Integral = DotProduct()
print(Integral)

This is 36% faster on my machine but this is not a case where Numba is really useful... Numba can be faster at least if the F function is expensive. The initial code takes less than 6 us to complete. This is far too small.


text:
Q: Create a class that is the "same" as another class I am using Ruby on Rails 3.0.10 and I would like to create a new class\model Class2 that has the same behavior (methods, constants, ...) and that is related to the same database table and ... of a class\model Class2. That is, the Class2 must be exactly the same as the Class1.
How can I do that?

Motivations

*

*I would like to do that because I have the Class1 (and a related database table) that is used to store some association data (:has_many and :belongs_to) and exactly the same associations can be handled also by the Class2 in a equal way as the Class1 makes.

*Also, I would like to do that because I would "organize" application files keeping the "Ruby on Rails Way" of make things. That is, I would like to create related view files in a separated folders for both the Class1 and the Class2 (maybe, it is just my "standardize things mania"!).
What about my motivations in order to create the new Class1?

What problems could I have in future developments?

A: You want to extend the class? this should do the trick:
class MoreUsers < Users
  set_table_name "users"
end

Hope this is the answer you're looking for.

A: Extend class:
class Class2 < Class1
end


text:
Q: pandas.str.findall() returning multiple instance of the same value but with reduce characters so I am having trouble with Pandas for a series findall(). currently I am trying to look at a report and retrieving all the electric components. Currently the report is either a line or a paragraph and mention components in a standardize way. I am using this code
failedCoFromReason =rlist['report'].str.findall(r'([CULJRQF]([\dV]{2,4}))',flags=re.IGNORECASE)

It returns the components but it also returns a repeat value of the number like this [('r919', '919'), ('r920', '920')]
I would like it just to return [('r919'), ('r920')] but I am struggling with getting it to work. Pretty new to pandas and regex and confused how to search. I have tried greedy and non greedy searches but it didn't work.

A: See the Series.str.findall reference:

Equivalent to applying re.findall() to all the elements in the Series/Index.

The re.findall references says that "if one or more groups are present in the pattern, return a list of groups; this will be a list of tuples if the pattern has more than one group."
So, all you need to do is actually remove all capturing parentheses in this case, as all you need is to get the whole match:
rlist['report'].str.findall(r'[CULJRQF][\dV]{2,4}', flags=re.I)

In other cases, when you need to preserve the group (to quantify it, or to use alternatives), you need to change the capturing groups to non-capturing ones:
rlist['report'].str.findall(r'(?:[CULJRQF](?:[\dV]{2,4}))', flags=re.I)

Though, in this case, it is quite redundant.