text:
Q: AngularJS - A simple infinite scroll I am trying to write a similar small infinite scroll to the one found here: http://jsfiddle.net/vojtajina/U7Bz9/
I've been able to display the first 5 pieces of data, however on scroll, the further items are not being displayed.
HTML:

{{ i.Title }}

JS:
var app = angular.module('app', []);

app.controller('MainCtrl', function($scope) {
  $scope.name = 'World';

  $scope.items = [
    {
       "Title":"Home"
    },
    {
       "Title":"Contact"
    },
    {
       "Title":"Help"
    },
    {
       "Title":"About"
    },
    {
       "Title":"Our Offices"
    },
    {
       "Title":"Our Locations"
    },
    {
       "Title":"Meet the Team"
    }
    ,
    {
       "Title":"Our Mission"
    },
    {
       "Title":"Join Us"
    },
    {
       "Title":"Conferences"
    },
    {
       "Title":"Tables"
    },
    {
       "Title":"Chairs"
    }
  ];

    var counter = 0;
    $scope.loadMore = function() {
        for (var i = 0; i < 5; i++) {
            $scope.items.push({id: counter});
            counter += 10;
        }
    };

    $scope.loadMore();

});

app.directive("directiveWhenScrolled", function () {
  return function(scope, elm, attr) {
        var raw = elm[0];

        elm.bind('app', function() {
            if (raw.scrollTop + raw.offsetHeight >= raw.scrollHeight) {
                scope.$apply(attr.whenScrolled);
            }
        });
    };
});

Here's a plunker: http://plnkr.co/edit/6ggYGZx6scSoJ5PNhj67?p=preview

A: I've found an awesome angularjs 'infinite' scroll solution.
What you need to do is just add an in-view directive in your project and do next stuff:

angular.module('infinitScrollApp', ['angular-inview'])
       .controller('infinitScrollController', infinitScrollController);

function infinitScrollController($scope) {
  $scope.limit = 10;
  $scope.items = Array.from(Array(1000).keys());

  $scope.loadMore = function (last, inview) {
      if (last && inview) {
          $scope.limit += 10;
      }
  }
}
.infinit-scroll-container {
  height: 150px;
  overflow-y:scroll
}

            {{item}}

A: There are two problems. First of all, what is attr.whenScrolled? Its undefined. Second one - limitTo: 5. You will allways show only 5 elements!
Here you have working code: http://plnkr.co/edit/VszvMnWCGb662azo4wAv?p=preview
What was changed? Your directive is called directiveWhenScrolled so call:
scope.$apply(attr.directiveWhenScrolled);

instead of
scope.$apply(attr.whenScrolled);

How lets deal with static limit. Change it into variable (remember about defining default value):

{{ i.Title }}

And now your loadMore function should look like this:
$scope.loadMore = function() {
    $scope.limit += 5;
};


text:
Q: Is it possible to eliminate output ripple of SMPS's by using two parallel SMPS's to produce outphase outputs to each other?

simulate this circuit – Schematic created using CircuitLab
Obviously it can not be that way. But why? Imagine one converter with a phase detector of its switching frequency, outputs a flag when the phase is 180° and other one synchronises its own oscillator to output an outphase ripple to other. Then it will be like below:

Green one is the output sum of two AC ripples and the common DC. What are the reasons why this can not be done?

A: Is it possible to eliminate output ripple of SMPS's by using two parallel SMPS's to produce outphase outputs to each other?
No.
However, some switching power supplies are multi-phase, which means they have multiple power trains in parallel inside.  This is usually done to increase the output current capability, but the phases are also usually run evenly staggered over a cycle to reduce ripple.
Eliminating ripple using two supplies would require each to having exactly the opposite ripple of the other, and then these two exactly averaging.  It should be obvious that's never going to happen.
Other than specifying absolutely 0 ripple, the main fault in your thought process is that the ripple of switching power supplies is unlikely to be something that is symmetric per half waveform.  Your diagram shows sine, for which this would work, but the ripple out of switching power supplies is more spiky than that.  Or, it can be a trapezoid output with fairly sharp rise, then slower decay, or sometimes a slow rise with fast decay.  Changes in the load will also affect the amplitude and shape of the ripple.  These kinds of waveforms 180° out of phase don't average to a flat line.

A: While you can't eliminate all the ripple, you can eliminate all components at the fundamental switching frequency by using a dual-phase switcher. An n-phase switcher can eliminate all harmonics up to the (n-1)th. Obviously in practice component mismatches and offsets cause some of this to be imperfect, but in practice very significant (10-20 dB) reduction is possible, and the peak-peak ripple at the output can be reduced, or equivalently, the output capacitance reduced for the same amount of ripple.

A: Some SMPS ICs have sync inputs/outputs. With this type, it is possible to run multiple ICs in polyphase. This increases the ripple frequency and decreases the ripple amplitude, making it easier to filter.
It might be easier simply to use a single polyphase controller to handle multiple switches.
Free running SMPS ICs without sync I/O would not be easy, and may be impossible, to synchronise into a nice polyphase.

A: The voltage ripple on the output is the integral of current in the output capacitor(s). If we assume the load draws a constant current then for the ripple voltage to be zero the current delivered from the switch mode converter(s) must also be constant.
If the ripple current from the switchers was a nice clean sinusiod at the switching frequency then what you propose would be possible. Instead as the name suggests it's a waveform resulting from switching, sometimes the current may be zero (bucks running in "continuous mode" do deliver current all the time, boosts, flybacks and converters running in discontinous mode don't) and when current is being delivered it's not quite at a constant rate (how close to constant it is depends on the value of the inductor). The exact shape of the waveform will depend on many factors including supply voltage and load current.
Having said that while your method won't completely eliminate ripple it will significantly reduce it. We call this a "polyphase" converter and it can be done with any number of phases from 2 upwards.
For now lets assume that the waveforms from all the converters are time-shifted copies of each other and are periodic at the switching frequency (these are approximatations of relality but good enough for now). We can view any periodic waveform as a series of sinusiods at harmmonics of the switching frequency.
If we have n perfectly matched phases then we eliminate any harmonics that are not a multiple of n. In general lower harmonics tend to be larger than higher ones for most waveforms and on top of this the output capacitor is acting as an integrator which means high frequency ripple currents have much less impact on ripple voltage than low frequency ones.
This is done in practice, for example http://www.linear.com/docs/4166 describes a converter IC that is designed to drive two phases directly and provides functionality for syncronising multiple chips to build converters with up to 12 phases.

redpajama_set_name: RedPajamaStackExchange


text:
Q: Browse File button doesn't work (Only in AM Revolution Slider) after patch 8788 I have installed the SUPEE-8788 patch in Magento 1.9.2.3 CE. At the first time I have installed the v1 of the patch, now I have reverted it and I have installed the v2, but the issue persisting. When I try to change the image background in a slide of AM Revolution Slider, the "Browse File.." doesn't work, I can't change the image.
I'd try to clear Magento cache, browser cache, restart Apache2 but nothing.
I'd check the source of page and this file are not present:

*

*/js/lib/uploader/flow.min.js

*/js/lib/uploader/fusty-flow.js

*/js/lib/uploader/fusty-flow-factory.js
Someone has an idea how I can solve?

A: You need to make sure that you've deleted all the .swf files from skin/adminhtml/default/default/media/. I had the same problem and removing them files fixed the issue for me.


text:
Q: How do I set a non-standard User-Agent using spray-client? I'm building an application for a Telco, using Scala and Akka, and need to communicate with Account Information and Refill servers using the UCIP protocol.
UCIP is a simple protocol, built on XMLRPC; the only issue I'm having is that it requires clients to set the User-Agent header in the specific format User-Agent: <client name>/<protocol version>/<client version>, which spray parses as invalid.
I tried creating a custom User-Agent header, inheriting from spray.http.HttpHeader but it still doesn't work. Here's what I've got so far:
import akka.actor.ActorSystem
import akka.event.{Logging, LoggingAdapter}
import spray.client.pipelining._
import spray.http._
import spray.httpx._

case class `User-Agent`(value: String) extends HttpHeader {
    def lowercaseName: String = "user-agent"
    def name: String = "User-Agent"
    def render[R <: Rendering](r: R): r.type = r ~~ s"User-Agent: $value"
}

class UcipClient(val url: String, val protocol: String, username: String, password: String) (implicit system: ActorSystem) {

    val log = Logging.getLogger(system, this)
    val logRequest: HttpRequest => HttpRequest = { r => log.debug(r.toString); r }
    val logResponse: HttpResponse => HttpResponse = { r => log.debug(r.toString); r }

    val pipeline = (
        addHeader(`User-Agent`("USSD-UCIP/%s/1.0".format(protocol)))
        ~> addCredentials(BasicHttpCredentials(username, password))
        ~> logRequest
        ~> sendReceive
        ~> logResponse
    )

    def send(req: UcipRequest) = pipeline(Post(url, req.getRequest))
}

My requests keep returning "Sorry, Error occured: 403, Invalid protocol version Not defined", however, they return the correct response when I send the same details using curl.
What am I missing, and is this even possible with spray-client? I've spent a fair bit of time checking the internets (which led me towards the custom header route), but still haven't figured this out...would really appreciate any help :-)

A: Turns out I wasn't far from the answer. While examining the headers being sent over the wire, I noticed the User-Agent was being set twice: once by my code, and again by Spray (because it considered my header invalid).
Setting the spray.can.client.user-agent-header to the empty string "" removed the second header, and requests were successful. Here's the final version of the custom header:
import spray.http._

object CustomHttpHeaders {
    case class `User-Agent`(val value: String) extends HttpHeader with Product with Serializable {
        def lowercaseName: String = "user-agent"
        def name: String = "User-Agent"
        def render[R <: Rendering](r: R): r.type = r ~~ s"User-Agent: $value"
    }
}

And the final UCIP client:
import akka.actor.ActorRefFactory
import com.typesafe.config.Config
import scala.concurrent.ExecutionContext.Implicits.global
import scala.xml.NodeSeq
import spray.client.pipelining._
import spray.http._
import spray.httpx._

class UcipFault(val code: Int, msg: String) extends RuntimeException(s"$code: $msg")

class AirException(val code: Int) extends RuntimeException(s"$code")

class UcipClient(config: Config, val url: String)(implicit context: ActorRefFactory) {
    import CustomHttpHeaders._

    val throwOnFailure: NodeSeq => NodeSeq = {
        case f if (f \\ "fault").size != 0 =>
            val faultData = (f \\ "fault" \\ "member" \ "value")
            throw new UcipFault((faultData \\ "i4").text.toInt,
                                (faultData \\ "string").text)
        case el =>
            val responseCode = ((el \\ "member")
                .filter { n => (n \\ "name").text == "responseCode" }
                .map { n => (n \\ "i4").text.toInt }).head
            if (responseCode == 0) el else throw new AirException(responseCode)
    }

    val pipeline = (
        addHeader(`User-Agent`("USSD-UCIP/%s/1.0".format(config.getString("ucip.server-protocol"))))
        ~> addCredentials(BasicHttpCredentials(config.getString("ucip.server-username"), config.getString("ucip.server-password")))
        ~> sendReceive
        ~> unmarshal[NodeSeq]
        ~> throwOnFailure
    )

    def send(req: UcipRequest) = pipeline(Post(url, req.getRequest))
}


text:
Q: Unity return rotation to 0 after button release I have small game I wrote in which i have object which moving forward and turning left  and right. when user press A object goes left and rotate  to the left if user pres D it goes left and rotate left, i what  to set rotation to 0 after user letting key up
bool slowbtn = Input.GetKey("s");
bool right = Input.GetKey("d");

if (right == true)
{
    rd.AddForce(sideForce * Time.deltaTime, 0, 0,ForceMode.VelocityChange);
    rd.transform.eulerAngles = new Vector3(0, 10 , 0);
}
if (Input.GetKey("a"))
{
    rd.AddForce(-sideForce * Time.deltaTime, 0, 0, ForceMode.VelocityChange);
    rd.transform.eulerAngles = new Vector3(0, -10 , 0);
}

if i wan to set rotation back to 0 when user release key i am using this
if (Input.GetButtonUp("a"))
{
    rd.transform.eulerAngles = new Vector3(0, 0, 0);
}
if (Input.GetButtonUp("d"))
{
    rd.transform.eulerAngles = new Vector3(0, 0, 0);
}

but it doesn't work I don't understand why and also it brakes my previous code , so object if not moving forward

A: Unity's Input.GetButtonUp and Input.GetButtonDown handle "virtual" buttons, which you set up in Input Settings. Input.GetKeyUp/Input.GetKeyDown are about keys on your keyboard. So, you should choose GetKey or GetButton but not both at the same time.
As I see, you want your object rotates during all the time user is pressing a key. I suggest you to use addition "state" property in your class:
private State state = State.IDLE;
private enum State {
  LEFT, RIGHT, IDLE
};

Update your code:
if (Input.GetKeyDown(KeyCode.D)) {
  state = State.RIGHT;
}
if (Input.GetKeyDown(KeyCode.A)) {
  state = State.LEFT;
}
if (Input.GetKeyUp(KeyCode.D) || Input.GetKeyUp(KeyCode.A)) {
  state = State.IDLE;
}
switch (state) {
  case State.LEFT:
    rd.AddForce(sideForce * Time.deltaTime, 0, 0, ForceMode.VelocityChange);
    rd.transform.eulerAngles = new Vector3(0, 10, 0);
  break;
  case State.RIGHT:
    rd.AddForce(-sideForce * Time.deltaTime, 0, 0, ForceMode.VelocityChange);
    rd.transform.eulerAngles = new Vector3(0, -10 , 0);
  break;
  case State.IDLE:
    rd.transform.eulerAngles = Vector3.zero;
  break;
}

Several recommedations:

*

*Operate with physics in FixedUpdate() method instead of Update()

*Use Unity's KeyCode enumeration for keyboard keys

*Keep your code clean

*Develop an algorithm first and then convert that algorithm to a code

A: When I replace your
Input.GetButtonUp("a")

with
Input.GetKeyUp("a")

this works totally fine.
Did you try to debug this code for yourself? Because it was quite simple to figure out that the Input.GetButtonUp(…) was not called by setting a breakpoint in this line.
Btw. I would consider writing your input code like this:
if (Input.GetKey("d"))
{
    rd.AddForce(sideForce * Time.deltaTime, 0, 0, ForceMode.VelocityChange);
    rd.transform.eulerAngles = new Vector3(0, 10, 0);
}
else if (Input.GetKey("a"))
{
    rd.AddForce(-sideForce * Time.deltaTime, 0, 0, ForceMode.VelocityChange);
    rd.transform.eulerAngles = new Vector3(0, -10, 0);
}
else
{
    rd.transform.eulerAngles = new Vector3(0, 0, 0);
}


text:
Q: Where can I find the Cerberus Turian Poison? My galaxy is currently 100% scanned and I haven't found any sign of a sample of Cerberus Turian Poison. Is it located in a galaxy I just haven't unlocked yet? Or perhaps in the Priority missions I'm waiting to do?
Considering how some missions become impossible to complete after certain Priority missions sometimes, I'm trying to put off the ones I have (Eden Prime and Perseus Veil) until absolutely necessary.

A: There's a side mission you'll undertake to rescue some Cerberus scientists who have defected.  This mission is titled "Arrae: Ex-Cerberus Scientists."  I don't want to spoil it, but it's a side mission that can potentially involve one of your former Mass Effect 2 squadmates.
During one part of this mission, you'll be able to wander around their lab.  The data about the poison is located in their lab.  I believe it's on the second floor, in a corner away from the large plate glass windows.  There's an NPC that you'll have to talk to in order to progress the story, and I believe you should search the lab thoroughly first, lest you miss this item.
There's a second opportunity, near the end of the mission, where the same NPC will ask you if you're ready to leave or not.  I told this person I was ready immediately, but MBraedley confirms that if you want a second chance to check the lab, this is it.
Although I found it in the lab, the ME Wikia states that if you miss it, you can buy it on the Citadel afterwards.  The credit reward for the mission is the same as the cost of the item, so if you missed it, the only reward is +5 Reputation, 30 XP, and a small War Asset boost from the general you cure.

A: You'll find the necessary item called the Turian Toxin Data in the lab area (under a microscope) during the mission Arrae: Ex-Cerberus Scientists. If you already missed this item, you can buy it from the Spectre terminal.


text:
Q: How to detach all objects from Hibernate session From time to time I need to clean Hibernate session.
How to prevent LazyInitializationException with obects that are attached to this session?
I am searching for something like session.detachAllObjects().
and then invoke session.clear()
After this I suppose these objects will be retrieved from DB.

A: session.clear() detaches all objects.
LazyInitializationException usually means that the entities are detached from a session, or a session is closed. If you want to avoid it, attach an object to a session (using session.merge(..)), or don't close it (using OpenSessionInView)


text:
Q: Filtering By Date Given Google Firestore Swift Currently, I am uploading information to Google Firestore and will be uploading the information with a date that the user gives. So for instance, before the user uploads, they select a date through UIDatePicker(). Which outputs a date in the format as: Jan 19, 2018.
Now when the user uploads the document, a field is in the database set to date, which will populate Jan 19, 2018.
My question is how can I effectively query a list of all the uploads in order by date, starting from the most recent date at the top, and the latest date at the bottom.
My final objective is to create a collection view which will just have the list of all the dates, starting at the most recent.
I cannot do it based on when the user uploads, as the user can upload information that is for a previous day. A user may also upload something to the database for the same day, in which case the date will come twice in a row.
What would be the most effective way?
Is there a query in Firestore which I could do? Or will I need to get all the document dates, and sort them myself within the application?
Any guidance would be great!
Thank you,

A: Well you can't apply query using date i.e. Jan 19, 2018. Only the thing is useful for your case is to store timestamp in FireStore. You can easily convert date into timestamp by using following code:
extension UIDate {
      var millisecondsSince1970:Int {
          return Int((self.timeIntervalSince1970 * 1000.0).rounded())
      }
}

Date().millisecondsSince1970 // 1476889390939

Then you can apply FireStore following query to get records on the basis of timestamp
databaseRef.order(by: "timeStamp", descending: true)


text:
Q: $p$ and $r$ are primes greater than $2$. $p+r$ vs $p+2r$, which could be a prime number? For $p+2r$, a example would be $3$ and $5$. Since $6+5 = 11$, I am led to believe $p+2r$ to be the right answer. But I don't know how it works?

A: hint: $p+r > 2$ and is an even number.


text:
Q: Programme crashes while deallocating a character array When I run the .exe being created with the below code in debug mode , it shows some assertion failure and the programme crashes But when i run the same exe created from the release mode of the below code , its working fine.
Please help to identify why I am geting the assertion failure in debug mode but not in release mode .
#include<iostream>
using namespace std;
#include<string.h>

void main()
{
    char *buf  = new char[5];   //pre-allocated buffer
    buf = "Hello";
    delete [] buf;
    getchar();
    //cout<<buf;
    //string *p = new (buf) string("hi");  //placement new
    //string *q = new string("hi");  //ordinary heap allocation
}

A: *

*void main is wrong. main returns int. No exceptions.

*You're doing delete[] "Hello". "Hello" is a string literal; you can't delete it.

A:  char *buf  = new char[5];   //pre-allocated buffer

Here you define a pointer, and initialize it to point to a dynamically allocated buffer with room for 5 characters.
buf = "Hello";

Here you initialize the pointer to point to the beginning of a string literal.
 delete [] buf;

Here you delete[] the buf pointer, but the buf pointer no longer points to anything you new[]'d up, it points to the string literal. You can only delete/delete[] a pointer that points to something you got from new/new[]. So you get undefined behavior, and likely crash
You likely meant to copy the content of your string into the buffer you new[]'d. Remember to account for the nul terminator:
int main()
{
    char *buf  = new char[6];   //pre-allocated buffer
    strcpy(buf, "Hello");
    delete [] buf;
    getchar();
    //cout<<buf;
    //string *p = new (buf) string("hi");  //placement new
    //string *q = new string("hi");  //ordinary heap allocation
}

Though, in C++, you'd rather use std::string from #include <string>;
std::string = "Hello";

A: When you do this:
buf = "Hello";

You're basically changing the pointer value (memory address) at which buf points to a read-only memory area, because "Hello" is a string literal and therefore is stored in read-only memory.
Then you attempt to free that memory, hence the crash.
Also, "Hello" is 6-bytes long, not 5.

A:  char *buf  = new char[6];   //pre-allocated buffer
 strncpy(buf, "hello", 6);
 delete [] buf;

buf = "hello"; would change the buf's value, from a pointer to new char[6] To a pointer point to "hello", a block of memory not in heap.

A: Because undefined behavior means anything can happen. The problem is that buf = "Hello" assigns the address of a string literal to buf, then tries to delete that literal. When compiled in debug mode the checking code sees that the address can't be deleted; in release mode that check isn't done, and the delete just stomps on something that isn't critical.

A: You're trying to deallocate the character-string literal "Hello". This line:
buf = "Hello";

redirects the pointer buf to point at the literal "Hello". You probably meant to do this:
char *buf = new char[6]; //need one extra space for terminating NUL character
strcpy(buf, "Hello");


text:
Q: First element of char array is getting initialized to null automatically.strings, scanf, printf Input:9 notation
printf("Input N value\n");
scanf("%d",&N);
char X[N];
int i=0,N=0;
for (i=0;i<N-1;i++)
 {
scanf("%c",&X[i]);
}
X[N-1]='\0';

for (i=0;i<N-1;i++)
{
printf("%c",X[i]);
}

Expected output:notation
Output:notatio
Why is this so?

A: When you read the length with your first scanf call you leave a newline in your input buffer.
At the second scanf call the first character read is the newline and then the rest. Adding a space before the %c in your second scanf string parameter will consume any left newlines.
scanf(" %c",&X[i]);

You also don't null terminate your string, before printing it.
X[N-1] = '\0' ;

A: You dont have to substract 1 in your for loops, otherwise it will miss 1 character at the end!
This should work:
#include <stdio.h>

int main() {

    int charNumber, charCount;

    printf("Input N value\n>");
    scanf("%d", &charNumber);

    char text[charNumber+1];

    for (charCount = 0; charCount < charNumber; charCount++)
        scanf(" %c", &text[charCount]);

    text[charNumber] = '\0';

    for (charCount = 0; charCount <= charNumber; charCount++)
            printf("%c", text[charCount]);

    return 0;

}

You can also print the string with:
printf("%s", text);


text:
Q: Fatal Error: does not derive any sentence When I run parser.y on the following file I get the following errors:
myanalyzer.y: warning: 14 nonterminals useless in grammar
myanalyzer.y: warning: 36 rules useless in grammar
myanalyzer.y:7.8-18: fatal error: start symbol main_struct does not derive any sentence

I cannot understand what is wrong with the code:
    %{
    #include <stdio.h>
    #include <string.h>
    extern int line_num;
    extern char *yytext;
%}
%start main_struct

%left PLUS

%token PUBLIC   1
...
%token CONSTANT_CHAR    45

%%
main_struct:variables_declaration
        class_declaration
        functions_declaration
        ;

constant:   INT
        |BOOLEAN
        |CHAR
        |STRING
        |FLOAT
        |DOUBLE
        ;

locality:   PUBLIC
        | PRIVATE
        ;

identifier1:    IDENTIFIER
        | identifier1 COMMA IDENTIFIER
        ;

class_body: /*empty*/
        |  locality variables_declaration locality functions_declaration identifier1
        |  locality variables_declaration identifier1
        |  locality functions_declaration identifier1
        |  identifier1
        ;

variables_declaration:  /*empty*/
            |  variables_declaration constant identifier1 SEMICOLON
                |  variables_declaration constant identifier1 COMMA
                ;

class_declaration:  /*empty*/
            | class_declaration CLASS identifier1 BEGIN class_body END
            ;

functions_declaration:  functions_declaration constant identifier1 LEFT_PARENTHESIS vars_in_func RIGHT_PARENTHESIS BEGIN function_body END
            | functions_declaration VOID identifier1 LEFT_PARENTHESIS vars_in_func RIGHT_PARENTHESIS BEGIN function_body END
            ;

vars_in_func:       /*empty*/
            | constant identifier1
            | vars_in_func COMMA constant identifier1
            ;

function_body:      /*empty*/
            | variables_declaration identifier1
            | identifier1
            ;
%%

int main ()
{
  if ( yyparse() == 0 && error==0){
     printf("Accepted\n");
   }
  else{
     printf("Rejected\n");
   }
}

I am now working first time with Bison so the code might not be good but I want to compile it so I can begin testing. But how can I fix this error?
Notice: I can simple do that:
main_struct:variables_declaration
            | class_declaration
            | functions_declaration
            ;

But this will be wrong because I want my program to have all 3 declarations.

A: functions_declaration has no non-recursive production, unlike variables_declaration and class_declaration which both have empty productions. Without a non-recursive production, it is impossible to derive a sentence from a non-terminal, since the derivation can never terminate.
Since no sentence can match functions_declaration, main_struct also cannot be matched, and that in turn renders all nonterminals useless.
There are two common patterns for writing repeating non-terminals, which correspond to the regular expression operators * (0 or more) and + (1 or more):
optional_repeating_element: /* EMPTY */
                          | optional_repeating_element element
                          ;

repeating_element         : element
                          | repeating_element element
                          ;

Note that these only differ in the base case. In both cases, you need to separately define a production for a single element. So in your case, you could use:
functions_declaration: function
                     | functions_declaration function
                     ;

function: constant identifier1 LEFT_PARENTHESIS vars_in_func RIGHT_PARENTHESIS
          BEGIN function_body END
        | VOID identifier1 LEFT_PARENTHESIS vars_in_func RIGHT_PARENTHESIS
          BEGIN function_body END
        ;

Three notes:
1) Don't manually number your tokens. Bison will do it for you, and the result is much more maintainable. Also, it is usually a lot more readable to use single-quoted characters for terminals which are single characters; these terminals don't need to be declared, and you can use a simple default flex rule to handle all of them (. {return *(unsigned char*)yytext;}.) So it is all around simpler, both to write and to read.
2) Your definition of vars_in_func will accept some sentences you probably don't want to accept. What you have is:
vars_in_func:       /*empty*/
            | constant identifier1
            | vars_in_func COMMA constant identifier1
            ;

Since vars_in_func can be empty (first production), the third production allows vars_in_func to start with a COMMA, so the following would be valid:
(, int foo)

To do this correctly, you need to separate the empty parameter-list case from the recursion.
3) Your use of identifier1 (which is quite a confusing name for a list of identifiers) is going to cause you problems. You allow function declarations to declare a list of names, but that is not distinguishable with finite lookahead from a variable declaration which declares a list of names. Consider the two sentences:
int variable1, variable2, variable3;

int function1, function2, function3() BEGIN END

When the parser finds the first ,, it cannot know whether what follows is a list of integer variables, or a list of functions with the same parameters and body. I'm guessing that you didn't really intend the second case to be possible, which means you shouldn't use identifier1 in functions_declaration (or class_declaration). Even in your parameter list non-terminal (vars_in_func), you have something odd, though parseable; vars_in_func is a comma-separated list of a type followed by a comma-separated list of names, so the following is legal:
void function(int a, b, int c, d)

Perhaps you intended that, but I'm not convinced.


text:
Q: Numerical Analysis - $n$-sided polygon tangential i need help with this question..I'm not so sure how to go about the arguments. Any help would be appreciated.
Consider a regular $n$-sided polygon tangential to and enclosing the unit circle to approximate $π$.
(a) Use geometrical arguments to show that the half-perimeter of the polygon $C_n = n \tan(\frac πn) ≥ π$.
(b) Calculate $C_4$ and $C_8$, not approximating irrationals by decimals.
(c) Use Richardson extrapolation with $h = \frac 1{n^2}$
to improve upon your results.

A: This is hard to write in text, since it's a very visual problem - if you have trouble following along, I suggest you grab a piece of paper and draw a picture of what I'm trying to describe. If there's a specific point you get stuck, I'll be happy to try and help.
The key fact about the circle is that every point on its perimeter is equally far from it's centre. We can use that fact to try and prove the formula. In particular, to find the side length of one of the sides of our polygon, we can construct a triangle where one of the corners is at the centre of the circle, and another is at a point where the polygon is tangent to the circle. Since this is a unit circle, the side length will have a length of 1.
The second thing we'll need is to realise the triangle we're constructing is right angled. This is because the side leading from the centre of the circle to it's edge is perpendicular to the tangent line of a circle.
Finally, we can think of the angle size of the point at the centre of the circle. The triangle we've constructed covers half of one side of our n-sided polygon, and there's nothing special about the half-side we constructed that distinguishes it from any other half-side. Therefore, each side of our polygon would take up an angle of 2π/n with respect to the centre of our circle, and a half side is half that - π/n.
So, we have a right-angled triangle, where one side is from the (and has a length of one). We also know the angle between the two sides. From there, we can calculate the length of the half side as tan(π/n). This is because the Opposite side of the triangle is the length we want to find, and the adjacent side has a length of one as the radius of our circle.
As there are 2n half-sides, the total length will be 2n tan(π/n). We want the half side, leading to the equation being n tan(π/n).


text:
Q: Laravel 5.1 - Built in password reset functionality not sending email with token OVERVIEW:
I'm creating a password reset functionality using the built in system in Laravel 5.1, I have followed the instructions exactly how it says here.
The view in resources/views/emails/password.blade.php receives a variable $token which contains the password reset token to match the user to the password reset request. Within the view, I have the following code which is supposed to create a URL link of the page where the user set the new password:
   Click here to reset your password: {{ url('password/reset/'.$token) }}

PROBLEM:
It does not send the email at all. But I have realized that, if I remove the last trailing slash (see below):
   Click here to reset your password: {{ url('password/reset'.$token) }}

I receive something like http://mywebsite.com/password/reset35df435dfgdfg...
CONCLUSION:
Whenever there is a trailing slash between password/reset/ and the $token, the email is not sent. Even when I manually type the URL.
Why would the / before the $token affect on the email being sent? Any ideas?
ATTEMPTED SOLUTIONS:
 url('password/reset', [$token]); //DID NOT WORK

 action('Auth\PasswordController@getEmail', ['token' => $token]);  //DID NOT WORK

 route('password/email', ['token' => $token]); //DID NOT WORK

 url('password/reset/'.$token); //DID NOT WORK

A: Try like this
url helper function second parameter is parameter array to pass with the url. Instead of append parameters to end of the url.., you can use like bellow.
url('password/reset', [$token]);

A: I found a solution! This is not usual, but if you add a backward trailing slash, it will keep the forward slash and it won't have a problem with the token.
url('password/reset\/', [$token]);
Thanks & Good luck!


text:
Q: Returning stringbuilder object What should be returned in this code? I am just working with StringBuilders and I don't know how I can return StringBuilder objects.
public String toProtocolString() {
    StringBuilder sb = new StringBuilder();
    sb.append(Integer.toString(points.length)).append(' ');
    sb.append(Integer.toString(points[0].length)).append(' ');
    for (int[] x : points)
        for (int y : x)
            sb.append(Integer.toString(y)).append(' ');
    //remove extra space at end
    sb.deleteCharAt(sb.length()-1);
    return ??????;

A: If you need to return a String, as the signature of your method suggests, you should
return sb.toString();

Otherwise, change the return type to StringBuilder and
return sb;

A: Return string value of stringbuilder using toString() method. More about it is in doc
return sb.toString();

A: To return a StringBuilder object you need to change the return type of your function signature from String to StringBuilder. But in most of the cases you don't want to do that because you will need another instance of StringBuilder in the callee method. So an elegant solution is that you return a variable of type String
In order to return a variable of type string just do this
return sb.toString();


text:
Q: if you were asked to answer to the question " what is the difference between the English language and a programming language" how you will respond? Basically in both cases you have:

*

*a well defined vocabulary

*a syntax to respect

*they both can express a business logic

*they can define semantics

I don't think that will be fair to say "A programming language is only useful for a PC" or something like that.
I just can't find a real answer, but we can feel the difference, it's strange.

A: Here's a biggie:
Mason has already said this, but:  Formal languages have formally defined semantics.  Human languages don't.  It's not still really well understood how humans extract semantics despite the fact that this has been studied for decades by linguists, philosophers and psychologists.
I think it's pretty obvious that formal languages lack the semantic richness of even simple natural language.  "The cat jumped over the lazy dog" encodes and is dependent on far more information about the world than just the definitions of the words and the syntax alone.  Formal languages lack the syntactic and semantic ambiguity that is possible with natural language as well.

A: When I was a prof 30 years ago there would be these Faculty Colloquia or off-site weekends where some profs from around the university would get invited, with deans, for fancy food and "collegial" discussions.
Read: b o r i n g.
Once the question was raised: Should a computer language be allowed as a substitute for the foreign language requirement?
This drove me nuts.
To think that learning BASIC or PASCAL (at the time) was even on the chart, compared to learning French, German, or another human language and culture, seemed preposterous.
Technology is beautiful. It has a depth of meaning that can't really be imagined outside of it.
At the same time, it is easy just to think of it as a means to an end - a way to engineer our mechanical slaves.
What is there in programming that can compare to a poem, or a novel?
When you learn a human language, it is not just a vocabulary, syntax, etc.
It is a window on history, culture, beauty, what makes life interesting.

A: "A programming language is only useful for a PC" isn't fair you're right.
Fair way to state the difference would be
A programming language is also useful for a PC
The point is, programming language (just like English) is primarily intended to be read / communicated by humans, but unlike English, it has a cumbersome limitation that it has to allow for machine execution.

...Writing code certainly feels very similar to writing poetry. When I'm writing poetry, it feels like the center of my thinking is in a particular place, and when I'm writing code the center of my thinking feels in the same kind of place. It's the same kind of concentration. So, I'm thinking up possibilities, I'm thinking about, well, so how do I reinvent the code, gee, you know, what's the simplest way to do this.
I'm thinking about things like simplicity -- how easy is it going to be for someone to look at it later? How well is it fulfilling the overall design that I have in mind? How well does it fit into the architecture? If I were writing a very long poem with many parts, I would be thinking, "Okay, how does this piece fit in with the other pieces? How is it part of the bigger picture?" When coding, I'm doing similar things, and if you look at the source code of extremely talented programmers, there's beauty in it. There's a lot of attention to compression, using the underlying programming language in a way that's easy to penetrate. Yes, writing code and writing poetry are similar...
         (Richard Gabriel, Janice J. Heiss, The Poetry of Programming)
...Instead of imagining that our main task is to instruct a computer what to do, let us concentrate rather on explaining to human beings what we want a computer to do.
The practitioner of literate programming can be regarded as an essayist, whose main concern is with exposition and excellence of style. Such an author, with thesaurus in hand, chooses the names of variables carefully and explains what each variable means. He or she strives for a program that is comprehensible because its concepts have been introduced in an order that is best for human understanding...
         (Donald E. Knuth, Literate Programming)

A: Ask a strange question and you get a strange answer :) Here are some differences (INMO)!
 - Add to the list the fact that recursion is meaningful to computers only and not to humans.

A: The essential distinction, I would say, is formally-defined syntax and semantics.
A programming language can be parsed by an automated tool according to formal rules, and found to either have meaning according to those rules, or be invalid and therefore worthless.  And if it does have meaning, it means exactly what the formal rules say it means and nothing else.
A human language, on the other hand, is not understood formally but intuitively.  You can mutilate the grammar to a pretty high degree and the person you're talking to will still understand what you mean, and what you mean (and are understood to mean) is frequently not precisely what you said.
As a side note, this tends to make natural language extremely difficult to parse. It remains one of the great unsolved problems of artificial intelligence, despite being one of the ones they've been working on the longest!

A: Purpose of any language is communication, to make your feelings known to other side be it a person or a machine. The basic difference between English language and programming language is the way of communicating the feelings. In programming language you do it in a way you do it with a child, giving parsed information while English is much more complicated than that. You need to make your thoughts understood as per the listener, but here you have a same set of instructions for the system. This is the basic point. Coming now to structure and composition- We use English in our programming languages but is not the other way around. Also neither the structure nor the composition is necessary in English but if you miss this in programs it computer will make your life hell till you correct it according to the predefined set of rules. It is why the programmers are trying to merge English into the Programming language that Artificial Intelligence was born; so as to merge the gap between English and Programming Languages, to make layman understand the machine and machine understand the layman.

A: When you're speaking programming language you're speaking data and clear instructions.
When you're speaking English you're having 1 big negotiation over non-data which ends in ambiguous instructions and hidden meanings to data supposedly being clear.


text:
Q: How to calculate the probability of many events in series? I am trying to determine the correct method to calculate the probabilities of this problem:
Assume a piece of dust is travelling through a tube made up of 5 sections. If the particle touches a wall, it will stick and not travel further. I want to determine the probability that the particle will pass through all sections of the tube without getting stuck.
Assume I have already obtained the probabilities of the particle getting stuck in each section of the tube. What is the proper way to calculate the overall probability of the particle making it through all 5 sections without sticking?
Assume the probability of sticking is about 0.02 for each section, although it varies slightly. My initial assumption was to add all the probabilities together as they seem to me to be mutually exclusive events. Is this correct?

A: Let $P(S_{i})$ = the probability of making it through a section.
The probability of making it through all the sections, assuming that each event is an independent one, is given by
$\prod_{i=1}^{5}P(S_{i})$ = $0.98^{5} = 0.9039$ (4s.f.)
Edit:
Also note, that mutually exclusive events, are events which cannot occur simultaneously. For example, obtaining a $2$ versus obtaining a $3$ on a dice roll are mutually exclusive events. In this case, your events are independent ones. This means that the outcome of one event does not affect the outcome of another event, or more precisely:
$P(A|B) = P(A)$
where $P(A|B)$ denotes the probability of $A$ given $B$

A: Let us say, $p$ will be the probability that it will we stuck in the tube.
Probability that it'll not be stuck : $1-p$
What we want is that it passes through all of them without getting stuck.
i.e. $$\underbrace {(1-p)\times(1-p)\dots (1-p)}_{5 ~~ \text {times}}=(1-p)^5$$
Multiplication means And ; Addition means Or
You want particle to pass through section $1$ and section $2$ and section $3$ $\dots$
Therefore, here we have multiplied all the $5$ probabilities.

A: You're assumption, though close is a little bit off. You'll get a number very close when working with small probabilities, but here's the problem. Imagine 3 segments each with a 50% probability to catch the dust. There's nothing wrong with this sceneario, but just adding gives you 150%.
What you do instead is convert them to the probability of going through, then treat them like independent events. So in this case it has a 98% chance to go through so you do 0.98x0.98x0.98x0.98x0.98=0.90. It's generally easier to picture probabilities as a series of dice rolls, in this case it's one roll per tube, but what's often more helpful is to imagine rolling for each tube right at the start before it even enters to see if it would get stuck if it did reach that tube. Now it's obvious that it'll only get through if you roll in the top 98% on every tube and will get stuck at some point otherwise. This is why you can't treat them as mutually exclusive, even though it can only get stuck on 1 tube you can say that it would have been stuck according to the rolls you made at the beginning.


text:
Q: ServletOutputStream does not throw exception when client aborts Hi i have the following construct in my Tomcat-Webapp
ServletOutputStream out = response.getOutputStream();
final PrintStream p = new PrintStream(out, true, "UTF-8");
while (condition) {
    p.println(StringUtils.join(values, ","));
    logger.debug("Exported line");
}

but when i close the requesting browser, the code continues to end, even when it takes several minutes and writes several megabytes.
I would expect that the ServletOutputStream whould throw an exception when the client is disconnected and the code tries to write data into it.
the ServletOutputStream is a
org.springframework.security.web.context.SaveContextOnUpdateOrErrorResponseWrapper$SaveContextServletOutputStream[delegate=org.apache.catalina.connector.CoyoteOutputStream@7fcdb6bc]

A: ok it tourned out that PrintStream covers underlying exceptions:
public void write(byte buf[], int off, int len) {
    try {
        synchronized (this) {
            ensureOpen();
            out.write(buf, off, len);
            if (autoFlush)
                out.flush();
        }
    }
    catch (InterruptedIOException x) {
        Thread.currentThread().interrupt();
    }
    catch (IOException x) {
        trouble = true;
    }
}

so i have to check for errors manually by calling
p.checkError()


text:
Q: how to call to method A of class A from method B of class A there seems to be a lot of answers on how to call  method A of class A from class B but none on how to call to method A of class A from method B of class A. this probably easy but am new to oop in python. here is a quick illustration of what am trying to do
  class A:
      def __init__():

      def method_A(self):
          xxxxxx
          return xxx...
      def method_B(self):
          ans = method_A(self)
          return ans

am getting the following error ======> "global name method_A ' is not defined"

A: ans = self.method_A()

self is an instance of A, and methods on instances are called using instance.method().

A: Attributes need to be referenced off the object.
ans = self.method_A()

A: Members of a class are accessed as attributes of self, so you just use this:
self.method_A()

Also, you do not need to pass self as parameter explicitly, that is done implicitly. This is all covered in the Python Tutorial, which everyone should read.


text:
Q: ImportError: DLL load failed after QGIS Upgrade from 3.14.1 to 3.14.16 I have upgrade my QGIS from 3.14.1 to 3.14.16 and I get this error on startup.
Traceback (most recent call last):
  File "", line 1, in
  File "C:/OSGEO4~1/apps/qgis/./python\qgis\__init__.py", line 70, in
    from qgis.PyQt import QtCore
  File "C:/OSGEO4~1/apps/qgis/./python\qgis\PyQt\QtCore.py", line 24, in
    from PyQt5.QtCore import *
ImportError: DLL load failed: Kan opgegeven procedure niet vinden.

Python versie:
3.7.0 (v3.7.0:1bf9cc5093, Jun 27 2018, 04:59:51) [MSC v.1914 64 bit (AMD64)]

QGIS versie:
3.14.16-Pi 'Pi', a235a149f0

Python pad:
['C:/OSGEO4~1/apps/qgis/./python', 'C:/Users/joeri/AppData/Roaming/QGIS/QGIS3\\profiles\\default/python', 'C:/Users/joeri/AppData/Roaming/QGIS/QGIS3\\profiles\\default/python/plugins', 'C:/OSGEO4~1/apps/qgis/./python/plugins', 'C:\\OSGEO4~1\\apps\\Python37', 'C:\\OSGEO4~1\\apps\\Python37\\Scripts', 'C:\\OSGeo4W64\\bin\\python37.zip', 'C:\\OSGEO4~1\\apps\\Python37\\DLLs', 'C:\\OSGEO4~1\\apps\\Python37\\lib', 'C:\\OSGeo4W64\\bin', 'C:\\Users\\joeri\\AppData\\Roaming\\Python\\Python37\\site-packages', 'C:\\OSGEO4~1\\apps\\Python37\\lib\\site-packages', 'C:\\OSGEO4~1\\apps\\Python37\\lib\\site-packages\\win32', 'C:\\OSGEO4~1\\apps\\Python37\\lib\\site-packages\\win32\\lib', 'C:\\OSGEO4~1\\apps\\Python37\\lib\\site-packages\\Pythonwin']

My toolbox processing is gone, I even cannot install anymore plugins, please help I need to get a certain QGIS model back.

A: There seem to be a range of issues for some users related to startup, python errors, and Processing or other plugins, in the latest Windows versions. It's not quite the same error messages you have, but see https://github.com/qgis/QGIS/issues/38914, https://github.com/qgis/QGIS/issues/38772, https://github.com/qgis/QGIS/issues/38720, https://github.com/qgis/QGIS/issues/38476
Developers seem to be saying they're fixed, but people keep reporting variations of the error.
Depending on your appetite to get your hands dirty, I'd suggest one of:

*

*Do a clean reinstall of QGIS, making sure you get 3.14.16-2 (or higher) for qgis, qgis-common, qgis-grass-plugin-common; qgis-grass-plugin7 3.14.16-3; and rbatch 149-5 (this probably unnecessary)

*Revert back to 3.14.15 or 3.14.1 (note the special version numbering for Pi - the version increments were 3.14[.0], 3.14.1, 3.14.15, 3.14.16)

*Try out the master (qgis-dev) development version, where bug patches should be more recent.


text:
Q: I have two horizontal scroll views. How can I show one at a time and switch between them on button click? On my android app I have two horizontal scroll views that act as docks. How can I make it so that if button 1 is clicked dock 1 displays and if button 2 is clicked dock 2 displays? Since they're docks I want them to both display in the same position.
here is my code:
<HorizontalScrollView
        android:layout_width="wrap_content"
        android:layout_height="wrap_content"
        android:layout_marginTop="50dp">

        <LinearLayout
            android:layout_width="wrap_content"
            android:layout_height="wrap_content"
            android:orientation="horizontal">

            <Button
                android:layout_width="wrap_content"
                android:layout_height="wrap_content"
                android:text="Button1" />

            <Button
                android:layout_width="wrap_content"
                android:layout_height="wrap_content"
                android:text="Button2" />

            <Button
                android:layout_width="wrap_content"
                android:layout_height="wrap_content"
                android:text="Button3" />

            <Button
                android:layout_width="wrap_content"
                android:layout_height="wrap_content"
                android:text="Button4" />

            <Button
                android:layout_width="wrap_content"
                android:layout_height="wrap_content"
                android:text="Button5" />
        </LinearLayout>

    </HorizontalScrollView>

    <HorizontalScrollView
        android:layout_width="wrap_content"
        android:layout_height="wrap_content"
        android:layout_marginTop="50dp">

    <LinearLayout
        android:layout_width="wrap_content"
        android:layout_height="wrap_content"
        android:orientation="horizontal">

        <Button
            android:layout_width="wrap_content"
            android:layout_height="wrap_content"
            android:text="Button1" />

        <Button
            android:layout_width="wrap_content"
            android:layout_height="wrap_content"
            android:text="Button2" />

        <Button
            android:layout_width="wrap_content"
            android:layout_height="wrap_content"
            android:text="Button3" />

        <Button
            android:layout_width="wrap_content"
            android:layout_height="wrap_content"
            android:text="Button4" />

        <Button
            android:layout_width="wrap_content"
            android:layout_height="wrap_content"
            android:text="Button5" />
    </LinearLayout>

                <Button
                android:layout_width="wrap_content"
                android:layout_height="wrap_content"
                android:text="dockButton1" />

               <Button
                android:layout_width="wrap_content"
                android:layout_height="wrap_content"
                android:text="dockButton2" />

Button code:
dock1button.setOnClickListener(new View.OnClickListener() {

   @Override
   public void onClick(View view) {

   }
});

dock2button.setOnClickListener(new View.OnClickListener() {

   @Override
   public void onClick(View view) {

   }
});

A: Step 1:
add id in both of the HorizontalScrollView
for example: android:id="@+id/hScrollView1" and android:id="@+id/hScrollView2"
Step 2:
Put both HorizontalScrollView in a parent LinearLayout like below:
    <LinearLayout>
    <HorizontalScrollView
     android:id="@+id/hScrollView1">
    .
    .
    </HorizontalScrollView>
    <HorizontalScrollView
     android:id="@+id/hScrollView2">
    .
    .
    </HorizontalScrollView>
    </LinearLayout>

Step 3:
In your button click just toggle the visibility:
in onClick just use..
hScrlView1.setVisibility(View.GONE);
hScrlView2.setVisibility(View.VISIBLE);

and
hScrlView1.setVisibility(View.VISIBLE);
hScrlView2.setVisibility(View.GONE);

where hScrlView1 and hScrlView2 are the ScrollView you want to show.

A: put the two horizontal listviews in a relative layout and set the visibility of one of them to invisible.
<?xml version="1.0" encoding="utf-8"?>
<LinearLayout xmlns:android="http://schemas.android.com/apk/res/android"
android:layout_width="match_parent"
android:layout_height="match_parent"
android:orientation="vertical" >

<RelativeLayout
    android:layout_width="match_parent"
    android:layout_height="wrap_content" >

    <HorizontalScrollView
        android:layout_width="wrap_content"
        android:layout_height="wrap_content"
        android:layout_marginTop="50dp" >

        <LinearLayout
            android:layout_width="wrap_content"
            android:layout_height="wrap_content"
            android:orientation="horizontal" >

            <Button
                android:layout_width="wrap_content"
                android:layout_height="wrap_content"
                android:text="Button1" />

            <Button
                android:layout_width="wrap_content"
                android:layout_height="wrap_content"
                android:text="Button2" />

            <Button
                android:layout_width="wrap_content"
                android:layout_height="wrap_content"
                android:text="Button3" />

            <Button
                android:layout_width="wrap_content"
                android:layout_height="wrap_content"
                android:text="Button4" />

            <Button
                android:layout_width="wrap_content"
                android:layout_height="wrap_content"
                android:text="Button5" />
        </LinearLayout>
    </HorizontalScrollView>

    <HorizontalScrollView
        android:layout_width="wrap_content"
        android:layout_height="wrap_content"
        android:layout_marginTop="50dp"
        android:visibility="invisible" >

        <LinearLayout
            android:layout_width="wrap_content"
            android:layout_height="wrap_content"
            android:orientation="horizontal" >

            <Button
                android:layout_width="wrap_content"
                android:layout_height="wrap_content"
                android:text="Button1" />

            <Button
                android:layout_width="wrap_content"
                android:layout_height="wrap_content"
                android:text="Button2" />

            <Button
                android:layout_width="wrap_content"
                android:layout_height="wrap_content"
                android:text="Button3" />

            <Button
                android:layout_width="wrap_content"
                android:layout_height="wrap_content"
                android:text="Button4" />

            <Button
                android:layout_width="wrap_content"
                android:layout_height="wrap_content"
                android:text="Button5" />
        </LinearLayout>
    </HorizontalScrollView>

</RelativeLayout>

        <Button
        android:layout_width="wrap_content"
        android:layout_height="wrap_content"
        android:text="dockButton1" />

    <Button
        android:layout_width="wrap_content"
        android:layout_height="wrap_content"
        android:text="dockButton2" />

then change the visibility in buttons' codes:
Button code:
dock1button.setOnClickListener(new View.OnClickListener() {

  @Override
  public void onClick(View view) {
     horizontalList2.setVisibilty(View.INVISIBLE);
     horizontalList1.setVisibilty(View.VISIBLE);
  }
});

dock2button.setOnClickListener(new View.OnClickListener() {
 @Override
 public void onClick(View view) {
    horizontalList1.setVisibilty(View.INVISIBLE);
    horizontalList2.setVisibilty(View.VISIBLE);
 }
 });

A: You'd be better off by just using FrameLayout containing both scrollviews. It would be more performant than using LinearLayout or even worse RelativeLayout.
Just do something like this (schematic code, some xml attrs omitted)
<FrameLayout>
  <HorizontalScrollView
    android:id="@+id/view1"/>

  <HorizontalScrollView
    android:id="@+id/view2"
    android:visibility="gone"
  />
</FrameLayout>

And then in your onClick handler(s) do something like
view1.setVisibility(View.VISIBLE)
view2.setVisibility(View.GONE)

or vice versa (depending on button pressed)


text:
Q: Displaying a div at a certain time resetting when the month changes I have a div/tab set to display after the 1st of Feb of this year.  This works great until the month ends and the div is then hidden again.  I want the div to remain open forever.  The first tab is set to display on the Feb 1st, the second is set to display on the 14th. Here is my code.

Tab 1

Tab 2

Tab 3

    <

A: Instead of checking for the year, the month and the current date via logical AND, just check if the current date is bigger than a specific timestamp (2020-02-01:00:00:00 in your case):
var date = new Date();
var refd = new Date(2020,1,1,0,0,0); // <-- Reference date

// compare if now (date) is bigger than reference (refd)
// by comparing the milliseconds since 1970-01-01
if (Number(date) >= Number(refd)) // <-- compare
{
    // ... elided, as before
}

A:

<form onLoad="displayDiv()" method="GET">

</form>


text:
Q: Creating a List of Dicts where the value is a list let me start off by saying, its possible I am attempting to use a terrible data structure.
Im trying to get information out of a large text dump and cant seem to get it sorted right.  Data looks like the below, but is much longer.
r1 r01
2020 77.7
2020 76.0
2020 77.7
r2 r02
2020 74.7
2020 74.0
2020 76.7
r2 r03
2020 74.2
2020 74.1
2020 76.8
r1 r04
2020 74.6
2020 75.6
2020 75.8

I thought I could end up getting it into a data structure like..
r1_list = [
    r01: [77.7,76.0,76.0,76.0],
    r04: [69.5,4,4,5],
]
r2_list = [
    r02: [1,2,3,4],
    r04: [3,4,4,5],
]

Then I could loop through the lists, and check the mean etc of the values per device.
Here is what ive been trying
import re

r1_list = []
r2_list = []

current_device = False
device_type = False
current_reading = False

def matchr1(line):
    matchThis = ""
    matched = re.match(r'^(r1)\s(r\d+)$',line)
    if matched:
        #Matches r1
        matchThis = matched.group(2)
    else:
        return False
    return matchThis

def matchr2(line):
    matchThis = ""
    matched = re.match(r'^(r2)\s(r\d+)$',line)
    if matched:
        #Matches r2
        matchThis = matched.group(2)
    else:
        return False
    return matchThis

def matchReading(line):
    matchThis = ""
    matched = re.match(r'^(\d+)\s(\d+.\d+)$',line)
    if matched:
        #Matches r2
        matchThis = matched.group(2)
    else:
       return False
    return matchThis

with open("data.txt") as f:
    for line in f:
        if matchr1(line):
            current_device = matchr1(line)
            device_type = "r1"

        if matchr2(line):
            current_device = matchr2(line)
            device_type = "r2"

        if matchReading(line):
            current_reading = matchReading(line)

        if current_reading:

            if device_type == "r1":
                temp_dict = {current_device: [current_reading]}
                r1_list.append(temp_dict)

            if device_type == "r2":
                temp_dict = {current_device: [current_reading]}
                r2_list.append(temp_dict)

        current_reading = False

print(r1_list)
print(r2_list)

What I get
[{'r01': ['77.7']}, {'r01': ['76.0']}, {'r01': ['77.7']}, {'r04': ['74.6']}, {'r04': ['75.6']}, {'r04': ['75.8']}]
[{'r02': ['74.7']}, {'r02': ['74.0']}, {'r02': ['76.7']}, {'r03': ['74.2']}, {'r03': ['74.1']}, {'r03': ['76.8']}]

A: There are two separate steps here:

*

*Looking at rows starting with "r" and finding there their data should be inserted.

*Looking at other rows and inserting them into the data structure.

Here's what I came up with:
#!/usr/bin/env python

data = """r1 r01
2020 77.7
2020 76.0
2020 77.7
r2 r02
2020 74.7
2020 74.0
2020 76.7
r2 r03
2020 74.2
2020 74.1
2020 76.8
r1 r04
2020 74.6
2020 75.6
2020 75.8"""

result = {}

for line in data.splitlines():
    if line.startswith("r"):
        # Find (or create) the place in the data structure where
        # we should insert the values.
        first, second = line.split()
        # dict.setdefault(key, value) sets `dict[key] = value` if
        # it's not already set, then returns `dict[key]`.
        dest = result.setdefault(first, {}).setdefault(second, [])
        # Move on to the next line.
        continue
    # Get the value of the line
    _, value = line.split()
    # Add it to the list we found in the `line.startswith('r')`
    # bit above.
    dest.append(value)

assert result == {
    "r1": {
        "r01": ["77.7", "76.0", "77.7"],
        "r04": ["74.6", "75.6", "75.8"]
    },
    "r2": {
        "r02": ["74.7", "74.0", "76.7"],
        "r03": ["74.2", "74.1", "76.8"]
    },
}


text:
Q: Chrome (and possibly other browsers) caching my script include PROBLEM:
I am hosting a widget on a client's website that will be different for each page on the site.
To render the widget, the client includes a script tag on their pages. This script tag is loaded for every page on the site and the code that it returns depends on the page.
So, if this script gets cached, the end result is that we serve a widget for the wrong page.
Right now, when we serve the script, we set in the response headers

Cache-Control: max-age=0
Expires : 24 hours in the past

yet sometimes browsers still cache the script.
QUESTION:
Is there a way to use http headers to stop caching in all cases or are we going to have to take a completely different approach?
UPDATE:
The headers that topek recommended greatly improved the non-cacheability of the scripts. However, (again in Chrome who seems to be the most cache-aggressive) when using the back, forward, or reload buttons the script is still cached. If you actually CLICK on anything it will be fetched from the server.
It seems that the only foolproof way to stop caching will be to set script sources that are guaranteed to be different for each page load (as suggested by esilija and tejs).

A: Those two headers should do the trick:
response.setHeader("Cache-Control", "no-cache, must-revalidate");
response.setHeader("Expires", "Sat, 26 Jul 1997 05:00:00 GMT");

or you set name according to the current page, e.g. when the user requests the page http://domain/posts/1 then the script name could be http://domain/script/scriptname/posts/1. With approach the script would still be cachable per page.
Do not append a query string on the script like script.js?random_string. Proxies don't play well with this approach. If you want to place a random string in the name, then put it before .js like this script-0934234234.js and rewrite the request on your server.


text:
Q: Pass a file reference as a parameter to a inserted step from another repo in a Azure YAML deployment I have a repository of yaml based jobs that I'd like to reuse in a number of yaml script. The script that will use the jobs however are in other repository.
The reusable job takes a file path as an input parameter. And for some reason the file can't be found when the imported job executes by the pipeline.
How do I reference the file in the parameter from the main job so it can be found when executing the imported job?
# MyMainScriptTemplate.yml that will be executed by the pipeline

trigger:
  - master

resources:
  repositories:
    - repository: AzureTemplates
    type: git
    name: AzureTemplates

jobs:
  - template: /FunctionApp/DeployFunctionApp.yml@AzureTemplates
  parameters:
    file: /Azure/Functions/template.json #This can be found when executing ...

# ReusableJobTemplate.yml defines a job that should be referenced from the main script

parameters:
  - name: file
  type: string

jobs:
  - job: DeployFunctionApp
  steps:
    - task: AzureResourceManagerTemplateDeployment@3
    inputs:
      deploymentScope: "Resource Group"
      azureResourceManagerConnection: "Dev"
      subscriptionId: "XYZ"
      action: "Create Or Update Resource Group"
      resourceGroupName: "XYZ"
      location: "West Europe"
      templateLocation: "Linked artifact"
      csmFile: ${{ parameters.file }}
      deploymentMode: "Incremental"
    displayName: "Run a one-line script"

A: Please check how mulirepo behaves.
I would recommend you two steps:

*

*add - checkout: AzureTemplates step before calling template

*and change path from /Azure/Functions/template.json to (Agent.BuildDirectory)/AzureTemplates/Azure/Functions/template.json


text:
Q: Log4PHP only logging last method call I'm a relatively new PHP programmer, my background is in Java. My question involves attempting to log function call entry and exits using Log4PHP. I am following a loose MVC pattern where I have PHP pages that render the view, PHP scripts to act as controller and PHP classes representing the model.
This is what is happening: I have a form that submits to the PHP controller, which then instantiates a PHP class. The newly created object does an insert into MySQL, returning the new auto-increment ID. Control then passes back to the controller, which forwards to a different PHP view, using header->location. Finally, the new PHP view does a select on the newly created ID.
The problem is that during this execution process, ONLY the lookup is being logged by Log4PHP; the INSERT is not. Here are some snippets:
<appender name="myConsoleAppender" class="LoggerAppenderConsole" />
<appender name="myLoggerAppenderDailyFile" class="LoggerAppenderDailyFile">
 <layout class="LoggerLayoutPattern">
       <param name="conversionPattern" value="%d{Y-m-d H:i:s} [%p] %c: %m (at %F line %L)%n" />
   </layout>
   <param name="file" value="file-%s.log" />
   <param name="datePattern" value="Y-m-d" />
</appender>
<logger name="merchant">
<appender_ref ref="myLoggerAppenderDailyFile" />
</logger>
<root>
<level value="DEBUG" />
<appender_ref ref="myConsoleAppender" />
</root>
</configuration>

The constructor:
public function __construct() {
.
.
Logger::configure('config.xml');
$this->log = Logger::getLogger(__CLASS__);
}

The two methods:
public function insertMerchant() {
$this->log->debug("Inserting new Merchant");
.
.
$this->log->debug("Merchant Inserted; ID = $merchantId");
}

public function findMerchantByUserId($userId) {
$this->log->debug("Finding Merchant with userId = $userId");
.
.
$this->log->debug("Merchant found with userId = $userId");
}

As I mentioned, ONLY the LAST call to findMerchantByUserId($userid) is being logged to file. The insert is never logged,
Thanks in advance for any help.


text:
Q: How can I write database Django database model instances during startup of the Django project? Is there a way to write the values of database model instances with initialization values during the startup phase of the Django project?
I'm not interested in migrations which require to invoke the command line prior to starting the Django project. The changes to the database shall be persistent w.r.t. the database change history.
In my case the system is in the IIoT context:

*

*An edge backend

*a MQTT broker

*potentially several end-device agents.

The operating state of the overall application consists of the operating state of the edge backend, the MQTT broker and the end devices.
The single source of truth about the opstate shall be the database.  This means only the edge backend needs to know about the opstate.
Initially after every start/restart of the Django project the operating state of all sub-components shall be unknown. One database model instance (singleton) holds the operating state of the overall distributed system via one-to-one references.

A: Why not use a fixture?
django-admin loaddata fixture [fixture ...]

or
python manage.py loaddata fixture <file>

Edit:
Ok so you make 2 points:

*

*There should be a history logged in the database.

*Signals should not be triggered.

point 1:
Since loaddata is using not the model to create the instances and save them, I don't know how it handles the history. Maybe someone else can weigh in here?
point 2:
as for signals, this is how you avoid the signals from firing when loading fixtures as explained in the official django documentation:

When fixture files are processed, the data is saved to the database as
  is. Model defined save() methods are not called, and any pre_save or
  post_save signals will be called with raw=True since the instance only
  contains attributes that are local to the model. You may, for example,
  want to disable handlers that access related fields that aren't
  present during fixture loading and would otherwise raise an exception:

from django.db.models.signals import post_save
from .models import MyModel

def my_handler(**kwargs):
    # disable the handler during fixture loading
    if kwargs['raw']:
        return
    ...

post_save.connect(my_handler, sender=MyModel)

*

*docs


text:
Q: Why does `Symbol#match` behave differently from `String#match` and `Regexp#match`? String#match and Regexp#match return a MatchData when match succeeds:
"".match(//) # => #<MatchData "">
//.match("") # => #<MatchData "">
//.match(:"") # => #<MatchData "">

But Symbol#match returns the match position (like String#=~):
:"".match(//) # => 0

Why does Symbol#match behave differently? Is there a use case?

A: I reported it as a bug in Ruby core: https://bugs.ruby-lang.org/issues/11991. Let's see what they will say.

Update
The questioned behaviour seems to have been a bug. It seems that from Ruby 2.4, Symbol#match will return a MatchData instance when a match succeeds.


text:
Q: Why is file_get_contents() faster than using fsock_open()? In PHP, sometimes I want to send an HTTP request to a remote site just to look at the response headers, so I declare it all manually and use the fsock_open() function.  However, this goes much slower than calling file_get_contents() with a remote URL (which loads the whole page content).  Why is this?  Is there a good alternative way to get just the response headers (to check if a page returns a 404 error, for example) that works as fast as file_get_contents()?

A: Have you just tried using curl?  You can get back the headers and also the content, if desired.
$ch = curl_init();

curl_setopt($ch, CURLOPT_URL, $url);

curl_setopt($ch, CURLOPT_RETURNTRANSFER, true);
curl_setopt($ch, CURLOPT_FOLLOWLOCATION, true);
curl_setopt($ch, CURLOPT_MAXREDIRS, 10);

$useragent = "Mozilla/5.0 (Windows; U; Windows NT 5.1; en-US; rv:1.9.0.5) Gecko/
2008120122 Firefox/3.0.5";
curl_setopt($ch, CURLOPT_USERAGENT, $useragent);

$output = curl_exec($ch);
$info = curl_getinfo($ch);

This will chase redirects, which isn't always desired.
Look at http://php.net/manual/en/function.curl-getinfo.php to see what you get back in $info.
You can try just doing a HEAD request instead of a GET (the CURLOPT_NOBODY option), but I have run into problems with some servers that deny HEADs for some reason.


text:
Q: BLAST database error: no alias or index file found for nucleotide database [swissprot] in search path I am following this link: http://www.ncbi.nlm.nih.gov/books/NBK52637/
I install NCBI BLAST+ package. Then create db folder inside blast-2.2.31+ folder to download one of NCBI databases. I select swissprot database and download it in the db folder. After that, I run:
perl update_blastdb.pl --passive swissprot
and it connect to NCBI successfully and download swissport in the bin folder. So, now I have two swissprot.tar.gz. One I download it in db folder and one downloaded in bin folder after running perl cammand.
Then I set PATH and BLASTDB environment variables. BLASTDB will contain which swissport database? the one in db or in bin?
The main issue appears when I type:
blastdbcmd -db swissprot -info
BLAST database error: no alias or index file found for nucleotide database [swissprot] in search path.....
What does this means?
I follow the link step by step.
Any hints?
Thank you and regards,,,
Alaa


text:
Q: closed form expression for the summation $\sum_{i=0}^{\infty}\binom{i+k}{i}x^ii^t$ I'm trying to find a closed form expression for this summation.
$\sum_{i=0}^{\infty}\binom{i+k}{i}x^ii^t$
Where k and t are given nonnegative integers. According to ( Checking Jaynes' formula 6.108 for $\sum\limits_{m=0}^\infty{m+a \choose m} m^nx^m$ ) the answer is
${(x\frac{d}{dx})}^t\frac{1}{{(1-x)}^{k+1}}$
And based on (What's the property of this series? Is it special? Coefficients of $\left(x\frac{d}{dx}\right)^n f(x) $) we can write
$\sum_{i=0}^{\infty}\binom{i+k}{i}x^ii^t=\left(x\frac{d}{dx}\right)^t\frac{1}{\left(1-x\right)^{k+1}}=\sum_{r=1}^{t}{S\left(t,r\right)x^r\frac{d^r}{dx^r}\frac{1}{\left(1-x\right)^{k+1}}}
=\sum_{r=1}^{t}{S\left(t,r\right)x^r\frac{\left(k+1\right)\left(k+2\right)\ldots\left(k+r\right)}{\left(1-x\right)^{k+r+1}}}
=\frac{1}{\left(1-x\right)^{k+1}}\sum_{r=1}^{t}{(k+1)(k+2)...(k+r)\ S\left(t,r\right)\ {(\frac{x}{1-x})}^r}$
Where $S(t,r)$ is the Stirling number of the second kind. This can be written in two ways. But none of them seems simpler to me.
$=\frac{1}{\left(1-x\right)^{k+1}}\sum_{r=1}^{t}{\frac{(k+r)!}{k!}\ S\left(t,r\right)\ {(\frac{x}{1-x})}^r}$
Or since it includes a falling factorial ($\left(k+r\right)_{\bar{r}}$), we can write
$=\frac{1}{\left(1-x\right)^{k+1}}\sum_{r=1}^{t}{\sum_{u=0}^{r}{S\left(t,r\right)\left(\frac{x}{1-x}\right)^rs\left(r,u\right)\left(k+r\right)^u}\ }$
$=\frac{1}{\left(1-x\right)^{k+1}}\sum_{r=1}^{t}{\sum_{u=1}^{r}{S\left(t,r\right)\left(\frac{x}{1-x}\right)^rs\left(r,u\right)\left(k+r\right)^u}\ }$
$=\frac{1}{\left(1-x\right)^{k+1}}\sum_{u=1}^{t}{\sum_{r=u}^{t}{S\left(t,r\right)s\left(r,u\right)\left(\frac{x}{1-x}\right)^r\left(k+r\right)^u}\ }
$
Where $s(r,u)$ is the signed Stirling number of the first kind (Remember $\sum_{r=u}^{t}{S\left(t,r\right)s\left(r,u\right)=\delta_{tu}}$ but this one is more complicated).
The question has not been solved yet (finding a closed form expression for this summation.
$\sum_{i=0}^{\infty}\binom{i+k}{i}x^ii^t$). Can you help me?
(I wrote what I've tried since it may inspire you).


text:
Q: Sci-Fi movie with attacking trees and vines (Asian) - YouTube scene I recently found a small scene on YouTube in which a group of soldiers is attacked by plants/vines/tentacles. Looks like an interesting fantasy/sci-fi horror movie.
Here is the scene:

Does anybody know the title of that movie?

A: It is Chong Qi Zhi She Gu Fo Tui (重启之蛇骨佛蜕) or Reunion: Escape from the Monstrous Snake (2021).
From the Grave Robbers Chronicles Wiki:

In order to rescue his former comrades, Hei Yan Jing goes deep into Cambodia's dense forests and fights against strange insects and hidden things in an underground palace to solve the mystery of his missing comrades.

A: This film is part of "The Lost Tomb" or "The Grave Robber Chronicles" (DaoMu Biji), a chinese TV franchise series with 8 parts and 5 films to the moment. Is a tomb raiders adventure series based in the books written by Xu Lei.
The guy in black glasses is Hai Yan Ning or Xie Xiazi (Black Blindman), interpreted by Ji Chen, the same actor and character in Tomb of the Sea (Sha Hai, 2018 TV Series).
Xie Xiazi is a blind guy, but he have the hability of see clearly only in the dark, then, always had sunglasses.


text:
Q: Definition of a Factorial Now I have always been rather intrigued with factorial, at first, in high school, teachers told me that factorials are only defined for whole numbers. As I studied, I found factorials for positive reals and negative fractions. But the integral with which we define factorial falls flat on the negative integers.
why is that we can find the factorial of (-1/2) and root(3) but not for -1 or -2? Does this go against the definition of a factorial? If yes, what IS the definition of a factorial because children are never taught it and it clouds their reasoning and perception of the topic.

A: Children are only taught the factorial of naturals because the definition is elementary (though $0!=1$ deserves special comments).
When you want to extend it to reals, a natural way is with the integral
$$I_n=\int_0^\infty x^ne^{-x}dx$$ as it verifies the recurrence
$$I_n=\int_0^\infty x^ne^{-x}dx=-\left. x^ne^{-x}\right|_0^\infty+n\int_0^\infty x^{n-1}e^{-x}dx=nI_{n-1}$$ and $I_n=n!$.
As the integral keeps a meaning with $n$ positive real, this is taken for the extension.
Now for the negatives, it makes sense to retain the recurrence
$$(n-1)!=\frac{n!}n,$$ resulting in infinite values for the negative integers.

A: The recursive definition of the factorial $(n+1)! = n! \cdot (n+1)$ can be rearranged to deduce $$n! = \dfrac{(n+1)!}{n+1}$$
This is one way to work out that $0!=1$, taking $n=0$ in the above. However, if we try and do this for $(-1)!$, we get a problem: $$(-1)! = \dfrac{(-1+1)!}{-1+1} = \dfrac{0!}{0} = \dfrac{1}{0}$$
But we can't divide by $0$, so we can't define $(-1)!$.
As noted in the comments, the gamma function $\Gamma$ is the "right" way to extend the factorial to non-integers. $\Gamma$ diverges at the negative integers, since it is required to satisfy $\Gamma(n+1) = \Gamma(n) \cdot (n+1)$, so the same argument as above applies.


text:
Q: google api call to big query wont give refresh token using c# I have read and read and played with this code inside out and I still cant work out how to get the refresh token. This in c#
I have tried different combo of access_type, prompt and approval_prompt params.
I keep revoking access by my user to the app, so when the auth code is being requested it does ask for myself to approve the app to be able to access.
I just want to get the refresh token so i can store it and keep refreshing.
here is the code below. I have removed the parts to get the auth code, but if it is needed i can add in. I wonder if anyone can simply spot something simply wrong.
        string GetJsonFromAPICall(string p_url,string p_post_data, string p_b64_id_secret)
            {
                //string C_TOKEN_URL = "https://oauth2.googleapis.com/token";
                string l_auth_string = "Basic " + p_b64_id_secret;

                print("p_post_data = ", p_url + "?"+p_post_data);
                print("Authorization", l_auth_string);
                HttpWebRequest request = WebRequest.Create(p_url) as HttpWebRequest;

                string postData = p_post_data;// "grant_type=authorization_code&code=" + p_auth_code + "&redirect_uri=" + p_redirect_url;
                request.Headers.Add("Authorization", l_auth_string);

                var data = Encoding.ASCII.GetBytes(postData);

                request.Method = "POST";
                request.ContentType = "application/x-www-form-urlencoded";
                request.ContentLength = data.Length;

                print("pos 20 in GetJsonFromAPICall");
                print("length ", data.Length.ToString());

                using (var stream = request.GetRequestStream())
                {
                    stream.Write(data, 0, data.Length);
                }
                var response = (HttpWebResponse)request.GetResponse();
                var responseString = new StreamReader(response.GetResponseStream()).ReadToEnd();

                return responseString;
            }

string getAccessToken(string p_b64_id_secret, string p_auth_code, string p_redirect_url)
                {
                    //string l_url = "client_id="+ p_C_GBQ_ONLINE_APP_APP_CLIENT_ID + "&client_secret="+ p_C_GBQ_ONLINE_APP_APP_CLIENT_SECRET + "access_type=offline&prompt=consent&grant_type=authorization_code&code=" + p_auth_code + "&redirect_uri=" + p_redirect_url;
                    string l_params = "grant_type=authorization_code&code=" + p_auth_code + "&redirect_uri=" + p_redirect_url;
                    l_params += "&access_type=offline";
                    l_params += "&prompt=consent";
                    l_params += "&approval_prompt=force";

                    //return GetJsonFromAPICall("https://oauth2.googleapis.com/token", l_params, p_b64_id_secret);
                    return GetJsonFromAPICall("https://www.googleapis.com/oauth2/v4/token", l_params, p_b64_id_secret);

                }

    var credentials = string.Format("{0}:{1}", C_GBQ_ONLINE_APP_APP_CLIENT_ID, C_GBQ_ONLINE_APP_APP_CLIENT_SECRET_ID);
    var b64_id_secret = Convert.ToBase64String(Encoding.UTF8.GetBytes(credentials));

    string l_auth_code = "xxxxx"; // worked out successfully earlier

    l_json_returned = getAccessToken(p_b64_id_secret, l_auth_code, C_GBQ_ONLINE_APP_REDIRECT_URL);

the returned json is
l_json_returned = : {
  "access_token": "FFFFFFFF",
  "expires_in": 3569,
  "scope": "https://www.googleapis.com/auth/cloud-platform.read-only https://www.googleapis.com/auth/bigquery",
  "token_type": "Bearer"
}


text:
Q: Required request part When I add a picture to my table, an error occurs:

Message Required request part 'picture' is not present
Description The server cannot or will not process the request due to
  something that is perceived to be a client error (e.g., malformed
  request syntax, invalid request message framing, or deceptive request
  routing).

Nothing is loaded into the database.
My controller:
@Controller
@RequestMapping("/general")
public class OrderController {
    private OrderService orderService;
    private Dao dao;

    public OrderController(OrderService orderService) {
        this.orderService = orderService;
    }

    @Autowired
    public void setOrderService(OrderService orderService) {
        this.orderService = orderService;
    }

    public OrderController() {

    }

    @GetMapping(value = "/list")
    public String get(Model theModel) {

        theModel.addAttribute("orders", orderService.getOrders());

        return "index";
    }

    @GetMapping(value = "/showFormForAdd")
    public String add(Model theModel) {
        Orders orders = new Orders();

        theModel.addAttribute("order", orders);

        return "create-orders";
    }

    @PostMapping(value = "/saveOrders")
    public String addOrders(@ModelAttribute("order") Orders orders, @RequestParam("picture") MultipartFile file) throws IOException {
        orders = orderService.uploadOrders(orders, file);
        orderService.add(orders);

        return "redirect:/general/list";
    }
}

Dao:
@Repository
public interface Dao {
    List<Orders> getAllOrders();

    void addAll(Orders orders);
}

OrderDaoImpl:
@Repository
public class OrderDaoImpl implements Dao {

    private SessionFactory orderDao = OrderDao.getSessionFactory();

    public OrderDaoImpl() {
    }

    @Autowired
    public void setOrderDao(SessionFactory orderDao) {
        this.orderDao = orderDao;
    }

    @Override
    @Transactional
    public List<Orders> getAllOrders() {
        Session session = orderDao.openSession();

        try {
            session.beginTransaction();

            Query<Orders> query = session.createQuery("from Orders", Orders.class);

            return query.getResultList();
        } finally {
            session.getTransaction().commit();
            session.close();
        }
    }

    @Override
    @Transactional
    public void addAll(Orders orders) {
        Session session = orderDao.openSession();

        try {
            session.beginTransaction();
            session.save(orders);
        } finally {
            session.getTransaction().commit();
            session.close();
        }
    }
}

create-orders.jsp:

    <title>Car Shop</title>
    <link rel="stylesheet" href="https://maxcdn.bootstrapcdn.com/bootstrap/4.0.0/css/bootstrap.min.css">

<form:form action="${pageContext.request.contextPath}/general/saveOrders" enctype="multipart/form-data"
           modelAttribute="order" method="post">

Создание объявления

                        Description:

                            <input id="description" name="description"/>

                        Price:

                            <input id="price" name="price"/>

                        Body:

                            <input id="body" name="body"/>

                        Brand:

                            <input id="brand" name="brand"/>

                        Engine:

                            <input id="engine" name="engine"/>

                        Model:

                            <input id="model" name="model"/>

                        Sold:

                            <input id="sold" type="checkbox" name="sold">

                        Image

                            <input id="pic" name="picture" type="file" class="file">

                            <button type="submit" class="btn btn-default" name="saveOrders">Сохранить</button>

                        Back to Orders list

        </form:form>


text:
Q: Flutter: Running "flutter pub get" nothing happens I'm trying to get packages, when I run flutter pub get it says a color red text I don't know what this means ! analyzer 0.38.4 and just terminated the process.
C:\Mobi\del_cus_app>flutter pub get
! analyzer 0.38.4
Running "flutter pub get" in del_cus_app...                         1.7s

C:\Mobi\del_cus_app>

I also already upgrade the flutter version

A: Hello BGTabulation BGTabulate, When you trying to get package then sometime our dependency is override on another package so when this kind of issue occurs then may be you have to do like
dependencies:
  intl: ^0.15.0

dependency_overrides:
   intl: ^0.16.0

A: Note the space character of the entered values.
dependencies:
  flutter_native_splash: ^0.1.9

A: Delete pubspec.lock file and run flutter pub get

A: try to using
                 flutter clean   command
then close IDE and restart it again,
it happens sometimes when dart analyzer crashes.


text:
Q: DSE Cassandra 4.8.4 not a valid port number I have a four node cluster and am trying to get node 1 up and running.
Version of Cassandra: DSE Cassandra 4.8.4
The syntax that I am using to log into cqlsh is:
cqlsh -u cassandra -pw cassandra 10.30.30.243 9160

And the output that I am receiving is as follows:

Usage: cqlsh [options] [host [port]]
cqlsh: error: '10.30.30.243' is not a valid port number.

A: You want just -p for the password its picking up the cassandra as the host then using the host as the port.
Try
cqlsh -u cassandra -p cassandra 10.30.30.243

You shouldn't need the port since thats the default port.

A: I think I have spent way to much time dis-assembling object code. It is really a treat to have source code. Here is what I did in bin/cqlsh.py, near line 2350 I added:
import pdb; pdb.set_trace()

Just before lines:
hostname = environment.get('CQLSH_HOST', hostname)
port = environment.get('CQLSH_PORT', port)

Keep in mind indentation is important to Python, it seems, if you get errors.
Debug using commands 'p hostname' and 'p port', use 'n' to step forward.
You can read the code, there are just a few lines to here:
    (Pdb) n
> /usr/local/c4/cassandra/bin/cqlsh.py(2368)read_options()
-> if optvalues.color in (True, False):
(Pdb) p port
'192.168.1.3:9042'

You can see "port" has become the IP address and the port, step on down to the try
and step through it:
    -> try: (Pdb) n
> /usr/local/c4/cassandra/bin/cqlsh.py(2383)read_options()
-> port = int(port) (Pdb) p port '192.168.1.3:9042' (Pdb) n ValueError: "invalid literal for int() with base 10: '192.168.1.3:9042'"
> /usr/local/c4/cassandra/bin/cqlsh.py(2383)read_options()
-> port = int(port)

So there you have it:
    > /usr/local/c4/cassandra/bin/cqlsh.py(2384)read_options()
-> except ValueError:
(Pdb) n
> /usr/local/c4/cassandra/bin/cqlsh.py(2385)read_options()
-> parser.error('%r is not a valid port number.' % port)
(Pdb) n
Usage: cqlsh.py [options] [host [port]]

cqlsh.py: error: '192.168.1.3:9042' is not a valid port number.
SystemExit: 2
> /usr/local/c4/cassandra/bin/cqlsh.py(2385)read_options()
-> parser.error('%r is not a valid port number.' % port)

I ran it with
bin/cqlsh -u cassandra -pw cassandra 192.168.1.3 9042

p len(arguments) 3
p arguments[0] 'cassandra'
p arguments[1]  '192.168.1.3'
p arguments[2] '9042'

> /usr/local/c4/cassandra/bin/cqlsh.py(2386)read_options()
-> parser.error('%r is not a valid port number.' % port)
(Pdb) p port
'192.168.1.3

I took a look at how parsing works in Python, the cqlsh.py parsing routine is expecting:
parser.add_option("-p", "--password", help="Authenticate using password.")

bin/cqlsh -u cassandra -p cassandra 192.168.1.3 9042
Now the parser is plenty happy
--Return--
> /usr/local/c4/cassandra/bin/cqlsh.py(2386)read_options()->(<Values at 0x...owser': None}>, '192.168.1.3', 9042)
-> return options, hostname, port

Now to figure out what is happening to the credentials; keeping mind I am not changing the Python, I am just feeding it various input.

AuthenticationFailed(...e=0100 [Bad credentials] message="Provided
  username cassandra and/or password are incorrect

Stepping through

https://github.com/python/cpython/blob/master/Lib/optparse.py

Password is parsed correctly with -p and stored off in 'password'.
The IP address and the port are good in
/usr/lib/python2.7/optparse.py(1405)parse_args()->(<Values at 0x...owser': None}>, ['192.168.1.3', '9042'])

Which brings us to naturally back to right where we left cqlsh.py
/usr/local/c4/cassandra/bin/cqlsh.py(2339)read_options()
-> hostname = option_with_default(configs.get, 'connection', 'hostname', DEFAULT_HOST)

Everything looks really good and then we hit some errors not seen before
(Pdb) p len(arguments)
2
(Pdb) p arguments
['192.168.1.3', '9042']
(Pdb) n
NoSectionError: No secti...nnection'
> /usr/local/c4/cassandra/bin/cqlsh.py(2258)option_with_default()
-> return cparser_getter(section, option)
(Pdb) n
> /usr/local/c4/cassandra/bin/cqlsh.py(2259)option_with_default()
-> except ConfigParser.Error:
(Pdb) n
> /usr/local/c4/cassandra/bin/cqlsh.py(2260)option_with_default()
-> return default
(Pdb) p len(arguments)
2
(Pdb) p arguments
['192.168.1.3', '9042']

Yet the arguments and the count still look perfect and in fact are returned as we saw above previously. Stepping on through from here shows this section is driven three times and produces the error each time.
NoSectionError: No secti...nnection'
    > /usr/local/c4/cassandra/bin/cqlsh.py(2258)option_with_default()
    -> return cparser_getter(section, option)
    (Pdb) n
    > /usr/local/c4/cassandra/bin/cqlsh.py(2259)option_with_default()
    -> except ConfigParser.Error:

My speculation at this point; The call to ConfigParser is having an undesired effect on the user or password field which were stored away nicely earlier. I expect the problem can be tracked down but I am out of time for this effort so I will leave that up to the professionals.
For now I have gone back to

authenticator: AllowAllAuthenticator in cassandra.yaml where

bin/cqlsh 192.168.1.3 9042

drops me right in to CQLSH.


text:
Q: SSAS excessive partition scanning on 16+ members in set SSAS 2012 scans all measure group partitions, if i put a set of more than 16 members on axis.
If i put 15 or less, then only one partition is scanned.
To check this issue i created a very simple cube with Sales measure and Dates dimension.
Here is a sample query (it is dummy, so it just returns same "VAL" for each member in set on "1" axis):
with
member val as aggregate
             (
                [Dates].[Calendar].[DateId].&[20100101]:[Dates].[Calendar].[DateId].&[20100102],
                [Measures].[Amount]
             )
select
        val on 0,
        head([Dates].[Calendar].[DateId].members, 16)  on 1
from [SSDDB]

The core feature he is AGGREGATE for 2 days (in real queries you could expect to see MTD instead of static range). Axis coordinates even don't seriously affect "val" member, they are just range of some dummy values.
When i run this query with 15 as HEAD function parameter, then i have following trace in profiler:
Started reading data from the 'Sales 2010' partition.
Finished reading data from the 'Sales 2010' partition.

and following query subcube verbose:
Dimension 1 [Dates] (+ * *)  [DateId]:+  [Years]:*  [Months]:*

But if a change 15 to 16 or more, then everything changes:
Started reading data from the 'Sales 2005' partition.
Started reading data from the 'Sales 2006' partition.
Started reading data from the 'Sales 2007' partition.
Started reading data from the 'Sales 2008' partition.
Started reading data from the 'Sales 2009' partition.
Started reading data from the 'Sales 2010' partition.
Finished reading data from the 'Sales 2007' partition.
Finished reading data from the 'Sales 2006' partition.
Started reading data from the 'Sales 2011' partition.
Finished reading data from the 'Sales 2005' partition.
Finished reading data from the 'Sales 2008' partition.
Finished reading data from the 'Sales 2009' partition.
Finished reading data from the 'Sales 2010' partition.
Finished reading data from the 'Sales 2011' partition.

and now "DateId" has "all" mark in verbose:
Dimension 1 [Dates] (* * *)  [DateId]:*  [Years]:*  [Months]:*

I tried to use:

*

*Direct slice on partition: no changes

*Static set of 16+ members: no changes

*Change aggregate to sum: no changes

*Cut aggregate's set to 1 member: it works ok, but who needs such aggregate...

*Checked DATAID: all are sequental, no gaps, no overlaps

When aggregate-function is SUM - not a big deal, but DISTINCT COUNT makes all queries run 3 times longer. This is a performance killer when you click on "+" button in EXCEL, and want to see MTD (distinct-count measure) for each day in a month.
Any ideas how to stop excessive scanning?


text:
Q: emacs ocaml REPL: "Searching for program: no such file or directory, ocaml" I'm trying to set up OCaml in Ubuntu 16.04.3 on VirtualBox. I'm new to all of them; please pardon my ignorance. I installed opam using
wget https://raw.github.com/ocaml/opam/master/shell/opam_installer.sh -O - | sh -s /usr/local/bin

and added
. /home/<username>/.opam/opam-init/init.sh > /dev/null 2> /dev/null || true

to my ~/.profile file according to the instructions following the opam installation. I installed tuareg using opam install tuareg and GNU emacs 24.5.1 using sudo apt-get install emacs.
When I tried to use the ocaml REPL by typing M-x run-ocaml and return in emacs, I got OCaml REPL to run: ocaml; when I hit enter again, I got
Searching for program: no such file or directory, ocaml

I then tried M-x shell to see if I can run ocaml from shell, and I noticed that I need to use opam switch every time I want to run ocaml from the terminal/shell; if I directly type ocaml, I would get
The program 'ocaml' is currently not installed. You can install it by typing: sudo apt-get install ocaml-interp

I'm not sure whether this has anything to do with the problem I'm getting.
As a second try, I went back to emacs and typed M-x run-ocaml, hit return, and hit return again at OCaml REPL to run: (this time without the ocaml). This opened up a new buffer:

But when I tried to type things in the new buffer, say 1+1;;, and hit shift-return, I get Output file descriptor of OCaml is closed, as shown above.
I've been reading different documentations and threads for instructions, but none of them quite describe my situation. Any help would be much appreciated!

A: Maybe you should try something like M-x run-ocaml, return, and then type something like /usr/bin/opam config exec -- ocaml (or whatever the path to your opam installation) instead of ocaml

A: So I solved the problem by following realworldocaml. I realized that I had several problems in my post, so I'm using this answer to
share the solution to each as suggested in the link.
@ghilesZ's answer perfectly solves the problem in my question title (thank you!). I should have added the path of ocaml either in the M-x command (as the above answer suggests) or in the ~/.emacs configuration file (as the link suggests). The path can be obtained by typing which ocaml in the terminal after completing the step below.
The need to type
eval `opam config env`

to run ocaml from the terminal can be solved by adding the line to the ~/.bashrc file. This is because typing the command in the current shell only sets things up for the current shell. In order for future shells to automatically set things up, it needs to be added in the login scripts.