问:
How can I populate a drop down list control Collection?
How can I populate a drop down list control (ASP.NET) from a SPListTemplateCollection (SharePoint 2007) ?

```<code>SPWeb web = SPContext.Current.Web;

ddlTemplateList = new DropDownList();
ddlTemplateList.DataSource = web.ListTemplates;
ddlTemplateList.DataBind();
</code>```

This code doesn't work in a right way... The name of the list template is not showed.

答:
You need to specify DataTextField and DataValueField to make it work.

```<code>ddlTemplateList.DataSource = web.ListTemplates;
ddlTemplateList.DataTextField = "DisplayColumnName";
ddlTemplateList.DataValueField = "ValudColumnName";
ddlTemplateList.DataBind();
</code>```

Body:
How can I populate a drop down list control (ASP.NET) from a SPListTemplateCollection (SharePoint 2007) ?

SPWeb web = SPContext.Current.Web;

ddlTemplateList = new DropDownList();
ddlTemplateList.DataSource = web.ListTemplates;
ddlTemplateList.DataBind();

This code doesn't work in a right way... The name of the list template is not showed.

Body:
You need to specify DataTextField and DataValueField to make it work.

ddlTemplateList.DataSource = web.ListTemplates;
ddlTemplateList.DataTextField = "DisplayColumnName";
ddlTemplateList.DataValueField = "ValudColumnName";
ddlTemplateList.DataBind();


来源: stackexchange

问:
How to open a specific activity from an external link clicking
I know this question is not new, but its a bit different from already asked questions. I have a website that provides links to my app. The links direct users to specific data on my app. This is the layout of my app: I have 4 activities as Activity1.class, Activity2.class, Activity3.class, and of course the MainActivity.class which is the launcher activity.

My worry is this: On my website, I have 3 buttons: button 1 goes to open directly Activity1 on my app (assuming the app is already installed on the device), Button 2 on website opens Activity2 in my app.

Note: the app and the website are not by any means linked.

My question is: how to get a URL link to specific activity on my app. I need 3 URLs that open different 3 activities. I need these links for external use, such that they open a specified activity whey clicked.

Something like: http://myapppackage/ACTIVITY1.

This is just an example.

答:
In you AndroidManifest.xml add intent-filters to the activities like this

```<code>   <activity android:name=".ACTIVITY1">
        <intent-filter>
            <action android:name="android.intent.action.VIEW" />
            <category android:name="android.intent.category.DEFAULT" />
            <category android:name="android.intent.category.BROWSABLE" />

            <data
                android:scheme="http"
                android:host="myapppackage"
                android:pathPattern="/ACTIVITY1" />
        </intent-filter>
    </activity>

    <activity android:name=".ACTIVITY2">
        <intent-filter>
            <action android:name="android.intent.action.VIEW" />
            <category android:name="android.intent.category.DEFAULT" />
            <category android:name="android.intent.category.BROWSABLE" />

            <data
                android:scheme="http"
                android:host="myapppackage"
                android:pathPattern="/ACTIVITY2" />
        </intent-filter>
    </activity>

     <activity android:name=".ACTIVITY3">
        <intent-filter>
            <action android:name="android.intent.action.VIEW" />
            <category android:name="android.intent.category.DEFAULT" />
            <category android:name="android.intent.category.BROWSABLE" />

            <data
                android:scheme="http"
                android:host="myapppackage"
                android:pathPattern="/ACTIVITY3" />
        </intent-filter>
    </activity>
</code>```

For more info check this out

Deep Linking In Android

ContentLicense: CC BY-SA 4.0

Body:
In you AndroidManifest.xml add intent-filters to the activities like this

   <activity android:name=".ACTIVITY1">
        <intent-filter>
            <action android:name="android.intent.action.VIEW" />
            <category android:name="android.intent.category.DEFAULT" />
            <category android:name="android.intent.category.BROWSABLE" />

            <data
                android:scheme="http"
                android:host="myapppackage"
                android:pathPattern="/ACTIVITY1" />
        </intent-filter>
    </activity>

    <activity android:name=".ACTIVITY2">
        <intent-filter>
            <action android:name="android.intent.action.VIEW" />
            <category android:name="android.intent.category.DEFAULT" />
            <category android:name="android.intent.category.BROWSABLE" />

            <data
                android:scheme="http"
                android:host="myapppackage"
                android:pathPattern="/ACTIVITY2" />
        </intent-filter>
    </activity>

     <activity android:name=".ACTIVITY3">
        <intent-filter>
            <action android:name="android.intent.action.VIEW" />
            <category android:name="android.intent.category.DEFAULT" />
            <category android:name="android.intent.category.BROWSABLE" />

            <data
                android:scheme="http"
                android:host="myapppackage"
                android:pathPattern="/ACTIVITY3" />
        </intent-filter>
    </activity>

For more info check this out

Deep Linking In Android


问:
tomcat7.service failed to start
I have a Server running tomcat7, when I try to restart the tomcat7 service it says:

```<code>Job for tomcat7.service failed because the control process exited with error code. See "systemctl status tomcat7.service" and "journalctl -xe" for details.
</code>```

When i check my systemctl status tomcat7.service, it gives me:

```<code>    tomcat7.service - LSB: Start Tomcat.
   Loaded: loaded (/etc/init.d/tomcat7; bad; vendor preset: enabled)
   Active: failed (Result: exit-code) since Tue 2016-12-20 11:19:29 UTC; 5min ago
     Docs: man:systemd-sysv-generator(8)
  Process: 5223 ExecStart=/etc/init.d/tomcat7 start (code=exited, status=1/FAILURE)

Dec 20 11:19:24 padrum systemd[1]: Starting LSB: Start Tomcat....
Dec 20 11:19:24 padrum tomcat7[5223]:  * Starting Tomcat servlet engine tomcat7
Dec 20 11:19:29 padrum tomcat7[5223]:    ...fail!
Dec 20 11:19:29 padrum systemd[1]: tomcat7.service: Control process exited, code=exited status=1
Dec 20 11:19:29 padrum systemd[1]: Failed to start LSB: Start Tomcat..
Dec 20 11:19:29 padrum systemd[1]: tomcat7.service: Unit entered failed state.
Dec 20 11:19:29 padrum systemd[1]: tomcat7.service: Failed with result 'exit-code'.
</code>```

I tried uninstalling it with dpkg -P and apt-get remove. everytime I try to reinstall it it gives me an error that i can't run my tomcat7.

Any ideas?
Thanks in advance

答: WE had a similar problem.  The tomcat7 would NOT launch from the startup scripts no matter what we did.  But if we ran the command in the startup script directly from the command line it would load into memory just fine.</p>

ContentLicense: CC BY-SA 3.0

Title: tomcat7.service failed to start

Body:
I have a Server running tomcat7, when I try to restart the tomcat7 service it says:

Job for tomcat7.service failed because the control process exited with error code. See "systemctl status tomcat7.service" and "journalctl -xe" for details.

When i check my systemctl status tomcat7.service, it gives me:

    tomcat7.service - LSB: Start Tomcat.
   Loaded: loaded (/etc/init.d/tomcat7; bad; vendor preset: enabled)
   Active: failed (Result: exit-code) since Tue 2016-12-20 11:19:29 UTC; 5min ago
     Docs: man:systemd-sysv-generator(8)
  Process: 5223 ExecStart=/etc/init.d/tomcat7 start (code=exited, status=1/FAILURE)

Dec 20 11:19:24 padrum systemd[1]: Starting LSB: Start Tomcat....
Dec 20 11:19:24 padrum tomcat7[5223]:  * Starting Tomcat servlet engine tomcat7
Dec 20 11:19:29 padrum tomcat7[5223]:    ...fail!
Dec 20 11:19:29 padrum systemd[1]: tomcat7.service: Control process exited, code=exited status=1
Dec 20 11:19:29 padrum systemd[1]: Failed to start LSB: Start Tomcat..
Dec 20 11:19:29 padrum systemd[1]: tomcat7.service: Unit entered failed state.
Dec 20 11:19:29 padrum systemd[1]: tomcat7.service: Failed with result 'exit-code'.

I tried uninstalling it with dpkg -P and apt-get remove. everytime I try to reinstall it it gives me an error that i can't run my tomcat7.

Any ideas?
Thanks in advance


问:
Output of weeknumbers in R and Excel is different
The ouput of Weekdays in R and Excel is different. Is there any way i can make both the ouput to be same. If possible the output of R should match with the Excel spread sheet.Below is the code and the data for reference:

```<code>structure(list(Pred_date = structure(c(7L, 8L, 10L, 2L, 9L, 14L,
6L, 12L, 5L, 15L, 13L, 3L, 1L, 12L, 12L, 3L, 12L, 12L, 4L, 7L,
9L, 11L, 11L), .Label = c("5/28/2020", "5/30/2020", "6/1/2020",
"6/12/2020", "6/13/2020", "6/20/2020", "6/22/2020", "6/23/2020",
"6/24/2020", "6/25/2020", "6/4/2020", "6/6/2020", "7/11/2020",
"7/18/2020", "7/4/2020"), class = "factor")), class = "data.frame", row.names = c(NA,
-23L))
library(lubridate)
date$Pred_date<-mdy(date$Pred_date)
date$Week_Act_Pay<-lubridate::week(ymd(date$Pred_date))
head(date)
</code>```

This is the output in R:

Below is the output in excel:

答:
Excel's WEEKNUM function has starting day as "Sunday" and January 1 is the first week of the year. You can reproduce the same output using "%U" in format and adding 1 to it.

```<code>date$Week_Act_Pay <- as.integer(format(date$Pred_date, "%U")) + 1
</code>```

Body:
The ouput of Weekdays in R and Excel is different. Is there any way i can make both the ouput to be same. If possible the output of R should match with the Excel spread sheet.Below is the code and the data for reference:

structure(list(Pred_date = structure(c(7L, 8L, 10L, 2L, 9L, 14L,
6L, 12L, 5L, 15L, 13L, 3L, 1L, 12L, 12L, 3L, 12L, 12L, 4L, 7L,
9L, 11L, 11L), .Label = c("5/28/2020", "5/30/2020", "6/1/2020",
"6/12/2020", "6/13/2020", "6/20/2020", "6/22/2020", "6/23/2020",
"6/24/2020", "6/25/2020", "6/4/2020", "6/6/2020", "7/11/2020",
"7/18/2020", "7/4/2020"), class = "factor")), class = "data.frame", row.names = c(NA,
-23L))
library(lubridate)
date$Pred_date<-mdy(date$Pred_date)
date$Week_Act_Pay<-lubridate::week(ymd(date$Pred_date))
head(date)

This is the output in R:

Below is the output in excel:

Body:
Excel's WEEKNUM function has starting day as "Sunday" and January 1 is the first week of the year. You can reproduce the same output using "%U" in format and adding 1 to it.

date$Week_Act_Pay <- as.integer(format(date$Pred_date, "%U")) + 1


答:
The documentation shows that the two functions (R's week and Excel's WEEKNUM) are calculating different things.

R: lubridate::week Calculates the number of 7-day periods between the given date and Jan. 1st, plus one.

Excel: WEEKNUM: Calculates the week number such that the week containing January 1 is the first week of the year, and assumes that the week starts in Sunday. This is also known as "epi week" (short for epidemiological), or "CDC week". Here is the reference

In R, you can get the epi week by simply using lubridate::epiweek() instead.

This example shows how each one is calculated for the date January 13, 2020

So, in your data, you can get the Excel results in R using:

```<code>date$Week_Act_Pay<-lubridate::week(ymd(date$Pred_date))
head(date)
</code>```

Prints this:

```<code>   Pred_date Week_Act_Pay
1 2020-06-22           26
2 2020-06-23           26
3 2020-06-25           26
4 2020-05-30           22
5 2020-06-24           26
6 2020-07-18           29
</code>```

Title: Output of weeknumbers in R and Excel is different

Body:
The documentation shows that the two functions (R's week and Excel's WEEKNUM) are calculating different things.

R: lubridate::week Calculates the number of 7-day periods between the given date and Jan. 1st, plus one.

Excel: WEEKNUM: Calculates the week number such that the week containing January 1 is the first week of the year, and assumes that the week starts in Sunday. This is also known as "epi week" (short for epidemiological), or "CDC week". Here is the reference

In R, you can get the epi week by simply using lubridate::epiweek() instead.

This example shows how each one is calculated for the date January 13, 2020

So, in your data, you can get the Excel results in R using:

date$Week_Act_Pay<-lubridate::week(ymd(date$Pred_date))
head(date)

Prints this:

   Pred_date Week_Act_Pay
1 2020-06-22           26
2 2020-06-23           26
3 2020-06-25           26
4 2020-05-30           22
5 2020-06-24           26
6 2020-07-18           29


问:
edit xml file using sed or something by matching over multiple lines
I'd like to 'edit' some xml files, which may have similar sections multiple times in one file.
I need add 2 possible missing lines (i call it a pair) inside each section.. i.e. check if the 'pair' exists or not, if it does not then add them.

e.g. below is the possible missing pair lines i'd like to add in.

```<code><arg>--possibleMissedKey</arg>
<arg>possibleMissedValue</arg>
</code>```

Below file has the pair, so i do not need to add them in
but if any of the  section did miss this pair, i'd like to add the pair in to the section.. Also the number of lines in each section is not predictable.

```<code>
    <some-tag-section-not-interesting>
        some contents not interesting to me
    </some-tag-section-not-interesting>
    <some-tag-to-look-for>
        <some stuff - a> ..... </some stuff - a>
        <arg>--possibleMissedKey</arg>
        <arg>possibleMissedValue</arg>
        <something-else-not-interesting>blahblah</something-else-not-interesting>
    </some-tag-to-look-for>
    <some-tag-to-look-for>
        <some stuff - b>....</some stuff - b>
        <arg>--possibleMissedKey</arg>
        <arg>possibleMissedValue</arg>
        <something-else-not-interesting>blahblah</something-else-not-interesting>
    </some-tag-to-look-for>

</code>```

so i've consider a few options, but each one i've a question for it:

the first thing came to my mind is 'sed'. I am hoping to replace the ending tag
</some-tag-to-look-for>
with

```<code>
        <arg>--possibleMissedKey</arg>
        <arg>possibleMissedValue</arg>
     </some-tag-to-look-for>

</code>```

i.e. essentially add it to the last part of the section.
but i am not aware of whether I can 'pattern match on multiple lines' in sed. and I have not used so called 'hold space'.
My experience with sed has been to check some string in the 'current single line'.

Another option i was hoping to check, is to introduce a inside_a_section_flag, initial value is '0'. start reading the file, the moment I find a staring <some-tag-to-look-for>, I turn that inside_a_section_flag to '1',
and once I reach the 'ending </some-tag-to-look-for>', I do some possible changes, and turn it back to '0'.
so this inside_a_section_flag, if it is 1, means I are inside of the section.... so I need to look for the 'pair',
  if I found the pair, I turn the inside_a_section_flag to be 1, meaning I do not need to add the pair and can get out of the current section....
but I am not aware of whether sed can also work with a variable flag, i.e. do conditional replacement/change based on a variable value.

Should this be done by shell at all, instead should this be done by a python script instead?

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

```<code>sed '/<some-tag-to-look-for>/{:a;n;/<arg>--possibleMissedKey<\/arg>/b;/<\/some-tag-to-look-for>/!{h;ba};x;s/\S.*/<arg>--possibleMissedKey<\/arg>/p;s//<arg>--possibleMissedValue<\/arg>/p;x}' file
</code>```

Match on a line containing <some-tag-to-look-for>.

Loop through the following lines.

If a line containing <arg>--possibleMissedKey</arg> is encountered, bail out.

Otherwise, if the current line does not match </some-tag-to-look-for>, make a copy and repeat.

When the end tag is found, insert the required two lines using the copied line as a template (so as to retain indentation).

Body:
I'd like to 'edit' some xml files, which may have similar sections multiple times in one file.
I need add 2 possible missing lines (i call it a pair) inside each section.. i.e. check if the 'pair' exists or not, if it does not then add them.

e.g. below is the possible missing pair lines i'd like to add in.

<arg>--possibleMissedKey</arg>
<arg>possibleMissedValue</arg>

Below file has the pair, so i do not need to add them in
but if any of the  section did miss this pair, i'd like to add the pair in to the section.. Also the number of lines in each section is not predictable.

    <some-tag-section-not-interesting>
        some contents not interesting to me
    </some-tag-section-not-interesting>
    <some-tag-to-look-for>
        <some stuff - a> ..... </some stuff - a>
        <arg>--possibleMissedKey</arg>
        <arg>possibleMissedValue</arg>
        <something-else-not-interesting>blahblah</something-else-not-interesting>
    </some-tag-to-look-for>
    <some-tag-to-look-for>
        <some stuff - b>....</some stuff - b>
        <arg>--possibleMissedKey</arg>
        <arg>possibleMissedValue</arg>
        <something-else-not-interesting>blahblah</something-else-not-interesting>
    </some-tag-to-look-for>

so i've consider a few options, but each one i've a question for it:

the first thing came to my mind is 'sed'. I am hoping to replace the ending tag
</some-tag-to-look-for>
with

        <arg>--possibleMissedKey</arg>
        <arg>possibleMissedValue</arg>
     </some-tag-to-look-for>

i.e. essentially add it to the last part of the section.
but i am not aware of whether I can 'pattern match on multiple lines' in sed. and I have not used so called 'hold space'.
My experience with sed has been to check some string in the 'current single line'.

Another option i was hoping to check, is to introduce a inside_a_section_flag, initial value is '0'. start reading the file, the moment I find a staring <some-tag-to-look-for>, I turn that inside_a_section_flag to '1',
and once I reach the 'ending </some-tag-to-look-for>', I do some possible changes, and turn it back to '0'.
so this inside_a_section_flag, if it is 1, means I are inside of the section.... so I need to look for the 'pair',
  if I found the pair, I turn the inside_a_section_flag to be 1, meaning I do not need to add the pair and can get out of the current section....
but I am not aware of whether sed can also work with a variable flag, i.e. do conditional replacement/change based on a variable value.

Should this be done by shell at all, instead should this be done by a python script instead?

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

sed '/<some-tag-to-look-for>/{:a;n;/<arg>--possibleMissedKey<\/arg>/b;/<\/some-tag-to-look-for>/!{h;ba};x;s/\S.*/<arg>--possibleMissedKey<\/arg>/p;s//<arg>--possibleMissedValue<\/arg>/p;x}' file

Match on a line containing <some-tag-to-look-for>.

Loop through the following lines.

If a line containing <arg>--possibleMissedKey</arg> is encountered, bail out.

Otherwise, if the current line does not match </some-tag-to-look-for>, make a copy and repeat.

When the end tag is found, insert the required two lines using the copied line as a template (so as to retain indentation).


问:
Google Script For Loop Issues
So this question seems to be beaten to death on the boards, but with all my reading and googling, I just can't figure out what I'm doing wrong.

I'm trying to adapt the code from this link
How to loop a google spreadsheet column values and set result in column B?

Below is what I've adapted it to

```<code>function EquationIterationTest(){
  var s = SpreadsheetApp.getActiveSpreadsheet();
  var sht = s.getSheetByName('Heath, OH')
  var drng = sht.getDataRange();
  var rng = sht.getRange(13, 2, 111, 1)
  //.getRange(13, 2, drng.getLastRow()-1, drng.getLastColumn())
  var rngA = rng.getValues();//Array of input values

  Logger.log(rngA);

  for(var i = 0; i < rngA.length; i++) {
    if(rngA[i][0] === 'subtotal'){
    rng.offset(0,3).setFormula('=iferror(sum(filter(Invoices!$E:$E,Invoices!$F:$F=$B14,Invoices!$A:$A=$C$2)))');
    }
   else{
     rng.offset(0,3).setValue('Dumb');
   }
   }
 }
</code>```

When I run this, rngA does get the first column of values (which in this instance starts at B13) however, it will not input the formula in the third column of values. Instead it moves right through the first if statement and executes the else statement. The only thing I can think is there's something wrong either with my if statement or my array.

I tried setting if(rngA[i][0] === 'subtotal') to if(rngA[i][1] === 'subtotal'), but that still returned "dumb" on every line.

Any help would be appreciated so I can stop being "dumb"!

Here's the link to my sheet.

https://docs.google.com/spreadsheets/d/1cDkwWThXDTssH89gJX7W1zKzsW86oLXO-FPfAIJvc-g/edit?usp=sharing

Thanks

答:
So I want to make sure I put this here because while the answer above was previously correct, I figured out a much faster way to do it using arrays. This function checks against the data range for a value (in this case "Subtotal") and then appends the equation to rows that that do not contain that value. It is easy to make it compare against the value though by changing the operator from != to ==.

```<code>
    function NewIterationTest(){
    var ss = SpreadsheetApp.getActiveSpreadsheet();
    var activeSheet = ss.getActiveSheet();
    var data = activeSheet.getRange(13, 2, 112, 1).getValues();

      for (var i = 0; i < data.length; i++){

        var rowData = data[i];
        var checkData = data;
        var row = checkData[i];
        var colB = row[0];

        if(colB != 'Subtotal'{

          activeSheet.getRange(13 + i, 5).setFormula('=iferror(sum(filter(Invoices!$E:$E,Invoices!$F:$F=$B14,Invoices!$A:$A=$C$2)))');
        }

      }
    }

</code>```

However, if anyone could tell me how to also eliminate compare against whether or not a the text is bold, that would be helpful. Not sure it can be done though since it's pulling against the array.

Title: Google Script For Loop Issues

Body:
So this question seems to be beaten to death on the boards, but with all my reading and googling, I just can't figure out what I'm doing wrong.

I'm trying to adapt the code from this link
How to loop a google spreadsheet column values and set result in column B?

Below is what I've adapted it to

function EquationIterationTest(){
  var s = SpreadsheetApp.getActiveSpreadsheet();
  var sht = s.getSheetByName('Heath, OH')
  var drng = sht.getDataRange();
  var rng = sht.getRange(13, 2, 111, 1)
  //.getRange(13, 2, drng.getLastRow()-1, drng.getLastColumn())
  var rngA = rng.getValues();//Array of input values

  Logger.log(rngA);

  for(var i = 0; i < rngA.length; i++) {
    if(rngA[i][0] === 'subtotal'){
    rng.offset(0,3).setFormula('=iferror(sum(filter(Invoices!$E:$E,Invoices!$F:$F=$B14,Invoices!$A:$A=$C$2)))');
    }
   else{
     rng.offset(0,3).setValue('Dumb');
   }
   }
 }

When I run this, rngA does get the first column of values (which in this instance starts at B13) however, it will not input the formula in the third column of values. Instead it moves right through the first if statement and executes the else statement. The only thing I can think is there's something wrong either with my if statement or my array.

I tried setting if(rngA[i][0] === 'subtotal') to if(rngA[i][1] === 'subtotal'), but that still returned "dumb" on every line.

Any help would be appreciated so I can stop being "dumb"!

Here's the link to my sheet.

https://docs.google.com/spreadsheets/d/1cDkwWThXDTssH89gJX7W1zKzsW86oLXO-FPfAIJvc-g/edit?usp=sharing

Thanks

Body:
So I want to make sure I put this here because while the answer above was previously correct, I figured out a much faster way to do it using arrays. This function checks against the data range for a value (in this case "Subtotal") and then appends the equation to rows that that do not contain that value. It is easy to make it compare against the value though by changing the operator from != to ==.

    function NewIterationTest(){
    var ss = SpreadsheetApp.getActiveSpreadsheet();
    var activeSheet = ss.getActiveSheet();
    var data = activeSheet.getRange(13, 2, 112, 1).getValues();

      for (var i = 0; i < data.length; i++){

        var rowData = data[i];
        var checkData = data;
        var row = checkData[i];
        var colB = row[0];

        if(colB != 'Subtotal'{

          activeSheet.getRange(13 + i, 5).setFormula('=iferror(sum(filter(Invoices!$E:$E,Invoices!$F:$F=$B14,Invoices!$A:$A=$C$2)))');
        }

      }
    }

However, if anyone could tell me how to also eliminate compare against whether or not a the text is bold, that would be helpful. Not sure it can be done though since it's pulling against the array.


问:
How could I make the program track the days completed on my habit tracker?

I want to create a feature where the program will track the number of days the user has completed their habit. I attempted to do it below, but it only printed the integer 1, instead of adding up the days properly.

```<code>import click

names_file = open("names.txt", "r+")
habits_file = open("habits.txt", "r+")
habits_time = open("time.txt", "r+")
days_completed = + 1

# Welcome Message
print("Welcome to Habit Tracker by Synclare")

# User Info
if click.confirm('Are you a new user?', True):
   user_name = input("Welcome. What's your name? ")
   names_file.write(user_name)

   habit = input("\nEnter a habit: ")
   habits_file.write(habit)

   time = input("For how long do you want to do this habit?")
   habits_time.write(time)

   print("Habit created.")

   else:
           print("\nWelcome back, " + names_file.readline() + ".")
           if click.confirm('\nWould you like to view your current habits?', True):
           read_habit = habits_file.read()
           read_time = habits_time.read()
           print(read_habit + ": " + habits_time.read())

              if click.confirm("\nHave you completed today's habit?", True):
                  print("You have completed " + str(days_completed) + "/" + read_time)
</code>```

答:
I can't see where you read days_completed from file. I would suggest to create some kind of data structures for habits - at least dictionary. Also it is not clear what do you mean by time - days repeated, or total time in minutes.
Something like:</p>

```<code>total_time = 6

habbits = {
    'habbit1': {'time': total_time},
    'habbit2': {'time': total_time}
    }

for h in habbits:
    print(f'For {h} you have spent {habbits[h]["time"]}')
</code>```

Body:
I want to create a feature where the program will track the number of days the user has completed their habit. I attempted to do it below, but it only printed the integer 1, instead of adding up the days properly.

import click

names_file = open("names.txt", "r+")
habits_file = open("habits.txt", "r+")
habits_time = open("time.txt", "r+")
days_completed = + 1

# Welcome Message
print("Welcome to Habit Tracker by Synclare")

# User Info
if click.confirm('Are you a new user?', True):
   user_name = input("Welcome. What's your name? ")
   names_file.write(user_name)

   habit = input("\nEnter a habit: ")
   habits_file.write(habit)

   time = input("For how long do you want to do this habit?")
   habits_time.write(time)

   print("Habit created.")

   else:
           print("\nWelcome back, " + names_file.readline() + ".")
           if click.confirm('\nWould you like to view your current habits?', True):
           read_habit = habits_file.read()
           read_time = habits_time.read()
           print(read_habit + ": " + habits_time.read())

              if click.confirm("\nHave you completed today's habit?", True):
                  print("You have completed " + str(days_completed) + "/" + read_time)

Body:
I can't see where you read days_completed from file. I would suggest to create some kind of data structures for habits - at least dictionary. Also it is not clear what do you mean by time - days repeated, or total time in minutes.
Something like:

total_time = 6

habbits = {
    'habbit1': {'time': total_time},
    'habbit2': {'time': total_time}
    }

for h in habbits:
    print(f'For {h} you have spent {habbits[h]["time"]}')


问:
Python-crontab package returns __init__ error
Can anyone tell me what I'm doing wrong with python-crontab?

```<code>from crontab import CronTab
system_cron = CronTab()
</code>```

generates the following error:

```<code>File "test.py", line 3, in <module>
cron = CronTab()
TypeError: __init__() takes exactly 2 arguments (1 given)
</code>```

I get the same problem when I try other variations of examples straight out of the package instructions:

```<code>my_user_cron  = CronTab(user=True)
users_cron    = CronTab(user='username')
</code>```

I've also tried creating the object with this approach, which I found in the python-crontab.py file:

```<code>cron = CronTab(tab='')
</code>```

But it generates this error: TypeError: __init__() got an unexpected keyword argument 'tab'

I've tried looking at the code in the package to see if maybe it's a documentation error and figure my way around, but it's beyond my skill level.  I believe this is the code that defines how I should be creating a crontab object:

```<code>def __init__(self, user=None, tab=None, tabfile=None, log=None):
    if user == True and not WINOS:
        user = pwd.getpwuid( os.getuid() )[ 0 ]
    self.lines = None
    self.crons = None
    self.filen = None
    # Protect windows users
    self.root  = not WINOS and os.getuid() == 0
    self.user  = user
    # Detect older unixes and help them out.
    self.intab = tab
    self.read(tabfile)
    self._log = log
</code>```

Any thoughts on what I am doing wrong?

help(CronTab) returns:

```<code>class CronTab(__builtin__.object)
|  Methods defined here:
|
|  __init__(self, crontab)
|
|  next(self, now=None, increments=[<function <lambda>>, <function <lambda>>, <function <lambda>>, <function _month_incr>, <function <lambda>>, <function _year_incr>, <function <lambda>>, <function <lambda>>, <function <lambda>>, <function <lambda>>, <function <lambda>>], delta=True)
|      How long to wait in seconds before this crontab entry can next be
|      executed.
|
|  previous(self, now=None, delta=True)
|
|  test(self, entry)
|
|   ----------------------------------------------------------------------
|  Data descriptors defined here:
|
|   matchers
</code>```

答:
```<code>cron = CronTab(user='name')
TypeError: __init__() got an unexpected keyword argument 'user'
</code>```

If you are getting above error do following things:

Uninstall crontab using

```<code>pip uninstall crontab
</code>```

and install

```<code>pip install python-crontab
</code>```

Body:
Can anyone tell me what I'm doing wrong with python-crontab?

from crontab import CronTab
system_cron = CronTab()

generates the following error:

File "test.py", line 3, in <module>
cron = CronTab()
TypeError: __init__() takes exactly 2 arguments (1 given)

I get the same problem when I try other variations of examples straight out of the package instructions:

my_user_cron  = CronTab(user=True)
users_cron    = CronTab(user='username')

I've also tried creating the object with this approach, which I found in the python-crontab.py file:

cron = CronTab(tab='')

But it generates this error: TypeError: __init__() got an unexpected keyword argument 'tab'

I've tried looking at the code in the package to see if maybe it's a documentation error and figure my way around, but it's beyond my skill level.  I believe this is the code that defines how I should be creating a crontab object:

def __init__(self, user=None, tab=None, tabfile=None, log=None):
    if user == True and not WINOS:
        user = pwd.getpwuid( os.getuid() )[ 0 ]
    self.lines = None
    self.crons = None
    self.filen = None
    # Protect windows users
    self.root  = not WINOS and os.getuid() == 0
    self.user  = user
    # Detect older unixes and help them out.
    self.intab = tab
    self.read(tabfile)
    self._log = log

Any thoughts on what I am doing wrong?

help(CronTab) returns:

class CronTab(__builtin__.object)
|  Methods defined here:
|
|  __init__(self, crontab)
|
|  next(self, now=None, increments=[<function <lambda>>, <function <lambda>>, <function <lambda>>, <function _month_incr>, <function <lambda>>, <function _year_incr>, <function <lambda>>, <function <lambda>>, <function <lambda>>, <function <lambda>>, <function <lambda>>], delta=True)
|      How long to wait in seconds before this crontab entry can next be
|      executed.
|
|  previous(self, now=None, delta=True)
|
|  test(self, entry)
|
|   ----------------------------------------------------------------------
|  Data descriptors defined here:
|
|   matchers

Body:
cron = CronTab(user='name')
TypeError: __init__() got an unexpected keyword argument 'user'

If you are getting above error do following things:

Uninstall crontab using

pip uninstall crontab

and install

pip install python-crontab


问:
Why is my service not updating on my app component?
I am working with Ionic 4 and I want to show information about the current logged user but is not working I mean it works on any component except the app component, I am using a variable called userData which is a BehaviorSubject. Do you know what is wrong with my code?

auth.service.ts

```<code>import { Platform } from '@ionic/angular';
import { Injectable } from '@angular/core';
import { Storage } from '@ionic/storage';
import { BehaviorSubject, Observable, from, of, throwError } from 'rxjs';
import { take, map,tap, switchMap, catchError } from 'rxjs/operators';
import { JwtHelperService } from "@auth0/angular-jwt";
import { HttpClient } from '@angular/common/http';
import { Router } from '@angular/router';
import { Tokens } from '../models/tokens';
import { environment } from 'src/environments/environment';

const helper = new JwtHelperService();
//Agregar token access y refresh
const accessToken = 'access';
const refreshToken = 'refresh';

@Injectable({
  providedIn: 'root'
})
export class AuthService {
  public user: Observable<any>;
  private userData = new BehaviorSubject(null);
  private access: string = null;
  private refresh: string = null;
  constructor(private storage: Storage, private http: HttpClient, private plt: Platform, private router: Router) {
    this.loadStoredTokens();
  }

  getTokenExpirationDate(userData): Date {
    if (userData['exp'] === undefined) return null;

    const date = new Date(0);
    date.setUTCSeconds(userData['exp']);
    return date;
  }

  isAcessTokenExpired(): boolean {
    let userData = this.userData.getValue();
    console.log(userData);
    if(!userData) return true;

    const date = this.getTokenExpirationDate(userData);
    if(date === undefined) return false;
    return !(date.valueOf() > new Date().valueOf());
  }

  loadStoredTokens() {
    let platformObs = from(this.plt.ready());

    this.user = platformObs.pipe(
      switchMap(() => {
        return from(this.storage.get(refreshToken));
      }),
      map(refreshToken => {
        if (refreshToken) {
          this.refresh = refreshToken;
        } else {
          this.refresh = null;
        }
      }),
      switchMap(() => {
        return from(this.storage.get(accessToken));
      }),
      map(accessToken => {
        if (accessToken) {
          this.access = accessToken;
          let decoded = helper.decodeToken(accessToken);
          this.userData.next(decoded);
          return true;
        } else {
          this.access = null;
          return null;
        }
      })
    );

  }

  login(credentials: {username: string, password: string }) {
    return this.http
    .post(`${environment.apiUrl}/token/obtain/`,credentials)
    .pipe(
      take(1),
      map(res => {
        // Extract the JWT
        return res;
      }),
      switchMap(token => {
        let decoded = helper.decodeToken(token['access']);
        this.userData.next(decoded);

        from(this.storage.set(refreshToken, token['refresh']))
        let storageObs = from(this.storage.set(accessToken, token['access']));
        return storageObs;
      })
    );

  }

  getUser() {
    return this.userData.getValue();
  }

  logout() {
    this.storage.remove(accessToken).then(() => {

      this.storage.remove(refreshToken).then(() => {
        this.router.navigateByUrl('/');
        this.userData.next(null);
      });

    });
  }

getAccessToken() {
  return  this.access;
}

 getRefreshToken() {
  return this.refresh;
}

setAccessToken(token) {
  this.storage.set(accessToken, token);
}

  refreshToken() {
    return this.http.post<any>(`${environment.apiUrl}/token/refresh/`, {
    'refresh': this.getRefreshToken()
    }).pipe(tap((tokens: Tokens) => {
      this.setAccessToken(tokens.access);
      this.access = tokens.access;
    }));
  }
}
</code>```

app.component.ts (I am using getUser() function in order to get the current user information)

```<code>import { Component, OnInit, ViewChildren, QueryList, OnChanges } from '@angular/core';

import { Platform, ModalController, ActionSheetController, PopoverController, IonRouterOutlet, MenuController } from '@ionic/angular';
import { SplashScreen } from '@ionic-native/splash-screen/ngx';
import { StatusBar } from '@ionic-native/status-bar/ngx';
import { Router } from '@angular/router';
import { faHome, faInfo, faFileContract } from '@fortawesome/free-solid-svg-icons';
import { ToastController } from '@ionic/angular';
import { AuthService } from './auth/services/auth.service';

@Component({
  selector: 'app-root',
  templateUrl: 'app.component.html',
  styleUrls: ['app.component.scss']
})
export class AppComponent implements OnInit {
  public selectedIndex = 0;
  user = null;

  public appPages = [
    {
      title: 'Home',
      url: '/home',
      icon: faHome
    },
    {
      title: 'About',
      url: '/about',
      icon: faInfo
    },
    {
      title: 'Legal',
      url: '/legal',
      icon: faFileContract
    }
  ];

  constructor(
    private platform: Platform,
    private splashScreen: SplashScreen,
    private statusBar: StatusBar,
    public modalCtrl: ModalController,
    private menu: MenuController,
    private actionSheetCtrl: ActionSheetController,
    private popoverCtrl: PopoverController,
    private router: Router,
    public toastController: ToastController,
    private auth: AuthService
  ) {
    this.initializeApp();
  }

  initializeApp() {
    this.platform.ready().then(() => {
      this.statusBar.backgroundColorByHexString('#D4AF37');
      this.splashScreen.hide();
    });
  }

  ngOnInit() {

    this.user = this.auth.getUser();
    const path = window.location.pathname.split('home/')[1];
    if (path !== undefined) {
      this.selectedIndex = this.appPages.findIndex(page => page.title.toLowerCase() === path.toLowerCase());
    }

  }

}
</code>```

app.component.html (here I want to show the user information, the same code is working in every component except this)

```<code><ion-app>
  <ion-split-pane contentId="main-content">
    <ion-menu contentId="main-content" type="overlay">
      <ion-content>
        <ion-list id="inbox-list">
          <ion-list-header>Menu</ion-list-header>
          <ion-note *ngIf="user">{{ user.email }} </ion-note>

          <ion-menu-toggle auto-hide="false" *ngFor="let p of appPages; let i = index">
            <ion-item (click)="selectedIndex = i" routerDirection="root" [routerLink]="[p.url]" lines="none" detail="false" [class.selected]="selectedIndex == i">
              <fa-icon (keyup)="onKeyFaIcon($event)" slot="start" [icon]="p.icon"></fa-icon>

              <ion-label>{{ p.title }}</ion-label>
            </ion-item>
          </ion-menu-toggle>
        </ion-list>

      </ion-content>
    </ion-menu>
    <ion-router-outlet id="main-content"></ion-router-outlet>
  </ion-split-pane>
</ion-app>
</code>```

答:
Please use async pipe to achieve this. As the user has no data while app loads. Please follow the code, it might help you.

app.component.html

```<code><ion-app>
<ion-split-pane contentId="main-content">
<ion-menu contentId="main-content" type="overlay">
  <ion-content>
    <ion-list id="inbox-list">
      <ion-list-header>Menu</ion-list-header>
      <ion-note *ngIf="user">{{ auth?.userData?.email | async }} </ion-note>
    </ion-list>
  </ion-content>
</ion-menu>
<ion-router-outlet id="main-content"></ion-router-outlet>
</code>```

keep the email properties in userData object. And keep AuthService scope as public while injection in the app.component.ts constructor.

Body:
I am working with Ionic 4 and I want to show information about the current logged user but is not working I mean it works on any component except the app component, I am using a variable called userData which is a BehaviorSubject. Do you know what is wrong with my code?

auth.service.ts

import { Platform } from '@ionic/angular';
import { Injectable } from '@angular/core';
import { Storage } from '@ionic/storage';
import { BehaviorSubject, Observable, from, of, throwError } from 'rxjs';
import { take, map,tap, switchMap, catchError } from 'rxjs/operators';
import { JwtHelperService } from "@auth0/angular-jwt";
import { HttpClient } from '@angular/common/http';
import { Router } from '@angular/router';
import { Tokens } from '../models/tokens';
import { environment } from 'src/environments/environment';

const helper = new JwtHelperService();
//Agregar token access y refresh
const accessToken = 'access';
const refreshToken = 'refresh';

@Injectable({
  providedIn: 'root'
})
export class AuthService {
  public user: Observable<any>;
  private userData = new BehaviorSubject(null);
  private access: string = null;
  private refresh: string = null;
  constructor(private storage: Storage, private http: HttpClient, private plt: Platform, private router: Router) {
    this.loadStoredTokens();
  }

  getTokenExpirationDate(userData): Date {
    if (userData['exp'] === undefined) return null;

    const date = new Date(0);
    date.setUTCSeconds(userData['exp']);
    return date;
  }

  isAcessTokenExpired(): boolean {
    let userData = this.userData.getValue();
    console.log(userData);
    if(!userData) return true;

    const date = this.getTokenExpirationDate(userData);
    if(date === undefined) return false;
    return !(date.valueOf() > new Date().valueOf());
  }

  loadStoredTokens() {
    let platformObs = from(this.plt.ready());

    this.user = platformObs.pipe(
      switchMap(() => {
        return from(this.storage.get(refreshToken));
      }),
      map(refreshToken => {
        if (refreshToken) {
          this.refresh = refreshToken;
        } else {
          this.refresh = null;
        }
      }),
      switchMap(() => {
        return from(this.storage.get(accessToken));
      }),
      map(accessToken => {
        if (accessToken) {
          this.access = accessToken;
          let decoded = helper.decodeToken(accessToken);
          this.userData.next(decoded);
          return true;
        } else {
          this.access = null;
          return null;
        }
      })
    );

  }

  login(credentials: {username: string, password: string }) {
    return this.http
    .post(`${environment.apiUrl}/token/obtain/`,credentials)
    .pipe(
      take(1),
      map(res => {
        // Extract the JWT
        return res;
      }),
      switchMap(token => {
        let decoded = helper.decodeToken(token['access']);
        this.userData.next(decoded);

        from(this.storage.set(refreshToken, token['refresh']))
        let storageObs = from(this.storage.set(accessToken, token['access']));
        return storageObs;
      })
    );

  }

  getUser() {
    return this.userData.getValue();
  }

  logout() {
    this.storage.remove(accessToken).then(() => {

      this.storage.remove(refreshToken).then(() => {
        this.router.navigateByUrl('/');
        this.userData.next(null);
      });

    });
  }

getAccessToken() {
  return  this.access;
}

 getRefreshToken() {
  return this.refresh;
}

setAccessToken(token) {
  this.storage.set(accessToken, token);
}

  refreshToken() {
    return this.http.post<any>(`${environment.apiUrl}/token/refresh/`, {
    'refresh': this.getRefreshToken()
    }).pipe(tap((tokens: Tokens) => {
      this.setAccessToken(tokens.access);
      this.access = tokens.access;
    }));
  }
}

app.component.ts (I am using getUser() function in order to get the current user information)

import { Component, OnInit, ViewChildren, QueryList, OnChanges } from '@angular/core';

import { Platform, ModalController, ActionSheetController, PopoverController, IonRouterOutlet, MenuController } from '@ionic/angular';
import { SplashScreen } from '@ionic-native/splash-screen/ngx';
import { StatusBar } from '@ionic-native/status-bar/ngx';
import { Router } from '@angular/router';
import { faHome, faInfo, faFileContract } from '@fortawesome/free-solid-svg-icons';
import { ToastController } from '@ionic/angular';
import { AuthService } from './auth/services/auth.service';

@Component({
  selector: 'app-root',
  templateUrl: 'app.component.html',
  styleUrls: ['app.component.scss']
})
export class AppComponent implements OnInit {
  public selectedIndex = 0;
  user = null;

  public appPages = [
    {
      title: 'Home',
      url: '/home',
      icon: faHome
    },
    {
      title: 'About',
      url: '/about',
      icon: faInfo
    },
    {
      title: 'Legal',
      url: '/legal',
      icon: faFileContract
    }
  ];

  constructor(
    private platform: Platform,
    private splashScreen: SplashScreen,
    private statusBar: StatusBar,
    public modalCtrl: ModalController,
    private menu: MenuController,
    private actionSheetCtrl: ActionSheetController,
    private popoverCtrl: PopoverController,
    private router: Router,
    public toastController: ToastController,
    private auth: AuthService
  ) {
    this.initializeApp();
  }

  initializeApp() {
    this.platform.ready().then(() => {
      this.statusBar.backgroundColorByHexString('#D4AF37');
      this.splashScreen.hide();
    });
  }

  ngOnInit() {

    this.user = this.auth.getUser();
    const path = window.location.pathname.split('home/')[1];
    if (path !== undefined) {
      this.selectedIndex = this.appPages.findIndex(page => page.title.toLowerCase() === path.toLowerCase());
    }

  }

}

app.component.html (here I want to show the user information, the same code is working in every component except this)

<ion-app>
  <ion-split-pane contentId="main-content">
    <ion-menu contentId="main-content" type="overlay">
      <ion-content>
        <ion-list id="inbox-list">
          <ion-list-header>Menu</ion-list-header>
          <ion-note *ngIf="user">{{ user.email }} </ion-note>

          <ion-menu-toggle auto-hide="false" *ngFor="let p of appPages; let i = index">
            <ion-item (click)="selectedIndex = i" routerDirection="root" [routerLink]="[p.url]" lines="none" detail="false" [class.selected]="selectedIndex == i">
              <fa-icon (keyup)="onKeyFaIcon($event)" slot="start" [icon]="p.icon"></fa-icon>

              <ion-label>{{ p.title }}</ion-label>
            </ion-item>
          </ion-menu-toggle>
        </ion-list>

      </ion-content>
    </ion-menu>
    <ion-router-outlet id="main-content"></ion-router-outlet>
  </ion-split-pane>
</ion-app>

Body:
Please use async pipe to achieve this. As the user has no data while app loads. Please follow the code, it might help you.

app.component.html

<ion-app>
<ion-split-pane contentId="main-content">
<ion-menu contentId="main-content" type="overlay">
  <ion-content>
    <ion-list id="inbox-list">
      <ion-list-header>Menu</ion-list-header>
      <ion-note *ngIf="user">{{ auth?.userData?.email | async }} </ion-note>
    </ion-list>
  </ion-content>
</ion-menu>
<ion-router-outlet id="main-content"></ion-router-outlet>

keep the email properties in userData object. And keep AuthService scope as public while injection in the app.component.ts constructor.


问:
Remove empty brackets ( ) from string
I had a problem in removing empty brackets from string, I tried few methods didn't work. kindly help

here is the dataframe

```<code>data = {'disc': ['( ) -2,4-dichloro-a- ( chloromethyl ) -benzenemethanol methanesulfonate','( ) ( s ) -isopropyl 2 ','( 2s3s ) -12-epoxy-3- ( boc-amino ) -4-phenylbutane ( ) boc-epoxideide']}
df1 = pd.DataFrame(data)
print(df1)
</code>```

which have multiple occurrence of ( ) need to remove only empty brackets.

input:

```<code>      disc
0   ( ) -2,4-dichloro-a- ( chloromethyl ) -benzenemethanol methanesulfonate
1   ( ) ( s ) -isopropyl 2
2   ( 2s3s ) -12-epoxy-3- ( boc-amino ) -4-p
</code>```

output:

```<code>     disc
0   -2,4-dichloro-a- ( chloromethyl ) -benzenemethanol methanesulfonate
1   ( s ) -isopropyl 2
2   ( 2s3s ) -12-epoxy-3- ( boc-amino ) -4-phenylbutane boc-epoxideide
</code>```

using replace is not helping because it will remove all brackets there in the string.

答:
pandas.DataFrame.replace does support using regex, so you can do:

```<code>import pandas as pd
data = {'disc': ['( ) -2,4-dichloro-a- ( chloromethyl ) -benzenemethanol methanesulfonate','( ) ( s ) -isopropyl 2 ','( 2s3s ) -12-epoxy-3- ( boc-amino ) -4-phenylbutane ( ) boc-epoxideide']}
df1 = pd.DataFrame(data)
df2 = df1.replace(r'\s*\(\s*\)\s*', '', regex=True)
print(df2)
</code>```

Output:

```<code>                                                disc
0  -2,4-dichloro-a- ( chloromethyl ) -benzenemeth...
1                                ( s ) -isopropyl 2
2  ( 2s3s ) -12-epoxy-3- ( boc-amino ) -4-phenylb...
</code>```

Note that you have to inform replace to use regular expression (regex=True) and I used so-called raw-string to simplify escaping, ( and ) needs to be escaped as they have special meaning in pattern, as for pattern itself I used 0 or more whitespaces (/s*) also before and after ( ) to also remove leading/trailing ones.

Title: Remove empty brackets ( ) from string

Body:
I had a problem in removing empty brackets from string, I tried few methods didn't work. kindly help

here is the dataframe

data = {'disc': ['( ) -2,4-dichloro-a- ( chloromethyl ) -benzenemethanol methanesulfonate','( ) ( s ) -isopropyl 2 ','( 2s3s ) -12-epoxy-3- ( boc-amino ) -4-phenylbutane ( ) boc-epoxideide']}
df1 = pd.DataFrame(data)
print(df1)

which have multiple occurrence of ( ) need to remove only empty brackets.

input:

      disc
0   ( ) -2,4-dichloro-a- ( chloromethyl ) -benzenemethanol methanesulfonate
1   ( ) ( s ) -isopropyl 2
2   ( 2s3s ) -12-epoxy-3- ( boc-amino ) -4-p

output:

     disc
0   -2,4-dichloro-a- ( chloromethyl ) -benzenemethanol methanesulfonate
1   ( s ) -isopropyl 2
2   ( 2s3s ) -12-epoxy-3- ( boc-amino ) -4-phenylbutane boc-epoxideide

using replace is not helping because it will remove all brackets there in the string.

Body:
pandas.DataFrame.replace does support using regex, so you can do:

import pandas as pd
data = {'disc': ['( ) -2,4-dichloro-a- ( chloromethyl ) -benzenemethanol methanesulfonate','( ) ( s ) -isopropyl 2 ','( 2s3s ) -12-epoxy-3- ( boc-amino ) -4-phenylbutane ( ) boc-epoxideide']}
df1 = pd.DataFrame(data)
df2 = df1.replace(r'\s*\(\s*\)\s*', '', regex=True)
print(df2)

Output:

                                                disc
0  -2,4-dichloro-a- ( chloromethyl ) -benzenemeth...
1                                ( s ) -isopropyl 2
2  ( 2s3s ) -12-epoxy-3- ( boc-amino ) -4-phenylb...

Note that you have to inform replace to use regular expression (regex=True) and I used so-called raw-string to simplify escaping, ( and ) needs to be escaped as they have special meaning in pattern, as for pattern itself I used 0 or more whitespaces (/s*) also before and after ( ) to also remove leading/trailing ones.


问:
Create my own commenting/Q&A system on Ruby on Rails, or just use Disqus or Intense Debate?
My site requires authentication, so it has membership. I wonder if I should create my own comment system for user to discuss/comment on an article, or should just use third-party comment system like Disqus or Intense Debate, which requires seperate account (Twitter, Facebook, etc.).

In fact, it would be good if there is a guide to create my own comment system or Q&A system for users to discuss a particular article on my website. If you know of any, please lemme know.

Thanks.

答:
I recently am working on a project where I had to weigh the same things. I eventually decided to roll my own comments.

Namely the advantage of rolling your own is that you have full control on how they work. I needed a moderation system/queue that I needed to work a specific way, for one. Second, someday I will be looking to integrate a 'community reputation' system, so that was another plus for rolling my own. Such things I don't want to leave to a third party solution outside of my control and the third parties don't always have such a flexible API to modify.

On the other hand, Disqus (or similar third party commenting systems) may be up your alley if your needs are more simple. For one, it's easy to get up and running and may be all you may really need. Accounts for it work across anything using Disqus, and that may win convenience points for your users who are sick and tired of having to sign up for a million accounts for a million websites. Disqus also has built in tools (for spam, trolls, etc) and that is also convenient.

If you go with rolling your own solution with user accounts, you can integrate things like Facebook/Twitter/etc login to make the registration process easier. But overall, like I said, depends on how fancy or complex you need the whole thing to be.

Should you roll your own, a good start is a recent Railscasts episode on the Ancestry gem http://railscasts.com/episodes/262-trees-with-ancestry, it should give you a good start on building threaded comments.


问:
Laravel Sanctum : blocked by CORS policy with Nuxt Auth module
I have a Laravel website served by Valet on backend.test and a Nuxt SPA on nuxt.backend.test:3005. When I try to authenticate to Sanctum with Nuxt Auth module, I get the CORS error below:

Access to XMLHttpRequest at 'http://backend.test/login' from origin
  'http://nuxt.backend.test:3005' has been blocked by CORS policy: No
  'Access-Control-Allow-Origin' header is present on the requested
  resource.

How can I fix it ?

Laravel configuration

config/cors.php:

```<code><?php

return [
    'paths' => ['*'],
    'allowed_methods' => ['*'],
    'allowed_origins' => ['*'],
    'allowed_origins_patterns' => [],
    'allowed_headers' => ['*'],
    'exposed_headers' => [],
    'max_age' => 0,
    'supports_credentials' => true,
];
</code>```

routes/api.php:

```<code>Route::middleware('auth:sanctum')->get('/user', function (Request $request) {
    return $request->user();
});
</code>```

app/Http/Kernel.php:

```<code>    protected $middlewareGroups = [
        ...
        'api' => [
            EnsureFrontendRequestsAreStateful::class,
            'throttle:60,1',
            \Illuminate\Routing\Middleware\SubstituteBindings::class,
        ],
    ];
</code>```

.env:

```<code>SANCTUM_STATEFUL_DOMAINS="backend.test"
SESSION_DOMAIN=".backend.test"
</code>```

Nuxt configuration
nuxt.config.js:

```<code>export default {
  server: {
    port: '3005',
    host: 'nuxt.backend.test'
  },
  ...
  modules: [
    '@nuxtjs/axios',
    '@nuxtjs/auth-next'
  ],
  axios: {
    proxy: true
  },
  proxy: {
    '/nuxt': {
      target: 'nuxt.backend.test',
      pathRewrite: { '^/nuxt': '/' }
    }
  },
  auth: {
    redirect: {
      callback: '/auth/callback'
    },
    strategies: {
      laravelSanctum: {
        provider: 'laravel/sanctum',
        url: 'http://backend.test'
      }
    }
  },
  ...
}
</code>```

pages/index.php:

```<code><template>
  <div>
    <div>
      ```{{ $auth.user }}```
    </div>
    <button @click="signIn()">Sign in</button>
  </div>
</template>

<script>
export default {
  methods: {
    signIn() {
      this.$auth.loginWith('laravelSanctum', {
        data: {
          email: 'me@home.com',
          password: '1qaz@WSX'
        }
      })
    }
  }
}
</script>
</code>```

答:
Laravel backend and Nuxt frontend have to be under the same domain, so I finally fixed it in 3 steps:

1. Add this to /etc/hosts:

```<code>127.0.0.1   nuxt.backend.test
</code>```

2. Using the beta version of @nuxt/auth:

```<code>npm remove @nuxtjs/auth
npm install @nuxtjs/auth-next @nuxtjs/axios
</code>```

In nuxt.config.js, use:

```<code>  modules: [
    '@nuxtjs/axios',
    '@nuxtjs/auth-next'
  ],
</code>```

3. Using the configuration below:

```<code>{
  axios: {
    proxy: true
  },
  proxy: {
    '/laravel': {
      target: 'http://backend.test',
      pathRewrite: { '^/laravel': '/' }
    }
  },
  auth: {
    strategies: {
      laravelSanctum: {
        provider: 'laravel/sanctum',
        url: '/laravel'
      }
    }
  }
}
</code>```

Alternatively, replacing backend.test and nuxt.backend.test by localhost and removing Nuxt server host from nuxt.config.js and then use php artisan serve instead of Valet for Laravel is fine too.

Body:
I have a Laravel website served by Valet on backend.test and a Nuxt SPA on nuxt.backend.test:3005. When I try to authenticate to Sanctum with Nuxt Auth module, I get the CORS error below:

Access to XMLHttpRequest at 'http://backend.test/login' from origin
  'http://nuxt.backend.test:3005' has been blocked by CORS policy: No
  'Access-Control-Allow-Origin' header is present on the requested
  resource.

How can I fix it ?

Laravel configuration

config/cors.php:

<?php

return [
    'paths' => ['*'],
    'allowed_methods' => ['*'],
    'allowed_origins' => ['*'],
    'allowed_origins_patterns' => [],
    'allowed_headers' => ['*'],
    'exposed_headers' => [],
    'max_age' => 0,
    'supports_credentials' => true,
];

routes/api.php:

Route::middleware('auth:sanctum')->get('/user', function (Request $request) {
    return $request->user();
});

app/Http/Kernel.php:

    protected $middlewareGroups = [
        ...
        'api' => [
            EnsureFrontendRequestsAreStateful::class,
            'throttle:60,1',
            \Illuminate\Routing\Middleware\SubstituteBindings::class,
        ],
    ];

.env:

SANCTUM_STATEFUL_DOMAINS="backend.test"
SESSION_DOMAIN=".backend.test"

Nuxt configuration
nuxt.config.js:

export default {
  server: {
    port: '3005',
    host: 'nuxt.backend.test'
  },
  ...
  modules: [
    '@nuxtjs/axios',
    '@nuxtjs/auth-next'
  ],
  axios: {
    proxy: true
  },
  proxy: {
    '/nuxt': {
      target: 'nuxt.backend.test',
      pathRewrite: { '^/nuxt': '/' }
    }
  },
  auth: {
    redirect: {
      callback: '/auth/callback'
    },
    strategies: {
      laravelSanctum: {
        provider: 'laravel/sanctum',
        url: 'http://backend.test'
      }
    }
  },
  ...
}

pages/index.php:

<template>

{{ $auth.user }}

    <button @click="signIn()">Sign in</button>

</template>

Body:
Laravel backend and Nuxt frontend have to be under the same domain, so I finally fixed it in 3 steps:

1. Add this to /etc/hosts:

127.0.0.1   nuxt.backend.test

2. Using the beta version of @nuxt/auth:

npm remove @nuxtjs/auth
npm install @nuxtjs/auth-next @nuxtjs/axios

In nuxt.config.js, use:

  modules: [
    '@nuxtjs/axios',
    '@nuxtjs/auth-next'
  ],

3. Using the configuration below:

{
  axios: {
    proxy: true
  },
  proxy: {
    '/laravel': {
      target: 'http://backend.test',
      pathRewrite: { '^/laravel': '/' }
    }
  },
  auth: {
    strategies: {
      laravelSanctum: {
        provider: 'laravel/sanctum',
        url: '/laravel'
      }
    }
  }
}

Alternatively, replacing backend.test and nuxt.backend.test by localhost and removing Nuxt server host from nuxt.config.js and then use php artisan serve instead of Valet for Laravel is fine too.


问:
Laravel collection paginate with where clause
I have a news table and i manage the read or unread flag. so I want to paginate both flags are separate without additional database queries.
My requirement is to get all the news and filter read or unread and paginate for a separate table view.
Once I try the following code but getting an error Method Illuminate\Database\Eloquent\Collection::paginate does not exist.

```<code>    $ns=News::all();
    $ns->where('read',1)->paginate(2);
    $ns->where('read',0)->paginate(2);
</code>```

I want to do that using only one DB Query.

答:
Please try to add it to helpers

```<code>function paginate($items, $perPage = 15, $page = null, $options = []) {
    $page = $page ?: (Paginator::resolveCurrentPage() ?: 1);
    $items = $items instanceof Collection ? $items : Collection::make($items);
    return new LengthAwarePaginator($items->forPage($page, $perPage), $items->count(), $perPage, $page, $options);
});
</code>```

Usage:

```<code>$ns = News::all();
$ns1 = paginate((clone $ns)->where('read', 1), 2);
$ns2 = paginate((clone $ns)->where('read', 0), 2);
</code>```

Body:
I have a news table and i manage the read or unread flag. so I want to paginate both flags are separate without additional database queries.
My requirement is to get all the news and filter read or unread and paginate for a separate table view.
Once I try the following code but getting an error Method Illuminate\Database\Eloquent\Collection::paginate does not exist.

    $ns=News::all();
    $ns->where('read',1)->paginate(2);
    $ns->where('read',0)->paginate(2);

I want to do that using only one DB Query.

Body:
Please try to add it to helpers

function paginate($items, $perPage = 15, $page = null, $options = []) {
    $page = $page ?: (Paginator::resolveCurrentPage() ?: 1);
    $items = $items instanceof Collection ? $items : Collection::make($items);
    return new LengthAwarePaginator($items->forPage($page, $perPage), $items->count(), $perPage, $page, $options);
});

Usage:

$ns = News::all();
$ns1 = paginate((clone $ns)->where('read', 1), 2);
$ns2 = paginate((clone $ns)->where('read', 0), 2);


问:
SQL Server 2008 transactional replication-Snapshot .NET error
I've setup a transactional replication (my first time) but the SQL Server Agent Job used for first snapshot keeps failing with this error:

A .NET Framework error occurred during execution of user-defined routine or aggregate "sp_scriptdropinsreconciliationproc_sqlclr":

  System.TypeInitializationException: The type initializer for 'System.Data.SqlClient.SqlConnection' threw an exception.

  ---> System.TypeInitializationException: The type initializer for 'System.Data.SqlClient.SqlConnectionFactory' threw an exception.
  ---> System.TypeInitializationException: The type initializer for 'System.Data.SqlClient.SqlPerformanceCounters' threw an exception.
  ---> System.Configuration.ConfigurationErrorsException: Configuration system failed to initialize

  ---> System.Configuration.ConfigurationErrorsException: An error occurred loading a configuration file: Access to the path 'C:\Windows\Microsoft.NET\Framework64\v2.0.50727\Config\machine.config' is denied. (C:\Windows\Microsoft.NET\Framework64\v2.0.50727\Config\machine.config)

  ---> System.UnauthorizedAccessException: Access to the path 'C:\Windows\Microsoft.NET\Framework64\v2.0.50727

I've checked the access to C:\Windows\Microsoft.NET\Framework64\v2.0.50727\Config\machine.config is fine, even double-checked by enabling auditing and confirmed.

I've also seen that a KB2840628 could create .NET issues but I don't have it installed on my server.

My environment is SQL Server 2008 running on Windows Server 2008 R2. Replication is all configured on the same server between two DBs

答: Please try with windows Authentication or change the snapshot agent run step from -DistributorSecurityMode , to -DistributorSecurityMode 0.</p>


问:
Solving cpanel errors from tracker
Hi i keep getting 3 errors that im having trouble solving or understanding with no help from my host, I have taken the step to move host due to bad service in general but would still like to know more about the errors if anyone can help. Im hoping a bigger better host will help but im aware all errors should be investigated if anyone can shed some light on these. These errors are taken from the cpanel error log and my website is a tracker.

1) File does not exist: /home/xxxx/public_html/wp-login.php
This is odd because i do not use wordpress, theres no wp plugings or any reference to wp in my code.

2) File does not exist: /home/xxxx/public_html/index.php
I get this on a few files, the index.php is there everything works, but the cpanel error log keeps bringing it up

3) Cannot allocate memory: [client xx.xx.xxx.xx:xxxxx] couldn't create child process: /usr/sbin/suphp for /home/xxxx/public_html/announce.php
I have tried changing the memory limit in php.ini & the disk usage is well under my limit

Any guidance would be very appreciated

答:
The first one is probably an indicator of the other two.

1)  This error is in your log because a hacker is poking around your site looking for common pages than can be a point of entry.  In this case, the hacker is probably looking to verify the existence of a wp-login.php file so that they can try some passwords on it.

2)  I would guess this is the same as above, but you actually have an index.html file not an index.php file.

Title: Solving cpanel errors from tracker


问:
Access variable from a different scene in Unity
I am fairly new to Unity and C# and am having some trouble. I am designing a 2d game, which has multiple levels. Each level contains a LevelManager which stores whether the level has been completed or not. They also have the DontDestroyOnLoad command in them. I want to access all the LevelManager gameObjects in my game and then store them in a level select scene. I want to use the win/lose bool to determine if the level has been completed so I can unlock the next level. To be clear, I want a way to access all the LevelManagers in my ENTIRE game and then store them as an array in a GameManager script. How do I do that?

Below is the LevelManager script which declares whether the level has been won or not.

```<code>using System.Collections;
using System.Collections.Generic;
using UnityEngine;
using UnityEngine.SceneManagement;

public class SceneController : MonoBehaviour
{
    private GameObject[] StartHouseCount;
    private GameObject[] StartDragonCount;
    private GameObject[] LiveDragonCount;
    private GameObject[] FinishedHouseCount;

    public int NumOfHouses;
    public int NumOfFinishedHouse;
    public int NumOfDragons;
    public int LiveNumOfDragons;
    public GameObject[] Players;
    public GameObject CurrentPlayer;

    [Header("Player")]
    public float RefuelRate;
    public float RepairRate;

    public GameObject canvas;
    public bool GameIsPaused = false;

    private GameObject MainPlayer;
    public bool Win = false;
    public int Level;
    // Start is called before the first frame update
    void Start()
    {
        CurrentPlayer = Players[0];
        StartHouseCount = GameObject.FindGameObjectsWithTag("House");
        StartDragonCount = GameObject.FindGameObjectsWithTag("Dragon");
        NumOfHouses = StartHouseCount.Length;
        NumOfDragons = StartDragonCount.Length;
        MainPlayer = Players[0];
    }

    // Update is called once per frame
    void Update()
    {
        GameIsPaused = canvas.GetComponent<PauseMenu>().GameIsPaused;

        LiveDragonCount = GameObject.FindGameObjectsWithTag("Dragon");
        LiveNumOfDragons = LiveDragonCount.Length;

        FinishedHouseCount = GameObject.FindGameObjectsWithTag("ThankYou");
        NumOfFinishedHouse = FinishedHouseCount.Length;

        if (Input.GetKeyDown(KeyCode.Alpha1))
        {
            CurrentPlayer = Players[0];
        }
        if (Input.GetKeyDown(KeyCode.Alpha2))
        {
            CurrentPlayer = Players[1];
        }

        if (NumOfFinishedHouse == NumOfHouses)
        {
            SceneManager.LoadScene("WinScene");
        }

        if (MainPlayer == null)
        {
            SceneManager.LoadScene("LoseScene");
        }
        if (MainPlayer.GetComponent<BasicHelicopterController>().CurrentFuel <= 0 || MainPlayer.GetComponent<BasicHelicopterController>().CurrentHealth <= 0)
        {
            SceneManager.LoadScene("LoseScene");
        }

    }
}
</code>```

答:
First, DontDestroyOnLoad is not supposed to do this - main usage for this is to implement things like unity-singleton (easy-to-use template). It means, you`ll have one instance of levelManager, not one per level.

To do it in your way, you need to load all the scenes additively, and get all the LevelManager instances. Or you can load all scenes one-by-one, getting level name and it`s isPassed value from current LevelManager. It can take a while, and its a wrong way.

The right way is to store inter-scene data in ScriptableObject models. It`s like a MonoBehaviour, but not related to scene - it just lays somewhere in project.

So, in your case, you can create ScriptableObject called LevelProgress. It will store the list of all passed levels. It will have public method LevelPassed(string levelName), as a parameter you can use anything - levels name, levels index in build, scene itself, whatever. Every time, when player passes any level, your LevelManager (remove DontDestoryOnLoad from it), which has a reference to LevelProgress scriptable object, will call LevelProgress.LevelPasses(currentLevel). And then, if you need to know, was some level passed, or not, you can just check, is LevelProgress.PassedLevels list contains this level.

Additionally, you need to implement between-sessions persistance for this scriptable object. IMO, the best way for this is to use JSONUtility to convert ScriptableObject into JSON string, and then write it to PlayerPrefs.

Body:
I am fairly new to Unity and C# and am having some trouble. I am designing a 2d game, which has multiple levels. Each level contains a LevelManager which stores whether the level has been completed or not. They also have the DontDestroyOnLoad command in them. I want to access all the LevelManager gameObjects in my game and then store them in a level select scene. I want to use the win/lose bool to determine if the level has been completed so I can unlock the next level. To be clear, I want a way to access all the LevelManagers in my ENTIRE game and then store them as an array in a GameManager script. How do I do that?

Below is the LevelManager script which declares whether the level has been won or not.

using System.Collections;
using System.Collections.Generic;
using UnityEngine;
using UnityEngine.SceneManagement;

public class SceneController : MonoBehaviour
{
    private GameObject[] StartHouseCount;
    private GameObject[] StartDragonCount;
    private GameObject[] LiveDragonCount;
    private GameObject[] FinishedHouseCount;

    public int NumOfHouses;
    public int NumOfFinishedHouse;
    public int NumOfDragons;
    public int LiveNumOfDragons;
    public GameObject[] Players;
    public GameObject CurrentPlayer;

    [Header("Player")]
    public float RefuelRate;
    public float RepairRate;

    public GameObject canvas;
    public bool GameIsPaused = false;

    private GameObject MainPlayer;
    public bool Win = false;
    public int Level;
    // Start is called before the first frame update
    void Start()
    {
        CurrentPlayer = Players[0];
        StartHouseCount = GameObject.FindGameObjectsWithTag("House");
        StartDragonCount = GameObject.FindGameObjectsWithTag("Dragon");
        NumOfHouses = StartHouseCount.Length;
        NumOfDragons = StartDragonCount.Length;
        MainPlayer = Players[0];
    }

    // Update is called once per frame
    void Update()
    {
        GameIsPaused = canvas.GetComponent<PauseMenu>().GameIsPaused;

        LiveDragonCount = GameObject.FindGameObjectsWithTag("Dragon");
        LiveNumOfDragons = LiveDragonCount.Length;

        FinishedHouseCount = GameObject.FindGameObjectsWithTag("ThankYou");
        NumOfFinishedHouse = FinishedHouseCount.Length;

        if (Input.GetKeyDown(KeyCode.Alpha1))
        {
            CurrentPlayer = Players[0];
        }
        if (Input.GetKeyDown(KeyCode.Alpha2))
        {
            CurrentPlayer = Players[1];
        }

        if (NumOfFinishedHouse == NumOfHouses)
        {
            SceneManager.LoadScene("WinScene");
        }

        if (MainPlayer == null)
        {
            SceneManager.LoadScene("LoseScene");
        }
        if (MainPlayer.GetComponent<BasicHelicopterController>().CurrentFuel <= 0 || MainPlayer.GetComponent<BasicHelicopterController>().CurrentHealth <= 0)
        {
            SceneManager.LoadScene("LoseScene");
        }

    }
}


问:
laravel 7 calling a method function for delete a file
i tried now long enough how i call the delete function from my mediacontroller in my media index.blade. I dont get it. So if someone of you give me a tipp please answer! I would really appreciate it!

Thats my media index.blade.php:

```<code><div class="container">

    <div class="row">
        <div class="col-4">

            <div class="card">
                <div class="card-header">
                    <h3>Upload</h3>
                </div>
                <div class="card-body">
                    <form method="post" enctype="multipart/form-data" action="{{"upload"}}">
                        @csrf
                        <div class="input-group">

                            <div class="custom-file">
                                <input type="file" class="custom-file-input" id="media"
                                       aria-describedby="media" name="file">
                                <label class="custom-file-label" for="media">Datei auswählen</label>
                            </div>
                        </div>
                        @error('file')
                        <div class="alert alert-danger">{{ $message }}</div>
                        @enderror
                        <hr/>
                        <button class="btn btn-success">Hochladen</button>
                    </form>
                </div>

            </div>

        </div>
        <div class="col-8">
            <div class="card">
                <div class="card-header">
                    <h1>Media</h1>
                    @if (session('status'))
                        <div class="alert alert-success" role="alert">
                            {{ session('status') }}
                        </div>
                    @endif
                </div>
                <div class="card-body">

                    <form action="{{route('media.index')}}" method="GET" role="search">
                        {{ csrf_field() }}
                        <div class="input-group">
                            <input type="text" class="form-control" name="q" value="{{request()->input("q")}}"
                                   placeholder="Suche...">
                            <span class="input-group-btn">
                                <button type="submit" class="btn btn-light">
                                    <span class="fa  fa-search"></span>
                                </button>
                            </span>
                        </div>
                    </form>
                    <br/>
                    @if($medias->count() > 0 )

                        <table class="table table-bordered table-hover">
                            <thead>
                            <th>ID</th>
                            <th>Dateiname</th>
                            <th>Extension</th>
                            <th>Größe</th>
                            <th>Preview</th>
                            </thead>
                            <tbody>
                            @foreach($medias as $media)
                                <tr>

                                    <td>{{$media->id}}</td>
                                    <td>{{$media->name}}</td>
                                    <td>{{$media->extension}}</td>
                                    <td>{{$media->size}}</td>

                                    <td><a href="{{route('media', $media->id)}}">
                                            @if(in_array($media->extension, ["jpg", "jpeg", "bpm", "png", "gif"]))
                                                <img src="{{route("media", $media->id)}}" width="150"/>
                                            @else
                                                @switch($media->extension)
                                                    @case("pdf")
                                                    <i class="fa fa-file-pdf"></i>

                                                    @break

                                                    @case("xsls")
                                                    <i class="fa fa-file-excel"></i>

                                                    @break

                                                    @case("doc")
                                                    <i class="fa fa-file-word"></i>

                                                    @break

                                                    @case("docx")
                                                    <i class="fa fa-file-word"></i>

                                                    @break

                                                    @case("svg")
                                                    <i class="fa fa-vector-square"></i>

                                                    @break

                                                @endswitch
                                            @endif
                                        </a></td>
                                    </td>
                                    <td><a href="{{ route('media.delete', [$media->id]) }}" class="btn btn-danger"> <i class="fa fa-trash"></i></a>
                                    </td>
                                </tr>
                            @endforeach
                            </tbody>
                        </table>
                    @else
                        <h4>Es wurden keine Daten gefunden</h4>
                    @endif
                    {{$medias->links()}}
                </div>
            </div>
        </div>
    </div>
</div>
</code>```

now my web.php with the routes:

```<code>Route::resource("kitas", "KitaController");
Route::resource("users", "UserController");
Route::resource("posts", "PostController");
Route::post("/upload", "MediaController@upload")->name("upload");
Route::get("media", "MediaController@index")->name("media.index");
Route::get("media/{id}/delete", "MediaController@index")->name("media.delete");
Route::get("/media/{id}", "MediaController@download")->name("media");
Route::get("/media/{id}/preview", "MediaController@preview")->name("media.preview");
</code>```

and now my MediaController:

```<code>class MediaController extends Controller

public function index() {

    $q = request()->input("q");
    if($q) {
        $medias=    Media::where('name','LIKE','%'.$q.'%')->orderByDesc('created_at')->paginate(10);
    }else {
        $medias = Media::orderByDesc('created_at')->paginate(10);
    }

    return view("media.index")->with(["medias" => $medias]);
}

public function upload( Request $request)
{
    $request->validate([
        "file" => "required"
    ]);
    $name = $request->file("file")->getClientOriginalName();
    $extension = $request->file("file")->getClientOriginalExtension();
    $size = $request->file("file")->getSize();
    $path = $request->file("file")->store("public/media");
   Media::create([
       "name" => $name,
       "extension" => $extension,
       "size" => $size,
       "path" => $path
   ]);
   return redirect()->route("media.index")->withStatus("Datei wurde erfolgreich hochgeladen!");

}

public function download($id)
{
    $media = Media::find($id);
    $file = storage_path(). "/app/". $media->path;
   return response()->file($file);
}

public function preview($id)
{
    $media = Media::whereIn('extension', ["jpg", "png", "gif", "bmp"])->where("id", "=", $id)->first();
    $file = storage_path(). "/app/". $media->path;
    $preview = Image::make($file)->resize(200, 200);
    return $preview->response();
}

public function delete($id)
{
    $media = Media::find($id);
    $media -> delete();
}
</code>```

I can click the delete buttons on the website, but nothing happens.

I cant find the solution. or work it out for myself. the sheer amount of different ways you can solve things with coding drives me nuts. I try to code now for like 9 months and i just get slowly forward, since Iam more used to have one solution to get to the goal not 500 differnt ones. Makes me a bit upset to get behind all the stuff.

Do you have also tipps how to learn to code from zero to hero?

thanks!

Pommesfee

答:
SO, thats my delete route:

```<code>Route::get("media/{id}/delete", "MediaController@index")->name("media.delete");
</code>```

and that would be the button to delete the image?

```<code><form action="{{ route('media.delete', [$media->id]) }} method="DELETE">
      @method('DELETE')
      @csrf
</form>
</code>```

I dont get behind about that and how to transfer it to my needs.

Body:
i tried now long enough how i call the delete function from my mediacontroller in my media index.blade. I dont get it. So if someone of you give me a tipp please answer! I would really appreciate it!

Thats my media index.blade.php:

Upload

                    <form method="post" enctype="multipart/form-data" action="{{"upload"}}">
                        @csrf

                                <input type="file" class="custom-file-input" id="media"
                                       aria-describedby="media" name="file">
                                Datei auswählen

                        @error('file')

{{ $message }}

                        @enderror

                        <button class="btn btn-success">Hochladen</button>
                    </form>

Media

                    @if (session('status'))

                            {{ session('status') }}

                    @endif

                    <form action="{{route('media.index')}}" method="GET" role="search">
                        {{ csrf_field() }}

                            <input type="text" class="form-control" name="q" value="{{request()->input("q")}}"
                                   placeholder="Suche...">

                                <button type="submit" class="btn btn-light">

                                </button>

                    </form>

                    @if($medias->count() > 0 )

                            ID
                            Dateiname
                            Extension
                            Größe
                            Preview

                            @foreach($medias as $media)

                                    {{$media->id}}
                                    {{$media->name}}
                                    {{$media->extension}}
                                    {{$media->size}}

                                    id)}}">
                                            @if(in_array($media->extension, ["jpg", "jpeg", "bpm", "png", "gif"]))
                                                id)}}" width="150"/>
                                            @else
                                                @switch($media->extension)
                                                    @case("pdf")

                                                    @break

                                                    @case("xsls")

                                                    @break

                                                    @case("doc")

                                                    @break

                                                    @case("docx")

                                                    @break

                                                    @case("svg")

                                                    @break

                                                @endswitch
                                            @endif

                                    id]) }}" class="btn btn-danger">

                            @endforeach

                    @else

Es wurden keine Daten gefunden

                    @endif
                    {{$medias->links()}}

now my web.php with the routes:

Route::resource("kitas", "KitaController");
Route::resource("users", "UserController");
Route::resource("posts", "PostController");
Route::post("/upload", "MediaController@upload")->name("upload");
Route::get("media", "MediaController@index")->name("media.index");
Route::get("media/{id}/delete", "MediaController@index")->name("media.delete");
Route::get("/media/{id}", "MediaController@download")->name("media");
Route::get("/media/{id}/preview", "MediaController@preview")->name("media.preview");

and now my MediaController:

class MediaController extends Controller

public function index() {

    $q = request()->input("q");
    if($q) {
        $medias=    Media::where('name','LIKE','%'.$q.'%')->orderByDesc('created_at')->paginate(10);
    }else {
        $medias = Media::orderByDesc('created_at')->paginate(10);
    }

    return view("media.index")->with(["medias" => $medias]);
}

public function upload( Request $request)
{
    $request->validate([
        "file" => "required"
    ]);
    $name = $request->file("file")->getClientOriginalName();
    $extension = $request->file("file")->getClientOriginalExtension();
    $size = $request->file("file")->getSize();
    $path = $request->file("file")->store("public/media");
   Media::create([
       "name" => $name,
       "extension" => $extension,
       "size" => $size,
       "path" => $path
   ]);
   return redirect()->route("media.index")->withStatus("Datei wurde erfolgreich hochgeladen!");

}

public function download($id)
{
    $media = Media::find($id);
    $file = storage_path(). "/app/". $media->path;
   return response()->file($file);
}

public function preview($id)
{
    $media = Media::whereIn('extension', ["jpg", "png", "gif", "bmp"])->where("id", "=", $id)->first();
    $file = storage_path(). "/app/". $media->path;
    $preview = Image::make($file)->resize(200, 200);
    return $preview->response();
}

public function delete($id)
{
    $media = Media::find($id);
    $media -> delete();
}

I can click the delete buttons on the website, but nothing happens.

I cant find the solution. or work it out for myself. the sheer amount of different ways you can solve things with coding drives me nuts. I try to code now for like 9 months and i just get slowly forward, since Iam more used to have one solution to get to the goal not 500 differnt ones. Makes me a bit upset to get behind all the stuff.

Do you have also tipps how to learn to code from zero to hero?

thanks!

Pommesfee

Body:
SO, thats my delete route:

Route::get("media/{id}/delete", "MediaController@index")->name("media.delete");

and that would be the button to delete the image?

<form action="{{ route('media.delete', [$media->id]) }} method="DELETE">
      @method('DELETE')
      @csrf
</form>

I dont get behind about that and how to transfer it to my needs.


问:
How can I read Adafruit INA 219 in LabVIEW? How can I get Serial Data from Arduino using LabVIEW?
I try to read voltage and current from an Adafruit INA 219 sensor with Arduino and I get the correct results. The problem is that I need the results for analyzing them and I need to read the sensor's values in LabVIEW or to send the results from the Arduino to Labview.

Arduino code:

```<code>#include <Wire.h>
#include <Adafruit_INA219.h>

Adafruit_INA219 ina219;

void setup(void)
{
  Serial.begin(115200);
  while (!Serial) {
      // will pause Zero, Leonardo, etc until serial console opens
      delay(1);
  }

  uint32_t currentFrequency;

  Serial.println("Hello!");

  // Initialize the INA219.
  // By default the initialization will use the largest range (32V, 2A).  However
  // you can call a setCalibration function to change this range (see comments).
  ina219.begin();
  // To use a slightly lower 32V, 1A range (higher precision on amps):
  //ina219.setCalibration_32V_1A();
  // Or to use a lower 16V, 400mA range (higher precision on volts and amps):
  //ina219.setCalibration_16V_400mA();

  Serial.println("Measuring voltage and current with INA219 ...");
}

void loop(void)
{
  float shuntvoltage = 0;
  float busvoltage = 0;
  float current_mA = 0;
  float loadvoltage = 0;

  shuntvoltage = ina219.getShuntVoltage_mV();
  busvoltage = ina219.getBusVoltage_V();
  current_mA = ina219.getCurrent_mA();
  loadvoltage = busvoltage + (shuntvoltage / 1000);

  Serial.print("Bus Voltage:   "); Serial.print(busvoltage); Serial.println(" V");
  //Serial.print("Shunt Voltage: "); Serial.print(shuntvoltage); Serial.println(" mV");
  Serial.print("Load Voltage:  "); Serial.print(loadvoltage); Serial.println(" V");
  Serial.print("Current:       "); Serial.print(current_mA); Serial.println(" mA");
  Serial.println("");

  delay(500);
}
</code>```

Try to read Adafruit INA 219 with LabVIEW

答:
Currently your values are being read by the Arduino and sent as strings to the Serial port.

If you want to use that format to communicate with LabVIEW, then you don't need to use the LINX toolkit - you can just use the Serial port via the VISA nodes.

You'd then need to convert the strings to numeric values to be able to do something 'useful' with them probably. You could try using something like Match Pattern or Match Regular Expression.

Something like this is probably what you're looking for:

As an aside, although I like StackOverflow in general, for LabVIEW related questions you'll probably get a faster response on forums.ni.com (and less likely to be closed as discussion-related, or duplicate).

Body:
I try to read voltage and current from an Adafruit INA 219 sensor with Arduino and I get the correct results. The problem is that I need the results for analyzing them and I need to read the sensor's values in LabVIEW or to send the results from the Arduino to Labview.

Arduino code:

#include <Wire.h>
#include <Adafruit_INA219.h>

Adafruit_INA219 ina219;

void setup(void)
{
  Serial.begin(115200);
  while (!Serial) {
      // will pause Zero, Leonardo, etc until serial console opens
      delay(1);
  }

  uint32_t currentFrequency;

  Serial.println("Hello!");

  // Initialize the INA219.
  // By default the initialization will use the largest range (32V, 2A).  However
  // you can call a setCalibration function to change this range (see comments).
  ina219.begin();
  // To use a slightly lower 32V, 1A range (higher precision on amps):
  //ina219.setCalibration_32V_1A();
  // Or to use a lower 16V, 400mA range (higher precision on volts and amps):
  //ina219.setCalibration_16V_400mA();

  Serial.println("Measuring voltage and current with INA219 ...");
}

void loop(void)
{
  float shuntvoltage = 0;
  float busvoltage = 0;
  float current_mA = 0;
  float loadvoltage = 0;

  shuntvoltage = ina219.getShuntVoltage_mV();
  busvoltage = ina219.getBusVoltage_V();
  current_mA = ina219.getCurrent_mA();
  loadvoltage = busvoltage + (shuntvoltage / 1000);

  Serial.print("Bus Voltage:   "); Serial.print(busvoltage); Serial.println(" V");
  //Serial.print("Shunt Voltage: "); Serial.print(shuntvoltage); Serial.println(" mV");
  Serial.print("Load Voltage:  "); Serial.print(loadvoltage); Serial.println(" V");
  Serial.print("Current:       "); Serial.print(current_mA); Serial.println(" mA");
  Serial.println("");

  delay(500);
}

Try to read Adafruit INA 219 with LabVIEW


问:
How to create a dictionary app in React-Native?
What are the options/approaches available in React-Native for developing a mobile dictionary app.</p>

答:
its depend to word count if it is to large i recommend to using a react-native db package like

https://github.com/Nozbe/WatermelonDB
or
https://github.com/realm/realm-js


问:
How do I add a stylesheet to an iFrame from the parent, using javascript?
my JSFiddle: http://jsfiddle.net/gCRuk/1/

HTML:

```<code>My replays on SC-Replay.com:<br>
<iframe frameborder="0" name="frame" id="frame1" src="http://www.sc-replay.com/embedPlayer/21368-TheLindyHop.html" style="left: 0pt; position: relative; top: 0pt; width: 980px; height: 500px; border: 0px solid #00214E;" n="" vspace="0" marginheight="0" marginwidth="0" hspace="0" allowtransparency="true"></iframe>
</code>```

Javascript:

```<code>var ss = document.createElement("link");
ss.type = "text/css";
ss.rel = "stylesheet";
ss.href = "http://www.lprestonsegoiii.com/WordPress/wp-content/themes/arjuna-x/style.css";

var iframe;
if(document.frames)
    iframe = document.frames["frame"];
else
    iframe = window.frames["frame"];
if(document.all)
    iframe.document.createStyleSheet(ss.href);
else
    iframe.document.getElementsByTagName("head")[0].appendChild(ss);
</code>```

I followed this guide: http://www.geekdaily.net/2007/09/19/javascript-adding-a-stylesheet-to-an-iframe/

And I'm not really sure what is happening here / what is going wrong.

答:
Generally speaking, you can't do that cross-domain due to JavaScript's Same Origin Policy.

It's possible if the iframe page, container page and the CSS file are all served from the same domain, which is what is assumed (but unfortunately not mentioned!) in the tutorial on GeekDaily.

Body:
my JSFiddle: http://jsfiddle.net/gCRuk/1/

HTML:

My replays on SC-Replay.com:

Javascript:

var ss = document.createElement("link");
ss.type = "text/css";
ss.rel = "stylesheet";
ss.href = "http://www.lprestonsegoiii.com/WordPress/wp-content/themes/arjuna-x/style.css";

var iframe;
if(document.frames)
    iframe = document.frames["frame"];
else
    iframe = window.frames["frame"];
if(document.all)
    iframe.document.createStyleSheet(ss.href);
else
    iframe.document.getElementsByTagName("head")[0].appendChild(ss);

I followed this guide: http://www.geekdaily.net/2007/09/19/javascript-adding-a-stylesheet-to-an-iframe/

And I'm not really sure what is happening here / what is going wrong.