问:
Xcode building while device is connected but not archiving
I am trying to build the project using this as basis :
GitHub code

but it is giving me error when i am trying to archive the project, while running it directly on device is okay. If i turn bitcode to off it makes the build but exit with some error on the iphone because dlib library is not being added needed for detection.

```<code>ld: bitcode bundle could not be generated because 'path/lib/libdlib.a(threads_kernel_shared.o)' was built without full bitcode. All object files and libraries for bitcode must be generated from Xcode Archive or Install build for architecture arm64
clang: error: linker command failed with exit code 1 (use -v to see invocation)
</code>```

I can see there is some problem in generation of dlib library but have no idea how to solve it up.
If anyone can guide me through it, i will be really thankful for the guidance. Thank you.

答:
Try this - Worked for me

Goto Build Settings -> Enable Bitcode -> Select 'No'

And Archive with Generic Device selected.

Body:
I am trying to build the project using this as basis :
GitHub code

but it is giving me error when i am trying to archive the project, while running it directly on device is okay. If i turn bitcode to off it makes the build but exit with some error on the iphone because dlib library is not being added needed for detection.

ld: bitcode bundle could not be generated because 'path/lib/libdlib.a(threads_kernel_shared.o)' was built without full bitcode. All object files and libraries for bitcode must be generated from Xcode Archive or Install build for architecture arm64
clang: error: linker command failed with exit code 1 (use -v to see invocation)

I can see there is some problem in generation of dlib library but have no idea how to solve it up.
If anyone can guide me through it, i will be really thankful for the guidance. Thank you.


来源: stackexchange

问:
display yes / no instead of bool true false in results C#
I have been trying to figure out how to display yes / no instead of a bool result of true / false to make this easier to read for my users.

I am using c# and visual studio 2015 and I have taken a look and try to apply some of the techniques noted here in stackoverflow
here and here.

Im not to sure which is the best way to resolve the query that I have.  In a nutshell I have a database table that holds 3 columns with bit datatypes (eg. A, B & C).  This table is the fed through the use of entity framework to my MVC project.

The model associated with this table holds these columns as bool.  I an using this table to list items in the database, however the results for these items display True / False to the user (see image below).

I have tried to change my Razor code to complete this task but have failed.

```<code>@item.AttachmentA.isTrue?"Yes":"No")
</code>```

And I have also tried this,

```<code>@Html.DisplayFor(modelItem => item.AttachmentA.isTrue?"Yes":"No")
</code>```

For both above, I'm getting compilation error that states,

'System.Nullable' does not contain a definition for 'isTrue' and no extension method 'isTrue' accepting a first argument of type 'System.Nullable' could be found (are you missing a using directive or an assembly reference?)

I cant quite seem to get the above working.  Would I be able to complete an if statement in my controller to complete this?

I have tried to complete this with something like the following code but this doesn't seem to work.

```<code>// GET: View for ACTIVE items and set status of the bool for true / false
public ActionResult Active()
{
    List<vwStatusActive> clientRecordsActive = db.vwStatusActives.ToList();

    foreach (vwStatusActive active in clientRecordsActive)
    {
        if (vwStatusActive == true)
        {
            vwStatusActive = 'Yes';
        }
        else
        {
            vwStatusActive = 'No';
        }
    }

    return View(clientRecordsActive);
}
</code>```

I have changed the above if statement in the controller to now hold variables for the bool true / false.

```<code>      // GET: View for ACTIVE items and set status of the bool for true / false
    public ActionResult Active()
    {
        List<vwStatusActive> clientRecordsActive = db.vwStatusActives.ToList();

        bool t = true;
        bool f = false;

        foreach (vwStatusActive active in clientRecordsActive)
        {
            if (t == true)
            {
                t = "Yes";
            }
            else
            {
                t = "No";
            }

        }

        return View(clientRecordsActive);
    }
</code>```

I now however get two error for the string items "Yes", "No" that state,

Cannot implicitly convert type 'string' to 'bool

If anyone has any suggestions on best practices, can you please advise?

答:
If AttachmentA property is of type bool then use

@(item.AttachmentA ? "Yes":"No")

OR

@{var isAttachmentA = (item.AttachmentA  ? "Yes" : "No");}
@Html.DisplayFor(modelItem => isAttachmentA )

If AttachmentA property is of type bool? (Nullable bool) then use

@(item.AttachmentA.GetValueOrDefault() ? "Yes":"No")

OR

@{var isAttachmentA = (item.AttachmentA.GetValueOrDefault()  ? "Yes" : "No");}
@Html.DisplayFor(modelItem => isAttachmentA )

ContentLicense: CC BY-SA 3.0

Body:
I have been trying to figure out how to display yes / no instead of a bool result of true / false to make this easier to read for my users.

I am using c# and visual studio 2015 and I have taken a look and try to apply some of the techniques noted here in stackoverflow
here and here.

Im not to sure which is the best way to resolve the query that I have.  In a nutshell I have a database table that holds 3 columns with bit datatypes (eg. A, B & C).  This table is the fed through the use of entity framework to my MVC project.

The model associated with this table holds these columns as bool.  I an using this table to list items in the database, however the results for these items display True / False to the user (see image below).

I have tried to change my Razor code to complete this task but have failed.

@item.AttachmentA.isTrue?"Yes":"No")

And I have also tried this,

@Html.DisplayFor(modelItem => item.AttachmentA.isTrue?"Yes":"No")

For both above, I'm getting compilation error that states,

'System.Nullable' does not contain a definition for 'isTrue' and no extension method 'isTrue' accepting a first argument of type 'System.Nullable' could be found (are you missing a using directive or an assembly reference?)

I cant quite seem to get the above working.  Would I be able to complete an if statement in my controller to complete this?

I have tried to complete this with something like the following code but this doesn't seem to work.

// GET: View for ACTIVE items and set status of the bool for true / false
public ActionResult Active()
{
    List<vwStatusActive> clientRecordsActive = db.vwStatusActives.ToList();

    foreach (vwStatusActive active in clientRecordsActive)
    {
        if (vwStatusActive == true)
        {
            vwStatusActive = 'Yes';
        }
        else
        {
            vwStatusActive = 'No';
        }
    }

    return View(clientRecordsActive);
}

I have changed the above if statement in the controller to now hold variables for the bool true / false.

      // GET: View for ACTIVE items and set status of the bool for true / false
    public ActionResult Active()
    {
        List<vwStatusActive> clientRecordsActive = db.vwStatusActives.ToList();

        bool t = true;
        bool f = false;

        foreach (vwStatusActive active in clientRecordsActive)
        {
            if (t == true)
            {
                t = "Yes";
            }
            else
            {
                t = "No";
            }

        }

        return View(clientRecordsActive);
    }

I now however get two error for the string items "Yes", "No" that state,

Cannot implicitly convert type 'string' to 'bool

If anyone has any suggestions on best practices, can you please advise?


问:
Syntax Error: line 0, col 95: Error: Expected Literal, got ''
I get this a [Syntax Error] line 0, col 95: Error: Expected Literal, got 'value' error when I try to  execute the following query:

```<code>    $qb = $this->createQueryBuilder('a');
    $qb
       ->join('a.categories', 'cat')
       ->where($qb->expr()->in('cat.name', $category));
    return $qb->getQuery()->getResult();
</code>```

The mapped field is as followed:

```<code>/**
 * @ORM\ManyToMany(targetEntity="Camten\TestBundle\Entity\Category", cascade={"persist"}, inversedBy="articles")
 */
 private $categories;
</code>```

Thought it was a problem with the data type but I really can't find what's wrong.

答:
You have to use setParameter() to bind parameter to dql variables
See below,

```<code>qb = $this->createQueryBuilder('a');

$qb
   ->join('a.categories', 'cat')
   ->where('cat.name = :nameParam')
   ->setParameter('nameParam', $category);
return $qb->getQuery()->getResult();
</code>```

(I named it nameParam to show it has nothing to do with cat.name)

If you want to use the $qb->expr()->* methods you should use eq() and not in()

```<code>qb = $this->createQueryBuilder('a');

$qb
   ->join('a.categories', 'cat')
   ->where($qb->expr()->eq('cat.name',':nameParam'))
   ->setParameter('nameParam', $category);
return $qb->getQuery()->getResult();
</code>```

Body:
I get this a [Syntax Error] line 0, col 95: Error: Expected Literal, got 'value' error when I try to  execute the following query:

    $qb = $this->createQueryBuilder('a');
    $qb
       ->join('a.categories', 'cat')
       ->where($qb->expr()->in('cat.name', $category));
    return $qb->getQuery()->getResult();

The mapped field is as followed:

/**
 * @ORM\ManyToMany(targetEntity="Camten\TestBundle\Entity\Category", cascade={"persist"}, inversedBy="articles")
 */
 private $categories;

Thought it was a problem with the data type but I really can't find what's wrong.

Body:
You have to use setParameter() to bind parameter to dql variables
See below,

qb = $this->createQueryBuilder('a');

$qb
   ->join('a.categories', 'cat')
   ->where('cat.name = :nameParam')
   ->setParameter('nameParam', $category);
return $qb->getQuery()->getResult();

(I named it nameParam to show it has nothing to do with cat.name)

If you want to use the $qb->expr()->* methods you should use eq() and not in()

qb = $this->createQueryBuilder('a');

$qb
   ->join('a.categories', 'cat')
   ->where($qb->expr()->eq('cat.name',':nameParam'))
   ->setParameter('nameParam', $category);
return $qb->getQuery()->getResult();


问:
Using JDBC in setup for a Jmeter Junit test
I was trying to use the JDBC to connect to my MySQL database in the setup and teardown methods of my Junit tests that are being run through Jmeter. Jmeter will create multiple threads, each of which will run one instance of my test. </p>

<p>The issue that I run into, is if I instantiate my datasource in the setup of my Junit test, then my connection pool runs out of connections. Is there a way to design my test so that this does not happen? I'm trying to avoid increasing my max MySQL connections to solve this issue. </p>

答:
A couple suggestions:

If possible use mocks or a mocking framework like mockito.

Use connection pooling if you're not already - this might alleviate the overhead of having more connections that you need.

ContentLicense: CC BY-SA 2.5

Body:
I was trying to use the JDBC to connect to my MySQL database in the setup and teardown methods of my Junit tests that are being run through Jmeter. Jmeter will create multiple threads, each of which will run one instance of my test.

The issue that I run into, is if I instantiate my datasource in the setup of my Junit test, then my connection pool runs out of connections. Is there a way to design my test so that this does not happen? I'm trying to avoid increasing my max MySQL connections to solve this issue.


问:
Difference in function performance between calling manually ('=') or through macros
I wrote a lookup function. Its performance differs dramatically depending whether or not I call it by hand on worksheet itself (through '=') or through macros.

My macro does the following:

```<code>Function betterSearch(searchCell As Range, aCol As Range, bCol As Range)
    For Each cell In aCol
        If LCase(cell.Value) = LCase(searchCell.Value) Then
            betterSearch = bCol.Cells(cell.row, 1)
            Exit For
        End If
        betterSearch = "Not found"
    Next
End Function
</code>```

The macro opens resultsWorkbook and dataWorkbook and then performs a search of the four values in column A from resultWorkbook in dataWorkbook and returns corresponding data from some other column of dataWorkbook.

```<code>'...opening resultWorkbook and dataWorkbook
For aRow = 6 To 9
    resultWorkbook.Worksheets("B3").Cells(aRow, 125).Value = _
            betterSearch(resultWorkbook.Worksheets("B3").Cells(aRow, 1) _
            , dataWorkbook.Worksheets("page 1").Range("A:A") _
            , dataWorkbook.Worksheets("page 1").Range("Z:Z"))

         resultWorkbook.Worksheets("B3").Cells(aRow, 126).Value = _
            betterSearch(resultWorkbook.Worksheets("B3").Cells(aRow, 1) _
            , dataWorkbook.Worksheets("page 1").Range("A:A") _
            , dataWorkbook.Worksheets("page 1").Range("I:I"))
Next aRow
</code>```

It's really slow - takes minutes for 1 file. But when I open that file manually and type in the formula and hit Enter it calculates instantly (so in that regard my function doesn't need optimizing - it already calculates fast but just in the worksheet, not inside the macros).

I'm not looking to optimize the function. I want to understand why this difference in performance happens. I have Application.Calculation = xlCalculationManual both for the main application and invisible application that runs along and does all the work:  ExcelApp.Calculation = xlCalculationManual and it seems to be changing the workbooks' states to manual but the slow performance is there as if the workbooks were still automatic.

答:
You can use the Find function, and use the MatchCase:=False so it will be case-insensitive.

It will be much faster than looping through your Column.

Code

```<code>Function betterSearch(searchCell As Range, aCol As Range, bCol As Range) As String

    Dim FndRng  As Range

    Set FndRng = aCol.Find(what:=LCase(searchCell.Value), LookIn:=xlValues, lookat:=xlWhole, _
                            searchorder:=xlRows, searchdirection:=xlNext, MatchCase:=False)
    If Not FndRng Is Nothing Then ' Find was successful
        betterSearch = bCol.Cells(FndRng.Row, 1)
    Else
        betterSearch = "Not found"
    End If

End Function
</code>```

ContentLicense: CC BY-SA 4.0

Body:
I wrote a lookup function. Its performance differs dramatically depending whether or not I call it by hand on worksheet itself (through '=') or through macros.

My macro does the following:

Function betterSearch(searchCell As Range, aCol As Range, bCol As Range)
    For Each cell In aCol
        If LCase(cell.Value) = LCase(searchCell.Value) Then
            betterSearch = bCol.Cells(cell.row, 1)
            Exit For
        End If
        betterSearch = "Not found"
    Next
End Function

The macro opens resultsWorkbook and dataWorkbook and then performs a search of the four values in column A from resultWorkbook in dataWorkbook and returns corresponding data from some other column of dataWorkbook.

'...opening resultWorkbook and dataWorkbook
For aRow = 6 To 9
    resultWorkbook.Worksheets("B3").Cells(aRow, 125).Value = _
            betterSearch(resultWorkbook.Worksheets("B3").Cells(aRow, 1) _
            , dataWorkbook.Worksheets("page 1").Range("A:A") _
            , dataWorkbook.Worksheets("page 1").Range("Z:Z"))

         resultWorkbook.Worksheets("B3").Cells(aRow, 126).Value = _
            betterSearch(resultWorkbook.Worksheets("B3").Cells(aRow, 1) _
            , dataWorkbook.Worksheets("page 1").Range("A:A") _
            , dataWorkbook.Worksheets("page 1").Range("I:I"))
Next aRow

It's really slow - takes minutes for 1 file. But when I open that file manually and type in the formula and hit Enter it calculates instantly (so in that regard my function doesn't need optimizing - it already calculates fast but just in the worksheet, not inside the macros).

I'm not looking to optimize the function. I want to understand why this difference in performance happens. I have Application.Calculation = xlCalculationManual both for the main application and invisible application that runs along and does all the work:  ExcelApp.Calculation = xlCalculationManual and it seems to be changing the workbooks' states to manual but the slow performance is there as if the workbooks were still automatic.

Body:
You can use the Find function, and use the MatchCase:=False so it will be case-insensitive.

It will be much faster than looping through your Column.

Code

Function betterSearch(searchCell As Range, aCol As Range, bCol As Range) As String

    Dim FndRng  As Range

    Set FndRng = aCol.Find(what:=LCase(searchCell.Value), LookIn:=xlValues, lookat:=xlWhole, _
                            searchorder:=xlRows, searchdirection:=xlNext, MatchCase:=False)
    If Not FndRng Is Nothing Then ' Find was successful
        betterSearch = bCol.Cells(FndRng.Row, 1)
    Else
        betterSearch = "Not found"
    End If

End Function


问:
Search Numpy array with multiple values
I have numpy 2d array having duplicate values.

I am searching the array like this.

```<code>In [104]: import numpy as np

In [105]: array = np.array

In [106]: a = array([[1, 2, 3],
     ...:            [1, 2, 3],
     ...:            [2, 5, 6],
     ...:            [3, 8, 9],
     ...:            [4, 8, 9],
     ...:            [4, 2, 3],
     ...:            [5, 2, 3])

In [107]: num_list = [1, 4, 5]

In [108]: for i in num_list :
     ...:     print(a[np.where(a[:,0] == num_list)])
     ...:
 [[1 2 3]
 [1 2 3]]
[[4 8 9]
 [4 2 3]]
[[5 2 3]]
</code>```

The input is list having number similar to column 0 values.
The end result I want is the resulting rows in any format like array, list or tuple for example

```<code>array([[1, 2, 3],
       [1, 2, 3],
       [4, 8, 9],
       [4, 2, 3],
       [5, 2, 3]])
</code>```

My code works fine but doesn't seem pythonic. Is there any better searching strategy with multiple values?

like a[np.where(a[:,0] == l)] where only one time lookup is done to get all the values.

my real array is large

答:
Approach #1 : Using np.in1d -

```<code>a[np.in1d(a[:,0], num_list)]
</code>```

Approach #2 : Using np.searchsorted -

```<code>num_arr = np.sort(num_list) # Sort num_list and get as array

# Get indices of occurrences of first column in num_list
idx = np.searchsorted(num_arr, a[:,0])

# Take care of out of bounds cases
idx[idx==len(num_arr)] = 0

out = a[a[:,0] == num_arr[idx]]
</code>```

Title: Search Numpy array with multiple values

Body:
I have numpy 2d array having duplicate values.

I am searching the array like this.

In [104]: import numpy as np

In [105]: array = np.array

In [106]: a = array([[1, 2, 3],
     ...:            [1, 2, 3],
     ...:            [2, 5, 6],
     ...:            [3, 8, 9],
     ...:            [4, 8, 9],
     ...:            [4, 2, 3],
     ...:            [5, 2, 3])

In [107]: num_list = [1, 4, 5]

In [108]: for i in num_list :
     ...:     print(a[np.where(a[:,0] == num_list)])
     ...:
 [[1 2 3]
 [1 2 3]]
[[4 8 9]
 [4 2 3]]
[[5 2 3]]

The input is list having number similar to column 0 values.
The end result I want is the resulting rows in any format like array, list or tuple for example

array([[1, 2, 3],
       [1, 2, 3],
       [4, 8, 9],
       [4, 2, 3],
       [5, 2, 3]])

My code works fine but doesn't seem pythonic. Is there any better searching strategy with multiple values?

like a[np.where(a[:,0] == l)] where only one time lookup is done to get all the values.

my real array is large

Body:
Approach #1 : Using np.in1d -

a[np.in1d(a[:,0], num_list)]

Approach #2 : Using np.searchsorted -

num_arr = np.sort(num_list) # Sort num_list and get as array

# Get indices of occurrences of first column in num_list
idx = np.searchsorted(num_arr, a[:,0])

# Take care of out of bounds cases
idx[idx==len(num_arr)] = 0

out = a[a[:,0] == num_arr[idx]]


问:
exception Convert ToInt32 dans c#
I have this code but  but when I run the program gives me this error System.FormatException: Input string was not in a correct format'.</p>

```<code>      public static void Main(string[] args)
    {

        string a =TextFormater("Teste teste ");

        Console.WriteLine(a);
    }
     public static string TextFormater(string ChaineTextArea)
    {
        string val = string.Empty;
        string Valreturn = string.Empty;
        int result;
        for (int i = 0; i <= ChaineTextArea.Length; i++)
        {
            val = ChaineTextArea.Substring(i, 1);
            var chars = val.ToCharArray();

            result = Convert.ToInt32(val);

            if (result != 13)
            {
                Valreturn= val;
            }

            else
            {
                Valreturn= "<br>" + val;
            }
        }
        return Valreturn;
    }
</code>```

答:
Your input is not a valid format for converting to Integer. However if you need the ASCII value of those characters, that can be arranged by this

```<code>string input = "Teste teste ";
var values = Encoding.ASCII.GetBytes(input);
foreach(var item in values)
{
    Console.WriteLine(item);
}
Console.ReadLine();
</code>```

Hope that will help.

Title: exception Convert ToInt32 dans c#

Body:
I have this code but  but when I run the program gives me this error System.FormatException: Input string was not in a correct format'.

      public static void Main(string[] args)
    {

        string a =TextFormater("Teste teste ");

        Console.WriteLine(a);
    }
     public static string TextFormater(string ChaineTextArea)
    {
        string val = string.Empty;
        string Valreturn = string.Empty;
        int result;
        for (int i = 0; i <= ChaineTextArea.Length; i++)
        {
            val = ChaineTextArea.Substring(i, 1);
            var chars = val.ToCharArray();

            result = Convert.ToInt32(val);

            if (result != 13)
            {
                Valreturn= val;
            }

            else
            {
                Valreturn= "
" + val;
            }
        }
        return Valreturn;
    }

Body:
Your input is not a valid format for converting to Integer. However if you need the ASCII value of those characters, that can be arranged by this

string input = "Teste teste ";
var values = Encoding.ASCII.GetBytes(input);
foreach(var item in values)
{
    Console.WriteLine(item);
}
Console.ReadLine();

Hope that will help.


问: how to delete the

答:
Use delete to remove a property from an object.

var ATLASCONFIG = {
 id:"1197971",
 prevurl:"http:www.1905.com/news/20170704/1197970.shtml#p1",
 nexturl:"http:www.1905.com/news/20170704/1197970.shtml#p1",
 shareIframe:"http://www.1905.com/api/share2.php?...."
}

delete ATLASCONFIG["shareIframe"];
console.log(ATLASCONFIG);```

Title: how to delete the <script> in the news I crawlered

Body:
Here is my code, when I execute it, there are some information which is from code of original website. They are included in the results.

enter code here
import urllib.request
from bs4 import BeautifulSoup
import re
URLdict=dict()
pageNum=1
while pageNum<2:
    user_agent = 'Chrome/58.0(compatible;MSIE 5.5; Windows 10)'
    headers = {'User-Agent': user_agent}
if pageNum==0:
    response=urllib.request.urlopen('http://www.1905.com/list-p-catid-
221.html')
else:
    url = 'http://www.1905.com/list-p-catid-221.html' + '?
    refresh=1321407488&page=' + str(pageNum)
    request = urllib.request.Request(url,headers=headers)
    response = urllib.request.urlopen(request)
first = response.read().decode('utf-8')
BSobj = BeautifulSoup(first, "html.parser")
for a in BSobj.findAll("a", href=True):
  if re.findall('/news/', a['href']):
     URLdict[a['href']] = a.get_text()
            #print(URLdict)
for link, title in URLdict.items():
 print(title, ":", link)
 ContentRequest = urllib.request.Request(link,headers=headers)
 ContentResponse = urllib.request.urlopen(ContentRequest)
 ContentHTMLText = ContentResponse.read().decode('utf-8')
 ContentBSobj = BeautifulSoup(ContentHTMLText, "html.parser")
 Content = ContentBSobj.find("div", {"class": "mod-content"})
 if Content is not None:
     print(Content.get_text())
pageNum=pageNum+1

I checked the original code,these information are from ,they are like these:

enter code here
var ATLASCONFIG = {
            id:"1197971",
            prevurl:"http:www.1905.com/news/20170704/1197970.shtml#p1",
            nexturl:"http:www.1905.com/news/20170704/1197970.shtml#p1",
            shareIframe:"http://www.1905.com/api/share2.php?....
        }

These information appeared in the results rather than my code. I can not send more than two links, so I deleted "//",I want to ask how to delete these,


问:
Resizing Auto Layout Constraint
I'm developing an iOS application in Xcode 8. I'm having trouble getting my head around the auto-layout constraints even after reading various tutorials. I am trying to find what combination of constraints allows me to have an adjustable spacing between the top layout guide and the top of my image view.

Below is the preview of the view on iPhone 7 Plus:

iPhone 7 Plus Demo

The top constraint of the UIImageView is currently set to =50, which is the perfect size for larger screens. However, I am trying to have this spacing shrink on smaller screens, as seen below:

iPhone 4s Demo

I have tried what feels like all possible combinations of various constraints with different sizes and priorities but the spacing is either small on all screens or large on all screens. Is there something I am missing?

答:
You can change the top spacing proportional to the height by taking the outlet of the topConstraint and in the viewDidLoad method you can change its value. . Here you need to find a constant value which when multiplied with the actual height of the device gives the required top spacing. Say you need 50p in 7+ which has a screen size of 736p so the constant is 50/736 = 0.067. So in 4s the spacing can be 480 * 0.067 = 33.

You can do this like

```<code>topspace.constant = self.view.frame.size.height * 0.067
</code>```

Title: Resizing Auto Layout Constraint

Body:
You can change the top spacing proportional to the height by taking the outlet of the topConstraint and in the viewDidLoad method you can change its value. . Here you need to find a constant value which when multiplied with the actual height of the device gives the required top spacing. Say you need 50p in 7+ which has a screen size of 736p so the constant is 50/736 = 0.067. So in 4s the spacing can be 480 * 0.067 = 33.

You can do this like

topspace.constant = self.view.frame.size.height * 0.067


问:
pass a php variable in an anchor tag inside a php loop
I have a list of records on a table which look like this..

PHP/HTML CODE:

```<code><script src="js/jquery-3.2.1.js"></script>
<?php
while($resrecord=mysqli_fetch_array($resdata))
{  ?>
  <tr>
        <td> <?php echo $resrecord[0];?>  </td>
        <td> <?php echo $resrecord[2];?>  </td>
        <td> <?php echo $resrecord[3];?>   </td>
        <td> <a onclick="window.open('test.php?id='+'<?php echo $resrecord[0]; ?>','popup','width=600,height=600');">Tesing</a>  </td>
          //also checked with href of anchor tag
  </tr>
 <?php }   ?>
</code>```

Which means I can't access a php variable in javascript. I also tried these methods

```<code><script type="text/javascript">
  var x= '<?php echo $resrecord[0]; ?>';
  //OR
  var x= '<?php echo json_encode($resrecord[0]); ?>';
    //here x won't populate with above php variables
</script>
</code>```

I've also tested the above javascript methods on a simple PHP variable which didn't belong to any loop and still didn't work.

答:
In order to access your variable value in JS, the best way is, keep you value in some element bonded with some selector  (keep it hidden if not required to display). Then use that selector to access the value.
eg.

```<code><script src="js/jquery-3.2.1.js"></script>
<?php
$i=0;
while($resrecord=mysqli_fetch_array($resdata))
{  $i++ ?>
  <tr>
        <td><div class="hidden selector_<?php echo $i ?>">
               <?php echo $resrecord[0];?>
            </div>
               <?php echo $resrecord[0];?>
        </td>
        <td> <?php echo $resrecord[2];?>  </td>
        <td> <?php echo $resrecord[3];?>   </td>
        <td> <a onclick="window.open('test.php?id='+'<?php echo $resrecord[0]; ?>','popup','width=600,height=600');">Tesing</a>  </td>
          //also checked with href of anchor tag
  </tr>
 <?php }   ?>
</code>```

JAVASCRIPT

```<code>var x = $(".selector_1").val();
</code>```

// you can iterate if required;
Hope you may get some idea with above example

Body:
I have a list of records on a table which look like this..

PHP/HTML CODE:

<?php
while($resrecord=mysqli_fetch_array($resdata))
{  ?>

         <?php echo $resrecord[0];?>
         <?php echo $resrecord[2];?>
         <?php echo $resrecord[3];?>
         <a onclick="window.open('test.php?id='+'<?php echo $resrecord[0]; ?>','popup','width=600,height=600');">Tesing
          //also checked with href of anchor tag

 <?php }   ?>

Which means I can't access a php variable in javascript. I also tried these methods

I've also tested the above javascript methods on a simple PHP variable which didn't belong to any loop and still didn't work.

Body:
In order to access your variable value in JS, the best way is, keep you value in some element bonded with some selector  (keep it hidden if not required to display). Then use that selector to access the value.
eg.

<script src="js/jquery-3.2.1.js"></script>
<?php
$i=0;
while($resrecord=mysqli_fetch_array($resdata))
{  $i++ ?>
  <tr>
        <td><div class="hidden selector_<?php echo $i ?>">
               <?php echo $resrecord[0];?>
            </div>
               <?php echo $resrecord[0];?>
        </td>
        <td> <?php echo $resrecord[2];?>  </td>
        <td> <?php echo $resrecord[3];?>   </td>
        <td> <a onclick="window.open('test.php?id='+'<?php echo $resrecord[0]; ?>','popup','width=600,height=600');">Tesing</a>  </td>
          //also checked with href of anchor tag
  </tr>
 <?php }   ?>

JAVASCRIPT

var x = $(".selector_1").val();

// you can iterate if required;
Hope you may get some idea with above example


问:
Parse a file for all occurrences of a string and generate key-values in JSON

I have a file (https://pastebin.com/STgtBRS8) in which I need to search for all the occurrences of the word "silencedetect".

I then have to generate a JSON file that contains the key-values of “silence_start”, “silence_end”, and “silence_duration”.

The JSON file should look like something like this:

```<code>[
{
"id": 1,
"silence_start": -0.012381,
"silence_end": 2.2059,
"silence_duration": 2.21828
},
{
"id": 2,
"silence_start": 5.79261,
"silence_end": 6.91955,
"silence_duration": 1.12694,
}
]
</code>```

This is what I have tried:

```<code>with open('volume_data.csv', 'r') as myfile:
    data = myfile.read().replace('\n', '')

for line in data:
    if "silencedetect" in data:
        #read silence_start, silence_end, and silence_duration and put in json
</code>```

I am unable to associate the 3 key-value pairs with each "silencedetect". How can I parse the key-values and get them in JSON format ?

答:
Complex solution using re.findall and enumerate functions:

```<code>import re, json

with open('volume_data.txt', 'r') as f:
    result = []
    pat = re.compile(r'(silence_start: -?\d+\.\d+).+?(silence_end: -?\d+\.\d+).+?(silence_duration: -?\d+\.\d+)')
    silence_items = re.findall(pat, f.read().replace('\n', ''))
    for i,v in enumerate(silence_items):
        d = {'id': i+1}
        d.update({pair[:pair.find(':')]: float(pair[pair.find(':')+2:]) for pair in v})
        result.append(d)

    print(json.dumps(result, indent=4))
</code>```

The output:

```<code>[
    {
        "id": 1,
        "silence_end": 2.2059,
        "silence_duration": 2.21828,
        "silence_start": -0.012381
    },
    {
        "id": 2,
        "silence_end": 6.91955,
        "silence_duration": 1.12694,
        "silence_start": 5.79261
    },
    {
        "id": 3,
        "silence_end": 9.12544,
        "silence_duration": 0.59288,
        "silence_start": 8.53256
    },
    {
        "id": 4,
        "silence_end": 10.7276,
        "silence_duration": 1.0805,
        "silence_start": 9.64712
    },
    {
        "id": 5,
        "silence_end": 13.6998,
        "silence_duration": 1.03406,
        "silence_start": 12.6657
    },
    {
        "id": 6,
        "silence_end": 20.1317,
        "silence_duration": 0.871519,
        "silence_start": 19.2602
    },
    {
        "id": 7,
        "silence_end": 22.4305,
        "silence_duration": 0.801859,
        "silence_start": 21.6286
    },
    ...
]
</code>```

Body:
I have a file (https://pastebin.com/STgtBRS8) in which I need to search for all the occurrences of the word "silencedetect".

I then have to generate a JSON file that contains the key-values of “silence_start”, “silence_end”, and “silence_duration”.

The JSON file should look like something like this:

[
{
"id": 1,
"silence_start": -0.012381,
"silence_end": 2.2059,
"silence_duration": 2.21828
},
{
"id": 2,
"silence_start": 5.79261,
"silence_end": 6.91955,
"silence_duration": 1.12694,
}
]

This is what I have tried:

with open('volume_data.csv', 'r') as myfile:
    data = myfile.read().replace('\n', '')

for line in data:
    if "silencedetect" in data:
        #read silence_start, silence_end, and silence_duration and put in json

I am unable to associate the 3 key-value pairs with each "silencedetect". How can I parse the key-values and get them in JSON format ?

Body:
Complex solution using re.findall and enumerate functions:

import re, json

with open('volume_data.txt', 'r') as f:
    result = []
    pat = re.compile(r'(silence_start: -?\d+\.\d+).+?(silence_end: -?\d+\.\d+).+?(silence_duration: -?\d+\.\d+)')
    silence_items = re.findall(pat, f.read().replace('\n', ''))
    for i,v in enumerate(silence_items):
        d = {'id': i+1}
        d.update({pair[:pair.find(':')]: float(pair[pair.find(':')+2:]) for pair in v})
        result.append(d)

    print(json.dumps(result, indent=4))

The output:

[
    {
        "id": 1,
        "silence_end": 2.2059,
        "silence_duration": 2.21828,
        "silence_start": -0.012381
    },
    {
        "id": 2,
        "silence_end": 6.91955,
        "silence_duration": 1.12694,
        "silence_start": 5.79261
    },
    {
        "id": 3,
        "silence_end": 9.12544,
        "silence_duration": 0.59288,
        "silence_start": 8.53256
    },
    {
        "id": 4,
        "silence_end": 10.7276,
        "silence_duration": 1.0805,
        "silence_start": 9.64712
    },
    {
        "id": 5,
        "silence_end": 13.6998,
        "silence_duration": 1.03406,
        "silence_start": 12.6657
    },
    {
        "id": 6,
        "silence_end": 20.1317,
        "silence_duration": 0.871519,
        "silence_start": 19.2602
    },
    {
        "id": 7,
        "silence_end": 22.4305,
        "silence_duration": 0.801859,
        "silence_start": 21.6286
    },
    ...
]


问:
Time measurement of functions with different signature in C#
I want to measure the time that certain function calls take in my application. For this I use the Stopwatch class and it works fine. It looks something like this:

```<code>static readonly Stopwatch StopWatch = new Stopwatch();

StopWatch.Restart();
void func();
StopWatch.Stop();
Assert.Blabla
</code>```

However I am typing this around a lot of functions. Is there a way to make a function that does this for me? I tried but since the signatures of the functions are all different I can't figure it out. I took a look at Func and Action, but they seem to require a fixed signature. I would like something like this:

```<code>CallAndMeasureFunction(func)
</code>```

答:
You can use something like below:

Define a method which takes your actual methods delegate as input:

```<code>public static TimeSpan GetTimestampFor(Action action)
    {
        TimeSpan timestamp = new TimeSpan(0);
        Stopwatch stopWatch = new Stopwatch();

        if (action != null)
        {
            stopWatch.Start();
            action.Invoke();
            stopWatch.Stop();

            timestamp = stopWatch.Elapsed;
        }

        return timestamp;
    }
</code>```

and call it as below:

```<code>var timeSpan = GetTimestampFor(() => {var xyz = ActualMethodForWhichTimeHasTobeMeasured()});
</code>```

With this code, you can measure every method's execution time

Body:
I want to measure the time that certain function calls take in my application. For this I use the Stopwatch class and it works fine. It looks something like this:

static readonly Stopwatch StopWatch = new Stopwatch();

StopWatch.Restart();
void func();
StopWatch.Stop();
Assert.Blabla

However I am typing this around a lot of functions. Is there a way to make a function that does this for me? I tried but since the signatures of the functions are all different I can't figure it out. I took a look at Func and Action, but they seem to require a fixed signature. I would like something like this:

CallAndMeasureFunction(func)

Body:
You can use something like below:

Define a method which takes your actual methods delegate as input:

public static TimeSpan GetTimestampFor(Action action)
    {
        TimeSpan timestamp = new TimeSpan(0);
        Stopwatch stopWatch = new Stopwatch();

        if (action != null)
        {
            stopWatch.Start();
            action.Invoke();
            stopWatch.Stop();

            timestamp = stopWatch.Elapsed;
        }

        return timestamp;
    }

and call it as below:

var timeSpan = GetTimestampFor(() => {var xyz = ActualMethodForWhichTimeHasTobeMeasured()});

With this code, you can measure every method's execution time


问:
Finding support for frequently occurring items
Assume I have a DataFrame where each row has order id and an item. I'd like to know which items appear most frequently with another (maybe probability of item appearing in order given that another item is there?)

Let's say the data is

```<code>order_id,item
1,a
1,b
1,c
2,a
2,b
2,d
3,a
3,b
3,e
</code>```

Then the pair a,b gets the highest score.

(I'm sure there's a technical name for this, can't find it :)

One possible output will be probability of pair appearing in order, in our case something like:

```<code>item1,item2,probablility
a,b,1
a,b,0.3
b,c,0.3
a,d,0.3
b,c,0.3
a,e,0.3
b,3,0.3
</code>```

答:
You are trying to calculate the support for various subsets of items. I have written a general code which finds the support for all combinations.

Creating the dataset

```<code>import sys
if sys.version_info[0] < 3:
    from StringIO import StringIO
else:
    from io import StringIO

import pandas as pd
data = StringIO("""order_id,item
1,a
1,b
1,c
2,a
2,b
2,d
3,a
3,b
3,e""")

df = pd.read_csv(data)
</code>```

Cross-tabulating

```<code>e = pd.crosstab(index=df.order_id, columns=df.item)
e = e.astype('bool')
</code>```

This is how e looks

```<code>item    a   b   c   d   e
order_id
1   True    True    True    False   False
2   True    True    False   True    False
3   True    True    False   False   True
</code>```

Now, for all combinations of subsets of lengths varying from 1 to number of unique items, we query if all the items in the subset have a True.

Main logic

```<code>from itertools import combinations
out = {}
for k  in range(1, len(df.item.unique())):
    combination_len_k = list(combinations(df.item.unique(), k))
    for c in combination_len_k:
        q = " & ".join(list(c))
        out[c] = len(e.query(q))*1./len(e)
</code>```

This gives us the following result.

```<code>{('a',): 1.0,
 ('a', 'b'): 1.0,
 ('a', 'b', 'c'): 0.3333333333333333,
 ('a', 'b', 'c', 'd'): 0.0,
 ('a', 'b', 'c', 'e'): 0.0,
 ('a', 'b', 'd'): 0.3333333333333333,
 ('a', 'b', 'd', 'e'): 0.0,
 ('a', 'b', 'e'): 0.3333333333333333,
 ('a', 'c'): 0.3333333333333333,
 ('a', 'c', 'd'): 0.0,
 ('a', 'c', 'd', 'e'): 0.0,
 ('a', 'c', 'e'): 0.0,
 ('a', 'd'): 0.3333333333333333,
 ('a', 'd', 'e'): 0.0,
 ('a', 'e'): 0.3333333333333333,
 ('b',): 1.0,
 ('b', 'c'): 0.3333333333333333,
 ('b', 'c', 'd'): 0.0,
 ('b', 'c', 'd', 'e'): 0.0,
 ('b', 'c', 'e'): 0.0,
 ('b', 'd'): 0.3333333333333333,
 ('b', 'd', 'e'): 0.0,
 ('b', 'e'): 0.3333333333333333,
 ('c',): 0.3333333333333333,
 ('c', 'd'): 0.0,
 ('c', 'd', 'e'): 0.0,
 ('c', 'e'): 0.0,
 ('d',): 0.3333333333333333,
 ('d', 'e'): 0.0,
 ('e',): 0.3333333333333333}
</code>```

Printing only length 2 combinations

In case you want to print only the length two combinations, you can modify for k  in range(1, len(df.item.unique())): and remove the loop by setting k=2. The answer in that case will be:

```<code>pd.Series(out)

a  b    1.000000
   c    0.333333
   d    0.333333
   e    0.333333
b  c    0.333333
   d    0.333333
   e    0.333333
c  d    0.000000
   e    0.000000
d  e    0.000000
</code>```

Body:
Assume I have a DataFrame where each row has order id and an item. I'd like to know which items appear most frequently with another (maybe probability of item appearing in order given that another item is there?)

Let's say the data is

order_id,item
1,a
1,b
1,c
2,a
2,b
2,d
3,a
3,b
3,e

Then the pair a,b gets the highest score.

(I'm sure there's a technical name for this, can't find it :)

One possible output will be probability of pair appearing in order, in our case something like:

item1,item2,probablility
a,b,1
a,b,0.3
b,c,0.3
a,d,0.3
b,c,0.3
a,e,0.3
b,3,0.3

Body:
You are trying to calculate the support for various subsets of items. I have written a general code which finds the support for all combinations.

Creating the dataset

import sys
if sys.version_info[0] < 3:
    from StringIO import StringIO
else:
    from io import StringIO

import pandas as pd
data = StringIO("""order_id,item
1,a
1,b
1,c
2,a
2,b
2,d
3,a
3,b
3,e""")

df = pd.read_csv(data)

Cross-tabulating

e = pd.crosstab(index=df.order_id, columns=df.item)
e = e.astype('bool')

This is how e looks

item    a   b   c   d   e
order_id
1   True    True    True    False   False
2   True    True    False   True    False
3   True    True    False   False   True

Now, for all combinations of subsets of lengths varying from 1 to number of unique items, we query if all the items in the subset have a True.

Main logic

from itertools import combinations
out = {}
for k  in range(1, len(df.item.unique())):
    combination_len_k = list(combinations(df.item.unique(), k))
    for c in combination_len_k:
        q = " & ".join(list(c))
        out[c] = len(e.query(q))*1./len(e)

This gives us the following result.

{('a',): 1.0,
 ('a', 'b'): 1.0,
 ('a', 'b', 'c'): 0.3333333333333333,
 ('a', 'b', 'c', 'd'): 0.0,
 ('a', 'b', 'c', 'e'): 0.0,
 ('a', 'b', 'd'): 0.3333333333333333,
 ('a', 'b', 'd', 'e'): 0.0,
 ('a', 'b', 'e'): 0.3333333333333333,
 ('a', 'c'): 0.3333333333333333,
 ('a', 'c', 'd'): 0.0,
 ('a', 'c', 'd', 'e'): 0.0,
 ('a', 'c', 'e'): 0.0,
 ('a', 'd'): 0.3333333333333333,
 ('a', 'd', 'e'): 0.0,
 ('a', 'e'): 0.3333333333333333,
 ('b',): 1.0,
 ('b', 'c'): 0.3333333333333333,
 ('b', 'c', 'd'): 0.0,
 ('b', 'c', 'd', 'e'): 0.0,
 ('b', 'c', 'e'): 0.0,
 ('b', 'd'): 0.3333333333333333,
 ('b', 'd', 'e'): 0.0,
 ('b', 'e'): 0.3333333333333333,
 ('c',): 0.3333333333333333,
 ('c', 'd'): 0.0,
 ('c', 'd', 'e'): 0.0,
 ('c', 'e'): 0.0,
 ('d',): 0.3333333333333333,
 ('d', 'e'): 0.0,
 ('e',): 0.3333333333333333}

Printing only length 2 combinations

In case you want to print only the length two combinations, you can modify for k  in range(1, len(df.item.unique())): and remove the loop by setting k=2. The answer in that case will be:

pd.Series(out)

a  b    1.000000
   c    0.333333
   d    0.333333
   e    0.333333
b  c    0.333333
   d    0.333333
   e    0.333333
c  d    0.000000
   e    0.000000
d  e    0.000000


问:
Rewriting example.com/section.php?username=xyz to example.com/xyz/section
Using the following htaccess, I have been able to rewrite example.com/profile.php?username=xyz to example.com/xyz,

```<code>RewriteEngine On
RewriteRule ^([a-zA-Z0-9_-]+)$ profile.php?user=$1
RewriteRule ^([a-zA-Z0-9_-]+)/$ profile.php?user=$1
</code>```

Adding the following to the above,

```<code>RewriteRule ^([a-zA-Z0-9_-]+)/section$ section.php?user=$1
RewriteRule ^([a-zA-Z0-9_-]+)/section/$ section.php?user=$1
</code>```

did not resolve example.com/section.php?username=xyz to example.com/xyz/section.

Am I doing something wrong here?

答:
I tested it and it works. Try this:

```<code>RewriteRule ^([a-zA-Z0-9_-]+)\/section$ section.php?user=$1
RewriteRule ^([a-zA-Z0-9_-]+)\/section\/$ section.php?user=$1
</code>```

All I did was escaping the / in the URL since / is a regex delimiter.

Body:
Using the following htaccess, I have been able to rewrite example.com/profile.php?username=xyz to example.com/xyz,

RewriteEngine On
RewriteRule ^([a-zA-Z0-9_-]+)$ profile.php?user=$1
RewriteRule ^([a-zA-Z0-9_-]+)/$ profile.php?user=$1

Adding the following to the above,

RewriteRule ^([a-zA-Z0-9_-]+)/section$ section.php?user=$1
RewriteRule ^([a-zA-Z0-9_-]+)/section/$ section.php?user=$1

did not resolve example.com/section.php?username=xyz to example.com/xyz/section.

Am I doing something wrong here?

Body:
I tested it and it works. Try this:

RewriteRule ^([a-zA-Z0-9_-]+)\/section$ section.php?user=$1
RewriteRule ^([a-zA-Z0-9_-]+)\/section\/$ section.php?user=$1

All I did was escaping the / in the URL since / is a regex delimiter.


答:
You can do</p>

```<code>a[numpy.in1d(a[:, 0], num_list), :]
</code>```

Title: Search Numpy array with multiple values

Body:
You can do

a[numpy.in1d(a[:, 0], num_list), :]


问:
Converting a code from dplyr to base R
I have to convert a two sets of code designed for dplyr into base R code as a package I use does not support dplyr. My code is below. Could anybody help converting it? I am not very experienced with base R. </p>

```<code>#Annual average
riverObs %>%
  filter(!is.na(Qobs)) %>%
  mutate(year = lubridate::year(date)) %>%
  group_by(year) %>%
  mutate(s1 = Qsim-Qobs,
         s2 = abs(s1),
         s3 = sum(s2),
         s4 = sum(Qobs),
         s5 = s3/s4,
         s6 = 1-s5) %>%
  summarise(AAVE = mean(s6))

#Annual peak error, Qobs
riverObs %>%
  filter(!is.na(Qobs)) %>%
  mutate(year = lubridate::year(date)) %>%
  group_by(year) %>%
  filter(Qobs == max(Qobs)) %>%
  select(year, Qobs) %>%
  ungroup
</code>```

答:
Try this</p>

```<code>library(data.table)

riverObs <- as.data.table(riverObs)
riverObs <- na.omit(riverObs)
riverObs[,year:=(year(date))]
riverObs[,s1:=(Qsim-Qobs),by="year"]
riverObs[,s2:=abs(s1)]
riverObs[,s3:=sum(s2),by="year"]
riverObs[,s4:=sum(Qobs),by="year"]
riverObs[,s5:=s3/s4]
riverObs[,s6:=1-s5,by="year"]
riverObs[,AAVE:=mean(s6),by="year"]

riverObs <- as.data.table(riverObs)
riverObs <- na.omit(riverObs)
riverObs[,year:=(year(date))]
riverObs[,max_Qobs:=max(Qobs),by="year"]
riverObs <- riverObs[Qobs == max(Qobs),]
riverObs <- riverObs[,.(year,Qobs)]
</code>```

Title: Converting a code from dplyr to base R

Body:
I have to convert a two sets of code designed for dplyr into base R code as a package I use does not support dplyr. My code is below. Could anybody help converting it? I am not very experienced with base R.

#Annual average
riverObs %>%
  filter(!is.na(Qobs)) %>%
  mutate(year = lubridate::year(date)) %>%
  group_by(year) %>%
  mutate(s1 = Qsim-Qobs,
         s2 = abs(s1),
         s3 = sum(s2),
         s4 = sum(Qobs),
         s5 = s3/s4,
         s6 = 1-s5) %>%
  summarise(AAVE = mean(s6))

#Annual peak error, Qobs
riverObs %>%
  filter(!is.na(Qobs)) %>%
  mutate(year = lubridate::year(date)) %>%
  group_by(year) %>%
  filter(Qobs == max(Qobs)) %>%
  select(year, Qobs) %>%
  ungroup

Body:
Try this

library(data.table)

riverObs <- as.data.table(riverObs)
riverObs <- na.omit(riverObs)
riverObs[,year:=(year(date))]
riverObs[,s1:=(Qsim-Qobs),by="year"]
riverObs[,s2:=abs(s1)]
riverObs[,s3:=sum(s2),by="year"]
riverObs[,s4:=sum(Qobs),by="year"]
riverObs[,s5:=s3/s4]
riverObs[,s6:=1-s5,by="year"]
riverObs[,AAVE:=mean(s6),by="year"]

riverObs <- as.data.table(riverObs)
riverObs <- na.omit(riverObs)
riverObs[,year:=(year(date))]
riverObs[,max_Qobs:=max(Qobs),by="year"]
riverObs <- riverObs[Qobs == max(Qobs),]
riverObs <- riverObs[,.(year,Qobs)]


问:
Error email send using gmail smtp server with CDOSYS
I have an error on asp page

error '80040211'
/contact_us1.asp, line 106

line 106 is ObjSendMail.Send method call. The bellow code is whole sending email through CDOSYS and without smtp server installed.

OS - Windows Server2008R2,
IIS - 7.5

```<code><%@LANGUAGE="VBSCRIPT" CODEPAGE="65001"%>
<!DOCTYPE html PUBLIC "-//W3C//DTD XHTML 1.0 Transitional//EN" "http://www.w3.org/TR/xhtml1/DTD/xhtml1-transitional.dtd">

<%
'Declaring Variables
Dim smtpserver,youremail,yourpassword,ContactUs_Name,ContactUs_Tel,ContactUs_Email
Dim ContactUs_Subject,ContactUs_Body,Action,IsError

' Edit these 3 values accordingly.. leave the smtp server alone as it is set for Gmail
smtpserver = "smtp.gmail.com"
youremail = "someone@gmail.com"
yourpassword = "--------"

' Grabbing variables from the form post
ContactUs_Name = Request("ContactUs_Name")
ContactUs_Tel = Request("ContactUs_Tel")
ContactUs_Email = Request("ContactUs_Email")
ContactUs_Subject = Request("ContactUs_Subject")
ContactUs_Body = Request("ContactUs_Body")
Action = Request("Action")

' Used to check that the email entered is in a valid format
Function IsValidEmail(Email)
    Dim ValidFlag,BadFlag,atCount,atLoop,SpecialFlag,UserName,DomainName,atChr,tAry1
    ValidFlag = False
        If (Email <> "") And (InStr(1, Email, "@") > 0) And (InStr(1, Email, ".") > 0) Then
            atCount = 0
            SpecialFlag = False
            For atLoop = 1 To Len(Email)
            atChr = Mid(Email, atLoop, 1)
                If atChr = "@" Then atCount = atCount + 1
                If (atChr >= Chr(32)) And (atChr <= Chr(44)) Then SpecialFlag = True
                If (atChr = Chr(47)) Or (atChr = Chr(96)) Or (atChr >= Chr(123)) Then SpecialFlag = True
                If (atChr >= Chr(58)) And (atChr <= Chr(63)) Then SpecialFlag = True
                If (atChr >= Chr(91)) And (atChr <= Chr(94)) Then SpecialFlag = True
            Next
            If (atCount = 1) And (SpecialFlag = False) Then
                BadFlag = False
                tAry1 = Split(Email, "@")
                UserName = tAry1(0)
                DomainName = tAry1(1)
            If (UserName = "") Or (DomainName = "") Then BadFlag = True
            If Mid(DomainName, 1, 1) = "." then BadFlag = True
            If Mid(DomainName, Len(DomainName), 1) = "." then BadFlag = True
                ValidFlag = True
            End If
        End If
        If BadFlag = True Then ValidFlag = False
        IsValidEmail = ValidFlag
End Function
%>
<html xmlns="http://www.w3.org/1999/xhtml">
<head>
</head>

<body class="oneColFixCtrHdr" onload="P7_initPM(0,0,1,-20,10)">

<%
' If there were no input errors and the action of the form is "SendEMail" we send the email off
If Action = "SendEmail" Then

    Dim strBody

    ' Here we create a nice looking html body for the email
    strBody = strBody & "<font face=""Arial"">Contact Us Form submitted at " & Now() &  vbCrLf & "<br><br>"
'   strBody = strBody & "From http://" & Request.ServerVariables("HTTP_HOST") &  vbCrLf & "<br>"
'   strBody = strBody & "IP " & Request.ServerVariables("REMOTE_ADDR") & vbCrLf & "<br>"
    strBody = strBody & "Name" & " : " & " " & Replace(ContactUs_Name,vbCr,"<br>") & "<br>"
    strBody = strBody & "Tel." & " : " & " " & Replace(ContactUs_Tel,vbCr,"<br>") & "<br>"
    strBody = strBody & "Email" & " : " & " " & Replace(ContactUs_Email,vbCr,"<br>") & "<br>"
    strBody = strBody & "Subject" & " : " & " " & Replace(ContactUs_Subject,vbCr,"<br>") & "<br>"
    strBody = strBody & "<br>" & Replace(ContactUs_Body,vbCr,"<br>") & "<br>"
    strBody = strBody & "</font>"

    Dim ObjSendMail
    Set ObjSendMail = CreateObject("CDO.Message")

    'This section provides the configuration information for the remote SMTP server.

    ObjSendMail.Configuration.Fields.Item ("http://schemas.microsoft.com/cdo/configuration/sendusing") = 2 'Send the message using the network (SMTP over the network).
    ObjSendMail.Configuration.Fields.Item ("http://schemas.microsoft.com/cdo/configuration/smtpserver") = "smtp.gmail.com"
    ObjSendMail.Configuration.Fields.Item ("http://schemas.microsoft.com/cdo/configuration/smtpserverport") = 465
    ObjSendMail.Configuration.Fields.Item ("http://schemas.microsoft.com/cdo/configuration/smtpusessl") = 1 'Use SSL for the connection
    ObjSendMail.Configuration.Fields.Item ("http://schemas.microsoft.com/cdo/configuration/smtpconnectiontimeout") = 60

    ObjSendMail.Configuration.Fields.Item ("http://schemas.microsoft.com/cdo/configuration/smtpauthenticate") = 1 'basic (clear-text) authentication
    ObjSendMail.Configuration.Fields.Item ("http://schemas.microsoft.com/cdo/configuration/sendusername") = "someone@gmail.com"
    ObjSendMail.Configuration.Fields.Item ("http://schemas.microsoft.com/cdo/configuration/sendpassword") = "----------"

    ObjSendMail.Configuration.Fields.Update

    'End remote SMTP server configuration section==

    ObjSendMail.To = youremail
    ObjSendMail.CC = "karapetyan.manuk@gmail.com;kmanuk@mail.ru"
    ObjSendMail.Subject = ContactUs_Subject
    ObjSendMail.From = ContactUs_Email

    ' we are sending a html email.. simply switch the comments around to send a text email instead
    ObjSendMail.HTMLBody = strBody
    'ObjSendMail.TextBody = strBody

    ObjSendMail.Send

    Set ObjSendMail = Nothing

' change the success messages below to say or do whatever you like
' you could do a response.redirect or offer a hyperlink somewhere.. etc etc
%>
<font size="12">Message uxarkvec barehajox</font>
<%
Else
%>
            <form action="contact_us1.asp" method="POST">
                <input type="hidden" name="Action" value="SendEmail">
                    <table border="0" cellspacing="1" style="font-size:14px; font-family:Verdana, Geneva, sans-serif;">
                        <tr>
                            <td valign="top">
                                Full Name:
                            </td>
                        </tr>
                        <tr>
                            <td colspan="2">
                                <input type="text" name="ContactUs_Name" size="35" value="<% =ContactUs_Name %>" required>
                            </td>
                        </tr>
                        <tr>
                            <td valign="top">
                                Tel.:
                            </td>
                        </tr>
                        <tr>
                            <td colspan="2">
                                <input type="text" name="ContactUs_Tel" size="35" value="<% =ContactUs_Tel %>">
                            </td>
                        </tr>
                        <tr>
                            <td valign="top">
                                Email:
                            </td>
                        </tr>
                        <tr>
                            <td colspan="2">
                                <input type="text" name="ContactUs_Email" size="35" value="<% =ContactUs_Email %>" required>
                            </td>
                        </tr>
                        <tr>
                            <td valign="top">
                                Subject:
                            </td>
                        </tr>
                        <tr>
                            <td colspan="2">
                                <input type="text" name="ContactUs_Subject" value="<% =ContactUs_Subject %>" size="35">
                            </td>
                        </tr>
                        <tr>
                            <td valign="top">
                                Message:
                            </td>
                        </tr>
                        <tr>
                            <td valign="top">
                                <textarea  cols="60" name="ContactUs_Body" wrap="soft" style="resize:none; height: 150px" required><% =ContactUs_Body %></textarea>
                            </td>
                        </tr>
                        <tr>
                            <td colspan="2">
                                <input type="submit" value="Send Message" style="font-size:16px">
                            </td>
                        </tr>
                    </table>
                </form>

<%
End If
%>

</body>
</html>
</code>```

Help me to resolve this issue please.

答:
I had same problem with gmail. Just two steps to resolve the problem:

changing the password to a strong password! A weak password wont work!

myaccount.google.com > security > Less secure app access > TURN ON

Body:
I have an error on asp page

error '80040211'
/contact_us1.asp, line 106

line 106 is ObjSendMail.Send method call. The bellow code is whole sending email through CDOSYS and without smtp server installed.

OS - Windows Server2008R2,
IIS - 7.5

<%@LANGUAGE="VBSCRIPT" CODEPAGE="65001"%>
<!DOCTYPE html PUBLIC "-//W3C//DTD XHTML 1.0 Transitional//EN" "http://www.w3.org/TR/xhtml1/DTD/xhtml1-transitional.dtd">

<%
'Declaring Variables
Dim smtpserver,youremail,yourpassword,ContactUs_Name,ContactUs_Tel,ContactUs_Email
Dim ContactUs_Subject,ContactUs_Body,Action,IsError

' Edit these 3 values accordingly.. leave the smtp server alone as it is set for Gmail
smtpserver = "smtp.gmail.com"
youremail = "someone@gmail.com"
yourpassword = "--------"

' Grabbing variables from the form post
ContactUs_Name = Request("ContactUs_Name")
ContactUs_Tel = Request("ContactUs_Tel")
ContactUs_Email = Request("ContactUs_Email")
ContactUs_Subject = Request("ContactUs_Subject")
ContactUs_Body = Request("ContactUs_Body")
Action = Request("Action")

' Used to check that the email entered is in a valid format
Function IsValidEmail(Email)
    Dim ValidFlag,BadFlag,atCount,atLoop,SpecialFlag,UserName,DomainName,atChr,tAry1
    ValidFlag = False
        If (Email <> "") And (InStr(1, Email, "@") > 0) And (InStr(1, Email, ".") > 0) Then
            atCount = 0
            SpecialFlag = False
            For atLoop = 1 To Len(Email)
            atChr = Mid(Email, atLoop, 1)
                If atChr = "@" Then atCount = atCount + 1
                If (atChr >= Chr(32)) And (atChr <= Chr(44)) Then SpecialFlag = True
                If (atChr = Chr(47)) Or (atChr = Chr(96)) Or (atChr >= Chr(123)) Then SpecialFlag = True
                If (atChr >= Chr(58)) And (atChr <= Chr(63)) Then SpecialFlag = True
                If (atChr >= Chr(91)) And (atChr <= Chr(94)) Then SpecialFlag = True
            Next
            If (atCount = 1) And (SpecialFlag = False) Then
                BadFlag = False
                tAry1 = Split(Email, "@")
                UserName = tAry1(0)
                DomainName = tAry1(1)
            If (UserName = "") Or (DomainName = "") Then BadFlag = True
            If Mid(DomainName, 1, 1) = "." then BadFlag = True
            If Mid(DomainName, Len(DomainName), 1) = "." then BadFlag = True
                ValidFlag = True
            End If
        End If
        If BadFlag = True Then ValidFlag = False
        IsValidEmail = ValidFlag
End Function
%>

<%
' If there were no input errors and the action of the form is "SendEMail" we send the email off
If Action = "SendEmail" Then

    Dim strBody

    ' Here we create a nice looking html body for the email
    strBody = strBody & "Contact Us Form submitted at " & Now() &  vbCrLf & "

"
'   strBody = strBody & "From http://" & Request.ServerVariables("HTTP_HOST") &  vbCrLf & "
"
'   strBody = strBody & "IP " & Request.ServerVariables("REMOTE_ADDR") & vbCrLf & "
"
    strBody = strBody & "Name" & " : " & " " & Replace(ContactUs_Name,vbCr,"
") & "
"
    strBody = strBody & "Tel." & " : " & " " & Replace(ContactUs_Tel,vbCr,"
") & "
"
    strBody = strBody & "Email" & " : " & " " & Replace(ContactUs_Email,vbCr,"
") & "
"
    strBody = strBody & "Subject" & " : " & " " & Replace(ContactUs_Subject,vbCr,"
") & "
"
    strBody = strBody & "
" & Replace(ContactUs_Body,vbCr,"
") & "
"
    strBody = strBody & ""

    Dim ObjSendMail
    Set ObjSendMail = CreateObject("CDO.Message")

    'This section provides the configuration information for the remote SMTP server.

    ObjSendMail.Configuration.Fields.Item ("http://schemas.microsoft.com/cdo/configuration/sendusing") = 2 'Send the message using the network (SMTP over the network).
    ObjSendMail.Configuration.Fields.Item ("http://schemas.microsoft.com/cdo/configuration/smtpserver") = "smtp.gmail.com"
    ObjSendMail.Configuration.Fields.Item ("http://schemas.microsoft.com/cdo/configuration/smtpserverport") = 465
    ObjSendMail.Configuration.Fields.Item ("http://schemas.microsoft.com/cdo/configuration/smtpusessl") = 1 'Use SSL for the connection
    ObjSendMail.Configuration.Fields.Item ("http://schemas.microsoft.com/cdo/configuration/smtpconnectiontimeout") = 60

    ObjSendMail.Configuration.Fields.Item ("http://schemas.microsoft.com/cdo/configuration/smtpauthenticate") = 1 'basic (clear-text) authentication
    ObjSendMail.Configuration.Fields.Item ("http://schemas.microsoft.com/cdo/configuration/sendusername") = "someone@gmail.com"
    ObjSendMail.Configuration.Fields.Item ("http://schemas.microsoft.com/cdo/configuration/sendpassword") = "----------"

    ObjSendMail.Configuration.Fields.Update

    'End remote SMTP server configuration section==

    ObjSendMail.To = youremail
    ObjSendMail.CC = "karapetyan.manuk@gmail.com;kmanuk@mail.ru"
    ObjSendMail.Subject = ContactUs_Subject
    ObjSendMail.From = ContactUs_Email

    ' we are sending a html email.. simply switch the comments around to send a text email instead
    ObjSendMail.HTMLBody = strBody
    'ObjSendMail.TextBody = strBody

    ObjSendMail.Send

    Set ObjSendMail = Nothing

' change the success messages below to say or do whatever you like
' you could do a response.redirect or offer a hyperlink somewhere.. etc etc
%>
Message uxarkvec barehajox
<%
Else
%>
            <form action="contact_us1.asp" method="POST">
                <input type="hidden" name="Action" value="SendEmail">

                                Full Name:

                                <input type="text" name="ContactUs_Name" size="35" value="<% =ContactUs_Name %>" required>

                                Tel.:

                                <input type="text" name="ContactUs_Tel" size="35" value="<% =ContactUs_Tel %>">

                                Email:

                                <input type="text" name="ContactUs_Email" size="35" value="<% =ContactUs_Email %>" required>

                                Subject:

                                <input type="text" name="ContactUs_Subject" value="<% =ContactUs_Subject %>" size="35">

                                Message:

                                <textarea  cols="60" name="ContactUs_Body" wrap="soft" style="resize:none; height: 150px" required><% =ContactUs_Body %></textarea>

                                <input type="submit" value="Send Message" style="font-size:16px">

                </form>

<%
End If
%>

Help me to resolve this issue please.


问:
Unable to import CSS and JS from node modules in index.html
My react app compiled by webpack is unable to find packages in the node_modules folder. The URLs are correctly set from my src/index.html as follows:

index.html

```<code><!DOCTYPE html>
<html lang="en">
<head>
    <link rel="stylesheet" href="../node_modules/font-awesome/css/font-awesome.min.css">
</head>
<body>
<div id="app"></div>
<script src="../node_modules/jquery/dist/jquery.min.js"></script>
<script src="/bundle.js"></script>
</body>
</html>
</code>```

webpack.config.js

```<code>let webpack = require("webpack");
let path = require("path");

let DIST_DIR = path.resolve(__dirname,"dist");
let SRC_DIR = path.resolve(__dirname,"src");

let config = {
    entry: SRC_DIR + "/index.js",
    output: {
        path: DIST_DIR + "/",
        filename: "bundle.js",
        publicPath: "/"
    },
    module:{
        loaders:[
            {
                test: /\.css$/,
                use: [ 'style-loader', 'css-loader' ]
            },
            {
                test: /\.js?/,
                include: SRC_DIR,
                loader: "babel-loader",
                query: {
                    presets:["react", "es2015", "stage-2"]
                }
            }
        ]
    }
};

module.exports = config;
</code>```

But the console reports the following errors which seem to ignore any ../ set in the beginning of the URL.

Console Errors:

GET http://localhost:8080/node_modules/font-awesome/css/font-awesome.min.css

  GET http://localhost:8080/node_modules/jquery/dist/jquery.min.js

I tried to set relative paths using ./ as follows but with the same result

```<code><link rel="stylesheet" href="./../node_modules/font-awesome/css/font-awesome.min.css">
</code>```

and

```<code><link rel="stylesheet" href="./node_modules/font-awesome/css/font-awesome.min.css">
</code>```

Folder Structure:

```<code>app/
 -dist/
    -bundle.js
    -index.html
 -node_modules/
 -src/
    -index.html
    -index.js
</code>```

How do I do this right? Should I move node_modules into src/ folder?

答: So the issue you are facing is probably due to your folder structure. If you place your index.html at root level your problem will likely to get resolved. Here is a simple github repository doing the same as yours.</p>

Body:
My react app compiled by webpack is unable to find packages in the node_modules folder. The URLs are correctly set from my src/index.html as follows:

index.html

<!DOCTYPE html>

    <link rel="stylesheet" href="../node_modules/font-awesome/css/font-awesome.min.css">

webpack.config.js

let webpack = require("webpack");
let path = require("path");

let DIST_DIR = path.resolve(__dirname,"dist");
let SRC_DIR = path.resolve(__dirname,"src");

let config = {
    entry: SRC_DIR + "/index.js",
    output: {
        path: DIST_DIR + "/",
        filename: "bundle.js",
        publicPath: "/"
    },
    module:{
        loaders:[
            {
                test: /\.css$/,
                use: [ 'style-loader', 'css-loader' ]
            },
            {
                test: /\.js?/,
                include: SRC_DIR,
                loader: "babel-loader",
                query: {
                    presets:["react", "es2015", "stage-2"]
                }
            }
        ]
    }
};

module.exports = config;

But the console reports the following errors which seem to ignore any ../ set in the beginning of the URL.

Console Errors:

GET http://localhost:8080/node_modules/font-awesome/css/font-awesome.min.css

  GET http://localhost:8080/node_modules/jquery/dist/jquery.min.js

I tried to set relative paths using ./ as follows but with the same result

<link rel="stylesheet" href="./../node_modules/font-awesome/css/font-awesome.min.css">

and

<link rel="stylesheet" href="./node_modules/font-awesome/css/font-awesome.min.css">

Folder Structure:

app/
 -dist/
    -bundle.js
    -index.html
 -node_modules/
 -src/
    -index.html
    -index.js

How do I do this right? Should I move node_modules into src/ folder?


问:
java.lang.ClassCastException while creating a dataframe with schema
I have some incoming data as rowValues, I will have to apply a particular schema and create a data frame , here is my code:

val rowValues = List("12","F","1980-10-11,1980-10-11T10:10:20")
val rdd = sqlContext.sparkContext.parallelize(Seq(rowValues))
val rowRdd = rdd.map(v => Row(v: _*))

var fieldSchema = ListBuffer[StructField]()

fieldSchema += StructField("C0", IntegerType, true, null)
fieldSchema += StructField("C1", StringType, true, null)
fieldSchema += StructField("C2", TimestampType, true, null)
val schema = StructType(fieldSchema.toList)

val newRow = sqlContext.createDataFrame(rowRdd, schema)
newRow.printSchema()   // new schema prints here
newRow.show()   // This fails with ClassCast exception
```

This fails with org.apache.spark.SparkException: Job aborted due to stage failure: Task 0 in stage 16.0 failed 1 times, most recent failure: Lost task 0.0 in stage 16.0 (TID 16, localhost): java.lang.ClassCastException: java.lang.String cannot be cast to java.sql.Timestamp

How do I apply this schema?

答:
Rather than applying schema you can cast the column in dataframe as your schema

You can use withColumn to with cast function to change the datatype of column

Below is the simple example

import spark.implicits._

val df = spark.sparkContext.parallelize(Seq(
  ("12","F","1980-10-11T10:10:20"),
  ("12","F","1980-10-11T10:10:20")
)).toDF("c0", "c1", "c2")

val newDf = df.withColumn("c0", df("c0").cast(IntegerType))
  .withColumn("c2", df("c2").cast(TimestampType))
//cast string date to timestamp

val newDf = df.withColumn("c0", df("c0").cast(IntegerType))
  .withColumn("c2", to_utc_timestamp(df("c2"), "yyyy-MM-dd HH:mm:ss"))
//to_utc_timestamp creates a timestamp form given column and date format

newDf.show(false)

newDf.printSchema()
```

Hope this helps!

Body:
I have some incoming data as rowValues, I will have to apply a particular schema and create a data frame , here is my code:

val rowValues = List("12","F","1980-10-11,1980-10-11T10:10:20")
val rdd = sqlContext.sparkContext.parallelize(Seq(rowValues))
val rowRdd = rdd.map(v => Row(v: _*))

var fieldSchema = ListBuffer[StructField]()

fieldSchema += StructField("C0", IntegerType, true, null)
fieldSchema += StructField("C1", StringType, true, null)
fieldSchema += StructField("C2", TimestampType, true, null)
val schema = StructType(fieldSchema.toList)

val newRow = sqlContext.createDataFrame(rowRdd, schema)
newRow.printSchema()   // new schema prints here
newRow.show()   // This fails with ClassCast exception

This fails with org.apache.spark.SparkException: Job aborted due to stage failure: Task 0 in stage 16.0 failed 1 times, most recent failure: Lost task 0.0 in stage 16.0 (TID 16, localhost): java.lang.ClassCastException: java.lang.String cannot be cast to java.sql.Timestamp

How do I apply this schema?

Body:
Rather than applying schema you can cast the column in dataframe as your schema

You can use withColumn to with cast function to change the datatype of column

Below is the simple example

import spark.implicits._

val df = spark.sparkContext.parallelize(Seq(
  ("12","F","1980-10-11T10:10:20"),
  ("12","F","1980-10-11T10:10:20")
)).toDF("c0", "c1", "c2")

val newDf = df.withColumn("c0", df("c0").cast(IntegerType))
  .withColumn("c2", df("c2").cast(TimestampType))
//cast string date to timestamp

val newDf = df.withColumn("c0", df("c0").cast(IntegerType))
  .withColumn("c2", to_utc_timestamp(df("c2"), "yyyy-MM-dd HH:mm:ss"))
//to_utc_timestamp creates a timestamp form given column and date format

newDf.show(false)

newDf.printSchema()

Hope this helps!


问:
Disable postback at click on a button
I want do disable postback after clicking a <asp:Button>. I've tried to do that by assigning onclick="return false", but in the button doesn't work.

How can I fix this?

答:
Put your asp button to inside the Updatepanel like</p>
```<code><asp:UpdatePanel ID="updPnl" runat="server" UpdateMode="Conditional" RenderMode="Block">
  <ContentTemplate>
    <asp:Button ID="btnID" runat="server"  OnClick="btn_Click" />
  </ContentTemplate>
</asp:UpdatePanel>
</code>```

Title: Disable postback at click on a button

Body:
Put your asp button to inside the Updatepanel like

<asp:UpdatePanel ID="updPnl" runat="server" UpdateMode="Conditional" RenderMode="Block">
  <ContentTemplate>
    <asp:Button ID="btnID" runat="server"  OnClick="btn_Click" />
  </ContentTemplate>
</asp:UpdatePanel>


问:
Nested if and Formula
HI i am trying to write the IF function like this.

```<code>=IF(AND(E3="Epyllion",J3="7"),".70","")
</code>```

But result always shows 0 instead of .70.

My point for this function is,

```<code>IF E3="Epyllion" AND J3="7" Then .70 AND IF E3="Epyllion" AND J3="5" Then ".72" AND IF E3="Epyllion" AND J3="3" Then ".80"
</code>```

Can someone help me to write this formula.

答:
The following formula works for me.

IF(AND(E3="Epyllion",J3=7),70,IF(AND(E3="Epyllion",J3=5),72,IF(AND(E3="Epyllion",J3=3),80,"NULL")))

Title: Nested if and Formula

Body:
HI i am trying to write the IF function like this.

=IF(AND(E3="Epyllion",J3="7"),".70","")

But result always shows 0 instead of .70.

My point for this function is,

IF E3="Epyllion" AND J3="7" Then .70 AND IF E3="Epyllion" AND J3="5" Then ".72" AND IF E3="Epyllion" AND J3="3" Then ".80"

Can someone help me to write this formula.