text:
Q: Transitioning between open close in details element Is it possible to animate the transition between the open/close state of the  element with just CSS?

A: Given the height has to snap at some point I prefer to start to animate the height and then snap. If your lucky enough to have all the elements a similar height this solution can be quite effective. (you do need a div inside your details elements though)
@keyframes slideDown {
    0% {
        opacity: 0;
        height: 0;
    }
    100% {
        opacity: 1;
        height: 20px; /* height of your smallest content, e.g. one line */
    }
}
details {
    max-width:400px;
}
details[open]>div {
    animation-name: slideDown;
    animation-duration: 200ms;
    animation-timing-function:ease-in;
    overflow:hidden;
}

see http://dabblet.com/gist/5866920 for example

A: No, not currently. Yes, but only if you know the height or can animate the font-size.
Originally, this wasn't the case. From http://html5doctor.com/the-details-and-summary-elements/, "...if you could use CSS transitions to animate the  opening and closing, but we can't just yet."  (There is a comment at HTML5 doctor near the end, but it appears to require JS to force the CSS animation.)
It was possible to use different styles based on whether it's opened or closed, but transitions didn't "take" normally. Today, however, the transitions do work if you know the height or can animate the font-size. See http://codepen.io/morewry/pen/gbJvy for examples and more details.
This was the 2013 solution that kind of fakes it:
CSS (May need to add prefixes)
/* http://daneden.me/animate/ */
@keyframes fadeInDown {
    0% {
        opacity: 0;
        transform: translateY(-1.25em);
    }
    100% {
        opacity: 1;
        transform: translateY(0);
    }
}
.details-animated[open] {
    animation-name: fadeInDown;
    animation-duration: 0.5s;
}

HTML

    CSS Animation - Summary
    Try using [Dan Eden's fadeInDown][1] to maybe fake it a little.  Yay, some animation.

This works today:
CSS (May need to add prefixes)
.details-animated {
  transition: height 1s ease;
}
.details-animated:not([open]) { height: 1.25em; }
.details-animated[open] { height: 3.75em; }

PS: Only tested in Chrome.  Hear FF still doesn't support details in general. IE and Edge prior to version 79 still don't support details.
(You can use keyframe animations or transitions to do all sorts of other animations for open. I've chosen fadeInDown for illustration purposes only. It is a reasonable choice which will give a similar feel if you are unable to add extra markup or will not know the height of the contents. Your options are, however, not limited to this: see the comments on this answer that include two alternatives, including the font-size approach.)

A: My short answer is : you can not transition between summary and the rest of the details content.
BUT!
You can do some nice transition inside the summary between the selector details and details[open]

details{
  position: relative;
  width: 100px;height: 100px;
  perspective: 1000px;
}
div{
  position: absolute;
  top: 20px;
  width: 100px;height: 100px;
  background: black;
}
details .transition{
  transition: 1s linear;
  transform-origin: right top;
  ;
}
details[open] .transition{
  transform: rotateY(180deg);
  background: orangered;
}

NB : I answer this because it was the first result from googling on this!

A: Of course it's possible:

DETAILS[open] SUMMARY ~ * {
  animation: sweep 3s ease-in-out;
}

@keyframes sweep {
  0% {
    opacity: 0;
    margin-left: -10px
  }
  100% {
    opacity: 1;
    margin-left: 0px
  }
}

  Summary content
  Test test test test.


text:
Q: Very similar MySQL queries results significantly varying query durations (WHERE on timespans) I have a MySQL table with around 600 K rows in it (Engine: InnoDB).
MySQL is running in a virtualbox machine with Ubuntu 16.04 LTS in it. MySQL server version is 5.7.23, if that's relevant.
The columns in the WHERE clauses (open_time and close_time) are both indexed and they are both DATETIME columns.
The column that I'm taking the sum of (volume) is a double.
This query returns instantly (0.000 seconds):
SELECT *
FROM klines
WHERE (open_time between '2018-01-01 00:00:00' AND '2018-01-01 12:00:00')
;

EXPLAIN output:

Whereas this one takes almost a second to fetch (varies between 0.640 and 0.703 seconds between 10 tries):
SELECT SUM(volume)
FROM klines
WHERE open_time >= '2018-01-01 00:00:00' AND close_time <= '2018-01-01 12:00:00'
;

EXPLAIN output:

Mind that both queries returns about the same rows (720 for first, 721 for the second. Second query returns the same 720 rows which first one returns, plus another one).
So, if I want to get just the rows, it does not matter if I use WHERE clause for two columns or one. But if I want to get the SUM of a column, query gets drastically slower when I use WHERE clause for two columns. If I use a single column however, it again returns instantly.
While I'm perfectly OK with using the query which queries the table using between two open_time criterias, I'm really curious about what's going on.
So, what would be the reason behind this?

A: open_time between '2018-01-01 00:00:00'
              AND '2018-01-01 12:00:00'

can easily use INDEX(open_time) to touch only the interesting rows.  But it is not possible to have an index that stops abruptly for this:
     open_time >= '2018-01-01 00:00:00'
AND close_time <= '2018-01-01 12:00:00'

INDEX(open_time) could be used, but the last half of the table would be scanned.  INDEX(close_time), similarly, would scan the first half of the table.  And there is now way to do both.
You probably have an additional constraint that is nowhere visible:

*

*[open..close] time ranges don't overlap?

*open is always < close?

These cannot be specified in standard SQL, nor is there any index formulation that would take advantage of either constraint.
Here are two rows that will mess up any optimization attempt:
INSERT INTO klines (open_time,             close_time)
            VALUES ('2018-01-01 06:00:00', '2037-12-31'),
                   ('1971-01-01',          '2018-01-01 06:00:00')
                   ('2037-01-01',          '1971-01-01')

There are fixes, but they require either assuming non-overlapping, then playing with the queries is severe ways; or playing with buckets.

redpajama_set_name: RedPajamaStackExchange


text:
Q: How to plot multiple dependent variables with seaborn? I want to consider time-series data, the three axes of an accelerometer to be exact.  I'm digging through the docs but am not immediately seeing how provide more than one signal and trying to figure out how to organize my data for pandas and seaborn in general.  After plotting a single run of the three signals, I hope to overlay multiple runs of those same signals to get a plot like this but for three signals:

import matplotlib.pyplot as plt
import pandas as pd
import seaborn as sns

data = [['t', 'x', 'y', 'z'],
        ['0', '1.024', '0.9980', '1.001'],
        ['1', '1.0-4', '0.9080', '1.021'],
        ...]
sns.set(color_codes=True)
df = pd.DataFrame(data, columns=['t', 'x', 'y', 'z'])
sns.tsplot(time='t', y=['x', 'y', 'z'], data=df).savefig("testing.png")

ValueError: setting an array element with a sequence.

pandas DataFrame docs
tsplot docs
Is there no way to combine these separate plots?
Plot multiple DataFrame columns in Seaborn FacetGrid

A: This seems to work:
N=100

num_runs = 3
out = []
for k in range(num_runs):
    data = np.random.rand(N,3) + np.sin(np.arange(N)/5)[:,np.newaxis]
    data = np.hstack([np.arange(N)[:,np.newaxis],data])
    data = np.hstack([np.zeros(N)[:,np.newaxis]+k,data])
    out.append(data)

data = np.vstack(out)

df = pd.DataFrame(data, columns=['sub','t', 'x', 'y', 'z'])
dfm = pd.melt(df, id_vars=['t','sub'], value_vars=['x', 'y', 'z'])
dfm
sns.tsplot(time='t',
           value='value',
           condition='variable',
           data=dfm,
           err_style="boot_traces",
           unit='sub',
           n_boot=50)

The data frame looks like this after pd.melt
    t   sub variable    value
0   0   0   x   0.952150
1   1   0   x   0.343075
2   2   0   x   0.630453
3   3   0   x   0.998851
4   4   0   x   1.237932
5   5   0   x   0.958720

Couple comments:

*

*tsplot wants the traces de-pivoted with a label column.  pd.melt does this for you.

*tsplot is also expecting multiple "trials" for a given variable, hence the loop I used to make the example dataframe.  Even if you only have one trace, you need to have a unit column that you can pass to tsplot.  Without that, I couldn't get it to work.


text:
Q: Show duplicates from one list with different ID's using linq I have a table with
ID  Name  ExcelID

1   a     1

2   b     1

3   a     2

4   b     2

5   c     2

I need to show the duplicates between two of the Excel ID's, so the output should show me 'C' as that is the unique value between excelid 1 & 2. For this reason i used the queries below to compare the two sets of data.
var assets = db.FPTStaticDataRatedFinancialAssetBase.OfType<FPTStaticDataRatedFinancialAssetBase>()
            .Where(c => c.FORATExcelId == fptexcel)
            .GroupBy(x => x.Name)
            .Select(y => y.FirstOrDefault()).ToList();

var assetsold = db.FPTStaticDataRatedFinancialAssetBase.OfType<FPTStaticDataRatedFinancialAssetBase>()
            .Where(c => c.FORATExcelId == fptexcelprevious)
            .GroupBy(x => x.Name)
            .Select(y => y.FirstOrDefault()).ToList();

I have grouped the data into two lists, one being excel id 1 and the second query being 2.
However if i try to use the except method to show the distinct values, it just shows me all values from both lists

A: var uniqueItems = db.FPTStaticDataRatedFinancialAssetBase.OfType<FPTStaticDataRatedFinancialAssetBase>()
   .GroupBy(p => p.Name)
   .Where(p => p.Count() == 1)
   .Select(p => p.FirstOrDefault());

should do the trick?
Trying it on the list you gave, it returned neatly item (5, "c", 2)

A: You can search for names where you only get one result :
var uniqueResult = db.FPTStaticDataRatedFinancialAssetBase.OfType<FPTStaticDataRatedFinancialAssetBase>()
        .Where(c => c.FORATExcelId == fptexcel || c.FORATExcelId == fptexcelprevious)
        .GroupBy(x => x.Name)
        .Where(c => c.Count() == 1)
        .Select(y => y.FirstOrDefault()).ToList();


text:
Q: Ubuntu 14.04 LTS wifi hardware disabled I've just installed Ubuntu 14.04 LTS on my HP Envy spectre xt 13-2000eg and i just can't get my wifi working.
I have an Intel Centrino Advanced-N 6205
I also have the gnome shell installed (I don't think thats the problem) when I try to connect to a wifi network it says hardware disabled.
When I run
rfkill list

I get
0: phy0: Wireless LAN
Soft blocked: no
Hard blocked: yes

Further I already checked, but I don't have a hardware switch for wireless connections. Simply trying
rfkill unblock all

won't do the trick either.
Funny thing is that for a short time the wifi worked but after the reboot i had the same problem again.
Maybe it is intel's iwlwifi? I couldn't figure out how to install that :/
I really hope someone can help me.

A: Hard Block cannot be unblocked using the software.
Your WiFi is perhaps turned of by your keyboard WiFi shortcut. It is also possible that it is disabled by your BIOS settings.  Try to enable it using your keyboard shortcut or any other key available in you system. Also check you BIOS settings for any WiFi related settings.

A: I had the same problem with HP Pavilion G6 and I tried everything including several re-installations. The solution is unbelievably simple. All I did was to load BIOS default setting and the hard block was removed. Working perfectly since then. Try and see if this helps.

A: Update: As I already mentioned in the comment of the answer my wifi now kind of works.
I figured out that after the restart the wifi is "hardware disabled" however if I suspend (in my case just close the laptop) and then immediately reopen i.e. wake it up again it works.
I have no clue why, but it does.
Maybe this helps someone, too.


text:
Q: How to get sorted elements from an starting index to a ending index in an array? Given an array of t integers we need to answer x queries.Each query describes an starting index and a ending index ,we need to print the sorted elements in the sub-array.
For Example-
Array={16,9,10,19,2}
for query 1 3 ,the answer would be
9 10 16
for query 2 5,the answer would be
2 9 10 19
Please suggest an optimal solution?Are there any advanced data structures involved?
The number of elements can be upto 10^5 .

A: Tag each element with it's position:
16 1, 9 2, 10 3, 19 4, 2 5

Sort it:
2 5, 9 2, 10 3, 16 1, 19 4

For each query walk through the result and return the elements which are within the range.
After preprocessing each query takes O(N) work.

A:
Are there any advanced data structures involved?

Nope, not at all. First you obtain the range given by those indexes, then you sort the resulting range. Then you print it. Seems pretty simple!
In fact, it's so simple, I'm going to show you an example:
#include <algorithm>
#include <vector>
#include <iostream>
#include <cassert>

template <typename T, size_t N>
size_t len(T (&)[N])
{
   return N;
}

int main()
{
    int array[] = {16,9,10,19,2};

    const int START = 1;  // user input ( 1-based index,)
    const int END   = 3;  // user input (inclusive range)

    assert((START-1) >= 0 && (START <= len(array)));
    assert((END-1)   >= 0 && (END <= len(array)));

    // These two lines do the work.
    // Everything else is just exposition.
    //
    // First construct a vector from the requested subrange,
    // then sort that resulting vector.
    //
    std::vector<int> v(array+(START-1), array+END);
    std::sort(std::begin(v), std::end(v));

    // Output the results to console for demo.
    // Uses C++ ranged-for syntax; replace with more
    // verbose equivalent if required, or do something
    // else with `v`.
    //
    for (auto elm : v) {
       std::cout << elm << ' ';
    }
}

// Output: 9 10 6

Live demo
You could make the code even terser (and possibly more efficient) by copying the subrange into an std::set rather than a std::vector, so sorting happens during insertion rather than after-the-fact. I hardly think either is ever going to be as much as O(n^2), contrary to your claims.
Can you do sufficient preprocessing to share information between individual queries and get your complexity down still further? I don't know. I don't think so.

A: If I understood your question: Sort it.
You can use any sorting algorithm you want, Wikipedia lists a few.
Depending on which algorithm you choose, you may need extra memory / data structures.
If sorting should come later, copy the array and sort the copy. Makes more sense, than sorting over and over again for every query.


text:
Q: Assembly error when compiling with GCC I'm getting "no such instruction" errors when compiling a .s file with this command:
$ gcc -s -o scall scall.s
scall.s: Assembler messages:
scall.s:2: Error: no such instruction: `section '
scall.s:4: Error: no such instruction: `global _start'
scall.s:7: Error: unsupported instruction `mov'
scall.s:8: Error: unsupported instruction `mov'
scall.s:11: Error: operand size mismatch for `int'
scall.s:13: Error: no such instruction: `section .data'
scall.s:15: Error: no such instruction: `msglength .word 12'

Here is the code of the file:
section .text
    global _start

_start:
    mov 4,%eax
    mov 1,%ebx
    mov $message,%ecx
    mov $msglength,%edx
    int  $0x80

section .data
   message: .ascii "Hello world!"
   msglength .word 12

How can I get rid of the errors?

A: I think the following code will compile ("gcc" can compile .s and .S files and link them with C library by default but "as" do the same and don't link code with C library)
as :
.section .text
    .global _start
_start:
    mov $4,%eax
    mov $1,%ebx
    mov $message,%ecx
    mov msglength,%edx
    int  $0x80

    mov $1, %eax
    mov $0, %ebx
    int $0x80
.section .data
    message: .ascii "Hello world!"
    msglength: .word 12

gcc:
.section .text
    .global main
main:
    mov $4,%eax
    mov $1,%ebx
    mov $message,%ecx
    mov msglength,%edx
    int  $0x80

    mov $1, %eax
    mov $0, %ebx
    int $0x80
.section .data
    message: .ascii "Hello world!"
    msglength: .word 12

A: Correct it as follows and compile it with -c param gcc -c test.s -o test
.text

_start:
.global main

main:
    mov 4,%eax
    mov 1,%ebx
    mov $message,%ecx
    mov $msglength,%edx
    int  $0x80

.data
   message: .ascii "Hello world!"
   msglength: .word 12


text:
Q: android how to set Error image using Aquery library I have a custom Gridview. In my adapter asynchronous image downloading done using AQuery. images are downloaded properly but in some cases error will occur so that time imageView background goes totaly white.i want to set that error image.
Now here is the code of my adapter in gridView():
try{
            String[] tmp_arr_thumb_img = prodItems.get(holder.position).getprod_image().split(global.split_seprator);
            //String imageID = tmp_arr_thumb_img[0];
            String thumbImg = tmp_arr_thumb_img[1];

            if (aQuery.shouldDelay(holder.position, convertView, parent, global.GLOBAL_UPLOADED_PHOTOS_URL + thumbImg)){
                aQuery.id(holder.imageView).image(R.drawable.no_image);
            }else{
                aQuery.id(holder.imageView)
                        .image(global.GLOBAL_UPLOADED_PHOTOS_URL + thumbImg,true,true,200,0, new BitmapAjaxCallback(){
                            @Override
                            protected void callback(String url, ImageView iv, Bitmap bm, AjaxStatus status) {

                                iv.setImageBitmap(bm);
                            }
                        }.animation(AQuery.FADE_IN));
            }
        }catch (OutOfMemoryError err){
            err.printStackTrace();
        }

A: Please update your code with this wil use a place holder imaage
aQuery.id(holder.imageView)
                    .image(global.GLOBAL_UPLOADED_PHOTOS_URL + thumbImg,true,true,200,R.drawable.placeholder, new BitmapAjaxCallback(){
                        @Override
                        protected void callback(String url, ImageView iv, Bitmap bm, AjaxStatus status) {

                            iv.setImageBitmap(bm);
                        }
                    }.animation(AQuery.FADE_IN));

A: If we are not able to load the image, use a default image (R.drawable.default_image)
String imageUrl = "http://www.vikispot.com/z/images/vikispot/android-w.png";
aq.id(R.id.image1).image(imageUrl, true, true, 0, R.drawable.default_image);

Make image view "invisible" if image failed to load
imageUrl = "http://a.b.com/invalid.jpg";
aq.id(R.id.image1).image(imageUrl, true, true, 0, AQuery.INVISIBLE);

Make image view "gone" if image failed to load
aq.id(R.id.image1).image(imageUrl, true, true, 0, AQuery.GONE);


text:
Q: Why is Angular validation done in components/Forms not once on Domain Model? I've come to Angular from a Grails background where you would define your business rules validation in one place against a domain model. GORM.... So when I've come to Angular, by way of Ionic, I'm surprised to not see something familiar. Am I missing something here? Is there a better way?

A: You can implement validation in any case you want. Just add 1 more layer between angular forms and your domain.
In general, Angular doesn't dictate what way your application should work. It just gives you instruments for interacting with browser and APIs.
You always can implement Domain#valid() method and update fields via Reactive Forms.
@Component({})
export class MyComponent implements OnInit{

    public form: Form = this.fb.group({
        fName: ['', []],
        lName: ['', []]
    });

    constructor(fb: FormBuilder){}

    ngOnInit(){
        this.form.valueChanges.subscribe((form) => {
            let entity: Entity = new Entity(form);
            let errors: ValidationErrors = entity.valid();
            if(errors.length){
                this.form.setErrors(errors);
                this.form.updateValueAndValidity();
            }
        });
    }
}


text:
Q: Models for vibrations and stress waves generated due to impact? Say that a small metal ball impacts a long thin cylindrical rod from above (let's say height of around 10 cm) in an elastic collision and causes stress waves to propagate left and right from the point of collision. Is there some model in literature that describes the shape of stress wave (spatially) that will be generated? I am assuming a sinusoidal stress wave won't be created and that the wave would be described by some sort of random power spectral density. Is that correct?
I am also curious about the time dynamics of the stress wave - is it correct to say that higher frequencies decay faster than lower frequency ones?
I'm from an EE background (hence not much background in mechanics) working on a research problem, and would greatly appreciate any tips that would help me get started!


text:
Q: Getting NULL instead the string value in soap request I have a mobile application which communicates with my soap web service through ajax.
The user have to insert 2 fields to login (uname and password) and when he press the login
button, a javascript method is been called to post the data to the web service via ajax.
I can get the input values from the html page, but when I debug the web service I see that the arguments that were received are null instead the values that the user entered, and I don't see why..
function login()
{
  var uname = document.getElementById('uname').value;
  var pass  = document.getElementById('password').value;

  var soapRequest =
        '<?xml version="1.0" encoding="utf-8"?> \
        <soap:Envelope xmlns:xsi="http://www.w3.org/2001/XMLSchema-instance"\
            xmlns:xsd="http://www.w3.org/2001/XMLSchema"\
            xmlns:soap="http://schemas.xmlsoap.org/soap/envelope/">\
          <soap:Body>\
            <Login xmlns="http://service.webservice.org/">\
              <Name>' + uname + '</Name>\
              <Password>' + pass + '</Password>\
            </Login>\
          </soap:Body>\
        </soap:Envelope>';

  $.ajax({
    type : "POST",
    url :  "http://localhost:8080/WebService/Service",
    contentType: "text/xml",
    dataType: "xml",
    data: soapRequest,

    success : function(data, status, req, xml, xmlHttpRequest, responseXML)
    {
        var xmlText = $(req.responseXML).find('LoginResult').text();
        alert(xmlText);
            },
    error: function ()
    {
        alert("error");
    }

});

A: The answer is that we need to declare the namespaces of the method we call in soap request.
so after you deploy your web service to the server (glassfish or something else) it creates
the WSDL file and each method has namespace.
so the soap request should be like that
var soapRequest =
    '<?xml version="1.0" encoding="utf-8"?> \
    <soap:Envelope xmlns:xsi="http://www.w3.org/2001/XMLSchema-instance"\
        xmlns:xsd="http://www.w3.org/2001/XMLSchema"\
        xmlns:soap="http://schemas.xmlsoap.org/soap/envelope/">\
      <soap:Body>\
        <ns2:Login xmlns:ns2="http://service.webservice.org/">\
          <Name>' + uname + '</Name>\
          <Password>' + pass + '</Password>\
        </ns2:Login>\
      </soap:Body>\
    </soap:Envelope>';

ns2 is the namespace that was created by default, you can set your namespace by yourself


text:
Q: How can I split a dataframe into multiple columns when my column header has \ in the name? I have a dataframe called ratings. It is a single column, named "tconst\taverageRating\tnumVotes", although it needs to be split into 3, separated by "\".
I understand that this statement can be used: ratings[['tconst','taverageRating','tnumVotes']] = ratings.???.str.split("\",expand=True,)
However, when I replace ??? with the actual column name, I get an error. I believe this is because of the \s in the column header.
Any help would be greatly appreciated.

A: Are you sure you are reading the data in correctly?
Looking at the header names, it looks likely that your data is actually \t i.e.tab separated (so, \t and numVotes make sense separately). In that case you should read your data like this:
pd.read_csv('http://language.media.mit.edu/data/public/unesco_langlang_20120722_iso639-3.txt', sep='\t')


text:
Q: Calculating difference with respect to previous day Stock.Open <- c(102.25,102.87,102.25,100.87,103.44,103.87,103.00)
Stock.Close <- c(102.12,102.62,100.12,103.00,103.87,103.12,105.12)
day<-c(1:7)
df<-data.frame(day,Stock.Close,Stock.Open)

How to I calculate the %difference for stock.open and stock.close each day w.r.t to the previous day.
Ex: I want to calculate %change in Stock.open between day1,day2 then day2,day3, day3,day4, and so on..

A: EDITED :
previous solution had a ratio computed on current value, not previous value (see edit history)
updated solution:
library(tidyverse)
df %>% bind_cols(map(df[2:3],~c(NA,diff(.x))/lag(.x)))
#   day Stock.Close Stock.Open Stock.Close1  Stock.Open1
# 1   1      102.12     102.25           NA           NA
# 2   2      102.62     102.87  0.004896201  0.006063570
# 3   3      100.12     102.25 -0.024361723 -0.006027024
# 4   4      103.00     100.87  0.028765481 -0.013496333
# 5   5      103.87     103.44  0.008446602  0.025478338
# 6   6      103.12     103.87 -0.007220564  0.004156999
# 7   7      105.12     103.00  0.019394880 -0.008375854

A: You can use quantmod::Delt
library(quantmod)
Delt(Stock.Open)

     Delt.1.arithmetic
[1,]                NA
[2,]       0.006063570
[3,]      -0.006027024
[4,]      -0.013496333
[5,]       0.025478338
[6,]       0.004156999
[7,]      -0.008375854

Delt(Stock.Close)

     Delt.1.arithmetic
[1,]                NA
[2,]       0.004896201
[3,]      -0.024361723
[4,]       0.028765481
[5,]       0.008446602
[6,]      -0.007220564
[7,]       0.019394880

You can also calculate open-to-close percentage change with
Delt(Stock.Open, Stock.Close)

     Delt.0.arithmetic
[1,]      -0.001271394
[2,]      -0.002430252
[3,]      -0.020831296
[4,]       0.021116288
[5,]       0.004156999
[6,]      -0.007220564
[7,]       0.020582524

As Moody_Mudskipper points out, you can add the results to your existing data frame with
# purrr
library(purrr)
df[4:5] <- map(df[2:3],Delt)

# base R
df[4:5] <- Map(Delt, df[2:3])

To obtain the day-to-day percent change in open-to-close percent change
df$ans <- Delt(Stock.Open, Stock.Close) / lag(Delt(Stock.Open, Stock.Close))

  day Stock.Close Stock.Open Delt.0.arithmetic
1   1      102.12     102.25                NA
2   2      102.62     102.87         1.9114865
3   3      100.12     102.25         8.5716616
4   4      103.00     100.87        -1.0136810
5   5      103.87     103.44         0.1968622
6   6      103.12     103.87        -1.7369655
7   7      105.12     103.00        -2.8505424

A: Here is one idea, using functions from dplyr and tidyr. lag can shift the values, the default is one. Once each row is ready, we can calculate the percentage change using mutate. replace_na is one way to replace the NA.
library(dplyr)
library(tidyr)

df2 <- df %>%
  mutate(Pre.Open = lag(Stock.Open)) %>%
  mutate(Percent.Change = (Stock.Open - Pre.Open) / Pre.Open * 100) %>%
  replace_na(list(Percent.Change = 0))
df2
  day Stock.Close Stock.Open Pre.Open Percent.Change
1   1      102.12     102.25       NA      0.0000000
2   2      102.62     102.87   102.25      0.6063570
3   3      100.12     102.25   102.87     -0.6027024
4   4      103.00     100.87   102.25     -1.3496333
5   5      103.87     103.44   100.87      2.5478338
6   6      103.12     103.87   103.44      0.4156999
7   7      105.12     103.00   103.87     -0.8375854

Update
If you want to calculate both the Stock.Open and Stock.Close percentage change, you can use the following code.
library(dplyr)
df2 <- df %>%
  mutate_at(vars(starts_with("Stock")), funs(Percent = (. - lag(.))/lag(.) * 100)) %>%
  replace(is.na(.), 0)
df2
  day Stock.Close Stock.Open Stock.Close_Percent Stock.Open_Percent
1   1      102.12     102.25           0.0000000          0.0000000
2   2      102.62     102.87           0.4896201          0.6063570
3   3      100.12     102.25          -2.4361723         -0.6027024
4   4      103.00     100.87           2.8765481         -1.3496333
5   5      103.87     103.44           0.8446602          2.5478338
6   6      103.12     103.87          -0.7220564          0.4156999
7   7      105.12     103.00           1.9394880         -0.8375854

A: The second shortest solution (and without external libraries):
df$relDiff.Stock.Open = c(NA,diff(df$Stock.Open,lag=1))/df$Stock.Open*100
df$relDiff.Stock.Close = c(NA,diff(df$Stock.Close,lag=1))/df$Stock.Close*100

Result
  day Stock.Close Stock.Open relDiff.Stock.Open relDiff.Stock.Close
1   1      102.12     102.25                 NA                  NA
2   2      102.62     102.87          0.6027024           0.4872345
3   3      100.12     102.25         -0.6063570          -2.4970036
4   4      103.00     100.87         -1.3680976           2.7961165
5   5      103.87     103.44          2.4845321           0.8375854
6   6      103.12     103.87          0.4139790          -0.7273080
7   7      105.12     103.00         -0.8446602           1.9025875

A: Very nice functionality in dplyr, lag and lead. You can also use data.table package.
library(dplyr)
 df <- df %>% mutate(Diff.Previous = Stock.Open - lag(Stock.Close) )
 df
  day Stock.Close Stock.Open Diff.Previous
1   1      102.12     102.25            NA
2   2      102.62     102.87          0.75
3   3      100.12     102.25         -0.37
4   4      103.00     100.87          0.75
5   5      103.87     103.44          0.44
6   6      103.12     103.87          0.00


text:
Q: how can i read data from firebase firestory by getx? how can I read data from firebase firestory by getx
I make all models and controllers and try to read data, but something is wrong
class ContollerBinding extends Bindings{
  @override
  void dependencies() {
    Get.lazyPut(() => DetailController());
    Get.lazyPut(() => DetailModel());
  }
}

class DetailController extends GetxController {

  List<DetailModel> get detailModel => _detailModel;
  List<DetailModel> _detailModel = [];

  final CollectionReference _detialCollectionReference = FirebaseFirestore.instance.collection('detail');
  DetailController(){
    getDetail();
  }
  getDetail() async {
    _detialCollectionReference.get().then((value) {
      for (int i= 0 ; i< value.docs.length ;i++){
        _detailModel.add(DetailModel.fromJson(value.docs[i].data())); //error here

      }
      update();
    });
  }
}

class DetailModel {
  String? name;
  String? title;
  String? text;
  String? img;
  String? time;
  String? prize;

  DetailModel({ this.name,  this.title,  this.text,  this.img,  this.time,  this.prize ,});

  DetailModel.fromJson(Map<dynamic, dynamic>?map, data){
    if (map == null){
      return;
    }
    name  = map['name'];
    title = map['title'];
    text = map['text'];
    img = map['img'];
    time = map['time'];
    prize = map['prize'];
  }

  toJson (){
    return {
      name = 'name',
      title = 'title',
      text = 'text',
      img = 'img',
      time = 'time',
      prize = 'prize',
    };
  }
}

I can't figure out where is the problem and I see a lot of videos and do like him, but it seems a problem
Gets a list of all the documents included in this snapshot.
2 positional argument(s) were expected, but 1 found.
Try adding the missing arguments.dartnot_enough_positional_arguments
The function can't be unconditionally invoked because it can be 'null'.
Try adding a null check ('!').dartunchecked_use_of_nullable_value
enter image description here


text:
Q: Android Jetpack Navigation Fragment show again and again I am developing an android app using Jetpack library:

*

*Hilt

*Navigation

*ViewModel

*DataBinding

Actually, I am familiar with MVP pattern.
I am trying to study MVVP pattern (Databinding and Jetpack ViewModel)
I have 2 fragments (A and B).
import androidx.fragment.app.Fragment
import androidx.fragment.app.viewModels
import androidx.navigation.fragment.findNavController
import androidx.navigation.fragment.navArgs

@AndroidEntryPoint
class AFragment {

    private val viewModel: AViewModel by viewModels()

    override fun onViewCreated(view: View, savedInstanceState: Bundle?) {
        super.onViewCreated(view, savedInstanceState)

        binding.viewModel = viewModel

    with(binding) {
        button.setOnClickListener {
            this@AFragment.viewModel.doAction()
        }
    }

    viewModel.result.observe(viewLifecycleOwner) { result ->
        findNavController().navigate(AFragmentDirections.actionAFragmentToBFragment(result))
    }
  }
}

And here is AViewModel:
@HiltViewModel
class AViewModel @Inject constructor(): ViewModel() {

    private val _result: MutableLiveData<Int> = MutableLiveData()
    val result: LiveData<Int>
        get() = _result

    fun doAction() {
        _result.postValue(SOME_ACTION_RESULT)
    }
}

It shows BFragment correctly.
But If I touch Back Button on BFragment, it still shows BFragment.
Actually, It went to back AFragment, but it comes again to BFragment.
When I touch Back Button on BFragment,

*

*AFragment is started again (I checked onViewCreated() is called again)

*Below observe code is called again:

viewModel.result.observe(viewLifecycleOwner) { result ->
    findNavController().navigate(AFragmentDirections.actionAFragmentToBFragment(result))
}

Why this code is called again?
And do I write code correctly?
What is the best practice?

Now, I found a solution.
In AFragment:
viewModel.result.observe(viewLifecycleOwner) { result ->
    if (result != null) {
        findNavController().navigate(AFragmentDirections.actionAFragmentToBFragment(result))
        viewModel.resetResult()
    }
}

and In AViewModel:
fun resetResult() {
    _result.postValue(null)
}

With this code, it works fine.
Yes... But I don't like this code...
It's... so weird...
I don't know what is the best practice...

A: the problem is related with livedata and fragment lifecycle.
AFragment and AViewModel lives when you move to FragmentB, but view in AFragment detach and attach when you move and come back. It means onViewCreated() called every time when you touch Back button on BFragment. As a result, AFragment start to observe AViewModel which has already valid data with its _result livedata.
You should separate uidata and events in livedatas. Easiest solution is  SingleEventLiveData implementation and use it.
  open class Event<out T>(private val content: T) {

  var hasBeenHandled = false
    private set // Allow external read but not write

  /**
   * Returns the content and prevents its use again.
  */
  fun getContentIfNotHandled(): T? {
    return if (hasBeenHandled) {
      null
    } else {
      hasBeenHandled = true
      content
    }
  }

in viewmodel:
private val _result: MutableLiveData<Event<Int>> = MutableLiveData()
val result: LiveData<Event<Int>>
    get() = _result

fun doAction() {
    _result.postValue(Event(5))
}

how to observe:
viewModel.result.observe(viewLifecycleOwner) { result ->
result.getContentIfNotHandled()?.let {
    findNavController().navigate(R.id.action_fragment_a_to_fragment_b)
}

}
sources:
https://medium.com/androiddevelopers/livedata-with-snackbar-navigation-and-other-events-the-singleliveevent-case-ac2622673150
How to create LiveData which emits a single event and notifies only last subscribed observer?


text:
Q: Find the vectors such that the parametric curve $g(t)=h_0+ th_1+ t^ 2h_2+ t^3h_3$ passes through points I'm stuck with this problem: "Find the vectors $h_0...h_3 ∈ ℝ^2$ such that the parametric curve   $g(t)=h_0+ th_1+ t^ 2h_2+ t^3h_3$ passes through $(0,0)$ when $t=0$, $(2,1)$ when $t=1$, $(1,3)$ when $t=2$, $(,4)$ when $t=3$".
My thoughts: if $t=0$, then $h_0$ passes through (2,1). I think I have to build a system of equations.
Thank you for your help.


text:
Q: Binding Indexer I have a collection of items in my app, and I want to set the Content of a ContentPresenter to one of these items. The item will be randomly defined by an int index. I can bind an item like this:
<ContentPresenter Content={Binding Items[0]}/>

but not like this:
<ContentPresenter Content={Binding Items[{Binding Index}]}/>

I've seen a number of answers suggesting using MultiBinding in WPF, but this isn't available in UWP. Is there an alternative?

A: You could create a view model property, returning Items[Index]:
public string RandomItem => Items[Index];

For the PropertyChanged notifications to work, you will need to raise the event whenever Index or Items changes, e.g.:
public int Index
{
    get { return _index; }
    set
    {
        _index = value;
        RaisePropertyChanged();
        RaisePropertyChanged(() => RandomItem);
    }
}

If you prefer to have the logic in the view and go the multi-binding way, you can use the Cimbalino toolkit. For that to work, first add 2 NuGet packages:

*

*Cimbalino.Toolkit

*Microsoft.Xaml.Behaviors.Uwp.Managed
Now you can create a converter:
public class CollectionIndexConverter : MultiValueConverterBase
{
    public override object Convert(object[] values, Type targetType, object parameter, CultureInfo culture)
    {
        var collection = (IList) values[0];
        var index = (int?) values[1];
        return index.HasValue ? collection[index.Value] : null;
    }

    public override object[] ConvertBack(object value, Type targetType, object parameter, CultureInfo culture)
    {
        throw new System.NotImplementedException();
    }
}

And use it from XAML:
<ContentPresenter>
    <interactivity:Interaction.Behaviors>
        <behaviors:MultiBindingBehavior PropertyName="Content" Converter="{StaticResource CollectionIndexConverter}">
            <behaviors:MultiBindingItem Value="{Binding Items}" />
            <behaviors:MultiBindingItem Value="{Binding Index}" />
        </behaviors:MultiBindingBehavior>
    </interactivity:Interaction.Behaviors>
</ContentPresenter>


text:
Q: Why has the author of this code used the .call method? Surely he could have just accessed the prototype? Im looking through some code (unfortunatly the author isnt around anymore) and im wondering why he has used the .call method.
hmlPlaylist.prototype.loadVideos = function () {
    var scope = this;

    this.config.scriptUrl = '_HMLPlaylistAjax.aspx?' + Math.random();

    jQuery.ajax({
        type: 'GET',
        url: this.config.scriptUrl,
        success: function (d, t, x) {
            scope.loadVideos_callback.call(scope, d);
        },
        error: function () {
        }
    });
};

hmlPlaylist.prototype.loadVideos_callback = function (data) {
    var jsonData = '';
    var jsonError = false;

    try {
        jsonData = eval("(" + data + ")");
    } catch (jError) {
        jsonError = true;
    }

    if (!jsonError) {

        if (jsonData.playlists.length > 0) {
            this.buildPlaylistList(jsonData.playlists);
        }
        if (jsonData.videos.length > 0) {
            this.buildVideoList(jsonData.videos);
            this.bindVideoNavs();
        }
    }
    else {

        // no json returned, don't do anything
    }
};

Obviously he seems to have used it to pass a 'this' reference to the loadVideos_callback method but why? The 'loadVideos_callback' method is attached to the prototype of 'hmlplaylist' which is the 'class'. So if you access this inside the 'loadVideos_callback' method you get to the same thing dont you?

A: yes, I think you are right (I can't see the code in action).  You still need the closure around scope, but in this case the use of call is not necessary.
To pull some of the comments into this answer, this is always the context on which the method was invoked.  So if a new instance of htmlPlayList was created, and the method invoked on that instance, this would be a reference to that instance.


text:
Q: How to stop automatically defaults user email address into cc address From last week, few of users in my org are facing an issue related to salesforce emails. When a user sends an correspondence on a case, at that time that user outlook email address is automatically defaults to cc'ing.
How I can stop automatically defaults user outlook email address into cc address ?
Thanks in advance!
Followed the following steps: Go to the Case object under Object Manager and then go to the Button/Actions, Search for the Email Action there and then remove CC from the predefined list of values
This problem occurring on random new users which gets on-board.
I followed steps mentioned by you and we have only To Recipients as predefined as seen in attached screenshot.


text:
Q: How to load balance between two VMs but only one VM is running at a time? I want to create two VMs on Azure. Put them in an Availability Set, run one of them, and if - for some reason - this machine has crashed, to start the other one automatically and forward traffic to it.
What is the best yet simple way to do this with Azure?
Thanks!
ASH

A: You can use Traffic Manager and configure Priority traffic-routing method
https://azure.microsoft.com/en-us/documentation/articles/traffic-manager-routing-methods/#wriority-traffic-routing-method


text:
Q: Making div look more like site linked to without copying source code direct? This is my current HTML code (details changed for privacy):

<!DOCTYPE html>

 <meta charset="utf-8" />

 <title>Anytown Car Sales | No.1 in West Yorkshire since 1982</title>

Anytown Car Sales

Est.1982

Sutton-in-Craven, West Yorkshire BD20

Tel: 01535 000000

2018 68 VAUXHALL INSIGNIA 1.5 TURBO 165 ELITE NAV, 5 door, blue, 15,000 miles £POA

What I have been trying to do is to make a DIV that looks similar to the list at https://www.britanniacarsales.co.uk/used-cars with the picture next to the vehicle and space in between divs (color of my website's body will be changed in the code) but I am not quite sure how to get it to look similar if not the same.
What changes should I make to the code so that div class content-usedcar looks like the style in the link I've used as inspiration from? (I'm trying to make this original work, not copying others' CSS).

A: <!DOCTYPE html>

  <meta charset="utf-8" />

  <title>Anytown Car Sales | No.1 in West Yorkshire since 1982</title>

Anytown Car Sales

Est.1982

Sutton-in-Craven, West Yorkshire BD20

Tel: 01535 000000

2018 68 VAUXHALL INSIGNIA 1.5 TURBO 165 ELITE NAV, 5 door, blue, 15,000 miles £POA

how about this?


text:
Q: How to Installing compas with rails 4? I am building a rails application and I want to install compass.
I put this on my Gemfile
gem "compass-rails", "~> 2.0.alpha.0"

I am trying to import the file
@import "compass"
and it seems that is not founding the file.
What more should I do except from the gem installation ?


text:
Q: DB21034E IBM db2 Error I am trying to execute db2 command in unix command prompt db2 -tvsf UC_Repair_History.sql it is giving me below error. I checked in the file only insert statements are there.I have executed the similar file those are execute this one is not executed. ERROR is given below
DB21034E  The command was processed as an SQL statement because it was not a
valid Command Line Processor command.  During SQL processing it returned:
SQL0104N  An unexpected token "END-OF-STATEMENT" was found following "�".
Expected tokens may include:  "JOIN <joined_table>".  SQLSTATE=42601
Please any one help

A: When performing a copy&paste e.g. from Word typographic quotes might get used which the DB2 CLI does not understand. Depending on the font it might be hard to spot the difference. In the following the first select statement was copied from Word, in the second statement I retyped the quotation marks:
db2 => SELECT COUNT(*) FROM SYSCAT.TABLES WHERE TABSCHEMA='SAPSR3'
SQL0104N  An unexpected token "'SAPSR3'" was found following "RE
TABSCHEMA='S".  Expected tokens may include:  "END-OF-STATEMENT".
SQLSTATE=42601

db2 => SELECT COUNT(*) FROM SYSCAT.TABLES WHERE TABSCHEMA='SAPSR3'

1
-----------
          0

  1 record(s) selected.


text:
Q: Starting service as a user with no password I'm trying to start a service as a user and things work fine, until I try a user that doesn't have a password. Then, it fails to start (due to log-on error).
Am I doing something wrong or is this "by design"?
The code to register this service:
    SC_HANDLE schService = CreateService(
        schSCManager,
        strNameNoSpaces,
        strServiceName,
        SERVICE_ALL_ACCESS,
        SERVICE_WIN32_OWN_PROCESS,
        SERVICE_AUTO_START,
        SERVICE_ERROR_NORMAL,
        szPath,
        NULL,
        NULL,
        NULL,
        strUser,
        (strPassword.IsEmpty())?NULL:strPassword);

A: It may be due to an OS security requirement or security policy. Check the security policies to see if anything is relevant there.

A: Yes, it was indeed related to the security policy. To elaborate:
http://technet.microsoft.com/en-us/library/bb457114.aspx
"If you want to disable the restriction against logging on to the network without a password, you can do so through Local Security Policy. The policy setting that controls blank password restriction can be modified using the Local Security Policy or Group Policy MMC snap-ins. You can use either tool to find this policy option at Security Settings\Local Policies\Security Options. The name of the policy is Accounts: Limit local account use of blank passwords to console logon only. It is enabled by default."
After disabling that, it all works fine.

A: You need to specify an empty string, not NULL if there is no password. NULL is not a valid empty string, "" is. Probably you should just pass strPassword for the last parameter.
SC_HANDLE schService = CreateService(
            schSCManager,
            strNameNoSpaces,
            strServiceName,
            SERVICE_ALL_ACCESS,
            SERVICE_WIN32_OWN_PROCESS,
            SERVICE_AUTO_START,
            SERVICE_ERROR_NORMAL,
            szPath,
            NULL,
            NULL,
            NULL,
            strUser,

// change this line to:
            strPassword.IsEmpty() ? L"" : strPassword);
// or maybe
            strPassword);

A: Thank you - I've tried that first actually, but to no avail.
If I start services.msc, manually go into service properties and clear the 2 password fields, then press "Apply" and try to start it, it also fails.


text:
Q: How to replace all lines except one word per line using a regular expression How do you replace all lines except one word per line using a regular expression?
I tried the following regex that mostly works but all the lines after the last match remain.
Find what: (?s)(.*?property": ")(\w+)(.*?$)
Replace with: \2\n
Simplified text file:
random lines of text
{
    "property": "my1Value",
    "property": "my2Value",
    "property": "my3Value",
}
more random lines of text

Expecting one word per line:
my1Value
my2Value
my3Value

A: You could just match single characters when the main pattern doesn't match. These will then get replaced by the empty string (since the capture groups captured nothing):
Find: (?s)"property": "([^"]+)".*?(\R)|.
Replace: \1\2


text:
Q: Google webmaster tools API: How to programmatically get a list of backlinks to your site? I'd like to get a list of the backlinks reported in Google webmaster tools programaticallly but the GData API doesn't include this.
http://code.google.com/intl/sv-SE/apis/webmastertools/docs/2.0/reference.html
Is there any good way to get these links?
What's the best way to get a list of backlinks to a site?

A: the api does not support it.
i use a fake-script (http://fakeapp.com/ a programmable browser) (any programmable browser will do) which gets executed daily the get this specific data. in my opinion it is the best backlinks data you can get.

A: There is a php script that you can use to download the backlinks as a csv file which you can then use.
https://github.com/Adduc/php-webmaster-tools-downloads
A pull request was just made to the main repo.


text:
Q: How to add controller endpoints to Razor Server in ASP.NET Core 7.0 / VS2022 I am trying to add a controller with routing to a Razor server-side app. I tried several things but I only see solutions for .NET 6 and cannot figure it out.
I created a controller like this:
using Microsoft.AspNetCore.Mvc;

namespace SAAR.Controllers
{
    [ApiController]
    [Route("settings/[controller]")]
    public class ConfigurationController : ControllerBase
    {
        public ConfigurationController()
        {
        }

        [HttpGet("test")]
        public string Test()
        {
            return "Test a controller in Razor";
        }
    }
}

Then in my program.cs I added:
builder.Services.AddControllers();

and
app.UseEndpoints(endpoints => {
    endpoints.MapRazorPages();
    endpoints.MapControllers();
});

AFAIK this should work and the endpoint http://localhost:5000/settings/test should be there but I get a http 404 error.
What am I doing wrong?
Here my complete program.cs:
using Microsoft.AspNetCore.Components;
using Microsoft.AspNetCore.Components.Web;
using Microsoft.EntityFrameworkCore;
using SAAR.Areas.Identity;
using SAAR.Data;
using SAAR.Services;
using SAAR.Settings;
using System.Configuration;

var builder = WebApplication.CreateBuilder(args);

// Add services to the container.
var connectionString = builder.Configuration.GetConnectionString("DefaultConnection") ?? throw new InvalidOperationException("Connection string 'DefaultConnection' not found.");

builder.Services.AddDbContext<ApplicationDbContext>(options =>
    options.UseSqlServer(connectionString));

builder.Services.AddDatabaseDeveloperPageExceptionFilter();

// Add MVC Controllers
builder.Services.AddControllers();
builder.Services.AddRazorPages();

builder.Services.AddServerSideBlazor();
builder.Services.AddTransient<IEmailSender, EmailSender>();

var app = builder.Build();

// Configure the HTTP request pipeline.
if (app.Environment.IsDevelopment())
{
    app.UseMigrationsEndPoint();
}
else
{
    app.UseExceptionHandler("/Error");
    // The default HSTS value is 30 days. You may want to change this for production scenarios, see https://aka.ms/aspnetcore-hsts.
    app.UseHsts();
}

app.UseHttpsRedirection();
app.UseStaticFiles();
app.UseRouting();

app.MapControllers();
app.MapBlazorHub();
app.MapFallbackToPage("/_Host");

app.UseEndpoints(endpoints => {
    endpoints.MapRazorPages();
    endpoints.MapControllers();
});

app.Run();

Thanks for any help...

A: In your case,the uri should be http://localhost:5000/settings/Configuration
The name of your  controller is Configuration not test
[ApiController]
[Route("settings/[controller]")]
public class ConfigurationController : ControllerBase
{
 .....
}

A: OK, figured it out, thanx!
Just create a new Razor Server project and add a folder 'Controllers' and add a C# class:ConfigurationController.cs:
using Microsoft.AspNetCore.Mvc;

namespace SAAR.Controllers
{
    [ApiController]
    [Route("[controller]")]
    public class ConfigurationController : ControllerBase
    {
        public ConfigurationController()
        {
        }

        [HttpGet("[action]")]
        public string Test()
        {
            // Route: /Configuration/Test
            return "Test a controller in Razor";
        }
    }
}

In program.cs add this code and remove duplicate app.[Method] calls.
app.UseEndpoints(endpoints => {
    endpoints.MapRazorPages();
    endpoints.MapControllers();
    endpoints.MapBlazorHub();
    endpoints.MapFallbackToPage("/_Host");

});

Insert this in program.cs
builder.Services.AddControllers();

So the complete program.cs looks like:
using Microsoft.AspNetCore.Components;
using Microsoft.AspNetCore.Components.Web;
using Microsoft.EntityFrameworkCore;
using SAAR.Areas.Identity;
using SAAR.Data;
using SAAR.Services;
using SAAR.Settings;
using System.Configuration;

var builder = WebApplication.CreateBuilder(args);

// Add services to the container.
var connectionString = builder.Configuration.GetConnectionString("DefaultConnection") ?? throw new InvalidOperationException("Connection string 'DefaultConnection' not found.");
builder.Services.AddDbContext<ApplicationDbContext>(options =>
    options.UseSqlServer(connectionString));
builder.Services.AddDatabaseDeveloperPageExceptionFilter();

// Add MVC Controllers
builder.Services.AddControllers();
builder.Services.AddRazorPages();

builder.Services.AddServerSideBlazor();

var app = builder.Build();

// Configure the HTTP request pipeline.
if (app.Environment.IsDevelopment())
{
    app.UseMigrationsEndPoint();
}
else
{
    app.UseExceptionHandler("/Error");
    // The default HSTS value is 30 days. You may want to change this for production scenarios, see https://aka.ms/aspnetcore-hsts.
    app.UseHsts();
}

app.UseHttpsRedirection();

app.UseStaticFiles();

app.UseRouting();

app.UseEndpoints(endpoints => {
    endpoints.MapRazorPages();
    endpoints.MapControllers();
    endpoints.MapBlazorHub();
    endpoints.MapFallbackToPage("/_Host");

});
app.Run();

A: You cannot use routing / MVC-controllers in an Razor Server web app.


text:
Q: Matlab 2014b on Ubuntu 14.04 busy idenfinitely When Matlab 2014b is loaded and ready to be used, as soon as I issue a command (any command, even quit) it gets stuck and remains 'busy' indefinitely.
Installation is fine I didn' get any errors. I am running Matlab locally.
Any suggestion?

A: The problem was related to the use of the proprietary ATI radeon graphic driver. For some reason, with that driver activated, MATLAB was not responding to any command.
Switching back to the xorg ATI driver everything works fine.


text:
Q: Throttling SQL Server database cpu usage I'm wondering if there is away to limit specific database from using server's resources like setting max CPU and RAM for each database [simpler to IIS App pools]?
I'm working with SQL Server 2014 Enterprise & I want to prevent some databases from slowing down the whole server.
Thanks

A:
Edited for clarity and consistency:

By the database itself? No. However, you can through the connection (what you should be trying to manage anyways) called the Resource Governor.

*

*CPU

*MEMORY

*Physical IO, depending on the version.

There are a number of Concepts which the Docs explain in greater detail:
Resource Pool

*

*a group of default, internal (cannot be changed), and custom made groups that have a set value on the amount of CPU, Memory, and Physical IO that a session may consume.

Workload Group

*

*a class of session requests that have  similar characteristics. These are mapped to  The appropriate resource pool and are set at the time of connection settings. Meaning the default database connect is used not the first USE statement or any statement afterwards.

The governor must be activated Or configured.  A governor specific function is run against the connection's  default settings  and map to a workload group.
.  This workload is attached to a specific resource pool where the limitations are enforced on all subsequent sessions that occur out of the connection.
This function is the most important part and you should keep it simple.
For more reading, visit the Docs:
Main Page -Resource Governor
Resource governor Resource pool
Research governor Workload group
Resource governor classifier function  | Docs Microsoft


text:
Q: Tortoise SVN: How to export & import a repo this is the first time I use Tortoise svn. I actually, couldn't completely understand the sense behind the snv.
I tried  check out of full repository from an svn server, but it couldn't be comleted without errors. I think it's because of slow local network we use. It last very long... So I want to copy "the repo" into a USB disk and paste that repo into my computer. I asked IT if this is possible, and I was answered that no! I a little bit googled and found something like "export svn".
My main question is that: Is it possible to export a repo from server, and import into my computer without need of using network.
My second question is that: If it is possible, how? I don't want full details, I need only some keywords.

A:
My main question is that: Is it possible to export a repo from server, and import into my computer without need of using network.

Short answer: yes, if you have physical access to the server. Then you can export the repository to a USB drive without any network access. But normally, this wont be the case.
svn export basically just download the files from the server. In difference to svn checkout it does not create a working copy.


text:
Q: Merging postgres data I have data in two postgresql databases that needs to be merged into 1.  Just to be clear, both databases have "good" data in them from a certain date that needs to be combined.  This isn't merely appending the data from one into another. In other words, let's say that table foo has an serial id field.  Both databases have a foo with ID=5555 and both values are valid (but different).  So, the target database's foo keeps 5555 and the new record should get added with a new ID of nextval(foo_id_seq).
So, it's a big mess.
My thoughts are to create a tmp schema in the target db and to copy the needed data from source db.  Then I need to essentially "upsert" the data.  New records get inserted with new ideas (and foreign keys updated) and records that exist in both dbs get updated.
I don't believe there is a tool that will help me with this.
My questions.
How best to handle generating the new id?  I know I could do it via selects and just leaving out the id column, but that's a lot of typing and would be slow.  My thinking is to create a temporary trigger for these tables that will override the id supplied when doing an insert.
Finally notes:

*

*Both databases are offline.  And I'm the only one that can get to them.

*Both database have the exact same schema

*Target database is 9.2

A: try using something like:
INSERT INTO A(id, f1, f2)
SELECT nextval('A_seq'), tmp_A.f1, tmp_A.f2
FROM tmp_A
WHERE tmp_A.id IN (select A.id FROM A);

INSERT INTO A(id, f1, f2)
SELECT tmp_A.id, tmp_A.f1, tmp_A.f2
FROM tmp_A
WHERE tmp_A.id NOT IN (select A.id FROM A);

The idea - use one INSERT .. SELECT .. to insert the data with conflicts in id fields and other INSERT .. SELECT .. to insert the data without the conflict.
Or simply generate new id for every inserted record:
INSERT INTO A(id, f1, f2)
SELECT nextval('A_seq'), tmp_A.f1, tmp_A.f2
FROM tmp_A;


text:
Q: base URL problem in my Drupal site
http://www.revdup.co.uk
I recently changed the domain name, I had to change a few absolute URLs and everything seems to be working fine now, except the front page, and only when I am logged in, not as a guest..
for some reason all the theme images (such as those used to build blocks appearance) are using an incorrect version of the base URL eg:
revdup.co.uk/revdup/themes/drupal_pwc010_tech/images/Block-s.png
instead of:
revdup.co.uk/themes/drupal_pwc010_tech/images/Block-s.png
I have changed the base URL variable in settings.php
Why is this only happening on one page and how can I fix it?

A: You'll need to explicitly clean the template cache. Go to Administrator->Themes->Selected theme->configure->Save.
This will regenerate the template cache with correct urls. Also clear the drupal cache in Admin/settings/performance.


text:
Q: Sharepoint JSOM - Get List Items - Uncaught ReferenceError: Type is not defined I have a customer web page added to my sharepoint site and i'm trying to retrieve items from a sharepoint list, but i keep getting a error. I am not sure where I am going wrong:
Here is the HTML code with the script tags to load the sp.js, sp.runtime.js, and sp.core.js files:
    <!DOCTYPE html>

        <meta charset="utf-8">
        <title>Some Title</title>

Here is code from my Javascript file:
    SP.SOD.executeFunc('sp.js', 'SP.ClientContext', function () {});
    document.addEventListener("DOMContentLoaded", function () {
        ExecuteOrDelayUntilScriptLoaded(retrieveListItems, "sp.js");
        });

    var collListItem;

    function retrieveListItems() {
        alert("Start Retrieval");
        var clientContext = new SP.ClientContext();
        var oList = clientContext.get_web().get_lists().getByTitle('SomeList');
        alert(oList);
        var camlQuery = new SP.CamlQuery();
        collListItem = oList.getItems(camlQuery);
        clientContext.load(collListItem);
        clientContext.executeQueryAsync(
        Function.createDelegate(this, this.onQuerySucceeded),Function.createDelegate(this, this.onQueryFailed)
        );
        alert("Retrieved");
        }

    function onQuerySucceeded(sender, args) {
        var listItemInfo = "";
        var listItemEnumerator = collListItem.getEnumerator();
        while (listItemEnumerator.moveNext()) {
        var oListItem = listItemEnumerator.get_current();
        listItemInfo += 'ID:  ' + oListItem.get_id() +
        ' Title: ' + oListItem.get_item('Item ID') +
        ' FirstName: ' + oListItem.get_item('Procedure Name') +
        ' LastName: ' + oListItem.get_item('Document Number') +
        '
';
        alert("success");
    }

    alert("post");

    document.querySelector("#test").html(listItemInfo);
    }

    function onQueryFailed(sender, args) {
    alert('Request failed. ' + args.get_message() +
    '\n' + args.get_stackTrace());
    }

This keeps failing due to the a uncaught reference error shown below and i'm not sure where I am going wrong.
Uncaught ReferenceError: Type is not defined
    at sp.core.js:2:213
(anonymous) @ sp.core.js:2
sp.runtime.js:2

       Uncaught ReferenceError: Type is not defined
    at sp.runtime.js:2:322
(anonymous) @ sp.runtime.js:2
sp.js:2

       Uncaught ReferenceError: Type is not defined
    at sp.js:2:203
(anonymous) @ sp.js:2
index.js:36

       Uncaught ReferenceError: SP is not defined
    at index.js:36:1


text:
Q: _locale.cy.request is not a function I'm trying to create a basic login command in Cypress, which was working when I used cy.visit().
After reading up on Cypress, I found out that logging in using the UI is an anti-pattern, so I'm attempting to switch over to calling cy.request() to post to the login route.
However, when I try this, I get an error that does not make sense to me:
TypeError: _locale.cy.request is not a function
This is my code in commands.js:
Cypress.Commands.add("login", () => {
  cy.request('POST', `${Cypress.config().baseUrl}/login`, {username: 'sysadmin', password: 'test'});
});

And this is where it gets called in the test:
it('Logs in successfully', () => {
  cy.login();
});

From my understanding, cy.request is a function that comes with Cypress, that can take in a method, url and body: https://docs.cypress.io/api/commands/request.html#Syntax.
Can anyone please explain why Cypress isn't recognizing its own native function?
Thanks

A: Old question, i had the same problem, but my solution was to simply ensure that there was no import { cy } from 'date-fns/locale'; at the top of your page.


text:
Q: Convert DOCX to PDF with documents4j (Which Internally uses VBScript for the conversion) The following is the simple code snippet which I am trying to use to convert a DOCX file into a PDF on my local system, which is as it is picked up from http://documents4j.com/#/.

*

*Running this piece of code as a part of service inside a web app (.war) deployed on Tomcat 9.0.37 which is running as Windows service.

*Created the below folder C:\Windows\SysWOW64\config\systemprofile\Desktop (Running documents4j application as Windows service).

*MS Office professional 2016 is installed (licenced copy).

Well with same configuration on VM 1: Windows server 2012 and VM 2: Windows server 2019 as mentioned in above three points. I'm able to convert the DOCX to PDF in my VM 1 : Windows server 2012. But the below problem I'm facing in VM 2: Windows server 2019.
On calling execute method the current thread is getting blocked for forever, which leads to memory leak. Please find the below error on execute method.
org.apache.catalina.loader.WebappClassLoaderBase.clearReferencesThreads The web application [appName] is still processing a request that has yet to finish. This is very likely to create a memory leak. You can control the time allowed for requests to finish by using the unloadDelay attribute of the standard Context implementation. Stack trace of request processing thread:[
 java.base@11.0.5/jdk.internal.misc.Unsafe.park(Native Method)
 java.base@11.0.5/java.util.concurrent.locks.LockSupport.park(LockSupport.java:194)
 java.base@11.0.5/java.util.concurrent.locks.AbstractQueuedSynchronizer.parkAndCheckInterrupt(AbstractQueuedSynchronizer.java:885)
 java.base@11.0.5/java.util.concurrent.locks.AbstractQueuedSynchronizer.doAcquireSharedInterruptibly(AbstractQueuedSynchronizer.java:1039)
 java.base@11.0.5/java.util.concurrent.locks.AbstractQueuedSynchronizer.acquireSharedInterruptibly(AbstractQueuedSynchronizer.java:1345)
 java.base@11.0.5/java.util.concurrent.CountDownLatch.await(CountDownLatch.java:232)
 com.documents4j.job.AbstractFutureWrappingPriorityFuture.get(AbstractFutureWrappingPriorityFuture.java:204)
 com.documents4j.job.AbstractFutureWrappingPriorityFuture.get(AbstractFutureWrappingPriorityFuture.java:10)
 com.documents4j.job.ConversionJobAdapter.execute(ConversionJobAdapter.java:13)

Code Snippet 1:
import java.io.File;
import java.io.FileInputStream;
import java.io.FileOutputStream;
import java.io.InputStream;
import java.io.OutputStream;
import com.documents4j.api.DocumentType;
import com.documents4j.api.IConverter;
import com.documents4j.job.LocalConverter;

public class WordMLToPDF2 {

    public static void main(String[] args) {

        File inputWord  = new File("C:\\Users\\anshu\\Downloads\\test.docx")
        , outputFile  = new File("C:\\Users\\anshu\\Downloads\\test.pdf");
        try  {
            InputStream docxInputStream = new FileInputStream(inputWord);
            OutputStream outputStream = new FileOutputStream(outputFile);
            IConverter converter = LocalConverter.builder()
                       .baseFolder(tmpDir)
                       .workerPool(20, 25, 2, TimeUnit.SECONDS)
                       .processTimeout(30, TimeUnit.SECONDS)
                       .build();
            converter.convert(docxInputStream).as(DocumentType.DOCX).to(outputStream).as(DocumentType.PDF).execute();
            outputStream.close();
            System.out.println("success");
            converter.shutDown();
        } catch (Exception e) {
            e.printStackTrace();
        }

    }

}

Below dependencies which I've configured in pom.xml
   <dependencies>
        <dependency>
            <groupId>org.docx4j</groupId>
            <artifactId>docx4j-documents4j-local</artifactId>
            <version>8.3.3</version>
        </dependency>
        <dependency>
            <groupId>org.docx4j</groupId>
            <artifactId>docx4j-JAXB-ReferenceImpl</artifactId>
            <version>8.3.3</version>
        </dependency>
        <dependency>
            <groupId>org.apache.logging.log4j</groupId>
            <artifactId>log4j-slf4j-impl</artifactId>
            <version>2.17.1</version>
        </dependency>
        <!-- API, java.xml.bind module -->
        <dependency>
            <groupId>jakarta.xml.bind</groupId>
            <artifactId>jakarta.xml.bind-api</artifactId>
            <version>2.3.2</version>
        </dependency>

        <!-- Runtime, com.sun.xml.bind module -->
        <dependency>
            <groupId>org.glassfish.jaxb</groupId>
            <artifactId>jaxb-runtime</artifactId>
            <version>2.3.2</version>
        </dependency>
    </dependencies>

EDIT:
After analyzing the source code. What I understood is:

*

*Internally documents4j executes a VBScript with the help of another library zt-exec (ZeroTurnaround Process Executor) to start the WINWORD or for the conversion of DOCX to PDF or to stop the WINWORD

*WINWORD program freezes When it executes wordApplication.Documents.Open(inputFile, False, True, False) word_convert

*In above statement wordApplication holds the object of Word.Application
word_start
word_convert
word_shutdwon


text:
Q: Shallow copy in c# I understand the definition of shallow copy
Shallow copying is creating a new object and then copying the non-static fields of the current object to the new object. If a field is a value type --> a bit-by-bit copy of the field is performed; for a reference type --> the reference is copied but the referred object is not; therefore the original object and its clone refer to the same object.
but why static fields are not copied?

A: Because static fields are not part of the object. You could access them with ClassName.StaticValue. In fact, you CAN'T access them with ClassInstanceName.StaticValue.

A: Static fields are shared by all the instances of a particular class.

A: Because static members are class level members not instance level which mean that static members common for all instances of given type.


text:
Q: Lottery fairness problem I'm wondering if this scheme is fair or not. I'm not an expert in math so I have no clue. When lottery room starts the winning number is set by random integer between 0-999. Every player enters the lottery also given random integer between 0-999, there is no duplicate. After lottery ends the payer closest to the winning number is the winner.
For example:
Winning number is 500
Player 1: assigned random number 123
Player 2: assigned random number 789
Player 3: assigned random number 456
So the winner is Player 3.

Is there any problem with this, can I call it fair? In my opinion it seems fair because everything is random, but then again there is something that disapproves its fairness.
Thank you.

A: Assuming the numbers are picked fairly, it is fine. One way to make it appear more fair is to make the distance cyclic, so that $999$ is distance $1$ from $0,$ $300$ is distance $400$ from $900.$ But that is just appearance - each person is just as likely to win the lottery as anybody else in the original scheme, as long as all choices of numbers are uniform.
The appearance of unfairness assumes the process goes like this: each person is assigned a random number known only to himself. Then the winning number is revealed.
A person who gets $999$ or $0$ as a number knows that his only chance of winning are the numbers less than halfway to the nearest other number to one side, while a person who gets $500$ knows that she can win on one side or the other. So at this point, to the guy with $999,$ it doesn't look fair.
And, indeed, this guy now has a lower probability of winning that the woman with $500.$ But this process is still fair because the draw of $999$ was fair - the man who got it could have gotten $500.$ So, right now he has a lower chance of winning, but before he got his number, he was just as likely as anybody else to be assigned $500.$
The "cyclic distance" approach alters that perception of fairness, because, after being assigned a number, not knowing anybody else's number or the winning number, a person knows his estimate of his odds are the same as anybody else's.
However, the cyclic distance is unnecessary if, while entering, before getting their draw, the man is told "the winner will be the closest to $326.$" Now, the man perceives his draw as the actual random process of the lottery, and when he gets $999,$ he knows he lost on that draw.


text: Q: вопрос про CSS в многостраничном сайте Я делаю сайт с несколькими страницами (контакты, галерея, и т.п) И поскольку это мой первый сайт, у меня вопрос, как стоит поступать, привязывать каждую страницу к тому же css файлу что и index.html или нужно создавать отдельный css файл для каждой новой страницы сайта? (работаю через gulp). Спасибо!


text:
Q: MVC OAuth authentication with Salesforce returns to login page I'm trying to get a working example of authenticating an MVC application in .NET against Salesforce using their OAuth authentication workflow. I've been referencing this walkthrough which is fairly simple. It is very similar to getting Google authentication to work. It boils down to setting up the .NET MVC project with the individual account authentication template and spin up a new connected application in Salesforce. Then, add the Owin.Security.Providers library for Salesforce, adjust the Startup.Auth.cs a bit and include the ClientId and ClientSecret from the Salesforce app, and the Authorization and Token endpoints. The callback URL it suggests is http://localhost:[port]/signin-salesforce which is pretty similar to the callback URL used for Google authentication.
While I am redirected to Salesforce and can login, the handshake that returns me back to my MVC application seems to encounter an issue that I cannot nail down. I get redirected back to the Login page and .NET doesn't seem to be aware of my login info, although I definitely have an active session with Salesforce (the Salesforce dashboard will automatically log me in). In the code, things start to go sideways here:
// GET: /Account/ExternalLoginCallback
[AllowAnonymous]
public async Task<ActionResult> ExternalLoginCallback(string returnUrl)
{
    var loginInfo = await AuthenticationManager.GetExternalLoginInfoAsync();
    if (loginInfo == null)
    {
        return RedirectToAction("Login");
    }
    //more code we never reach
}

loginInfo is always null. So, to figure out what sort of request is being sent to .NET, I turned to Fiddler and encountered a request against localhost:[port]/signin-salesforce with a bunch of parameters that gets a curious response:

HTTP/1.1 302 Found
Location: /Account/ExternalLoginCallback?error=access_denied
Server: Microsoft-IIS/10.0
Set-Cookie: .AspNet.Correlation.Salesforce=; path=/; expires=Thu, 01-Jan-1970 00:00:00 GMT
X-SourceFiles: =?UTF-8?B?YzpcdXNlcnNcc3RldmUuY2FtaXJlXGRvY3VtZW50c1x2aXN1YWwgc3R1ZGlvIDIwMTVcUHJvamVjdHNcU2FsZXNGb3JjZUludGVncmF0aW9uXFNhbGVzRm9yY2VJbnRlZ3JhdGlvblxzaWduaW4tc2FsZXNmb3JjZQ==?=
X-Powered-By: ASP.NET
Date: Fri, 20 May 2016 21:46:09 GMT
Content-Length: 0

Note the Location header, which tells .NET to redirect to /Account/ExternalLoginCallback with an error parameter of "access_denied". Enabling some tracing in Owin reveals that something is returning a 400 either in .NET or to .NET, but I don't know what.
So, that's where I'm at. A null loginInfo object in my controller and evidence that something is going wrong in some web requests. I've perused several other related questions, but almost none focus on SalesForce and they provide answers that aren't really applicable (for instance, I have no Google+ API to enable). Any ideas on how to rectify this?

A: Looks like the redirect URI is required to match the one on the Identity server. As you are getting redirected to the login page again, looks like the redirect URI might not be matching with the Client secret and Client Id.
In the SalesForce Identity server, there will be a redirect URI that will decide the path where you will get redirected once the authentication is done. Sometimes you also have to provide the URI with Client ID and secret to get completely authorized.

A: To everyone having issues with the loginInfo always coming back null when it really shouldn't be, This may not fix your issue, however I spend days on a similar problem with facebook and google. I ended up clearing the HttpContext session before ExternalLoginCallback is invoked and it's been working perfect ever since. Not saying this will fix it, but hopefully it helps somebody.
//
// POST: /Account/ExternalLogin
[HttpPost]
[AllowAnonymous]
[ValidateAntiForgeryToken]
public ActionResult ExternalLogin(string provider, string returnUrl)
{
    // Clear any other session first as this seems to cause unexpected null responses.
    if (ControllerContext.HttpContext.Session != null)
    {
        ControllerContext.HttpContext.Session.RemoveAll();
    }

    // Request a redirect to the external login provider
    return new ChallengeResult(provider, Url.Action("ExternalLoginCallback", "Account", new { ReturnUrl = returnUrl }));
}

When I was testing mine, I checked with Fiddler and I was getting a token back okay, If you are not getting a valid response then this won't help.

A: I would check Startup.Auth.cs and verify that your organization has the correct instance and you are not using the one in the walkthrough (if different).  My organization, for example, starts with na10.salesforce.com.  The walkthrough uses ap1.salesforce.com.
    AuthorizationEndpoint = "https://**ap1**.salesforce.com/services/oauth2/authorize",
    TokenEndpoint = "https://**ap1**.salesforce.com/services/oauth2/token"

I would also ensure that the cookies and cache are cleared.  For example, I fired up a brand new VS 2015 MVC project, without any OAuth info and I was logged in via the SFDC provider.  No client id, secret, not even a SFDC section!
I did the walkthrough and was able to authenticate with SFDC OAuth.  Like you said, it was very straightforward. I wouldn't tear apart your code so much as worry about something simple.

A: I further went ahead to download the Owin.Security.Providers.Salesforce code and added it to my project reference to be able to debug the issue. I found out that when the response for the oauth code swap was being performed I received an exception for 'Response status code does not indicate success: 400 (TLS 1.1 or higher required).' I was working off the sandbox and Salesforce has disabled TLS 1.0 starting June 2016. so adding this line of code on my Account Controller Constructor fixed my issue:
 System.Net.ServicePointManager.SecurityProtocol = SecurityProtocolType.Tls11 | SecurityProtocolType.Tls12;


text:
Q: The application on Angular does not receive a response from the server There is an application on Angular, the backend is an application on Java-Spring.
Both of them are running on a server in a shared network, on a Windows OC machine in VirtualBox (Linux).
The essence of the problem is that when you try to open a web application in a browser, it runs completely on one computer out of five with Windows OC and on one of one on Linux OC.
The browser is everywhere Chrome, only in Linux Mozilla
The application itself is launched, but it does not receive data from the backend at startup.
At the same time I get an error
Failed to load resource:
http://10.151.78.6:5003/es-serv/api/v1/get-data/sh1 net::ERR_CONNECTION_RESET

Here is the controller method that receives requests, there is no call to it in the logs
   @GetMapping("/get-data/" + RestApiConstants.VARIABLE_NAME)
    public ResponseEntity<ListResponse<DataDto>> getData(
       @PathVariable(RestApiConstants.PARAM_NAME_WORD) String name) {
        log.info("getData -> start");
        return converterDtoService.converterDataDto(name);
    }

Moreover, if you just try to open the link in the browser bar
http://10.151.78.6:5003/es-serv/api/v1/get-data/sh1

Then I get the data every time, I have never noticed any failures.
Very similar to the problem with CORS, but then the browser gives a specific error to all requests. Yes, and cors is disabled in the Java application. And even then it is not clear why it still works on some browsers.
It doesn't look like a timeout problem either, because I get an error instantly, and when the server doesn't respond, some time passes and it's noticeable.
And another such moment, I added a forced data reading button to the application. And after 20-30 attempts to read the data, the answer may still come to those computers that did not receive them.
If it was a problem with the network, then it is unclear why on the same computer from the same browser, the GET request typed in the browser line gets answers all the time, without a single pass.
Tell me where to look to understand the reason?

A: The problem was solved by updating the browsers to the latest version. And before that, the browser version was not very old. I don't understand how this could affect the transmission of the GET request over the network?


text:
Q: How to check if number is a Mersenne prime? What is an efficient way to check if a Int32 n is a Mersenne prime?
This is my attempt :
Apparently this code returns true for some numbers which are a Mersenne prime e.g. 31 but it doesn't for others such as 127.
Can somebody tell me whats wrong with my code?
/// <summary>
/// Checks if a nubmer is a mersenne prime
/// </summary>
/// <param name="candidate"></param>
/// <returns></returns>
public static bool IsMersennePrime(uint n)
{
    var x = Math.Pow(2, n) - 1;
    return IsPrime((uint)x);
}

/// <summary>
/// Checks if a nubmer is a prime
/// </summary>
/// <param name="candidate"></param>
/// <returns>true if number is a prime false if its not a prime</returns>
private static bool IsPrime(uint candidate)
{
    //
    // Test whether the parameter is a prime number.
    //
    if ((candidate & 1) == 0)
    {
        if (candidate == 2)
        {
            return true;
        }
        else
        {
            return false;
        }
    }
    int num = (int)Math.Sqrt((double)candidate);
    for (int i = 3; i <= num; i += 2)
    {
        if ((candidate % i) == 0)
        {
            return false;
        }
    }
    return true;
}

A: Since you just want Mersenne primes which fits into an uint the best way is to check against actual values. Read more about A000043 and A000668.
private static int[] A000043 = new int[] { 2, 3, 5, 7, 13, 17, 19, 31, 61, 89, 107, 127, 521, 607, 1279, 2203, 2281, 3217, 4253, 4423, 9689, 9941, 11213, 19937, 21701, 23209, 44497, 86243, 110503, 132049, 216091, 756839, 859433, 1257787, 1398269, 2976221, 3021377, 6972593, 13466917, 20996011, 24036583, 25964951, 30402457, 32582657 };
private static int[] A000668 = new int[] { 3, 7, 31, 127, 8191, 131071, 524287, 2147483647 };

public static bool IsInA000668(int value) => A000668.Contains(value);
public static bool IsInA000043(int value) => A000043.Contains(value);


text:
Q: Plotting Only One Point in 3D Matplotlib I'm trying to plot the solution of a linear system with 3 planes, the solution is the point (1,1,1) I've plotted the point with point command but I suspect the point is not in the right place:
ax.plot([1.], [1.], [1.], markerfacecolor='k', markeredgecolor='k', marker='o', markersize=5, alpha=0.6)

Thanks
Ok, the code is:
#/usr/bin/env python3
# -*- coding: utf-8 -*-

import numpy as np
import matplotlib.pyplot as plt
from mpl_toolkits.mplot3d import Axes3D
from sympy.solvers import *
from sympy import *
from matplotlib import rcParams

# Activating LateX
rcParams['text.latex.unicode'] = True
rcParams['text.usetex'] = True
rcParams['text.latex.preamble'] = '\\usepackage{amsthm}', '\\usepackage{amsmath}', '\\usepackage{amssymb}',
'\\usepackage{amsfonts}', '\\usepackage[T1]{fontenc}', '\\usepackage[utf8]{inputenc}'

# Declaring the three planes as functions
f1 = lambda x, y: x + y -1
f2 = lambda x, y: 1 - x + y
f3 = lambda x, y: 1 + x - y

# Declaring symbolic variables
x = Symbol('x')
y = Symbol('y')
z = Symbol('z')

# Solving the linear system
fun1 = x+y-z-1
fun2 = x-y+z-1
fun3 = -x+y+z-1
solucion = solve([fun1, fun2, fun3], [x, y, z])

# Printing the solution
pprint(('Solución Del Sistema es: {}').format(solucion))

# Stablishing our ranges for our variables
x1 = y1 = np.arange(-5, 5, 0.25)
ceros = np.zeros(len(x1))

# Stablishing our meshgrid
x, y = np.meshgrid(x1, y1)

# Our 3D Canvas Figure Plot
fig = plt.figure()
ax = fig.add_subplot(111, projection='3d')

# Plotting the 3 planes
ax.plot_surface(x, y, f1(x, y), rstride=1, cstride=1, linewidth=0, antialiased=True, color='blue')
ax.plot_surface(x, y, f2(x, y), rstride=1, cstride=1, linewidth=0, antialiased=True, color='red')
ax.plot_surface(x, y, f3(x, y), rstride=1, cstride=1, linewidth=0, antialiased=True, color='green')
ax.plot([1.], [1.], [1.], markerfacecolor='k', markeredgecolor='k', marker='o', markersize=5, alpha=0.6)

# Putting the limits in the axes
ax.set_xlim(-10, 10)
ax.set_ylim(-10, 10)
ax.set_zlim(-10, 10)

# Writing the axis labels
ax.set_xlabel('x', color='blue')
ax.set_ylabel('y', color='blue')
ax.set_zlabel('z', color='blue')

# Writing The Title of The Plot
ax.set_title(r'$Graphical\; Resolution\; Linear\; System\; 3 \times 3$', fontsize=18)

# Stablishing the plots of our legend labels
blue_proxy = plt.Rectangle((0, 0), 1, 1, fc='b')
red_proxy = plt.Rectangle((0, 0), 1, 1, fc='r')
green_proxy = plt.Rectangle((0, 0), 1, 1, fc='g')
black_proxy = plt.Line2D([0], [0], linestyle="none", marker='o', alpha=0.6, markersize=10, markerfacecolor='black')

# Drawing Our Legend
ax.legend([blue_proxy,red_proxy, green_proxy, black_proxy], [r'$x+y-z=1$',r'$x-y+z=1$', r'$-x+y+z=1$', r'$Sol.\; (1,1,1)$'], numpoints=1, loc='upper left')

plt.show()

An image:
The z-coordinate of the point (1,1,1) is not at the height 1, it is below 0. So, the point is not drawn in the correct place.

A: I think your code is completely correct. The point IS at its position namely (1,1,1). You can drag the plot to see the point from another angle and you'll find that the point is at a correct position.
Trust yourself! By replacing the z-coordinate of point to maybe 10.0, you'll find that your code is correct.


text:
Q: Imprimir con PHP una fecha con números de día Tengo un problema en el que no puedo ponerle el numero del día al nombre del día, muestro el código así se entiende mejor.
    public function get_all_available($id_tipo_turno, $id_lugar){
        $result = array();

         $this->db->select('*');
         $this->db->from('cronograma');
         $this->db->where('id_tipo_turno', $id_tipo_turno);
         $this->db->where('id_lugar', $id_lugar);

         $query=$this->db->get();
         if ($query->num_rows() > 0)
         {
            foreach ($query->result() as $row)
            {
                $id_cronograma = $row->id_cronograma;
            }
        }

        $this->db->select('*');
        $this->db->from('cronograma_dia_semana c');
        $this->db->where('id_cronograma', $id_cronograma);

        $query=$this->db->get();
        $dias = [];
        if ($query->num_rows() > 0)
        {
            foreach ($query->result() as $row)
            {
                $dias[] = (object)array(

                    'id_dia_semana' => $row->id_dia_semana,
                    'hora_inicio'   => $row->hora_inicio,
                    'hora_fin'      => $row->hora_fin,
                    'intervalo'     => $row->intervalo,
                    'name_en'       => $this->get_day_name((int)$row->id_dia_semana),
                    'name_es'       => '',
                );
            }
        }

        $day_name = date('l'); // Tuesday
        $day_number = (int)date('j'); // 8

        $limit = 21;
        $index = 0;
        $fechas_de_atencion =[];

        for( $i=0; $i < $limit; $i++ ){

            $finded = false;

            foreach($dias as $d){
                if( $d->name_en === $day_name ){
                    $finded = true;
                    $day_number++;

                }

            }

            if( $finded ){

                $fechas_de_atencion[] = $day_name .' '. $day_number; // mas el numero de dia ????
            }

            $day_name  = date('l', strtotime($day_name . '+1 day'));

        }

        echo json_encode($fechas_de_atencion);

        return $result;

    }

Ese método me imprime lo siguiente:

["Friday 10","Monday 11","Friday 12","Monday 13","Friday 14","Monday 15"]{"success":true,"message":"","data":[]}

Esto hace lo siguiente, busca días disponibles para sacar un turno X, en mi base de datos tengo que LUNES Y VIERNES están disponibles, y le pongo un limite de 21 días para que me muestre turnos. debería mostrarme esto:

VIERNES 12, LUNES 15, VIERNES 19, LUNES 22, VIERNES 26, LUNES 29

Los números de días es lo que no se calcular, muchas gracias desde ya!

A: PHP tiene funciones builtin para hacer operaciones aritméticas con fechas. No debes hacerlo manualmente con incrementales ya que tendrás complejidad innecesaria cuando la fecha llegue a 30, 31, 1ro, si es bisiesto o cambie el año. Ejemplo de uso:
<?php
$now = new DateTime('NOW'); // Ejemplo con Hoy
$test_day = DateTime::createFromFormat('Y-m-d', '2021-03-20'); // Dia cualquiera

$now->modify('+1 day'); // Mañana
echo $now->format('Y-m-d');
// Imprime: 2021-03-10

// Se puede poner en variable el incremental, por ejemplo para un ciclo.
$add = 1;
$now->modify('+'.$add.' day');
echo $now; // Pasado mañana
// Imprime: 2021-03-11

$test_day->modify('+5 day'); // +5 días
echo $test_day->format('Y-m-d');
// Imprime: 2021-03-25

$test_day->modify('+1 month'); // +1 mes (sumado a los 5 días anteriores)
$days = array('Lunes', 'Martes', 'Miercoles', 'Jueves', 'Viernes', 'Sabado', 'Domingo');
$var = explode(",", $test_day->format('N,d'));
echo $days[$var[0]-1] . ' ' . $var[1];
// Imprime: Domingo 25

Adicional, puedes ver los formatos de salida.

A: Muchas gracias aeportugal, lo solucione de la siguiente manera.
$fecha = date('Y-m-d'); // 2021-03-09
        $limit = 21;
        $fechas_de_atencion =[];

        for( $i=0; $i < $limit; $i++ ){

            //$dia_actual = $this->dame_el_dia($fecha); // aca tiene tuesday martes
            $dia_actual = date('l', strtotime($fecha));
            $finded = false;
            foreach($dias as $d){
                if( $d->name_en === $dia_actual ){
                    $finded = true;
                }
            }

            if( $finded ){

                $fechas_de_atencion[] = date('l', strtotime($fecha)) . ' '. date('d', strtotime($fecha));
            }

            $fecha = date('Y-m-d', strtotime($fecha . '+1 day'));

        }

        echo json_encode($fechas_de_atencion);

        return $result;


text:
Q: Sharepoint/WSS Reporting Services Integration woes after a number of failed attempts i seem to have successfully installed the Reporting services add-in to my WSS farm. However, I seem to be missing most of the enhanced functionality eg no report library template, no report center site template. the only additional functionality available is the report viewer web part.
background: 2 server WSS 3.0 farm with CA (Central admin) WFE (web front end) and reporting services addin installed on 1, and SQL05 SP2 with Reporting services (RS) and all databases installed on other. I have a VM environment set up and have rolled this back and repeated a number of times.
I have configured RS within CA and activated 'Report Server INtegration Feature'. Within the 'site settings' I have a 'Reporting Services' heading with a 'manage shared schedules' item/link, not sure if there should be other options?
I was of the understanding that to view reports within sharepoint i could either create a new site using the 'report center' template or add a report library to an existing site, neither of which seems available
I am at a loss as to what to do, as all online information seems to do with dealing with installation issues/errors, which i seem to have eventually got past

A: It sounds like maybe the SSRS addin for SharePoint didn't get installed.
http://www.microsoft.com/downloads/details.aspx?familyid=1E53F882-0C16-4847-B331-132274AE8C84&displaylang=en
In the AppMgmt section of Central Admin, you should have a "Manage Integration Settings" in the Reporting Services area if this was installed properly.
Here are 2 URLs that discuss the installation and features available:
http://netindonesia.net/blogs/kasim.wirama/archive/2008/01/01/integrate-sql-server-2005-reporting-services-into-windows-sharepoint-services-3-0.aspx
http://blogs.msdn.com/sharepoint/archive/2007/02/19/microsoft-sql-server-2005-sp2-reporting-services-integration-with-wss-3-0-and-moss-2007.aspx


text:
Q: How to Make Sessions and Login Credentials for every page in Asp.net with mysql database? I have done a Admin Web site Using ASP.net, C# with MySQL data Base
My website is Only designed for admin So that I have less users like 4-5..
But I made a Mistake that My Web Site Has 9 Pages in that
If I Copy and Paste the URL of a Page Its opening without login credential's and sessions..
So Please Suggest me for this kind. So that it should check authentication when ever a page is opened.
I am new to asp.net and I tried for this kind But I found Only for SQL server
I want it For ASP.net, C# with MySQL Data Base
I don't want to use SQL-server as its commercial and expansive..

A: Use master page... check credential in master page...
or else

*

*you should pass credential to one page from another page(query string or cookie etc)

*check credential in load method in all pages

http://dotnet.tekyt.info/?p=31
http://www.dotnetfunda.com/codes/show/4580/login-page-using-mysql-database
http://geekswithblogs.net/dotNETvinz/archive/2009/04/30/creating-a-simple-registration-form-in-asp.net.aspx
http://www.codeproject.com/Articles/438259/Insert-Update-Search-and-Delete-CRUD-operation-usi
http://www.mono-project.com/MySQL
http://www.mono-project.com/Database_Access
http://www.codeproject.com/Articles/438259/Insert-Update-Search-and-Delete-CRUD-operation-usi

A: You can use web.config to deny access
<system.web>
    <authorization>
      <allow roles="admin" />
      <deny users="*" />
    </authorization>
  </system.web>


text:
Q: restoring SQL Server from backup into a database with different database name? I have been provided SQL Server backups to restore but they have to be restored into new databases with different names on same server.
To explain it, say I have database "MyDB" and its backup "MyDB_full.bac" has been provided. I want to restore it into "MyDB_new".
What I have tried ?
I have tried to restore  it in SSMS but was unsuccessful, since I m getting error message :

the backup set holds a backup of a database other than the existing

Kindly note I don't want to lose basic database "MyDB".

A: I found this link to be particularly helpful. I'll summarize below:
you are probably trying to restore the database on another existing active database. You can run the following query (albeit with your details filled in) to restore your database:

RESTORE DATABASE AdventureWorks
FROM DISK = 'C:\BackupAdventureworks.bak'
WITH REPLACE


text:
Q: ValueError: Input 0 is incompatible with layer conv2d_1: expected ndim=4, found ndim=5 I am trying to pass a RGB image from a simulator into my custom neural network. At the source of the RGB generation (simulator), the dimension of RGB image is (3,144,256).
This is how I construct the neural network:
rgb_model = Sequential()
rgb = env.shape() // this is (3, 144, 256)
rgb_shape = (1,) + rgb
rgb_model.add(Conv2D(96, (11, 11), strides=(3, 3), padding='valid', activation='relu', input_shape=rgb_shape, data_format = "channels_first"))
Now, my rbg_shape is (1, 3, 144, 256).

This is the error I get:
rgb_model.add(Conv2D(96, (11, 11), strides=(3, 3), padding='valid', activation='relu', input_shape=rgb_kshape, data_format = "channels_first"))
File "/usr/local/lib/python2.7/dist-packages/keras/engine/sequential.py", line 166, in add
layer(x)
File "/usr/local/lib/python2.7/dist-packages/keras/engine/base_layer.py", line 414, in call
self.assert_input_compatibility(inputs)
File "/usr/local/lib/python2.7/dist-packages/keras/engine/base_layer.py", line 311, in assert_input_compatibility
str(K.ndim(x)))
ValueError: Input 0 is incompatible with layer conv2d_1: expected ndim=4, found ndim=5

Why is keras complaining that the expected dimension is 5 when my actual dimension is 4?
P.S: I have the same question as this question. I ideally wanted to comment on that post but don't have enough reputation.
Edit:
Here is the code that deals with the error:
rgb_shape = env.rgb.shape
rgb_model = Sequential()
rgb_model.add(Conv2D(96, (11, 11), strides=(3, 3), padding='valid', activation='relu', input_shape=rgb_shape, data_format = "channels_first"))
rgb_model.add(Conv2D(128, (3, 3), strides=(2, 2), padding='valid', activation='relu', data_format = "channels_first" ))
rgb_model.add(Conv2D(384, (3, 3), strides=(1, 1), padding='valid', activation='relu', data_format = "channels_first"))
rgb_model.add(Conv2D(384, (3, 3), strides=(1,1), padding='valid', activation='relu', data_format = "channels_first"))
rgb_model.add(Conv2D(256, (3,3), strides=(1,1), padding='valid', activation='relu', data_format = "channels_first"))
rgb_model.add(Flatten())
rgb_input = Input(shape=rgb_shape)
rgb = rgb_model(rgb_input)

This is the new error when I pass env.rgb.shape as input_shape in Conv2D:
dqn.fit(env, callbacks=callbacks, nb_steps=250000, visualize=False, verbose=0, log_interval=100)
  File "/usr/local/lib/python2.7/dist-packages/rl/core.py", line 169, in fit
    action = self.forward(observation)
  File "/usr/local/lib/python2.7/dist-packages/rl/agents/dqn.py", line 228, in forward
    q_values = self.compute_q_values(state)
  File "/usr/local/lib/python2.7/dist-packages/rl/agents/dqn.py", line 69, in compute_q_values
    q_values = self.compute_batch_q_values([state]).flatten()
  File "/usr/local/lib/python2.7/dist-packages/rl/agents/dqn.py", line 64, in compute_batch_q_values
    q_values = self.model.predict_on_batch(batch)
  File "/usr/local/lib/python2.7/dist-packages/keras/engine/training.py", line 1276, in predict_on_batch
    x, _, _ = self._standardize_user_data(x)
  File "/usr/local/lib/python2.7/dist-packages/keras/engine/training.py", line 754, in _standardize_user_data
    exception_prefix='input')
  File "/usr/local/lib/python2.7/dist-packages/keras/engine/training_utils.py", line 126, in standardize_input_data
    'with shape ' + str(data_shape))
ValueError: Error when checking input: expected input_1 to have 4 dimensions, but got array with shape (1, 1, 3, 144, 256)

A: The input shape of a Conv2D layer is (num_channels, width, height). So you should not add another dimension (actually the input shape is (batch_size, num_channels, width, height) but you don't need to set batch_size here; it will be set in fit method). Just pass input_shape=env.shape to Conv2D and it would work fine.
Edit:
Why do you define an Input layer and pass it to the model? That's not how it works. First, you need to compile the model using compile method, then train it on the training data using fit method and then use predict method to make predictions. I highly recommend to read the official guide to find out how these things work.