text:
Q: If the Triwizard Tournament was so dangerous, why risk more people in the underwater task? The Triwizard Tournament was dangerous, hence the reason why it was cancelled and not run for many years.
So why did the school use real students for bait? Could they not have used Transfigured objects to look like the students? I am assuming that Professor McGonagall and Dumbledore would have the required skill to do this.
Or they could have used Polyjuice Potion brewed by Professor Snape and then have teachers in the guise of the students to act as bait if they needed real people to save. This would have meant that experienced wizards might have been able to help stop a death that might have occurred.
It seem rather reckless to use real students for this task.

A: There were most likely several safety precautions involved, especially with the merpeople themselves.
Dumbledore, and the other teachers, likely had several safety precautions in places to prevent harm to any of the students, as we see Harry realising.

Harry's feeling of stupidity was growing. Now he was out of the water, it seemed perfectly clear that Dumbledore's safety precautions wouldn't have permitted the death of a hostage just because their champion hadn't turned up. Why hadn't he just grabbed Ron and gone? He would have been first back.
Harry Potter and the Goblet of Fire, Chapter 26, "The Second Task"

Ron also comes to pretty much the same conclusion before when Harry breaks through the water's surface with him and Gabrielle.

The crowd in the stands was making a great deal of noise; shouting and screaming, they all seemed to be on their feet; Harry had the impression they thought that Ron and the little girl might be dead, but they were wrong... both of them had opened their eyes; the girl looked scared and confused, but Ron merely expelled a great spout of water, blinked in the bright light, turned to Harry, and said, "Wet, this, isn't it?" Then he spotted Fleur's sister. "What did you bring her for?"
"Fleur didn't turn up, I couldn't leave her," Harry panted.
"Harry, you prat," said Ron, "you didn't take that song thing seriously, did you? Dumbledore wouldn't have let any of us drown!"
"The song said —"
"It was only to make sure you got back inside the time limit!" said Ron. "I hope you didn't waste time down there acting the hero!"
Harry Potter and the Goblet of Fire, Chapter 26, "The Second Task"

In fact Dumbledore speaks Mermish and was in conversation with the chief merperson after all the champions had reached the surface. It seems likely that they would have had some measures in place with the merpeople in case anything bad should happen.

Dumbledore was crouching at the water's edge, deep in conversation with what seemed to be the chief merperson, a particularly wild and ferocious-looking female. He was making the same sort of screechy noises that the merpeople made when they were above water; clearly, Dumbledore could speak Mermish. Finally he straightened up, turned to his fellow judges, and said, "A conference before we give the marks, I think."
Harry Potter and the Goblet of Fire, Chapter 26, "The Second Task"

In fact this seems all the more the case when we see them watching Harry as he rises to the surface and is struggling.

Merpeople were rising with him. He could see them swirling around him with ease, watching him struggle through the water. ... Would they pull him back down to the depths when the time was up? Did they perhaps eat humans? Harry's legs were seizing up with the effort to keep swimming; his shoulders were aching horribly with the effort of dragging Ron and the girl. ...
Harry Potter and the Goblet of Fire, Chapter 26, "The Second Task"

The merpeople were also heavily involved in the task and seem to know the rules of it, considering they wouldn't let Harry take more than one person.

Harry looked around. There was no sign of any of the other champions. What were they playing at? Why didn't they hurry up? He turned back to Hermione, raised the jagged rock, and began to hack at her bindings too —
At once, several pairs of strong gray hands seized him. Half a dozen mermen were pulling him away from Hermione, shaking their green-haired heads, and laughing.
"You take your own hostage," one of them said to him. "Leave the others..."
"No way!" said Harry furiously — but only two large bubbles came out.
"Your task is to retrieve your own friend... leave the others..."
Harry Potter and the Goblet of Fire, Chapter 26, "The Second Task"

A: The 'hostages' in the lake were never actually in any  real danger.
The hostages in the lake were never really in danger, they were actually quite safe. Both Hermione and Ron (when he wasn't making up things to sound impressive) said that when they were being prepared for the Second Task, Dumbledore put them into an enchanted sleep and they'd wake up when they were back above water. At no point were they actually in any danger.

"At first, he gave what seemed to be the truth; it tallied with Hermione's story, anyway – Dumbledore had put all the hostages into a bewitched sleep in Professor McGonagall's office, first assuring them that they would be quite safe, and would awake when they were back above the water." - Harry Potter and the Goblet of Fire, Chapter 27 (Padfoot Returns)

Dumbledore wasn't going to let innocent people who weren't even contestants in the Triwizard Tournament be in danger just so the champions would have a motivation for their task. The sleep they were in prevented them from drowning, and additionally, the merpeople were guarding them.

"Harry sped towards the hostages, half expecting the merpeople to lower their spears and charge at him, but they did nothing." - Harry Potter and the Goblet of Fire, Chapter 26 (The Second Task)

The merpeople were with the hostages the entire time they were underwater, and armed with spears, so if a threat other than drowning should arise, they'd be able to keep them safe if needed. Dumbledore was able to find out from them what happened with the champions under the water, so he can communicate with them and believes them to be trustworthy enough to trust their account.

"Mer-chieftainess Murcus has told us exactly what happened at the bottom of the lake, and we have therefore decided to award marks out of fifty for each of the champions, as follows …"  - Harry Potter and the Goblet of Fire, Chapter 26 (The Second Task)

Harry at first believed that the merpeople were a threat, but the evidence doesn't really support that. In fact it seems more likely that Dumbledore (as he can communicate with them) had them act as guardians of a sort - they refused to help Harry free his hostage or take more than one, but that seems likely to be because of the rules of the Tournament rather than malice. The hostages weren't in danger then - if there was a real danger then the merpeople would likely have acted differently. Considering Dumbledore's extreme anger at the Ministry placing Dementors at Hogwarts, it seems highly unlikely he'd be willing to leave people with creatures he didn't trust or thought evil.


text:
Q: Get the next (not immediatelly) element in jquery I have a structure of my HTML code like this:

<fieldset>

        <input type="text" name="username" />

    <input type="button" name="next" value="Next" />
</fieldset>

<fieldset>

        <input type="password" name="password" />

    <input type="button" name="next" value="Next" />
</fieldset>

I wanted to do that if one user press enter and the field is selected, it press automatically the Next input, and I make this jQuery code:
$('input[name="username"], input[name="password"]').keypress(function (e) {
    var key = e.which;
    if (key == 13) {
        $('input[name="next"]').click();
        return false;
    }
});

It works, but only if the user press enter in the first step (in this case username). When the user try to press enter in the second step (in this case password) nothing happens because the code click the first input next of the page, in this case of the first step.
There's a manner with jQuery so the user can click the corresponding next button? I find the next function but it works only if it's the next sibling element.

A: thre are two button with name=next that is problem , because click enter on password it select first button which is name=next
Solution to problem is make use of next() function available in jquery libarary.
$( this ).parent().next('input[name="next"]').click();

another solution is make use of unique value for name vlaue,  because its bad idea to have two element with same name. try below  ex.
<fieldset>

        <input type="text" name="username" />

    <input type="button" name="usernamenext" value="Next" />
</fieldset>

<fieldset>

        <input type="password" name="password" />

    <input type="button" name="passwordnext" value="Next" />
</fieldset>

and you jquery be like
$('input[name="username"], input[name="password"]').keypress(function (e) {
    var key = e.which;
    if (key == 13) {
         $('input[name= "'+ $(this).attr('name') +'next"]').click();
        return false;
    }
});

making use of unique will end all issues ,

A: Use a traverse to target the specific instance and avoid clicking all of them
$(this).parent().next().click();

redpajama_set_name: RedPajamaStackExchange


text:
Q: Как сгруппировать элементы исходного списка в другой список со списками с заранее заданным количеством элементов? У меня есть список [элемент_1, элемент_2, .... элемент_N].
Как получить из исходного списка список, состоящий из нескольких списков, содержащих элементы исходного списка с заранее заданным количеством элементов?
Т.е. [элемент_1, элемент_2, .... элемент_N] -> [[элемент_1, элемент_2, .... элемент_K], [элемент_K+1, элемент_K+2, .... элемент_M], [элемент_M+1, элемент_M+2, элемент_N],].
Например, если есть исходный список с 86 элементами, надо что бы получился список с, например, 4 списками по 20 элементов и одного списка с 6 элементами (остаток).

A: In [36]: from funcy import partition, chunks # pip install funcy

In [37]: array = list(range(87))

In [38]: len(list(partition(20, array))) # Без остатков
Out[38]: 4

In [39]: result = list(chunks(20, array)) # С остатками

In [40]: result[-1]
Out[40]: [80, 81, 82, 83, 84, 85, 86]

Подробнее о том что такое funcy читайте тут.
Или можем реализовать по своему:
In [68]: def foo(array, count):
    ...:     result = []
    ...:     for i in range(count, len(array), count):
    ...:         result.append(array[len(sum(result, [])):i])
    ...:     if len(sum(result, [])) != len(array):
    ...:         result.append(array[len(sum(result, [])):])
    ...:     return result
    ...:

In [69]: result = foo(array, 20)

In [70]: len(result)
Out[70]: 5

In [71]: result[-1]
Out[71]: [80, 81, 82, 83, 84, 85, 86]

A: Можно воспользоваться простым list comprehension и индексированием:
In [55]: lst = list(range(1, 87))

In [56]: K = 20

In [57]: res = [lst[i:i+K] for i in range(0, len(lst), K)]

In [58]: print(res)
[[1, 2, 3, 4, 5, 6, 7, 8, 9, 10, 11, 12, 13, 14, 15, 16, 17, 18, 19, 20], [21, 22, 23, 24, 25, 26, 27, 28, 29, 30, 31, 32, 33, 34, 35, 36, 3
7, 38, 39, 40], [41, 42, 43, 44, 45, 46, 47, 48, 49, 50, 51, 52, 53, 54, 55, 56, 57, 58, 59, 60], [61, 62, 63, 64, 65, 66, 67, 68, 69, 70, 7
1, 72, 73, 74, 75, 76, 77, 78, 79, 80], [81, 82, 83, 84, 85, 86]]

Длины "суб-списков":
In [60]: [len(x) for x in res]
Out[60]: [20, 20, 20, 20, 6]


text:
Q: How to get YouTubeBaseActivity using YouTube API in Fragment? I've tried to play youtube video on android  with YouTubePlayerSupportFragment.
But in my case, I have to overlay play button on top of youtube player so Ive decided to use YouTubeBaseActivity.
My class is  extending BaseFragment  (Fragment) which means I can't extends YouTubeBaseActivity. ( can't extends 2 sigh...)

*

*Is there any method to get YouTubeBaseActivity without extending it?

*or can I get YouTubePlayerView like I've done with YouTubePlayerSupportFragment ( as below).

*If its not possible then can I display play button only on the player??
(Chromeless style doesn't show the play button)
public class StudentFragment extends BaseFragment{

...

public View onCreateView{

fragment1 = (YouTubeFragment) getChildFragmentManager().findFragmentById(R.id.fragment_youtube);

fragment1.setVideoId(movie_Id);

}

public class YouTubeFragment extends YouTubePlayerSupportFragment implements YouTubePlayer.OnInitializedListener{

public void setVideoId(final String videoId) {

mVideoId = videoId;

initialize(youtube_developer_key, this);

}

etc...

A:
I've tried to play youtube video on android with
  YouTubePlayerSupportFragment.
But in my case, I have to overlay play button on top of youtube player
  so Ive decided to use YouTubeBaseActivity.

It does not make any difference. You will experience the same behavior using the Activity and/or the Fragment.

My class is extending BaseFragment (Fragment) which means I can't
  extends YouTubeBaseActivity. ( can't extends 2 sigh...)

Even if it was possible, it would not make any sense to have a single class that extends both an Activity and a Fragment.

Is there any method to get YouTubeBaseActivity without extending it?
or can I get YouTubePlayerView like I've done with
  YouTubePlayerSupportFragment ( as below).

You have two simple options: either use the YouTubeBaseActivity + YouTubePlayerView, or go with the YouTubeSupportFragment.

If its not possible then can I display play button only on the
  player?? (Chromeless style doesn't show the play button)

And now we get to the point: you cannot place any View over the YouTube player, otherwise video playback will keep stopping every second or so.
You can try using the STANDARD style for the YouTubePlayer instance (which, if I am not mistaken, already shows a button over the video) and see if that suits your needs.


text:
Q: Xcode - use var from different ViewControllers I got 2 ViewControllers. One for my configuration and one for the test app i am building. So what i want is to set a Textfield in my konfigViewController and to use this value i type into this textfield, in my mainViewController.
So how do I get a connection between these different ViewControllers? i already tried to include the konfigViewController.h in the mainViewController.m.
In konfigViewController.h the textfield is declared. The Viewcontroller is also linked to the .h &.m file.


text:
Q: Subtori of restriction of scalars Let $E/F$ be a finite separable extension of a commutative field $F$. Let $T$ be the torus
${\rm Res}_{E/F}\; {\mathbb G}_m$, where ${\rm Res}$ is Weil's restriction of scalar. Is there a simple description of all subtori of $T$ ?


text:
Q: Simple JQuery slider not working properly I am new to jQuery and javascript and I am working on some animations to practice my new skills. The following code is a simple slider that cycles through 4 slides with setInterval() and can also be navigated on click. The slider works fine except for when the first or last slide is active and the buttons are clicked. In this case, the slider shows a blank slide before cycling back. I tried to manipulate the ul on click when the margin-left is equal to -2880px, without any success. Here is my code:

var i = 0;

$(document).ready(function() {
  setInterval(function() {
  $("#my-slider").animate({"margin-left": "-=720px"}, 1000, function(){
     i++;
     if( i === 4 ) {
          i = 0;
           $("#my-slider").css("margin-left", 0);
     }
     });
    }, 5000);
  })
  $(document).ready(function() {
$(".right").click(function() {
    $("#my-slider").animate({"margin-left": "-=720px"}, 1000);
});

$(".left").click(function() {
 $("#my-slider").animate({"margin-left": "+=720px"}, 1000);
   });
 });
.slider-wrapper {
 width: 50%;
 height: 400px;
 margin: 0 auto;
 overflow: hidden;
}

.slider-wrapper ul {
 list-style-type: none;
 width: 3600px;
 max-width: 3600px;
 height: 400px;
 padding: 0;
 margin: 0;
}

.slider-wrapper li {
 float: left;
 width: 720px;
 height: 400px;
}

#slide1 {
background: #04151F;
}

#slide2 {
 background: #183A37;
}

#slide3 {
 background: #EFD6AC;
}

#slide4 {
 background: #C44900;
}

#slide5 {
 background: #04151F;
}

.left, .right {
 font-size: 40px;
 z-index: 1;
 position: fixed;
 float: right;
 margin: -15% 0 0 0.5%;
 cursor: pointer;
 color: #FFF;
}

.right {
 margin-left: 47%;
}

←

→

Thank you for your help.

A: You need to use the code from your cycle for the buttons as well.
$(document).ready(function() {
$(".right").click(function() {
    $("#my-slider").animate({"margin-left": "-=720px"}, 1000, function(){
    i++;
        if( i === 4 ) {
          i = 0;
           $("#my-slider").css("margin-left", 0);
        }
  });
});

A: I Think it`s the simplest solution!

https://jsfiddle.net/nbLz6zzb/1/

var i = 0;

$(document).ready(function() {

  setInterval(function() {
  $("#my-slider").animate({"margin-left": "-=720px"}, 1000, function(){
        i++;
        if( i === 4 ) {
          i = 0;
           $("#my-slider").css("margin-left", 0);
        }
     });
    }, 5000);

/////////////////////////////////////

$(".right").click(function() {
    $("#my-slider").animate({"margin-left": "-=720px"}, 1000, function(){
        i++;
        if( i === 4 ) {
          i = 1;
           $("#my-slider").css("margin-left", 0);
        }
     });
});

$(".left").click(function() {

 if ( $("#my-slider").css("margin-left") <= '720px' && $("#my-slider").css("margin-left") >= '0px') {
  $("#my-slider").animate({"margin-left": "-2880px"}, 1000);
 } else {
  $("#my-slider").animate({"margin-left": "+=720px"}, 1000);
 }

   });

});
.slider-wrapper {
width: 50%;
height: 400px;
margin: 0 auto;
overflow: hidden;
}

.slider-wrapper ul {
list-style-type: none;
width: 3600px;
max-width: 3600px;
height: 400px;
padding: 0;
margin: 0;
}

.slider-wrapper li {
float: left;
width: 720px;
height: 400px;
}

#slide1 {
background: #04151F;
}

#slide2 {
background: #183A37;
}

#slide3 {
background: #EFD6AC;
}

#slide4 {
background: #C44900;
}

#slide5 {
background: #04151F;
}

.left, .right {
font-size: 40px;
z-index: 1;
position: fixed;
float: right;
margin: -15% 0 0 0.5%;
cursor: pointer;
color: #FFF;
}

.right {
margin-left: 47%;
}

←

→


text:
Q: Getting exception while passing specific parameters in struts2 xml Hi i am working on struts2, I am facing problem while passing specific parameters. My xml for controller is like below
<action name="summary/*/*" class="UserController" method="summary">
            <result>/view/user/Summary.jsp</result>
            <param name="type">{1}</param>
            <param name="user.loginName">{2}</param>
            <interceptor-ref name="caspianDefaultStack" />
        </action>

If i pass url like summary/profile/jhon It work fine but when i pass url like summary/profile/jhon.mickel (If second parameter contains ".")  the method summary is not called why it is behaving in a strange way and how can i resolve this??

A: Use regex to directly map the params in the wild-cards mapping. Something like this :
<action name="summary/{type}/{user.loginName}" class="UserController" method="summary">
            <result>/view/user/Summary.jsp</result>
            <interceptor-ref name="caspianDefaultStack" />
        </action>

If that still doesn't work, then use {FIELD_NAME:REGEX} format. See the docs for example.


text:
Q: any client to be able to decrypt a mesage but not to create an encrypted message I have an .Net Application and i want to this application which has some features. Depending client's domain and what features he wants i want to provide him a string which he will store it a file and will be accessible from the application.
I will create a second application which will get as parameters the domain and the features and it will produce the string.
Is there any way to encrypt this string with a key and my application (the first one mentioned)  to decrypt it?
I have in mind something like private/public key but reversing the logic. I mean, to encrypt the string from my second application wit the private key and the first application to decrypt it with the public key.
The purpose is the customer to not be able to change the string so that to change the available features.
PS i have an idea to use digital signature, but i dont know if i can have the public/private keys stored at xmlstrings. I think i have seen it somewhere (exporting/importing) but i am not sure

A: Yes, digital signatures are the correct tool to use for this.
Storing the keys is a minor implementation detail.  Typically, such keys are natively represented as binary strings, possibly in ASN.1 or a similar encoding.  If you need to store the keys in some format that cannot handle arbitrary binary data, you can always e.g. base64-encode them first.


text:
Q: AspNet Core How can I change MicrosoftAccountOptions/GoogleOptions/FacebookOptions/TwitterOptions in controller This's in Startup.cs ConfigureServices how I config the OAuth providers
services.AddAuthentication(options => {
                options.DefaultScheme = CookieAuthenticationDefaults.AuthenticationScheme;
                options.DefaultChallengeScheme = OpenIdConnectDefaults.AuthenticationScheme;
            })
            .AddFacebook(x => {
                x.AppId = "xxx";
                x.AppSecret = "xxx";
            })
            .AddTwitter(x => {
                x.ConsumerKey = "xxx";
                x.ConsumerSecret = "xxx";
            })
            .AddGoogle(x => {
                x.ClientId = "xxx";
                x.ClientSecret = "xxx";
            })
            .AddMicrosoftAccount(x => {
                x.ClientId = "xxx";
                x.ClientSecret = "xxx";
            })

Then, for some requirements, I need to update AppId/AppSecret in controller action, How I can do that?


text:
Q: Autofill for UITextField is broken In my sign up form in my app, the keyboard suggests an entry for my first name, last name, eventually a strong password, but not for my email address. I have content-type set to email in the storyboard and in code:

self.emailTxt.textContentType = .emailAddress

But no suggestion. You can see in the image below, the keyboard suggests the first and last name of the user, but for email it is blank.
In the next image I show that in signing up for sites on safari, it does suggest my email. Even moreso, it suggests to autofill the entire page:
What could I be missing?
EDIT: I created a github repo demonstrating the error. Every field should be auto-filled. What I am experiencing is that in this app, the email works but password doesn't suggest to create a new password. Nothing is working together.

A: So, the issue in general was that apple's autofill was having a difficult time determining if I was creating an account. From their documentation here:

By default, the system selects the a keyboard based on the input
  view's textContentType property; however, you can mix the input view's
  text content type and keyboard type to explicitly define the desired
  keyboard. For example, if your site uses email addresses as user
  names, set the input view's textContentType property to .username, and
  set the keyboardType property to .UIKeyboardType.emailAddress.

So, for the email address I set the content type to username and the keyboard type to email, and all is fixed.

A: Setting Content-type =  {Email Address} works for me. It should work.
Try delete current UITextField and do it again


text:
Q: Nested max-width and min-width divs I am trying to create the following layout.

I am trying to make yellow and red block fluid, while keeping the green and blue block max-width. See this fiddle.
When I try to expand the screen size green block cuts from rest of layout.
When I try to reduce the screen size the yellow block comes downs.
HTML code

A: Try like this: Demo
ADD this in your code:
* {
    -moz-box-sizing: border-box;
    -webkit-box-sizing: border-box;
    box-sizing: border-box;
}


text:
Q: Volume integral and divergence theorem Evaluate the integral
$$\int _V^{ }\:\underline∇·\underline r\:dV$$
where $V$ is the volume bounded by the surface $z=a^2-x^2-y^2$ (a paraboloid) and the plane $z=0$.
How do I get started on this problem? At the moment I have $\underline r=(x,y,a^2-x^2-y^2)$ so $\underline∇·\underline r=2$, and the limits of integration are $-a\le x \le a, -\sqrt{a^2-x^2}\le y \le \sqrt{a^2-x^2}, 0\le z \le a^2-x^2-y^2$. But I don't think this is the right approach. I am asked to compare the answer to the sum $\int _{S_C}\underline r·d\underline S\:+\int _{S_B}^{ }\:\underline r·d\underline S=\frac{3\pi a^4}{2}$ where $S_C$ is the part of the paraboloid for which $z\ge 0$ and $S_B$ is the circular base of the paraboloid, which satisfies $x^2+y^2=a^2$ with $z=0$.

A: $\underline r = (x, y, z)$ and not $(x,y,a^2-x^2-y^2)$.
$z = a^2 - x^2 - y^2$ only on the paraboloid surface.
$\nabla \cdot \underline r = 3$
In polar coordinates, $0 \leq z \leq a^2 - \rho^2, 0 \leq \rho \leq a$
So the volume integral is,
$ \displaystyle \int_0^{2\pi} \int_0^{a^2} \int_0^{\sqrt{a^2 - z}} 3~\rho~ d\rho~ dz~d\theta = \frac{3 \pi a^4}{2}$


text:
Q: Do/Undo using command pattern in Python I have read that using command pattern is one of the most popular ways to accomplish do/undo functionality. In fact, I have seen that it's possible to stack a bunch of actions and reverse them in order to reach a given state. However, I'm not quite sure how that can be done in Python and most of the tutorials I have read, dabble into concepts but don't show an actual implementation in Python.
Does anyone know how do/undo functionality work in Python?
For reference, this is my (naive and probably ridden with errors) code:
# command
class DrawCommand:
    def __init__(self, draw, point1, point2):
        self.draw = draw
        self.point1 = point1
        self.point2 = point2
    def execute_drawing(self):
        self.draw.execute(self.point1, self.point2)
    def execute_undrawing(self):
        self.draw.unexecute(self.point1, self.point2)
# invoker
class InvokeDrawALine:
    def command(self, command):
        self.command = command
    def click_to_draw(self):
        self.command.execute_drawing()
    def undo(self):
        self.command.execute_undrawing()
# receiver
class DrawALine:
    def execute(self, point1, point2):
        print("Draw a line from {} to {}".format(point1, point2))
    def unexecute(self, point1, point2):
        print("Erase a line from {} to {}".format(point1, point2))

instantiating as follows:
invoke_draw = InvokeDrawALine()
draw_a_line = DrawALine()
draw_command = DrawCommand(draw_a_line, 1, 2)
invoke_draw.command(draw_command)
invoke_draw.click_to_draw()
invoke_draw.undo()

output:
Draw a line from 1 to 2
Erase a line from 1 to 2

Obviously, this test doesn't allow stack several actions to undo. Maybe I'm completely mistaken so I would appreciate some help.

A: How I'd go about this
class Command(object):
    def execute(self, canvas):
         raise NotImplementedError

class DrawLineCommand(Command):
    def __init__(self, point1, point2):
        self._point1 = point1
        self._point2 = point2

    def execute(self, canvas):
        canvas.draw_line(self._point1, self._point2)

 class DrawCircleCommand(Command):
     def __init__(self, point, radius):
        self._point = point
        self._radius = radius

     def execute(self, canvas):
        canvas.draw_circle(self._point, self._radius)

class UndoHistory(object):
    def __init__(self, canvas):
        self._commands = []
        self.canvas = canvas

    def command(self, command):
        self._commands.append(command)
        command.execute(self.canvas)

    def undo(self):
        self._commands.pop() # throw away last command
        self.canvas.clear()
        for command self._commands:
            command.execute(self.canvas)

Some thoughts:

*

*Trying to undo an action can be hard. For example, how would you undraw a line? You'd need to recover what used to be under that line. A simpler approach is often to revert to a clean slate and then reapply all the commands.

*Each command should be contained in a single object. It should store all of the data neccesary for the command.

*In python you don't need to define the Command class. I do it to provide documentation for what methods I expect Command objects to implement.

*You may eventually get speed issues reapplying all the command for an undo. Optimization is left as an excersize for the reader.

A: Here is an implementation keeping the commands in a list.
# command
class DrawCommand:
    def __init__(self, draw, point1, point2):
        self.draw = draw
        self.point1 = point1
        self.point2 = point2
    def execute_drawing(self):
        self.draw.execute(self.point1, self.point2)
# invoker
class InvokeDrawLines:
    def __init__(self, data):
        self.commandlist = data
    def addcommand(self, command):
        self.commandlist.append(command)
    def draw(self):
        for cmd in self.commandlist:
            cmd.execute_drawing()
    def undocommand(self, command):
        self.commandlist.remove(command)

# receiver
class DrawALine:
    def execute(self, point1, point2):
        print("Draw a line from" , point1, point2)


text:
Q: fadein a DIV when another DIV is clicked then fadeout when DIV is clicked again I have a sliding panel on my page which brings out the navigation (www.helloarchie.blue). When the panel slides out, I'd like to fade in the content inside slowly, then fadeout the content when the user clicks the icon to close the panel. How would I do that?
CSS: (div I want to fadein/out)
.sb-slidebar nav { text-align: left; }

HTML:

 Home

About

Archives

Services

Contact me

HTML (this is the icon I want the user to click to open the panel and fadein/out the content)

A: Use jquery's .fadeToggle(), as in the example below. See the documentation for .fadeToggle() here.

$(document).ready(function() {
  $('#click-me').on('click', function() {
    $('#fade-me').fadeToggle();
  });
});
#fade-me {
  background-color: red;
  width: 100px;
  height: 100px;
  display: none;
}
#click-me {
  cursor: pointer;
}

Toggle Fade

So, applying to your code sample, you would want something like this:
$(document).ready(function() {
    $('.sb-toggle-right').on('click', function() {
        $('.sb-slidebar').fadeToggle();
    });
});

A: From looking at the classname you have used on div in question it looks like you're using a plugin to handle the sliding in/out of the panel? Without seeing the javascript you're using it's difficult to say exactly what you could do but I'd have thought if you can access the plugin's documentation you may be able to locate methods used to run functions at the beginning and end of the animation/slide. In these methods I would add/remove a classname of my own which handle the fade in and out of the div. It would look somehting like this:
Javascript:
onSlideStart: function() {
        $(this).removeClass('fade-me-in');
},
onSlideEnd: function() {
        $(this).addClass('fade-me-in');
}

CSS
div {
    opacity: 0;
}

div.fade-me-in {
    opacity: 1;
    -webkit-transition: opacity 0.3s;
    transition: opacity 0.3s;
}

I hope that helps, if not, post the javascript you're using and I may be able to help further.


text:
Q: Reference request Eigenspace decomposition Hodge Laplacian on forms on manifolds with boundary I know that on a connected, compact, oriented Riemannian manifold without boundary the Hodge Laplacian $\Delta_k=(d+\delta)^2$ (acting on $k$-forms) admits an orthogonal eigenspace decomomposition of $L^2\Lambda^k(M)$, consisting of smooth eigenforms, where all eigenvalues have finite multiplicity, are non-negative and only accumulate at infinity. A reference for this is for instance:
The Laplacian on a Riemannian manifold: An Introduction to Analysis on Manifolds (1997), Cambridge University Press. By Steven Rosenberg [Theorem $1.30$]
I was wondering whether the same holds true for compact manifolds with boundary, provided we impose some appropriate boundary conditions. Rosenberg deals first with the case of $0$-forms before proving the general result. He mentions after the $\Lambda^0(M)$ case, that we may allow boundary if we impose Dirichlet or Neumann boundary conditions. I also found references for this case. However he does not say anything about a similar result for general $k$-forms on manifolds with boundary.
So my question is, do we also have an orthogonal eigenspace decomposition of $L^2\Lambda^k(M)$ in the case of compact manifolds with boundary (under some appropriate boundary condtions, e.g. vanishing normal component)?
So far I was not able to find any reference for such a result. If anyone is aware of a paper or book dealing with this problem I would highly appretiate it.
Thanks in advance


text:
Q: upload .txt file into textarea in django? I'm new to Django. I've made textareas for a website, using the django forms widget.
I want to add a fileupload to be able to upload a .txt file that will be inserted into the text area. How do I go about it?
I've checked the documentation at https://docs.djangoproject.com/en/2.1/topics/http/file-uploads/
How do I incorporate this code within what I've already written?
forms.py
class HomeForm(forms.ModelForm):
    textInput = forms.CharField(required=True, widget=forms.Textarea(
        attrs={
            'class': 'form-control',
            'placeholder': 'Input text...',
            'id': 'input1'
        }
    ))

    class Meta:
        model = Post #import Post model from home models.py
        fields = {'textInput',} #comma required to ensure tuple capability

models.py
class Post(models.Model):
    post = models.CharField(max_length=1000)
    user = models.ForeignKey(User, on_delete=models.PROTECT) #default .CASCADE
    date = models.DateTimeField(auto_now=True) #data saved into db

views.py
class HomeView(TemplateView):
    template_name='home/home.html'

    def get(self, request):
        form = HomeForm

        posts = Post.objects.all()
        args = {'form': form, 'posts': posts}

        return render(request, self.template_name, args)

    def post(self, request):
        form = HomeForm(request.POST)
        if form.is_valid():
            post = form.save(commit=False) #saves data (thanks to the model form)
            #comit is false as object still needs to be modified
            post.user = request.user
            post.save()
            text = form.cleaned_data['textInput'] #anticipates SQL injection
            #return redirect('home:home')

        args = {'form': form, 'text': text}
        return render(request, self.template_name, args)

A: At first you should append forms.FileField to take ability to use Django framework uploading mechanism.
Any Django form has its lifecycle while request is processing. When user upload .txt file, you can catch this in save method like this:
class HomeForm(forms.ModelForm):
    ...
    text_file = forms.FileField()
    ...

    def save(self, commit=True):
        ...
        # check if text_file contains content
        text_file_data = self.cleaned_data.get("text_file")
        ...
        if text_file_content:
            # self.instance is instance of "Post" model
            self.instance.post = text_file_content
        ...
        return super().save(commit)


text:
Q: How can I use RTRIM or REPLACE when I know the length I want to trim but not what it may contain? I need to RTRIM the last 7 characters from a result set in an Oracle query. These 7 chars can be anything; spaces, alpha numeric etc... and I don't know the exact length of any value.
So for example I'd like to run something like this
 SELECT RTRIM (COl_A, (SELECT LENGTH (COL_A)-7) FROM TABLE_ONE;

or a replace equivalent
SELECT REPLACE(COL_A, (SELECT LENGTH (COL_A)-7 FROM TABLE_ONE),'');

Do I need to do something with SUBSTRING maybe?
I know how to remove/replace specific chars but I'm having trouble when dealing with unknown chars. I've seen a few examples of similar problems but they seem unnecessarily complicated... or does this require a more in depth solution than I think it should?
As always thanks in advance for advice or hints.

A: You are in search of the substr function.
select substr(col_a, 1, length(col_a) - 7) from table_one

A: Actually, the correct solution is:
select substr(col_a, 1, (case when length(col_a) < 7 then 0 else length(col_a) - 7 end) from table_one

To be general, you would want to take into account what happens when the length is less than 7.


text:
Q: What am I doing wrong with .blit() in Pygame? I've been attempting to learn Pygame recently but I'm having a bit of trouble. One thing is that I can't get an image to display, at all. I've tried lots of different methods but the closest I've got is getting this error message,

TypeError: argument 1 must be pygame.Surface, not function

when trying to use .blit(). I've seen the command used this way in a tutorial but for some reason it doesn't work for me. My code is below.
Python 3.8, Spyder, macOS 10.14.6
import pygame as pg
pg.init()

width = 800
height = 600

white = ((255, 255, 255))
purple = ((100, 0, 130))

screen = pg.display.set_mode((width, height))
pg.display.set_caption("Race Game:")
clock = pg.time.Clock()

car = pg.image.load("car.png")

def car(x, y):
    screen.blit(car, (x, y))

x = width * 0.45
y = height * 0.8

crashed = False
while not crashed:
    for event in pg.event.get():
        if event.type == pg.QUIT:
            crashed = True

    screen.fill(white)
    car(x, y)
    pg.display.update()
    clock.tick(60)

pg.quit()
quit

A: The pygame.Surface object and the function have the same name car:

car = pg.image.load("car.png")

def car(x, y):
   screen.blit(car, (x, y))

The function car covers the variable car, that causes the error. When you do  screen.blit(car, (x, y)) in the function car, then car refers to the function car rather than the pygame.Surface object car.
You have to use different names. For instance:
car_image = pg.image.load("car.png")

def car(x, y):
    screen.blit(car_image, (x, y))


text:
Q: how to manage multiple form templates in fuelphp Hello I just migrated from CI to Fuel.... I am using Fieldset class to auto generate form in the view.... The problem i am facing is I have multiple types of form templates i.e some of my models use twitter bootstrap horizontal inline form where as few models use custom templates... I am able to set single type of form template in form.php which i copy from fuel/core/config/form.php to fuel/app/config/form.php
Here is the sample return array for form template
return array(
// regular form definitions
'prep_value'                 => true,
'auto_id'                    => true,
'auto_id_prefix'             => 'form_',
'form_method'                => 'post',
'form_template'              => "\n\t\t{open}\n\t\t
\n{fields}\n\t\t
\n\t\t{close}\n",
'fieldset_template'          => "\n\t\t
{open}
\n{fields}

\n\t\t{close}\n",
'field_template'             => "\t\t
\n\t\t\t{label}{required}	\n\t\t\t{field} {description} {error_msg}	\n\t\t
\n",
'multi_field_template'       => "\t\t
\n\t\t\t{group_label}{required}	\n\t\t\t{fields}\n\t\t\t\t{field} {label}
\n{fields}{description}\t\t\t{error_msg}\n\t\t\t	\n\t\t
\n",
'error_template'             => '{error_msg}',
'group_label'                => '{label}',
'required_mark'              => '*',
'inline_errors'              => false,
'error_class'                => null,
'label_class'                => null,

// tabular form definitions
'tabular_form_template'      => "
{fields}
\n",
'tabular_field_template'     => "{field}",
'tabular_row_template'       => "
{fields}
\n",
'tabular_row_field_template' => "\t\t\t{label}{required} {field} {error_msg}	\n",
'tabular_delete_label'       => "Delete?",

);
I want multiple form templates like this so that i will be able to auto generate the form where it is needed using $fieldset->form()->build() function...
Is there any way to do this??

A: yes. try this:

forge($name = 'default', $config = array());

$article_form = Fieldset::forge('article',array(
// regular form definitions
'prep_value'                 => true,
'auto_id'                    => true,
'auto_id_prefix'             => 'form_',
'form_method'                => 'post',
'form_template'              => "\n\t\t{open}\n\t\t
\n{fields}\n\t\t
\n\t\t{close}\n",
'fieldset_template'          => "\n\t\t
{open}
\n{fields}

\n\t\t{close}\n",
'field_template'             => "\t\t
\n\t\t\t{label}{required}	\n\t\t\t{field} {description} {error_msg}	\n\t\t
\n",
'multi_field_template'       => "\t\t
\n\t\t\t{group_label}{required}	\n\t\t\t{fields}\n\t\t\t\t{field} {label}
\n{fields}{description}\t\t\t{error_msg}\n\t\t\t	\n\t\t
\n",
'error_template'             => '{error_msg}',
'group_label'                => '{label}',
'required_mark'              => '*',
'inline_errors'              => false,
'error_class'                => null,
'label_class'                => null,

// tabular form definitions
'tabular_form_template'      => "
{fields}
\n",
'tabular_field_template'     => "{field}",
'tabular_row_template'       => "
{fields}
\n",
'tabular_row_field_template' => "\t\t\t{label}{required} {field} {error_msg}	\n",
'tabular_delete_label'       => "Delete?",
));


text:
Q: If all html elements inside a whatever element are hidden, then hide a specific html element I have an issue where what I want is to check if all the tr elements with class="RateContainer" inside that div are hidden(display:none because of hide()). And if they are hidden pls select for example class="elementToHide" and hide it also:

What I have tried is this:
$(".panel-body.no-padding>table>tbody>tr").each(function () {
                    if ($(this).find(">table>tbody>tr:visible").length == 0) {
                        $('.elementToHide').hide();
                    }
                });

Also this:
$(".panel-body.no-padding").filter(function () {
     return $(this).find("tr:visible").length == 0;
  }).hide();

And this:
var elementsHidden = $(".panel-body.no-padding").not(function () {
      return ($(this).children(":visible").length > 0) ? false : true;
    });
$(".resultElementos").html(elementsHidden.length);
//And here them if length == 0 them take the bif father and hide him from the cops jeje

But I´m not able to hide it!!, do you know why??
Thank you (:


text:
Q: MVC 5, Web API And Owin Am I correct when I say, Web API can run on OWIN and MVC 5 cannot?
So in my project i still need my Global.asax with public class WebApiApplication : System.Web.HttpApplication
At the moment I have my owin Startup.cs which looks like this:
public void Configuration(IAppBuilder app)
{
    var httpConfig = new HttpConfiguration
    {

    };

    WebApiConfig.Register(httpConfig);

    app.UseWebApi(httpConfig);
    app.UseCors(CorsOptions.AllowAll);

    RouteConfig.RegisterRoutes(RouteTable.Routes);//MVC Routing
    BundleConfig.RegisterBundles(BundleTable.Bundles);
}

Is RouteConfig.RegisterRoutes(RouteTable.Routes) nough?
Whenever I browse to any MVC route I get a 404.

A: Yes, you're right, MVC 5 (based in ASP.NET 4) requires IIS, it can't self-host.  MVC 6 (based in ASP.NET 5, now called ASP.NET Core 1) doesn't have this limitation.  If you need self-hosting, start playing with ASP.NET Core 1 (it is incredibly awesome) or if you need RTM right now, use WebAPI.

A:
Am I correct when I say, Web API can run on OWIN and MVC 5 cannot?

Not clear what you're asking but OWIN is not server but it's a middleware which help injecting pipelines in order to pre-process requests in stages and it doesn't depend on WebAPI or MVC version but it depends if hosting server have OWIN specifications implemented.

Is RouteConfig.RegisterRoutes(RouteTable.Routes) enough?

yes this will work for Asp.net MVC but for web api you need to register the routes in separate configuration class. Usually the WebAPI configuration may look like as specified in default Asp.net WebAPI template(> vs2013)
public static class WebApiConfig
{
    public static void Register(HttpConfiguration config)
    {
        // Web API routes
        config.MapHttpAttributeRoutes();

        config.Routes.MapHttpRoute(
            name: "DefaultApi",
            routeTemplate: "api/{controller}/{id}",
            defaults: new { id = RouteParameter.Optional }
        );
    }
}

Make sure the Url you're requesting matches either the MVC or WebAPI route templates.


text:
Q: Transitioning from C# to VB.NET Any suggestions on how I should approach this?  Thanks.

A: Take a look at this VB to C# Comparison chart for some of the syntax and keyword differences.

A: I have to do this often - and my biggest hang-up is the semi-colon.  Never fails that my first few days of writing VB after a longer stint of C# coding, the VB compiler is always barking at me for putting a semi-colon on every line of VB code.
Other than that, it shouldn't be too painful.  If you're fluent in C#, moving to VB might be stressful for the first few days, but after that you should be smooth sailing.
Code converter tools come in handy to help you remember/learn/re-learn all of those odd syntax differences that you forget easily.  The one I normally turn to first is http://converter.telerik.com/ - and if that won't do the trick, a quick google search for code converters will turn up a handful of other good ones.
Another pain point that I've had in the past too is Snippets.  Snippets in C# rock - but in VB rock a bit less.  Get to know the differences between those and life will be much easier.  (Come on VB team - get that enter key working like the C# snippet team has it...)

A: A good C# to VB.NET converter will help.

A: Aside from revulsion and horror I recommend (from experience - ugh) to just start.  Build a simple app.  The magic is in the experience.  It doesn't make sense until you have spent lots of time trying to figure out why something doesn't work.

A: I went the other way (VB to C#) and found the syntax to be so similar that the transition was painless.  I can now pretty much program in either platform – thanks a lot to the IDE intellisense.

A: Take advantage of the "With" statement!  One of my favorite parts of VB.NET.

A: It's not as difficult as it seems at first.  Took me about a month from going strictly C++\C# to VB to get comfortable.

A: If you are familiar with programing you should just have to learn the syntax...why would anyone want to go from C# to VB? who knows  :)

A: My first question would be 'Why?'. I'd like to think that you can pretty much get the same thing done with either C# or VB.Net. Given that it's managed code, why not just leave them as they are?
Let's just assume you have your reasons :)
1) There are a couple of tools that will do this (see http://www.developerfusion.com/tools/convert/csharp-to-vb/ for a sample).
2) The other option is to manually convert the code, compile, fix errors, and repeat. Painful.

A: It's a pretty straight-forward thing, actually.  VB.Net is a perfectly good (if, imo, verbose) language with most of the expressiveness you've grown accustomed to in C#.  Just be aware that certain specific keywords are different and that you've got a different background culture and you'll do fine.

A: You can also use a tool like CodeRush from DevExpress (no affiliation).  The short-cut keys for any operation are the same for both languages and will produce the correct output for the language.
For example: key combo "mv" yields:
In C#
public void MethodName ()
{

}

In VB
Public Sub MethodName()

End Sub

A: Use XML literals and marvel how resentful fellow C# programmers suddenly are.

A: There were some useful articles in Visual Studio magazine back in Jan 2008.

*

*What C# developers should know about VB

*And for completeness: what VB developers should know about C#


text:
Q: Cyrillic in URLs using hyperref produces file link instead of URL link I have an URL containing Cyrillic characters, e.g.:
    \href{https://bg.wikipedia.org/wiki/Начална_страница}{Bulgarian Wikipedia Main Page}
When I compile the document, the link points to a local file such as: file:\\\Users\me\path\to\source\file\location\followed_by_something_mangled
which is obviously not the desired result.
It appears that \href cannot properly identify the link type ("url link") and detects a "file link".
One way to circumvent this is described here (in short: one encodes the original Cyrillic-containing URL to https://bg.wikipedia.org/wiki/%D0%9D%D0%B0%D1%87%D0%B0%D0%BB%D0%BD%D0%B0_%D1%81%D1%82%D1%80%D0%B0%D0%BD%D0%B8%D1%86%D0%B0)
This, however, aside from being ugly, contains all those % signs, which are interpreted as comments when \href is used inside, say, \textit{} and the compilation fails because of parenthesis mismatch.
Any ideas how to fix that?
P.S. I use XeLaTeX and my preamble is:
\documentclass[12pt,a4paper]{book}

\usepackage{fontspec}
\usepackage{xunicode}
\usepackage{xltxtra}
\setmainfont{Free Serif}

\usepackage{hyperref}

A similar problem appears when I use pdfLaTeX + inputenc

A: The address with percent encoding is correct for the first argument of \href.
If \href is used inside the argument of another command, then the percent % can be escaped with the backslash \% to prevent the percent character being interpreted as comment character:
\documentclass{article}
\usepackage{hyperref}
\begin{document}
\textit{%
  \href{https://bg.wikipedia.org/wiki/%
    \%D0\%9D\%D0\%B0\%D1\%87\%D0\%B0\%D0\%BB\%D0\%BD\%D0\%B0_%
    \%D1\%81\%D1\%82\%D1\%80\%D0\%B0\%D0\%BD\%D0\%B8\%D1\%86\%D0\%B0}{%
    Bulgarian Wikipedia Main Page}%
}
\end{document}

Another variation:
\documentclass{article}
\usepackage{hyperref}

\begingroup
  \catcode`\^^A = 14 % ^^A is comment char
  \catcode`\%=12
  \gdef\UrlBulgarianWikipediaMainPage{^^A
    https://bg.wikipedia.org/wiki/^^A
    %D0%9D%D0%B0%D1%87%D0%B0%D0%BB%D0%BD%D0%B0_^^A
    %D1%81%D1%82%D1%80%D0%B0%D0%BD%D0%B8%D1%86%D0%B0}
\endgroup

\begin{document}
\textit{%
  \expandafter\href\expandafter{%
    \UrlBulgarianWikipediaMainPage
  }{%
    Bulgarian Wikipedia Main Page}%
}
\end{document}

A: After playing with it an hour or so I have found this workaround. I give \href the tinyUrl and have it print out the website in Cyrillic. Here's the code:
\footnote{Wikipedia: Биоелектричен потенцијал
  \href{http://tinyurl.com/hp6o9t7}
       {\mkurl{https://mk.wikipedia.org/wiki/Биоелектричен\_потенцијал}}}

Here I use a tinyUrl to avoid the hassle with escaping %, and \mkurl is just a command that stylizes the text to look like a \url link. I didn't find which font is default, but my bet is CMU Typewriter Text which looks very close, except that the \url typeset is slightly bolded (\textbf bolds it too much). Here's my setup for the colors:
\usepackage{fontspec}
\definecolor{bbe}{rgb}{0, 0.27, 0.52}
\usepackage{hyperref}
\hypersetup{
   colorlinks,
   menucolor=black,
   linkcolor=black,
   citecolor=black,
   urlcolor=bbe
}
\newfontfamily\urlfont[]{CMU Typewriter Text}
\newcommand{\mkurl}[1]{\urlfont{\color{bbe} #1}}

Looks good enough for me :)


text:
Q: Swift Realm import Json Array Data I need to install the initial data into my Swift Realm from a Json array file.
The json data is in a file called "FundData.json".
I think I am having an issue reading the Json data because it is in an array.
What would be the best way to approach this initial setup of the database? I usually use SwiftyJSON.  I am not a Json or Realm sort of person.
This is the simplified Realm Class:
import Foundation
import RealmSwift

class Fund: Object  {

    @objc dynamic var symbol:String = ""
    @objc dynamic var name:String = ""
    @objc dynamic var type:String = ""
    @objc dynamic var primary:Bool = false

}

Here is some of the Json data:
[
{
    "symbol": "VTSMX",
    "name": "Vanguard Total Stock Market Index Fund",
    "type": "stock",
    "primary": "true"
},
{
    "symbol": "VFIAX",
    "name": "Vanguard 500 Index Fund",
    "type": "stock",
    "primary": "false"
},
{
    "symbol": "VSMAX",
    "name": "Vanguard Small-Cap Index Fund",
    "type": "stock",
    "primary": "false"
},
{
    "symbol": "VWIGX",
    "name": "Vanguard International Growth Fund Investor Shares",
    "type": "stock",
    "primary": "false"
}
]

I was able to use the Realm example of with a string. I somehow need to get the data from the json file.
let data = "{\"symbol\": \"VTSMX\",\"name\": \"Vanguard Total Stock Market Index Fund\",\"type\": \"stock\",\"default\": \"1\" }".data(using: .utf8)!

try! realm.write {
let json = try! JSONSerialization.jsonObject(with: data, options: [])
        realm.create(Fund.self, value: json, update: .modified)
    }

Thank you.

A: Change your parsing line to
let array = try JSONSerialization.jsonObject(with: data, options: []) as? [[String: Any]]

and the array variable will contain an array of dictionaries with your data. So you need to loop over the array to create your Fund objects
do {
    if let array = try JSONSerialization.jsonObject(with: data, options: []) as? [[String: Any]] {
        print(array)
    }
} catch {
    print(error)
}

will print

[["name": "Vanguard Total Stock Market Index Fund", "primary": "true", "type": "stock", "symbol": "VTSMX"], ["symbol": "VFIAX", "name": "Vanguard 500 Index Fund", "type": "stock", "primary": "false"], ["type": "stock", "primary": "false", "symbol": "VSMAX", "name": "Vanguard Small-Cap Index Fund"], ["primary": "false", "symbol": "VWIGX", "name": "Vanguard International Growth Fund Investor Shares", "type": "stock"]]

You could also look into letting your Fund class implementing Codable but I am not sure if it's worth it here.


text:
Q: JQL query fails in Jira API call What is wrong in my Jira API call ?
'''
curl -D- -u : -X GET -H "Content-Type: application/json" https://jiratraining02.atlassian.net/rest/api/2/search?jql=project=Project_WebDevelopment_Demo AND issuetype=Story AND status=READY FOR DEV
'''
I am getting the below error
curl: (6) Couldn't resolve host 'AND'
curl: (6) Couldn't resolve host 'issuetype=Story'
curl: (6) Couldn't resolve host 'AND'
curl: (6) Couldn't resolve host 'status=READY'
curl: (6) Couldn't resolve host 'FOR'
curl: (6) Couldn't resolve host 'DEV'

What I want to Achieve is -

*

*This command should give a json output. From the Json output, I have to extract the issue ID.

*In a bitbucket pipeline, I have to run yaml to move the tickets to a different status when the jo completes.

A: I'd run the query inside the Jira UI and then copy the Share link and use that in curl


text:
Q: ClearCase 8.0.x comes with Which IBM java version? I see Java 6 in some website and as this is not the current version of Java, there would be still be a perceived security risk around this.
So which IBM java version comes with ClearCase 8.0.x?

A: The most complete sources of information are:

*

*"ClearCase system requirement", and

*"Rational ClearCase version 8.0.0.x Release Notes" and 8.0.1.x.
(for instance, the 8.0.1.3 mentions that the IBM JRE has been updated with Java 6 Sr15)

The supported JDK is
IBM Runtime Environment, Java Technology Edition: 6.0.9
The prerequisite minimum is 6.0.9.3 for ClearCase 8.0.1.


text:
Q: R How to write a variable number of rows with same attributes in one row by creating new columns I have a huge data frame consisting of about 7.000 rows, each with a specific ID-number, which can   occur several times (up to 16). In a simple version it looks like this:
ID <- factor(c("a","a","a","a","b","c","c","d","d","d"))
var1 <-c(10,20,10,40,30,20,20,10,10,40)
var2 <-c(5,5,4,8,9,2,4,7,1,3)

df <- data.frame(ID,var1,var2)
df
    ID var1 var2
1   a   10    5
2   a   20    5
3   a   10    4
4   a   40    8
5   b   30    9
6   c   20    2
7   c   20    4
8   d   10    7
9   d   10    1
10  d   40    3

Now I would like to form my data.frame in the way that the attributes with the same ID are written in one row, so that I have (in this case) up to 4 columns for var1 and 4 columns for var2, as the most frequent ID occurs four times (ID a). All other spaces, for which no data exists, should be filled with .
The resulting data.frame should look like this:
    ID  var1_1 var1_2 var1_3 var1_4 var2_1 var2_2 var2_3 var2_4
1   a      10     20     10     40     5      5      4      8
2   b      30     NA     NA     NA     9      NA     NA     NA
3   c      20     20     NA     NA     2      4      NA     NA
4   d      10     10     40     NA     7      1      3      NA

My idea was to solve this via tapply
df2 <- tapply (df$var1,df$ID,paste)

which gives me the following output:
$a
[1] "10" "20" "10" "40"
$b
[1] "30"
$c
[1] "20" "20"
$d
[1] "10" "10" "40"

If I convert this to a dataframe it looks like this:
> df3 <-as.data.frame(df2)
> df3

             df3
a 10, 20, 10, 40
b             30
c         20, 20
d     10, 10, 40

The problem is that I now have only one variable instead of the desired four. (or actually eight, concerning those resulting from var2, which I would have handled like var1 and combined via merge in a final step).
I then tried strsplit() but this does not help me to solve the Problem, as I don´t get the different columns and I don't no how to add the NA values.
Maybe there is a simple function to restructure the data.frame? I would be very lucky if someone could help me.

A: Add a secondary ID and use reshape:
Here's what our second ID should look like (actually, this is generally known as your "time" variable)
with(df, ave(rep(1, nrow(df)), ID, FUN = seq_along))
#  [1] 1 2 3 4 1 1 2 1 2 3

With that, base R's underappreciated reshape takes care of this with ease:
df$ID2 <- with(df, ave(rep(1, nrow(df)), ID, FUN = seq_along))
reshape(df, direction = "wide", idvar="ID", timevar="ID2")
#   ID var1.1 var2.1 var1.2 var2.2 var1.3 var2.3 var1.4 var2.4
# 1  a     10      5     20      5     10      4     40      8
# 5  b     30      9     NA     NA     NA     NA     NA     NA
# 6  c     20      2     20      4     NA     NA     NA     NA
# 8  d     10      7     10      1     40      3     NA     NA

Alternatively, with "reshape2":
library(reshape2)
df$ID2 <- with(df, ave(rep(1, nrow(df)), ID, FUN = seq_along))
dfL <- melt(df, id.vars=c("ID", "ID2"))
dcast(dfL, ID ~ variable + ID2, value.var="value")
#   ID var1_1 var1_2 var1_3 var1_4 var2_1 var2_2 var2_3 var2_4
# 1  a     10     20     10     40      5      5      4      8
# 2  b     30     NA     NA     NA      9     NA     NA     NA
# 3  c     20     20     NA     NA      2      4     NA     NA
# 4  d     10     10     40     NA      7      1      3     NA

A: ncolVar1 <- max(rowSums(table(ID, var1)))
ncolVar2 <- max(rowSums(table(ID, var2)))

fun <- function(x, maxcol) {ifelse(length(x)==maxcol, list(x), list(c(x, rep(NA, maxcol-length(x)))))}

cbind(do.call(rbind, tapply(var1, ID, fun, ncolVar1)), do.call(rbind, tapply(var2, ID, fun, ncolVar2)))

#    [,1] [,2] [,3] [,4] [,5] [,6] [,7] [,8]
# a   10   20   10   40    5    5    4    8
# b   30   NA   NA   NA    9   NA   NA   NA
# c   20   20   NA   NA    2    4   NA   NA
# d   10   10   40   NA    7    1    3   NA


text:
Q: Docker Compose - give access to docker.sock before running (Telegraf) UPDATE:
I've tried implementing the accepted answer from here Telegraf can not connect to Docker sock like this in my docker compose file:
telegraf3:
  image: telegraf
  user: telegraf:$$(stat -c '%g' /var/run/docker.sock)
  volumes:
    - ./telegraf/telegraf3.conf:/etc/telegraf/telegraf.conf
    - /var/run/docker.sock:/var/run/docker.sock

I am getting this error:
Error response from daemon: unable to find group $(stat -c '%g' /var/run/docker.sock): no matching entries in group file

How can i fix this issue? :)
Background:
I'm trying to run Telegraf (https://github.com/influxdata/telegraf) with the docker input. I'm running Telegraf via Docker Compose, and i've configured it roughly like this:
telegraf3:
  image: telegraf
  volumes:
    - ./telegraf/telegraf3.conf:/etc/telegraf/telegraf.conf
    - /var/run/docker.sock:/var/run/docker.sock:rw
  env_file:
    - ./telegraf/telegraf.env
  depends_on:
    - influxdb

The telegraf configuration uses a docker input plugin to interact with the docker.sock. It doesn't work, i get a permission related error:
test-grafana-telegraf3-1  | 2022-12-29T12:09:10Z E! [inputs.docker] Error in plugin: Got permission denied while trying to connect to the Docker daemon socket at unix:///docker.sock: Get "http://%2Fdocker.sock/v1.24/info": dial unix /docker.sock: connect: permission denied

Basically, the entrypoint.sh script runs telegraf (the application) with the telegraf user, which can't access the docker.sock
There's a fix for this issue described here: Telegraf can not connect to Docker sock
Issue
As i am using docker compose, i would like this fix to be defined in the compose file, and not be dependent on me starting the container with docker run.
I've tried this:
telegraf3:
  image: telegraf
  volumes:
    - ./telegraf/telegraf3.conf:/etc/telegraf/telegraf.conf
    - /var/run/docker.sock:/var/run/docker.sock:rw
  env_file:
    - ./telegraf/telegraf.env
  depends_on:
    - influxdb
  command: ["bash -c -u telegraf $$(stat -c '%g' /var/run/docker.sock)", "/entrypoint.sh"]

But then i get this error:
test-grafana-telegraf3-1  | setpriv: failed to execute bash -c -u telegraf $(stat -c '%g' /var/run/docker.sock): No such file or directory

test-grafana-telegraf3-1 exited with code 127


text:
Q: Flask: Bad Request POST 400 I use flask and firebase. I have 2 button in satis.html . When user press button2 , i want to retrieve some data from database and show it. But i get " Bad Request " Error.
Heres my code :
@app.route('/satis', methods=['GET', 'POST'])
def satis():
    if (request.method == 'POST'):
                sehir=request.form['il']
                yas=request.form['yas']
                id=request.form['id']
                gun=request.form['satisgunu']
                cins=request.form['cinsiyet']
                tarz=request.form['satistarzi']
                db = firebase.database()
                db.child("names").push({"sehir": sehir,"yas":yas,"id":id,"gun":gun,"cins":cins,"tarz":tarz})
                todo = db.child("names").get()
                to = todo.val()
                if request.form['submit'] == 'add':
                    db = firebase.database()
                    users_by_score = db.child("names").order_by_child("id").equal_to("2").get()
                    us = users_by_score.val()
                    return render_template('satis.html', t=to.values(),u=us.values())
                return render_template('satis.html', t=to.values())

A: You have only handled for post method. You need to also handle the GET method situation.
@app.route('/satis', methods=['GET', 'POST'])
def satis():
    db = firebase.database()
    todo = db.child("names").get()
    to = todo.val()
    if (request.method == 'POST'):
                sehir=request.form['il']
                yas=request.form['yas']
                id=request.form['id']
                gun=request.form['satisgunu']
                cins=request.form['cinsiyet']
                tarz=request.form['satistarzi']
                db.child("names").push({"sehir": sehir,"yas":yas,"id":id,"gun":gun,"cins":cins,"tarz":tarz})
                if request.form['submit'] == 'add':
                    db = firebase.database()
                    users_by_score = db.child("names").order_by_child("id").equal_to("2").get()
                    us = users_by_score.val()
                    return render_template('satis.html', t=to.values(),u=us.values())
    return render_template('satis.html', t=to.values())


text:
Q: BufferedReader infinite loop I'm getting an infinite loop error but I don't know how to end the loop.
int a,b,c;
String line;

BufferedReader  br  =  new  BufferedReader(new  InputStreamReader(System.in));

while((line=br.readLine())!=null);
{
    System.out.println("Enter the two numbers to add:");
    a=Integer.parseInt(line);
    b=Integer.parseInt(line);
    c = a+b;
    System.out.println("Sum of two numbers:"+ c);
}

A: You need to remove ; from the end of the while loop because now you code is like
while loop without body
while((line=br.readLine())!=null);

and code block
{
    System.out.println("Enter the two numbers to add:");
    a=Integer.parseInt(line);
    b=Integer.parseInt(line);
    c = a+b;
    System.out.println("Sum of two numbers:"+ c);
}

So the code will stay in the while loop forever and just read lines
Note: a and b will convert the same line to int if your line like 10 20 you need to split it into 2 string first then get every integer in the variable
String[] number = line.split(" ");
a=Integer.parseInt(numbers[0]);
b=Integer.parseInt(numbers[1]);

or you can use Scanner to read integer by integer for example
Scanner scanner = new Scanner(System.in);
while (scanner.hasNext()) {
    int a = scanner.nextInt();
    int b = scanner.nextInt();
    int c = a+b;
    System.out.println("Sum of two numbers:"+ c);
}

A: package stackoverflow;

import java.io.BufferedReader;
import java.io.IOException;
import java.io.InputStreamReader;

public class InfLoop {

    public static void main(final String[] args) throws IOException {
        example1();
        example2();
    }

    private static void example1() {
        try (InputStreamReader isr = new InputStreamReader(System.in);
                BufferedReader br = new BufferedReader(isr);) {

            while (true) {
                final String line1 = br.readLine();
                if (line1 == null) {
                    System.out.println("First number not entered! Aborting...");
                    break;
                }

                final String line2 = br.readLine();
                if (line2 == null) {
                    System.out.println("Second number not entered! Aborting...");
                    break;
                }

                final int number1 = Integer.parseInt(line1);
                final int number2 = Integer.parseInt(line2);
                final int c = number1 + number2;
                System.out.println("Result of '" + number1 + "'+'" + number2 + "'='" + c + "'");
            }

        } catch (final Exception e) {
            e.printStackTrace();
        }
    }

    private static void example2() throws IOException {
        try (InputStreamReader isr = new InputStreamReader(System.in);
                BufferedReader br = new BufferedReader(isr);) {

            while (true) {
                final Integer number1 = readInteger(br, "Enter first number: ");
                if (number1 == null) {
                    System.out.println("First number is invalid! Aborting...");
                    break;
                }

                final Integer number2 = readInteger(br, "Enter second number: ");
                final String line2 = br.readLine();
                if (line2 == null) {
                    System.out.println("Second number is invalid! Aborting...");
                    break;
                }

                final int c = number1.intValue() + number2.intValue();
                System.out.println("Sum of '" + number1 + "'+'" + number2 + "'='" + c + "'");
            }
        }
    }

    private static Integer readInteger(final BufferedReader pBr, final String pMessage) {
        if (pMessage != null) System.out.println(pMessage);
        try {
            final String line = pBr.readLine();
            if (line == null) return null;

            return Integer.valueOf(line);

        } catch (final Exception e) {
            return null;
        }
    }
}
/*
 * 1) indentation was off, use IDE that does formatting for you
 * 2) use try/resource(/catch/finally)
 * 3) you need to read 2 separate lines, else a and b are the same
 * 4) start using helper methods (readInteger), save you lots of duplicate code
 * 5) there's two different ways of error handling here: handle inside the method (example1), or throw (example2),
 *    whatever is more useful for the calling code
 * 6) usually handling errors (instead of throwing them) should only be done if it is a direct requirement to the method!
 */

/UPDATE: changed IOException to Exception in readInteger()

A: Try something like this:
public static void main(String[] args) throws Exception {
    int a, b, c;
    String line;

    BufferedReader br = new BufferedReader(new InputStreamReader(System.in));
    do {
        System.out.println("Enter the two numbers to add:");
        if ((line = br.readLine()) != null && !line.isBlank()) {
            String[] input = line.split(" ");
            a = Integer.parseInt(input[0]);
            b = Integer.parseInt(input[1]);
            c = a + b;
            System.out.println("Sum of two numbers:" + c);
        } else {
            break;
        }
    } while (true);
}

Output:
Enter the two numbers to add:
4 5
Sum of two numbers:9
Enter the two numbers to add:


text:
Q: How to apply folder hierarchy with npm publish --registry? I am not sure where to change in command line for npm publish or package.json file for npm. I am trying to structure the Nexus repository using the version. I have written a gitlab ci/cd pipeline. The result that I want in Nexus dashboard is
- ProjectName
  - v1.0.0
    - artifacts.zip
  - v2.0.0
    - artifacts.zip

I have the following pipeline written:
npm publish --registry $Nexus_REPO_URL


text:
Q: How to accept Decimal values in Foundation 6 I have a form field built in Foundation 6 but it does not allow for decimal input.
HTML
<input type="number" name="decimal_amount" max="10" placeholder="" required>

When I enter 8.5 I get this error:
Please enter a valid value. The two nearest values are 8 and 9.
Here is the entire HTML block:
    <head>
    <!-- Foundation CSS via CDN -->
    <link rel="stylesheet" href="https://cdn.jsdelivr.net/foundation/6.1.2/foundation.min.css">
    <!-- 1140px Grid styles for IE -->
    <!--[if lte IE 9]><link rel="stylesheet" href="css/ie.css" type="text/css" media="screen" /><![endif]-->
    <!-- The 1140px Grid - http://cssgrid.net/ -->
    <link rel="stylesheet" href="../css/1140.css" type="text/css" media="screen" />
    <!--css3-mediaqueries-js - http://code.google.com/p/css3-mediaqueries-js/ - Enables media queries in some unsupported browsers-->
    <script type="text/javascript" src="../js/css3-mediaqueries.js"></script>
    <!-- Foundation JavaScript via CDN -->
    <script src="https://cdn.jsdelivr.net/foundation/6.1.2/foundation.min.js"></script>
    </head>
        <div class="large-6 columns">
          <label class="left">Ranking (scale 1-10, decimals allowed)
            <input type="number" name="decimal_amount" max="10" placeholder="" required>
          </label>
        </div>

<script src="js/vendor/jquery.min.js"></script>
<script src="js/foundation.min.js"></script>
<script>
    $(document).foundation();
</script>
</body>

Here is the error console

A: It is really a question of HTML5. Add the step="0.1" to the input to describe the type of decimal precision. Here is an example to the 100th's.
<input type="number" name="decimal_amount" max="10" step="0.01" placeholder="" required>

http://www.w3.org/TR/2012/WD-html5-20121025/common-input-element-attributes.html#attr-input-step


text:
Q: Jsoup select multiple siblings after a paticular sibling I'm trying to get multiple nodes out as one block of text, where these nodes are particular siblings grouped at the end of a list of similar siblings.  Its proving tricky in pure JSoup selector syntax.   Im a newb to this :P
Given this fragment of HTML:

Product information

Gently baked breakfast biscuits

Proven to slowly release carbohydrates

Made with a blend of 5 wholegrains

Contains 6 packs of 4 breakfast b

Suitable for vegetarians

At xxxx, we're passion blablabla

Allergy Information

Contains: Barley, Oats, Spelt, Wheat, Milk, Rye, Soya\Soybeans

May Contain: Eggs, Nuts, Peanuts

I want and can get the two last p tags using the following:
h2:containsOwn(Product Information) + div.detailsWrapper > div.content h3:containsOwn(Allergy Information) ~ p

But they are returned as separate items.  Is there a way to get just the last two p tags as a single block of text ?
Thanks dan

A: A simple answer for above html is
doc.select("h3 ~ p")

Jsoup has a ~ which selects preceding sibling. So E ~ F means an F element preceded by sibling E. Using that you could say doc.select("h3 ~ p") to get last two tags for above html.

A: I don't think you can. They're not a single or nested block of elements in the document model. text() only returns "the combined text of this element and all its children", it says nothing about siblings!
Is it such a hardship? One way you could get around it is to select the h3 Allergy Information element alone, and then ask for its siblingElements(). This returns all the siblings that come after it as an Elements object, and Elements.text() returns "the combined text of all the matched elements."
doc.select("h3:containsOwn(Allergy Information)").get(0).siblingElements().text()


text:
Q: Select Values based on extracting values PHPMyadmin enter image description here
My table has data as shown in the picture.
I selected the SiteInstanceID value based on a selection from another column "AttributeValue".
SELECT
   `SiteInstanceID`
FROM
   `sitecomponentattributevalues`
WHERE
   `AttributeValue` = 00069

Now I want to select all data from the same table where the SiteInstanceID is 61 (the extracted value from the above code)
enter image description here

A: You can use exists:
select s.*
from sitecomponentattributevalues s
where exists (
    select 1
    from sitecomponentattributevalues s1
    where s1.SiteInstanceID = s.SiteInstanceID and s1.AttributeValue = '0069'
)

A: you can join both SELECT statements with WHERE IN like this
SELECT * FROM `sitecomponentattributevalues`
WHERE `SiteInstanceID` IN
(SELECT `SiteInstanceID` FROM `sitecomponentattributevalues`
WHERE `AttributeValue` = 00069)


text:
Q: HTML button displays very differently on 2 pages with same CSS I have two web pages - one is a Product Listings Page:

/*BUTTON STYLE*/

button {
  background-color: #132257;
  color: white;
  border: 0.25em solid white;
  cursor: pointer;
  width: 100%;
  height: 90%;
}

/*PRODUCT LISTINGS PAGE*/

.shoplayout {
  grid-area: MC;
  display: grid;
  grid-template-columns: 1fr 4fr;
  grid-template-areas: "filters listing";
}

.filters {
  grid-area: filters;
}

.listing {
  grid-area: listing;
  display: grid;
  grid-template-columns: repeat(3, 1fr);
  gap: 0.75em;
}

.product {
  width: 100%;
  display: grid;
  grid-template-columns: 1fr;
  grid-template-rows: repeat(6, auto);
  border: 0.125em solid #1b2493;
}

.product>* {
  height: 8vh;
  line-height: 8vh;
  border-bottom: solid 0.02em #1b2493;
  padding-left: 0.25em;
}

.product div:nth-child(even) {
  /*Every second div within a product has the same background*/
  background-color: lightsteelblue;
}

.productbuy {
  display: grid;
  grid-template-columns: repeat(4, 1fr);
  text-align: center;
  border: none;
}

.productpic {
  grid-row: 1;
  padding: 0;
  border: none;
  display: flex;
  justify-items: center;
  height: 20vh;
}

.productpic>img {
  /*https: //stackoverflow.com/questions/3029422/how-do-i-auto-resize-an-image-to-fit-a-div-container*/
  max-width: 100%;
  max-height: 100%;
}

/*PRODUCT DETAILS PAGE*/

.productdetails {
  grid-area: MC;
  display: grid;
  grid-template-columns: repeat(2, 1fr);
  grid-template-rows: repeat(6, auto);
  gap: 1em;
}

.productdetails>* {
  border-bottom: solid 0.02em #1b2493;
  padding-left: 0.25em;
}

.picdetail {
  grid-column: 1 / span 2;
  grid-row: 1;
  background-color: cornsilk;
  justify-items: center;
  border: none;
}

.picdetail img {
  max-width: 100%;
  max-height: 100%;
}

.productnumbers {
  display: grid;
  grid-template-columns: repeat(4, 1fr);
  text-align: center;
}

Ch. BonPlonque, 2019

Bordeaux, France

Crisp fresh white

3.21/5, 3 reviews

€15.95

Stock: 5

<button>Buy</button>

Qty

One is a Products Details Page:

/*BUTTON STYLE*/

button {
  background-color: #132257;
  color: white;
  border: 0.25em solid white;
  cursor: pointer;
  width: 100%;
  height: 90%;
}

/*PRODUCT LISTINGS PAGE*/

.shoplayout {
  grid-area: MC;
  display: grid;
  grid-template-columns: 1fr 4fr;
  grid-template-areas: "filters listing";
}

.filters {
  grid-area: filters;
}

.listing {
  grid-area: listing;
  display: grid;
  grid-template-columns: repeat(3, 1fr);
  gap: 0.75em;
}

.product {
  width: 100%;
  display: grid;
  grid-template-columns: 1fr;
  grid-template-rows: repeat(6, auto);
  border: 0.125em solid #1b2493;
}

.product>* {
  height: 8vh;
  line-height: 8vh;
  border-bottom: solid 0.02em #1b2493;
  padding-left: 0.25em;
}

.product div:nth-child(even) {
  /*Every second div within a product has the same background*/
  background-color: lightsteelblue;
}

.productbuy {
  display: grid;
  grid-template-columns: repeat(4, 1fr);
  text-align: center;
  border: none;
}

.productpic {
  grid-row: 1;
  padding: 0;
  border: none;
  display: flex;
  justify-items: center;
  height: 20vh;
}

.productpic>img {
  /*https: //stackoverflow.com/questions/3029422/how-do-i-auto-resize-an-image-to-fit-a-div-container*/
  max-width: 100%;
  max-height: 100%;
}

/*PRODUCT DETAILS PAGE*/

.productdetails {
  grid-area: MC;
  display: grid;
  grid-template-columns: repeat(2, 1fr);
  grid-template-rows: repeat(6, auto);
  gap: 1em;
}

.productdetails>* {
  border-bottom: solid 0.02em #1b2493;
  padding-left: 0.25em;
}

.picdetail {
  grid-column: 1 / span 2;
  grid-row: 1;
  background-color: cornsilk;
  justify-items: center;
  border: none;
}

.picdetail img {
  max-width: 100%;
  max-height: 100%;
}

€15.95

Stock: 5

<button>Buy</button>

Qty

Pretty much everything displays as I want with the exception of the button captioned BUY:

The HTML for the .productbuy element is identical in both cases, the CSS is identical in both cases 9with the exception of the nth child background-color), the button style applies across the entire website, so I am puzzled as to why this is happening.
Any and all suggestions gratefully received.

A: Thanks to both MD Code and Andrea who spotted that there must have been a problem with the parent containers. In the second case, the product details page, there was a div missing from the page structure, and the CSS for both pages was somewhat messy.
So I tidied things up and it works perfectly now.
Product Details Page HTML is now:

Name and vintage

Origin

Description

Reviews

Grapes

Producer

TA

pH

RS

ABV

€15.95

Stock: 5

<button>Buy</button>

Qty

Putting in the div "DetailsLayout" meant the page structure was correct; I then tidied up the CSS:
/*LAYOUT FOR THE PLP*/
.shoplayout {
    grid-area: MC;
    display: grid;
    grid-template-columns: 1fr 4fr;
    grid-template-areas: "filters listing";
    }

/*LAYOUT FOR THE PDP - THIS WAS MISSING PREVIOUSLY*/
.detailslayout {
    grid-area: MC;
    display: grid;
    grid-template-columns: repeat(2, 1fr);
    grid-template-rows: repeat(6, auto);
    gap: 1em;
    }

.detailslayout > * {
        height: 8vh;
        line-height: 8vh;
    }

.products {
    width: 100%;
    display: grid;
    grid-template-columns: 1fr;
    grid-template-rows: repeat(6, auto);
    border: 0.125em solid #1b2493;
    }

.products > * {
    height: 8vh;
    line-height: 8vh;
    border-bottom: solid 0.02em #1b2493;
    padding-left: 0.25em;
    }

.products div:nth-child(even) {
    background-color: lightsteelblue;
    }

.productbuy {
    display: grid;
    grid-template-columns: repeat(4, 1fr);
    text-align: center;
    border: none;
    background-color: lightsteelblue;
    }

.productpic {
    grid-row: 1;
    padding: 0;
    border: none;
    display: flex;
    justify-items: center;
    height: 20vh;
    }

.productpic  img, .detailspic img {
    max-width: 100%;
    max-height: 100%;
    }

.detailspic {
    grid-column: 1 / span 2;
    grid-row: 1 ;
    background-color: cornsilk;
    justify-items: center;
    border: none;
    height: 20vh;
    }

.detailsnumbers {
    display: grid;
    grid-template-columns: repeat(4, 1fr);
    text-align: center;
    }

Now, on both pages the buttons render in the same way on the PLP:

And on the PDP:

Thanks to all for your help,
Dermot

A: The problem is not your style, button is working good but on details page your button's styles is according to the div parent change div parent style


text:
Q: Why do we rotate the axes instead of rotating the conic? In several sources such as the Wikipedia articles on conic sections and the matrix representation of conic sections and p.104 of Pettofrezzo's Matrices and Transformations, it is stated that we can rotate the coordinate axes when handling conics. For example, an appropriate rotation of the coordinate axes can result in the $xy$ term being conveniently eliminated. Another example is the result that states that the discriminant of the conic is invariant under rotations of the coordinate axes.
My question is: why do we express these ideas in terms of changing the coordinate axes instead of rotating the conic around the origin while keeping the axes fixed? It seems to me that rotating one object would be preferable because changing the entire coordinate system would mean that we have to change the coordinates of every object with which we are working on the plane.

A: The two notions are equivalent: Rotating the axes with respect to the conic is equivalent to rotating the conic with respect to the axes in the opposite direction.
Also note that rotating "the entire coordinate system" is also just rotating one object; the union of two lines, the axes. And it just so happens that the union of two lines is a (degenerate) conic, so really you are just rotating a conic in either case.


text:
Q: QRCode Generation in Laravel we have SNIPE IT Asset Management ,in that using(\Com\Tecnick\Barcode\Barcode()) QRCODE Generator. its working perfectly and produces
URL : http://xxxxx/xxxx/public/hardware/29/view
Now we want add new parameter in that URL as below
URL : http://xxxxx/xxxx/public/hardware/29/345/view

A: Assuming that you're designing your Laravel application correctly, using models and model bindings, you can do the following.
You need a route:
// Assuming you have a model called Hardware.
$router->get('hardware/{hardware}/view', function (Hardware $hardware) {
    return Barcode::generate('...'); // This is where you'd call the Barcode library you're using
});


text:
Q: Let $g: N→C$ be the arithmetical function giving the Dirichlet coefficients of the Dirichlet series 1/ζ(2s). Prove that $|µ(n)| =\sum_{d|n} g(d) $ Let  $g: N→C$ be the arithmetical function giving the Dirichlet coefficients of the Dirichlet series 1/ζ(2s).
a) Prove that g($k^2$) = µ(k) for every integer k, and that g(k) = 0 when k is not a square
b) Prove that $$|µ(n)| =\sum_{d|n} g(d) $$ Deduce that $$\sum_{n≤x} |µ(n)| = \sum_{nm≤x } g(m)=\sum_{nk^2≤x} |µ(k)|=\sum_{\sqrt k ≤x} |µ(k)|\sum_{n≤x/k^2} 1=\sum_{k ≤\sqrt x} µ(k) \lfloor\frac{x}{k^2}\rfloor$$ c) Use the previous equality to deduce that
#{n ∈N: n ≤ x, n is squarefree} =$\sum_{n≤x} |µ(n)|$= x/ζ(2) + O(√x).
d) Deduce that for every θ > 1/2 there exists $x_0 = x_0(θ)$ such that {n ∈N: n ∈ [x,x + $x^θ$], n is squarefree} is not empty ∀x ≥ $x_0$
I know this are a lot of question but for the last three I'm in trouble, the first I know that I can do it

A: a) First, one needs to find the Dirichlet series for $\frac{1}{\zeta(s)}$. Assuming $\frac{1}{\zeta(s)}=\sum_{n=1}^{\infty}\frac{a_{n}}{n^{s}}$, since $\zeta(s)\frac{1}{\zeta(s)} = 1$ from the formula for the coefficients of the product of two Dirichlet series one gets:
$\zeta(s)\frac{1}{\zeta(s)} = (\sum_{n=1}^{\infty}\frac{a_{n}}{n^{s}})(\sum_{n=1}^{\infty}\frac{1}{n^{s}})=\sum_{n=1}^{\infty}\frac{(a*1)_{n}}{n^{s}},$
where $1 = 1(n)$ is the identity arithmetic function and $(a*1)$ a Dirichlet convolution. From this relation, $a*1 = \epsilon$, where $\epsilon$ is the multiplicative identity. From Möbius inversion formula, $a = \epsilon*\mu$ where $\mu$ is the Möbius function. Hence $a_{n} = \mu(n), n = 1,2,3...$
From the findings above, $\frac{1}{\zeta(2s)} = \sum_{n=1}^{\infty}\frac{\mu(n)}{n^{2s}} = \sum_{n=1}^{\infty}\frac{\mu(n)}{(n^{2})^{s}} = \sum_{n=1}^{\infty}\frac{g(n)}{n^{s}}$. From this last equality, one obtains that $g(n^{2})=\mu(n) \text{ for } n\in\mathbb{N}$ and $g(n) = 0 $ when $n$ is not the square of a natural number.
b) $g(n)$ is multiplicative:
Let $n,m \in \mathbb{N}$ be such that $(n,m) = 1$. Suppose that $nm$ is the square of some natural number. Given a prime $p$ such that $p|nm$, let $\alpha > 0$ be the largest exponent such that $p^{\alpha}|nm$. If $p|n$, then $p^{\alpha}|n$ otherwise $(n,m) \neq 1$. Since $2|\alpha$, from the fundamental theorem of arithmetic one gets that $n$ is the square of some natural number. It is also clear that $m$ is also a square. Therefore, $g(nm) = \mu(\sqrt{nm})=\mu(\sqrt{n})\mu(\sqrt{m}) = g(n)g(m)$. Now suppose $nm$ is not a square, then it is clear that $n \text{ and } m$ can not be both squares. Hence $g(nm) = g(n)g(m) = 0$.
Define $S(n) = \sum_{d|n}g(d)$. Because $g$ is multiplicative so is $S$, therefore one only needs to show that $S(p^{n})=|\mu(p^{n})|$, for powers of primes. It is clear that:
$$S(p^{n}) = \sum_{k = 0}^{n} g(p^{k}) = \sum_{k = 0}^{ \lfloor n/2 \rfloor}g(p^{2k}) = \sum_{k = 0}^{\lfloor n/2 \rfloor}\mu(p^{k}).$$
For $n = 1, \text{ since } \lfloor n/2 \rfloor = 0, \text{ then } S(p) = \mu(1) = |\mu(p)| = 1.$ For $n > 1$, since $\lfloor n/2 \rfloor > 0,$ then $S(p^{n}) = \mu(1) + \mu(p) = |\mu(p^{n})| = 0.$
Given arithmetic functions $f \text{ and } h$ such that $h(n) = \sum_{d|n}f(d)$, it is possible to show that:
$$\sum_{n \leq x}h(n) = \sum_{n \leq x}\lfloor \frac{x}{n} \rfloor f(n).$$
Applying the formula above, one gets:
$$\sum_{n \leq x}|\mu(n)| = \sum_{n \leq x}\lfloor \frac{x}{n} \rfloor g(n) = \sum_{k^{2} \leq x} \lfloor \frac{x}{k^{2}} \rfloor g(k^{2}) = \sum_{k^{2} \leq x} \lfloor \frac{x}{k^{2}} \rfloor \mu(k) = \sum_{k \leq \sqrt{x}} \lfloor \frac{x}{k^{2}} \rfloor \mu(k).$$
c) First one needs to show that:
$$\sum_{k > \sqrt{x}}\frac{x}{k^{2}} = O(\sqrt{x}).$$
Applying Euler's summation formula:
$$x\sum_{k > \sqrt{x}}\frac{1}{k^{2}} = x\int_{\sqrt{x}}^{\infty}\frac{1}{t^{2}}dt +  x\int_{\sqrt{x}}^{\infty} (t-\lfloor t\rfloor)(\frac{-1}{t^{3}})dt - \frac{x}{(\sqrt{x})^{2}}(\lfloor\sqrt{x}\rfloor - \sqrt{x}),$$
$$x\sum_{k > \sqrt{x}}\frac{1}{k^{2}} \leq x\int_{\sqrt{x}}^{\infty}\frac{1}{t^{2}}dt + x\int_{\sqrt{x}}^{\infty} |t-\lfloor t\rfloor|(\frac{1}{t^{3}})dt + \frac{x}{(\sqrt{x})^{2}}|\lfloor\sqrt{x}\rfloor - \sqrt{x}|,$$
$$x\sum_{k > \sqrt{x}}\frac{1}{k^{2}} \leq \sqrt{x} + \frac{1}{2} + 1.$$
Hence,
$$(\sum_{k \leq \sqrt{x}} \lfloor \frac{x}{k^{2}} \rfloor \mu(k))\zeta(2) = [\sum_{k \leq \sqrt{x}} (\lfloor \frac{x}{k^{2}} \rfloor - \frac{x}{k^{2}})\mu(k) + x\sum_{k = 1}^{\infty}\frac{\mu(k)}{k^{2}} - x\sum_{k > \sqrt{x}}\frac{\mu(k)}{k^{2}}]\zeta(2),$$
$$(\sum_{k \leq \sqrt{x}} \lfloor \frac{x}{k^{2}} \rfloor \mu(k))\zeta(2) = [\sum_{k \leq \sqrt{x}} (\lfloor \frac{x}{k^{2}} \rfloor - \frac{x}{k^{2}})\mu(k) - x\sum_{k > \sqrt{x}}\frac{\mu(k)}{k^{2}}]\zeta(2) + x,$$
$$|(\sum_{k \leq \sqrt{x}} \lfloor \frac{x}{k^{2}} \rfloor \mu(k))\zeta(2) - x| \leq [\sum_{k \leq \sqrt{x}} |\lfloor \frac{x}{k^{2}} \rfloor - \frac{x}{k^{2}}||\mu(k)| + x\sum_{k > \sqrt{x}}\frac{|\mu(k)|}{k^{2}}]\zeta(2),$$
$$|(\sum_{k \leq \sqrt{x}} \lfloor \frac{x}{k^{2}} \rfloor \mu(k))\zeta(2) - x| \leq (\sqrt{x} + \sqrt{x} + 1 + \frac{1}{2})\zeta(2).$$
Therefore,
$$|(\sum_{k \leq \sqrt{x}} \lfloor \frac{x}{k^{2}} \rfloor \mu(k)) - \frac{x}{\zeta(2)}| \leq 2\sqrt{x} + \frac{3}{2}.$$
d) $\#\{n \in \mathbb{N} : n \in [x, x + x^{\theta}], n \text{ is squarefree}\} = \sum_{ x \leq n \leq x + x^{\theta} } |\mu(n)| \geq \sum_{n \leq x + x^{\theta}}|\mu(n)| - \sum_{n \leq x}|\mu(n)| = \frac{x^{\theta}}{\zeta(2)} + O(\sqrt{x+x^{\theta}}) + O(\sqrt{x}).$
For any $\theta > 1/2$, it is easy to see that:
$$lim_{x \rightarrow \infty}[\frac{x^{\theta}}{\zeta(2)} + O(\sqrt{x+x^{\theta}}) + O(\sqrt{x})] = +\infty.$$
Therefore, there exists $x_{0} = x_{0}(\theta)$ such that for $x \geq x_{0}$ then:
$$\frac{x^{\theta}}{\zeta(2)} + O(\sqrt{x+x^{\theta}}) + O(\sqrt{x}) \geq 1.$$


text:
Q: Is a custom session interface accessed in the same way as the default session object? I want to define another session interface that uses itsdangerous, based on this snippet.
app.session_interface = ItsdangerousSessionInterface()

The default session is accessed like a dictionary:
session['username'] = request.form['username']

Once I assign a new interface, do I use it in the same way as the default session object?

A: Flask's session is already using itsdangerous as of version 0.10.  That snippet is not needed anymore.   To answer the direct question though: yes, you always use the session like a dictionary.


text:
Q: gravar arquivo json no banco de dados é uma boa idéia?
estava pensando em fazer um projeto aonde o usuário irá criar vários elementos dinamicamente (tabelas, escolher uma determinada opção, preencher etc), estes elementos gerados dinamicamente deverão ser salvas no banco para posteriormente serem atualizadas, modificadas (algo semelhante ao jsfiddle, onde você dar um update em um projeto já existente, modificar, etc).
Como normalmente os desenvolvedores fazem? gravam o json no banco? depois lêêm ele e vão gerando e preenchendo os elementos no html?
{["firstName":{"required":"true","type":"text"},"lastName":{"required":"true","type":"text"}}

A: Não só pode, como é uma prática comum e recomendada para esse tipo de situação. Além disso os dados salvos podem vir a ser usados por qualquer linguagem e framework, já que JSON é universalmente entendido.
Por exemplo, passando o Json para seu frontend, com Javascript você cria os campos. Você pode também usar o Json e gerar o HTML com PHP. Você pode até mesmo usar o JSON e gerar uma tela para uma App iPhone, com Swift. E assim vai.
É tão aceitável, que os principais RDBMS possuem estruturas internas para JSON:

*

*PostgreSQL possui um tipo nativo json e jsonb com diversas funções utilitárias para tratar JSON: http://www.postgresql.org/docs/9.3/static/functions-json.html

*O MySQL 5.7.7 também adicionou o tipo JSON: http://mysqlserverteam.com/json-labs-release-native-json-data-type-and-binary-format/
Bancos noSQL são puramente Json:

CouchDB, é um banco de dados de código-aberto que foca na facilidade de uso e na filosofia de ser "um banco de dados que abrange a Web"1 . É um banco de dados não-relacional (NoSQL) que usa JSON para armazenar os dados, JavaScript como sua linguagem de consulta https://pt.wikipedia.org/wiki/CouchDB


text:
Q: Hermiticity of spin-orbit coupling in real space In the Kane-Mele model, the spin-orbit coupling is defined in real space as
$$\sum_{\langle \langle i j \rangle \rangle \alpha \beta} i t_2 \nu_{ij} s^z_{\alpha \beta} c_{i \alpha}^\dagger c_{j \beta}$$
where the sum is over next-nearest-neighbor sites on a honeycomb lattice, and $\nu_{ij} = - \nu_{ij} = \pm 1$ depends on the orientation of the next-nearest-neighbor bonds (I don't believe the details of how $\nu_{ij}$ is calculated is relevant for Hermiticity). I am having difficulty understanding how this term is Hermitian. Taking the Hermitian conjugate seemingly gives
$$\left(\sum_{\langle \langle i j \rangle \rangle \alpha \beta} i t_2 \nu_{ij} s^z_{\alpha \beta} c_{i \alpha}^\dagger c_{j \beta}\right)^\dagger = \sum_{\langle \langle i j \rangle \rangle \alpha \beta} (-i) t_2 \nu_{ij} s^z_{\alpha \beta} c_{i \alpha} c_{j \beta}^\dagger = \sum_{\langle \langle i j \rangle \rangle \alpha \beta} i t_2 \nu_{ij} s^z_{\alpha \beta} c_{j \beta}^\dagger c_{i \alpha}
\\
= -\sum_{\langle \langle i j \rangle \rangle \alpha \beta} i t_2 \nu_{ij} s^z_{\alpha \beta} c_{i \alpha}^\dagger c_{j \beta}  $$
where in the final line we have relabeled indices and used that $\nu_{ij} = - \nu_{ji}$, $s^z_{\alpha \beta} = s^z_{\beta \alpha}$.  I must be missing something obvious, but this seems to show that the term is anti-Hermitian, instead of Hermitian. What am I missing here?

A: In the first expression after the equals sign on the first line you have $c_{i\alpha}c^\dagger_{j\beta}$. It should be   $c^\dagger_{j\beta}c_{i\alpha}$ since
$(AB)^\dagger = B^\dagger A^\dagger$.

A: From the first to second expression on the first line, the Conjugation operation should transpose the matrix $v_{ij}$ to $v_{ji}$, giving the missing minus sign.


text:
Q: How to use int in a C# textBox I made a calculator that uses textboxes.
private void Btnrovnase_Click(object sender, EventArgs e)
    {

        int vysledek;
        vysledek = (int.Parse(textBox1.Text) / int.Parse(textBox2.Text));
        textBox3.Text = vysledek.ToString();

My code looks like this but now I want to use int named a in it.
The question is, is there a way to put the int in textbox1 or textbox2?

A: If you want only digits and numbers, you can use a NumericUpDown control.
But if you want a TextBox, you can use KeyPress event:
private void NumericTextBox_KeyPress(object sender, KeyPressEventArgs e)
{
  if ( !char.IsDigit(e.KeyChar) )
    e.Handled = true;
}

You can assign NumericTextBox_KeyPress to all desired TextBoxes.
If you want to handle things such as decimal separator you can use for example:
System.Globalization.CultureInfo.CurrentCulture.NumberFormat.NumberDecimalSeparator

Like that:
string separatorDecimal = CultureInfo.CurrentCulture.NumberFormat.NumberDecimalSeparator;

if ( !char.IsDigit(e.KeyChar)
  && new string(e.KeyChar, 1) != separatorDecimal )
  e.Handled = true;


text:
Q: Kubernetes: Same node but different IPs I have created a K8s cluster on GCP, and I deployed an application.
Then I scaled it:

kubectl scale deployment hello-world-rest-api --replicas=3

Now when I run 'kubectl get pods', I see three pods. Their NODE value is same. I understand it means they all are deployed on same machine. But I observe that IP value for all three is different.
If NODE is same, then why is IP different?

A: There are several networks in a k8s cluster. The pods are on the pod network, so every pod deployed on the nodes of a k8s cluster can see each other as though they are independent nodes on a network. The pod address space is different from the node address space. So, each pod running on a node gets a unique address from the pod network, which is also different from the node network. The k8s components running on each node perform the address translation.


text:
Q: Null Pointer Exception Error in arrayList add declare when I'm trying to use sentMessages method in testClass, I got a NullpointerException error in the line receiverUser.privateMessageList.add(privateMessage);
even I initialized the "privateMessageList" list. How can I deal with this problem?
public class User {

    private String userName;
    private String password;
    private String firstName;
    private String lastName;
    private String userType;
    int topicCount = 0;
    final int maxTopicNumber = 5;

    ArrayList<PrivateMessage> privateMessageList;

    public User(String userName, String password, String firstName, String lastName, String user_type) {
        this.userName = userName;
        this.password = password;
        this.firstName = firstName;
        this.lastName = lastName;
        this.userType = "USER";

    }
    //private message section
    public PrivateMessage sentMessage(String newMessage, User receiverUser) {
        privateMessageList = new ArrayList<>();
        PrivateMessage privateMessage = new PrivateMessage(this.userName, newMessage);
        receiverUser.privateMessageList.add(privateMessage);
        System.out.println("Message sent successfully!");
        return privateMessage;
    }

    public void ListMessages(User receiverUser) {
        System.out.println("Inbox of " + receiverUser);
        for (int i = 0; i < receiverUser.privateMessageList.size(); i++) {
            System.out.println(receiverUser.privateMessageList.get(i));
            System.out.println("Sent by: " + this.userName);
        }
    }

A: If you create a User and not call sentMessage method, your privateMessageList will not be created, thus executing any list method will cause NPE.
So initialize privateMessageList inside of the constructor or inline.
List<PrivateMessage> privateMessageList =new ArrayList<>();

Your sendMessage method will look like this:
public PrivateMessage sentMessage(String newMessage, User receiverUser) {
    PrivateMessage privateMessage = new PrivateMessage(this.userName, newMessage);
    receiverUser.privateMessageList.add(privateMessage); // list is already created
    System.out.println("Message sent successfully!");
    return privateMessage;
}

Secondly, if you are creating privateMessageList inside of your sentMessage method, than your list will always have single element. Because another method call will remove previous list. It seems to be a bug.

A: You're NOT initializing privateMessageList.
Initialize it in the constructor, so that it's always intialized.
Your sentMessage() method initializes the privateMessageList of this. But it doesn't initialize (and shouldn't)  the list of receiverUser.
Each user has its own list. Initializing one user's list won't initialize another user's list.
Initializing it in the constructor makes everything simpler and safer: there is no good reason for a user to ever have a null list.

A: replace this receiverUser.privateMessageList.add(privateMessage); to
privateMessageList.add(privateMessage);
create ArrayList object inside instance initializer block or inside constructor.