问:
Optimizing queries for content popularity by hits

I've done some searching for this but haven't come up with anything, maybe someone could point me in the right direction.

I have a website with lots of content in a MySQL database and a PHP script that loads the most popular content by hits. It does this by logging each content hit in a table along with the access time. Then a select query is run to find the most popular content in the past 24 hours, 7 day or maximum 30 days. A cronjob deletes anything older than 30 days in the log table.

The problem I'm facing now is as the website grows the log table has 1m+ hit records and it is really slowing down my select query (10-20s). At first I though the problem was a join I had in the query to get the content title, url, etc. But now I'm not sure as in test removing the join does not speed the query as much as I though it would.

So my question is what is best practise of doing this kind of popularity storing/selecting? Are they any good open source scripts for this? Or what would you suggest?

Table scheme

"popularity" hit log table

  nid | insert_time | tid

  nid: Node ID of the content

  insert_time: timestamp (2011-06-02 04:08:45)

  tid: Term/category ID

"node" content table

  nid | title | status | (there are more but these are the important ones)

  nid: Node ID

  title: content title

  status: is the content published (0=false, 1=true)

SQL

```<code>SELECT node.nid, node.title, COUNT(popularity.nid) AS count
FROM `node` INNER JOIN `popularity` USING (nid)
WHERE node.status = 1
  AND  popularity.insert_time >= DATE_SUB(CURDATE(),INTERVAL 7 DAY)
GROUP BY popularity.nid
ORDER BY count DESC
LIMIT 10;
</code>```

答:
You can do some 'aggregation' in te background, for example by a con job. Some suggestions (in no particular order) that might help:

1. Create a table with hourly results. This means you can still create the statistics you want, but you reduce the amount of data to (24*7*4 = about 672 records per page per month).

your table can be somewhere along the lines of this:

```
hourly_results (
nid integer,
start_time datetime,
amount integer
)
```

after you parse them into your aggregate table you can more or less delete them.

2.Use result caching (memcache, apc)
You can easily store the results (which should not change every minute, but rather every hour?), either in a memcache database (which again you can update from a cronjob), use the apc user cache (which you can't update from a cronjob) or use file caching by serializing objects/results if you're short on memory.

3. Optimize your database
10 seconds is a long time. Try to find out what is happening with your database. Is it running out of memory? Do you need more indexes?

Body:
I've done some searching for this but haven't come up with anything, maybe someone could point me in the right direction.

I have a website with lots of content in a MySQL database and a PHP script that loads the most popular content by hits. It does this by logging each content hit in a table along with the access time. Then a select query is run to find the most popular content in the past 24 hours, 7 day or maximum 30 days. A cronjob deletes anything older than 30 days in the log table.

The problem I'm facing now is as the website grows the log table has 1m+ hit records and it is really slowing down my select query (10-20s). At first I though the problem was a join I had in the query to get the content title, url, etc. But now I'm not sure as in test removing the join does not speed the query as much as I though it would.

So my question is what is best practise of doing this kind of popularity storing/selecting? Are they any good open source scripts for this? Or what would you suggest?

Table scheme

"popularity" hit log table

  nid | insert_time | tid

  nid: Node ID of the content

  insert_time: timestamp (2011-06-02 04:08:45)

  tid: Term/category ID

"node" content table

  nid | title | status | (there are more but these are the important ones)

  nid: Node ID

  title: content title

  status: is the content published (0=false, 1=true)

SQL

SELECT node.nid, node.title, COUNT(popularity.nid) AS count
FROM `node` INNER JOIN `popularity` USING (nid)
WHERE node.status = 1
  AND  popularity.insert_time >= DATE_SUB(CURDATE(),INTERVAL 7 DAY)
GROUP BY popularity.nid
ORDER BY count DESC
LIMIT 10;

Body:
You can do some 'aggregation' in te background, for example by a con job. Some suggestions (in no particular order) that might help:

1. Create a table with hourly results. This means you can still create the statistics you want, but you reduce the amount of data to (24*7*4 = about 672 records per page per month).

your table can be somewhere along the lines of this:

hourly_results (
nid integer,
start_time datetime,
amount integer
)

after you parse them into your aggregate table you can more or less delete them.

2.Use result caching (memcache, apc)
You can easily store the results (which should not change every minute, but rather every hour?), either in a memcache database (which again you can update from a cronjob), use the apc user cache (which you can't update from a cronjob) or use file caching by serializing objects/results if you're short on memory.

3. Optimize your database
10 seconds is a long time. Try to find out what is happening with your database. Is it running out of memory? Do you need more indexes?


来源: stackexchange

问:
Nested SQL IN statement for cell with more than 1 value

How do i write the SQL such that it will return me

tom,ken,jerry

I tried this SQL as

```<code>select name
  from staffDB
 where dept in (select value
                  from ConfigDB
                 where key = 'dept')
</code>```

but it returns no value, no nope, i'm not allowed to alter the database design.

答:
One option would be splitting by commas, an then combining through use of LISTAGG() function within SELECT .. CONNECT BY level .. Statement :

```<code>WITH ConfigDB( key, value ) AS
(
 SELECT 'dept', 'A,B,C' FROM dual
), StaffDB( name, dept ) AS
(
 SELECT 'tom'  , 'A' FROM dual UNION ALL
 SELECT 'ken'  , 'B' FROM dual UNION ALL
 SELECT 'jerry', 'C' FROM dual
), t AS
(
 SELECT REGEXP_SUBSTR(value,'[^,]',1,level) AS letter, level AS lvl
   FROM ConfigDB
  CONNECT BY level <= REGEXP_COUNT(value,',') + 1
)
SELECT LISTAGG(name,',') WITHIN GROUP (ORDER BY lvl) AS DBNAme
  FROM t
  JOIN StaffDB
    ON dept = letter
</code>```

Demo

ContentLicense: CC BY-SA 4.0

Body:
How do i write the SQL such that it will return me

tom,ken,jerry

I tried this SQL as

select name
  from staffDB
 where dept in (select value
                  from ConfigDB
                 where key = 'dept')

but it returns no value, no nope, i'm not allowed to alter the database design.

Body:
One option would be splitting by commas, an then combining through use of LISTAGG() function within SELECT .. CONNECT BY level .. Statement :

WITH ConfigDB( key, value ) AS
(
 SELECT 'dept', 'A,B,C' FROM dual
), StaffDB( name, dept ) AS
(
 SELECT 'tom'  , 'A' FROM dual UNION ALL
 SELECT 'ken'  , 'B' FROM dual UNION ALL
 SELECT 'jerry', 'C' FROM dual
), t AS
(
 SELECT REGEXP_SUBSTR(value,'[^,]',1,level) AS letter, level AS lvl
   FROM ConfigDB
  CONNECT BY level <= REGEXP_COUNT(value,',') + 1
)
SELECT LISTAGG(name,',') WITHIN GROUP (ORDER BY lvl) AS DBNAme
  FROM t
  JOIN StaffDB
    ON dept = letter

Demo


问:
How to get parameter "par" from link app/page/par in a servlet?
I have some app, where a user going to link like "..app/page/par", should be redirected to page "..app/page" and then on it page should be add some data, that I should get using parameter "par"

How can I do it, using java servlets?

答:
The session scope can be used to store the parameter value on the server side between the two requests.

Request 1
app/page/par

```<code>String parameterValue = request.getParameter("par");
request.getSession().setAttribute("par", parameterValue);
response.sendRedirect("app/page");
</code>```

Request 2
app/page

```<code>// pass the value to the view
request.setAttribute("viewAttributeName", request.getSession().getAttribute("par"));
</code>```

Body:
The session scope can be used to store the parameter value on the server side between the two requests.

Request 1
app/page/par

String parameterValue = request.getParameter("par");
request.getSession().setAttribute("par", parameterValue);
response.sendRedirect("app/page");

Request 2
app/page

// pass the value to the view
request.setAttribute("viewAttributeName", request.getSession().getAttribute("par"));


问:
Rails 3.1: Engine vs. Mountable App
Can someone help me understand the differences between a Rails Engine and a Mountable app?  In Rails 3.1, you can create either one with the "rails new plugin ___" command.

```<code>rails plugin new forum --full        # Engine
rails plugin new forum --mountable   # Mountable App
</code>```

When would you want to use one versus the other?  I know you can package an Engine as a gem, for one.  Is that not the case for Mountable Apps?  What other differences are there?

答:
The difference, I believe, is that a mountable app's are isolated from the host app, so they can't share classes - models, helper etc. This is because a Mountable app is a Rack endpoint (i.e a Rack app in its own right).

Disclaimer: I have, like most, only just started toying with Rails 3.1.

ContentLicense: CC BY-SA 3.0

Title: Rails 3.1: Engine vs. Mountable App

Body:
Can someone help me understand the differences between a Rails Engine and a Mountable app?  In Rails 3.1, you can create either one with the "rails new plugin ___" command.

rails plugin new forum --full        # Engine
rails plugin new forum --mountable   # Mountable App

When would you want to use one versus the other?  I know you can package an Engine as a gem, for one.  Is that not the case for Mountable Apps?  What other differences are there?


问:
How do I Building an Android application that can print files (PDF, photos, ...) with a printer inside the network?
I am building an Android application that prints files with a printer inside the network, I have used network service discovery (NSD) and I already got an Ip and port and also a printer name, so now I need how to call this printer and send a print command to it, these are preliminary pictures of the application that I work on him :

My app: image before click Search Button

My app: image after click Search Button

So anyone can help me !!

答:
The android documents are so clear about it.
what kind of file do you want to print:

Printing photos

Printing a custom document

Printing an HTML document


问:
Python, detect letters with “in”
I’m learning python and got stuck on the “in” keyword.
I want to write a simple code which detects the Turkish letters, for example ı,ş,ö,ç,ğ,ü. But my code never find those letters. It always prints ok. What can I do?

usern = input("username:")
if usern in ("ş", "ı", "ö", "ç", "ü", "ğ"):
    print("turkish letter detected")
else:
    print("ok.")
```

答:
The membership test is the other way around, and using any() will simplify things. Also, if you want a bit more extra efficiency, you can convert usern into a set object, for faster membership testing:

```<code>userset = set(usern)
if any(c in userset for c in ("ş","ı","ö","ç","ü","ğ")):
    ...
</code>```

Title: Python, detect letters with “in”

Body:
The membership test is the other way around, and using any() will simplify things. Also, if you want a bit more extra efficiency, you can convert usern into a set object, for faster membership testing:

userset = set(usern)
if any(c in userset for c in ("ş","ı","ö","ç","ü","ğ")):
    ...


问:
create multi div element in jquery
I want to create a function that creates several boxes for me by capturing the title, text, photo, link and text of the link. That these values change, but the overall shape of the boxes is a model

each div contain with Different values taken by jquery codes:

```<code><div>
   <img></img>
   <h3></h3>
   <p></p>
   <a><span></span></a>
</div>
</code>```

i try it but not complete and not work:

```<code>$(document).ready(function () {
        var newDiv = document.getElementById("reports-box");

        function makenewDivBox(options) {
            var div = document.createElement("div");
            for (var i = 0; i < options.length; i++) {
                var div = document.createElement("div");
                var img = document.createElement("img");
                var title = document.createElement("h3");
                var description = document.createElement("p");
                var link = document.createElement("a");
                var linkText = document.createElement("span");
                img.id = img1;
                img.type = "img";
                img.src = options[i].src;
                title.id = Title1;
                title.type = "h3";
                title.text = options[i].text;
                description.id = des1;
                description.type = "p";
                description.text = options[i].text;
                link.id = link1;
                link.type = "hrefa";
                link.text = options[i].text;
                linkText.id = des1;
                linkText.type = "hrefa";
                linkText.text = options[i].text;
                div.appendChild(img)
                div.appendChild(title)
                div.appendChild(description)
                div.appendChild(link)
                div.appendChild(linkText)
            }
            newDiv.appendChild(div);
        }
        var options1 = [{
            title="t1",
            img: "url('image/j1.png')",
            description: "content1",
            link: "www.link1.com",
            linkText: "click here"
        }]
        var options2 = [{
            title="t2",
            img: "url('image/j2.png')",
            description: "content2",
            link: "www.link2.com",
            linkText: "more here"
        }]
        var options3 = [{
            title="t3",
            img: "url('image/j3.png')",
            description: "content3",
            link: "www.link3.com",
            linkText: "report here"
        }]
        var options4 = [{
            title="t4",
            img: "url('image/j4.png')",
            description: "content4",
            link: "www.link4.com",
            linkText: "more details here"
        }]
        makenewDivBox(options1);
        makenewDivBox(options2);
        makenewDivBox(options3);
        makenewDivBox(options4);
});
</code>```

答:
I was able to solve it myself.
I'll put the code here, maybe it will be useful for someone:

in html:

```<code><div class="rowReports"></div>
</code>```

in jquery:

```<code>$(document).ready(function () {
var Titels = [
            "title1",
            "title2",
            "title3",
            "title4",
            "title5",
            "title6",
            "title7",
            "title8"
        ];
        var imgSrces = [
            "/FrontEnd/media/image/Nashriyat.png",
            "/FrontEnd/media/image/plan.png",
            "/FrontEnd/media/image/majameElmi.png",
            "/FrontEnd/media/image/kargahAmuzeshi.png",
            "/FrontEnd/media/image/targoman.png",
            "/FrontEnd/media/image/scoma.png",
            "/FrontEnd/media/image/elmsanji.png",
            "/FrontEnd/media/image/tablighat.png"
        ];
        var Descriptions = [
            "Desc1",
            "Desc2 ",
            "Desc3",
            "Desc4",
            "Desc5",
            "Desc6",
            "Desc7",
            "Desc8",
            "Desc9"
        ]
        var Links = [
            "/Page/frmDefault1.aspx",
            "/Page/frmDefault2.aspx",
            "/Page/frmDefault3.aspx",
            "/Page/frmDefault4.aspx",
            "/Page/frmDefault5.aspx",
            "/Page/frmDefault6.aspx",
            "/Page/frmDefault7.aspx",
            "/Page/frmDefault8.aspx"
        ];
        var TextLinks = [
            "more report",
            "send email",
            "more details",
            "join group",
            "more info",
            "add number",
            "more",
            "continue"
        ];
        for (i = 0; i<Titels.length; i++)
            $('.rowReports').append(
                $('<div/>')
                .attr("id", "newDiv"+i)
                    .addClass("newDiv reports-box bloated")
                    .append(' <a href="' + Links[i] + '">' +
                        '<img class="servicesPic" alt="info" src="' + imgSrces[i] + '"/>' + '<h3>' + Titels[i] + '</h3>' +
                        '<p>' + Descriptions[i] + '</p>' +
                    '<span>' + TextLinks[i] + '</span>'+ '</a>'
                        )

        );
});
</code>```

Title: create multi div element in jquery

Body:
I want to create a function that creates several boxes for me by capturing the title, text, photo, link and text of the link. That these values change, but the overall shape of the boxes is a model

each div contain with Different values taken by jquery codes:

i try it but not complete and not work:

$(document).ready(function () {
        var newDiv = document.getElementById("reports-box");

        function makenewDivBox(options) {
            var div = document.createElement("div");
            for (var i = 0; i < options.length; i++) {
                var div = document.createElement("div");
                var img = document.createElement("img");
                var title = document.createElement("h3");
                var description = document.createElement("p");
                var link = document.createElement("a");
                var linkText = document.createElement("span");
                img.id = img1;
                img.type = "img";
                img.src = options[i].src;
                title.id = Title1;
                title.type = "h3";
                title.text = options[i].text;
                description.id = des1;
                description.type = "p";
                description.text = options[i].text;
                link.id = link1;
                link.type = "hrefa";
                link.text = options[i].text;
                linkText.id = des1;
                linkText.type = "hrefa";
                linkText.text = options[i].text;
                div.appendChild(img)
                div.appendChild(title)
                div.appendChild(description)
                div.appendChild(link)
                div.appendChild(linkText)
            }
            newDiv.appendChild(div);
        }
        var options1 = [{
            title="t1",
            img: "url('image/j1.png')",
            description: "content1",
            link: "www.link1.com",
            linkText: "click here"
        }]
        var options2 = [{
            title="t2",
            img: "url('image/j2.png')",
            description: "content2",
            link: "www.link2.com",
            linkText: "more here"
        }]
        var options3 = [{
            title="t3",
            img: "url('image/j3.png')",
            description: "content3",
            link: "www.link3.com",
            linkText: "report here"
        }]
        var options4 = [{
            title="t4",
            img: "url('image/j4.png')",
            description: "content4",
            link: "www.link4.com",
            linkText: "more details here"
        }]
        makenewDivBox(options1);
        makenewDivBox(options2);
        makenewDivBox(options3);
        makenewDivBox(options4);
});

Body:
I was able to solve it myself.
I'll put the code here, maybe it will be useful for someone:

in html:

<div class="rowReports"></div>

in jquery:

$(document).ready(function () {
var Titels = [
            "title1",
            "title2",
            "title3",
            "title4",
            "title5",
            "title6",
            "title7",
            "title8"
        ];
        var imgSrces = [
            "/FrontEnd/media/image/Nashriyat.png",
            "/FrontEnd/media/image/plan.png",
            "/FrontEnd/media/image/majameElmi.png",
            "/FrontEnd/media/image/kargahAmuzeshi.png",
            "/FrontEnd/media/image/targoman.png",
            "/FrontEnd/media/image/scoma.png",
            "/FrontEnd/media/image/elmsanji.png",
            "/FrontEnd/media/image/tablighat.png"
        ];
        var Descriptions = [
            "Desc1",
            "Desc2 ",
            "Desc3",
            "Desc4",
            "Desc5",
            "Desc6",
            "Desc7",
            "Desc8",
            "Desc9"
        ]
        var Links = [
            "/Page/frmDefault1.aspx",
            "/Page/frmDefault2.aspx",
            "/Page/frmDefault3.aspx",
            "/Page/frmDefault4.aspx",
            "/Page/frmDefault5.aspx",
            "/Page/frmDefault6.aspx",
            "/Page/frmDefault7.aspx",
            "/Page/frmDefault8.aspx"
        ];
        var TextLinks = [
            "more report",
            "send email",
            "more details",
            "join group",
            "more info",
            "add number",
            "more",
            "continue"
        ];
        for (i = 0; i<Titels.length; i++)
            $('.rowReports').append(
                $('<div/>')
                .attr("id", "newDiv"+i)
                    .addClass("newDiv reports-box bloated")
                    .append(' <a href="' + Links[i] + '">' +
                        '<img class="servicesPic" alt="info" src="' + imgSrces[i] + '"/>' + '<h3>' + Titels[i] + '</h3>' +
                        '<p>' + Descriptions[i] + '</p>' +
                    '<span>' + TextLinks[i] + '</span>'+ '</a>'
                        )

        );
});


问:
How to configure kafka topic retention policy during creation with Spring?
I need to configure retention policy of a particular topic during creation. I tried to look for solution i could only find command level alter command as below

./bin/kafka-topics.sh --zookeeper localhost:2181 --alter --topic my-topic --config retention.ms=1680000

Can someone let me know a way to configure it during creation, something like xml or properties file configuration in spring-mvc.

答:
To create a topic using AdminClient programmatically with the specified retention time, do the following:

NewTopic topic = new NewTopic(topicName, numPartitions, replicationFactor);
topic.configs(Map.of(TopicConfig.RETENTION_MS_CONFIG, retentionMs.toString()));
adminClient.createTopics(List.of(topic));
```


问:
Android Studio - XML Editor autocomplete not working with support libraries
I just started using the new android.support.design library. When using any of the widgets inside the XML editor I stop getting the XML autocomplete suggestions!

For example,

```<code><android.support.design.widget.CoordinatorLayout
    android:id="@+id/header_root"
    android:layout_width="match_parent"
    android:layout_height="200dp">

    <ImageView
        android:layout_width="match_parent"
        android:layout_height="match_parent"
        android:background="@color/primary_dark" />

    <android.support.design.widget.FloatingActionButton
        android:layout_width="wrap_content"
        android:layout_height="wrap_content"
        android:layout_gravity="bottom|right"
        android:src="@drawable/ic_action_add"
        android:layout_marginLeft="16dp"
        android:layout_marginRight="16dp"
        android:layout_marginTop="56dp"
        app:fabSize="normal"
        app:layout_anchor="@id/header_root"
        app:layout_anchorGravity="bottom|right|end" />

</android.support.design.widget.CoordinatorLayout>
</code>```

None of the tags will show the autocomplete popup, like when I start typing "android:i" no popup appears, the only suggestion I get is shown in the following picture.

I have tried cleaning my project, restarting the pc, restarting Android Studio.. nothing is working!

答:
One possibility is to check power mode in the android studio. Go to File > Power mode and check it's on or off.
If it is on, You also will not get any suggestions. To get suggestions, It must be off.

If it doesn't work for you then you should reset your Android studio which will set the default configuration for you.
For that, find out .AndroidStudioBeta or .AndroidStudio folder and delete those and restart the android studio. Generally, you will get this folder into users\[user name]\.AndroidStudio3.3.

Let me know if it helps you then. Happy coding..!

Body:
I just started using the new android.support.design library. When using any of the widgets inside the XML editor I stop getting the XML autocomplete suggestions!

For example,

<android.support.design.widget.CoordinatorLayout
    android:id="@+id/header_root"
    android:layout_width="match_parent"
    android:layout_height="200dp">

    <ImageView
        android:layout_width="match_parent"
        android:layout_height="match_parent"
        android:background="@color/primary_dark" />

    <android.support.design.widget.FloatingActionButton
        android:layout_width="wrap_content"
        android:layout_height="wrap_content"
        android:layout_gravity="bottom|right"
        android:src="@drawable/ic_action_add"
        android:layout_marginLeft="16dp"
        android:layout_marginRight="16dp"
        android:layout_marginTop="56dp"
        app:fabSize="normal"
        app:layout_anchor="@id/header_root"
        app:layout_anchorGravity="bottom|right|end" />

</android.support.design.widget.CoordinatorLayout>

None of the tags will show the autocomplete popup, like when I start typing "android:i" no popup appears, the only suggestion I get is shown in the following picture.

I have tried cleaning my project, restarting the pc, restarting Android Studio.. nothing is working!


问:
how can i disable user touch of a UIbarbutton without disabling?
i have a UiBarButton item in my Toolbar.i need to deactivate the user touch interaction in
UiBarButton. there is no setUserInteractionEnabled property to it.  when i am hiding it there is no proper visibility .can any one tell me that how can i disable user touch interaction of a UIbarbutton without disabling it?

答:
You can always do:

```<code>[yourbutton removeTarget:nil
                  action:NULL
        forControlEvents:UIControlEventAllEvents];
</code>```

That will remove all actions and targets associated with the button.

Body:
You can always do:

[yourbutton removeTarget:nil
                  action:NULL
        forControlEvents:UIControlEventAllEvents];

That will remove all actions and targets associated with the button.


问:
Chaining Regex replace on apache superset with postgres backend
I am trying to create a new column based on other column with regexp on apache-superset and postgres backend.

I am using:

```<code>REGEXP_REPLACE(website,'^[a-z]{2}\\.google.com', 'google')
</code>```

Which works and now I have a new column where 'google' is present when the regexp is True. How can I chain multiple statements for example have:

```<code>REGEXP_REPLACE(website,'^[a-z]{2}\\.google.com', 'google')
REGEXP_REPLACE(website,'^[a-z]{2}\\.bing.com', 'bing')
</code>```

When I try to add new regexp_replace it stops working, I've tried separating the statements by a comma but it does not work.

Basically I need something similar to this in postgres:

```<code>CASE
    WHEN REGEXP_MATCH(website,'^[a-z]{2}\\.google.com')
        THEN 'google'
    WHEN  REGEXP_MATCH(website,'^[a-z]{2}\\.bing.com')
        THEN 'bing'
    ELSE '(other)'
END
</code>```

答:
You could try using a capture group:

```<code>REGEXP_REPLACE(website,'^[a-z]{2}\\.(google|bing)\\.com', '\\1')
</code>```

Note that if the above does not work, then try using \1 or $1 as the capture group.

Body:
I am trying to create a new column based on other column with regexp on apache-superset and postgres backend.

I am using:

REGEXP_REPLACE(website,'^[a-z]{2}\\.google.com', 'google')

Which works and now I have a new column where 'google' is present when the regexp is True. How can I chain multiple statements for example have:

REGEXP_REPLACE(website,'^[a-z]{2}\\.google.com', 'google')
REGEXP_REPLACE(website,'^[a-z]{2}\\.bing.com', 'bing')

When I try to add new regexp_replace it stops working, I've tried separating the statements by a comma but it does not work.

Basically I need something similar to this in postgres:

CASE
    WHEN REGEXP_MATCH(website,'^[a-z]{2}\\.google.com')
        THEN 'google'
    WHEN  REGEXP_MATCH(website,'^[a-z]{2}\\.bing.com')
        THEN 'bing'
    ELSE '(other)'
END

Body:
You could try using a capture group:

REGEXP_REPLACE(website,'^[a-z]{2}\\.(google|bing)\\.com', '\\1')

Note that if the above does not work, then try using \1 or $1 as the capture group.


问:
How to do "static overloaded const" in C#?
I'm creating a game in C#. Each level is made up of several tiles. Each tile is of a certain type e.g. grass floor, wooden wall, etc.

Ideally I would like to have one base class "Tile" and inherit from it to create classes for each type of tile. I would like to have the properties of the tile some kind of static/const/etc member of the sub-class since each type of tile is only ever going to have the same properties. I.e. I don't want 100 Tiles have a property which all have the same value, that seems rather inefficient.

The problem is you can't do that in C#. Are there any ways to achieve what I want?

My alternative idea was to separate it all into to trees, one with only the class "Tile" which represents an instance and another "TileType" from which I instanciate one object for each type and maybe access them through some kind of "TileTypeCollection". This feels strange though and I would rather do it in the first way.

Are there any general guidelines when dealing with a situation like this?

答:
There are several options which jump to mind depending on exact requirements.

IF there is a common property which differs in value for each type, then declare it in the base class, make it a readonly value and set it in the constructor of each type.

If you have properties which only exist on a specific type, then these should be declared in the sub-class and similarly read-only.


答:
Try

usern=input(“username:”)
if any([let in [“ş”,“ı”,”ö”,”ç”,”ü”,”ğ”] for let in usern]):
     print(“turkish letter detected”)
else
    print(“ok.”)
```

Title: Python, detect letters with “in”

Body:
I’m learning python and got stuck on the “in” keyword.
I want to write a simple code which detects the Turkish letters, for example ı,ş,ö,ç,ğ,ü. But my code never find those letters. It always prints ok. What can I do?

usern = input("username:")
if usern in ("ş", "ı", "ö", "ç", "ü", "ğ"):
    print("turkish letter detected")
else:
    print("ok.")


问:
Element with that ID already exists in the database
I am working on a practice Spring Boot project that lists/adds/updates/deletes math problems from a mysql database. I am using Spring Boot with JPA to do the database operations. In my case, the db already has the problems and the button 'listproblems' returns all the buttons to a table. I can edit/delete without a problem. But when it comes to adding a new problem, I don't know how to add the new entry to the database. At this point, I don't know what to share but here is the current addProblem method:

```<code>//This is in the ProblemController.java on the server side application

@PostMapping("/post")
    public void addProduct(@RequestParam("cont") String pcont) {

        // Get a valid pid first
        Iterable<Problem> problist = probRepository.findAll();
        int min = 100000;
        int max = 0;
        int gap = 0;

        for (Problem myprod : problist) {
            if (myprod.getPid() < min) {
                min = myprod.getPid();
            }
            if (myprod.getPid() > max) {
                max = myprod.getPid();
            }
        }

        for (int i = min + 1; i < max; i++) {
            if (!probRepository.existsById(i)) {
                gap = i;
                break;
            }
        }

        if (gap == 0) {
            gap = max + 1;
        }

        System.out.println("max: " + max);

        max = max + 1;

        Problem prob = new Problem();
        prob.setPid(max);
        prob.setContent(pcont);
        probRepository.save(prob);
    }
</code>```

Problem.java Entity class

```<code>@Entity
public class Problem {
    @Id
    @GeneratedValue(strategy=GenerationType.AUTO)
    private Integer pid;

    @Column(name = "content")
    private String content;

    public Integer getPid() {
        return pid;
    }

    public void setPid(Integer pid) {
        this.pid = pid;
    }

    public String getContent() {
        return content;
    }

    public void setContent(String content) {
        this.content = content;
    }

}
</code>```

This function is basically iterating through the items to find the maximum index, then incrementing the index by 1 to get the next index. But It still doesn't work.

Please let me know if you want to see anything in particular to help me understand this.

答:
Thank you. Looking at the entity and your code, I would say that you are using the The_Auto_Strategy that will generate an ID automatically. You could just remove:

```<code>prob.setPid(max);
</code>```

And your code should work.
If you want to set an ID you should use:

```<code>@Id
@GeneratedValue(strategy=GenerationType.IDENTITY)
private Integer pid;
</code>```

Body:
I am working on a practice Spring Boot project that lists/adds/updates/deletes math problems from a mysql database. I am using Spring Boot with JPA to do the database operations. In my case, the db already has the problems and the button 'listproblems' returns all the buttons to a table. I can edit/delete without a problem. But when it comes to adding a new problem, I don't know how to add the new entry to the database. At this point, I don't know what to share but here is the current addProblem method:

//This is in the ProblemController.java on the server side application

@PostMapping("/post")
    public void addProduct(@RequestParam("cont") String pcont) {

        // Get a valid pid first
        Iterable<Problem> problist = probRepository.findAll();
        int min = 100000;
        int max = 0;
        int gap = 0;

        for (Problem myprod : problist) {
            if (myprod.getPid() < min) {
                min = myprod.getPid();
            }
            if (myprod.getPid() > max) {
                max = myprod.getPid();
            }
        }

        for (int i = min + 1; i < max; i++) {
            if (!probRepository.existsById(i)) {
                gap = i;
                break;
            }
        }

        if (gap == 0) {
            gap = max + 1;
        }

        System.out.println("max: " + max);

        max = max + 1;

        Problem prob = new Problem();
        prob.setPid(max);
        prob.setContent(pcont);
        probRepository.save(prob);
    }

Problem.java Entity class

@Entity
public class Problem {
    @Id
    @GeneratedValue(strategy=GenerationType.AUTO)
    private Integer pid;

    @Column(name = "content")
    private String content;

    public Integer getPid() {
        return pid;
    }

    public void setPid(Integer pid) {
        this.pid = pid;
    }

    public String getContent() {
        return content;
    }

    public void setContent(String content) {
        this.content = content;
    }

}

This function is basically iterating through the items to find the maximum index, then incrementing the index by 1 to get the next index. But It still doesn't work.

Please let me know if you want to see anything in particular to help me understand this.

Body:
Thank you. Looking at the entity and your code, I would say that you are using the The_Auto_Strategy that will generate an ID automatically. You could just remove:

prob.setPid(max);

And your code should work.
If you want to set an ID you should use:

@Id
@GeneratedValue(strategy=GenerationType.IDENTITY)
private Integer pid;


问:
Getting property description attribute
Existing code (simplified)

I have this function

```<code>public static string[] GetFieldNames<T>(IEnumerable<T> items)
  where T : class
{
  var properties = typeof(T).GetProperties().Where(p => SystemTypes.Contains(p.PropertyType)); // Only get System types

  return properties.Select(p => p.Name).ToArray();
}
</code>```

So if say I have this class

```<code>class MyClass {
  public string Name { get; set; }

  [Description("The value")]
  public int Value { get; set; }
}
</code>```

I can have code like this

```<code>List<MyClass> items = ...; // Populate items somehow
string[] fieldNames = GetFieldNames(items); // This returns ["Name", "Value"]
</code>```

That works fine.

The problem

I need to get the Description (if it exists), so that GetFieldNames(items) returns ["Name", "The value"]

How do I modify the GetFieldNames() function to read the Description attribute if it exists?

(Please note that this function has been simplified, the real function is much more complex, so please avoid changing the logic)

答:
I am using Description attribute a lot so I wrote Nuget for this purpose.

With it you could just call:

```<code>typeof(TestClass).GetPropertyDescription("PropertyName");
</code>```

It also allows to take DescriptionAttribute from class, field, enum and method.

Title: Getting property description attribute

Body:
Existing code (simplified)

I have this function

public static string[] GetFieldNames<T>(IEnumerable<T> items)
  where T : class
{
  var properties = typeof(T).GetProperties().Where(p => SystemTypes.Contains(p.PropertyType)); // Only get System types

  return properties.Select(p => p.Name).ToArray();
}

So if say I have this class

class MyClass {
  public string Name { get; set; }

  [Description("The value")]
  public int Value { get; set; }
}

I can have code like this

List<MyClass> items = ...; // Populate items somehow
string[] fieldNames = GetFieldNames(items); // This returns ["Name", "Value"]

That works fine.

The problem

I need to get the Description (if it exists), so that GetFieldNames(items) returns ["Name", "The value"]

How do I modify the GetFieldNames() function to read the Description attribute if it exists?

(Please note that this function has been simplified, the real function is much more complex, so please avoid changing the logic)

Body:
I am using Description attribute a lot so I wrote Nuget for this purpose.

With it you could just call:

typeof(TestClass).GetPropertyDescription("PropertyName");

It also allows to take DescriptionAttribute from class, field, enum and method.


问:
How to remove public from url in laravel
I want ro remove public word from the url in laravel. I tried updating .htaccess and renaming server.php to index.php file but after that I got path error. All the css, js, fonts are not working without public word in the url. Please help me so that I can set all the path of css, js, fonts and remove public word from url in laravel. Any help would be appreciable.

答:
Move your all files from /public to your root folder / (which is mainly your laravel folder).

Now open index.php file and edit 2 lines, as below :

```<code>require __DIR__.'/../vendor/autoload.php';
// changed to
require __DIR__.'/vendor/autoload.php';
</code>```

&

```<code>$app = require_once __DIR__.'/../bootstrap/app.php';
// changed to
$app = require_once __DIR__.'/bootstrap/app.php';
</code>```

Now add this lines to your .htaccess to prevent access .env from URL :

```<code><Files .env>
order allow,deny
Deny from all
</Files>
</code>```

By this method you can host your laravel app in any kind of shared hosting too.

Hope this helps.

Body:
Move your all files from /public to your root folder / (which is mainly your laravel folder).

Now open index.php file and edit 2 lines, as below :

require __DIR__.'/../vendor/autoload.php';
// changed to
require __DIR__.'/vendor/autoload.php';

&

$app = require_once __DIR__.'/../bootstrap/app.php';
// changed to
$app = require_once __DIR__.'/bootstrap/app.php';

Now add this lines to your .htaccess to prevent access .env from URL :

<Files .env>
order allow,deny
Deny from all
</Files>

By this method you can host your laravel app in any kind of shared hosting too.

Hope this helps.


问:
Sorted a javascript array of objects by an object property
Hay, i have an array of objects and i need to sort them (either DESC or ASC) by a certain property of each object.

Here's the data

```<code>obj1 = new Object;
obj1.date = 1307010000;

obj2 = new Object;
obj2.date = 1306923600;

obj3 = new Object;
obj3.date = 1298974800;

obj4 = new Object;
obj4.date = 1306923600;

obj5 = new Object;
obj5.date = 1307096400;

data = [obj1,obj2,obj3,obj4,obj5];
</code>```

Now, i want to order the data array so that the objects are in order by date.

Can someone help me with this?

答:
This solution works with any type of data:

```<code>sort_array_by = function(field, reverse, pr){
  reverse = (reverse) ? -1 : 1;
  return function(a,b){
    a = a[field];
    b = b[field];
    if (typeof(pr) != 'undefined'){
      a = pr(a);
      b = pr(b);
    }
    if (a<b) return reverse * -1;
    if (a>b) return reverse * 1;
    return 0;
  }
}
</code>```

Then, use it like this (reverse sort):

```<code>data.sort(sort_array_by('date', true, function(a){
   return new Date(a);
}));
</code>```

As another example, you can sort it by a property of type "integer":

```<code>data.sort(sort_array_by('my_int_property', true, function(a){
   return parseInt(a);
}));
</code>```

Body:
Hay, i have an array of objects and i need to sort them (either DESC or ASC) by a certain property of each object.

Here's the data

obj1 = new Object;
obj1.date = 1307010000;

obj2 = new Object;
obj2.date = 1306923600;

obj3 = new Object;
obj3.date = 1298974800;

obj4 = new Object;
obj4.date = 1306923600;

obj5 = new Object;
obj5.date = 1307096400;

data = [obj1,obj2,obj3,obj4,obj5];

Now, i want to order the data array so that the objects are in order by date.

Can someone help me with this?

Body:
This solution works with any type of data:

sort_array_by = function(field, reverse, pr){
  reverse = (reverse) ? -1 : 1;
  return function(a,b){
    a = a[field];
    b = b[field];
    if (typeof(pr) != 'undefined'){
      a = pr(a);
      b = pr(b);
    }
    if (a<b) return reverse * -1;
    if (a>b) return reverse * 1;
    return 0;
  }
}

Then, use it like this (reverse sort):

data.sort(sort_array_by('date', true, function(a){
   return new Date(a);
}));

As another example, you can sort it by a property of type "integer":

data.sort(sort_array_by('my_int_property', true, function(a){
   return parseInt(a);
}));


问:
Python data output to Excel
While spending hours attempting to figure out ways to import stats to an Excel file I came across a version of this script that I've attempted to use in Python. When executing I get the following error below the second csv_output portion of the script:

KeyError: 0

I'm just beginning to learn the nuances of Python and can't really figure out what I'm doing wrong here.

I'm currently using Python 3.6 and Windows 10. Any help would be greatly appreciated.

```<code>import requests
import csv

url = "http://stats.nba.com/stats/leagueLeaders?
LeagueID=00&PerMode=PerGame&Scope=S&Season=2017-
18&SeasonType=Regular+Season&StatCategory=PTS"

data = requests.get(url, timeout=5)
entries = data.json()

with open('output.csv', 'w') as f_output:
    csv_output = csv.writer(f_output)
    csv_output.writerow(entries['resultSet'][0]['headers'])
    csv_output.writerows(entries['resultSet'][0]['rowSet'])
</code>```

答:
This solution worked for me:</p>

```<code>  import pandas as pd
    data = requests.get(url, timeout=5)
    entries = data.json()
    Header=entries['resultSet']['headers']
    data =entries['resultSet']['rowSet']
    filename='c:\\test\\NBA.xlsx'

    df = pd.DataFrame.from_records(data)
    df.columns=Header
    writer = pd.ExcelWriter(filename, engine='xlsxwriter')
    df.to_excel(writer, sheet_name='sheet1', index=False,startrow=0 , startcol=0)
    writer.save()
</code>```

Title: Python data output to Excel

Body:
While spending hours attempting to figure out ways to import stats to an Excel file I came across a version of this script that I've attempted to use in Python. When executing I get the following error below the second csv_output portion of the script:

KeyError: 0

I'm just beginning to learn the nuances of Python and can't really figure out what I'm doing wrong here.

I'm currently using Python 3.6 and Windows 10. Any help would be greatly appreciated.

import requests
import csv

url = "http://stats.nba.com/stats/leagueLeaders?
LeagueID=00&PerMode=PerGame&Scope=S&Season=2017-
18&SeasonType=Regular+Season&StatCategory=PTS"

data = requests.get(url, timeout=5)
entries = data.json()

with open('output.csv', 'w') as f_output:
    csv_output = csv.writer(f_output)
    csv_output.writerow(entries['resultSet'][0]['headers'])
    csv_output.writerows(entries['resultSet'][0]['rowSet'])

Body:
This solution worked for me:

  import pandas as pd
    data = requests.get(url, timeout=5)
    entries = data.json()
    Header=entries['resultSet']['headers']
    data =entries['resultSet']['rowSet']
    filename='c:\\test\\NBA.xlsx'

    df = pd.DataFrame.from_records(data)
    df.columns=Header
    writer = pd.ExcelWriter(filename, engine='xlsxwriter')
    df.to_excel(writer, sheet_name='sheet1', index=False,startrow=0 , startcol=0)
    writer.save()


问:
How to upload file using multer or body-parser
I am a NodeJS beginner, following along a book "Web Development with MongoDB and NodeJS". I am stuck at its chapter 6 with 'multer'. When I use multer for file uploads the server throws the following error:

```<code>/Users/fk / Documents / imageuploader / node_modules / express / lib / application.js: 209
throw new TypeError('app.use() requires middleware functions'); ^

TypeError: app.use() requires middleware functions
</code>```

but when I replace it with bodyParser the server fires up but when I click the upload button it gives me the following error on the browser.

```<code>500 TypeError: Cannot read property 'file' of undefined
</code>```

However, it is supposed to redirect me towards another page, where the uploaded file is shown.

Here is my bodyParser code, please see if I am using it correctly because it gives me "body-parser deprecated" at the starting of the server. I've seen other questions like mine and I followed but none of them really work.

```<code>app.use(bodyParser.json());
app.use(bodyParser.urlencoded({
  extended: true
}));

app.use(bodyParser({
  uploadDir: path.join(__dirname, '../public/upload/temp')
}));
</code>```

Following code shows how I use multer, just in case if there is something I shouldn't be doing please let me know. Which one would be better in case of uploading files, body-parser or multer?

```<code>app.use(multer({
  dest: path.join(__dirname, '../public/upload/temp')
}));

var saveImage = function() {
  var possible = 'abcdefghijklmnopqrstuvwxyz0123456789',
    imgUrl = '';

  for (var i = 0; i < 6; i += 1) {
    imgUrl += possible.charAt(Math.floor(Math.random() * possible.length));
  }

  var tempPath = req.files.file.path,
    ext = path.extname(req.files.file.name).toLowerCase(),
    targetPath = path.resolve('./public/upload/' + imgUrl + ext);

  if (ext === '.png' || ext === '.jpg' || ext === '.jpeg' || ext === '.gif') {
    fs.rename(tempPath, targetPath, function(err) {
      if (err) throw err;
      res.redirect('/images/' + imgUrl);
    });
  } else {
    fs.unlink(tempPath, function() {
      if (err) throw err;

      res.json(500, {
        error: 'Only image files are allowed.'
      });
    });
  }
};
saveImage();
</code>```

Preceding block of code is the logic that I am using to upload the file. In the error it is referring to 'file' as undefined which is in the following line in the saveImage function. It is unable to get the path and therefore throws error 500 according to the else part of the saveImage function. Why is 'file' undefined here? I dont get it.

```<code>var tempPath = req.files.file.path,
</code>```

答:
I corrected the code of the book "Web Development with MongoDB and NodeJS" as follows:

```<code>app.use(multer({dest:path.join(__dirname,'../public/upload/temp')}).any());
.
.
.
.
const tempPath = req.files[0].path,  // Temporary location of uploaded file
ext = path.extname(req.files[0].originalname).toLowerCase(), // Get file extension of the uploaded file
targetPath = path.resolve(`./public/upload/${imgUrl}${ ext}`); // The final path for the image file

</code>```

The other parts of code remained intact. It worked and I could upload image files.
Best wishes,
Mehrdad Sheikhan

Body:
I am a NodeJS beginner, following along a book "Web Development with MongoDB and NodeJS". I am stuck at its chapter 6 with 'multer'. When I use multer for file uploads the server throws the following error:

/Users/fk / Documents / imageuploader / node_modules / express / lib / application.js: 209
throw new TypeError('app.use() requires middleware functions'); ^

TypeError: app.use() requires middleware functions

but when I replace it with bodyParser the server fires up but when I click the upload button it gives me the following error on the browser.

500 TypeError: Cannot read property 'file' of undefined

However, it is supposed to redirect me towards another page, where the uploaded file is shown.

Here is my bodyParser code, please see if I am using it correctly because it gives me "body-parser deprecated" at the starting of the server. I've seen other questions like mine and I followed but none of them really work.

app.use(bodyParser.json());
app.use(bodyParser.urlencoded({
  extended: true
}));

app.use(bodyParser({
  uploadDir: path.join(__dirname, '../public/upload/temp')
}));

Following code shows how I use multer, just in case if there is something I shouldn't be doing please let me know. Which one would be better in case of uploading files, body-parser or multer?

app.use(multer({
  dest: path.join(__dirname, '../public/upload/temp')
}));

var saveImage = function() {
  var possible = 'abcdefghijklmnopqrstuvwxyz0123456789',
    imgUrl = '';

  for (var i = 0; i < 6; i += 1) {
    imgUrl += possible.charAt(Math.floor(Math.random() * possible.length));
  }

  var tempPath = req.files.file.path,
    ext = path.extname(req.files.file.name).toLowerCase(),
    targetPath = path.resolve('./public/upload/' + imgUrl + ext);

  if (ext === '.png' || ext === '.jpg' || ext === '.jpeg' || ext === '.gif') {
    fs.rename(tempPath, targetPath, function(err) {
      if (err) throw err;
      res.redirect('/images/' + imgUrl);
    });
  } else {
    fs.unlink(tempPath, function() {
      if (err) throw err;

      res.json(500, {
        error: 'Only image files are allowed.'
      });
    });
  }
};
saveImage();

Preceding block of code is the logic that I am using to upload the file. In the error it is referring to 'file' as undefined which is in the following line in the saveImage function. It is unable to get the path and therefore throws error 500 according to the else part of the saveImage function. Why is 'file' undefined here? I dont get it.

var tempPath = req.files.file.path,

Body:
I corrected the code of the book "Web Development with MongoDB and NodeJS" as follows:

app.use(multer({dest:path.join(__dirname,'../public/upload/temp')}).any());
.
.
.
.
const tempPath = req.files[0].path,  // Temporary location of uploaded file
ext = path.extname(req.files[0].originalname).toLowerCase(), // Get file extension of the uploaded file
targetPath = path.resolve(`./public/upload/${imgUrl}${ ext}`); // The final path for the image file

The other parts of code remained intact. It worked and I could upload image files.
Best wishes,
Mehrdad Sheikhan


问:
RANK query using PARTITION BY fails in mysql
I tried below query to partition by but which fails with below query, the inner query works

```<code>select  issueid, task_type, assignee, timeoriginalestimate, CREATED,
dense_rank() over ( partition by issueid order by CREATED desc ) as rank
       from(
       --- Complex query with p.pname, i.issuenum, cg.issueid, it.pname task_type, i.assignee, i.timeoriginalestimate, cg.CREATED, columns which works fine
       )
</code>```

Exception:
You have an error in your SQL syntax; check the manual that corresponds to your MySQL server version for the right syntax to use near '( partition by issueid order by CREATED desc ) as rank
       from(
SELECT p.pna' at line 3

Update:

```<code>SELECT VERSION(); -- 5.6.27
</code>```

答:
Although your MySQL version do not support Window function, I am letting this is not the issue. Guess you have a higher version and window function is supported.

Now, in your query you have defined the Alias of a column name to "Rank" which is a reserved keyword for your database and you can not use that as column name.

Hope this below hints will help you-

```<code>select
issueid,
task_type,
assignee,
timeoriginalestimate,
CREATED,
dense_rank() over ( partition by issueid order by CREATED desc ) as rn -- change the alias name
from(
   -- Your subquery
) A -- Also need to give a Alias name to your sub query
</code>```

Finally, if you have lower version check this LINK for help to get an idea of creating Row_number or Ranking for MySQL older versions.

In addition, this following sample query will really help you finding solution for different type row_number in mysql-

```<code>SET @simple_row_number := 0;
SET @id_wise_row_number := 0;
SET @dense_rank_per_id := 0;
SET @prev := 0;

SELECT *,

@simple_row_number := @simple_row_number + 1 AS simple_row_number,
@id_wise_row_number := IF(issueid > @prev, @id_wise_row_number + 1, @id_wise_row_number) AS id_wise_row_number,
@dense_rank_per_id :=IF(issueid > @prev,1, @dense_rank_per_id + 1) AS dense_rank_per_id,

@prev := A.issueid Prev_IssueId

FROM (
    SELECT 1 issueid, '20200601' CREATED UNION ALL
    SELECT 1 issueid, '20200401' CREATED UNION ALL
    SELECT 1 issueid, '20200501' CREATED UNION ALL
    SELECT 1 issueid, '20200201' CREATED UNION ALL
    SELECT 1 issueid, '20200301' CREATED UNION ALL
    SELECT 2 issueid, '20200301' CREATED UNION ALL
    SELECT 2 issueid, '20200201' CREATED UNION ALL
    SELECT 2 issueid, '20200401' CREATED
) A
ORDER BY issueid, CREATED DESC
</code>```

Body:
I tried below query to partition by but which fails with below query, the inner query works

select  issueid, task_type, assignee, timeoriginalestimate, CREATED,
dense_rank() over ( partition by issueid order by CREATED desc ) as rank
       from(
       --- Complex query with p.pname, i.issuenum, cg.issueid, it.pname task_type, i.assignee, i.timeoriginalestimate, cg.CREATED, columns which works fine
       )

Exception:
You have an error in your SQL syntax; check the manual that corresponds to your MySQL server version for the right syntax to use near '( partition by issueid order by CREATED desc ) as rank
       from(
SELECT p.pna' at line 3

Update:

SELECT VERSION(); -- 5.6.27

Body:
Although your MySQL version do not support Window function, I am letting this is not the issue. Guess you have a higher version and window function is supported.

Now, in your query you have defined the Alias of a column name to "Rank" which is a reserved keyword for your database and you can not use that as column name.

Hope this below hints will help you-

select
issueid,
task_type,
assignee,
timeoriginalestimate,
CREATED,
dense_rank() over ( partition by issueid order by CREATED desc ) as rn -- change the alias name
from(
   -- Your subquery
) A -- Also need to give a Alias name to your sub query

Finally, if you have lower version check this LINK for help to get an idea of creating Row_number or Ranking for MySQL older versions.

In addition, this following sample query will really help you finding solution for different type row_number in mysql-

SET @simple_row_number := 0;
SET @id_wise_row_number := 0;
SET @dense_rank_per_id := 0;
SET @prev := 0;

SELECT *,

@simple_row_number := @simple_row_number + 1 AS simple_row_number,
@id_wise_row_number := IF(issueid > @prev, @id_wise_row_number + 1, @id_wise_row_number) AS id_wise_row_number,
@dense_rank_per_id :=IF(issueid > @prev,1, @dense_rank_per_id + 1) AS dense_rank_per_id,

@prev := A.issueid Prev_IssueId

FROM (
    SELECT 1 issueid, '20200601' CREATED UNION ALL
    SELECT 1 issueid, '20200401' CREATED UNION ALL
    SELECT 1 issueid, '20200501' CREATED UNION ALL
    SELECT 1 issueid, '20200201' CREATED UNION ALL
    SELECT 1 issueid, '20200301' CREATED UNION ALL
    SELECT 2 issueid, '20200301' CREATED UNION ALL
    SELECT 2 issueid, '20200201' CREATED UNION ALL
    SELECT 2 issueid, '20200401' CREATED
) A
ORDER BY issueid, CREATED DESC


问:
How to add time zone to specific format in momentjs?
I am trying to get specific format of datetime with time zone

i am getting string of time format which is shown below

```<code>var dateTime = "2020-06-01T01:50:57.000Z CDT"
</code>```

I need to convert the format in to

```<code> const offsetTime = moment(date).add("-0.00", 'hours')
 const formatedDate = moment(offsetTime, 'h:mm:ss A')
.utc()
.format('h:mm A')//(1:50 AM)
</code>```

Required output

```<code>(1:50 AM CDT)
</code>```

Do i need to split the string and get the format or do we have any method to convert it to this format in momentjs

In simple way to say

```<code>YYYY-MM-DDTHH:mm:ss.SSS[Z] z To hh:mm A z //format
</code>```

and if the string contains only 2 character like "CT" instead of CDT how to capture that.

答:
You can zz to get timezone in output. For ex:
moment()..format('h:mm A zz')

More documentation here momentJS

Body:
I am trying to get specific format of datetime with time zone

i am getting string of time format which is shown below

var dateTime = "2020-06-01T01:50:57.000Z CDT"

I need to convert the format in to

 const offsetTime = moment(date).add("-0.00", 'hours')
 const formatedDate = moment(offsetTime, 'h:mm:ss A')
.utc()
.format('h:mm A')//(1:50 AM)

Required output

(1:50 AM CDT)

Do i need to split the string and get the format or do we have any method to convert it to this format in momentjs

In simple way to say

YYYY-MM-DDTHH:mm:ss.SSS[Z] z To hh:mm A z //format

and if the string contains only 2 character like "CT" instead of CDT how to capture that.


问:
Enforcing Blazor webassembly to use Newtonsoft.Json on client side
In Blazor webassembly is there a way to enforce the use of Newtonsoft.Json serlialization for httpclient and methods such as GetJsonAsync, PostAsJsonAsync etc.

Or the only way is to write helper methods and use GetAsync and then serialize the response manually using Newtonsoft.Json?

答:
is there a way to enforce the use of Newtonsoft.Json  for ... PostAsJsonAsync etc.

No. This has been shifting around a bit lately, especially for Blazor. But the System.Net.Http.Json.HttpClientJsonExtensions are now directly dependent on System.Text.Json, not pluggable.

So yes, you will have to write your own helpers, not too big a deal. The linker might even remove the System.Text.Json classes in a Release build, I'm not sure.

But the counter question is of course why you need this?  NewtonSoft is legacy from now on and if you really have incompatible data maybe ask if you can resolve this with some System.Text options.


问:
How i save the opened levels in my android app
I have a quiz game that i coded by java (using android studio).
My question is how i save the levels that the user opened , when the user closes the app, nothing is saved and the user has to start playing the game from level 1 again , i tried to use SharedPreferences but it doesn't work,cause i have many categories in my app and each one has many levels ,so even when SharedPreferences  work it will not help cause it will save the level of all the categories what the user doesn't open it

edit:sorry I forget to say I using realtime database (firebase) in my app&is there are way exepet room database

```<code>public class SetsActivity extends AppCompatActivity {

private GridView gridView;
private AppCompatDialog loadingDialoge;
private sets_adapter adapter;
private AdView mAdView;
private  int l,sets,level;
private String title;

@Override
protected void onCreate(Bundle savedInstanceState) {
    super.onCreate(savedInstanceState);
    setContentView(R.layout.activity_sets);

    Toolbar toolbar=findViewById(R.id.sets_toolbar);
    gridView=findViewById(R.id.sets_gv);

    setSupportActionBar(toolbar);
    getSupportActionBar().setDisplayHomeAsUpEnabled(true);
    getSupportActionBar().setTitle(title);

    l=getIntent().getIntExtra("lvl",0);
    title=getIntent().getStringExtra("title");
    sets=getIntent().getIntExtra("sets",0);

    loadlvl();

    adapter=new sets_adapter(sets,title,level);

    gridView.setAdapter(adapter);

}

//on back item click
@Override
public boolean onOptionsItemSelected(@NonNull MenuItem item) {
    if (item.getItemId()==android.R.id.home)
        finish();
    return super.onOptionsItemSelected(item);
}

@Override
protected void onPause() {
    savelevel();
    super.onPause();
    finish();
}

private void savelevel(){
    SharedPreferences savechange = this.getPreferences(Context.MODE_PRIVATE);
    SharedPreferences.Editor editor = savechange.edit();
    editor.putInt("lvl",l);
    editor.commit();
}

private void loadlvl(){
    SharedPreferences savechange = this.getPreferences( Context.MODE_PRIVATE);
    level=savechange.getInt("lvl",-1);

}
</code>```

}

答:
You can save data to your local database using Room. It is easy to use.

Check documentations here: https://developer.android.com/training/data-storage/room

Body:
I have a quiz game that i coded by java (using android studio).
My question is how i save the levels that the user opened , when the user closes the app, nothing is saved and the user has to start playing the game from level 1 again , i tried to use SharedPreferences but it doesn't work,cause i have many categories in my app and each one has many levels ,so even when SharedPreferences  work it will not help cause it will save the level of all the categories what the user doesn't open it

edit:sorry I forget to say I using realtime database (firebase) in my app&is there are way exepet room database

public class SetsActivity extends AppCompatActivity {

private GridView gridView;
private AppCompatDialog loadingDialoge;
private sets_adapter adapter;
private AdView mAdView;
private  int l,sets,level;
private String title;

@Override
protected void onCreate(Bundle savedInstanceState) {
    super.onCreate(savedInstanceState);
    setContentView(R.layout.activity_sets);

    Toolbar toolbar=findViewById(R.id.sets_toolbar);
    gridView=findViewById(R.id.sets_gv);

    setSupportActionBar(toolbar);
    getSupportActionBar().setDisplayHomeAsUpEnabled(true);
    getSupportActionBar().setTitle(title);

    l=getIntent().getIntExtra("lvl",0);
    title=getIntent().getStringExtra("title");
    sets=getIntent().getIntExtra("sets",0);

    loadlvl();

    adapter=new sets_adapter(sets,title,level);

    gridView.setAdapter(adapter);

}

//on back item click
@Override
public boolean onOptionsItemSelected(@NonNull MenuItem item) {
    if (item.getItemId()==android.R.id.home)
        finish();
    return super.onOptionsItemSelected(item);
}

@Override
protected void onPause() {
    savelevel();
    super.onPause();
    finish();
}

private void savelevel(){
    SharedPreferences savechange = this.getPreferences(Context.MODE_PRIVATE);
    SharedPreferences.Editor editor = savechange.edit();
    editor.putInt("lvl",l);
    editor.commit();
}

private void loadlvl(){
    SharedPreferences savechange = this.getPreferences( Context.MODE_PRIVATE);
    level=savechange.getInt("lvl",-1);

}

}


问:
Big and small gaps using circlize in R
How do I group categories so that they appear with big gaps in a chord diagram generated using the circlize package in R?

For example, given the following adjacency matrix:

```<code>  A B    C   D  E F    G   H
A 0 0    0   0  0 0 1168   0
B 0 0 2545 278  0 0    0 337
C 0 0    0 817  0 0    0   0
D 0 0    0   0 10 0    0   0
E 0 0    0   0  0 0    0   0
F 0 0    0   0  0 0    0   0
G 0 0  561 326  0 0    0 281
H 0 0   46   8  0 0    0   0
</code>```

I would like to create the three groups {A}, {B,C}, and {D,E,F,G,H}, so that when using chordDiagram() its parameter small.gap is used between segments within a group and big.gap is used between groups.

Note that this is code that will be run daily in production, and I cannot guarantee that movements always will occur between all categories. In the example above, no movements occur from or to the category F, resulting in it being omitted from the output. Using gap.after I hard-coded the desired result (see image), but this is not a feasible solution since I do not know which categories will be drawn or not. I would also prefer that a solution is not dependent on the ordering of the columns and rows in the matrix.

答:
In the upcoming version 0.4.10, circlize will support a named vector as input for gap.after. It is already in the master branch, so after pulling it in R it is possible to programmatically produce the correct gaps.

```<code>library(devtools)
install_github("jokergoo/circlize")
library(circlize) # chord diagrams

mat = read.table(textConnection("
  A B    C   D  E F    G   H
A 0 0    0   0  0 0 1168   0
B 0 0 2545 278  0 0    0 337
C 0 0    0 817  0 0    0   0
D 0 0    0   0 10 0    0   0
E 0 0    0   0  0 0    0   0
F 0 0    0   0  0 0    0   0
G 0 0  561 326  0 0    0 281
H 0 0   46   8  0 0    0   0"))
mat = as.matrix(mat)

big_gap = 10
small_gap = 2

# For example three groups x,y,z
sector_grouping = cbind.data.frame(
  "Sec" = c("A","B","C","D","E","F","G","H"),
  "Grp" = c("x","y","y","z","z","z","z","z")
)
# Check which, if any, groups lack both outgoing and incoming
empty_row = rowSums(mat)[sector_grouping$Sec] == 0
empty_column = colSums(mat)[sector_grouping$Sec] == 0
# Remove empty sectors
sector_grouping = sector_grouping[!(empty_row & empty_column),]
# Iterate and set a big gap (last sector in group) or small gap.
for(i in 1:nrow(sector_grouping)) {
  sector_grouping[i,"Gap"] = ifelse(
    sector_grouping[i,2]==sector_grouping[i+1,2],
    small_gap,
    big_gap
  )
}
# The last sector needs fixing (always assumed big)
sector_grouping$Gap[is.na(sector_grouping$Gap)] = big_gap
# Build named vector
gap.after = sector_grouping$Gap
names(gap.after) = sector_grouping$Sec

circos.par(gap.after = gap.after)
chordDiagram(mat, order = LETTERS[1:8])
circos.clear()
</code>```

I'd like to thank the author @Zuguang Gu of circlize for the prompt help after I reached out to him.

Title: Big and small gaps using circlize in R

Body:
How do I group categories so that they appear with big gaps in a chord diagram generated using the circlize package in R?

For example, given the following adjacency matrix:

  A B    C   D  E F    G   H
A 0 0    0   0  0 0 1168   0
B 0 0 2545 278  0 0    0 337
C 0 0    0 817  0 0    0   0
D 0 0    0   0 10 0    0   0
E 0 0    0   0  0 0    0   0
F 0 0    0   0  0 0    0   0
G 0 0  561 326  0 0    0 281
H 0 0   46   8  0 0    0   0

I would like to create the three groups {A}, {B,C}, and {D,E,F,G,H}, so that when using chordDiagram() its parameter small.gap is used between segments within a group and big.gap is used between groups.

Note that this is code that will be run daily in production, and I cannot guarantee that movements always will occur between all categories. In the example above, no movements occur from or to the category F, resulting in it being omitted from the output. Using gap.after I hard-coded the desired result (see image), but this is not a feasible solution since I do not know which categories will be drawn or not. I would also prefer that a solution is not dependent on the ordering of the columns and rows in the matrix.

Body:
In the upcoming version 0.4.10, circlize will support a named vector as input for gap.after. It is already in the master branch, so after pulling it in R it is possible to programmatically produce the correct gaps.

library(devtools)
install_github("jokergoo/circlize")
library(circlize) # chord diagrams

mat = read.table(textConnection("
  A B    C   D  E F    G   H
A 0 0    0   0  0 0 1168   0
B 0 0 2545 278  0 0    0 337
C 0 0    0 817  0 0    0   0
D 0 0    0   0 10 0    0   0
E 0 0    0   0  0 0    0   0
F 0 0    0   0  0 0    0   0
G 0 0  561 326  0 0    0 281
H 0 0   46   8  0 0    0   0"))
mat = as.matrix(mat)

big_gap = 10
small_gap = 2

# For example three groups x,y,z
sector_grouping = cbind.data.frame(
  "Sec" = c("A","B","C","D","E","F","G","H"),
  "Grp" = c("x","y","y","z","z","z","z","z")
)
# Check which, if any, groups lack both outgoing and incoming
empty_row = rowSums(mat)[sector_grouping$Sec] == 0
empty_column = colSums(mat)[sector_grouping$Sec] == 0
# Remove empty sectors
sector_grouping = sector_grouping[!(empty_row & empty_column),]
# Iterate and set a big gap (last sector in group) or small gap.
for(i in 1:nrow(sector_grouping)) {
  sector_grouping[i,"Gap"] = ifelse(
    sector_grouping[i,2]==sector_grouping[i+1,2],
    small_gap,
    big_gap
  )
}
# The last sector needs fixing (always assumed big)
sector_grouping$Gap[is.na(sector_grouping$Gap)] = big_gap
# Build named vector
gap.after = sector_grouping$Gap
names(gap.after) = sector_grouping$Sec

circos.par(gap.after = gap.after)
chordDiagram(mat, order = LETTERS[1:8])
circos.clear()

I'd like to thank the author @Zuguang Gu of circlize for the prompt help after I reached out to him.


问:
How to limit width of multiple TextFields inside a Column? Wrapping the latter with a SizedBox doesn't work
This is my tree:

Scaffold(-> Column(-> Expanded(-> ListView(-> Column(-> TextFields)))));

I want to limit the width of these TextFields (say, to 200px), but using SizedBox/Container/ConstrainedBox and setting a width/maxWidth on the Column isn't working; I have to wrap each individual TextField with a SizedBox for it to work- which adds a lot of fluff to my code.

Is there a better way to do this?

答:
I found the answer while watching https://www.youtube.com/watch?v=XcnP3_mO_Ms.

"If you put AspectRatio into something like Expanded, then that will
  be forced by its parent to expand. Tightly fitted widgets like
  Expanded don't give their children a choice-- harsh. If this happens
  to you, just put something like Align between the Expanded and the
  AspectRatio.

Align will be forced by Expanded to fill the area, but it will let its
  child assume its own proportions. Thanks, Align!"

I have to wrap my Column in a Container, and then wrap the Container in an Align to break free of Expanded.


问:
GitHub Remote Error - Large File
I cannot push new changes to my remote GitHub repository because my IOS Swift project uses the opencv framework, which is 150 MB large. I get the following error message:

```<code>remote: error: GH001: Large files detected.
You may want to try Git Large File Storage - https://git-lfs.github.com.
remote: error: Trace: ......aa11d45...12994...
remote: error: See http://git.io/iEPt8g for more information.
remote: error: File Pods/OpenCV/opencv2.framework/Versions/A/opencv2 is 150.06 MB; this exceeds GitHub's file size limit of 100.00 MB
 ! [remote rejected] master -> master (pre-receive hook declined)
</code>```

I have try the Large File Storage, by running the following command line commands:

```<code>git lfs track "Pods/OpenCV/opencv2.framework/Versions/A/opencv2"
git add .gitattributes
</code>```

but I still get the same error message.

How can I push changes to GitHub when I have a large framework file like opencv2.

答:
There could be two reasons,

You missed the run git install lfs in repository directory.
Please follow commands like

git install lfs

git lfs track "Pods/OpenCV/opencv2.framework/Versions/A/opencv2"

git add .gitattributes

There could be previous commits that have a large file without lfs track, so you might need to reset your repository, I recommend to clone repo in another directory then,

Install the lfs (git install lfs),

Copy the large file in repo directory,

Let lfs track the files

then, commit and push.

Title: GitHub Remote Error - Large File

Body:
I cannot push new changes to my remote GitHub repository because my IOS Swift project uses the opencv framework, which is 150 MB large. I get the following error message:

remote: error: GH001: Large files detected.
You may want to try Git Large File Storage - https://git-lfs.github.com.
remote: error: Trace: ......aa11d45...12994...
remote: error: See http://git.io/iEPt8g for more information.
remote: error: File Pods/OpenCV/opencv2.framework/Versions/A/opencv2 is 150.06 MB; this exceeds GitHub's file size limit of 100.00 MB
 ! [remote rejected] master -> master (pre-receive hook declined)

I have try the Large File Storage, by running the following command line commands:

git lfs track "Pods/OpenCV/opencv2.framework/Versions/A/opencv2"
git add .gitattributes

but I still get the same error message.

How can I push changes to GitHub when I have a large framework file like opencv2.


问:
How to get the focus on a textbox on a key press
We have a page which requires user to enter some input and post submission (e.g. by hitting Enter key or Submit button). The answer is shown to the end user and we provide a link which says 'Press any key to continue'.

The focus on the input box is automatically shown, either after pressing any key or by clicking on the link. Can someone provide some sample code to do this?

答:
```<code>$("a").mousedown(function(){
    alert('keypressed');
});

$.keypress(function(){
    alert('keypressed');
});
</code>```


问:
how to stop consuming messages from kafka when error occurred and restart consuming again after some time in spring boot
This is the first time i am using Kafka. i have a spring boot application and i am consuming messages from kafka topics and storing messages in DB. I have a requirement to handle DB fail over, if DB is down that message should not be committed and suspend consuming messages for some time and after some time listener can start consuming messages again. what is the better approach to do this.</p>

```<code> i am using spring-kafka:2.2.8.RELEASE which is internally using kafka 2.0.1
</code>```

答:
There are two approaches which I can think of doing this:

First Approach: Let the auto-commit option for consuming messages be true. The configuration for this is enable.auto.commit. By default, this would be true, so you do not need to change anything. Whenever your DB operation fails, you can put the messages on a different topic say a topic named failed_events. When you do this, you can have the same application (Which populates the DB) running say once at a daily level to consume the message from failed_events topic and populate the DB again. This way you can keep track of how many times the DB write gets failed. One small thing to note is what if during this run also the DB is down, then what do you do. You can decide what to do in this case. Probably discard the message if it is Ok to do so, or do a certain number of retries.

Second approach: If it is very deterministic to know that for how long the DB would be down. And if the time period is very small, then it is better to do a sleep operation in the case of DB write failure. Say the application sleeps for 10 minutes before it retries again. You will not have to create a separate topic in this case.

The advantage of this approach is that you don't have to run a separate instance of the same application to fetch from a different topic. You could do all of them in one single application. Maintaining this becomes relatively easier.

The disadvantage of this approach is that if the DB is down for a very long period, say 1 day, Then you will end up losing the message.

Body:
This is the first time i am using Kafka. i have a spring boot application and i am consuming messages from kafka topics and storing messages in DB. I have a requirement to handle DB fail over, if DB is down that message should not be committed and suspend consuming messages for some time and after some time listener can start consuming messages again. what is the better approach to do this.

 i am using spring-kafka:2.2.8.RELEASE which is internally using kafka 2.0.1


问:
Is it possible to add a new TFS User Story to the top of the backlog via the REST api?
We have an integration that adds TFS 2018 user stories to a Team via rest api. Currently the newly created user story goes to the bottom of the backlog. Is there a way to have it get added to the top of the backlog?</p>

答:
Sorry, there is no such way to do this.

The sequence of items on each backlog is determined according to where you have added the items or moved the items on the page. As you drag and drop items within the backlog list, a background process updates the Stack Rank (Agile and CMMI processes) or Backlog Priority (Scrum process) fields. These fields are used by the system to track the relative ranking of items on the product, feature, epic, or other portfolio backlog.

The preferred method for bulk edit is to use multi-select to move
  items to the top, bottom, or specific position within the page. If you
  must perform a bulk edit of one of the backlog order fields to get a
  large number of work items in the priority order you want, use Excel.
  You can export a query containing the backlog items, update either the
  Backlog Priority or Stack Rank fields, and then publish your changes.

You could find this info in our official doc here. It's not able to do this via the Rest API.


问:
How To Integrate/Access Existing GCP Storage Bucket To Firebase Swift App Programmatically?
I create buckets on GCP Storage using the Node.js library. Later, I want to access these GCP Storage buckets from my Firebase iOS app. However, I can't. I receive the following error when trying to access my existing GCP buckets from my iOS app:

Your bucket has not been set up properly for Firebase Storage. Please visit https://console.firebase.google.com/project/MY_PROJECT/storage/files to automatically repair this issue and then retry. If the issue lasts longer than five minutes, you may have insufficient permissions to repair the project. You can check your permissions by visiting https://console.firebase.google.com/iam-admin/iam/project?project=MY_PROJECT."

It seems like I need to go to the Firebase Storage console and manually import existing Google Cloud Storage buckets to my Firebase project (as suggested here).

How can I import existing GCP Storage buckets to my iOS Firebase project programmatically? Or, is there a way to access existing GCP buckets and perform operations on them from my iOS app using Firebase Storage library?

Note: I'm on the Blaze plan. firebase-storage@system.gserviceaccount.com is added to my existing GCP buckets as Storage admin, just like it is for my default Firebase Storage bucket.

Here's a screenshot from Firebase console that explains the situation.

答:
Having encountered the same issue, I'm afraid there is no available programmatic solution right now.

Even if a bucket is created from the Admin SDK in a cloud function, it is not automatically attached to the Firebase project, which is required to apply some security rules and use it on the client side.

The attachment process itself looks like a black box. There is no IAM apparent change after the bucket selection and process validation in the Firebase console.

So, at this date, I would not recommend using custom buckets in Firebase projects for the following reasons:

It appears not possible to programmatically attach a custom bucket to a Firebase Project, the only working method being a manual addition via the web console

Regarding the very promising admin.securityRules() functions namespace, this is quite new (end of 2019) and the documentation lacks some thorough examples.


问:
switch character in line linux
This is file that I got

```<code> 1  CAGGAAAGACAATTCCAAAATCAGTTAGAGTCCTGTTGGCGCGTGTAATACATCTCCACTTTGAAAATGAAGACAGGGGGTTACGAGTGTTATTAATGAG
 2  TGGGAATGTAAATTAGTCCAGCCACTCTGGAGAACCGTATGGAGGTTCCTCCAAAAATTACAAATAGAACTACCATATGATCCAGCAATCCCATGCTATG
 3  AGATTTCCCTGAGAAAGTCATATTTAAGCTGCCATTTGAAGACCAAGGAATCATGACTAGAGACAAGAAGAGAGAACATAGAGTGATTATGGAGAATCTT
 4  AGTATCAGTCCAGTCCTCAGTGACGGGACCCTAACTGACCTGCCCTTCTTTGGCTTAGATTGCTTAAATGGTTCTGGATGTGATGATGGTGCACCTTGCC
 5  TATATTAGAGTAGAGTCTAAAGATTAGAATGATCCACAGGTTAATATGGGCCATTATAAAGAGATTAGTGATATTAACAATNTAGTATCAACATGGAGAT
 6  TCTATTATTTCATTGGGGTTGCAAAATTGTGATTTTCTAATCATTTCACTTTTCCTATATTTATTGCCTGGAACTTTGTAAAGAAGAAATTGATCTTATT
 7  TACCCTCAGGCTTATTAGGGTTGGAAACTCCACCCTGGGAAATTTGTGGTCAGACAGGTTTTCTGCTCTGGAACACTTTTTTCTGTTGTTTAAGATTTTT
 8  GCAAGAGAATCACTTGAACCCAGGAGGCAGAGGTTGCAGTGAGCCGGGATCGCGCCACTGCACTTCAGCCTGGGTGACAGTGTGAGACTCCATCTCAAAA
 9  TCACTGGTATTAAATCCCCAAATCAGAAATTTTGGACTGATTAAAAAAATGCACCAATCAAACAACAGAATTTCACACCAGATTTTGATAGTATACTTAT
10  GTAAACTACTTGTGAATATTTTTAATTAATGGCAATGTGGTTGCTTGCATACATTTAATAACAACATGTTTTATTTTATAANGGGCCATAACTGGAGGAA
11  TTCTTTTGAACTACTGAATCTCTGAGAACACTTAACAGGGTGAAGTTCAGTATTTACTTATTATTGTGAATCTGATAGCTGAAGTGATTTTTGTACAGCA
12  TCCCAAAGTGCTGGGATGACAGGCGTGAGCCACCGCGCCCGGCCCAAAGGAATTACTTTTAACTAAGAAACCTCCCACCCACCTCCTCCAGTTGCTATAT
13  CCGATCTTCAGGTTCTAAATTATGAAGTGGTTGATGGTCCTCAATAAGTGAACCATGAAATGCTTTCTTTACCTGGTGAAAATACATGGTGGTATAATAA
</code>```

Each character in file represent nucleotide sequence, and I'm trying to switch it in complement one, and change it in reversed direction.

which

```<code>G -> C , C->G , A->U, T -> A
</code>```

sample input & output will be

```<code>input
CAAATGGG

output
CCCAUUUG
</code>```

I tried

```<code> sed -i 's/C/G/g' file | sed -i 's/G/C/g' file | sed -i 's/A/U/g' file | sed -i 's/T/A/g' file
</code>```

but dind't worㅏ

答:
This might work for you (GNU sed):

```<code>sed -i 'y/GCAT/CGUA/;G;:a;s/(.)(\n.*)/\2\1/;ta;s/.//' file
</code>```

Translate the characters G,C,S and T to C,G,U and A.

Reverse the line by introducing a newline as a delimiter and adding the last character of the original line to the front of the new reversed line to be. When there are no further characters to add, remove the newline, voila!

Alternative:

```<code>sed -i 'y/GCAT/CGUA/;s/.*/echo "&"|rev/e' file
</code>```

Title: switch character in line linux

Body:
This is file that I got

 1  CAGGAAAGACAATTCCAAAATCAGTTAGAGTCCTGTTGGCGCGTGTAATACATCTCCACTTTGAAAATGAAGACAGGGGGTTACGAGTGTTATTAATGAG
 2  TGGGAATGTAAATTAGTCCAGCCACTCTGGAGAACCGTATGGAGGTTCCTCCAAAAATTACAAATAGAACTACCATATGATCCAGCAATCCCATGCTATG
 3  AGATTTCCCTGAGAAAGTCATATTTAAGCTGCCATTTGAAGACCAAGGAATCATGACTAGAGACAAGAAGAGAGAACATAGAGTGATTATGGAGAATCTT
 4  AGTATCAGTCCAGTCCTCAGTGACGGGACCCTAACTGACCTGCCCTTCTTTGGCTTAGATTGCTTAAATGGTTCTGGATGTGATGATGGTGCACCTTGCC
 5  TATATTAGAGTAGAGTCTAAAGATTAGAATGATCCACAGGTTAATATGGGCCATTATAAAGAGATTAGTGATATTAACAATNTAGTATCAACATGGAGAT
 6  TCTATTATTTCATTGGGGTTGCAAAATTGTGATTTTCTAATCATTTCACTTTTCCTATATTTATTGCCTGGAACTTTGTAAAGAAGAAATTGATCTTATT
 7  TACCCTCAGGCTTATTAGGGTTGGAAACTCCACCCTGGGAAATTTGTGGTCAGACAGGTTTTCTGCTCTGGAACACTTTTTTCTGTTGTTTAAGATTTTT
 8  GCAAGAGAATCACTTGAACCCAGGAGGCAGAGGTTGCAGTGAGCCGGGATCGCGCCACTGCACTTCAGCCTGGGTGACAGTGTGAGACTCCATCTCAAAA
 9  TCACTGGTATTAAATCCCCAAATCAGAAATTTTGGACTGATTAAAAAAATGCACCAATCAAACAACAGAATTTCACACCAGATTTTGATAGTATACTTAT
10  GTAAACTACTTGTGAATATTTTTAATTAATGGCAATGTGGTTGCTTGCATACATTTAATAACAACATGTTTTATTTTATAANGGGCCATAACTGGAGGAA
11  TTCTTTTGAACTACTGAATCTCTGAGAACACTTAACAGGGTGAAGTTCAGTATTTACTTATTATTGTGAATCTGATAGCTGAAGTGATTTTTGTACAGCA
12  TCCCAAAGTGCTGGGATGACAGGCGTGAGCCACCGCGCCCGGCCCAAAGGAATTACTTTTAACTAAGAAACCTCCCACCCACCTCCTCCAGTTGCTATAT
13  CCGATCTTCAGGTTCTAAATTATGAAGTGGTTGATGGTCCTCAATAAGTGAACCATGAAATGCTTTCTTTACCTGGTGAAAATACATGGTGGTATAATAA

Each character in file represent nucleotide sequence, and I'm trying to switch it in complement one, and change it in reversed direction.

which

G -> C , C->G , A->U, T -> A

sample input & output will be

input
CAAATGGG

output
CCCAUUUG

I tried

 sed -i 's/C/G/g' file | sed -i 's/G/C/g' file | sed -i 's/A/U/g' file | sed -i 's/T/A/g' file

but dind't worㅏ

Body:
This might work for you (GNU sed):

sed -i 'y/GCAT/CGUA/;G;:a;s/(.)(\n.*)/\2\1/;ta;s/.//' file

Translate the characters G,C,S and T to C,G,U and A.

Reverse the line by introducing a newline as a delimiter and adding the last character of the original line to the front of the new reversed line to be. When there are no further characters to add, remove the newline, voila!

Alternative:

sed -i 'y/GCAT/CGUA/;s/.*/echo "&"|rev/e' file


问:
socket send part down but receive part Up , possible?
I am wondering if it is possible to have a socket with send which doens't work (because buffer of peer is full maybe) while receive part still working ?

EDIT:

In case of a peer which doesn't perform a half close connection, and which it is too long to process its receive buffer (so its receive buffer is full), can I have an error only on my send part ?

答: Short answer: yes. If remote peer receives data at a slow rate (possibly due to slow data processing between recv calls) it will slow down transmission at a sending side: ACKs will be coming slowly and sending buffer will quickly get full which will cause your socket send operation to block or return error. On the other hand, as TCP is bidirectional protocol and TCP stack uses different kernel buffer for receiving data, local peer can still receive data sent from remote peer. </p>


问:
Invalid Callback Error when Setting Up Mocked Method using Moq
I have a class that I am testing.  This class has a dependency that I am mocking with the latest version of Moq.  The method I am mocking has the following signature.

```<code>IQueryable<T> Get<T>(
      Expression<Func<T, bool>> filter = null,
      Func<IQueryable<T>, IOrderedQueryable<T>> orderBy = null,
      string property = "")
      where T : BaseEntity;
</code>```

I mock this in this way

```<code>_repositoryMock
                .Setup(_ => _.Get(
                    It.IsAny<Expression<Func<X, bool>>>(),
                    It.IsAny<Func<IQueryable<X>, IOrderedQueryable<X>>>(),
                    It.IsAny<string>()))
                .Returns<X>(_ => Enumerable.Empty<X>().AsQueryable());
</code>```

When I run this test, I get the following error for this line.

```<code>System.ArgumentException: 'Invalid callback. Setup on method with 3 parameter(s) cannot invoke callback with different number of parameters (1).'
</code>```

What is going on here?

答:
Change the Returns statement to

```<code>.Returns(Enumerable.Empty<X>().AsQueryable());
</code>```

If you want to provide a delegate you've got to provide all of the parameters.

Body:
I have a class that I am testing.  This class has a dependency that I am mocking with the latest version of Moq.  The method I am mocking has the following signature.

IQueryable<T> Get<T>(
      Expression<Func<T, bool>> filter = null,
      Func<IQueryable<T>, IOrderedQueryable<T>> orderBy = null,
      string property = "")
      where T : BaseEntity;

I mock this in this way

_repositoryMock
                .Setup(_ => _.Get(
                    It.IsAny<Expression<Func<X, bool>>>(),
                    It.IsAny<Func<IQueryable<X>, IOrderedQueryable<X>>>(),
                    It.IsAny<string>()))
                .Returns<X>(_ => Enumerable.Empty<X>().AsQueryable());

When I run this test, I get the following error for this line.

System.ArgumentException: 'Invalid callback. Setup on method with 3 parameter(s) cannot invoke callback with different number of parameters (1).'

What is going on here?

Body:
Change the Returns statement to

.Returns(Enumerable.Empty<X>().AsQueryable());

If you want to provide a delegate you've got to provide all of the parameters.


问:
BST insert(root, value) recursive method
EDIT: I've figured it out - scrapped this design and started over and it worked! Thank you for your suggestions.

I'm working on a BST algorithm homework assignment and I'm hopelessly stuck on the insert method. All of the resources I've found online have a version similar to what I've created, but I am failing the JUnit test given to us by our professor. I can pass the base cases (null root and binary tree where the root.payload == value). I can't seem to pass the next test though. Here is my code for the insert(root, value) method:

public static Node<Integer> insert(Node<Integer> root, Integer value) {
    if (root == null) {
        root = new Node<>(value);
    } else if (root.payload.equals(value)) {
        return root;
    } else if (value < root.payload) {
        return root.left = insert(root.left, value);
    } else {
        return root.right = insert(root.right, value);
    }
    return root;
}
```

What ends up being returned is the original root node, but from my understanding, the returned value at the end should be my new node. I've looked at my textbook and some online resources and all of them have something very similar to this design, so I'm quite confused as to why it's not working. I've tried some other designs but all of them end up being a NullPointerException. The JUnit test that was given to us verifies that we inserted the node in the correct place, in addition to checking the Node's payload. I'm failing both of these tests. This is our first assignment using recursion, so I'm still fairly new at it. Any guidance would be greatly appreciated!

答:
```<code>public static Node<Integer> insert(Node<Integer> root, Integer value) {
    if (root == null) {
        root = new Node<>(value);
    } else if (value < root.payload) {
         root.left = insert(root.left, value);
    } else if (value > root.payload) {
         root.right = insert(root.right, value);
    }
    return root;
}
</code>```

This will add the value at its correct place and return the root. You can print the tree to check the same

Body:
EDIT: I've figured it out - scrapped this design and started over and it worked! Thank you for your suggestions.

I'm working on a BST algorithm homework assignment and I'm hopelessly stuck on the insert method. All of the resources I've found online have a version similar to what I've created, but I am failing the JUnit test given to us by our professor. I can pass the base cases (null root and binary tree where the root.payload == value). I can't seem to pass the next test though. Here is my code for the insert(root, value) method:

public static Node<Integer> insert(Node<Integer> root, Integer value) {
    if (root == null) {
        root = new Node<>(value);
    } else if (root.payload.equals(value)) {
        return root;
    } else if (value < root.payload) {
        return root.left = insert(root.left, value);
    } else {
        return root.right = insert(root.right, value);
    }
    return root;
}

What ends up being returned is the original root node, but from my understanding, the returned value at the end should be my new node. I've looked at my textbook and some online resources and all of them have something very similar to this design, so I'm quite confused as to why it's not working. I've tried some other designs but all of them end up being a NullPointerException. The JUnit test that was given to us verifies that we inserted the node in the correct place, in addition to checking the Node's payload. I'm failing both of these tests. This is our first assignment using recursion, so I'm still fairly new at it. Any guidance would be greatly appreciated!

Body:
public static Node<Integer> insert(Node<Integer> root, Integer value) {
    if (root == null) {
        root = new Node<>(value);
    } else if (value < root.payload) {
         root.left = insert(root.left, value);
    } else if (value > root.payload) {
         root.right = insert(root.right, value);
    }
    return root;
}

This will add the value at its correct place and return the root. You can print the tree to check the same


问:
Android - How to draw a transparent rectangle bordered shape with only its corners visible?
I want to draw a shape like this in android.

I used the following code

```<code><?xml version="1.0" encoding="utf-8"?>
<shape xmlns:android="http://schemas.android.com/apk/res/android"
android:id="@+id/shape_my">
<stroke
    android:width="2dp"
    android:dashWidth="20dp"
    android:dashGap="20dp"
    android:color="#c1c1c1" />
<padding
    android:bottom="20dp"
    android:left="20dp"
    android:right="20dp"
    android:top="20dp" />
<corners android:radius="0dp" />
<solid android:color="#00000000" />
</shape>
</code>```

But no perfection I got. Help me, friends.

答:
Below is the drawable that doesn't depends on the width and height of the rectangle, you can use this drawable for portrait and landscape :</p>

```<code><layer-list xmlns:android="http://schemas.android.com/apk/res/android">
    <item
        android:width="8dp"
        android:height="48dp"
        android:gravity="top|left">
        <shape android:shape="rectangle">
            <solid android:color="#000000" />
        </shape>
    </item>
    <item
        android:width="48dp"
        android:height="8dp"
        android:gravity="top|left">
        <shape android:shape="rectangle">
            <solid android:color="#000000" />
        </shape>
    </item>
    <item
        android:width="8dp"
        android:height="48dp"
        android:gravity="top|right">
        <shape android:shape="rectangle">
            <solid android:color="#000000" />
        </shape>
    </item>
    <item
        android:width="48dp"
        android:height="8dp"
        android:gravity="top|right">
        <shape android:shape="rectangle">
            <solid android:color="#000000" />
        </shape>
    </item>
    <item
        android:width="8dp"
        android:height="48dp"
        android:gravity="bottom|left">
        <shape android:shape="rectangle">
            <solid android:color="#000000" />
        </shape>
    </item>
    <item
        android:width="48dp"
        android:height="8dp"
        android:gravity="bottom|left">
        <shape android:shape="rectangle">
            <solid android:color="#000000" />
        </shape>
    </item>
    <item
        android:width="8dp"
        android:height="48dp"
        android:gravity="bottom|right">
        <shape android:shape="rectangle">
            <solid android:color="#000000" />
        </shape>
    </item>
    <item
        android:width="48dp"
        android:height="8dp"
        android:gravity="bottom|right">
        <shape android:shape="rectangle">
            <solid android:color="#000000" />
        </shape>
    </item>
</layer-list>
</code>```

Body:
I want to draw a shape like this in android.

I used the following code

<?xml version="1.0" encoding="utf-8"?>
<shape xmlns:android="http://schemas.android.com/apk/res/android"
android:id="@+id/shape_my">
<stroke
    android:width="2dp"
    android:dashWidth="20dp"
    android:dashGap="20dp"
    android:color="#c1c1c1" />
<padding
    android:bottom="20dp"
    android:left="20dp"
    android:right="20dp"
    android:top="20dp" />
<corners android:radius="0dp" />
<solid android:color="#00000000" />
</shape>

But no perfection I got. Help me, friends.

Body:
Below is the drawable that doesn't depends on the width and height of the rectangle, you can use this drawable for portrait and landscape :

<layer-list xmlns:android="http://schemas.android.com/apk/res/android">
    <item
        android:width="8dp"
        android:height="48dp"
        android:gravity="top|left">
        <shape android:shape="rectangle">
            <solid android:color="#000000" />
        </shape>
    </item>
    <item
        android:width="48dp"
        android:height="8dp"
        android:gravity="top|left">
        <shape android:shape="rectangle">
            <solid android:color="#000000" />
        </shape>
    </item>
    <item
        android:width="8dp"
        android:height="48dp"
        android:gravity="top|right">
        <shape android:shape="rectangle">
            <solid android:color="#000000" />
        </shape>
    </item>
    <item
        android:width="48dp"
        android:height="8dp"
        android:gravity="top|right">
        <shape android:shape="rectangle">
            <solid android:color="#000000" />
        </shape>
    </item>
    <item
        android:width="8dp"
        android:height="48dp"
        android:gravity="bottom|left">
        <shape android:shape="rectangle">
            <solid android:color="#000000" />
        </shape>
    </item>
    <item
        android:width="48dp"
        android:height="8dp"
        android:gravity="bottom|left">
        <shape android:shape="rectangle">
            <solid android:color="#000000" />
        </shape>
    </item>
    <item
        android:width="8dp"
        android:height="48dp"
        android:gravity="bottom|right">
        <shape android:shape="rectangle">
            <solid android:color="#000000" />
        </shape>
    </item>
    <item
        android:width="48dp"
        android:height="8dp"
        android:gravity="bottom|right">
        <shape android:shape="rectangle">
            <solid android:color="#000000" />
        </shape>
    </item>
</layer-list>


问:
Removing key/value pairs in list of dictionary having None Values
inputs : [{'test1': 'test', 'test2': None}]

Exected output : [{'test1': 'test'}]

答:
```<code>keep_keys = set()

for d in inputs:
        for key, value in d.items():
                if value is not None:
                        keep_keys.add(key)

remove_keys = set(d) - keep_keys

for d in inputs:
        for k in remove_keys:
                del d[k]

print (inputs)
</code>```


问:
Nested SQL IN statement for cell with more than 1 value

How do i write the SQL such that it will return me

tom,ken,jerry

I tried this SQL as

```<code>select name
  from staffDB
 where dept in (select value
                  from ConfigDB
                 where key = 'dept')
</code>```

but it returns no value, no nope, i'm not allowed to alter the database design.

答:
Please use below query,

```<code>select * from
(select LISTAGG(Name, ',') WITHIN GROUP (ORDER BY Dept) as name,
LISTAGG(Dept, ',') WITHIN GROUP (ORDER BY Dept) as dept from staffDB)
where dept  in
(select value from ConfigDB);
</code>```

Below is the Test Case,

Body:
How do i write the SQL such that it will return me

tom,ken,jerry

I tried this SQL as

select name
  from staffDB
 where dept in (select value
                  from ConfigDB
                 where key = 'dept')

but it returns no value, no nope, i'm not allowed to alter the database design.

Body:
Please use below query,

select * from
(select LISTAGG(Name, ',') WITHIN GROUP (ORDER BY Dept) as name,
LISTAGG(Dept, ',') WITHIN GROUP (ORDER BY Dept) as dept from staffDB)
where dept  in
(select value from ConfigDB);

Below is the Test Case,


问:
Converting Strings in Excel to Dates
We imported a bunch of data into cells.  But when you click on the cell, their is an apostrophe before the data, so it thinks its a string. By removing the apostrophe, the data gets recognized as dates. How do I avoid doing this by hand?</p>

答:
Yep, go for Find Replace (Ctrl + H)

find: '        //apostrophe
replace with:  //leave this blank

click "replace all"

Title: Converting Strings in Excel to Dates