text:
Q: love2D Error: Bad argument #2 to 'rectangle' (number expected, got nil) I don't know what I'm doing wrong... Im getting the error in the player.draw() function. the bad argument that its talking about is in the love.graphics.rectangle() method. It's saying that v.x is a bad argument. But it should be working. both v.x and v.y should be working. Because its accessing fields of elements within the table or array right? Can someone tell me what I'm doing wrong and how to fix this? much appreciation! Here is my code:
require "scripts.player"

width = love.graphics.getWidth()

block = {}
block.width = 60
block.height = 10
block.speed = 150
block.timer = 0
block.timerLim = math.random(1,2)
block.spawnX = math.random(0, width - player.width)

function block.spawn(x,y)
    table.insert(block, {x = x, y = y})
end

function block.move(dt)
    for i,v in ipairs(block) do
        v.y = v.y + block.speed * dt
    end
end

function block.draw()
    for i,v in ipairs(block) do
        love.graphics.setColor(255,0,255)
        love.graphics.rectangle("fill", v.x, v.y, block.width block.height)
    end
end

function block.spawnHandler(dt)
    block.timer = block.timer + dt
    if block.timer > block.timerLim then
        block.spawn(spawnX, -10)
        block.timer = 0
        block.timerLim = math.random(1,2)
        block.spawnX = math.random(0, width - block.width)
    end
end

-- Parent Functions --

function DRAW_BLOCK()
    block.draw()
end

function UPDATE_BLOCK(dt)
    block.move(dt)
    block.spawnHandler(dt)
end

A: in function block.spawnHandler you meant block.spawnX instead of spawnX.
Since spawnX does not exist, its value is nil, which goes into the spawn function and gets set as the x value of the coordinate which then makes its way into rectangle and is the bad argument.
You can read more about that and how to prevent it from biting you again here: https://www.lua.org/pil/13.4.1.html
In short, lua is really weird, until you 'fix' it by making accesses to nonexistent variables throw errors instead of return nil, and about 800 other things like that. Once you 'fix' all those things, you have something which is merely weird and is not quite lua anymore.


text:
Q: Reading specific characters from a file in Python Suppose I want to read file in this format:
2

300   234 2 3

23444

If I use readline() it iterates over the entire line. What I want is for it to read only the numbers nothing else. How should I do this??

A: You can use re module.
import re

numbers = re.findall('[0-9]+', readline())

It will return all numbers as a list.

A: Use readline() to get the entire line as a string, then split the string using split(), which will return a list of strings (in your case, numbers) in the line.
Example:
line = yourFile.readline()
numList = line.split()

Now numList contains the numbers that were on that line.
Source: https://docs.python.org/2/library/stdtypes.html#str.split

redpajama_set_name: RedPajamaStackExchange


text:
Q: Tweet params with twitter API I want to have this template to tweet a String+Params like this:

What am I doing wrong?
Thanks in advance

A: Apparently it was like this:


text:
Q: are these two total variation distance formula equivalent Is this total variation distance is same as
$\|\mu-\nu\|_{TV}=\sup_{A \text{ is Borel}}\{|\mu(A)- \nu(A)|\}$
I am confused as I see many definitions of TV metric. Thanks for helping. If one can refer to a book where I can get the definition of the first type would be good.
Edit: I found this but there is a $\frac{1}{2}$, still confused and need a reference. Thanks!

A: In the case of $[0,1]$ for example (or any compact space for that matter), we can show that $\rho(\mu, \nu)=\sup \{\sum\limits_{k=1}^{\infty} |\mu(A_n)-\nu(A_n)|\}$ where the supremum is taken over all partitions $(A_n)$ of $[0,1]$ by measurable sets. This is not the same as $\|\mu-\nu\|_{TV}$.  However $\|\mu-\nu\|_{TV} \leq \rho(\mu, \nu) \leq 2 \|\mu-\nu\|_{TV}$, so these two metrics are equivalent.


text:
Q: Display image depending of result in MySQL query, using PHP I need to change a value depending a result.
In this case, if my row "status" is "Active" I want to put something like that in a table:
'.$row['register_status'].'
'if($row['status']=='Active'){print "";}'
'.$row['register_status'].'

What is wrong?
Edit: Sorry. I did not put all code. Here starting my array and I put with quotes your code but can't run
if(mysql_num_rows($result) > 0)
{
    $number = 1;
    while($row = mysql_fetch_assoc($result))
    {
            $data .= '

            '.$row['register_status'].'
            '
            if($row['status']=='Active')
            {
            echo '';
            }
            '

';
            $number++;
    }
}
else
{
    // records now found
    $data .= '
Records not found!
';
}

$data .= '
';

echo $data;


text:
Q: is it possible to index html content in postgresql full text search? I have a bunch of html pages. The idea is to allow users enter keywords to search through these html pages. only html pages that match the criteria will be store for later references. I knew that Elastic search can index html,pdf, and more but in my case I already have postgresql as my database and my system is small enough so I don't want to have Elasticsearch as extra dependency for this project.
A few issues I have here here:

*

*because html won't be stored unless the query match the users' keywords, is there a better approach to handle this without having had to index html first to the search engine to be able to search and remove it afterward if it doesn't match the criteria ?

*yes is it possible to index whole html content like in Elasticsearch ?
Thanks a lot for your help?


text:
Q: How to make a CSS grid set its height based on the size of elements without squeezing? I have a CSS grid with a dynamic number of elements. I set it up with this code:
  display: grid;
  margin: 0;
  padding: 0;
  height:100%;
  grid-template-rows: repeat(auto-fit, 200px);
  grid-template-columns: repeat(3, 200px);
  gap: 15px;
  grid-auto-flow: row dense;

This fits in nicely.. creates a grid with a number of squares that fits in 3 columns. Now the problem happens when the number of elements are bigger than what fits in the screen height. Instead of automatically adjusting the height to fit in those elements at 200px (the template size), newly added cells are shrunk down at the bottom.
If I simply remove height:100%, then all elements get shrunk and don't respect the 200px / 200px rule. How to make it work?


text:
Q: How achieve Approval process in this Scenario I have idea about how the approval is work for normal scenario like user click on approval , it will got to manager, he will approve or reject based on action we are able update/trigger any event.

In my scenario , I have Requirement when user click on button called "approval Process" I have to send the task to Manager approval.
if you observe the diagram clearly . I have 4 different level of user group, once user click on submit for approval, approval will sent to all 4 group.
Criteria For Reject: When "Any one user" in "Any of the Group"  click on the reject, I have update status to reject in task.
Criteria For Accept : When "Any one user" of the "Each Group" should click on the accept ie.. all the 4 group manager has accept then, I have update status to Accept in task.
How to achieve this functionality using salesforce OOTB functionality ? Any help please ...

A: Here assuming each group has multiple members who can approve.
Create a queue name "All Department" which consists of all the 4 groups.

Create 4 checkboxes with a name:

*

*IMApprovedStatus

*BSITApprovedStatus

*ComplianceApprovedStatus

*ArchitectApprovedStatus

Create a status pickist which holds following values:

*

*Approve1

*Approve2

*Approve3

*Approve4

Write a trigger on before update

*

*logic behind the trigger will be, before update system should check the approver belongs to which group and respectively update group specific checkbox.

*Also, you should put a validation that if an user of previous group already approved then other group member from the same group cannot approve. Since you will be re-submitting the approval process and that approval process will go to all the users.

First approval process:

*

*You can define proper criteria so that it can be submitted to the "All Department" Queue.

*Here in the approval action, update the Status as "Approve1" through workflow field update. (Note that, check Re-evaluate Workflow Rules after Field Change checkbox in the field update, otherwise process builder will not fire)

*Unlock record after approval

Write a process builder which auto-submits to the 2nd approval process where status is "Approve1".

2nd Approval process:

*

*Add status = "Approve1" as a criteria to submit and submit to "All Department" queue.

*Here in the approval action, update the Status as "Approve2" through workflow field update.

*Unlock record after approval

Write a process builder which auto-submits to the 3rd approval process where status is "Approve2".

3rd Approval process:

*

*Add status = "Approve1" and "Approve2", as a criteria to submit and submit to "All Department" queue.

*Here in the approval action, update the Status as "Approve3" through workflow field update.

*Unlock record after approval

Write a process builder which auto-submits to the 4th approval process where status is "Approve3".

4th Approval process:

*

*Add status = "Approve1" and "Approve2" and "Approve3", as a criteria to submit and submit to "All Department" queue.

*Here in the approval action, update the Status as "Approve4" or any final status through workflow field update.

*Lock record after approval

Rejection behavior is easy, on any of the rejects it will update as Rejected.

A: You can try one option Here. On approve selection screen You can add all four group and select the second option which is

*

*Require unanimous approval from all selected approvers :
The record is only approved if all of the approvers approve the request. The approval request is rejected if any of the approvers reject the request.

So you might get your expected result. The only point which I'm not sure for now is if you select a group then do we need approval from all group member. But you can give it a try as it will not take much time.

A: There are also some AppExchange packages that support scenarios like this without requiring you to code or create enhanced flows.
E.g. Approvals Pro https://appexchange.salesforce.com/listingDetail?listingId=a0N4V00000He5z6UAB&tab=e
Full disclosure: I'm affiliated with Approvals Pro


text:
Q: jQuery - using .slideToggle to toggle ONLY ONE thing at a time All I want is for each list to toggle in and out when you click the span that precedes it. What happens now is that clicking one span toggles all the lists. I'm a jQuery beginner, but I feel like this is a really simple thing to do, so I'm frustrated that I can't figure it out. Also, there will be a LOT of these on the page, so I don't want to have to add a bunch of code for each new list.
This is my HTML:
123 Main Street

2 bedrooms

1 bathroom

New carpets throughout

All large kitchen appliances included

In-unit washer and dryer

Central air

Dishwasher

Renter responsible for all utilities

321 Main Street

2 bedrooms

1 bathroom

New carpets throughout

All large kitchen appliances included

In-unit washer and dryer

Central air

Dishwasher

Renter responsible for all utilities

So, again, I want to be able to click each span with a class of "rental" and toggle the list that immediately follows it.
Here is the jQuery I have been using:
$(document).ready(function(){
$('.rental').click(function() {
$('.rental-det').slideToggle()
});
});

I have also added display: none; to the .rental-det class to make them hidden by default.

A: Change
$('.rental-det').slideToggle()

to
$(this).next('.rental-det').slideToggle();

jsFiddle example
Your $('.rental-det').slideToggle() was selecting all lists of the .rental-det class, where you wantes to use instead $(this) and .next() to pick the list that followed the span that was clicked on.

A: I would modify the HTML to move the spans to divs and place the details withing those divs.
$('.rental').on('click',function(){
    $(this).children().slideToggle();
});

This will simply display and javascript.
See my fiddle.
http://jsfiddle.net/LeHMa/


text:
Q: What does the "arrow" icon shown in the iPhone status bar indicate? The icon shows an arrow like symbol pointing towards upper right. It appears towards the left of the battery indicator in iPhone.
What does this mean?

A: This icon represents Location Services. The icon isn't generally shown all the time. The appearance of this icon indicates that some iOS app/service has recently accessed your current location.
The appearance of the icon can be configured by going to Settings app → Privacy → Location Services → System Services on your iPhone and toggling the switch shown in front of Status Bar Icon item.

Your iPhone may use not just GPS, but a combination of various technologies such as Bluetooth, crowd-sourced Wi-Fi hotspots, location determined by cellular towards, and other GPS like technologies such, GLONASS, Galileo, and QZSS to determine the current location.
Also, as shown above the Status Bar Icon item, the icon itself could be styled in different form to convey different information.

A: It means that your GPS is turned ON.


text:
Q: Batch Rename in Fish shell I get 15 or 20 files every week with random names that include several symbols such as !,' etc. Plus there is space. So I need to replace space with _, and any other symbols to nothing before I can pass them to another script. I use thunar for the job now, but I'll very much like to automate it in the script. I'm using fish shell.

A: Okay, I find an old tool called rename. It did the trick without using sed or any complex command.
http://rename.sourceforge.net/


text:
Q: is this sort of layout possible with flexbox or react-css-grid? I am about to start a react project and it involves a bit complicated layout and it needs to be responsive.
I have drawn a rough diagram in paint of what I need to do and have marked the places where I am finding it tough to accomplish.
could you tell me if that kind of layout can be accomplished in react with either flexbox or react-css-grid or maybe something else??
if there's a link you could point me to a tutorial or an article which explains this, then that would be very helpful.
Here's the image

A: Flexbox should be enough. You can use flexbox-direction: column for the base page, and give appropriate CSS classes to the React component you will use to build this layout.
For A, you can use transform: skewY() but the element beneath should accommodate the new space after skewing element A.
Regarding B, it can easily be done using flexbox. Justify items to flex-start (and some padding), and then give the bigger square position: relative. Smaller square should then have the position: absolute, and then you can position it accordingly to the bigger square. That should be it in short lines, but I can throw some demo later if you still need help.


text:
Q: How to get the bookflip effect with JavaScript Finally I found the effect I was looking for.
Sadly it is written as a java applet.
Do you know how can I get the same effect with JavaScript?
You can see the effect in the link below... it switches between pictures as though they where book pages:
http://javaboutique.internet.com/BookFlip/

A: For some reason I could not see the applet:
Please tell me if this does the job for you:
http://clickheredammit.com/pageflip/
Good luck!
EDIT:
I found one more:
http://plugins.jquery.com/project/jFlip
See it working here:
http://www.jquery.info/scripts/jFlip/demo.html
Tell me if no of this suits you!


text:
Q: std::string::clear() vs using another string I need a temporary string to append and modify pre-existing strings so that i can use with DrawText. That temporary string needs to change inside a function so I have 2 options:
-Use std::string::clear()
-Initialize another temporary string.
I can use and understand both methods but I'm wondering, which one is better?
Edit: To the function in question, having low running-time is essential

A: Whichever one more clearly reflects the intent of the code is better. The one you would use if you didn't stop to think which was "better" is better.

A: If (and only if) profiling reveals a performance problem in your function then you might save tiny amounts of time by reusing an existing string.
The memory of the existing string is already allocated. No new memory allocation needs to be made unless the string exceeds the size of the memory allocation.
On the other hand, if you create and destroy a lot of strings, the allocation time can start to add up.
I have some code where std::string allocation and copying dominates the profile. To fix it sometime in the future, we're going to have to implement string pooling, custom allocators and use string_ref instead of string.
So yes, it can be a problem. But measure to find out before trying to fix it.


text:
Q: Error using sub-string method with textfield We are have an error when we try to obtain the first few character of a string
First we tried to remove the last two offending characters
That produced the same error we are seeing when we try to obtain the first few characters
The On Key Typed method is attached to a textfield when MAX character are exceeded a custom alert
is fired. We have looked at many ways to remove or get sub-strings in various SO questions before posting
The string entered will never be the same hence we do not know the specific character to replace
Here is the code and a screen shot of the ERROR notice that the "o" in front of the original text
The string we are entering is "This is a test to see how many yo"
We are trying to obtain only the "This is a test to see how many"
The System.out.println(strNew) is exactly that but when strNew is add to the textfield the "o" shows up
Our question is how to prevent this ?
OR What is the cause of the odd text that is palaced in the textfield?
Here is the Minimal Code to test
public class Atest extends Application {
@Override
public void start(Stage stage) throws Exception {
    Parent root = FXMLLoader.load(getClass().getResource("test.fxml"));
    Scene scene = new Scene(root);
    stage.setScene(scene);
    stage.show();
}
public static void main(String[] args) {
    launch(args);
}

The Controller
public class testController implements Initializable {
@FXML
TextField txtDesc;
@FXML
private void handleButtonAction(ActionEvent event) {
    txtDesc.setText("Thanks");
}
@FXML
private void descLEN(){
    txtDesc.setOnKeyTyped(event ->{
    int maxCharacters = 10;
    if(txtDesc.getText().length() > maxCharacters)
        event.consume();
    });
}
@Override
public void initialize(URL url, ResourceBundle rb) {
}

We have no idea how to post FXML Code all you need is a TextField
with the id txtDesc and set the OnKeyTyped to descLEN

A: Because you are consumed with the Custom Alert you may not like our answer
I call this We Hear You Knocking but You Can NOT Come In Your event is consume
OK the answer suggested by Sedrick is great but we have only used 3 Lines of Code
No Custom Alert just 30 Character and a bunch of consuming ha ha
@FXML
private void onType(){
    txtDescription.setOnKeyTyped(event ->{
    int maxCharacters = 30;
    if(txtDescription.getText().length() > maxCharacters)event.consume();
});

All right 7 lines if you count the FXML tab and the declaration and formatting


text:
Q: Organizing VBA Project I am maintaining a large MS Access Project. Over time the number of modules and classes has grown, at this moment it contains 90 modules. More and more time do I spend searching for a specific class in the list. (I know about Shift+F2 :))
Is there any way to organize the list of modules in the VBA editor, i.e. some kind of Addin? My idea would be subfolders in the tree or a filter-as-you-type textbox.
Best regards,
 Torben

A: First of all try: MZ-Tools. It has free version for MS Access. HomePage
It's a toolkit that help maintain access project in many aspects: create automatic documentation; create, modify and maintain procedures, functions and properties etc.

A: Develop a logical naming system. You can't get a tree per-se, but you can name things in a way that they are easier to find.
Module 1: A_systemtools
module 2: __systemtools_a
module 3: B_programitems
etc...


text:
Q: Categories where projective objects are flat  In many categories arising in the theory of algebras or modules, projective objects are flat. For example each projective module over a ring with identity is flat. However, there are categories where this principle is violated: Lewis has shown that the category of Mackey functors for the orthogonal group $O(n)$ has non-flat projectives.
Q1: Is there a classification of symmetric monoidal abelian categories $\mathcal{A}$  where all projectives are flat ? BTW: Do such categories have a particular name ?
If a classification is too strong to establish, I would be interested in
Q2: Are there criteria that ensure that projectives are flat ?
An example for Q2 is, when $\mathcal{A}$ has direct sums and the unit is a progenerator of $\mathcal{A}$ (this is just the categorification of the module case mentioned above). Note that this criteria doesn't work for instance in the category of $RG$-modules ($R$  commutative ring, $G$ a group) where the tensor product is given by $M \otimes_R N$ with diagonal $G$-operation.

A: As for the second question, an obvious sufficient condition is that $\mathcal{A}$ is AB4, the tensor product commutes with direct sums, and the existence of a generating family of flat objects.
Namely, if $\{F_i\}_{i \in I}$ is such a generating family and $P$ is a projective object of $\mathcal{A}$, then ${\bigoplus_{i \in I}} F_i^{\oplus \hom(F_i,P)} \to P$ is an epimorphism, which shows that $P$ is a direct summand of flat objects, therefore also flat.
Following the terminology of algebraic geometry, a generating family of invertible objects, or more generally dualizable objects (which are in particular flat) might be called an ample family. An abelian $\otimes$-category which has such an ample family might be called divisorial. When $X$ is a divisorial scheme, then $\mathrm{Qcoh}(X)$ is an example (but there are few projective objects). Other examples arise from $\otimes$-analogues of non-commutative projective schemes à la Artin-Zhang.
When $\mathcal{A}$ is as above and $G$ is a group, then $\mathrm{Rep}_{\mathcal{A}}(G) := [G,\mathcal{A}]$ has the same properties: If $\{F_i\}$ is a generating family of flat objects of $\mathcal{A}$, then $\{F_i[G]\}$ is a generating family of flat objects of $\mathrm{Rep}_{\mathcal{A}}(G)$. Here, $F \mapsto F[G]$ is the functor which is left adjoint to the forgetful functor, constructed via $F[G] = \bigoplus_{g \in G} F$ with the obvious $G$-action.

A: This is the sort of question which would interest my advisor, Mark Hovey. In fact, he and Keir Lockridge wrote a paper called Semisimple Ring Spectra which addresses questions like this in triangulated categories (which cannot be abelian but make more sense to work with if you do homotopy theory). In this paper he has two results which answer your question in that context. I'll paraphrase them and highlight the bits that matter, but first some definitions.
A triangulated category come with an endofunctor $\Sigma$ which acts like suspension in topological spaces or shift in chain complexes (there are axioms for this). With this endofunctor you can define homotopy classes of maps and do cohomology theory. Call such a category $T$ a weak stable homotopy theory if every cohomology theory is representable. Suppose you have such a theory and it comes with a compact generator $S$ (i.e. the smallest localizing subcategory containing $S$ is $T$). Call such a theory a stable homotopy theory if there is also an axiom saying that $S$ plays nicely with the smash product. Call it a Brown category if all homology theories and natural transformations between them are representable. Assume below these hypotheses hold on $T$.
Proposition 2.1: The generator $S$ is semisimple iff projective objects and realizable objects coincide.
Remark 2.3: The generator $S$ is von Neumann regular iff flat objects and realizable objects coincide.
For the definitions of semisimple and von Neumann regular, see that paper. These are just the versions for triangulated categories of standard properties of rings. So semisimple implies von Neumann regular and there are classifications for when the converse holds. Furthermore, you can find a classification of semisimple objects in such theories $T$ as Theorem 4.1, which is a purely algebraic classification based on $\pi_*(S)$. So this gives some sense of a classification of theories where projectives and flats are the same. I don't know if anything like this has been done in the abelian setting. I'd be very interested to know!


text:
Q: What is the correct way to auto-create related model objects in django-registration? I'm a total Django newbie and apologize in advance if I'm not using the correct terminology.
I'm using django-registration to register user on my web-app. I've successfully adapted it work with my custom user model GeneralUser.
Conceptually, each GeneralUser has a Business, another model that I've defined. Whether this is the correct decision or not, I've decided that I never want to register a user without a related Business object.
I've read countless threads on customizing django form, and finally after a few days of unsuccessful attempts, came upon an answer that helped reach a solution. However, I am unsure that my code is correct/safe. This is my adaptation, followed by the linked-answer:
my adaptation:
class GeneralUserForm(UserCreationForm):
    business_name = forms.CharField(required=True)

    class Meta:
        model = GeneralUser
        fields = ['username', 'email', 'password1',
                  'password2', 'business_name']

    def save(self, commit=True):
        user = super(UserCreationForm, self).save(commit=True)
        business = Business(name=user.business_name, owner=user)

        # notice: no if-block
        user.save()
        business.save()
        # notice: returning only a user-instance
        return user

This code successfully creates a user and a business object, and creates the relationship. Looking at the original answer code though, I wonder if there isn't something critical I'm missing:
Answer I based my code on:
class UserCreateForm(UserCreationForm):
    job_title = forms.CharField(max_length=100, required=True)
    age = forms.IntegerField(required=True)

    class Meta:
        model = User

    def save(self, commit=True):
        if not commit:
            raise NotImplementedError("Can't create User and UserProfile without database save")
        user = super(UserCreateForm, self).save(commit=True)
        user_profile = UserProfile(user=user, job_title=self.cleaned_data['job_title'],
            age=self.cleaned_data['age'])
        user_profile.save()
        # notice: multiple returns
        return user, user_profile

A few questions about the differences:

*

*Why doesn't my code work if I end it like this:

.
if commit:
        user.save()
        business.save()
        return user

*

*I'm not using cleaned_data, is that okay?

*What is the purpose of the if not commit block in the original code?

*Most importantly, is this a "legitimate way" to handle user registration that requires an automatic object-relation on creation?

A: *

*cleaned_data is the dictionary of data after all validation in every field in that form. Now you can decide whether to rely on it or not(preferably you should).So as a pseudocode we could say cleaned_data + errors will be all fields.

*commit is used to decide whether it should commit to db(write). From the above code, to add a related model object like profile, the original object(User) has to be created first.Thats why it make force commit.

*To add a related object on object creation, there are multiple ways like post_save signals, override model save, override form save etc.So you are using one of good approach, I would say.


text:
Q: Send to a friend form in popup Is there any way to make send to a friend form in popup box in product view page i have tried with the default template code in "template/sendfriend/send.phtml" by directly copy in to a popup box but its seems to be error can anyone help me to do this

A: First you need create a popup on the product page using the any of these library jQuery, Bootstrap or Prototype js.
After that include/call the send.phtml file on this popup content.

A: I use Fancy box for that
My Email to friend link looks like
<?php if ($this->canEmailToFriend()): ?>

        <a class="feature first v-centered-content" rel="fancybox1" href="<?php echo $this->helper('catalog/product')->getEmailToFriendUrl($_product) ?>" title="<?php echo $this->__('Email to a Friend') ?>">
         Email to a Friend

<?php endif; ?>

My fancybox popup init

Remove Header footer from sendto friend page from layout
    <sendfriend_product_send>
        <reference name="root">
            <remove name="header"/>
            <remove name="footer"/>
        </reference>
    </sendfriend_product_send>

send button event after form fillup
jQuery('#send-email').click(function(){
    setTimeout(function () {
        parent.jQuery.fancybox.close();
        parent.location.reload(true);
    }, 1000);

})


text:
Q: c++ не правильно определяет цвет пикселя Я пишу простого бота который определяет цвет и нажимает на кнопки если цвет изменился, но С++ не правильно его определяет
int B;
HDC hdc_ = GetDC(NULL);
COLORREF color;

for (; ;)
{
    color = GetPixel(hdc_, 894, 368);
    B = GetBValue(color);
    cout << B << endl;
}

При смене цвета в указанных координатах цвет не изменяется, но когда я перемещаю консоль в какое-то другое место он изменяется, хотя координаты указаны не там куда я переместил консоль. При выполнении такой программы в python или java проблем не возникает


text:
Q: RXJS RetryWhen - continue error downstream while attempting retry The steps:

*

*I have a source stream (observable) that is a web socket connection.

*When the connection is disconnected or errors the source emits a error on the stream.

*Downstream from the source I use retryWhen to attempt a reconnect to the web socket connection after every x seconds.

*

*Up to this point everything works as I want.

*Further downstream I have a catchError that sets a default value. This allows the application to know the up-to-date status of the connection.
Example code (a very simplistic example of my code):
connect(): Observable<any> {
  return this.websocket() // source stream that errors when it disconnects
    .pipe(
      retryWhen( errors =>
        errors.pipe(
         delay( 2000 ) // delay retry
        )
      )
    )
}

connectionStatus(): Observable<boolean>{
  return this.connect().pipe(
    catchError( () => of( false ) ), // this does not trigger with the retryWhen
    map( () => true )
  )
}

The problem:
I want the downstream subscribers to know that it's disconnected while it is attempting the retryWhen. However, the downstream catchError is not triggered while retryWhen is happening.
Any ideas how I can attempt re-connecting for all subscribers (not just the connectionStatus), but also when notify downstream when the connection is down (errors).
After re-connecting I want to continue streaming to all subscribers like nothing has happened.
Let me know if anything is unclear.

A: So writing this post helped me answer my own question.
/*
Basic stream handling no errors or retries..
*/
connect(){
  return this.websocket();
}

/*
Have a stream that is always connected for all subscribers
*/
alwaysConnected(){
  return this.connect().pipe(
    retryWhen( errors => {
      return errors.pipe(
        delay( 2000 )
      )
    })
  )
}

/*
use the continuous stream (no errors) and then in sub stream listen for the errors.
*/
connectionFails() {
  return this.alwaysConnected().pipe(
    switchMap( () => {
      return this.connect().pipe( // switch to stream that errors
        catchError( error => of( false ) ),
        filter(connection => connection === false )
      )
    })
  )
}

/*
Get a boolean for either a fail or success
*/
connectionStatus() {
  return merge(
    this.connectionFails(),
    this.alwaysConnected().pipe( map( () => true ))
  )
}

There were a couple of issues.

*

*handling retry and catcherror

*not completing a subscription when handling the error
There might be a simpler more elegant solution. Feel free to suggest.


text:
Q: Rails ActionMailer: Does :sendmail work in production? I have a form on my site for users to contact me, and on form submission a mailer is delivered. In my config/initializers I have a setup_mail intializer:
ActionMailer::Base.smtp_settings = {
  :address              => "localhost",
  :port                 => 25
}

ActionMailer::Base.delivery_method = :sendmail

It works in development. But compared to SMTP servers (like Gmail, where you have :login, :username, :password, etc.) I feel like there are so few settings, so I am wary of whether or not it works in production. Where does :sendmail actually send from? For the email I want sent, it's going to use the user email as the sender and my email as the receiver.


text:
Q: GNU Octave error message When I load Octave each time I get the below errors after the welcome/info message.
error: `prefix' undefined near line 12 column 35

error: evaluating argument list element number 2

error: called from:

error:   C:\Octave\Octave3.4.3_gcc4.5.2\share\octave\site\m\startup/octaverc at line 12, column 1

octave:1>

Does anybody know why this is happening?

A: For that version of octave, the default settings of that file around that line are:
prefix=octave_config_info('prefix');
setenv('path',[getenv('path'),';',prefix,'\mingw32\bin;',prefix,'\msys\bin']);
setenv('path',[getenv('path'),';',prefix,'\gs\gs9.02\bin'])

So you should check if it has changed


text:
Q: magento 2 add quantity below 1 to cart I'm going insane! I want to add 0,5 to my cart in Magento 2 and it's not working!
I adjusted the "Minimum Qty Allowed in Shopping Cart" to 0.5 and tried everything, but not working.
1.2 is working fine, but 0.9 will not work
link: https://www.huurhulp.nl/tricot-stoffen/stippen/tricot-rood-stippen-8mm.html
I'f i look in the page source i find this section, and i'm thinking that there's the problem.
<div class="control">
   <input type="number"
      name="qty"
      id="qty"
      maxlength="12"
      value="0.5"
      title="Qty" class="input-text qty"
      data-validate="{"required-number":true,"validate-item-quantity":{"minAllowed":1}}"
    />
 </div>

A: It is in the line in ProductView.phpThis line seems to disallow min quantities less than 1.
magento/module-catalog-inventory/Block/Plugin/ProductView.php: $params['minAllowed'] = max((float)$stockItem->getQtyMinAllowed(), 1);
I manually set it to 0,5 and that did the job (But not nice...)


text:
Q: Program with named pipes sometimes working sometimes fails Hello I am trying to do a program in c that uses named pipes to communicate with another program but if i run it more than once it fails most of the time with occasionally working perfectly, even though i don't change anything between tests.
Here is the code for  arbitro.c the program that i execute first
#include <stdio.h>
#include <stdlib.h>
#include <string.h>
#include <fcntl.h>
#include <sys/stat.h>
#include <sys/types.h>
#include <unistd.h>
#include <signal.h>

int main(int argc, char *argv[])
{
    int fd,id1,cont_pront=0,i=0;
    char nomejog[40]="",instrucao[40]="";
    // FIFO file path
        char * myfifo = "myfifo";
    // Creating the named file(FIFO)
        mkfifo(myfifo, 0666);
do{
    fd = open(myfifo,O_RDONLY);
        if(fd == -1){
            fprintf(stdout, "Erro a abrir.\n");
        }
        // First open in read only and read
    for(int i=0;i<2;i++){
        read(fd, nomejog, 40); //Recebe o nome do jogador
        read(fd, &id1,sizeof(id1)); //Recebe o id do primeiro jogador
        fprintf(stdout, "Nome: %s -» %d\n", nomejog,id1);
        cont_pront++;
    }
    fprintf(stdout, "Nº: %d\n", cont_pront);

    //Now open in write mode and write
    fd = open(myfifo,O_WRONLY);
    if(fd == -1){
        fprintf(stdout, "Erro a abrir.\n");
    }
    if(cont_pront >= 2){
        cont_pront = -1;
    }
    write(fd, &cont_pront, sizeof(int));
    close(fd);

// optind is for the extra arguments
// which are not parsed
for(; optind < argc; optind++){
    if(i == 0){
        printf("Duração do campeonato: %s\n", argv[optind]);
    }else{
    if(i == 1){
        printf("Tempo de espera: %s\n", argv[optind]);
    }
    }

    i++;
}

}while(strcmp(instrucao,"exit") != 0);
    return 0;
}

and here is the code for cliente.c
#include <stdio.h>
#include <stdlib.h>
#include <string.h>
#include <fcntl.h>
#include <sys/stat.h>
#include <sys/types.h>
#include <unistd.h>
#include <signal.h>

int main(int argc, char *argv[]){
    int fd1,cont_pront=0;
    char nomejog[40]="";
    // FIFO file path
        char * myfifo = "myfifo";
    // Creating the named file(FIFO)
        mkfifo(myfifo, 0666);

    // Open FIFO for write only
        fd1 = open(myfifo, O_WRONLY);
        //Enviar o nome do jogador ao arbitro
        for(int i=0;i<2;i++){

        write(fd1, nomejog,strlen(nomejog)+1); //Envia o nome do jogador já pronto
        write(fd1,&i, sizeof(int)); //Envia o id
        strcpy(nomejog,"pedro");
    }
    close(fd1);

    //Receber quantos jogadores estão prontos
    fd1 = open(myfifo, O_RDONLY);

    read(fd1, &cont_pront, sizeof(int)); //Recebe o nome do jogador

    if(cont_pront == -1){
        //Tem jogadores necessários para começar o jogo
        fprintf(stdout,"Existem jogadores suficientes, o campeonato vai ser iniciado...\n");
        execl("GAMEDIR/game01","GAMEDIR/game01", NULL);
    }else{
        //Ainda não tem jogadores suficientes para começar o jogo
        fprintf(stdout,"Nao tem jogadores suficientes para comecar o campeonato.\n");
    }
    close(fd1);
return 0;
}

if everything goes well this is supposed to say that there are enough players and the executes the game, but for some reason sometimes it repeats everything sending more players in blank or the client stops midway execution or even doesn't send the correct players in the first place


text:
Q: Upload file and send parameters to spring portlet controller Can any one of you tell me how to upload a file and also pass a input parameter to the controller using spring mvc portlet controller ?
Action URL and form in jsp :
<portlet:actionURL var="addDetailsURL">
    <portlet:param name="addDetails" value="addDetailsValue"/>
</portlet:actionURL>

<div id = "<portlet:namespace/>addDetailsDIV" >
    <form action="${addDetailsURL}" enctype="multipart/form-data" method="post">

        <input style="display:block;" type="text" name="selectedDetail" id='selectedDetail'/> <%-- holds the parameter that is supposed to be passed to the controller --%>

                <fmt:message key = "selectFileUploadTxt"/>

                <input id="uploadedFile" type="file" name="uploadedFile" />

                <span id="<portlet:namespace />closeAddDetailDia">cancel

                <Button id="uploadButton"><fmt:message key="addDetailButtonTxt" /></Button>

    </form>

On submit the request goes to the controller but the "selectedDetail" parameter is null.
Controller code :
@RequestMapping("VIEW")
public class AddDetailsController {

    /**
     *
     * @param actionRequest
     * @param actionResponse
     * @return
     * @throws IOException
     */
    @SuppressWarnings({ "rawtypes", "unused" })
    @ActionMapping(params = "addDetails=addDetailsValue")
    public String fileUpload(ActionRequest actionRequest, ActionResponse actionResponse,
        @RequestParam String selectedDetail
            ) throws PortletException, IOException {
        System.out.println("selectedDetail : " + selectedDetail); // it is null
        System.out.println("selectedDetail : " + actionRequest.getParameter("selectedDetail")); // it is null

The file upload part is working fine but I am not getting the "selectedDetail" parameter. Please help .
Environment Details

*

*WebSphere Portal v7002

*IDE - RAD v8.5

*Spring version 3.1.0

Please let me know if you need any other detail.

A: On the backend, define a bean to hold the form data including the file.
I'll call it FormBean. FormBean should have an instance variable of type
private org.springframework.web.multipart.commons.CommonsMultipartFile file;
Changes in the form will include having "commandName" and "path" in form elements:
<form:form enctype="multipart/form-data" commandName="formBean"... />
&
<form:input id="uploadedFile" type="file" name="uploadedFile" path="file"/>
The following link explains this well:
https://portalhub.wordpress.com/2012/05/20/spring-mvc-portlet-file-upload-and-download/


text:
Q: Unable to determine if app installed after upgrading build compileSdkVersion to 30 We have the following code to determine if Facebook, Twitter etc. is installed on the app (for simplicity code posted is refactored for just Facebook).
        String packageName = "com.facebook.katana";
        info = context.getPackageManager().getPackageInfo(packageName, 0);
        if(info != null && info.applicationInfo.enabled) {
            LogTool.c(TAG, platform.name() + " is installed");
            return true;
        }

This code works as expected until we upgraded the build.gradle file to compileSdkVersion 30 and targetSdkVersion 30. When these were both at 29 they worked as expected. Upgrading to version 30 give the following error:
class android.content.pm.PackageManager$NameNotFoundException

Anyone know what the correct way, or what I'm missing, to do this with the latest versions of these apps?


text:
Q: Rectifying awk statement I have a file as below to do date and number validation. File:
006063416.01|USD|1| |00.00000|00.00000|O| |20100802|20160119| |D|+0000006063416|0000000000|          |060.634164000|
06063416.001|AUD|M| |00.00000|00.00000|O| |2015991130|20160319| |D|+0000006063416|0000000000|          |006a063416096|
06063416.002|HKD|M| |00.00000|00.00000|O| |20151130|20168919| |D|+0000006063416|0000000000|          |006063416075|

Script:
#!/bin/ksh
set -x
validate() {
echo "Performing file  validations ..."
file=/var/applications/scripts/bin/CLIMAMT_SG
CURR_DTTM=`date +%Y%m%d.%H%M%S`
output=/var/applications/scripts/bin/output_CLIMAMT_SG.${CURR_DTTM}
awk -F\| '$16 !~ /^[0-9]+$/ {print "Line:"NR" Field:16 "$16" is not Numeric"}(date "+%Y%m%d" -d "$10")+0 != "$10"{print "Line:"NR" Field:10 "$10" is not in date format";next}' $file > $output
echo "Validation Complete"}
validate

output:
Line:1 Field:16 060.634164000 is not Numeric
Line:1 Field:10 20160119 is not in date format
Line:2 Field:16 006a063416096 is not Numeric
Line:2 Field:10 20160319 is not in date format
Line:3 Field:10 20168919 is not in date format

problem is that even 20160319 is reported as incorrect

A: This line:
(date "+%Y%m%d" -d "$10")+0 != "$10"{print "Line:"NR" Field:10 "$10" is not in date format";next}

does not call out the the external date command. awk parses that like this:

*

*the - operator has higher precedence than string concatenation, so first we take the string "%Y%m%d" and subtract the variable d, resulting in the value 0

*now we take the value of the date variable (which is empty) and concatenate 0 and the string "$10" (not the value of the 10th field)

*this results in the string "0$10"

*then we add zero to that string, resulting in the value zero

*and compare that to the value of the 10th field.

That will only match if you have 0 in the 10th field.
GNU awk has some time functions, so you could do something like (untested)
function validate_date(datestr,   timespec) {
    timespec = substr(datestr,1,4) " " substr(datestr,5,2) " " substr(datestr,7,2) " 0 0 0")
    return mktime(timespec)
}

{
    if (validate_date($10) == -1) {
        print $10 " is an invalid date"
    }
}

A: (date "+%Y%m%d" -d "$10")+0 in awk when variables date and d are unset subtracts the two strings +%Y%m%d which has a numeric value of zero and (the value of) field 10 which in this case might be 20161499 thus producing the value -20161499. I got this part wrong and glenn got it right, but either way it doesn't run date as desired.
To run a command from awk and get its output, use the pipe form of getline (see info on your system or online) but you can't fit it entirely in a condition so make it part of your action:
{ cmd = "date +%Y%m%d -d " $10; cmd | getline checktime; close (cmd);
  if( checktime != $10 ) { print "invalid time" $10; next } }

Alternatively if you have GNU awk (and if you have GNU date you probably do) you can use the builtin functions mktime and strftime
(which do fit in a moderately complicated condition)
 strftime("%Y%m%d", mktime(substr($10,1,4)" "substr($10,5,2)" "substr($10,7,2)" 00 00 00")) == $10


text:
Q: Ubuntu 18.10 Cosmic Cuttlefish not connecting to my Android phone. Showing ERROR: Unable to access & couldn't find matching udev device. What to do? Ubuntu 18.10 Cosmic Cuttlefish is not connecting to my Android phone. It shows the error:

Unable to access "SDM636 MTP SN:E48333B7"
Couldn't find matching udev device.

What to do?

A: How to connect Android device using MTP Ubuntu- Youtube Tutorial
Connect an Android device using MTP in Ubuntu.
You need to follow following steps because ubuntu doesn't show your mtp devices (security reasons).
Open a terminal and type commands
$ sudo apt-get install libmtp-common mtp-tools libmtp-dev libmtp-runtime libmtp9

$ sudo apt-get dist-upgrade

Remove # from in front of last line
$ sudo nano /etc/fuse.conf

connect your phone to your pc (unlocked)
$ lsusb

open new terminal and type the following command
$ sudo nano /lib/udev/rules.d/69-mtp.rules

copy and paste below lines and replace Device with your phone name and the addresses as shown in image below.
replace the addresses as in the image
# Device
ATTR{idVendor}=="XXXX", ATTR{idProduct}=="YYYY", SYMLINK+="libmtp-%k", ENV{ID_MTP_DEVICE}="1", ENV{ID_MEDIA_PLAYER}="1"

type the following command
$ sudo nano /etc/udev/rules.d/51-android.rules

Replace the addresses as shown in the image
ATTR{idVendor}=="XXXX", ATTR{idProduct}=="YYYY", MODE="0666"

$ sudo service udev restart

$ sudo reboot


text:
Q: How to enable 3D Touch peek & pop but prevent navigation in iOS 9? I want to enable peek preview en my table View, but i don't want the user to actually navigate to the destination VC. I just want to let him peek, but not navigate into it.

A: I found a solution to this question.
The VC needs to implement the UIViewControllerPreviewingDelegate protocol which handles the peek and pop behaviours.


text:
Q: Django execute order by before filter i'm using django 2.0.7
so, i want to order a queryset and then select distinct entries,
after that, i'm gonna perform some filtering
as you can see here i'm doing the order and select distinct stuff
forms = Form.objects.order_by('user','-created_at').distinct('user')

and here i'm filtering some attributes
filterd_qs = forms.filter(**query)

the problem is that the order_by query is executed after the filter query which causes unexpected results (it's applying the filter on the whole queryset),
the sql query resulted from the last filter :
SELECT DISTINCT ON ("table"."user_id") fields FROM "appname_form" WHERE where_clause ORDER BY "appname_form"."user_id" ASC, "appname_form"."created_at" DESC;

so how do i force django orm to wrappe the orderby query by the filter query !!
any suggestion will do
edit: guys i think you didnt understand the problem,
let's say that we have this queryset
queryset = [
('john',"02-23-2020",type2),
('sarah',"02-03-2020",type1),
('joe',"01-11-2020",type2),
('john',"02-25-2020",type1),
('joe',"02-28-2020",type1)
]

when i first do the distinct orderby query the result will be
queryset = [
('john',"02-25-2020",type1),
('sarah',"02-03-2020",type1),
('joe',"02-28-2020",type1)
]

and then, when i execute the filter for example:
queryset = Form.objects.order_by('user','-created_at').distinct('user')
qs = queryset.filter(type=type2)

the result will be
queryset = [
('john',"02-23-2020",type2),
('joe',"01-11-2020",type2)
]

although the result should an empty queryset !!

A: You can create a subquery which contains the latest Form per user and then filter by this subquery to get what you want
forms = Form.objects.filter(
    id__in=Form.objects.order_by('user','-created_at').distinct('user').values('id')
).filter(**query)

MySQL is usually pretty bad at processing subqueries, it may perform better if you evaluate the subquery and pass the result if you're using MySQL. PostgreSQL is much better at handling subqueries and should be fine


text:
Q: Enable MsSQL PDO driver on LAMP w/ PHP5.3.6 I've been googling and searching SO for the better part of an hour, and fail to find a good answer. I'm a server admin noob here, so I'm sure this is not too difficult, but I sure don't know what to do.
Info:
Running PHP5.3.6 on an Apache server, using WHM/cPanel as the server admin GUI
I'm trying to connect to a client's MsSQL database, and alas, get the following error:
Fatal error: Call to undefined function mssql_connect()

So I start googling, see that perhaps that's not the best function to use anyway. Alright, so I look at PHPinfo for PDO support:
PDO drivers     sqlite, sqlite2, mysql

How on earth do I get mssql to show up in that list, so I can do something like the following:
$dbh = new PDO("mssql:host=host.name;dbname=name", 'user', 'pass');

I can't seem to google my way out of this one. Any thoughts?

A: You can uncomment the "extension=php_pdo_mssql.dll" line in php.ini if you have access to it.
If it still doesn't work, you might want to try this (once again, only if you have access to it):

ntwdblib.dll - The most common issue is that you do not have the
  ntwdblib.dll file installed in your PHP directory (where php.exe is,
  or sometimes placing it in the ext directory works as well). This
  library can be found with your Enterprise Manager dll's or in your SQL
  servers system32 folder. It's generally best to take the file from the
  server where SQL Server is installed -quoted from
  http://www.helpspot.com/helpdesk/index.php?pg=kb.page&id=13

If you are doing this on some kind of rented hosting (IE: Shared Hosting) you may need to contact the support from the hosting provider to get them to enable it if you can't get it to work.
http://us.php.net/mssql also has a lot of information. The installation is what I just stated above, but the user comments address a lot of more unique situations and provide more detail.


text:
Q: MySQL: Creating a dataset with multiple where clauses I have different MySQL SELECT queries, all with different where statements. These produce totals, unique totals, totals of a certain type.
So for-instance:
Loc    | total | unique | missing

London | 10 | 5 | 2

New York |20 |10 |5

Currently I am running each of these Select queries separately, but I'd rather run them all at once. Is there a way to do this in MySQL?
Something like:
SELECT
    Location
    Count(total)
    SELECT
        count(unique)
    FROM
        .. my tables..
    WHERE
        .. where clause for unique part ..
    GROUP BY
        unique
FROM
    .. my tables ..
WHERE
    .. where clause for total part ..
GROUP BY
    total

A: Perhaps what you want is a UNION
SELECT * from table where...
UNION
SELECT * from table where...

Obviously the columns returned from each query need to be the same.

A: I expect a subquery (or several) is in order.
select location, (select count(total)
                  from totalTable
                  where totalTable.location = locationTable.location) as total,
                 (select count(uniqe)
                  from uniqeTable
                  where uniqeTable.location = locationTable.location) as uniqe,
                 (select count(missing)
                  from missingTable
                  where missingTable.location = locationTable.location) as missing
from locationTable
where locationCriteria = searchCriteria

You can reference the same table in multiple subqueries, if necessary - just try to join them on ids, preferrably on something that's properly indexed.  Obviously the where clauses will have to be adjusted as necessary.

A: Thank you all. For anyone else trying to get to grips with this, my eventual solution was:
SELECT
   Geo,
   total,
   SUM(unique) as unique
FROM
   (SELECT
      Geo,
      COUNT(total) AS total,
      0 unique,
    FROM
      -- my tables --
    WHERE
      -- where clause for totals --
    GROUP BY
      Geo)
  UNION
    (SELECT
      Geo,
      0 total,
      COUNT(unique) AS unique,
     FROM
       -- my tables --
     WHERE
       -- where clause for unique --
     GROUP BY
       Geo)
) as tmptable
GROUP BY
   Geo


text:
Q: He intentado crear varios arrays para cargar diferentes elementos pero no hay manera No se como crear el array de imágenes en un widget reutilizable ni implementarlo en la clase. Es para que en cada Card se vea una imagen distinta. Y lo mismo con el título, descripción y 2 botones de ButtonBar, todo dentro de la Card me refiero. Es muy lioso para mi. Lo he intentado pero no hay manera.
Necesito ayuda con esto. Gracias.

A: primero que todo te recomendaría entregar un poco mas de información acerca de la duda que tengas. Por lo que se entiende, deberias de construir un array de mapas para asi procesarlo en un for in, de esta forma podria hacer lo de a continuacion. espero te sirva.
@override
Widget build(BuildContext context) {
final imagenes = [];
return Scaffold(
  body: ListView(
    children: [
      for (var imagen in imagenes)
        llamarImagenes(imagen),
    ],
  ),
);
}

Widget llamarImagenes(imagen) {
  return Card(
    margin: const EdgeInsets.all(5),
    child: Column(
      children: [
        Text(imagen.titulo),
        Container(
          padding: const EdgeInsets.all(5),
          child: Image(image: imagen.url),
        ),
        Text(imagen.descripcion),
      ],
    ),
  );
}


text:
Q: How to scroll to a particular section of the data fetched from an API while filtering the data on some parameter? I am calling an API from a server, and I am getting this as a response. A part of the data I am getting -
{
    "id": 322854,
    "date": "2022-09-20T18:00:00+00:00",
    "time": "18:00",
    "timestamp": 1663696800,
    "timezone": "UTC",
    "stage": null,
    "week": null,
    "status": {
        "long": "Game Finished",
        "short": "FT",
        "timer": null
    },
    "league": {
        "id": 9,
        "name": "French Cup",
        "type": "cup",
        "season": 2022,
        "logo": "https://media-2.api-sports.io/basketball/leagues/9.png"
    },
    "country": {
        "id": 4,
        "name": "France",
        "code": "FR",
        "flag": "https://media-2.api-sports.io/flags/fr.svg"
    },
    "teams": {
        "home": {
            "id": 22,
            "name": "Boulazac",
            "logo": "https://media-2.api-sports.io/basketball/teams/22.png"
        },
        "away": {
            "id": 2294,
            "name": "CEP Lorient",
            "logo": "https://media-2.api-sports.io/basketball/teams/2294.png"
        }
    },
    "scores": {
        "home": {
            "quarter_1": 16,
            "quarter_2": 12,
            "quarter_3": 21,
            "quarter_4": 26,
            "over_time": null,
            "total": 75
        },
        "away": {
            "quarter_1": 9,
            "quarter_2": 16,
            "quarter_3": 19,
            "quarter_4": 23,
            "over_time": null,
            "total": 67
        }
    }
}
{
    "id": 322854,
    "date": "2022-09-20T18:00:00+00:00",
    "time": "18:00",
    "timestamp": 1663696800,
    "timezone": "UTC",
    "stage": null,
    "week": null,
    "status": {
        "long": "Game Not Started",
        "short": "NS",
        "timer": null
    },
    "league": {
        "id": 9,
        "name": "French Cup",
        "type": "cup",
        "season": 2022,
        "logo": "https://media-2.api-sports.io/basketball/leagues/9.png"
    },
    "country": {
        "id": 4,
        "name": "France",
        "code": "FR",
        "flag": "https://media-2.api-sports.io/flags/fr.svg"
    },
    "teams": {
        "home": {
            "id": 22,
            "name": "Boulazac",
            "logo": "https://media-2.api-sports.io/basketball/teams/22.png"
        },
        "away": {
            "id": 2294,
            "name": "CEP Lorient",
            "logo": "https://media-2.api-sports.io/basketball/teams/2294.png"
        }
    },
    "scores": {
        "home": {
            "quarter_1": 16,
            "quarter_2": 12,
            "quarter_3": 21,
            "quarter_4": 26,
            "over_time": null,
            "total": 75
        },
        "away": {
            "quarter_1": 9,
            "quarter_2": 16,
            "quarter_3": 19,
            "quarter_4": 23,
            "over_time": null,
            "total": 67
        }
    }
}

There are a bunch of such objects in an array each having a different fixture. As you can see that status?.short === "NS" in one while the other is status?.short === "FT". Now, I want to filter the data using these properties.

Fixtures

        {fixtures.map((fixture) => (

              ......

          ))}

I want the data to be displayed in such a manner that when the user browse to that page and the API is being fetched, eventhough the entire data (fixtures) is being displayed in the page. I want the fixtures that have not yet started, i.e has the property of status?.short === "NS", to be displayed in the window that is visible to the user. And the rest data can be acquired by either scrolling up, which will have the fixtures that have been completed, or by scrolling down which will have the fixtures that have not yet been started.
If, I am unable to understand what I want properly, then you can check out this page . This is exactly what I am planning to achieve.


text:
Q: Fwrite solution rewrite PHP So.. i have problems with this code :
$filename = "info.txt";
$tex = $_POST['Name'];
$text = $tex . $_POST['Surname'];
$fp = fopen ($filename, "w");
if ($fp) {
fwrite ($fp, $text);
fclose ($fp);

It saves ONLY 1 name & surname. after another person submits his info, previous information is lost.
Is it possible to save all information?

A: You have to change the mode for fopen :
change 'w' to 'a' (a for append)
You'll find more information about each mode right here:
http://us2.php.net/manual/en/function.fopen.php#refsect1-function.fopen-parameters


text:
Q: Unable to view/customize Entities when change the language other than the base language in MS Dynamics CRM 2011 I am unable to customize/view the entities when I change the Microsoft Dynamics CRM 2011 language other than the base language. Any guidance to fix this issue? Thanks!

A: You can customize Dynamics CRM (create/modify entities, attributes, system views, ...) only using the base language.
There are no fix for this issue.

A: You can partly work with customization and your local language by first opening the customization page or the form editor using the base language and then changing to your local language.


text:
Q: Laravel, table doesn't exist В базе данных land есть таблицы peoples и pages.
Также есть модели People и Page.
People.php
class People extends Model
{
//    protected $table = 'peoples';
}
...

Page.php
class Page extends Model
{
    //
}

В контроллере пытаюсь показать все записи через модели People и Page,
маршрут
Route::get('/', ['as'=>'home','uses'=>'IndexController@show']);

контроллер
class IndexController extends Controller
{
    public function show() {
        $pages = Page::all();
        dump($pages);

        $people = People::all();
        dump($people);
    }
}

но записи из таблицы pages нормально отображаются с помощью dump, а записи из таблицы peoples не отображаются, выдаёт ошибку:
Base table or view not found: 1146 Table 'land.people' doesn't exist (SQL: select * frompeople)
Если в модели People добавить protected $table = 'peoples'; то ошибка пропадает, но хотелось-бы понять, из-за чего ошибка, две модели практически идентичны.
Почему в модели people появляется ошибка?

A: Так происходит, потому что правила создания таблиц и моделей в laravel следующие:
Модель - ед.ч
Таблица - мн.ч
Если углубиться в изучение англ языка и попытаться понять причину, то можно найти, что
Page - страница (ед.ч), Pages (мн.ч) - страницы (ларавель приводит page во мн.ч)
people - люди (мн.ч хотя по правилам должно быть ед.ч), а peoples - НАРОД (это не является множественным числом от слова people!).
В результате laravel оставляет people так как есть так как оно уже является мн.ч! и ищет land.people в Вашей БД. Слово person (ед.ч) - people (мн.ч) <- данное преобразование является верным!

A: class People extends Model
{
//    protected $table = 'peoples';
}

По умолчанию в фреймворках предусмотрено, что если вы не указываете в экземпляре класса свойство, или метод, описывающий имя таблицы, которую использует данный класс - то автоматически берет имя таблицы равное названию класса, в вашем случае people. Из этого выходит что вы зря закомментировали строчку, т.к. она определяет с какой таблицей вам работать. Есть два варианта решения вашей проблемы:

*

*Переименовать класс People в Peoples - плохое решение, т.к. лучше задавать названия моделей и соответсвующих таблиц в единственном числе

*Переименовать название таблицы, вместо peoples в people
А если быть еще честнее, то People - это и есть "Люди", поэтому слова Peoples просто не существует :)


text:
Q: How do the space helmets in The Expanse attach to the suits? I'm specifically referring to the TV Show, but not sure if the workings of the space suits and helmets are mentioned in the books.
I've been rewatching the TV series again and wondered how the helmets work. There doesn't seem to be any sort of attachments that allow the helmet to connect securely to the space suit/VAC suit (mainly referring to the Belter suits). The helmets just seem to be slipped in over the head, with no pressurised seal around the neck area.

A: The books themselves are extremely vague on the subject. Typically the act of removing (or opening) a helmet is described simply as "he undid his helmet seals " (Leviathan Wakes) or "he fumbled with the helmet's seals until he managed to pop off the visor" (Leviathan Falls). So there is no real clue if the seals are mechanical, electrical, or something else.
More information is available from the TV series. Belters commonly have a scar around their neck where the helmet joins to the spacesuit, and many of them cover them up with tattoos. The origin of these scars is explained by Dawes in season 1, episode 6: ""The old EVA helmets used to burn like that... The contacts would cook your skin."
With large electrical currents running through the seals it seems likely, although I don't believe it is stated explicitly, that the seal is made electromagnetically. This is consistent with the book description too.


text:
Q: Flutter - how to change textcolor in search delegate class? I managed to change the hintStyle-color

@override
ThemeData appBarTheme(BuildContext context) {
  return ThemeData(
    primaryColor: kPrimaryColor,
    primaryIconTheme: IconThemeData(
      color: Colors.white,
    ),
    inputDecorationTheme: InputDecorationTheme(
      hintStyle:
        Theme.of(context).textTheme.title.copyWith(color: Colors.white),
    ),
  );
}

But if i type something into the appbar searchfield, the color is still black...

How can I properly change the textcolor in the SearchDelegate class?

A: Using SearchDelegate you can customize both, Search's text hint value and color as well as query's color and size. To achieve this:
Search's text hint value --> you can override searchFieldLabel which is a String.
@override
String get searchFieldLabel => 'Your Custom Hint Text...';

Search's color --> you can override with hintColor property of the Theme class:
@override
  ThemeData appBarTheme(BuildContext context) {
    return Theme.of(context).copyWith(
      hintColor: Colors.white,
    );
  }

Query's text color and size -->  you need to override delegate's appBarTheme method and change what you need. To change query's text color, set the textTheme of headline6:
@override
ThemeData appBarTheme(BuildContext context) {
assert(context != null);
final ThemeData theme = Theme.of(context).copyWith(
  textTheme: TextTheme(
    headline6: TextStyle(
      color: Colors.white,
      fontSize: 18.0,
    ),
  ),
);
assert(theme != null);
return theme;
}

A: Change the headline6 text style in your app ThemeData :
MaterialApp(
      theme: ThemeData(
      textTheme: TextTheme(
          headline6: TextStyle(color: 'Your Prefered Color'))
      ),
      home: Home()
    );

A: This is how I am theming search delegate:
  @override
  ThemeData appBarTheme(BuildContext context) {
    return Theme.of(context).copyWith(
      inputDecorationTheme: searchFieldDecorationTheme,
      textTheme: Theme.of(context).textTheme.copyWith(
        headline6: TextStyle(color: Colors.white),
      ),
    );
  }

I copy global textTheme styles, and override only specific headline.
For more search styling (like hint color, search input size, input underline etc.), inputDecorationTheme is used.

A: With reference to the discussion in the comments of the question,  appBarTheme's  textTheme property allows changing the color.
example code credit @Matthias
Code:
textTheme: TextTheme(title: TextStyle( color: Colors.white, fontSize: 18,),),

A: All these answers regarding textTheme property affect the Text widget in other parts of the search page. So you would end up with somewhat transparent text in light theme because the text color has blended with the background.
So it is an incomplete solution

A: I added the hintColor:Colors.white line and it worked for me.
@override
ThemeData appBarTheme(BuildContext context) {
final ThemeData theme = Theme.of(context);
return theme.copyWith(
  primaryColor: Colors.blue,
  primaryIconTheme: theme.primaryIconTheme.copyWith(color: Colors.white),
  hintColor: Colors.white,

  textTheme: TextTheme(
    headline6: TextStyle(color: Colors.white,
    fontSize: 18)

  )
);


text:
Q: putc implemented as Macro ic C++? I know Macro implementation of putc() in C, but is it same in C++?

A: It will depend on your implementation of cstdio. In most cases this is really just a wrapper around stdio.h, with wrappers declared inside the std namespace, and the C and C++ compilers share the same standard library for C functions. For example, VS2010 uses stdio.h for C++, in which putc is implemented as both a macro and a function, depending on environment and other compile-time definitions.

A: Which version of C++?  C++83 (1983)?  C++98 (1998)?  C++11 (2011)?
The C++98 and C++11 Specifications rely on the ISO C specifications for C Library functions, and do not put additional implementation constraints on them, other than trivial ones like renaming stdio.h to cstdio.h and allowing inclusion without the dot-h suffix.
See: C++98 Specification
See: C++11 Specification
Look in cstdio.h if you are interested in your particular compiler.
However, if we dig deeper and take a look at the ISO C standard: "ISO/IEC 9899:1990" (C89/C90), well, we find that it is unavailable for free viewing on the web (not even the final draft standard), so moving on to C99 (NOT ISO C), you find...
...that C99 (Not "ISO C") says putc() MAY be implemented as a macro,
See: C99 Specification
So if you are really developing in Obj-C++ (which uses C99), then C99 is the relevant specification to consider, not ISO C (C90).  Also, since C99 lets the compiler writer decide whether to make putc() a macro or not, you should consider it an open possibility, and decide whether you really care to know about the C90 (ISO C) spec which is becoming obsolete (now that even C11 (2011) is out.)

A: Yes it is.  Both C and C++ use <stdio.h> which has the same scheme in all implementations that I know of.


text:
Q: Quicksort (Random Pivot) code not sorting correctly Java The code is a quicksort algorithm with a random pivot. It is not sorting the random array completely; I can't figure out why. The error seems to be with the bounds of the recursive calls and swapping.
    public static <E extends Comparable<E>> void quickerSort(ArrayList<E>         input, int lower, int higher){
            int first = lower;
            int last = higher;
            if (lower >= higher)
            return;
        //generates the random pivot
            int pivot = rand.nextInt(higher-lower+1) + lower;

        //moves the pivot to the beginning of the list

            E temp = input.get(first);
            input.set(first, input.get(pivot));
            input.set(pivot, temp);
            pivot = first;
            first++;

      //if the values on the left side of the array are less than the
      //value of the pivot, first is incremented (first part of loop) until
      //a greater value is reached

      //if the values on the right side of the array are greater than the
      //value of the pivot, last is incremented until a lesser value is reached

            while (first < last){
                  while (input.get(first).compareTo(input.get(pivot)) <= 0 && first < last){
                         first++;
            }
                  while(input.get(last).compareTo(input.get(pivot)) > 0 && last >= first){
                         last--;
            }

       //switches the two values reached through the while loops
            if (first < last){
                temp = input.get(first);
                input.set(first, input.get(last));
                input.set(last, temp);
            }
        }

     //moves the pivot to where first is
        temp = input.get(first-1);
        input.set(first-1, input.get(pivot));
        input.set(pivot, temp);

     //calls the method recursively
        if (lower < first-1){
            quickerSort(input,lower,first-1);
        }
        if (first < higher){
            quickerSort(input,first,higher);

        }
    }

//implementing method
public static void testQuickSort(){

      //creates a random list of integers to be sorted and prints it
        ArrayList<Integer> list = new ArrayList<Integer>();
        Random rand = new Random();
        for (int i = 0; i <= 19; i++){
            list.add(rand.nextInt(100));
            System.out.print(list.get(i)+" ");
    }
      //calls quicksort and then prints the sorted array
        System.out.println();
        Assignment2.quickSort(list);
        for (int i = 0; i <= 19; i++){
            System.out.print(list.get(i)+" ");
    }
    }

A: Your code would not work for a simple input, {6, 0}, since your first and last will both point to the second element, therefore, 6 and 0 never get swapped.
I modified your code a little bit and it worked. I used variable names which make more sense here, but the logic is the same.
public static <E extends Comparable<E>> void quickSort(ArrayList<E> input, int low, int high) {
    if (low >= high)
        return;

    // generates the random pivot
    int pivotIndex = new Random().nextInt(high - low + 1) + low;

    E pivot = input.get(pivotIndex);

    // moves the pivot to the beginning of the list
    Collections.swap(input, pivotIndex, low);

    int i = low;
    int j = high;

    // if the values on the left side of the array are less than the
    // value of the pivot, first is incremented (first part of loop) until
    // a greater value is reached

    // if the values on the right side of the array are greater than the
    // value of the pivot, last is incremented until a lesser value is
    // reached

    while (i <= j) {
        while (input.get(i).compareTo(pivot) <= 0 && i < j) {
            i++;
        }
        while (input.get(j).compareTo(pivot) > 0 && j >= i) {
            j--;
        }

        // break here when two pointers meet since the pivot position has been found
        if (i >= j)
            break;

        // switches the two values reached through the while loops
        Collections.swap(input, i, j);
    }

    // moves the pivot to where j is
    Collections.swap(input, low, j);

    // calls the method recursively
    quickSort(input, low, j - 1);

    quickSort(input, j + 1, high);

}


text:
Q: What will be happen if you dynamically allocates memory for one object of the class as an argument? class Example
{
  private:
   Example* pointer;
   Example* pointer2;
  public:
   Example();
   void setPointer2(Example* object);
};

Example::Example()
{
  pointer = new Example();
}

void Example::setPointer2(Example* object)
{
  this->pointer2 = object;
}

int main()
{
  Example object;
  object.setPointer2(new Example());

  return 0;
}

Delete is not important. I just want to know what is the differences between this two object which is adresses holding by pointer and pointer2. Are they differently allocated? The actual question is, does it matter where to use the "new" operator?

A: A major problem you have in your code is infinite recursion! The constructor you have defined:
Example::Example()
{
  pointer = new Example();
}

creates a new object of its own type. This will call the constructor (again), and that call will call the constructor (again and again...)
But, other than that issue, it doesn't really matter whether you create a new object by directly assigning its address to pointer or if you create the object elsewhere and then assign its address (later) to pointer2. Both will point to an object of the class.


text:
Q: returning component inside function not working I've a component which i'm rendering by considering some conditions. It's done as follows
const Test = () => {
    return

            No internet connection. Please check your connection settings and try again

}

function checkInternetConnection(){

    isOnline().then(online => {

       if(online === true){

           console.log("Came in here")

            return <Test/>

        }

    });
}

Then i'm calling my function as follows
const App = () => (

        {checkInternetConnection()}
);

But the issue is eventhough i'm getting the console log inside checkInternetConnection function, the returned component is not appearing. What can be cause of this?

A: Your <Test/> is being returned by the then callback function, not your checkInternetConnection function. Because you are conditionally rendering based on some asynchronous operation, you need to take a different approach in order for your component to update correctly.
One idea is to turn your stateless component into a stateful component by making it a class, and calling setState when your promise resolves:
import React from 'react';

class App extends React.Component {

    constructor(props) {
        super(props);
        this.state = {
            isOnline: false // set initial state to false
        };
    }

    componentDidMount() {
        isOnline().then(online => {
            this.setState({
                isOnline: true; // call setState to update state and rerender App
            });
        });
    }

    render() { // use inline expression to conditionally show <Test/> if isOnline is true

        return (

              { this.state.isOnline && <Test /> }

        );
    }
}

A: Since isOnline() has a .then() clause I assume it is an asynchronous Promise?
If that is the case, then that is your culprit. The component will not re-render when the promise returns as React only renders when state changes, which is not the case here.
To get the behavior you describe do the rendering of the Test component based on a state variable and set it in your .then() when the promise returns.


text:
Q: Transform an iterator on an unordered_map with pointer value type to an iterator on the same map with const reference value type I have the following class :
#include <unordered_map>
#include <memory>

class Node {
public:
    typedef std::unique_ptr<Node> ptr_type;
    typedef std::unordered_map<char, ptr_type> map_type;

    typedef /**???**/ const_iterator;

    const_iterator begin() const;
    const_iterator end() const;

private:
    map_type _children;
};

As you can see, I want a way fo a user of this class to iterate over elements of _children without being able to modify them. That is why I want to create an iterator that point to elements of type pair<char, const Node&> instead of pair<char, ptr_type>.
Creating a base iterator class seems a little too complicated for the task at hand. I have taken a look at boost iterator, I think transform_iterator may be the way to go, but I have not yet found how to make it work.
While I'm at it, does anyone know where I can find examples of the different examples of iterators defined in boost-iterators ? There is only one example in the doc for each type, and they do not always fit my needs (I'm new to this library, I may have missed something obvious).
UPDATE: Here is my attempt at using boost::transform_iterator
class Node {
public:
    typedef std::unique_ptr<Node> ptr_type;
    typedef std::unordered_map<char, ptr_type> map_type;

    struct Transformer {
        std::pair<char, const Node&> operator()(const std::pair<char, ptr_type> &p) const {
            return std::pair<char, const Node&>(p.first, *p.second);
        }
    };

    typedef boost::transform_iterator<Transformer, map_type::const_iterator, std::pair<char, const Node&>&, std::pair<char, const Node&>> const_iterator;

    const_iterator begin() const {
        return boost::make_transform_iterator<Transformer, map_type::const_iterator>(_children.begin(), Transformer());
    }
    const_iterator end() const {
        return boost::make_transform_iterator<Transformer, map_type::const_iterator>(_children.end(), Transformer());
    }

private:
    map_type _children;
};

It unfortunately does not compile, and gives the following error:
error: no type named 'type' in 'boost::mpl::eval_if<boost::is_same<boost::iterators::use_default, boost::iterators::use_default>, boost::result_of<const Node::Transformer(const std::pair<const char, std::unique_ptr<Node> >&)>, boost::mpl::identity<boost::iterators::use_default> >::f_ {aka struct boost::result_of<const Node::Transformer(const std::pair<const char, std::unique_ptr<Node> >&)>}'
     typedef typename f_::type type;

A: If use of boost-iterator is not mandatory, you can write your own iterator. I'm posting one, which satisfies ForwardIterator. You can expand it to BidirectionalIterator trivially (it may be a bit tedious, however).
Before posting it, I'm afraid I couldn't fulfill your reqirement (aside from use of boost-iterator); std::pair<char, const Node*> is used instead of std::pair<char, const Node&> because the latter prohibits copying. Maybe this is what prevented you from compiling your boost::transform_iterator example (I'm not certain; I'm not so familiar with boost-iterator).
Anyway, here is the code.cpp (125 lines long). main function for testing included:
#include <unordered_map>
#include <memory>

class Node;

template <class Map>
class MyIterator {
public:
    // iterator member typedefs
    using iterator_category = std::forward_iterator_tag;
    using value_type = std::pair<char, const Node*>;
    using difference_type = std::ptrdiff_t;
    using pointer = value_type*;
    using reference = value_type&;

    // typedef for underlying iterator
    using underlying_iterator = typename Map::const_iterator;

    // constructors
    // takes an underlying iterator
    explicit MyIterator(underlying_iterator it) : _it(std::move(it)) {}
    // default constructor; required by ForwardIterator
    MyIterator() = default;

    // dereference; required by InputIterator
    reference operator*() {
        update();
        return _p;
    }

    // dereference; required by InputIterator
    pointer operator->() {
        update();
        return &_p;
    }

    // increment; required by Iterator
    MyIterator<Map>& operator++() {
        ++_it;
        return *this;
    }

    // increment; required by InputIterator
    MyIterator<Map> operator++(int) {
        auto mit = *this;
        ++*this;
        return mit;
    }

    // comparison; required by EqualityComparable
    bool operator==(const MyIterator<Map>& mit) const {
        return _it == mit._it;
    }

    // comparison; required by InputIterator
    bool operator!=(const MyIterator<Map>& mit) const {
        return !(*this == mit);
    }

private:
    // this method must be called at dereference-time but not
    // traverse-time in order to prevent UB at a wrong time.
    void update() {
        _p = value_type{_it->first, &*(_it->second)};
    }

    // the underlying iterator that tracks the map
    underlying_iterator _it;
    // the pair of the desired type. without it, e.g. operator-> doesn't
    // work; it has to return a pointer, and the pointed must not be a
    // temporary object.
    value_type _p;
};

class Node {
public:
    typedef std::unique_ptr<Node> ptr_type;
    typedef std::unordered_map<char, ptr_type> map_type;

    typedef MyIterator<map_type> const_iterator;

    const_iterator begin() const {
        return const_iterator{_children.begin()};
    }
    const_iterator end() const {
        return const_iterator{_children.end()};
    }

private:
    map_type _children;

// additional members for testing purposes.
public:
    Node(std::string name) : _name(std::move(name)) {}
    Node(std::string name, map_type&& children) :
        _children(std::move(children)), _name(std::move(name)) {}
    std::string const& name() const {
        return _name;
    }
private:
    std::string _name;
};

#include <iostream>

// test program; construct a simple tree and print children.
int main() {
    typedef std::unique_ptr<Node> ptr_type;
    typedef std::unordered_map<char, ptr_type> map_type;

    ptr_type leaf1(new Node("leaf1"));
    ptr_type leaf2(new Node("leaf2"));
    ptr_type leaf3(new Node("leaf3"));
    map_type branch;
    branch.emplace('1', std::move(leaf1));
    branch.emplace('2', std::move(leaf2));
    branch.emplace('3', std::move(leaf3));
    Node parent("parent", std::move(branch));

    for (auto it = parent.begin(); it != parent.end(); ++it) {
        std::cout << it->first << ' ' << it->second->name() << '\n';
    }

    return 0;
};

compilation command:
g++ -std=c++11 -g -O2 -Wall code.cpp

my output:
3 leaf3
2 leaf2
1 leaf1

MyIterator is written as a template class so that when you want to change std::unordered_map to e.g. std::map, you don't need to modify MyIterator ;)
What complicates things is that the operator* must return a reference to an std::pair; it means that there must exist a (non-temporary) object of std::pair somewhere, otherwise that reference becomes a dangling reference. Same for the operator-> (replace "reference" by "pointer").
Here, MyIterator::_p is the std::pair whose reference is taken. This is copy-assigned upon updates, which std::pair<char, const Node&> (pair containing a reference) prohibits.
Alternatives to std::pair<char, const Node&> are std::pair<char, const Node*> or std::pair<char, std::reference_wrapper<const Node>>. Replace it->second->name() by it->second.get().name() if you choose to use std::reference_wrapper alternative.

A: I think this might be the reason boost::indirect_iterator exists. Adapting an example from the boost documentation on a (trivial) map<char, char *>:
#include <iostream>
#include <map>
#include <boost/iterator/indirect_iterator.hpp>

int main() {
    char characters[] = "abcdefg";
    size_t ncharacters = sizeof characters - 1;
    char *charptr[ncharacters];

    for (size_t i = 0; i < ncharacters; ++i) {
        charptr[i] = &characters[i];
    }

    std::map <char, char *> map1;
    for (size_t i = 0; i < ncharacters; ++i) {
        map1[characters[i]] = charptr[i]; /* Trivial, just to demonstrate */
    }

    boost::indirect_iterator<char * const*, char const> const_indirect_first(charptr),
                                                        const_indirect_last(charptr + ncharacters);

    std::copy(const_indirect_first, const_indirect_last, std::ostream_iterator<char>(std::cout, " "));
    std::cout << std::endl;

    return 0;
}


text:
Q: DateTimePicker Should only show Current Date
Possible Duplicate:
Limiting the dates within a C# win form DateTimePicker

in C#, is it possible to Only Set the DateTimePicker to the current date only? the users cannot select back to a previous or future dates. The DateTimePicker will only show or have the current Date.

A: You should be able to do that setting the MinDate and MaxDate properties.
 dateTimePicker1.MinDate = dateTimePicker1.MaxDate = DateTime.Now;

According to some, this should actually throw a DoesntMakeSenseException , but...  maybe it should be reported as a bug...


text:
Q: Como saber o último fim de semana de um mês em LUA Como obter o último fim de semana do mês de Março, para alterar a sua hora para o horário de verão.
Código paraidentificar se é o mês de Março e se é um domingo.
month_now=os.date("%m")
week_day=os.date("%w")
if week_day=="7" then
  print("domingo")
end
if month_now=="03" then
  print("Março")
end

A: Sem entrar no mérito do horário de verão, a função abaixo calcula o dia do último sábado de março de um dado ano.
function last(y)
    local t={ day=31, month=3, year=y }
    local w=os.date("*t",os.time(t)).wday
    return 31-(w%7)
end


text:
Q: Laravel 5.5 custom exception handling I'm using Laravel 5.5 and am new to it. As concerns error handling, I found that Laravel has many facades and features built-in, however, I seem not to have wrapped my head around all the features it provides (to originally make my life easier).
What I want is that whenever an error occurs (i.e. exception's thrown), Laravel shall redirect the user to the previous page and display an error message (not the error itself, you don't want users to be able to see this in production; I thought of something like 'Error occurred').
I included a display for errors in all of my views, so I just need to pass (via POST I suppose) an array message with title and message, as well as style (using Bootstrap styles, e.g. danger, warning, success). Ideally, the exception is logged somewhere so I'm able to reproduce errors later on.
My current solution is devoid of Laravel's nice features since I just try-catch everywhere and redirect to a specific page (I've chosen to be 'the right one' for this error). Also, this oppresses the original error.
What is the best approach for my desire?

A: Have a look at Laravel's exception handler: https://laravel.com/docs/5.5/errors#the-exception-handler
You can achieve what you want by implementing custom render() method that would return a redirect response.

The render method is responsible for converting a given exception into an HTTP response that should be sent back to the browser.

A: This is my solution which excludes the validation and thus supports Laravel's built-in validation error, whereas every other error is differently displayed:
Log::error($exception->getMessage());
if($exception instanceof \Illuminate\Validation\ValidationException)
   return parent::render($request, $exception);

return redirect(URL::previous())->withErrors(['Error', 'Unknown Error']);

Thanks to @jedrzej.kurylo who posted a solution on where to start. The code above shall be used under /App/Exceptions/Handler.php, function render.


text:
Q: Way to store sequence in a Perl script What is the Best way to store sequence in a text file or some other way by Perl script. When I run the script for first time, I want the sequence to be 1 and for second time 2. I should also take care of contention when more than one Perl process access the file.
my $seqfile = "f";
my $fh = FileHandle->new($seqfile, O_RDONLY | O_CREAT);
flock($fh, LOCK_EX);
my $seq = $fh->getline;
$seq = 0 unless($seq);
$seq = $seq + 1;
flock($fh, LOCK_UN);

How to write the $seq back without losing the lock on the file?

A: like this:
my $seqfile = "f";
my $fh = FileHandle->new($seqfile, O_RDWR | O_CREAT);
flock($fh, LOCK_EX) or die; # alternatively do loop retrying...
my $seq = $fh->getline;
$seq = 0 unless($seq);
$seq = $seq + 1;
seek ($fh, 0, SEEK_SET);
print $fh $seq;
close ($fh);

Note that close($fh) will take care of flushing buffered data to file as well as releasing lock.