text:
Q: MENSA IQ Test and rules of maths In a Mensa calendar, A daily challenge - your daily brain workout. I got this and put a challenge up at work.
The Challenge starts with..
Assume you are using a basic calculator and press the numbers in the order shown,
replacing each question mark ...continues... What is the highest number you can
possibly score?

Basically, only using $+,-, * ,\div$, once in place of a question mark.

$5 ? 4 ? 7 ? 3 ? 2 =$

We all worked out the operators to be

$5 + 4 $ x $ 7 - 3/2 =$

Except that I calculated the answer to be $31.5$ and the others argued $30$. THe answer sheet from MENSA says the calculated total is 30.
Nobody actually understood the first part about using a basic calculator. I initially thought the challenge was all about the rules of maths.
And when I asked why nobody else applied the rules of maths, they all forgot about it, not because the challenge said to use some "basic calculation"
I emailed MENSA and queried them about the challenge and they replied,
Thank you for your email.

On a basic calculator it will be:
5 + 4 = 9
9 x 7 = 63
63 – 3 = 60
60 ÷ 2 = 30

Kind regards,
Puzzle Team

My Reply,
 Thank you for your reply.

 Could you please define what a basic calculator is? I tried 4 pocket,
 £1 calculators, and all gave me 31.5.

And finally their definition.
I guess what the question really means, whether you do the sum manually or on a
calculator,  is don't change the order of the numbers. The Casio calculators we have in
the office allow you to do the sum as it appears:

5 + 4 = 9
9 x 7 = 63
63 – 3 = 60
60 ÷ 2 = 30

Kind regards,
Puzzle Team

So they guess the challenge meant to do it that way. Why not just say ignore rules of maths. What is the point of this anyway?

My original question, on Maths Stack (this one) was why MENSA used 30 instead of 31.5. And initially I did not understand that using a basic calculator meant calculating left to right by pressing equals after each operation.
So what is going on here? If they wanted us the ignore rules of math they should of said taht. Because my basic calculator gives me 31.5 and not 30.0 (I dont have a special. Casio MENSA calculator though)
Windows standard calculator gives me 30. Why? None of my pocket, office, el cheapo calculators do this.

Google, or Windows Scientific give me 31.5 - As do ally my elelctornic calculators.

A: Just to play devil's advocate and give MENSA the benefit of the doubt since we don't have the actual question. Maybe for the following reasons, 30 can be THE valid answer:

*

*The actual sequence of operators does not change whether it is 30 or 31.5, which is the key for getting the right response.

*There is a difference between IQ and simply knowing rules. Figuring out how to get to 30 takes a keen eye and a bit of thought (calculators not allowed for MENSA test). e.g. imagine this a multiple choice question without the answer 31.5.

A: I have just seen your update to the question with the reply from Mensa.
The question setters are trying too hard. It's the case that you need to be able to think like them to get the right answer rather than being intelligent. If they meant that the calculator ignores rules of precedence then they should state that explicitly as a basic calculator can mean many things and doesn't have to exclude rules of precedence as computing is very cheap compared to the 80's when a basic calculator might be expected to ignore precedence.
Do you really want to join such a club?

A: In response to edit of initial post, then answer is clearly $30$. Basic calculators are assumed to evaluate in order from left to right.

Original post I responded to
In a Mensa calander, IQ dialy challenge I got this and put a challenge up at work.
Using +,-,time and divide only once. Use the math operator only once to get the highest answer.

5 ? 4 ? 7 ? 3 ? 2 =

We all worked out

5 + 4 x 7 - 3 / 2 = 30

Except that my result answer was 31.5 and not 30, like in the answers of the MENSA calendar.
Why was I the only one that applied the rules of maths on this? ANd when I asked why nobody else applied the rule of maths, I got the weirdest looks. Nobody knew about multiplication before division, subtraction before adding?  I thought that was why the question was marked as the most difficutl to test if you knew this.

Response to original post
Sadly, many people forget the basic rules of arithmetic as they (a) don't view them as affecting their lives, (b) didn't like maths, and/or (c) know technology can handle the problem for them. The issue with the last point is that different technologies handle things differently. The Google calculator (much like most graphing calculators) will handle order of operations for you correctly. The standard Windows calculator appears to be operating like an old 4 function calculator which evaluates after every operation is completed as opposed to correct order of operations. Though this can also happen when users hit enter after every operation is finished as opposed to when the whole expression is finished. (Don't have access to a Windows calculator right now so can't tell which is the reason for the wrong answer.)

A: You are indeed correct in that we apply multiplication and division before addition and subtraction.
However, multiplication and division have the same precedence, as does addition and subtraction. When multiplication and division (or addition and subtraction) are both part of an expression, we evaluate which ever appears first (when reading from left to right).

"When do I apply what?"

The good old "order of operations, once again:

*

*Parentheses or brackets. Perform the part of the expression enclosed in parentheses or brackets, first, working from innermost to outermost. $$50/[5 \times (2 + 3)] = 2$$

*Exponents. Then take powers of a term. $(2+3)^2 / 3 = (5)^2/3 = \frac{25}{3}$.

*multiplication and division (performed from left to right). $8/4 \times 3 = 2\times 3$, $8\times 4/3 = \frac{32}{3}$

*addition and subtraction (performed from left to right)

A: With the edits you've made to your question, it's now clear — at least to the older generation — that MENSA's answer is correct and yours is not.
The point is that the challenge does not, as you seem to think, ask you to replace the question marks in:
5 ? 4 ? 7 ? 3 ? 2 =

with the operators +, −, × and ÷ in any order, and then to evaluate the resulting string as a mathematical expression according to the rules of arithmetic.  If that's what they'd meant, that's what they would've written.  Rather, what the challenge literally tells you to do (emphasis  mine) is:

"Assume you are using a basic calculator and press the numbers in the order shown,
  replacing each question mark..."

In context, it should be clear that, by "basic calculator" they mean a classic 4-function pocket calculator (as opposed to a fancy modern formula calculator) like this one:

These kinds of calculators traditionally had no memory to store complicated expressions (and no way to enter or, indeed, display anything like parentheses), so they used immediate execution: they would only have enough memory to store two numbers and an operator, and every time you pressed an operator button (+, −, ×, ÷ or =), the previously chosen operator would be applied to combine the two stored numbers into one.  (The function of the = button was simply to perform the last operation and show the result without queuing any new operation.)
Effectively, such calculators thus evaluated all expressions stricly from left to right, ignoring arithmetic precedence; the sequence of button presses 5 ? 4 ? 7 ? 3 ? 2 = would be evaluated as (((5 ? 4) ? 7) ? 3) ? 2 = regardless of the operators the ? marks stood for.
Of course, this is a pretty limited method of computation: for example, there's no way to directly calculate an expression like (2 * 3) + (4 * 5) on such a calculator.  As a limited workaround, most pocket calculators did include an extra memory slot into which the user could store an intermediate result for later recall.  (That's what the "M−" and "M+" buttons in the picture are for.)  Of course, if you needed more than one such intermediate result, you'd better have either some paper and a pencil handy, or just a good memory.  Still, it was the best you could do cheaply using 1970's technology, so people learned to live with the limitations.

A: Our mnemonic was "MDAS" but we didn't interpret it as addition before subtraction. It was multiplication and division before addition and subtraction, as others have pointed out.
So, evaluating 5 + 4 x 7 − 3 / 2 would be:

*

*5 + 4 x 7 - 3 / 2

*5 +  28   - 3 / 2

*5 +  28   - 1.5

*33 - 1.5

*31.5

A: The correct answer is neither 30 nor 31.5 but +×−÷.
I have never seen MENSA calendar but you stated "like in the answers of the MENSA calendar." Did you mean readers' or publisher's answers? The first would be amusing, the second would be appalling.
Anyway, being smarter than the average MENSA enthusiast is something one welcomes rather than complaining about.

A: I bet your work mates were amazed by your stunning mathematical ability, isn't the highest answer possible actually 61.5?

A: 5+4*7-3/2 The Google agreed with me.
Yes, order of operations is Multiple and Divide first:
5+(4*7)-(3/2) = 31.5
So then, you want to multiply the two biggest numbers you can and have the largest denominator as possible when subtracting or smallest denominator as possible when adding.  You could do an proof by exhaustion since the dataset is small:
5+4-7*3/2 = -1.5
5+4-7/3*2 = 4.33
5+4*7-3/2 = 31.5
5*4+7-3/2 = 25.5
... etc

A: But parentheses weren't allowed in the original question so you cannot apply them selectively. You either work with mdas rules (implied parentheses) or the primitive left to right calc. Thus neither 61.5 nor 63 are valid.

A: It seems like a fair assumption that the rules of math should be applied to a mathematical expression.
Btw, it is not stated (but I guess it's implied) that the operators must be put in place of the question marks, or else
-5/4+7*32 = 222.75

A: the answer is 31.5. you know it but you messed up the math.
with subtraction and addition it shouldnt matter which is carried out first; they can both be considered to be identical functions (addition of a positive and a negative no or vice versa)
the answer is therefore 28+5-1.5; whichever way you look at it.


text:
Q: Why are my SVG paths jumping when trying to morph with AnimeJS? I'm trying to morph shapes here. I got it to work with polygons. I also got morphing to work with a simple path that has 3 points , but when I'm trying to do something with my actual SVG it just throws me a bunch of errors and is super buggy. All I did was slightly move some points and anchor handles. The final result after the morphing is correct but the actual animation is not at all what I desire. The morphed path is a copy of the original with some points altered. So the amount of points and the path direction should be the same. I even checked in Illustrator.
let test = anime({
    targets: `.test path:last-of-type`,
    d: [
        { value: 'M113.14,116.59a8,8,0,0,1-3.26-15.31,45.79,45.79,0,0,0,0-83.69A8,8,0,1,1,116.38,3a61.79,61.79,0,0,1,0,112.93A8,8,0,0,1,113.14,116.59Z' },
        { value: 'M113.14,116.59a8,8,0,0,1-3.26-15.31c16.52-7.35,13.84-33.54,27.19-41.85s-10.67-34.5-27.19-41.84A8,8,0,1,1,116.38,3c22.29,9.91,44.73,38.64,21.45,82.6,0,24.39.84,20.41-21.45,30.33A8,8,0,0,1,113.14,116.59Z' }
    ],
    easing: 'easeOutSine',
    duration: 2000,
    loop: false,
    complete: function(anim) {
        anim.reverse();
    },
    autoplay: false
});

Live example

A: To implement smooth animation, it is necessary that the number of node points and their type match in all paths.
Look at the paths in the vector editor.

The large semicircle has one node point more than the small semicircle. An extra point is indicated in the figure with a red arrow.
An extra point must be removed so that the number of node points is the same on both paths.
After editing, save the file and copy the paths to another file to create animation.
Animation with SVG SMIL

<svg  xmlns="http://www.w3.org/2000/svg" xmlns:xlink="http://www.w3.org/1999/xlink"
    width="25vw" hieght="25vh" viewBox="0 0 153.07 118.86">
    <path d="M75.75,8.72V110.15a8.7,8.7,0,0,1-14.83,6.18L35.13,90.74a11.26,11.26,0,0,0-8-3.27H11.29A11.29,11.29,0,0,1,0,76.18V42.68A11.28,11.28,0,0,1,11.29,31.4H27.18a11.27,11.27,0,0,0,8-3.28L60.92,2.54A8.7,8.7,0,0,1,75.75,8.72Z"/>
    <path d="M98.63,86.72a8,8,0,0,1-2.85-15.48,12.62,12.62,0,0,0,0-23.61,8,8,0,0,1,5.68-15,28.63,28.63,0,0,1,0,53.52A7.94,7.94,0,0,1,98.63,86.72Z">
     <animate
       attributeName="d"
       begin="0s"
       dur="1s"
       repeatCount="indefinite"
       values="
          m 98.63,86.72 c -8.896613,0.01429 -11.168355,-12.324863 -2.85,-15.48 10.87779,-4.111221 10.87779,-19.498779 0,-23.61 C 91.637862,46.06151 89.551515,41.432137 91.120003,37.290001 92.688492,33.147866 97.317862,31.06151 101.46,32.63 c 11.10918,4.225054 18.45261,14.874508 18.45261,26.76 0,11.885492 -7.34343,22.534946 -18.45261,26.76 -0.90058,0.361333 -1.859762,0.554526 -2.83,0.57 z;
        m 120.63,116.72 c -13.84288,4.29526 -17.65743,-9.06575 -10.85,-13.48 35.6227,-19.637776 34.69936,-61.423453 7.12758,-81.035919 C 110.18826,18.209024 104.23624,11.222661 108.01033,5.3312852 110.87272,0.86306533 113.31786,1.06151 117.46,2.63 c 10.57498,4.7592492 35.07508,19.514212 34.45261,56.76 -0.37039,22.162492 -8.1082,37.551535 -18.83964,49.45716 -0.90058,0.36133 -9.08042,7.1019 -12.44297,7.87284 z" />
    </path>
    <path d="m 98.63,86.72 c -8.896613,0.01429 -11.168355,-12.324863 -2.85,-15.48 10.87779,-4.111221 10.87779,-19.498779 0,-23.61 C 91.637862,46.06151 89.551515,41.432137 91.120003,37.290001 92.688492,33.147866 97.317862,31.06151 101.46,32.63 c 11.10918,4.225054 18.45261,14.874508 18.45261,26.76 0,11.885492 -7.34343,22.534946 -18.45261,26.76 -0.90058,0.361333 -1.859762,0.554526 -2.83,0.57 z"/></svg>

Animation morph with AnimeJS

const small = 'm 98.63,86.72 c -8.896613,0.01429 -11.168355,-12.324863 -2.85,-15.48 10.87779,-4.111221 10.87779,-19.498779 0,-23.61 C 91.637862,46.06151 89.551515,41.432137 91.120003,37.290001 92.688492,33.147866 97.317862,31.06151 101.46,32.63 c 11.10918,4.225054 18.45261,14.874508 18.45261,26.76 0,11.885492 -7.34343,22.534946 -18.45261,26.76 -0.90058,0.361333 -1.859762,0.554526 -2.83,0.57 z';
const big = 'm 120.63,116.72 c -13.84288,4.29526 -17.65743,-9.06575 -10.85,-13.48 35.6227,-19.637776 34.69936,-61.423453 7.12758,-81.035919 C 110.18826,18.209024 104.23624,11.222661 108.01033,5.3312852 110.87272,0.86306533 113.31786,1.06151 117.46,2.63 c 10.57498,4.7592492 35.07508,19.514212 34.45261,56.76 -0.37039,22.162492 -8.1082,37.551535 -18.83964,49.45716 -0.90058,0.36133 -9.08042,7.1019 -12.44297,7.87284 z';

var timeline = anime.timeline({
  autoplay: true,
  direction: "alternate",
  loop: true
});

timeline.add({
  targets: ".test",
  d: {
    value: [
      small,
      big
    ],
    duration: 1000,
    easing: "easeOutSine"
  },
  offset: 200
});
.test {
    position: fixed;top:0;
    left:0;height: 300px;width:300px;
}
div {
width:25vw;
height:auto;
}
<script src='https://cdnjs.cloudflare.com/ajax/libs/animejs/2.2.0/anime.min.js'></script>
<div >
            <svg viewBox="0 0 153.07 118.86">
            <path  d="M75.75,8.72V110.15a8.7,8.7,0,0,1-14.83,6.18L35.13,90.74a11.26,11.26,0,0,0-8-3.27H11.29A11.29,11.29,0,0,1,0,76.18V42.68A11.28,11.28,0,0,1,11.29,31.4H27.18a11.27,11.27,0,0,0,8-3.28L60.92,2.54A8.7,8.7,0,0,1,75.75,8.72Z"/>

            <path  d="m 98.63,86.72 c -8.896613,0.01429 -11.168355,-12.324863 -2.85,-15.48 10.87779,-4.111221 10.87779,-19.498779 0,-23.61 C 91.637862,46.06151 89.551515,41.432137 91.120003,37.290001 92.688492,33.147866 97.317862,31.06151 101.46,32.63 c 11.10918,4.225054 18.45261,14.874508 18.45261,26.76 0,11.885492 -7.34343,22.534946 -18.45261,26.76 -0.90058,0.361333 -1.859762,0.554526 -2.83,0.57 z"/>
            <path class="test" d="m 120.63,116.72 c -13.84288,4.29526 -17.65743,-9.06575 -10.85,-13.48 35.6227,-19.637776 34.69936,-61.423453 7.12758,-81.035919 C 110.18826,18.209024 104.23624,11.222661 108.01033,5.3312852 110.87272,0.86306533 113.31786,1.06151 117.46,2.63 c 10.57498,4.7592492 35.07508,19.514212 34.45261,56.76 -0.37039,22.162492 -8.1082,37.551535 -18.83964,49.45716 -0.90058,0.36133 -9.08042,7.1019 -12.44297,7.87284 z"/>

            </svg>
        </div>

redpajama_set_name: RedPajamaStackExchange


text:
Q: Como aumentar o desempenho de uma busca com for Basicamente o programa que fiz faz esse mesmo procedimento, porem com mais dados.
Preciso aumentar o desempenho da busca, claro que isso pode ser feito com bibliotecas caso seja melhor.
Não importa como aumente o desempenho, desde que o formato dos dados se mantenha.
import time
import random

numbers = []
searchs = []
search_range = 1

for i in range(0, 9999):
    numbers.append((int(random.random() * 100), int(random.random() * 100), int(random.random() * 100)))
    searchs.append((int(random.random() * 100), int(random.random() * 100), int(random.random() * 100)))

start = time.time()
for search in searchs:
    for number in numbers:
        if (search[0] > (number[0] - search_range) and search[0] < (number[0] + search_range) and
            search[1] > (number[1] - search_range) and search[1] < (number[1] + search_range) and
            search[2] > (number[2] - search_range) and search[2] < (number[2] + search_range)):
            print(number)
            break

print('Time: %.2f' % (time.time() - start))

Obs: Lembrando que apenas oque eu quero é o desempenho da busca, o resto do programa foi apenas um exemplo.


text:
Q: Alternating Riemann Zeta Function (Dirichlet eta function) convergence proof I am reading a proof on proving the convergence of the alternating Riemann Zeta Function but I cant understand how they went from the 2nd line of math to the 3rd. Can someone please explain why the inequality $\left| \frac{1}{(2n-1)^s}-\frac{1}{(2n)^s}\right|\leq\left|\frac{s}{(2n-1)^{s+1}}\right|$ is true? I understand everything else but why this inequality is true.

A: Triangle inequality:
$$\left|\int_{2n-1}^{2n} sx^{-s-1} \,\mathrm{d}x\right|\le \int_{2n-1}^{2n} |sx^{-s-1}|\,\mathrm{d}x.$$
Now bound the second integral by replacing the integrand with its maximum on the interval.


text:
Q: Changing angular material date picker date format on run time I have app wide default date format for angular material date picker i.e. dd/mm/yyyy and I have common a date picker component which I reused in different places. In couple of places, I need the date picker date format to be dd/mm/yy. I do not want to create another common date picker component only for different date format. I want to pass a format using @input() and date picker will change the format accordingly. Looks like angular material does not have any thing to do that.
Any one have any solution for that?

A: I think you can try working with Angular DatePipe: https://angular.io/api/common/DatePipe


text:
Q: If statement automatically open a tab but still remain focused on the current tab - php Currently I have this code:
if($t_link->link_type == 'Success')
echo " Success Link";
else
echo " Failed";

But this only open a new tab which it will be clicked, what I want is to automatically open a new tab but still remain to the current page.

A: if($t_link->link_type == 'Success')
echo '';
echo '<button  onclick="NewTab()"> Success Link</button>';
else
echo " Failed"


text:
Q: Lists conversion I am newbie to prolog and I am trying to flatten a list which is like this:
X = [[[0,0,1],[1,0,2]],[[0,1,3],[0,2,2]],[[0,3,5],[0,4,4]],[[0,5,4],[0,6,5]]]

The desired output is:
X = [[0,0,1],[1,0,2],[0,1,3],[0,2,2],[0,3,5],[0,4,4],[0,5,4],[0,6,5]]

How can I do this?

A: Use recursion :-)
myflatten([], []).
myflatten([[A, B]|T], [A|[B|FlattenedT]]) :- myflatten(T, FlattenedT).

And then query:
?- myflatten([[[0,0,1],[1,0,2]],[[0,1,3],[0,2,2]],[[0,3,5],[0,4,4]],[[0,5,4],[0,6,5]]], X).


text:
Q: Spring boot using Webflux & Kotlin: CRUD operation from inside a subscribed Mono is failing I'm in the process of testing how to query data from the "jsonplaceholder" API and save the received data to a local Postgresql database. When I make a call from Postman, the received data is returned correctly by "jsonplaceholder", but weirdly nothing is stored in the database.
Maybe I'm just missing something in my code (see below), I don't know!
This is a Spring Boot application with Webflux and Kotlin and Postgres'SQL as local database.
Thanks in advance for any help!
    /* The config file: WebfluxConfig.kt*/
    package com.example.monoSubscribe.config

    import org.springframework.context.annotation.Configuration
    import org.springframework.http.codec.ServerCodecConfigurer
    import org.springframework.web.reactive.config.CorsRegistry
    import org.springframework.web.reactive.config.EnableWebFlux
    import org.springframework.web.reactive.config.WebFluxConfigurer

    @Configuration
    @EnableWebFlux
    class WebfluxConfig: WebFluxConfigurer {

    override fun addCorsMappings(registry: CorsRegistry) {
        registry.addMapping("api/**")
    }
    override fun configureHttpMessageCodecs(configurer:
    ServerCodecConfigurer) {
        configurer.defaultCodecs().maxInMemorySize(-1)
    }
    }

    /* The model: Post.kt */
    package com.example.monoSubscribe.model

    data class Post(
    val userId: Int,
    val id: Int,
    val title: String,
    val body: String
    )

    /* The Repository: JsonholderRepo.kt */
    package com.example.monoSubscribe.repo

    import com.example.monoSubscribe.model.Post
    import org.springframework.data.repository.reactive.ReactiveCrudRepository

    interface JsonholderRepo: ReactiveCrudRepository<Post, Long> {
    }

    /* The service: AppService.kt */
    package com.example.monoSubscribe.service

    import com.example.monoSubscribe.model.Post
       import com.example.monoSubscribe.repo.JsonholderRepo
    import org.springframework.stereotype.Service
    import org.springframework.web.reactive.function.client.WebClient
    import org.springframework.web.util.UriBuilder
    import reactor.core.publisher.Flux
    import reactor.core.publisher.Mono

    @Service
    class AppService( private val jsonholderRepo : JsonholderRepo ) {

    fun createPost(postReq: Post) : Mono<Post> {
        return jsonholderRepo.save(
                Post(
                    userId = postReq.userId,
                    id = postReq.id,
                    title = postReq.title,
                    body = postReq.body
                )
            )
    }

    /** Call remote API (json placeholder) */
    fun fetchPosts(): Flux<Post> =
    fetch("/posts").bodyToFlux(Post::class.java)
    fun fetch(path: String): WebClient.ResponseSpec {
        val baseURL = "http://jsonplaceholder.typicode.com/"
        val client = WebClient.create(baseURL)
        return client.get().uri{
                builder: UriBuilder ->
            builder.path(path)
                .build()
        }.retrieve()
    }
    }

    //The controller: AppController.kt
    package com.example.monoSubscribe.controller

    import com.example.monoSubscribe.model.Post
    import com.example.monoSubscribe.service.AppService
    import org.springframework.http.ResponseEntity
    import org.springframework.web.bind.annotation.*
    import reactor.core.publisher.Mono
    import reactor.kotlin.core.publisher.toMono

    @RestController
    @RequestMapping("/api")
    class AppController(private val appService: AppService) {

    @PostMapping("/posts")
    fun createPost(@RequestBody postReq: Post): Mono<Post> {
        return appService.createPost(postReq)
    }

    /** Call remote API - Json placeholder  */
    @GetMapping("/jsonplaceholder")
    fun getData(): Mono<ResponseEntity<List<Post>>> {
        val ret =  appService.fetchPosts()
            .take(3)
            .collectList()
            .map { body -> ResponseEntity.ok().body(body) }
            .toMono()
        ret.log().subscribe(
            {
                val x:List<Post> = it.body as List<Post>
                for (t in x){
                    print(t)
                    appService.createPost(t)
                }
            },null,
            { }
        )
        return ret
    }

    }

    /* The property file: application.yaml */
    spring:
      r2dbc:
        url: r2dbc:postgresql://localhost:5432/
        username: postgres
        password: "*********"
      jpa:
        properties:
          hibernate:
            generate_statistics: true
    server:
      error:
        include-message:
    logging:
      file:
        name: src/main/kotlin/de/cops/webfluxPostgresql/logging/aam.log

    /* The build.gradle*/
    import org.jetbrains.kotlin.gradle.tasks.KotlinCompile

    plugins {
    id("org.springframework.boot") version "2.7.4"
    id("io.spring.dependency-management") version "1.0.14.RELEASE"
    kotlin("jvm") version "1.6.21"
    kotlin("plugin.spring") version "1.6.21"
    }

    group = "com.example"
    version = "0.0.1-SNAPSHOT"
    java.sourceCompatibility = JavaVersion.VERSION_11

    repositories {
    mavenCentral()
    }

    dependencies {
    implementation("org.springframework.boot:spring-boot-starter-data-r2dbc")
    implementation("org.springframework.boot:spring-boot-starter-webflux")
    implementation("com.fasterxml.jackson.module:jackson-module-kotlin")
    implementation("io.projectreactor.kotlin:reactor-kotlin-extensions")
    implementation("org.jetbrains.kotlin:kotlin-reflect")
    implementation("org.jetbrains.kotlin:kotlin-stdlib-jdk8")
    implementation("org.jetbrains.kotlinx:kotlinx-coroutines-reactor")
    runtimeOnly("org.postgresql:postgresql")
    runtimeOnly("org.postgresql:r2dbc-postgresql")
    testImplementation("org.springframework.boot:spring-boot-starter-test")
    testImplementation("io.projectreactor:reactor-test")
    implementation("org.springframework.boot:spring-boot-starter-
    validation:2.7.5")
    }

      tasks.withType<KotlinCompile> {
    kotlinOptions {
        freeCompilerArgs = listOf("-Xjsr305=strict")
        jvmTarget = "11"
    }
    }

    tasks.withType<Test> {
    useJUnitPlatform()
    }

A: The problem is the way how you're trying to save posts in the database.
At the moment is not saved because this part of the code doesn't have time to execute. subscribe doesn't mean that the main thread will complete after the execution of these lines.
       ret.log().subscribe(
            {
                val x:List<Post> = it.body as List<Post>
                for (t in x){
                    print(t)
                    appService.createPost(t)
                }
            },null,
            { }
        )

In your case saving is running on a separate thread which doesn't block the main thread. The main thread completes before save operations took place. That's why the database is empty.
Saving posts operations should be a part of the reactive stream that you already have. If you put it before mapping to ResponseEntity you'll omit additional mapping from the response entity to post again.
Something like that should work.
        return appService.fetchPosts()
            .take(3)
            .flatMap { appService.createPost(it) }
            .collectList()
            .map { body -> ResponseEntity.ok().body(body) }
            .toMono()


text:
Q: How to call image url from directory using php I want to display the image and the image url of a directory
I found this code, but there is a dot before the filename.
<?php
$files = glob("./images/*.*");
for ($i=0; $i<count($files); $i++) {
    $image = $files[$i];
    print "<textarea>";
    print "http://" .$_SERVER['SERVER_NAME'].$image;
    print "</textarea>"."
";
    echo ''."

";
}
?>

the result will be like this :
<textarea>http://domain.com./images/filename.png<textarea>

please help to fix this. thanks.

A: I solved the problem by using the following:
<?php
$files = glob("images/*.*");
for ($i=0; $i<count($files); $i++) {
    $image = $files[$i];
    echo ''."

";
    print "<textarea>";
    print "http://" .$_SERVER['SERVER_NAME'].$image;
    print "</textarea>"."

";
}
?>


text:
Q: Android RecyclerView fail when inserting new items while it is scrolling I have a problem when I try to insert new items to recyclerView/ adapter while recyclerView (list) is scrolling .Everything works fine when list is not scrolling but when I drag the list and try to insert a new item (while is still scrolling) it crash. Any idea on what can be the problem. This is the error message I get:
java.lang.IllegalArgumentException: Tmp detached view should be removed from RecyclerView before it can be recycled: ViewHolder{2414800 position=0 id=-1, oldPos=-1, pLpos:-1 update tmpDetached no parent}
                                                                                at android.support.v7.widget.RecyclerView$Recycler.recycleViewHolderInternal(RecyclerView.java:5429)
                                                                                at android.support.v7.widget.RecyclerView.removeAnimatingView(RecyclerView.java:1242)
                                                                                at android.support.v7.widget.RecyclerView$ItemAnimatorRestoreListener.onAnimationFinished(RecyclerView.java:11156)
                                                                                at android.support.v7.widget.RecyclerView$ItemAnimator.dispatchAnimationFinished(RecyclerView.java:11656)
                                                                                at android.support.v7.widget.SimpleItemAnimator.dispatchChangeFinished(SimpleItemAnimator.java:304)
                                                                                at android.support.v7.widget.DefaultItemAnimator$7.onAnimationEnd(DefaultItemAnimator.java:363)
                                                                                at android.support.v4.view.ViewPropertyAnimatorCompatJB$1.onAnimationEnd(ViewPropertyAnimatorCompatJB.java:51)
                                                                                at android.view.ViewPropertyAnimator$AnimatorEventListener.onAnimationEnd(ViewPropertyAnimator.java:1121)
                                                                                at android.animation.ValueAnimator.endAnimation(ValueAnimator.java:1153)
                                                                                at android.animation.ValueAnimator.doAnimationFrame(ValueAnimator.java:1313)
                                                                                at android.animation.AnimationHandler.doAnimationFrame(AnimationHandler.java:146)
                                                                                at android.animation.AnimationHandler.-wrap2(AnimationHandler.java)
                                                                                at android.animation.AnimationHandler$1.doFrame(AnimationHandler.java:54)
                                                                                at android.view.Choreographer$CallbackRecord.run(Choreographer.java:872)
                                                                                at android.view.Choreographer.doCallbacks(Choreographer.java:686)
                                                                                at android.view.Choreographer.doFrame(Choreographer.java:618)
                                                                                at android.view.Choreographer$FrameDisplayEventReceiver.run(Choreographer.java:860)
                                                                                at android.os.Handler.handleCallback(Handler.java:751)
                                                                                at android.os.Handler.dispatchMessage(Handler.java:95)
                                                                                at android.os.Looper.loop(Looper.java:154)
                                                                                at android.app.ActivityThread.main(ActivityThread.java:6119)
                                                                                at java.lang.reflect.Method.invoke(Native Method)
                                                                                at com.android.internal.os.ZygoteInit$MethodAndArgsCaller.run(ZygoteInit.java:886)
                                                                                at com.android.internal.os.ZygoteInit.main(ZygoteInit.java:776)

This is the xml:
    <android.support.v7.widget.RecyclerView
    android:id="@+id/recyclerView"
    android:layout_width="match_parent"
    android:layout_height="200dp"
    android:layout_alignParentLeft="true"
    android:layout_alignParentStart="true"
    android:layout_below="@+id/appBar"
    app:layout_behavior="@string/appbar_scrolling_view_behavior"
    app:layout_constraintHorizontal_bias="1.0"
    app:layout_constraintLeft_toLeftOf="parent"
    app:layout_constraintRight_toRightOf="parent"
    app:layout_constraintTop_toBottomOf="@+id/appBar"/>

on main:
    adapter = new SelectionDemoAdapter(sectionList);  // SelectionDemoAdapter contains two views header and item
    recyclerView.setLayoutManager(new StickyHeaderLayoutManager());
    recyclerView.setAdapter(adapter);
    recyclerView.addItemDecoration(new DividerItemDecoration(this, LinearLayoutManager.VERTICAL));
    recyclerView.setItemAnimator(new DefaultItemAnimator());

Adapter from here :ShamylZakariya StickyHeaders
public class SelectionDemoAdapter extends SectioningAdapter {

private ArrayList<SectionManager.Section> sectionList = new ArrayList<>();

public SelectionDemoAdapter(ArrayList<SectionManager.Section> sectionList) {
    this.sectionList=sectionList;
}

public class ItemViewHolder extends SectioningAdapter.ItemViewHolder {
    public View dateLine;
    public TextView memoTitle, memoCreator, memoCreationTime;
    public ImageView memoIcon, memoProtected;

    public ItemViewHolder(View itemView) {
        super(itemView);
        memoTitle = (TextView) itemView.findViewById(R.id.textViewMemoTitle);
        memoCreator = (TextView) itemView.findViewById(R.id.textViewMemoCreator);
        memoCreationTime = (TextView) itemView.findViewById(R.id.textViewMemoCreationTime);
        dateLine=(View) itemView.findViewById(R.id.dateLine);

        memoIcon=(ImageView) itemView.findViewById(R.id.imageViewMemoIcon);
        memoProtected =(ImageView) itemView.findViewById(R.id.imageViewProtected);
    }
}
public class HeaderViewHolder extends SectioningAdapter.HeaderViewHolder {
    TextView categoryTextView;
    TextView rightTextView;

    public HeaderViewHolder(View itemView) {
        super(itemView);
        categoryTextView = (TextView) itemView.findViewById(R.id.categoryTextView);
        rightTextView = (TextView) itemView.findViewById(R.id.rightTextView);
    }

}

@Override
public int getNumberOfSections() {
    return sectionList.size();
}

@Override
public int getNumberOfItemsInSection(int sectionIndex) {
    return sectionList.get(sectionIndex).memoArrayList.size();
}

@Override
public boolean doesSectionHaveHeader(int sectionIndex) {
    return !TextUtils.isEmpty(sectionList.get(sectionIndex).category);
}

@Override
public ItemViewHolder onCreateItemViewHolder(ViewGroup parent, int itemType) {
    LayoutInflater inflater = LayoutInflater.from(parent.getContext());
    View v = inflater.inflate(R.layout.memo_row_layout, parent, false);
    return new ItemViewHolder(v);
}

@Override
public HeaderViewHolder onCreateHeaderViewHolder(ViewGroup parent, int headerType) {
    LayoutInflater inflater = LayoutInflater.from(parent.getContext());
    View v = inflater.inflate(R.layout.list_item_selectable_header, parent, false);
    return new HeaderViewHolder(v);
}

@SuppressLint("SetTextI18n")
@Override
public void onBindItemViewHolder(SectioningAdapter.ItemViewHolder viewHolder, int sectionIndex, int itemIndex, int itemType) {
    ItemViewHolder ivh = (ItemViewHolder) viewHolder;
    //Log.d("esx","Memo adapter POSITION: "+position+" of "+memoList.size());
    SectionManager.Section section=sectionList.get(sectionIndex);
    Memo memo = section.memoArrayList.get(itemIndex);
    //memo.printALL();

    ivh.memoTitle.setText(memo.getMemoHeader().getTitle());
    ivh.memoTitle.setTextColor(MemoPriority.getPriorityType(memo.getMemoHeader().getPriority()).getColor());
    ivh.memoCreator.setText(memo.getMemoHeader().getCreator());
    ivh.dateLine.setBackgroundColor(MemoPriority.getPriorityType(memo.getMemoHeader().getPriority()).getColor());
    ivh.memoCreationTime.setText(TimeHelper.getDate(memo.getCreationTime(), TimeHelper.TimeFormat.HH_MM_SS));
    ivh.memoIcon.setImageResource(memo.getMemoHeader().getIconResourceID());
    if(memo.getMemoHeader().isProtected()) {
        ivh.memoProtected.setImageResource(Utils.getDrawableResourceID("protected_eye"));
        ivh.memoProtected.setColorFilter(MemoPriority.getPriorityType(memo.getMemoHeader().getPriority()).getColor(), PorterDuff.Mode.SRC_IN);
    }else {
        ivh.memoProtected.setImageResource(Utils.getDrawableResourceID("not_protected_eye"));
        ivh.memoProtected.setColorFilter(MemoPriority.getPriorityType(memo.getMemoHeader().getPriority()).getColor(), PorterDuff.Mode.SRC_IN);
    }

    ivh.itemView.setActivated(isSectionItemSelected(sectionIndex, itemIndex));

}

@SuppressLint("SetTextI18n")
@Override
public void onBindHeaderViewHolder(SectioningAdapter.HeaderViewHolder viewHolder, int sectionIndex, int headerType) {
    SectionManager.Section s = sectionList.get(sectionIndex);
    HeaderViewHolder hvh = (HeaderViewHolder) viewHolder;

    hvh.categoryTextView.setText(s.category);
    hvh.rightTextView.setText(s.rightText);

    hvh.itemView.setActivated(isSectionSelected(sectionIndex));
}

}


text:
Q: jnius.jnius.JavaException: Class not found I made a test application on kivy to call a service. I have these files:
main.py
from kivy.app import App
from kivy.uix.button import Button
from jnius import autoclass

class TestButton(Button):
    # When the button is pressed, this function is called
    def run_test_service(self):
        service = autoclass('org.test.myapp.ServiceMyservice')
        mActivity = autoclass('org.kivy.android.PythonActivity').mActivity
        argument = ""
        service.start(mActivity, argument)

class ServiceTestApp(App):
    def build(self):
        return TestButton()

if __name__ == "__main__":
    ServiceTestApp().run()

buildozer.spec
[app]

# (str) Title of your application
title = My Application

# (str) Package name
package.name = myapp

# (str) Package domain (needed for android/ios packaging)
package.domain = org.test

...

# (list) List of service to declare
#services = Myservice:main.py

service / main.py
from os import environ
from plyer import notification
import time

argument = environ.get('PYTHON_SERVICE_ARGUMENT', '')

while True:
    notification.notify(title="Hello", message="How do you?")
    time.sleep(5)

As a result, I get the error:

jnius.jnius.JavaException: Class not found b'org/test/myapp/ServiceMyservice

I tried to change the service argument following the advice of other users, but got the same error.
What should I specify in the service argument to access the service script?

A: I changed package name and package domain to
# (str) Package name
package.name = oscservice

# (str) Package domain (needed for android/ios packaging)
package.domain = org.kivy

and I changed this line.service=autoclass('org.kivy.oscservice.ServiceMyservice')
Your problem is solved in debug mode. For the release mode, before the buildozer -v android release command, you just need to type in Terminal export BUILDOZER_ALLOW_KIVY_ORG_DOMAIN=1.


text:
Q: Calculate and Display the Percentage of Time Passed I'm going through ThinkJava Version 6.1.0 (latest) and in Chapter 2 Exercise 2.3, I'm stuck on #5 which asks "Calculate and display the percentage of the day that has passed. You might run into problems when computing percentages with integers, so consider using floating-point."
I've attempted to get the percentage, but I'm not getting the right result.
I've completed the first 4 questions. Here is what I have so far:
public class Date {

    public static void main(String[] args) {

        int hour = 13, minute = 58, second = 45;
        double percentage;
        double secondsSinceMidnight = second + (minute * 60) + (hour * 3600);
        double secondsRemainingInDay = (60-second) + ((60-1-minute)*60) + (24-1-hour)*3600;

        percentage = (secondsSinceMidnight * 100) / 60;

        System.out.println("Number of seconds since midnight:");
        System.out.println(secondsSinceMidnight);

        System.out.println("Number of seconds remaining in the day:");
        System.out.println(secondsRemainingInDay);

        System.out.println("Percentage of the day past:");
        System.out.println(percentage + "%");
    }
}

Thank you for your help and support!

A: Please check the formula for calculating the percentage of the day already past.
    percentage = (secondsSinceMidnight * 100) / 60;

Does not seem right to me. It should be something like
    percentage =  100 * secondsSinceMidnight  / totalSecondsInDay;

totalSecondsInDay can be the sum of secondsRemainingInDay and secondsSinceMidnight

A: i think your code have problems with type-casting
in line 3 exchange int with double:
double hour = 13, minute = 58, second = 45;

or there is problem with constant numbers , write numbers in this way : 60.0 instead of 60

A: Here's an example with a hardcoded time. It's in military time obviously so keep that in mind.
public class Time
{
    public static void main(String[] args) {
        int startHour = 12;         //when you start editing program
        int startMinute = 00;
        int startSecond = 00;
        System.out.print("Number of seconds since midnight: ");
        startMinute = (startHour * 60 + startMinute );
        startSecond = (startMinute * 60 + startSecond);
        System.out.print(startSecond);
        System.out.println(" seconds");

        int secondInADay = 86400;    //number of seconds in a day
        System.out.print ("Seconds remaining in the day: ");
        System.out.println (secondInADay - startSecond);

        System.out.print("Percent of the day that has passed: ");
        double startSeconds = 43200;    //number of seconds that have passed in a day at start of editing program
        System.out.println(startSeconds * 100 / 86400);

        int endHour = 16;               //time when finished editing program
        int endMinute = 00;
        int endSecond = 00;

        System.out.print ("Difference = ");     //difference in time from start to finish
        endMinute = (endHour * 60 + endMinute );
        endSecond = (endMinute * 60 + endSecond);
        System.out.print (endSecond - startSecond);
        System.out.print (" seconds");
    }
}


text:
Q: Postgres Creating Schema in a specific database I got one suggestion form stackoverflow.com to create schema in a specific database as follows:
CREATE DATABASE foo;
 \connect foo;
CREATE SCHEMA yourschema;

But I am getting error as follows:

ERROR:  syntax error at or near "\" LINE 2:  \connect foo;
           ^
*** Error ***
ERROR: syntax error at or near "\"

Situation :
Login as postgress
create user u1
create database db1 with owner u1
\connect u1
create schema s1
Please help me in creating schema in a specific db.

A: This works, if - and only if - you're using psql:
postgres@berry-pc:~$ psql template1
psql (8.4.10)
Type "help" for help.

template1=# CREATE DATABASE foo;
CREATE DATABASE
template1=# \connect foo;
psql (8.4.10)
You are now connected to database "foo".
foo=# \connect template1
psql (8.4.10)
You are now connected to database "template1".
template1=# DROP DATABASE foo;
DROP DATABASE
template1=# \q

\connect is a psql command. It's not normal SQL, so you can't use that in a .sql file. There is no way to do it from within a sql file, as far as I know. The rationale behind this, is that you should reconnect to a different database once you want to use that different database. This is for database separation. The reason MySQL has implemented the use $database syntax is because of it's lack of schema's, but PostgreSQL doesn't have a command like that, as a database should be separated in schema's, rather than databases.


text:
Q: Rails 4: will_paginate error when trying to Sort a Resource Based on a Calculated Value I use Rails 4.1.0 I want to sort profiles based on completeness so for this i have this code in my profile model
def completeness
    percent = 10

    percent += 15 if self.useravatar.present?
    percent += 5 if self.summary.present?
    percent += 5 if self.profile_languages.present?
    percent += 10 if self.educations.present?
    return percent
end

def self.sorted_by_completeness
  Profile.all.sort_by(&:completeness).reverse
end

and this is my profiles index controller
  def index
    @profiles = Profile.paginate(page: params[:page], per_page: 10).sorted_by_completeness
  end

But when I'm trying to access profile index page I'm getting this error undefined methodtotal_pages' for #` can someone tell me why i'm getting this error

A: sort_by will return Array collection
to test open rails console and type
Profile.all.sort_by(&:completeness).reverse.class

for will_paginate to work with Array you need to  require 'will_paginate/array'
so just change your profile_controller as
require 'will_paginate/array'
class ProfileController < ApplicationController
  def index
    @profiles = Profile.sorted_by_completeness.paginate(page: params[:page], per_page: 10)
  end
end

A: Two problems with your approach:

*

*In your view, you're probably using will_paginate(@projects) which fails because that method isn't for arrays.

*You're sorting the rows after they've been paginated. This means that however you sort them, the sorting will be applied to only one page at a time. Thus whatever solution you choose, you need to specify the order before you paginate the data.
A solution would be to obviously use pagination on your array. Something like:
require 'will_paginate/array' # to enable pagination on an array
@projects = Project.sorting_method.paginate(arguments)

However for a large number of projects, that will soon become impractical.
The best way IMO, to enable pagination, is to have a completeness field in your projects table that gets updated anytime it should. Then, you could very easily do the following:
@projects = Project.order("completeness DESC").paginate(arguments)

Another solution would be to use sub-queries in a SQL select statement to calculate each project's completeness. Something like:
lcq = "SELECT COUNT(*) FROM profile_languages WHERE
  (profile_languages.project_id = projects.id)"
ecq = "SELECT COUNT(*) FROM educations WHERE
  (educations.project_id = projects.id)"

@projects = \
  Project.select(
    "#{project.column_names.join(',')},
    SELECT(
      (CASE useravatar WHEN NULL THEN 0 ELSE 15 END) +
      (CASE summary WHEN NULL THEN 0 ELSE 5 END) +
      (CASE (#{lcq}) WHEN 0 THEN 0 ELSE 5 END) +
      (CASE (#{ecq}) WHEN 0 THEN 0 ELSE 10 END)
    ) AS completeness").
  order("completeness DESC").
  paginate(arguments)

With some debugging, that should work. I don't like it though. A bunch of code that is hard to read and sub-queries that might slow things down a lot.

A:  def index
  @profiles = Profile.sorted_by_completeness(params[:page])
 end

In your model file:
def self.sorted_by_completeness(current_page)
    Profile.all.sort_by(&:completeness).reverse.paginate(page: current_page)
end

TO define your per_page limit use below code:
 #app/config/initializers/will_paginate.rb
  WillPaginate.per_page = 10

Else if you want to define it in model level:
  #profile.rb
   class Profile < ActiveRecord::Base
      self.per_page = 10
    #your other model level logic goes here.
    end


text:
Q: Status of Beilinson conjectures? (I hesitate to post that question here, but I received on answer on FB:)
Does anyone know how the current status of work on them is? And how the possible generalizations etc. which one thinks currently on, look like?

A: The survey of Nekovar tells you what was known about the Beilinson conjectures in the early 90s. Other surveys/introductions from that time include Scholl-Deninger, Soulé, Ramakrishnan (in Contemporary mathematics 83), and the volume edited by Rapoport, Schappacher and Schneider (introduction here, all articles here). Since then, not a lot has happened I think. There is a fairly recent article of Otsubo with some results for Fermat curves (published version, arXiv version). There is a nice reformulation of the conjectures in terms of Arakelov motivic cohomology, by Jakob Scholbach (see articles on his webpage). You might also want to check out some of the articles of Rob de Jeu and his coauthors. In addition, there have been various attempts at new descriptions of the Beilinson regulator, most recently by Bunke and Tamme (their work will by the way be the topic of a summer school in Freiburg in July), but this does not in itself imply any progress on the Beilinson conjectures themselves.
If you are interested in recent progress on special values in general, there are other areas where more exciting things are happening. Search for work on the Birch and Swinnerton-Dyer conjecture, the Equivariant Tamagawa number conjecture, and Weil-etale cohomology (starting point for Weil-etale: webpage of Baptiste Morin).

A: In addition to Andreas's excellent answer, we should also mention the Tamagawa number conjecture of Bloch and Kato, which predicts the undetermined rational factor arising in Beilison's conjectural description of the $L$-value. The Bloch-Kato conjecture was later reformulated and generalized by Fontaine and Perrin-Riou to the case of motives with coefficients in an arbitrary number field. Here are some references :
Bloch, Kato, L-functions and Tamagawa numbers of motives.
Fontaine, Perrin-Riou, Autour des conjectures de Bloch et Kato: cohomologie galoisienne et
 valeurs de fonctions L.
Colmez, Fonctions L p-adiques.
Kings, The Bloch-Kato conjecture on special values of L-functions. A survey of known results.
Flach, The equivariant Tamagawa number conjecture : A survey.
Gealy, On the Tamagawa Number Conjecture for Motives Attached to Modular Forms.
Bellaïche, An introduction to the conjecture of Bloch and Kato.


text:
Q: How can I evaluate the processing power of a GPU relative to a CPU? Suppose I have a program that does a lot of floating-point computations and is impractically slow on my current hardware. To reduce the runtime as much as possible, I want to figure out whether it's better to invest in CPUs or GPUs, given a fixed budget (around $3000-4000 in my case). I know that to compare one CPU to another, I can get a very rough sense of the relative processing speeds by multiplying the clock frequency by the number of cores for each CPU and comparing those numbers. But what about GPUs? Is there some way to quickly calculate a number based on the specs of the GPU that will tell me roughly how fast I can expect it to run my program, relative to a known CPU?
I know that the actual processing speed will depend heavily on the way the program is constructed and on other factors besides CPU/GPU clock speeds. For purposes of this question, I'm ignoring those other factors, i.e. I'm assuming that the time taken for any task other than floating-point number crunching is negligible (so it's not I/O bound or anything like that), and that the program is infinitely parallelizable (so, given any number of CPU or GPU cores, all of them will be used to maximum capacity as long as the program runs).

A: Well, you could try with synthetic benchmarks. They will give you some idea. NVIDIA'a CUDA toolkit for example contains some programs which are run on both CPU and GPU and it can be used to compare how long it takes to execute them on each platform.
If you need to do it only using GPU datasheets, you can do that too. For example, here's the page for my GeForce 9500 GS. You can find information about number of processing cores there. Processing capability is proportional to GPU frequency and core number. Some cards even have GFLOPS number too. There was a document with more uniform detailed descriptions available for each card, but I can't find a way to get to it right now. Maybe it's in CUDA toolkit downloads?
There's also the compute ability level which shows which features each card provides, but if I remember correclty, it doesn't make a direct impact on calculation speed, only on precision and instruction set that may be used.
I'm not up to date with information about cards from other manufacturers, but I expect that thare are ways to get the data at least for AMD and Intel too.


text:
Q: How to CI build branches in VSTS We use Git repositories in VSTS with branches and Pull Requests model to allow Code Reviews.
We have a CI Build definition and following it Release definition for all commits pushed to master.
And it would be a huge bonus if we can do CI for all branches too.
However Build definition for Git repos allows to setup only single branch to track.
And creating a Build per branch isn't feasible, as our branches are short-living aka feature branches and we delete them after PR merge to master.
Yes, there is an ability to specify to run CI build for PRs to master in Branch Policies page. But there are 2 issues with this:

*

*this will build only PR, while we want to build all the individual commits in branches as soon as they are pushed there

*CI build for PRs will trigger our Release too, but we obviously want it to be triggered only for master builds. Yes I can analyze $(Build.SourceBranch) or $(Build.SourceBranchName) in the Release definition and fail if it's not "master" but it will create a failed Release anyway, which I just want to avoid at all
So... how can we have CI builds in VSTS for any arbitrary branch?

Update
Another idea wrt running Release only for master builds - is to trigger Release from the Build side, e.g. by using API if $(Build.SourceBranch) equals to 'master', say by custom PowerShell script.
I can see there's even an extension for VSTS Trigger build step, but it will trigger even for non-master builds, although Microsoft is working on a feature to run steps conditionally.

A:
However Build definition for Git repos allows to setup only single branch to track.

That's actually not true. (You may be confused by the fact that the Repository tab has a Default branch setting, which only accepts a single branch.)
On the build definition, go to the Triggers tab. Check the Continuous Integration box if it isn't already.
Under Branch filters click Add new filter and set the value to *. (It will prompt you to select an existing branch, but you can ignore that and just hit Enter.)
Your build definition will now build commits on any branch in your repo.

A: You can add a powershell script task at the end of your build definition to trigger the release via Rest API, I created a simple code sample for your reference:
if ($env:BUILD_SOURCEBRANCHNAME -eq "master")
{
$collectionuri = $env:SYSTEM_TEAMFOUNDATIONCOLLECTIONURI
$buildid = $env:BUILD_BUILDID
$project = $env:SYSTEM_TEAMPROJECT
$token = $env:SYSTEM_ACCESSTOKEN
$builddef = $env:BUILD_DEFINITIONNAME
$buildnum = $env:BUILD_BUILDID
$releaseid = 2;

#Generate API URL
$account = "";
$reg = "https://+(?<acc>\w+?).visualstudio+"
if ($collectionuri -match $reg)
{
    $account = $Matches.acc;
}
else
{
    Write-Host "Fail to get the account name from collection url";
}
$url= "https://" + $account + ".vsrm.visualstudio.com/"+ $project + "/_apis/release/releases?api-version=3.0-preview.2"

#Generate Auth info
$basicAuth= ("{0}:{1}"-f "anys",$token)
$basicAuth=[System.Text.Encoding]::UTF8.GetBytes($basicAuth)
$basicAuth=[System.Convert]::ToBase64String($basicAuth)
$headers= @{Authorization=("Basic {0}"-f $basicAuth)}

#Generate body content
$instanceRef = @{id = $buildID};
$artif = @{alias = $builddef; instanceReference = @{id = $buildnum}}
$content = @{
    definitionId = $releaseid
    description = "Triggered from CI Build"
    artifacts = @($artif)
    }
$json = $content | ConvertTo-Json -Depth 100

#Call Rest API to start the release
$responseBuild = Invoke-RestMethod -Uri $url -headers $headers -Method Post -Body $json -ContentType "application/json"
}
else
{
    Write-Host "Not master branch, no release triggered"
}

You need to update the "releaseid" to the id of the release definition you'd like to trigger and in the security configuration of that definition, set the "Create releases" permission to "Allow" for "Project Collection Build Service" account.

A: Very very easy.

*

*Go to the Marketplace and install GitVersion into VSTS/Azure DevOps
https://marketplace.visualstudio.com/items?itemName=gittools.gitversion

*As what was described before, change your CI trigger to monitor all branches:

The reason I also add line #2 to monitor tags is because I leverage GitVersion and git tags to version the build artifact when I'm ready to release my product.  When I apply and push a git tag the build doesn't detect it unless I explicitly tell it to watch for it.  My format for git tag is "v1.2.3" starting with lower-case "v".  Just in case I want to apply any other tag and not start a build.

*Lastly change the build number format.  You need to discern what branch is building.  GitVersion uses semantic versioning thus this describes what is building.

*Now kick off as many builds from any number of branches and see them all kick off from a single build definition.  Set once and forget from now on!

Benefits:

*

*No scripts to maintain

*Follow semantic versioning

*Create a build pipeline/definition once and never have to worry about feature branches every again.

*Will still work for Pull Requests.

*Read more about GitVersion at https://gitversion.readthedocs.io
The secret sauce:  GitVersion reads the Git history, so the number increments for every git commit AFTER it is tagged. It creates build variables from the CI system it is using and makes them available.  It derives these variables and creates a tag or alias for the branch it is building depending on the mode you are using GitVersion in.  In the example above I had some commits (not shown), when it was version 0.1.0 then I tagged it version 1.0.0 and released it.  The next commit predicted that the next version would be 1.1.0 and there were lots of commits (11 of them) into the develop branch.  The build name uses the alias alpha since build artifacts are alpha candidates.  There were 4 more commits.  There was a feature branch build after that branched from commit #15, made a 16th commit and pushed that, and was built.  I think you are getting the idea.  It's all from one single build pipeline and using GitVersion to describe what branch is being build and the commit being built.  Semantic versioning describes the build.


text:
Q: having simple buttons in papervision there's a simple thing in papervision I can't do , I want to have a simple button on my swf like we have in flash , just a 2d square which is on screen and you can click on it and have some action , I didn't find any solutions for this
I'll be appreciated if someone can help me with this
thanks

A: First of all, I would like to say that you'd better not use papervision anymore, since that project has been stopped and will not be developed any further. It is better to change to Away3D for that matter.
That being said, I do have the solution to your problem. It is actually very simple. You can just add an OBJECT_PRESS-eventListener to a 3Dobject, or you can create a button that isn't a 3Dobject and justr place it over your view (if you want a 2D-button).
//If you want a 3D-object to act as a button
yourButton.addEventListener(InteractiveScene3DEvent.OBJECT_PRESS, someFunction);

//If you want a 2D-non-papervision-button to be over your view.
var yourButton:Button = new Button();
stage.addChildAt(yourButton, IndexHigherThanYourView);


text:
Q: htaccess rule confulictle when i add new rule in php i want to redirecy this
from
www.example.com/babycare/general_help/category.php?id=12

to
www.example.com/article/category/12`

i write the rule for this
RewriteCond %{THE_REQUEST} /babycare/general_help/category\.php\?id=([0-9]+)  [NC]
RewriteRule ^ /article/category/%1? [L,R]

This redirect me  FROM
www.example.com/babycare/general_help/category.php?id=12

to
www.example.com/article/category/12

But i  also redirect
from
www.example.com/babycare/general_help

to
www.example.com/article

SO what should i do??i try to add different rule but that rule confulict the above rule and both stop working

A: Try using this code:
RewriteRule ^babycare/general_help$ article [R=301,NC,L]

Use this code before your .htaccess
RewriteCond %{THE_REQUEST} /babycare/general_help/category\.php\?id=([0-9]+)  [NC]
RewriteRule ^ /article/category/%1? [L,R]

Maybe this could help you


text:
Q: Iteration numbers with True False condition Please HELP!!
I have a list:
a = ['False', 'False', 'True', 'True', 'True', 'False', 'False', 'True', 'True']

I want to generate iteration number if it's False the number continues and if it's True the number stays.
I Try this code:
result = []
x = 1
for i in a:
    while i == 'False':
        result.append(x)
        if i == 'True':
            x+=1
            continue
            result.append(x)
        x += 1

it's just keep running and did not show any output.
the desired output will be [1,2,3,3,3,4,5,6,6]
I have no idea what's wrong with it
Thanks

A: This can actually be solved pretty nicely with accumulate from itertools
from itertools import accumulate

a = ['False', 'False', 'True', 'True', 'True', 'False', 'False', 'True', 'True']

print(list(accumulate(1 if i == 'False' else 0 for i in a)))

Same result as gtomer, which I believe is the correct output.

A: See this code below:
a = ['False', 'False', 'True', 'True', 'True', 'False', 'False', 'True', 'True']
result = []
x = 0
for i in a:
    if i == 'False':
        x+=1
    result.append(x)

print (result)

Note that if I understood your text, your desired output is not correct

A: The error in your code is that once i takes a value of "False" it goes in a (infinite) while loop and never comes out. Bcz the value of i never changes in the while loop itself.
result = []
x=1
for i in a:
  if i=="False":
    x+=1
  result.append(x)

This should work for you

A: Yet another version of this (with the output behaving as required by OP):
def weird_sequence(some_list):
    prev = None
    number = 0
    for item in some_list:
        if prev is None:
            prev = "False"
        if item == "False" or prev == "False":
            number += 1
        yield number
        prev = item

Usage:
>>> list(weird_sequence(['False', 'False', 'True', 'True', 'True', 'False', 'False', 'True', 'True']))
[1, 2, 3, 3, 3, 4, 5, 6, 6]


text:
Q: How to link comments to each post by id with Laravel Blade I have created a Post and Comment application. I am trying to link the comments to the id of the post. I am trying to use PHP in a Blade template to do this. I get the error that the variable post_id does not exist. I want to use the @if and @foreach of Blade. The problem seems to be in the @if statement.
Here is my HTML:

        @foreach($posts as $post)

id }}">

                          {{ $post->title }}

                       by {{ $post->user->firstName }} {{ $post->user->lastName }} |
                       {{ $post->created_at }} |
                          3 Comments

                          {{ $post->post }}

                  <input type="text" name="addComment" placeholder="Add your comment" class="form-control" v-model="comment">

                <input id="addComment" type="submit" name="submitComment" value="Submit Comment" class="btn btn-default" v-on:click="submitComment" data-id="{{ $post->id }}">

              @if($post->comment->post_id == $post->id)
                @foreach($post->comment as $comment)

By: {{ $comment->user->firstName }} {{ $comment->user->lastName }}

{{ $comment->comment }}

                @endforeach
              @endif

          @endforeach

Here is my PostController:
  public function index(){
      $posts = Post::with('comment', 'user')->orderBy('id', 'desc')->limit(20)->get();
      return view('post.posts')->with('posts', $posts);
    }

A: You don't need @if statement, remove it. $post->comment is a collection, that 's why your are not getting post_id. if you want to check, then check inside foreach.
            @foreach($post->comment as $comment)

By: {{ $comment->user->firstName }} {{ $comment->user->lastName }}

{{ $comment->comment }}

            @endforeach

A: You need to add post_id to the comments table and use the relationship:
public function comments()
{
    return $this->hasMany(Comment::class);
}

Then you'll be able to load related comments:
Post::with('comments', ....

And iterate over posts and their comments:
@foreach ($posts as $post)
    @foreach ($post->comments as $comment)
        {{ $comment->content }}
    @endforeach
@endforeach

A: I think if you create relationship between Post model and Comment model (post table and comments table), your @if is useless. I recommend you to check your corresponding models.
Your code should be like this,
Post.php
public function comments(){
    return $this->morphMany('App\Comments','commentable');
}

Comment.php
public function commentable(){
    return $this->morphTo();
}

in my app Comment model is shared by some other models also.
Eg :- User's Questions also have comments.
Find more details in laravel:Eloquent page


text:
Q: How to manage source code and infra seprately with Terraform I have an app written in Nodejs, deployed to GCP AppEngine.
AppEngine configuration is defined in yaml file like this
# app.yaml
runtime: nodejs12

# instance class
instance_class: F4_1G

# environment variables
env_variables:
  ENVIRONMENT: 'develop'

AppEngine deploy command
gcloud app deploy app.yaml

From now on I want to manage this AppEngine infra with Terraform. How can I deploy separately Nodejs source (by gcloud) and yaml file (by Terraform) but app still working?
Any tutorial or related links is approciate.

A: You should be able to use the app_engine_application terraform resource.
If you really want to use gcloud, there is also Terraform gcloud module.
For example:
# Verify Terraform gcloud module works in your environment
module "gcloud_deploy_app" {
  source  = "terraform-google-modules/gcloud/google"
  version = "~> 2.0"
  use_tf_google_credentials_env_var = true
  skip_download                     = false

  create_cmd_entrypoint  = "gcloud"
  create_cmd_body        = "app deploy app.yaml"

  # if you want to skip the destroy, but you could also have another gcloud command
  destroy_cmd_entrypoint = "echo"
  destroy_cmd_body       = "skip"
}


text:
Q: How do we import C code outputs to be used in matlab for visualisation i have a C code that finds the solution of a function using the methode of bisection and Newton Raphson, and i want to compare the results using graphs ( i am asked to do so in matlab as it's a school project ), but i have no idea how.
here's my code :
`
#include <stdio.h>
#include <math.h>
#include<stdio.h>
#include<math.h>
float F0 (float V)
{
float J0 = 1e-15;
float n = 0.68;
float V0 = 0.025;
int E = 1;
int R = 100;
    return (E-V-R*J0*(exp(n*V/V0)-1));
}

float F1 (float V)
{
float J0 = 1e-15;
float n = 0.68;
float V0 = 0.025;
int E = 1;
int R = 100;
    return (-1-n*R*J0/V0*exp(n*V/V0));
}
void Dichotomie (float *V, float a, float b, int *itr)
{
    *V=(a+b)/2;
    ++(*itr);
    printf("Iteration no. %3d V = %7.5f\n", *itr, *V);

}

void Newton(int itr, int maxmitr, float h, float V0, float V1, float err)
{

    for (itr=1; itr<=maxmitr; itr++)
    {
        h=F0(V0)/F1(V0);
        V1=V0-h;
        printf("Iteration no. %3d, V = %9.6f\n", itr, V1);
        if (fabs(h) < 2*err)
        {
            printf("After %3d iterations, root = %8.6f\n", itr, V1);
            return;
        }
        V0=V1;
    }
    printf(" The required solution does not converge or iterations are insufficient\n");
    return;
}

int main ()
{
    float J0 = 1e-15;
    float n = 0.68;
    float V0 = 0.025;
    int E = 1;
    int R = 100;
    int itr = 0, maxmitr;
    float V, a, b, err, V1;
    float h;

    a = 0;
    b = 1;
    err = 0.000001;
    maxmitr = 100;
    Newton(itr, maxmitr,h,V0,V1,err);

    Dichotomie (&V, a, b, &itr);
    do
    {
        if (F0(a)*F0(V) < 0)
            b=V;
        else
            a=V;
        Dichotomie (&V1, a, b, &itr);
        if (fabs(V1-V) < 2*err)
        {
            printf("After %d iterations, root = %6.6f\n", itr, V1);
            return 0;
        }
        V=V1;
    }
    while (itr < maxmitr);
    printf("The solution does not converge or iterations are not sufficient");

    return 1;
}

`
I read some documentations about this in the Matlab website, and i found that there is a function block in Simulink to be used, but i have no idea how Simulink works.


text:
Q: requestLocationUpdates five times started from IntentService My control flow is in an IntentService (triggered by a GcmListenerService) and should now get the location of the user. As
LocationServices.FusedLocationApi.getLastLocation(mGoogleApiClient)

might return null, I should request some location updates. I assume with every update the location is more accurate than the one before because of GPS mechanics. I suppose five measurements/updates should be enough for an accurate location.
How can I implement that logic in an IntentService? The class implements the listener interfaces:
public class LocationIntentService extends IntentService
 implements GoogleApiClient.ConnectionCallbacks,
 GoogleApiClient.OnConnectionFailedListener,
 LocationListener

This way I could use a counter in public void onLocationChanged(Location location) and call LocationServices.FusedLocationApi.removeLocationUpdates() after five updates. However, I'm not sure if I can trust Android that the same IntentService lives that long and is not removed by the garbage collector as soon as onHandleIntent is done.
This is the complete code I'm using so far without the logic to collect only five updates:
public class LocationIntentService extends IntentService implements GoogleApiClient.ConnectionCallbacks, GoogleApiClient.OnConnectionFailedListener, LocationListener {

    private GoogleApiClient mGoogleApiClient;

    public LocationIntentService() {
        super("LocationIntentService");
    }

    @Override
    protected void onHandleIntent(Intent intent) {
        mGoogleApiClient = new GoogleApiClient.Builder(getBaseContext())
                .addApi(LocationServices.API)
                .addConnectionCallbacks(this)
                .addOnConnectionFailedListener(this)
                .build();

        mGoogleApiClient.connect();
    }

    @Override
    public void onConnectionFailed(ConnectionResult result) {
        System.out.println(result.toString());
    }

    @Override
    public void onConnected(Bundle connectionHint) {
        LocationRequest mLocationRequest = LocationRequest.create();
        mLocationRequest.setInterval(500);
        mLocationRequest.setPriority(LocationRequest.PRIORITY_HIGH_ACCURACY);
        if (ActivityCompat.checkSelfPermission(this, Manifest.permission.ACCESS_FINE_LOCATION) == PackageManager.PERMISSION_GRANTED) {
            LocationServices.FusedLocationApi.requestLocationUpdates(mGoogleApiClient, mLocationRequest, this);
        }
    }

    @Override
    public void onConnectionSuspended(int cause) {
    }

    private void displayLocation(Location location) {
        System.out.println(location.toString());
        DbHandler dbHandler = new DbHandler(getBaseContext());
        double latitude = location.getLatitude();
        double longitude = location.getLongitude();
        double altitude = location.getAltitude();
        float speed = location.getSpeed();
        long time = location.getTime();
        float accuracy = location.getAccuracy();
        PersistedLocation persistedLocation = new PersistedLocation(time, latitude, longitude, altitude, accuracy, speed);
        dbHandler.insertLocation(persistedLocation);
    }

    @Override
    public void onLocationChanged(Location location) {
        displayLocation(location);
    }
}

A: I managed to accomplish this with setNumUpdates(int i) and setExpirationDuration(long l).
@Override
public void onConnected(Bundle connectionHint) {
    LocationRequest mLocationRequest = LocationRequest.create();
    mLocationRequest.setInterval(500);
    mLocationRequest.setNumUpdates(5);
    mLocationRequest.setExpirationDuration(10000);
    mLocationRequest.setPriority(LocationRequest.PRIORITY_HIGH_ACCURACY);
    if (ActivityCompat.checkSelfPermission(this, Manifest.permission.ACCESS_FINE_LOCATION) == PackageManager.PERMISSION_GRANTED) {
        LocationServices.FusedLocationApi.requestLocationUpdates(mGoogleApiClient, mLocationRequest, this);
    }
}


text:
Q: RadioButton and CheckBox not showing in Custom Look and Feel I'm creating a custom Look and Feel for a company as my final trainee ship for graduation. I've been stuck on this part for a few days now and me and my colleagues can't seem to fix it.
I'm trying to create a custom radio button an checkbox for the Look and Feel. Now when I want to display the stock ones to the screen / JFrame it won't display.
Once I activate my Look and Feel the checkboxes and radio buttons dissapear. But the label of them does display on screen. When I create the checkbox / radio outside the look and feel or give a nimbus look and feel to them, it does display. So somehow my Look and Feel is breaking things. Can anyone help?
This is my code for the radio button;
public class MyRadioBut extends BasicRadioButtonUI {

    public MyRadioBut()
    {
        super();
    }

    public static ComponentUI createUI(JComponent c) {
        return new MyRadioBut();
    }

    @Override
    public void installUI(final JComponent c) {
        super.installUI(c);
    }

    public static MyRadioBut createRadio()
    {
        MyRadioBut radio = new MyRadioBut();

        return radio;
    }
    private boolean defaults_initialized = false;
    @Override
    public void installDefaults(AbstractButton b) {
        super.installDefaults(b);

    }
}

Code for checkbox is the same.
Look and feel code;
package iac.lookandfeel;

import java.awt.Font;

import javax.swing.SwingUtilities;
import javax.swing.UIDefaults;
import javax.swing.UIManager;
import javax.swing.plaf.basic.BasicLookAndFeel;

public class MyLookAndFeel extends BasicLookAndFeel {

    /**
     *
     */
    private static final long serialVersionUID = 1L;

    static MyButton btn = new MyButton();
    static MyProgressBar pb = new MyProgressBar();
    static MyLabel lbl = new MyLabel();
    static MyTab tab = new MyTab();
    static MyRadioBut radio = new MyRadioBut();
    static MyComboBox combo = new MyComboBox();

    public MyLookAndFeel() {
        super();

    }

    @Override
    public String getName() {
        // TODO Auto-generated method stub
        return "IAC Look and Feel";
    }

    @Override
    public String getID() {
        // TODO Auto-generated method stub
        return "IAC Look and Feel";
    }

    @Override
    public String getDescription() {
        // TODO Auto-generated method stub
        return "IAC's Look And Feel";
    }

    @Override
    public boolean isNativeLookAndFeel() {
        // TODO Auto-generated method stub
        return false;
    }

    @Override
    public boolean isSupportedLookAndFeel() {
        // TODO Auto-generated method stub
        return true;
    }

    @Override
    public boolean getSupportsWindowDecorations()
    {
        return true;
    }
    public static void setAllFonts() {
        Font defaultFont = UIManager.getDefaults().getFont("Button.font");
        int defaultSize = defaultFont.getSize();
        Font font = new Font("Serif", Font.PLAIN, 50);

        UIManager.put("Button.font", font);

        UIManager.put("RadioButton.font", font);
        UIManager.put("CheckBox.font", font);

        UIManager.put("ComboBox.font", font);
        UIManager.put("Label.font", font);
        UIManager.put("TabbedPane.font", font);
        UIManager.put("TextField.font", font);
        UIManager.put("PasswordField.font", font);
        UIManager.put("TextArea.font", font);
        UIManager.put("ProgressBar.font", font);

    }

    @Override
    protected void initClassDefaults(UIDefaults table)
    {
        setAllFonts();
        MyButton.createButton();
        MyProgressBar.createBar();
        MyLabel.createLabel();
        MyTab.createTab();
        MyRadioBut.createRadio();
        MyCheckBox.createCheckBox();
        MyComboBox.createCombo();

        super.initClassDefaults(table);
        String IACPackage = "iac.lookandfeel.";
        final String basicPackageName = "javax.swing.plaf.basic.";
        Object[] uiDefaults = {
                "ButtonUI", IACPackage + "MyButton",
                "CheckBoxUI", IACPackage + "MyCheckBox",
                "ColorChooserUI", basicPackageName + "BasicColorChooserUI",
                "FormattedTextFieldUI", basicPackageName + "BasicFormattedTextFieldUI",
                "MenuBarUI", basicPackageName + "BasicMenuBarUI",
                "MenuUI", basicPackageName + "BasicMenuUI",
                "MenuItemUI", basicPackageName + "BasicMenuItemUI",
                "CheckBoxMenuItemUI", basicPackageName + "BasicCheckBoxMenuItemUI",
                "RadioButtonMenuItemUI", basicPackageName + "BasicRadioButtonMenuItemUI",
                "RadioButtonUI", IACPackage + "MyRadioBut",
                "ToggleButtonUI", basicPackageName + "BasicToggleButtonUI",
                "PopupMenuUI", basicPackageName + "BasicPopupMenuUI",
                "ProgressBarUI", IACPackage + "MyProgressBar",
                "ScrollBarUI", basicPackageName + "BasicScrollBarUI",
                "ScrollPaneUI", basicPackageName + "BasicScrollPaneUI",
                "SplitPaneUI", basicPackageName + "BasicSplitPaneUI",
                "SliderUI", basicPackageName + "BasicSliderUI",
                "SeparatorUI", basicPackageName + "BasicSeparatorUI",
                "SpinnerUI", basicPackageName + "BasicSpinnerUI",
                "ToolBarSeparatorUI", basicPackageName + "BasicToolBarSeparatorUI",
                "PopupMenuSeparatorUI", basicPackageName + "BasicPopupMenuSeparatorUI",
                "TabbedPaneUI", IACPackage + "MyTab",
                "TextAreaUI", basicPackageName + "BasicTextAreaUI",
                "TextFieldUI", basicPackageName + "BasicTextFieldUI",
                "PasswordFieldUI", basicPackageName + "BasicPasswordFieldUI",
                "TextPaneUI", basicPackageName + "BasicTextPaneUI",
                "EditorPaneUI", basicPackageName + "BasicEditorPaneUI",
                "TreeUI", basicPackageName + "BasicTreeUI",
                "LabelUI", IACPackage + "MyLabel",
                "ListUI", basicPackageName + "BasicListUI",
                "ToolBarUI", basicPackageName + "BasicToolBarUI",
                "ToolTipUI", basicPackageName + "BasicToolTipUI",
                "ComboBoxUI", IACPackage + "MyComboBox",
                "TableUI", basicPackageName + "BasicTableUI",
                "TableHeaderUI", basicPackageName + "BasicTableHeaderUI",
                "InternalFrameUI", basicPackageName + "BasicInternalFrameUI",
                "DesktopPaneUI", basicPackageName + "BasicDesktopPaneUI",
                "DesktopIconUI", basicPackageName + "BasicDesktopIconUI",
                "FileChooserUI", basicPackageName + "BasicFileChooserUI",
                "OptionPaneUI", basicPackageName + "BasicOptionPaneUI",
                "PanelUI", basicPackageName + "BasicPanelUI",
                "ViewportUI", basicPackageName + "BasicViewportUI",
                "RootPaneUI", basicPackageName + "BasicRootPaneUI",
        };
        //   UIManager.put(MyLookAndFeel.UI_CLASS_ID,  MyButton.class.getName());
        table.putDefaults(uiDefaults);
    }
}

IACPackage is my own package which I use in all components.
Hope one of you guys got an idea.
I have a test gui which I test the look and feel on: I create the checkbox and radio like this;
JCheckBox CBox = new JCheckBox("Checkbox");
    JRadioButton Radio = new JRadioButton("Radio");
It does display the string but not the icons.

A: Fixed it myself.
Icon defaultIcon;
defaultIcon = UIManager.getIcon("CheckBox.icon");
UIManager.put("CheckBox.icon", defaultIcon);

I used this to get the default icon from UI manager and after that I put it back with the put statement. Quite stupid solution but it works!


text:
Q: How to solve a problem using row_number, lag / lead, join SQL In sql, I'm completely new, but I need to solve this problem using only row_number, lag / lead, join. I've been struggling with the problem for 2 days and I just can't solve it correctly.
We have a table with data, you need to get the answer of the following from:
 Client 2017-11-01 04:59:07.6140000 2017-11-01 05:06:53.9090000 Agent C56D5EF0-CBC4-473F-90A7-A7A10223AE3E
    Client 2017-11-01 05:07:18.7020000 2017-11-01 05:07:43.1280000 Agent C56D5EF0-CBC4-473F-90A7-A7A10223AE3E
    Client 2017-11-01 05:07:59.5780000 2017-11-01 05:14:12.5870000 Agent C56D5EF0-CBC4-473F-90A7-A7A10223AE3E
    Client 2017-11-01 05:14:56.3690000 2017-11-01 06:06:56.1080000 Agent C56D5EF0-CBC4-473F-90A7-A7A10223AE3E
    Client 2017-11-01 06:21:17.5480000 2017-11-01 06:21:38.4280000 Agent C56D5EF0-CBC4-473F-90A7-A7A10223AE3E

It's my code:
      if object_id('tempdb..#c1') is not null
          drop table #c1

        create table #c1 (datemessage datetime2 ,id_tasks nvarchar(255),Whowritedmessage nvarchar(255));

        insert into #c1
        values
        ('2017-11-01 04:59:07.614','C56D5EF0-CBC4-473F-90A7-A7A10223AE3E','Client'),
        ('2017-11-01 05:05:17.500','C56D5EF0-CBC4-473F-90A7-A7A10223AE3E','Client'),
        ('2017-11-01 05:06:53.909','C56D5EF0-CBC4-473F-90A7-A7A10223AE3E','Agent'),
        ('2017-11-01 05:06:53.909','C56D5EF0-CBC4-473F-90A7-A7A10223AE3E','Agent'),
        ('2017-11-01 05:07:18.702','C56D5EF0-CBC4-473F-90A7-A7A10223AE3E','Client'),
        ('2017-11-01 05:07:43.128','C56D5EF0-CBC4-473F-90A7-A7A10223AE3E','Agent'),
        ('2017-11-01 05:07:59.578','C56D5EF0-CBC4-473F-90A7-A7A10223AE3E','Client'),
        ('2017-11-01 05:09:55.063','C56D5EF0-CBC4-473F-90A7-A7A10223AE3E','Client'),
        ('2017-11-01 05:14:12.587','C56D5EF0-CBC4-473F-90A7-A7A10223AE3E','Agent'),
        ('2017-11-01 05:14:56.369','C56D5EF0-CBC4-473F-90A7-A7A10223AE3E','Client'),
        ('2017-11-01 06:06:56.108','C56D5EF0-CBC4-473F-90A7-A7A10223AE3E','Agent'),
        ('2017-11-01 06:07:07.279','C56D5EF0-CBC4-473F-90A7-A7A10223AE3E','Agent'),
        ('2017-11-01 06:21:17.548','C56D5EF0-CBC4-473F-90A7-A7A10223AE3E','Client'),
        ('2017-11-01 06:21:38.428','C56D5EF0-CBC4-473F-90A7-A7A10223AE3E','Agent')

        SELECT
tabC.whowritedmessage,
tabA.datemessage,
tabA.answer,
tabA.whowritedmessage,
tabA.id_tasks
FROM(SELECT
ROW_NUMBER() OVER (PARTITION BY whowritedmessage ORDER BY datemessage) as number,
whowritedmessage
FROM #c1
where whowritedmessage ='Client') as tabC
join (SELECT
              top 50 percent
ROW_NUMBER() OVER (PARTITION BY whowritedmessage ORDER BY datemessage) as number,
LEAD(datemessage,7) OVER (ORDER BY whowritedmessage) as datemessage,
datemessage as answer,
whowritedmessage,
id_tasks
FROM #c1
) as tabA  on tabA.number = tabC.number

We have a table with data, you need to get the answer of the following from:
 Client 2017-11-01 04:59:07.6140000 2017-11-01 05:06:53.9090000 Agent C56D5EF0-CBC4-473F-90A7-A7A10223AE3E
 Client 2017-11-01 05:07:18.7020000 2017-11-01 05:07:43.1280000 Agent C56D5EF0-CBC4-473F-90A7-A7A10223AE3E
 Client 2017-11-01 05:07:59.5780000 2017-11-01 05:14:12.5870000 Agent C56D5EF0-CBC4-473F-90A7-A7A10223AE3E
 Client 2017-11-01 05:14:56.3690000 2017-11-01 06:06:56.1080000 Agent C56D5EF0-CBC4-473F-90A7-A7A10223AE3E
 Client 2017-11-01 06:21:17.5480000 2017-11-01 06:21:38.4280000 Agent C56D5EF0-CBC4-473F-90A7-A7A10223AE3E

but I constantly get 7 lines, although there should be 5, because if the client goes the same next line, it is not taken into account and the same with the agent

A: Check this script-
WITH CTE AS
(
    SELECT *,
    LAG(whowritedmessage) OVER (ORDER BY datemessage) who_lag
    FROM #c1
)

SELECT whowritedmessage,
datemessage,
ans,
ISNULL(who_lag,'Agent') whowritedmessage2,
id_tasks
FROM
(
    SELECT *,
    LEAD(datemessage) OVER (ORDER BY datemessage) ans,
    LEAD(whowritedmessage) OVER (ORDER BY datemessage) who_lead
    FROM CTE
    WHERE (whowritedmessage <> who_lag OR who_lag IS NULL)
)A
WHERE whowritedmessage = 'Client'

Output is-
whowritedmessage    datemessage                 ans                          whowritedmessage2  id_tasks
Client              2017-11-01 04:59:07.6140000 2017-11-01 05:06:53.9090000  Agent              C56D5EF0-CBC4-473F-90A7-A7A10223AE3E
Client              2017-11-01 05:07:18.7020000 2017-11-01 05:07:43.1280000  Agent              C56D5EF0-CBC4-473F-90A7-A7A10223AE3E
Client              2017-11-01 05:07:59.5780000 2017-11-01 05:14:12.5870000  Agent              C56D5EF0-CBC4-473F-90A7-A7A10223AE3E
Client              2017-11-01 05:14:56.3690000 2017-11-01 06:06:56.1080000  Agent              C56D5EF0-CBC4-473F-90A7-A7A10223AE3E
Client              2017-11-01 06:21:17.5480000 2017-11-01 06:21:38.4280000  Agent              C56D5EF0-CBC4-473F-90A7-A7A10223AE3E

Changed:
For better understanding, I have added 1 more CTE here with same output as above script.
WITH CTE AS
(
    SELECT *,
    LAG(whowritedmessage) OVER (ORDER BY datemessage) who_lag
    FROM #c1
),
CTE2 AS
(
    SELECT  whowritedmessage,   datemessage,
    LEAD(datemessage) OVER (ORDER BY datemessage) ans,
    ISNULL(who_lag,'Agent') whowritedmessage2,
    id_tasks
    FROM CTE
    WHERE (whowritedmessage <> who_lag OR who_lag IS NULL)
)

--SELECT * FROM CTE
--SELECT * FROM CTE2
SELECT * FROM CTE2 WHERE whowritedmessage = 'Client'

You can run one by one SELECT statement(Commented now) to understand how data is transforming step by step. Remember, 3rd SELECT statement is your final script and other 2 commented SELECT is just for your checking. Hope this will help you understand the whole process.

A: SELECT t2.whowritedmessage,t2.datemessage,t2.answer,ISNULL(this_lag,'Agent') as whowritedmessage2,t2.id_tasks
FROM
(SELECT *,
LEAD(datemessage) over (order by datemessage) answer,
LEAD(whowritedmessage) over (order by datemessage) this_lead
FROM
 (SELECT *,
LAG(whowritedmessage) over (order by datemessage) this_lag
FROM #c1) as t1
Where whowritedmessage <> this_lag or this_lag IS NULL) as t2
Where whowritedmessage = 'Client'


text:
Q: TIMIT Corpus. Cant play .WAV audiofile but can play it if I convert it into .mp3 I downloaded the files from the timit speech corpus found here: https://github.com/philipperemy/timit
When I try playing the .WAV files with groove music or windows media player I get an error saying the file cannot be played.
However after converting the file to mp3 using an online converter, the file suddenly works.
The .WAV files are only around 100-200KB in size.
Does anyone know what the reason for this problem might be?

A: Found the answer here: reading a WAV file from TIMIT database in python
Apparently it is not actually a .WAV file but a NIST file.


text:
Q: Perl RegEx Parse block of notes on 10 digit number Ok, so here's the thing. I have note in an old sql server text format. It puts all notes for a record in one big blob of data. I need to take that blob of text and parse it out to create one row for each note entry with separate columns for timestamp, user, and note text. The only way do do this that I can think of is to use regex to locate the unix timestamp for each note and parse on that. I know that there is the split function for parsing on delimiters, but that removes the delimiter. I need to parse on \d{10} but also retain the 10 digit number. Here is some sample data.
create table test_table
(
job_number number,
notes varchar2(4000)
)

insert into test_table values
(12345, '1234567890 username notes text notes text notes text notes text 5468204562 username notes text notes text notes text notes text 1025478510 username notes text notes text notes text notes text')
(12346, '2345678901 username notes text notes text notes text notes text 1523024512 username notes text notes text notes text notes text 1578451236 username notes text notes text notes text notes text')
(12347, '2345678902 username notes text notes text notes text notes text 2365201214 username notes text notes text notes text notes text 1202154215 username notes text notes text notes text notes text')

I would like to see one record for each note to look like this.
JOB_NUMBER        DTTM    USER     NOTES_TEXT
----------    ----------  ----     ----------
12345         1234567890  USERNAME notes text notes text notes text notes text
12345         5468204562  USERNAME notes text notes text notes text notes text
12345         1025478510  USERNAME notes text notes text notes text notes text
12346         2345678901  USERNAME notes text notes text notes text notes text
12346         1523024512  USERNAME notes text notes text notes text notes text
12346         1578451236  USERNAME notes text notes text notes text notes text
12347         2345678902  USERNAME notes text notes text notes text notes text
12347         2365201214  USERNAME notes text notes text notes text notes text
12347         1202154215  USERNAME notes text notes text notes text notes text

Thank you for any help you can provide

A: Text::ParseWords can handle the quoted strings and split on comma. You can skip ahead in the input by using the flip-flop operator 1 .. /values/. This particular skip method may need to be revised.
Then it is just a matter of parsing the strings, which can be done by splitting using a lookahead assertion and then capturing the various entries in each substring. The regex in the split:
my @entries = split /(?<!^)(?=\d{10})/, $data;

has a negative lookbehind assertion to avoid matching at the start of the string ^, and a lookahead assertion to match 10 numbers. This will effectively split at the numbers and keep them.
The DATA file handle is used for demonstration, simply replace <DATA> with <> to use with argument file name.
use strict;
use warnings;
use Text::ParseWords;

my $format = "%-12s %-12s %-10s %s\n";              # format for printing
my @headers = qw(JOB_NUMBER DTTM USER NOTES_TEXT);
printf $format, @headers;
printf $format, map "-" x length, @headers;         # print underline
while (<DATA>) {
    next while 1 .. /values/;                       # skip to data
    s/^\(|\)$//g;                                   # remove parentheses
    my ($job, $data) = quotewords('\s*,\s*',0, $_); # parse string
    my @entries = split /(?<!^)(?=\d{10})/, $data;  # split into entries
    for my $entry (@entries) {                      # parse each entry
        my ($dttm, $user, $notes) = $entry =~ /^(\d+)\s+(\S+)\s+(.*)/;
        printf $format, $job, $dttm, $user, $entry;
    }
}

__DATA__
create table test_table
(
job_number number,
notes varchar2(4000)
)

insert into test_table values
(12345, '1234567890 username notes text notes text notes text notes text 5468204562 username notes text notes text notes text notes text 1025478510 username notes text notes text notes text notes text')
(12346, '2345678901 username notes text notes text notes text notes text 1523024512 username notes text notes text notes text notes text 1578451236 username notes text notes text notes text notes text')
(12347, '2345678902 username notes text notes text notes text notes text 2365201214 username notes text notes text notes text notes text 1202154215 username notes text notes text notes text notes text')

Output:
JOB_NUMBER   DTTM         USER       NOTES_TEXT
----------   ----         ----       ----------
12345        1234567890   username   1234567890 username notes text notes text notes text notes text
12345        5468204562   username   5468204562 username notes text notes text notes text notes text
12345        1025478510   username   1025478510 username notes text notes text notes text notes text
12346        2345678901   username   2345678901 username notes text notes text notes text notes text
12346        1523024512   username   1523024512 username notes text notes text notes text notes text
12346        1578451236   username   1578451236 username notes text notes text notes text notes text
12347        2345678902   username   2345678902 username notes text notes text notes text notes text
12347        2365201214   username   2365201214 username notes text notes text notes text notes text
12347        1202154215   username   1202154215 username notes text notes text notes text notes text