text:
Q: I am using a git repo called LikeButton, but the state of my button keeps jumping around in my recyclerview? I am using a git repo called LikeButton, but the state of my button keeps jumping around in my recyclerview? Here is the repo https://github.com/jd-alexander/LikeButton. Basically when I click on a recyclerview item, it sets a textview to the word true or false based on if the user liked the post or not, and this works. However, the state of my button is doing some weird stuff, it jumps around...
Here is my Adapter, is their anything wrong with it?
public class ViewpagerAdapter extends RecyclerView.Adapter<ViewpagerAdapter.ViewDashboard>{
    private LayoutInflater mLayoutInflater;

    private ArrayList<QuestionData> data = new ArrayList<>();

    public ViewpagerAdapter(Context context) {
        mLayoutInflater=LayoutInflater.from(context);
    }

    public void setBloglist(ArrayList<QuestionData> listBlogs) {
        this.data = listBlogs;
        notifyItemRangeChanged(0,listBlogs.size());
    }

    @Override
    public ViewDashboard onCreateViewHolder(ViewGroup parent, int viewType) {
        View view = mLayoutInflater.inflate(R.layout.customizejson, parent, false);
        ViewDashboard viewholder = new ViewDashboard(view);
        return viewholder;
    }

    @Override
    public void onBindViewHolder(ViewDashboard holder, int position) {
        QuestionData questionHolder = data.get(position);
        holder.questionText.setText(questionHolder.getMtext());
        //This sets the text, to a true or a false String
        holder.mStudentVoted.setText(questionHolder.getVoters());
        holder.mLikeButton.setTag(holder);
    }

    @Override
    public int getItemCount() {
        return data.size();
    }

    class ViewDashboard extends RecyclerView.ViewHolder {
        private TextView questionText;
        private LikeButton mLikeButton;
        private TextView mStudentVoted;
        public ViewDashboard(View itemView) {
            super(itemView);
            questionText = (TextView)itemView.findViewById(R.id.questionText);
            mStudentVoted = (TextView)itemView.findViewById(R.id.studentVoted);

            mLikeButton = (LikeButton)itemView.findViewById(R.id.like_button_viewpager);

            mLikeButton.setOnLikeListener(new OnLikeListener() {
                @Override
                public void liked(LikeButton likeButton) {
                    Voting voting = new Voting(getAdapterPosition(),ViewpagerAdapter.this, questionId);
                    voting.onUpVote();
                }

                @Override
                public void unLiked(LikeButton likeButton) {
                    Voting voting = new Voting(getAdapterPosition(),ViewpagerAdapter.this, questionId);
                    voting.onDownVote();
                }
            });
        }
    }
}

Voting Class
public class Voting {

private int adapterPosition;
private RecyclerView.Adapter adapter;
private String stringId;
private TextView studentVoted;
//TODO Trim Constructor
public Voting(int adapterPosition,final RecyclerView.Adapter adapter, TextView questionId, TextView studentVoted) {
    stringId = questionId.getText().toString();
    this.adapter = adapter;
    this.studentVoted=studentVoted;
}

public void onUpVote() {

    final RequestQueue mRequestQueue = VolleySingleton.getInstance().getRequestQueue();

    StringRequest postVoteUp = new StringRequest(Request.Method.PUT, PUT_VOTE_UP, new Response.Listener<String>() {
        @Override
        public void onResponse(String response) {
            System.out.println("Succesful Upvote The Students Value is " + studentVoted);

        }

    }, new Response.ErrorListener() {
        @Override
        public void onErrorResponse(VolleyError error) {
            System.out.println("failed Upvote");

        }
    });
    mRequestQueue.add(postVoteUp);
}
public void onDownVote() {
    final RequestQueue mrequestQueue = VolleySingleton.getInstance().getRequestQueue();
    //TODO Delete Token(inserted for student 3 for testing purposes)
    StringRequest postVoteDown = new StringRequest(Request.Method.PUT, PUT_VOTE_DOWN, new Response.Listener<String>() {
        @Override
        public void onResponse(String response) {
            //TODO OnResponse, must setLiked(False)
            //Succesful downVote The Students Value is true
            //studentVoted.setText("false");

            System.out.println("Succesful downVote The Students Value is "+studentVoted);
        }

    }, new Response.ErrorListener() {
        @Override
        public void onErrorResponse(VolleyError error) {

            System.out.println("failed downVote");
        }
    });
    mrequestQueue.add(postVoteDown);
}
public void realTimeUpVoting(TextView textView){
    String voteString= textView.getText().toString();
    int voteNumber=Integer.parseInt(voteString)+1;
    textView.setText("" + voteNumber);
}
public void realTimeDownVoting(TextView textView){
    String voteString= textView.getText().toString();
    int voteNumber=Integer.parseInt(voteString)-1;
    textView.setText("" + voteNumber);
}
}

Json Request and Parsing Methods
public void JsonRequestMethod() {
    mVolleySingleton = VolleySingleton.getInstance();
    mRequestQueue = mVolleySingleton.getRequestQueue();
    JsonArrayRequest request = new JsonArrayRequest(Request.Method.GET, URL_HOME, (String) null, new Response.Listener<JSONArray>() {
        @Override
        public void onResponse(JSONArray response) {
            try {
                mListblogs.clear();
                mListblogs = new YourTask().execute(response).get();

            } catch (InterruptedException | ExecutionException e) {
                e.printStackTrace();
            }
        }
    }, new Response.ErrorListener() {
        @Override
        public void onErrorResponse(VolleyError error) {
        }
    });
    mRequestQueue.add(request);
}

private ArrayList<QuestionData> parseJSONResponse(JSONArray response) {
    if (!response.equals("")) {
        try {
            StringBuilder data = new StringBuilder();
            for (int x = 0; x < response.length(); x++) {
                JSONObject currentQuestions = response.getJSONObject(x);
                JSONArray arrSubcategory = currentQuestions.optJSONArray("questions");
                for (int y = 0; y < arrSubcategory.length(); y++) {
                    JSONObject objectSubcategory = arrSubcategory.getJSONObject(y);
                    String text = objectSubcategory.optString("text");
                    String studentId = objectSubcategory.optString("studentId");
                    String votes=objectSubcategory.optString("votes");
                    /*JSONArray cycles through the array of voters, when a user votes
                    their ID is added to the array.When they downvote, it is removed
                     */
                    JSONArray voters= objectSubcategory.optJSONArray("voters");

                    QuestionData questionData = new QuestionData();
                    questionData.setMstudentId(studentId);
                    questionData.setMtext(text);
                    questionData.setVotes(votes);
                    questionData.setVoters(checkIfVoted(voters));
                    mQuestionDataArrayList.add(questionData);
                }
            }
        } catch (JSONException e) {
            e.printStackTrace();
        }
    }
    return mQuestionDataArrayList;
}
private static String checkIfVoted(JSONArray jsonArray ) {
    /*pass in a json Array, copy the array into ints, and if
      the students Id is contained in the array return the string true
     */
    int[] voteIds = new int[jsonArray.length()];
    for(int i=0;i<voteIds.length;i++){
        voteIds[i] = jsonArray.optInt(i);
    }
    for(int i=0;i<voteIds.length;i++){
        if(voteIds[i]== Integer.parseInt(Login.getUserId())){
            //TODO String was only used for Testing purposes, Convert to Boolean later
            return "true";
        }
    }
    return "false";
}

A:
you are currently only updating the textview which is why your recycleview changes state when scrolling.

Should change your voting class and pass the question Data rather textview
    public Voting(int adapterPosition,final RecyclerView.Adapter adapter, TextView questionId, TextView studentVoted) {

change to
    public Voting(int adapterPosition,final RecyclerView.Adapter adapter, QuestionData questionData, TextView studentVoted) {
   // make other changes for the data

and then in
public void realTimeUpVoting(QuestionData questionData){
data.votes++ //something like that. idont know your model
// now call back using interface the recyleview data changed method so it updates the count in recycleview automatically.

Edit
passing the question Data in click button
 class ViewDashboard extends RecyclerView.ViewHolder {
    public int position

 public void onBindViewHolder(ViewDashboard holder, int position) {
     holder.position = position
 }

 public void liked(LikeButton likeButton) {
     QuestionData questionHolder = data.get(position);


text:
Q: How can I use github api to decide the dependencies between two commit? I know that GitHub offer an api to compare two commit like https://developer.github.com/v3/repos/commits/#compare-two-commits. However, I wonder if I can use api on GitHub to decide the relationship between two commits. See the following commit graph:
A ---> B ---> C ---> D
└--->E---------------┘

From the above, commit A is the predecessor of commit B & commit E, while commit B is not predecessor of commit E.
Considering my situation, judge whether commit A is predecessor of commit B is enough. Thanks a lot!

A: One of my instructors suggests that, we can download the commit message to the sql database, then query the relationship. since github api message contains commit's previous_commit, we can use this to construct the relationship.

redpajama_set_name: RedPajamaStackExchange


text:
Q: Check if a radio button was previously checked or not I have a group of radio buttons and I want to add functionality that allows a user to deselect all radios by clicking on the radio that is currently selected.
E.g. by default the first radio is checked. The user then clicks on the second radio which then becomes select. The user now decides that actually no radio should be selected at all and clicks the second radio again to remove all selections.
The problem is that with a change or click event I'm not able to determine of a radio was checked before the user clicked it.
Is there a way to determine if a radio button was previously checked or not?

A: Easy - store the most recently clicked button in a Javascript variable

A: You can add an attribute to the radio button like
<input type="radio" data-checked="true">

and then all radio buttons with that attribute will be accesible via
$("input:radio[data-checked]")

you can add a listener that will add that attribute like so:
$(function(){
   $('input').change(function(){
      if($(this).attr('data-checked')){
          $(this).removeAttr('data-checked');
      } else {
          $(this).attr('data-checked', 'true');
      }
   })
})


text:
Q: $dQ=Tds$ and quasistatic process See Ján Lalinský's commment on Entropy $dQ=TdS$ and Work $dW = -pdV$ conditions?
My question are:

*

*Is there a way to prove that $dQ=Tds$ is a quasistatic process?

*What's the funcitonal description for quasistatic process?

A: Since it is necessary to first have a functional understanding of a quasi-static process I will attempt to answer question 2 first.
A quasi-static process is one that is carried out such that disequilibrium is minimized at each step in the process. Such a process is also a reversible process if it does not involve friction.  Such disequilibria typically involve pressure and temperature differentials.
For example, heat transfer requires a temperature difference between two things. A temperature difference is an example of disequilibrium and it is that disequilibrium which drives the heat transfer process. To reduce the disequilibrium you need to reduce the temperature difference. That of course slows down the rate of heat transfer. In order to eliminate the disequilibrium, the temperatures would have to be equal. But then you would not have heat transfer. This demonstrates that in real life all processes are necessarily irreversible. We can only approach reversible processes in the limit.
Now regarding question 1.
Let's first rearrange the equation
$$dS=\frac {dQ}{T}$$
This equation does not necessarily mean a quasi-static (reversible) process is involved unless it is accompanied by an explicit statement that $dQ$ is a reversible transfer of heat. That stipulation is explicit in the following commonly used definition of $dS$:
$$ds=\frac{dQ_{rev}}{T}$$
Where $dQ_{rev}$ means a process that involves a reversible (quasi-static) transfer of heat. Since entropy is a property of the system, the difference in entropy of the system between two equilibrium states does not depend on the process being quasi-static. However the total entropy change, system + surroundings, does depend on whether or not the process is quasi-static (reversible). The total will $=0$ if the process is quasi-static (reversible) and will be $>0$ if not quasi-static (irreversible).  So I think the relevant "proof" you would want to know is how this is true.
The following is not necessarily a "proof" but rather an example of why a process needs to be quasi-static (reversible) in order for the total entropy change (system + surroundings) to be, or approach, zero.
Consider a system H (a hot body) and its surroundings C (a cold body). Further consider both H and C to be thermal reservoirs, that is, they are so massive relative to the desired heat transfer, that heat transfer between them doesn't change their temperatures. The temperature of body H is $T_H$ and the temperature of body C is $T_C$. We bring the bodies together and desire to transfer heat $Q$ from H to C. Since the temperature of either does not change, the heat transfer occurs isothermally.  Let's look at the entropy changes:
For Body A (System):  $$\Delta S_A = -Q/T_H$$ (which is a drop in entropy)
For Body B (Surroundings):  $$\Delta S_C = +Q/T_C$$ (which is a rise in entropy)
The total entropy change $$\Delta S_A + \Delta S_C = -Q/T_H + Q/T_C$$
Then for any $$T_H > T_C$$
$$ Q/T_C - Q/T_H> 0$$
In order for the total entropy change to approach zero, the process must be carried out quasi-statically, meaning the temperature difference must approach zero.  This of course, results in the heat transfer rate approaching zero and the time it takes to transfer Q infinitely long. This is why in order to have quasi-static (reversible) processes those processes must be carried out very slowly
Hope this helps

A: I think, if the process is not quasi static, the properties will not be the same through out the system(i.e. the properties will change from point to point within the system).If we discuss about the pressure of the entire system or temperature of the entire system,entropy change of the system, etc.. means we are discussing about a quasi static process.This is why, quasi static processes are said to be made up of equilibrium states.These states can be plotted as points in a graph(PV or TS graphs).Since the terms T and dS in your equation are the properties of the entire system , you are describing a quasi static process.


text:
Q: Spring: not accept POST request under mvc:resources? how to fix that I am using spring framework in my project,
Here is part of my web.xml:
<servlet>
    <servlet-name>SpringMvcServlet</servlet-name>
    <servlet-class>org.springframework.web.servlet.DispatcherServlet</servlet-class>
    <init-param>
        <param-name>contextConfigLocation</param-name>
        <param-value>
            /WEB-INF/servlet-context.xml
        </param-value>
    </init-param>
    <load-on-startup>1</load-on-startup>
</servlet>

<servlet-mapping>
    <servlet-name>SpringMvcServlet</servlet-name>
    <url-pattern>/*</url-pattern>
</servlet-mapping>
<filter>
    <filter-name>httpMethodFilter</filter-name>
    <filter-class>org.springframework.web.filter.HiddenHttpMethodFilter</filter-class>
</filter>
<filter-mapping>
    <filter-name>httpMethodFilter</filter-name>
    <url-pattern>/*</url-pattern>
</filter-mapping>

<error-page>
    <error-code>404</error-code>
    <location>/system/404.html</location>
</error-page>
<error-page>
    <error-code>500</error-code>
    <location>/system/500.html</location>
</error-page>

And configure:
<mvc:resources mapping="/system/**" location="/WEB-INF/pages/system/" />

But I find so many error in my log, some request like this:

*

*POST /index.php

*POST /notexists.html

They were not exists in my server, so will call "/system/404.html", but the mvc:resources don't accept POST method, so it will return 500 Error.
How to fix that? or work around?
Thanks

A: First of all: I think you abuse the ResourceHttpRequestHandler when you try to use it for POST requests. -- And I am not sure that every thing works correct if you made this handler to handle POST requests.

<mvc:resources /> configure an instance of class org.springframework.web.servlet.resource.ResourceHttpRequestHandler. This has the super class WebContentGenerator and this super class has a property Set<String>   supportedMethods.
So all what you need to do is:
<property name="supportedMethods">
    <list>
       <value>GET</value>
       <value>HEAD</value>
       <value>POST</value>
    </list>
</property>

Unfortunately this requires that you configure the ResourceHttpRequestHandler by hand instead of using <mvc:resources />
<bean class="org.springframework.web.servlet.handler.SimpleUrlHandlerMapping">
     <property name="urlMap">
         <map>
              <entry key="/system/**" value="myResourceHandler" />
         </map>
     </property>
     <property name="order" value="100000" />
</bean>

<bean id="myResourceHandler" name="myResourceHandler"
      class="org.springframework.web.servlet.resource.ResourceHttpRequestHandler">
      <property name="locations" value="/WEB-INF/pages/system/" />
      <property name="supportedMethods">
         <list>
            <value>GET</value>
            <value>HEAD</value>
            <value>POST</value>
         </list>
     </property>
     <!-- cacheSeconds: maybe you should set it to zero because of the posts-->
</bean>

I have not proved this configuration, I have just written it down from what the ResourceBeanDefintionParser does.


text:
Q: M2E-Pro The product with the same Merchant SKU is being listed now. SKU must be unique for each Amazon item I'm retriving the above error , while listing products on M2E-Pro. The error seems to appear only on some products. But interesting that on Amazon I've no products at all. I deleted them all. So it's still saying that the SKU should be unique. All the products have unique SKU on Magento.
So what the error stands for. And how could I fix it ?

A: After many hours of work I just discovered the reason of the problem. Will pass you an email that I sent to the support of M2E-pro:
--- So, I think that today I should help You. I asked you for support 2 days ago about:
"The product with the same Merchant SKU is being listed now. SKU must be unique for each Amazon item".
Basically this error message may generate misunderstandings in certain circumstances. Assume the case that for some reasons the server fails to list the products (the script or the server will shutdown) or in my case an HTTP error 504 was generated by NGINX due to some internal TIMEOUT settings. The Lock_Item table of M2E-Pro will mantain forever my SKUS locked. This is the error. If this happens, the call to the function getQueueOfSkus() in code\community\Ess\M2ePro\Model\Connector\Amazon\Product\List\multiple.php file at line 641 returns the locked queue. So any attempt to relist, list or doing whatever with the same product skus will return the error above, which is basically not the exact description of what is going on. Only a cleanup of the Lock_item table could solve the problem.  Solution: Do some cleanings if possible in the cronjob, just to verify that all is ok. The company for which I'm working was stuck for 3 days because of this error.---


text:
Q: How should I treat gray-out area on pixcel device? I'm sorry that I have never see or used an actual device with android OS such as Google pixcel, but I found that gray-out area on top of screen like screen shot below.
*This is "Pixcel 4 API 30 mobile emulator" called from vsCode.

And I found this kind of dead area on Pixcel 5 emulator as well, but am not sure that this is somthing in common for all android OS.
Finally, I'd like to ask that if I should avoid something to display here or this is only emulator matters and do not have to care about this ?
In case that  I have to care this area with developing by flutter, should I intentionally separate code or design between these kind of device and the others, as I'm usually using Iphone emulator and actual machine but have never seen this area and beleive I need not to care this kind of area and adopting top-margin for this problem.
Thanks for your helpful comment.
Code Added:
class holder extends ConsumerWidget {
  @override
  Widget build(BuildContext context, WidgetRef ref) {
    ref.watch(_modalProvider );
    return Scaffold(
      body: Column(
        children: [
          Container(
            margin: const EdgeInsets.only(bottom: 10),
            // flex: 1,
            child: Container(
              margin: EdgeInsets.only(top: 40),//should I do this to avoid this area?
              width: double.infinity,
              height: 40,
              // color: Colors.grey,
              alignment: Alignment.topLeft,
              child: Image.asset('images/flutter.png'),
            ),
          ),
          Flexible(
            child: ListView(
            scrollDirection: Axis.vertical,
            shrinkWrap: true,
            children: [
              Folders(
                name: "list",
                subTitle: null,
              ),
            ],
          )
          ),
        ],
      ),
      floatingActionButtonLocation: FloatingActionButtonLocation.endTop,
      floatingActionButton: Container(
        width: 50.0,
        child: FloatingActionButton(
          backgroundColor: Colors.white,
          child: const Icon(
            Icons.search_sharp,
            color: MyStyle.mainColor,
            ),
          onPressed: () {
              ref.read(_modalProvider.notifier).update((state){
              showTopModalSheet<String?>(context, DumyModal());
            });

          },
        ),
      ),
    );
  }
}

A: That area will be also visible in real devices so you should take that area into consideration. But Scaffold widget will start the rendering from below that point so you don't have to think about it.
İf you want to change color of that area, you can
Container(
    decoration: BoxDecoration(color: Color.white),
    child: SafeArea(
           Scaffold:...
        )
)

It also effects IOS and Android devices differently, I believe that is why it is only visible in some devices


text:
Q: Override cart item price and image in WooCommerce I'm working on a plugin where I need to override the price and the image of the product when is added to the cart. So far I was able to change just the price.
Can someone please help me to implement something similar also for the images?
My_Plugin.php
global $woocommerce;

$custom_price = 200;
$product_id = 2569;
$variation_id = 2697;
$quantity = 1;

$cart_item_data = array('custom_price' => $custom_price, 'regular_price' => $regular_price);
$woocommerce->cart->add_to_cart( $product_id, $quantity, $variation_id, $variation, $cart_item_data );
$woocommerce->cart->calculate_totals();

functions.php
function woocommerce_custom_price_to_cart_item($cart_object)
{
    foreach ($cart_object->cart_contents as $key => $value) {
        if (isset($value["custom_price"])) {
            $value['data']->set_price($value["custom_price"]);
        }
    }
}

add_action( 'woocommerce_before_calculate_totals', 'woocommerce_custom_price_to_cart_item', 16 );

Is possible also to add some additional fields to the products when is added to the cart, like: url_file_uploaded, additional_description, etc
Many thanks!

A: Your code is a bit obsolete since WooCommerce 3 and there are some missing things. Try the following replacement to include also your custom image attachment ID as follows:
In Your file My_Plugin.php:
$custom_price   = 200;
// $regular_price  = 200; // Not needed and not defined (in your code)
$thumbnail_id   = 35; // <=== Here define the post type "attachment" post ID for your image (Image attachment ID)
$product_id     = 2569;
$variation_id   = 2697;
$variation      = array(); // ? | Not defined in your code
$quantity       = 1;
$cart_item_data = array(
    'custom_price'  => $custom_price,
    // 'regular_price' => $regular_price,
    'thumbnail_id' => $thumbnail_id, // Here we add the image attachment ID
);

WC()->cart->add_to_cart( $product_id, $quantity, $variation_id, $variation, $cart_item_data );
WC()->cart->calculate_totals();

In functions.php file of your child theme:
add_action( 'woocommerce_before_calculate_totals', 'custom_cart_item_data_replacement' );
function custom_cart_item_data_replacement( $cart ) {
    if ( is_admin() && ! defined( 'DOING_AJAX' ) )
       return;

    // Loop through cart items
    foreach ( $cart->cart_contents as $cart_item ) {
        // Custom price
        if( isset($cart_item["custom_price"]) ) {
            $cart_item['data']->set_price($cart_item["custom_price"]);
        }
        // Custom image attachment id
        if( isset($cart_item["thumbnail_id"]) ) {
            $cart_item['data']->set_image_id($cart_item["thumbnail_id"]);
        }
    }
}

It should works.
You can also alter all product properties via the WC_Product setter available methods.


text:
Q: Advise on this . My code has some blocker.i am getting the error 'object required' I am using the functions below.In the first one i have parsed the node of xml and its value using MSXML. similar func fr other xml.i want to use two nodevalues and highlight it.i tried something.but i am getting error in the line highlighted(**) as 'Object Required'.your quick reply will help me more.
Public Sub DisplayNode1(ByRef Nodes1 As MSXML2.IXMLDOMNodeList, _
   ByVal Indent1 As Integer)
some lines
  RichTextBox2.Text = Space$(Indent) & xNode1.ParentNode.nodeName & _
        ":" & xNode1.NodeValue

        difference

some lines
Public Sub difference()

Dim a As IXMLDOMText

Dim b As IXMLDOMText

a.NodeValue = xNode.innertext  'i get erroe in line

b.NodeValue = xNode1.innertext

If StrComp(a, b) > 0 Then

a = vbRed

b = vbRed

End If

please help me soon.

A: There is a lot that is potentially wrong with this.

*

*xnode isn't declared anywhere in your code sample

*Neither a, b, or xnode are explicitly set anywhere in your code sample

*Unless xnode is a form/module/global level variable then it will be out of scope in the Difference procedure

*It's not shown but I'm guessing that you don't have Option Explicit set in your code or by default

You'll need to address these points first before you can get anywhere with this code.


text:
Q: Xen DomU images running on Ubuntu 12.04 I have backed up the contents of /etc/xen/ and /var/lib/xen and have installed Ubuntu 12.04 hoping to migrate off of CentOS.
I am attempting to test some of these images and am receiving some odd errors. Firstly after I startup vm-0 from an old configuration I see this:
Name                                        ID   Mem VCPUs      State   Time(s)
Domain-0                                     0 68654    24     r-----     28.3
vm-0                                         1  4096     1     --p---      0.0

The command used to start the domain was xm create vm-0 which is what would have started the VM on CentOS. I also tried with the "xl" toolset but maybe that is something to migrate to after I get the older vm's working.
Bottom line, does it seem as though backing up the images from /var/lib/xen and /etc/xen for configurations on CentOS would work on Ubuntu or am I heading down a horrible path. My other option is to go back and reinstall CentOS and backup the images in another fashion.


text:
Q: How to request undeletion? One of my answers was deleted by a mod today. I have since then corrected my answer and I would like to have it undeleted. I'm not able to do that myself, and there appears to be no explicit method to request undeletion. I can flag my answer but I'm not confident that all flags get processed. Ideally, I would like to be able to notify the mod who deleted my answer directly.
So what are my options here? I have flagged and I'm waiting for a response...

A: Flagging your answer, explaining exactly what happened and why you think it should be undeleted is the right thing to do.
Any of the mods can understand your issue and deal with it, you don't have to contact the one that deleted your answer directly.
All the flags get processed eventually, just be patient.


text:
Q: Fade a Pseudo Element on scroll - JS or jQuery I have a pseudo element I'd like to fade to opacity:0 on scroll.  I can't seem to make head nor tale of how to do it.  I've set up a codepen here. http://codepen.io/emilychews/pen/JWyaKr
Normally I'd use Greensock, but I can't on this project. I also have to use a pseudo element, not an absolutely positioned div. The fade needs to happen after 10px scroll from the top and then come back when the user scrolls back to the top (its part of a nav element)
HTML

My Div

CSS
#mydiv {
    background: red;
    width: 10%;
}

#mydiv:after {
    content: '';
    position: absolute;
    height: 10%;
    width: 10%;
    top: 30px;
    background: black;
}

Any ideas would be awesome.  I feel as though I'm either about to cry or eat a bucket of fried chicken in frustration.
Emily

A: Set a transition for opacity on the pseudo element, and add a class to the main element on scroll that you use in the selector to change opacity on your pseudo element.

var $mydiv = $('#mydiv');
$(window).scroll(function() {
  if ($(this).scrollTop() > 10) {
    $mydiv.addClass('fade');
  } else {
    $mydiv.removeClass('fade');
  }
})
body {
  height: 200vh;
}

#mydiv {
  background: red;
  width: 10%;
}

#mydiv:after {
  content: '';
  position: absolute;
  height: 10%;
  width: 10%;
  top: 30px;
  background: black;
  transition: opacity .25s;
}

#mydiv.fade:after {
  opacity: 0;
}

My Div


text:
Q: CAS 4, does not work properly with cas client core 3.1.12 Edited QUESTION
As title shown, currently i am using CAS 3.5.2, therefore i upgrade to CAS 4.i just change the user name casuser and mellon to admin admin. its a very minimal changes.
therefore when i try to login, for example:
1 login, abcd/login
2 redirect to cas/login
3 after success logon, its redirect to abcd/login?st=xxxxxx with blank page.
do i miss somethings? or i need to change pom.xml?
below is part of my pom.xml
<dependency>
            <groupId>org.springframework.security</groupId>
            <artifactId>spring-security-cas</artifactId>
            <version>3.1.0.RELEASE</version>
            <scope>compile</scope>
        </dependency>
        <dependency>
            <groupId>org.opensaml</groupId>
            <artifactId>opensaml</artifactId>
            <version>1.1</version>
            <scope>runtime</scope>
        </dependency>
        <dependency>
            <groupId>xml-security</groupId>
            <artifactId>xmlsec</artifactId>
            <version>1.3.0</version>
            <scope>runtime</scope>
        </dependency>
        <dependency>
            <groupId>net.sf.ehcache</groupId>
            <artifactId>ehcache</artifactId>
            <version>1.6.2</version>
            <scope>runtime</scope>
        </dependency>

my error log
java.lang.StringIndexOutOfBoundsException: String index out of range: -1
    at java.lang.String.substring(String.java:1911)
    at org.jasig.cas.client.validation.Saml11TicketValidator.parseResponseFromServer(Saml11TicketValidator.java:50)
    at org.jasig.cas.client.validation.AbstractUrlBasedTicketValidator.validate(AbstractUrlBasedTicketValidator.java:197)
    at org.springframework.security.cas.authentication.CasAuthenticationProvider.authenticateNow(CasAuthenticationProvider.java:140)
    at org.springframework.security.cas.authentication.CasAuthenticationProvider.authenticate(CasAuthenticationProvider.java:126)
    at org.springframework.security.authentication.ProviderManager.authenticate(ProviderManager.java:156)
    at org.springframework.security.cas.web.CasAuthenticationFilter.attemptAuthentication(CasAuthenticationFilter.java:242)
    at org.springframework.security.web.authentication.AbstractAuthenticationProcessingFilter.doFilter(AbstractAuthenticationProcessingFilter.java:194)
    at org.springframework.security.web.FilterChainProxy$VirtualFilterChain.doFilter(FilterChainProxy.java:323)
    at org.springframework.security.web.authentication.logout.LogoutFilter.doFilter(LogoutFilter.java:105)
    at org.springframework.security.web.FilterChainProxy$VirtualFilterChain.doFilter(FilterChainProxy.java:323)
    at org.jasig.cas.client.session.SingleSignOutFilter.doFilter(SingleSignOutFilter.java:65)
    at org.springframework.security.web.FilterChainProxy$VirtualFilterChain.doFilter(FilterChainProxy.java:323)
    at org.springframework.security.web.context.SecurityContextPersistenceFilter.doFilter(SecurityContextPersistenceFilter.java:87)
    at org.springframework.security.web.FilterChainProxy$VirtualFilterChain.doFilter(FilterChainProxy.java:323)
    at org.springframework.security.web.FilterChainProxy.doFilter(FilterChainProxy.java:173)
    at org.springframework.web.filter.DelegatingFilterProxy.invokeDelegate(DelegatingFilterProxy.java:346)
    at org.springframework.web.filter.DelegatingFilterProxy.doFilter(DelegatingFilterProxy.java:259)
    at org.apache.catalina.core.ApplicationFilterChain.internalDoFilter(ApplicationFilterChain.java:243)
    at org.apache.catalina.core.ApplicationFilterChain.doFilter(ApplicationFilterChain.java:210)
    at sg.com.innovax.opscentralv5.objects.setEncoding.doFilter(setEncoding.java:100)
    at org.apache.catalina.core.ApplicationFilterChain.internalDoFilter(ApplicationFilterChain.java:243)
    at org.apache.catalina.core.ApplicationFilterChain.doFilter(ApplicationFilterChain.java:210)
    at org.apache.catalina.core.StandardWrapperValve.invoke(StandardWrapperValve.java:222)
    at org.apache.catalina.core.StandardContextValve.invoke(StandardContextValve.java:123)
    at org.apache.catalina.authenticator.AuthenticatorBase.invoke(AuthenticatorBase.java:472)
    at org.apache.catalina.core.StandardHostValve.invoke(StandardHostValve.java:171)
    at org.apache.catalina.valves.ErrorReportValve.invoke(ErrorReportValve.java:99)
    at org.apache.catalina.valves.AccessLogValve.invoke(AccessLogValve.java:947)
    at org.apache.catalina.core.StandardEngineValve.invoke(StandardEngineValve.java:118)
    at org.apache.catalina.connector.CoyoteAdapter.service(CoyoteAdapter.java:408)
    at org.apache.coyote.http11.AbstractHttp11Processor.process(AbstractHttp11Processor.java:1009)
    at org.apache.coyote.AbstractProtocol$AbstractConnectionHandler.process(AbstractProtocol.java:589)
    at org.apache.tomcat.util.net.JIoEndpoint$SocketProcessor.run(JIoEndpoint.java:312)
    at java.util.concurrent.ThreadPoolExecutor.runWorker(ThreadPoolExecutor.java:1145)
    at java.util.concurrent.ThreadPoolExecutor$Worker.run(ThreadPoolExecutor.java:615)
    at java.lang.Thread.run(Thread.java:722)

Therefore i checked the error code,view and breakpoint the source code(package org.jasig.cas.client.validation;). in Saml11TicketValidator.parseResponseFromServer, its because the response result wasnt in expected therefore substring got problems. this 1 just exception handling, is not a root cause.The root cause is in Saml11TicketValidator retrieveResponseFromServer, why CAS4 Return login page(in my CAS4, is already login)??? is it a bug?
note: my maven dependency is using cas-client-core-3.1.12.jar

A: if your cas4 return login page in Saml11TicketValidator , that means most probably u need to setup saml 1st.


text:
Q: how to make this code work for multiple textboxes foreach (TextBox c in this.Controls)
{
    foreach (Label lb in this.Controls)
    {
        if (c.Text == string.Empty)
            c.Visible = false;
        else
        {
            c.Visible = true;
            if (c.Visible == lb.Visible)
                lb.Visible = true;
            else
                lb.Visible = false;
        }
    }
}


text:
Q: size_t Loss of sign (return) (int to unsigned int)) This program counts the length of a string by subtraca warning message
-\
My stringLength function returns a size_t that is
Is my mistake in the format specifier or how I return my value?
#include <stdio.h>
#include <stdlib.h>

size_t stringLength(const char *str);

int main(void)
{

    return 0;
}

size_t stringLength(const char *str)
{
    const char *strCopy = str;

    while (*str)
    {
        str++;
    }

}

A: The issue you're having is that operator-() returns a signed value, rather than unsigned. Because in your routine you know that the value will always be positive, you can add a cast to  size_t and not worry about the sign being wrong.
return static_cast<size_t>(str - strCopy); //C++

or
return (size_t)(str - strCopy); //C


text:
Q: Thought Experiments on black holes, (im)possible perpetual motion and minimum mass for photographic plates Consider a black hole in vacuum at Temperature T. The setup that I am interested is a one that collects thermal photons from a black hole by enclosing in a spherical photographic plate and then lowering it back into the black hole.
If one assumes that photographic plates are massless.(which they are not). Then the very fact that I can lower the photographic plates(after the photons are collected) back into the black hole allows for a possibility of for the creation of a perpetual motion machine, from the potential energy generated by lowering the collected photons back into the black hole.
The mass of the photons emitted is equal to the mass of the black hole that has evaporated away. When I drop the photons back in the black hole, The mass of the black hole is equal to the original mass that we started off with. Which is why i thought it could be perpetual. This can continue for ever.
Of course I know something is wrong with such a setup. I think It can be traced to my assumption about photographic being massless.
My understanding of black hole thermodynamics is pretty elementary. Perhaps some one could comment on what is going on?

A: The Hawking radiation emitted from the Black Hole lowers its mass and reduces the energy in it's gravitational field. If you now drop the photographic plate back into the Black Hole you will get energy back. However if you take that energy away, by using it to generate electricity or whatever, you leave the Black Hole with a lower mass. That's where the energy has come from.
Suppose you take a small enough Black Hole that it radiates a lot of energy and put it in the boiler of a steam engine. You can now use the heat to generate electricity, but of course the Black Hole eventually evaporates away to nothing. Take the same Black Hole and put it inside a perfect mirror, that reflects back all the emitted radiation, and the Black Hole remains unchanged but of course now you can't generate any electricity from it.


text:
Q: In iOS 15.2 UITableView cell height bug when add embedded view in swift I have a project that works fine in xcode 12.5.1 and ios prior to 15.2 - it has UITableView with cells that contains embedded view. I set height of cells "not expanded" by default when loads UITableViewController and then expand them by tap on rows.
When I migrate to Xcode 13.2.1 and app works on ios 15.2 device it has a bug with cell height -
when UITableViewController loads and loads cells that contains embedded views then its height always set as a height of embedded view.
Maybe someone faced with this bug and have any solutions?
Code:
This is how I add cells -
func tableView(_ tableView: UITableView, cellForRowAt indexPath: IndexPath) -> UITableViewCell {
        let cell = cells[indexPath.section]![indexPath.row]
        cell.layer.zPosition = CGFloat(indexPath.row)
        cell.configure(with: models[indexPath.section]![indexPath.row])

        if indexPath.section == 0

        {
        switch indexPath.row {
        case 0:
            cell.addEmbeddedView(Section.init())
        default:
            break
        }
}

and this is how I "fix" size of cell to not expand before I tap on cell:
extension UITableView {
    func fixCellBounds() {
        DispatchQueue.main.async { [weak self] in
            for cell in self?.visibleCells ?? [] {
                cell.layer.masksToBounds = false
                cell.contentView.layer.masksToBounds = false
            }
        }
    }

and how I expand cell when tap on it:
func tableView(_ tableView: UITableView, didSelectRowAt indexPath: IndexPath) {
        guard let cell = tableView.cellForRow(at: indexPath) as? MyTableViewCell else { return }
        tableView.beginUpdates()
        cell.expanded.toggle()
        tableView.fixCellBounds()
        tableView.endUpdates()
    }

var expanded: Bool = false {
        didSet {
            let duration = CATransaction.animationDuration()
            UIView.animate(withDuration: duration) {
                self.arrow.transform = self.expanded ? CGAffineTransform(rotationAngle: .pi / 2) :  .identity

                self.height.isActive = !self.expanded
                self.foldView.alpha = self.expanded ? 1 : 0
                self.container.layoutIfNeeded()
            }

        }
    }


text:
Q: what does Zookeeper fault tolerant exactly mean ? simultaneously Or accumulatively? As mentioned in the ZooKeeper Getting Started Guide , a minimum of three servers are required for a fault tolerant clustered setup, and it is strongly recommended that you have an odd number of servers.
So If I got 5 servers, and as mentioned above I can still survive when 2 of them failed.But It means simultaneously Or accumulatively ??
So how about this :
5 servers -> fail one -> 4 servers -> fail one -> 3 servers -> fail one -> 2 servers -> fail one -> die
And what's the difference between 3 servers(initialization) and 3 servers (degeneration from 5 servers) ??

A: For Zookeeper cluster to work, it needs quorum. And quorum is the majority of servers from the cluster.

*

*With a 3 node cluster, the majority is 2 nodes. So you can tolerate only 1 node not being in sync at the same time.

*With a 5 node cluster, the majority is 3 nodes. So you can tolerate only 2 nodes not being in sync at the same time.

*With a 7 node cluster, the majority is 4 nodes. So you can tolerate only 3 nodes not being in sync at the same time.

What does being in sync mean? The node is not part of the quorum not only when it is not running. But also when it is still rejoining the cluster after a failure.
The nodes are hardcoded in Zookeeper configuration. So each node in the cluster know that it should be part of a cluster with N nodes. Therefore it doesn't work in the way that a 7 node cluster where two nodes are down is suddenly a 5 node cluster and another 2 nodes can go down. It will always behave as a 7 node cluster and only 3 nodes can go down unless you change the configuration files.
The whole thing about even and odd number of nodes is basically about the number of nodes which could be down while maintaining the quorum. And with 4 node cluster, the majority will be 3. So 4 node cluster can still tolerate only 1 node being down. Hence it doesn't make much sense to use 4 node cluster which has the same fault tolerance as the 3 node cluster.


text:
Q: C# / Access Getting Primary Keys from Access 2003 I'm using OleDb to interact with an Access database, and I'm trying to find out how to get the primary keys of each table, but in such a way that they are associated with the tables. In other words, I don't just want a flat list of the primary key column names--I want to be able to determine which table they belong to.
Any idea how to do this? I've used the GetSchema() method to get a table of tables, but that table's information does not appear to include primary keys (or any other indexes, for that matter).

A: Ok--did a little outputting of column names and got a better understanding of how the schema tables are related.
To do this, pass the string "Indexes" to the GetSchema() method. Each record in the index table contains both the table name and whether or not the index is the primary key.

A: I think what you mean is that for each FOREIGN KEY in the schema you want to discover the name of the referenced table. From a quick google it seems this may not be possible:
Microsoft Connect: DbConnection.GetSchema: no ways to get foreign keys' columns
...which is strange because with ADO classic's (COM, not .NET) OpenSchema method you can.


text:
Q: Filtro em mais de uma coluna Boa tarde pessoal, fiz uma tabela que tem seus dados iterados através do v-for, ocorre que eu preciso filtrar essa tabela por coluna eu encontrei a função  filter porém só consigo filtrar uma  quero poder filtrar o resultado desse filter usando os critérios das outras colunas.
pensei em por && no filtro da primeira table mas ele só mostra resultado se preencher todos os campos ou || mas ele vai me mostrando qq coisa que eu digitar no input
Segue o código que estou usando para filtrar
tenho essa table aqui :
segue código :

<script>

export default {
  data() {
    return {
      CodigoPapel: "",
      CodigoTipoNegociacao: "",
      listas: [
        {
          CodigoPapel: 90,
          NomeEmpresa: "IRBR1",
          CodigoTipoNegociacao: 77,
        },
        {
          CodigoPapel: 90,
          NomeEmpresa: "ARGX4",
          CodigoTipoNegociacao: 3,
        },
        {
          CodigoPapel: 12,
          NomeEmpresa: "Petrobras",
          CodigoTipoNegociacao: 3,
        },
      ],
    };
  },
  computed: {

    listaFiltrada: function () {

     return this.listas.filter((item)=> {
       return item.CodigoPapel == this.CodigoPapel
     })
    },
  },

};
</script>
<script src="https://cdnjs.cloudflare.com/ajax/libs/vue/2.5.17/vue.js"></script>

A: Você só precisa incluir as condições dentro da função da filter, retornando true para caso o elemento deve aparecer, ou false para caso ele deva ser filtrado:

const lista = [{"CodigoPapel":90,"NomeEmpresa":"IRBR1","CodigoTipoNegociacao":77},{"CodigoPapel":90,"NomeEmpresa":"ARGX4","CodigoTipoNegociacao":3},{"CodigoPapel":12,"NomeEmpresa":"Petrobras","CodigoTipoNegociacao":3}]

this.CodigoTipoNegociacao = '3'
this.CodigoPapel = ''

const resultado = lista.filter(item => {
    let aparece = true
    if (this.CodigoPapel) aparece &= this.CodigoPapel == item.CodigoPapel
    if (this.CodigoTipoNegociacao) aparece &= this.CodigoTipoNegociacao == item.CodigoTipoNegociacao

    return aparece
})

console.log(resultado)

No exemplo eu inicio a condição para aparecer na lista como true. Caso CodigoPapel ou CodigoTipoNegociacao não seja um valor falsy (como uma string vazia), a comparação será feita, e o resultado é atribuído à aparece.
Utilizando o operador &= você pode realizar a comparação lógica and durante a atribuição, dessa forma, mesmo que o resultado da comparação seja true, se aparece for false, ele continuará como false, pois false && true é false.
O mesmo também poderia ser obtido utilizando o operador ternário de forma mais direta:

const lista = [{"CodigoPapel":90,"NomeEmpresa":"IRBR1","CodigoTipoNegociacao":77},{"CodigoPapel":90,"NomeEmpresa":"ARGX4","CodigoTipoNegociacao":3},{"CodigoPapel":12,"NomeEmpresa":"Petrobras","CodigoTipoNegociacao":3}]

this.CodigoTipoNegociacao = '3'
this.CodigoPapel = ''

const resultado = lista.filter(item =>
    (this.CodigoPapel ? this.CodigoPapel == item.CodigoPapel : true) &&
    (this.CodigoTipoNegociacao ? this.CodigoTipoNegociacao == item.CodigoTipoNegociacao: true)
)

console.log(resultado)

Nessa comparação, se CodigoTipoNegociacao ou CodigoTipoNegociacao estiverem vazias, você simplesmente resulta a comparação em true, pois uma string vazia significa que o item deve aparecer.


text:
Q: Delete row from JTable with custom table model I've a subclass of JTable that uses a custom table model (an implementation of AbstractTableModel) to manage data.
The problem occurs when I try to delete a row with the method deleteRow. The row in my table is replaced by a blank string but the row is not deleted.
Here is the code:
public class LiveSearchTableModel extends AbstractTableModel
{

  private List<String> columnNames = new ArrayList<String>();
  private Map<Point, Object> displayData = new HashMap<Point, Object>();
  private Map<Point, Object> originalData = new HashMap<Point, Object>();

  public LiveSearchTableModel(List<String> columnNames,
      Map<Point, Object> tableData)
  {
    this.columnNames = columnNames;
    this.displayData = tableData;
    this.originalData.putAll(tableData);
  }

  @Override
  public int getColumnCount() {
    return columnNames.size();
  }

  @Override
  public int getRowCount() {
    return displayData.size() / columnNames.size();
  }

  @Override
  public Object getValueAt(int rowIndex, int columnIndex) {
    return displayData.get(new Point(rowIndex, columnIndex));
  }

  public void deleteRow (int row)
  {
    for (int cont = 0; cont < columnNames.size();cont++)
    {
      displayData.remove(new Point (row,cont));
    }

    this.fireTableRowsDeleted(row, row);
  }

  @Override
  public void setValueAt(Object value, int rowIndex, int columnIndex)
  {
    this.displayData.put(new Point(rowIndex, columnIndex), value);
    this.fireTableDataChanged();
  }
}

A: The sscce below illustrates one potential problem: The keys of a Map are not ordered, while the rows of a table are. In the approach shown, an array of keys must by updated with each change to the data. See also this related example. If required, you could extend Point to implement Comparable, as shown here for Value.
import java.awt.BorderLayout;
import java.awt.EventQueue;
import java.awt.Point;
import java.awt.event.ActionEvent;
import java.util.ArrayList;
import java.util.Arrays;
import java.util.HashMap;
import java.util.List;
import java.util.Map;
import javax.swing.AbstractAction;
import javax.swing.JButton;
import javax.swing.JFrame;
import javax.swing.JPanel;
import javax.swing.JScrollPane;
import javax.swing.JTable;
import javax.swing.table.AbstractTableModel;

/**
* @see https://stackoverflow.com/q/12330167/230513
*/
public class TableModelTest extends JPanel {

    public TableModelTest() {
        super(new BorderLayout());
        final MyModel model = new MyModel();
        JTable table = new JTable(model);
        this.add(new JScrollPane(table));
        this.add(new JButton(new AbstractAction("Delete") {

            @Override
            public void actionPerformed(ActionEvent e) {
                model.remove(0);
            }
        }), BorderLayout.SOUTH);
    }

    public class MyModel extends AbstractTableModel {

        private List<String> names = new ArrayList<String>();
        private Map<Point, Object> data = new HashMap<Point, Object>();
        private Point[] keys;

        public MyModel() {
            this.names = Arrays.asList("Point", "Name");
            data.put(new Point(1, 1), "One");
            data.put(new Point(2, 2), "Two");
            data.put(new Point(3, 3), "Three");
            this.keys = data.keySet().toArray(new Point[data.size()]);
        }

        public void remove(int row) {
            data.remove(keys[row]);
            keys = data.keySet().toArray(new Point[data.size()]);
            this.fireTableRowsDeleted(row, row);
        }

        @Override
        public int getColumnCount() {
            return names.size();
        }

        @Override
        public String getColumnName(int col) {
            return names.get(col);
        }

        @Override
        public int getRowCount() {
            return data.size();
        }

        @Override
        public Object getValueAt(int row, int col) {
            if (col == 0) {
                return keys[row];
            } else {
                return data.get(keys[row]);
            }
        }
    }

    private void display() {
        JFrame f = new JFrame("TableModelTest");
        f.setDefaultCloseOperation(JFrame.EXIT_ON_CLOSE);
        f.add(this);
        f.pack();
        f.setLocationRelativeTo(null);
        f.setVisible(true);
    }

    public static void main(String[] args) {
        EventQueue.invokeLater(new Runnable() {

            @Override
            public void run() {
                new TableModelTest().display();
            }
        });
    }
}


text:
Q: When was the last data dump uploaded to archive.org? The publishing date on archive.org/details/stackexchange is 16th March 2015

Stack Exchange Data Dump by Stack Exchange, Inc.
Published March 16, 2015
Usage Attribution-Share Alike 3.0

However, the files appear to be newer than that, the time stamps from archive.org/download/stackexchange/ indicate August, except the Comments and Badges files which are April.
stackoverflow.com-Badges.7z                      09-Apr-2015 19:28     90.9M
stackoverflow.com-Comments.7z                    09-Apr-2015 19:42     2.0G
stackoverflow.com-PostHistory.7z                 18-Aug-2015 15:49     12.0G
stackoverflow.com-PostLinks.7z                   18-Aug-2015 15:50     35.6M
stackoverflow.com-Posts.7z                       18-Aug-2015 16:52     7.3G
stackoverflow.com-Tags.7z                        18-Aug-2015 16:52     573.1K
stackoverflow.com-Users.7z                       18-Aug-2015 16:54     153.0M
stackoverflow.com-Votes.7z                       18-Aug-2015 16:58     500.1M

I've imported all the data with the stack dump offline browser, which reported a large number of inconsistently errors, I'm guessing from the mixing an old comment file with newer post file.
Is this a mistake? Where can I find a consistent set of files? Unfortunately I cannot access bit-torrent from where I work.

A: A good way to estimate the age of the data (true, not the same as upload date, maybe some format changed, but likely what most people want), is to download Votes.xml ("only" 400M compressed) and:
tail Votes.xml

This shows to me that the latest dump that I've just downloaded was from 2014-09.
Then I've done:
grep 2014-10 Votes.xml

to confirm, and got no results as expected.
So this seems to be the one from this announcement: Stack Exchange September 2014 Data Dump is available
I've found a few questions mentioning that the data is outdated or that the date is not clearly documented:

*

*Add date to data dump download

*Update frequency of SE Data Dump on Web Archive

*Latest stack Exchange data dump on internet archive not latest

A: In the data obtain via bittorrent from https://archive.org/download/stackexchange/stackexchange_archive.torrent
the latest post from stackoverflow that I saw was from 2014-09-14 03:07:29 UTC.
However, the zip archive https://archive.org/compress/stackexchange/formats=7Z&file=/stackexchange.zip had posts from 2015/08.


text:
Q: voila iypwidgets 'nice' loader When a notebook is rendered with voila a VERY NICE loader appear when the website is being rendered by voila, which might take several seconds if the dashboard is large.
Once in the dashboard is created and launched the User might run operations that can take several seconds to compute.
I would like to run a loader on top of the dashboard indicating the user that the computer is calculating. (Floating spinning icon or whatever)
Is it possible?
If it is not possible with the floating option is 5here any ipywidget as computing indicator (loading bar or similar)
Thx

A: I would tend to have an output widget somewhere in at the top of the dashboard like:
out_loader = widgets.Output()

Everytime a heavy function starts to run the loader is show.
with out_loader:
    display(loading_bar)

And at the end of the function
out_loader.clear_output()

I dont know if those can be written in only one line. Would be better.

A: I did something similar, but couldn't find a way to overlay an image over the controls (locking out any further interaction etc). The easiest way I found was to have an Output widget dedicated to a progress bar, and display the progress bar when a long running calculation was happening.
This works best with a 'repeating' loading bar, such as https://i.imgur.com/CS6l6tB.gif rather than one that actually displays true progress.
import ipywidgets as widgets
import time

gif_address = 'PATH_TO_YOUR_LOADING_BAR'

with open(gif_address, 'rb') as f:
    img = f.read()

#   create loading bar widget, ready to display when running long function
loading_bar = widgets.Image(value=img)

def long_running_function():
    time.sleep(2)

out = widgets.Output()
display(out)

# make sure your widgets are observing a function which includes these lines:
with out:
    display(loading_bar)
    long_running_function()
    out.clear_output()


text:
Q: Reading continuously incoming data (usb4java) I have spent a considerable amount of time trying to figure out the best way of reading continuously a large amount of data using the Low-level functions of usb4java (Libusb).
The amount of data I need to read is 640kbyte/s in a Full Speed device, theoretically is possible, and I should be using less than half of the bandwidth available. The problem I am having is that the data I am reading has glitches that could be coming from either missing or corrupt data.
I have tried both Sync and Async with similar results. Here I post the code I am using to do this in Async mode, any help is appreciated.
public Void doInBackground() {

    loop = true;
    handle = comm_device_async.gethandle();

    buffer = BufferUtils.allocateByteBuffer(PacketSize).order(ByteOrder.LITTLE_ENDIAN);
    Transfer transfer = LibUsb.allocTransfer();

    LibUsb.fillBulkTransfer(transfer, handle, IN_ENDPOINT, buffer, read_callback, null, TIMEOUT);
    int result = LibUsb.submitTransfer(transfer);
    if (result != LibUsb.SUCCESS) {
        throw new LibUsbException("Unable to submit transfer", result);
    }

    while (loop) {
        synchronized (synchObj) {
            while (!transfercompleted) {
                try {
                    synchObj.wait();
                } catch (InterruptedException ex) {
                    Logger.getLogger(GraphPanel_JChart2D.class.getName()).log(Level.SEVERE, null, ex);
                }
            }
        }
        transfercompleted = false;

        multipledatashort[readcyclecount] = read_callback_data;
        readcyclecount++;
        if (readcyclecount == readcycles) {
            synchronized (dataListShort) {
                dataListShort.add(multipledatashort);
                dataListShort.notify();
            }
            readcyclecount = 0;
        }

    }
    return null;
}

TransferCallback read_callback = new TransferCallback() {

    ByteBuffer buffer;
    long startTime = 0;

    @Override
    public void processTransfer(Transfer transfer) {
        System.out.println("ReadCallback loop time " + (System.nanoTime() / 1000 - startTime));
        startTime = System.nanoTime() / 1000;
        read_callback_data = new short[transfer.buffer().capacity() / 2];
        for (int i = 0; i < read_callback_data.length; i++)
            read_callback_data[i] = transfer.buffer().getShort();

        synchronized (synchObj) {
            transfercompleted = true;
            synchObj.notify();
        }

        buffer = BufferUtils.allocateByteBuffer(PacketSize).order(
                ByteOrder.LITTLE_ENDIAN);
        LibUsb.fillBulkTransfer(transfer, collectWorker_usb4java_async_fast.handle, IN_ENDPOINT, buffer,
                read_callback, null, TIMEOUT);
        int result = LibUsb.submitTransfer(transfer);
        if (result != LibUsb.SUCCESS) {
            throw new LibUsbException("Unable to submit transfer", result);
        }

    }
};

A: I found a thread that describes pretty a similar issue
http://libusb.6.n5.nabble.com/Fwd-FT2232H-asynchronous-maximum-data-rates-td4519549.html
There are two main points

*

*
He is saying submitting a single request asynchronously (and
  resubmitting it) turns out to work worse than submitting synchronous
  requests. This is expected, doing more busywork takes more time.

*
the goal is to keep the list of URB's at the kernel constantly filled.
  Anytime that list empties, there's a chance it won't be refilled in
  time to request data and the FT2232H buffer will fill up. So the
  right way to do the asynchronous mode is to make a list of transfers. Each time one of them returns, another is requested.
  There's overhead involved in converting this request into the
  corresponding list of URBs, but as long as the list starts out big
  enough, we can amortize this overhead over the time the other
  transfers take to complete

So basically for large amount of data we need to have a buffer of transactions to be submitted, so there is always one pending when the last one ends.
I am going to be working on that, but I haven't found any good examples of how this should be done using usb4java. Again, any help is appreciated


text:
Q: Socket bind() working with unavailable address When I am trying to bind an unavailable address to an icmp socket like something which is not assigned to any interface, it binds to it without throwing any error. Am I doing something wrong?
if (c->pc_saddr.ps_len == sizeof(saddr.sin_addr.s_addr)) {

    bzero(&saddr, sizeof(saddr));
    saddr.sin_len = sizeof(saddr);
    saddr.sin_family = AF_INET;
    bcopy(c->pc_saddr.ps_data, &saddr.sin_addr.s_addr,
          c->pc_saddr.ps_len);

    /*
     * note: if bind fails, just log it & let the kernel decide on the
     * source address to use.
     */
    if (bind(icmp_socket.ps_socket_fd, (struct sockaddr*)&saddr, sizeof(saddr)) != 0) {

        trace(TRACEFLAG_GENERAL, "%s: bind failed icmp: %s",
                   __FUNCTION__, strerror(errno));
    }
}


text:
Q: Difference in execution plan between Xpath and cts:search in Marklogic Running xdmp:plan() on an Xpath, in the execution plan I found  the following:
<qry:info-trace>Selected n fragments</qry:info-trace>
But running xdmp:plan() on cts:search(/Xpath,cts:and-query(())) , I got
  <qry:info-trace>Selected n fragments to filter</qry:info-trace>
Why is "to filter" missing in the second case?

A: With 7.0-3 and cts:search:
xdmp:plan(cts:search(/a/b/c, cts:and-query(())))
=>
...
<qry:info-trace>Selected N fragments to filter</qry:info-trace>
...

Whereas with XPath:
xdmp:plan(/a/b/c)
=>
...
<qry:info-trace>Selected N fragments</qry:info-trace>
....

The difference is mostly aesthetic. The cts:search function accepts an unfiltered option, while XPath has no such option: XPath results are always filtered. The plan only mentions filtering when unfiltered search is possible, and filtering is enabled.
xdmp:plan(cts:search(/a/b/c, cts:and-query(()), 'unfiltered'))
=>
...
<qry:info-trace>Selected N fragments</qry:info-trace>
....

See https://docs.marklogic.com/guide/performance/unfiltered for background on why filtering is enabled by default, and why you might want to disable it in certain circumstances.


text:
Q: Install Ubuntu - "Device for bootloader installation" From my understanding, the Grub2 bootloader can be installed on any EFI System Partition (ESP), specifically under \EFI\ubuntu.
I have 2 SSDs - with 3 ESP on each of them (for testing purpose):

*

*/dev/sda has sda1, sda3, sda5 as ESP

*/dev/sdb has sdb1, sdb3, sdb5 as ESP

I wasted my time last night only to test the following scenarios for this bootloader installation option:

*

*Mount /dev/sda2 as root / and select the same device, eg: /dev/sda for bootloader installation

*Mount /dev/sda2 as root / and select the ESP on the same device, eg: /dev/sda1, /dev/sda3, /dev/sda5 for bootloader installation

*Mount /dev/sda2 as root / and select a different device, eg: /dev/sdb for bootloader installation

*Mount /dev/sda2 as root / and select the ESP on a different device, eg: /dev/sdb1, /dev/sdb3, /dev/sdb5 for bootloader installation

(image for illustration purpose, not my real test case)
No matter what I select, the bootloader (\EFI\ubuntu) is always installed on the first ESP of /dev/sda drive - the sda1. Edit: even when I mount sdb2 as root / and choose sdb for bootloader installation, the bootloader is still installed on /dev/sda1, meaning if I remove the 1st SSD, the system won't be able to boot!
What is the point of this option if it always choose the first ESP partition found on the system anyway?


text:
Q: Writing a Jest test for an async function throwing an error fails I am trying to test a function that throws an error asyncronously, but jest is not catching it
    async function fn() {
      await new Promise(async (res, rej) => {
        await new Promise(res => setTimeout(res, 1000))
        throw new Error('some error')
      })
    };

    await expect(fn()).rejects.toThrowError('some error');

jest errors out
 ● execSeries › throws error and terminates early if a command errors

    some error

      68 |       await new Promise(async (res, rej) => {
      69 |         await new Promise(res => setTimeout(res, 1000))
    > 70 |         throw new Error('some error')
         |               ^
      71 |       })
      72 |     };

A: I can't figure out how to get it to work with throw syntax but if I change it to reject the promise it works...
    async function fn() {
      await new Promise(async (res, rej) => {
        await new Promise(res => setTimeout(res, 1000))
        rej('some error')
      })
    };

    await expect(fn()).rejects.toThrowError('some error');

Downside is that if there is a throw inside sub functions this won't work unless I catch it on top and rethrow it
    async function fn() {
      await new Promise(async (res, rej) => {
        try {
           await somethingThatThrowsError;
        } catch (e) {
           rej(e)
        }
      })
    };

    await expect(fn()).rejects.toThrowError('some error');


text:
Q: Browser does not have rewritten URL with query string When I rewrite the URL by adding a query string, the URL in the browser does not have the query string.  Here's what I have:
location / {
    rewrite ^/$ /?page=test break;
}

Instead, I see the original URL in the browser when I visit the root directory.  I am able to rewrite to another path.

A: As written, this is only a rewrite, which is (and should be) handled internally by the web server without the user being aware of it.
You can make this user-visible either temporarily or permanently by adding the redirect or permanent statements to your rewrite line (nginx doc for rewrite).
Be careful with the permanent variant (HTTP Code 301), the name is quite literal and the browser will store this so it's hard to change this afterwards - this should only ever be used to migrate to a new system.
Using redirect will force the browser to reload the site with the new URL, so this should be used with care as well, as it will add a significant delay to your page load times.

A: This issue is happening because of this.  rewriting with a query string works.


text:
Q: Bezier curves in As3 Am i right in thinking that from the Flash GUI you can only draw Cubic Bezier Curves, and from Actionscript you can only draw Quadratic Bezier Curves ? Really?
This seems, well.. im sure it cant be.. It would be crazy if i had to write a Quadratic Bezier drawing app to work out some point co-ordinates.

A: If you're using the drawing API, then you can only draw Quadratic Bezier Curves using the curveTo() function.
http://help.adobe.com/en_US/FlashPlatform/reference/actionscript/3/flash/display/Graphics.html#curveTo()
For proper bezier curves, it's not that hard, but you'll have to do it yourself. Some quick links with source code that I found:
http://www.paultondeur.com/2008/03/09/drawing-a-cubic-bezier-curve-using-actionscript-3/
http://www.farmcode.org/post/2009/07/06/Fast-2D-Bezier-Library-for-ActionScript-3.aspx

A: Actually from Flash Player 11, released yesterday, the Drawing API supports Cubic Bezier curves:
(amongst other improvements and additions on this major release...)
http://www.adobe.com/devnet/flashplayer/articles/whats-new-flash-player11.html

A: This is a great post to draw Cubic Bezier curves in ActionScript using the fl.motion.BezierSegment class:
http://www.eleqtriq.com/2010/04/cubic-bezier-in-flash/
It's awesome - I created a complete curve with multiple segments with a fraction of the code and classes you need for most of the other links on this page:
var resolution  :uint       = 50;
var step        :Number     = 1/resolution;

function drawCurve(p0:Point, c0:Point, c1:Point, p1:Point)
{
    var bezier  :BezierSegment  = new BezierSegment(p0, c0, c1, p1);
    var t       :Number         = 0;
    while (t <= 1)
    {
        var pt:Point = bezier.getValue(t);
        with (graphics)
        {
            lineStyle(0.1, 0x00FFFF);
            t == 0
                ? moveTo(pt.x, pt.y)
                : lineTo(pt.x, pt.y);
        }
        t+=step;
    }
    pt = bezier.getValue(1);
    graphics.lineTo(pt.x, pt.y);
}

It's a really great post!


text:
Q: Override eclipse Plugin in Project explorer In my project the user sees the red cross icon on the file containing an error and the folders above. When the (modelling nature of the sirius) plugin is added to the project the red cross dissapears on the file (not on the folders).
How can i keep the error icon on the file?
I can get information about the content extension which probably causes the problem
IWorkbenchPage page = PlatformUI.getWorkbench().getActiveWorkbenchWindow().getActivePage();         ProjectExplorer expl = (ProjectExplorer) page.findView(IPageLayout.ID_PROJECT_EXPLORER);
INavigatorContentService content = expl.getNavigatorContentService();
INavigatorContentExtension siriusext = content.getContentExtensionById("org.eclipse.sirius.ui.resource.content.session");
siriusext.getDescriptor().getAppearsBeforeId();

The problem is probably the sirius INavigatorContentService because it is set to appear before id "org.eclipse.jdt.java.ui.javaContent"
(siriusext.getDescriptor().getAppearsBeforeId())
How can i (have the modelling nature and) keep the error icon on the file?
Any help is appreciated!

A: I answered your question on the Sirius forum [1].
The problem seems to come from the getImage() implementation in the label provider used by the INavigatorExtension provided by Sirius.
A workaround could be to try to provide your own navigator content with an Override element targeting the Sirius Content Management (org.eclipse.sirius.ui.resource.content.session) as suppressed extension and provide your own label provider (which could extend the Sirius one and specifically handle the file case in getImage, but you might loose the M decorator on files handled by Sirius).
Could you open a bugzilla [2] to track the issue ? Then the team will have the possibility to analyze the issue and try to find a proper solution.
Regards,
Maxime
[1] https://www.eclipse.org/forums/index.php?t=msg&th=877968&goto=1498330&#msg_1498330
[2] https://bugs.eclipse.org/bugs/enter_bug.cgi?product=sirius


text:
Q: How to add to a RavenDB List in .net Update: I fixed it by copy pasting the working code into a new clean project. I have no idea why I was getting that bug, but as long as it's gone
I'm having problems figuring exactly how to do what I want.
In this instance, what I have is a db of merchants, and I want to be able to add venues as a list to the merchant entry in the database. For some reason I cannot figure out why, I can fetch the merchant, but cannot seem to get a hold of the id of the entry that I have fetched and then update it. (I'm having some problems with updating as well, From what I've seen I need the Id of the entry I want, and then I can update with a patch... right?)
Here is my Json class:
 public class Merchant
  {
     [JsonProperty(PropertyName = "name")]
     public string name { get; set; }
     [JsonProperty(PropertyName = "venues")]
     public List<Venue> venues { get; set; }

 }

public class Venue
{
    [JsonProperty(PropertyName = "name")]
    public string name { get; set; }
    [JsonProperty(PropertyName = "tills")]
    public List<Till> tills { get; set; }
}

public class Till
{
    [JsonProperty(PropertyName = "name")]
    public string name { get; set; }
}

Here's my RavenDB Handler class's functions that are relevent:
 public List<JObject> QueryFromDb(string query)
     {
        List<Object> objReturned;
        List<JObject> jObjects = new List<JObject>();
        using (IDocumentSession session = store.OpenSession())
        {
            objReturned = session
            .Advanced.RawQuery<Object>(query)
            .ToList();
        }
        for (var i = 0; i < objReturned.Count; i++)
        {
            var json = JsonConvert.SerializeObject(objReturned[i], Formatting.Indented);
            jObjects.Add(JObject.Parse( json.ToString()));
        }

        return jObjects;
    }

    public String GetJsonFromDB(string query)
    {
        string returnStr = "";
        List<JObject> myResponse = QueryFromDb(query);
        for (var i = 0; i < myResponse.Count; i++)
        {
            var json = JsonConvert.SerializeObject(myResponse[i], Formatting.Indented);
            returnStr += json.ToString();
        }
        return returnStr;
    }

And here is me trying to get ahold of the Id of the ravendb entry:
 public void UpdateMerchantList()
    {
        merchantGrid.Rows.Clear();
        List<JObject> myResponse = ravenDB.QueryFromDb("from Merchants");
        for (var i = 0; i < myResponse.Count; i++)
        {
           var json = JsonConvert.SerializeObject(myResponse[i], Formatting.Indented);
           Merchant merchant = new Merchant(json.ToString());
           if (myResponse[i].Property("Id") != null) { merchant.MyID = myResponse[i].Property("Id").ToString(); }
           merchantGrid.Rows.Add(merchant.MyID, merchant.name);
        }
    }

For some reason, I took this code and transplanted it into a console app, and got it to work with this code:
  List<JObject> result = ravenDb.QueryFromDb("from Merchants");
        for(var i = 0; i < result.Count; i++)
        {
            Console.WriteLine(result[i].Property("Id").ToString());
        }

Which does give me the exact stuff I want:
"Id": "merchants/97-A"
"Id": "merchants/98-A"
"Id": "merchants/129-A"
"Id": "merchants/130-A"
But when I transplant it backinto my form and try to add this to the datagridview I cannot see it anymore.
update: have been able to add to the list into the merchant class in the console app. Here is the code.
 public void AddVenue(string idArg,Venue venue)
    {
        using (IDocumentSession session = store.OpenSession())
        {

            var merchant = session.Load<Merchant>(idArg);
            List<Venue> venuesList = new List<Venue>();
            if (merchant.venues == null) { session.Advanced.Patch(merchant, m => m.venues, venuesList); }
            else
            {
                session.Advanced.Patch(merchant,
                x => x.venues,
                venues => venues.Add(venue));
            }
            session.SaveChanges();

        }
    }

Just so people understand what I'm talking about: here is the json that outputs from the form application:

Why?
when in console with pretty much identical code (copy pasted) I get this:

I'm getting more data from one application than the other, and I really really want the id.
I'm going to refactor the code into a wcf application I guess. Just because. Maybe I'll accidentally fix it doing that.

A: You can load directly the object of given class, no need to handle JSON (de)serialization yourself, unless there is a specific reason to do so.
Also, using patching is more useful when you don't want to load the document (to save bandwidth). When you already have the document loaded, you can simply change it and save the changes.
See the following code for reference:
public class Merchant
{
    // note added Id property
    public string Id { get; set; }
    [JsonProperty(PropertyName = "name")]
    public string name { get; set; }
    [JsonProperty(PropertyName = "venues")]
    public List<Venue> venues { get; set; }
}

public class Venue
{
    [JsonProperty(PropertyName = "name")]
    public string name { get; set; }
    [JsonProperty(PropertyName = "tills")]
    public List<Till> tills { get; set; }
}

public class Till
{
    [JsonProperty(PropertyName = "name")]
    public string name { get; set; }
}

public void MerchantsTest()
{
    using (var store = GetDocumentStore())
    {
        using (var session = store.OpenSession())
        {
            session.Store(new Merchant { Id = "merchant-1", name = "merchant1", venues = new List<Venue> { new Venue { name = "venue-1A", tills = new List<Till> { new Till { name = "till-1A-first" } } } } });
            session.Store(new Merchant { Id = "merchant-2", name = "merchant2", venues = new List<Venue> { new Venue { name = "venue-2A", tills = new List<Till> { new Till { name = "till-2A-first" } } } } });

            session.SaveChanges();
        }

        using (var session = store.OpenSession())
        {
            // you can load all merchants
            var merchants = session.Query<Merchant>(null, "Merchants").ToList();

            // or load specific merchant by ID
            var merchant2 = session.Load<Merchant>("merchant-1");

            // add a venue to a loaded merchant (not using patch but simply adding the object)
            merchant2.venues.Add(new Venue { name = "venue-2B", tills = new List<Till> { new Till { name = "till-2B-first" } } });

            session.SaveChanges();
        }
    }
}


text:
Q: How to calculate the optimal glyph bounds in a character map for OpenGL text rendering To render text with OpenGL I take the textured quad approach, I draw a quad for every character that needs to be represented. I store all the character texture information in a single texture, and use glScalef and glTranslatef on the texture matrix to select the correct character in the texture. At first I only put a few characters in the image used to create the texture and it worked well.
Since then I needed to render more characters, like lower case letters. I tried adding more characters, but now my text ends up unaligned and smaller.
Is there a proper way to create character maps, or is my approach all together wrong?
Note: I am using a mono-style font so font dimensions should not be the issue, however I would like to add support for fonts with non-uniform size characters as well.
EDIT: I'm using a vertex buffer for drawing rather than immediate mode.
EDIT 2: The texture containing the character map has 9 rows, each with 11 characters. Since the characters are the same size, I use glscalef on the texture matrix to 1/9 the width of the texture, and 1/11 the height. The VBO defines the quad (0,0),(1,0),(0,1),(1,1) and tex coords (0,0),(1,0),(0,1),(1,1). The nonalignment seems to be due to my transformations not fitting each glyph exactly. How are the optimal bounds for each glyph calculated?

A: In hopes that this may be useful to others. The optimal glyph bounds can be calculated by first normalizing the pixel offsets of each letter so that they are numbers within the range of 0 and 1. The widths and heights can also be normalized to determine the correct bounding box. If the widths and heights are uniform, like in mono fonts, static width and height values may be used for computing the glyph bounds.
Saving an array of pixel position values for each glyph would be tedious to calculate by hand, so it is better to start the first glyph at the first pixel of the character map and keep no spacing in between each letter. This would make calculating the bottom left uv coordinates easy with for loops
void GetUVs(Vector2* us, Vector2* vs, float charWidth, float charHeight, int cols, int rows)
{
    for (int x = 0; x < cols; x++)
    {
        for (int y = 0; y < rows; y++)
        {
            int index = x + cols * y;
            us[index].x = x * charWidth;
            vs[index].y = y * charHeight;
        }
    }
}

The rest of the bounds could be calculated by adding the width, the height, and the width and height respectively.


text:
Q: Symfony set variable in session really slow How come that setting a variable in my session is really really slow?
I have a voter which runs at every request (afaik). In this voter, I need to run a query to determine which custom roles my user has (defined in MySQL). So what I want to do, is save this data into my session, so I don't have to run this query on every request, which is really heavy.
So the code in my vote function:
$permissions = $this->context_manager->get('session')->get('permissions');
if (!$permissions) {
    $permissions = $this->entitymanager->findPermissions(User $user);
    $this->context_manager->get('session')->set('permissions', $permissions);
}

I debugged this (commenting every line, until I knew what was the problem) and it turned out that setting the variable in the session was really slow. Anyone knows why?


text:
Q: Taylor Series Expansion of an Arbitrary Function to an Arbitrary Power I am currently trying to express an arbitrary function, $f(x)$ to an arbitrary power, $m$, using a Taylor series
$$
\left[f\left(x\right)\right]^m
$$
I first considered expressing $f\left(x\right)=\sum_{n=1}^{\infty}{a_n\left(x-b\right)^n}$, where $a_n=\frac{1}{n!}\ \frac{\partial^nf}{\partial x^n}$ and $b$ is the point about which the function is known. I first multiplied the series unto itself m times and got the following:
$$\left[f\left(x\right)\right]^m=\sum_{n=1}^{\infty}{a_{n,1}\left(x-b\right)^n}\sum_{n=1}^{\infty}{a_{n,2}\left(x-b\right)^n}\sum_{n=1}^{\infty}{a_{n,3}\left(x-b\right)^n}\ldots=\ $$
$$=\ldots\sum_{i=1}^{\infty}\sum_{j=1}^{\infty}\sum_{k=1}^{\infty}{a_ia_ja_k\ldots\left(x-b\right)^{i+j+k+\ldots}}\ $$
Where I have $m$ summations upon one another. For example, when $m=3$, the expression looks as follows:
$$\sum_{i=1}^{\infty}\sum_{j=1}^{\infty}\sum_{k=1}^{\infty}{a_ia_ja_k\left(x-b\right)^{i+j+k}}$$
Is there a simpler way to represent this? I was thinking about using some sort of binomial expansion, but I'm not sure where to start with that. Later I'd like to try to do this a function of two variables, such as $f(x,y)$, but wanna start simple first. Any advice on the latter matter would be greatly appreciated.


text:
Q: LINQ join error in Release mode I use Sql Server compact database, and my linq query work properly in debug mode, but it has error in release mode !
My query use "join" and the exception is:

The method '
  [My_Project_Namespace.MyTransactions,My_Project_Namespace.Users].
  ' is not a property accessor

Here is my LINQ query:
var result = from transRow in db.MyTransactions
             join userRow in db.Users on transRow.User_id equals userRow.Id
             join clientRow in db.Clients on
                transRow.Client_id equals clientRow.Id
             select new
             {
                 userId = transRow.User_id,
                 clientId = transRow.Client_id,
                 userName = userRow.Fname + " " + userRow.Lname,
                 clientName = clientRow.Fname + " " + clientRow.Lname,
                 reg_date = transRow.Reg_date,
                 value = transRow.Value
             };

My aim is add (or replace) the user id with his name and also the client id with his name.

A: as Oleksiy Gapotchenko (Eazfuscator.NET Developer) said here
you need to add this on the assembly level:
[assembly: Obfuscation(Feature = "anonymous type properties renaming", Exclude = true)]

then, all of your anonymous method and types won't be obfuscated, and (probably) will work....

A: I found out that's because of using some obfuscators like "Eazfuscator.NET".
but it will work with some other obfuscators like "Babel" !


text:
Q: Python ThreadPoolExecutor not run max I need it to run two threads at the same time. Please help me, i had tried anything i know.
    with ThreadPoolExecutor(max_workers=2) as executor:
    futures = []
    for k, v in dict_tk_mk.items():
        futures.append(executor.submit(login(k,v)))

enter image description here

A: It seems like you are using wrong syntax of executor.submit. It should be like this
with ThreadPoolExecutor(max_workers=2) as executor:
    futures = []
    for k, v in dict_tk_mk.items():
        futures.append(executor.submit(login, *(k,v))) # see this line, you will find the issue

For detailed example from where i learnt the syntax, please this: https://docs.python.org/3/library/concurrent.futures.html#threadpoolexecutor-example
PS: I made this error when I was new too :P


text:
Q: Cache content of QWebView for offline usage I wish to use a QWebView in application, which most of time is in offline state. Even then it should present as up to date data as it is possible.
For example - user visits the stackoverflow.com webpage via QWebView. After 2-3 days he wish to visit the same webpage, however he is in offline state. As a result he gets the last available content.
The question - Is it possible to easily add an offline storage to QWebView instance?


text:
Q: How to format cultural date in JQGrid? JQGrid supports multi-language. That also includes dates. I have formatted most of the date but facing problem in Bulgarian date. As they have date and time like 21.12.2001 r 18:12:30 u. Now, I am facing problem to get that r and u in the date that is getting displayed. Same case is there with Korea.
Input format is 'ISO8601Long' so I need newformat in JQGrid which allows that extra r and u. Else I am getting the format.
I am facing issue while displaying the grid data. Its not edit mode.
Please let me know if any further details needed. You can check details about Bulgaria culture here.

A: What you can do is the usage of Globalize jQuery plugin. I modified the demo from the answer. The demo demonstrate one possible implementation of your requirements.

I used the following
formatter: function (cellvalue) {
    // we don't use time zones information in the code below
    var dMatch = cellvalue.match(new RegExp("([0-9]{4})(-([0-9]{2})(-([0-9]{2})" +
            "(T([0-9]{2}):([0-9]{2})(:([0-9]{2})(.([0-9]+))?)?" +
            "(Z|(([-+])([0-9]{2}):([0-9]{2})))?)?)?)?")),
        date = new Date(
            Number(dMatch[1] || 0),   // year
            Number(dMatch[3] || 0)-1, // month
            Number(dMatch[5] || 0),   // day
            Number(dMatch[7] || 0),   // hours
            Number(dMatch[8] || 0),   // minutes
            Number(dMatch[10] || 0),  // seconds
            Number(dMatch[12] || 0)
        ); // milliseconds

    return Globalize.format(date, "F");
},
unformat: function (v) {
    return Globalize.parseDate(v);
}


text:
Q: How to animate cursor immediately on click, while JavaScript is running, before Postback I'm implementing Google Charts and providing the option to export them to PDF or Word.  In order to achieve this, I am calling the getImageURI() method after each chart is drawn.  These are on reports, and some reports have quite a few images.
On one that has nearly 100, Firefox is giving a warning message for a script that is taking too long.  If I remove the image creation part, it runs much faster.  However, I need to generate those at some point.
My first attempt was to run a new JavaScript method to do this when the Export to Word/Excel was clicked, prior to sending that command back to the server.  This works fine, but I can't get the animation of the cursor in progress to begin right away.
drawChartsWithImageGeneration: function () {

    $("body").addClass("cursorProgress"); // changes cursor

    $("div.chartContainer").each(function () {
        var chartContainer = $(this);
        drawChart(chartContainer);
    });

    $("body").removeClass("cursorProgress"); // changes cursor back
}

If I add a console.log() at the beginning of the function, it does execute immediately.  However, for some reason, the class is not added to the body tag until the drawChart() function completes and the PostBack ensues.
The Anchor tag that initiates this has the doPostBack on the href and the drawChartsWithImageGeneration on the onclick event.
(FYI: Using C#)

A: What you could do is change your drawChart function to take in a callback which gets executed after the chart is rendered.  Loop through each one of the charts and render each with a millisecond gap between. This should give the cursor enough time to change on the screen.
Also, if there are hundreds of charts on the page, the millisecond gap between each chart render will keep browsers (Firefox) from complaining about an unresponsive script.
drawChart: function (container, callback) {
    // Chart creation logic here
    // somewhere create an instance of the google chart object
    // and call it "chart" for use below

    google.visualization.events.addListener(chart, 'ready', callback || $.noop);
},

drawChartsWithImageGeneration: function () {
    var $chartContainers = $("div.chartContainer");
    var chartCount = $chartContainers.length;

    $("body").addClass("cursorProgress"); // changes cursor

    // Draw each chart one at a time, change the cursor back when all charts have finished
    (function doDraw(index) {
        if (index < chartCount) {
            setTimeout(function() {
                drawChart($chartContainers.eq(index), function () {
                    doDraw(index + 1);
                });
            }, 1);
        }
        else {
            $("body").removeClass("cursorProgress"); // changes cursor back

            // Whatever else you need to do after all charts are ready
        }
    })(0);
}

A: It could be that the DOM did not have enough time between functions to update.
Try setting a timeout for 300 ms before continuing the rest of your functions.
It could also be that your drawChart function is not waited on to be completed to start the script that removes the cursorProgress class.
Try moving the remove cursorProgress class function to the end of your drawChart function.


text:
Q: Access props from selector's resultFunc I have a similar use case as in the accessing react props in selectors docs, but in my case let's say the visibilityFilter comes from the props. Is there a way how to achieve something like below?
export const getVisibleTodos = createSelector(
  getTodos,
  (todos, props) => {
    // props is undefined
    switch (props.visibilityFilter) {
      case 'SHOW_ALL':
        return todos
      case 'SHOW_COMPLETED':
        return todos.filter(t => t.completed)
      case 'SHOW_ACTIVE':
        return todos.filter(t => !t.completed)
    }
  }
)

I still need it to be properly memoized, but I guess that's the second step.

A: Props (or ownProps) is the second argument passed to any mapStateToProps function.
Using that, you can extract the property you want as one of the inputs to your resultFunc.
export const getVisibleTodos = createSelector(
  getTodos,
  (state, props) => props.visibilityFilter,
  (todos, visibilityFilter) => {
    switch (visibilityFilter) {
      case 'SHOW_ALL':
        return todos
      case 'SHOW_COMPLETED':
        return todos.filter(t => t.completed)
      case 'SHOW_ACTIVE':
        return todos.filter(t => !t.completed)
    }
  }
)


text:
Q: Wildfly: Management user vs Application user I downloaded Wildfly (wildfly-13.0.0.Final) and I want to configure it. I start standalone.bat in the bin folder of JBOSS_HOME directory (I use Windows platform).
I go to management console: localhost:8080 -> Administration Console. I see this

Your WildFly Application Server is running.
  However you have not yet added any users to be able to access the admin console.
To add a new user execute the add-user.bat script within the bin folder of your WildFly installation and enter the requested information.

I run add-user.bat and it asks me what kind of user I would like to add.
I need a user to have permissions to deploy, redeploy applications. For example, for Apache Tomcat I can consifure tomcat-users.xml file and add users there (https://stackoverflow.com/a/1327730/4587961), so when I log into console as that user, I can deploy applications.

A: You need to add a Management user with the add-user.bat, whose credentials you will be able to log in the web admin with.
You could direclty add the user to the mgmt-users.properties file in the configuration directory of your standalone or domain, but the entry must be of the form <username>:DIGEST-MD5(<username>:ManagementRealm:<password>), which the add-user.bat script will handle for you.
You don't need any particular role unless you set up RoleBasedAccessControl.
Applicative users are used by applications with frameworks such as JAAS and are interfaced through the "default" security-domain, which refers to the ApplicationRealm containing those users.

A: As I read
https://docs.jboss.org/author/display/WFLY10/EJB+invocations+from+a+remote+server+instance
https://developer.jboss.org/thread/240892
Management user is used to enter the web console. Here you can deploy app, make settings, add resources (JPA config for example). Application users do not have access to the web console. They can be used for example to authenticate services. For example to invoke remove EJB bean, you need application user credentials to access the remove server.


text:
Q: Laravel 5.3 and Parsley remote validation i tryed to remote validate the email and username for a registration form with parsley. I get allways the message:
public/checkUserName?username=tester 405 (Method Not Allowed)

So here is my code:
Input:
<input data-parsley-remote="{{ route('checkUserName') }}"  data-parsley-remote-message="Der Username ist bereits vergeben!" data-parsley-remote-options='{ "type": "POST", "dataType": "jsonp", "data": {_token: CSRF_TOKEN, "UserName": "username" } }'

Route:
Route::post('/checkUserName', [
   'uses' => 'UserController@checkUserName',
   'as' => 'checkUserName'
]);

UserController:
public function checkUserName(Request $request)
{
    if(user::where('UserName','=',$request->input('UserName'))->exists()){
           return response::json('exists', 404);
        }else{
           return response::json('not exists', 200);
        }
}

A: The error 405 (Method Not Allowed) is thrown by Laravel because request method GET is not allowed to handle the route registered for POST.
First of all, I'm not familiar with Parsley but after observing your code, what I've found is that, you have setup the parsley to send AJAX request using POST method but the data type is set to jsonp.
// Extracted from the question
data-parsley-remote-options='{
    "type": "POST",
    "dataType": "jsonp",
    "data": {_token: CSRF_TOKEN, "UserName": "username" }
}'

In this case, jsonp is not possible using POST  method because it sends a GET request (using a script tag...) and hence, your route is not found because you've registered the route as POST.
So, it's happening because of inappropriate data type (jsonp) with the request method POST. I'm sure that, the Parsely is sending a GET request instead of POST request because of dataType:jsonp.
So, you can check the network tab in your browser inspector to find out the request method that is being sent and you should either register the route with Route::get() or change the dataType to something else, could be json but you should check the Parsely documentation for available data types.