雪花飘飘的天空

文章 评论 浏览 30

雪花飘飘的天空 2025-02-21 00:33:25
  1. $ _ POST 设置变量时,您会缺少数组键。
  2. 当您比较变量时,您的字符串周围有 [] 。这将字符串放在数组中,但是变量的值只是字符串。不要那样做。
<?php

if (isset($_POST['submit'])) {
    $input=$_POST['input'];
    $circles=$_POST['circles'];
    $convercircle=$_POST['convercircle'];

    if ($circles=='diameter' && $convercircle=='radius') {
        $output=$input*2;
        echo "The radius is $output";
    }
    elseif ($circles=='circumference' && $convercircle=='radius') {
        $output=$input/2;
        echo "The radius is $output";
    }
    elseif ($circles=='radius' && $convercircle=='diameter') {
        $output=$input*2;
        echo "The diameter is $output";
    }
    elseif ($circles=='radius' && $convercircle=='circumference') {
        $output=$input*2*3.14;
        echo "The circumference is $output";
    }
    elseif ($circles=='diameter' && $convercircle=='circumference') {
        $output=$input*3.14*2;
        echo "The circumference is $output";
    }
    elseif ($circles=='circumference' && $convercircle=='diameter') {
        $output=$input*3.14*2;
        echo "The diameter is $output";
    }
    else {
        echo "Please select a circle and a conversion";
    }
}
  1. You're missing the array keys when you set the variables from $_POST.
  2. When you're comparing the variables, you have [] around the strings. That puts the string in an array, but the values of the variables are just strings. Don't do that.
<?php

if (isset($_POST['submit'])) {
    $input=$_POST['input'];
    $circles=$_POST['circles'];
    $convercircle=$_POST['convercircle'];

    if ($circles=='diameter' && $convercircle=='radius') {
        $output=$input*2;
        echo "The radius is $output";
    }
    elseif ($circles=='circumference' && $convercircle=='radius') {
        $output=$input/2;
        echo "The radius is $output";
    }
    elseif ($circles=='radius' && $convercircle=='diameter') {
        $output=$input*2;
        echo "The diameter is $output";
    }
    elseif ($circles=='radius' && $convercircle=='circumference') {
        $output=$input*2*3.14;
        echo "The circumference is $output";
    }
    elseif ($circles=='diameter' && $convercircle=='circumference') {
        $output=$input*3.14*2;
        echo "The circumference is $output";
    }
    elseif ($circles=='circumference' && $convercircle=='diameter') {
        $output=$input*3.14*2;
        echo "The diameter is $output";
    }
    else {
        echo "Please select a circle and a conversion";
    }
}

自动获取错误消息而不是结果

雪花飘飘的天空 2025-02-20 23:47:50

如果是 cossociative array

function isAssoc($array) {
    $array = array_keys($array);
    return ($array !== array_keys($array));
}

if (isAssoc($ONEANSWER['answers']['answer'])) {
    $ONEANSWER['answers']['answer'] = [$ONEANSWER['answers']['answer']];
}
if (isAssoc($THREEANSWERS['answers']['answer'])) {//it's not associative array
    $THREEANSWERS['answers']['answer'] = [$THREEANSWERS['answers']['answer']];
}

使用 isassoc

If it's associative array make it sequential array

function isAssoc($array) {
    $array = array_keys($array);
    return ($array !== array_keys($array));
}

if (isAssoc($ONEANSWER['answers']['answer'])) {
    $ONEANSWER['answers']['answer'] = [$ONEANSWER['answers']['answer']];
}
if (isAssoc($THREEANSWERS['answers']['answer'])) {//it's not associative array
    $THREEANSWERS['answers']['answer'] = [$THREEANSWERS['answers']['answer']];
}

using isAssoc

JSON中的PHP计数节点返回许多

雪花飘飘的天空 2025-02-20 19:26:27

这是我写的一些代码,以演示如何做到这一点。我创建了一个 filedownloader 类,因为下载完成后,您可以获取源URL和目标文件名。我还添加了一个进度活动。仅使用 webclient 类的问题是,您将失去在事件中正在处理哪个文件的跟踪。

Imports System.ComponentModel
Imports System.Net

    ' A class for downloading files, with progress and finished events
Public Class FileDownloader

    ' Private storage
    Private FileURL As String = ""
    Private SaveToPath As String = ""

    ' A class to return our result in
    Public Class FileDownloaderFileDownloadedEventArgs
        Public Property DownloadedURL As String
        Public Property SaveToPath As String
        Public Sub New(DownloadedURL As String, SaveToPath As String)
            Me.DownloadedURL = DownloadedURL
            Me.SaveToPath = SaveToPath
        End Sub
    End Class

    ' A class to show progress
    Public Class FileDownloaderProgressEventArgs
        Public Property DownloadURL As String
        Public Property SaveToPath As String
        Public Property TotalBytes As Long
        Public Property ProgressBytes As Long
        Public Property ProgressPercent As Integer
        Public Property UserState As Object

        Public Sub New(DownloadURL As String, SaveToPath As String, TotalBytes As Long, ProgressBytes As Long, ProgressPercent As Integer, UserState As Object)
            Me.DownloadURL = DownloadURL
            Me.SaveToPath = SaveToPath
            Me.TotalBytes = TotalBytes
            Me.ProgressBytes = ProgressBytes
            Me.ProgressPercent = ProgressPercent
            Me.UserState = UserState
        End Sub
    End Class

    ' The event to raise when the file is downloaded
    Public Event FileDownloaded(sender As Object, e As FileDownloaderFileDownloadedEventArgs)
    ' The event to raise when there is progress
    Public Event Progress(sender As Object, e As FileDownloaderProgressEventArgs)

    ' Pass in the URL and FilePath when creating the downloader object
    Public Sub New(FileURL As String, SaveToPath As String)
        Me.FileURL = FileURL
        Me.SaveToPath = SaveToPath
    End Sub

    ' Call Download() to do the work
    Public Sub Download()
        Using wc As New WebClient
            AddHandler wc.DownloadFileCompleted, AddressOf DownloadFileCompleted
            AddHandler wc.DownloadProgressChanged, AddressOf DownloadProgressChanged
            wc.DownloadFileAsync(New Uri(FileURL), SaveToPath)
        End Using
    End Sub

    ' Catch the download complete and raise our event
    Private Sub DownloadProgressChanged(ByVal sender As Object, ByVal e As DownloadProgressChangedEventArgs)
        RaiseEvent Progress(Me, New FileDownloaderProgressEventArgs(FileURL, SaveToPath, e.TotalBytesToReceive, e.BytesReceived, e.ProgressPercentage, e.UserState))
    End Sub

    Private Sub DownloadFileCompleted(sender As Object, e As AsyncCompletedEventArgs)
        ' Some code you want to run after each file has downloaded
        RaiseEvent FileDownloaded(Me, New FileDownloaderFileDownloadedEventArgs(FileURL, SaveToPath))
    End Sub
End Class

#Region "How to use the FileDownloader class"

    Private Sub Button2_Click(sender As Object, e As EventArgs) Handles Button2.Click
        ' Loop the URLs in the ListBox
        For Each item In ListBox1.Items
            ' Create a FileDownloader object to handler each one
            Dim FD = New FileDownloader(item, "c:\temp\" & IO.Path.GetFileName(item))
            ' Attach the event handlers
            AddHandler FD.FileDownloaded, AddressOf FileDownloaded
            AddHandler FD.Progress, AddressOf Progress
            ' Start the download
            FD.Download()
        Next
    End Sub

    ' Event handler for file download completed
    Private Sub FileDownloaded(sender As Object, e As FileDownloader.FileDownloaderFileDownloadedEventArgs)
        tb_Log.AppendText(e.DownloadedURL & "  Downloaded To:  " & e.SaveToPath & vbCrLf)
    End Sub

    ' Event handler for progress
    Private Sub Progress(sender As Object, e As FileDownloader.FileDownloaderProgressEventArgs)
        tb_Log.AppendText(IO.Path.GetFileName(e.DownloadURL) & " " & e.ProgressPercent & "% downloaded" & vbCrLf)
    End Sub

#End Region

Here is some code I wrote to demonstrate how you could do this. I created a FileDownloader class as this will allow you to get the source url and destination filename when the download completes. I have also added an event for progress. The problem with just using the WebClient class on its own is that you lose track of which file is being processed in the events.

Imports System.ComponentModel
Imports System.Net

    ' A class for downloading files, with progress and finished events
Public Class FileDownloader

    ' Private storage
    Private FileURL As String = ""
    Private SaveToPath As String = ""

    ' A class to return our result in
    Public Class FileDownloaderFileDownloadedEventArgs
        Public Property DownloadedURL As String
        Public Property SaveToPath As String
        Public Sub New(DownloadedURL As String, SaveToPath As String)
            Me.DownloadedURL = DownloadedURL
            Me.SaveToPath = SaveToPath
        End Sub
    End Class

    ' A class to show progress
    Public Class FileDownloaderProgressEventArgs
        Public Property DownloadURL As String
        Public Property SaveToPath As String
        Public Property TotalBytes As Long
        Public Property ProgressBytes As Long
        Public Property ProgressPercent As Integer
        Public Property UserState As Object

        Public Sub New(DownloadURL As String, SaveToPath As String, TotalBytes As Long, ProgressBytes As Long, ProgressPercent As Integer, UserState As Object)
            Me.DownloadURL = DownloadURL
            Me.SaveToPath = SaveToPath
            Me.TotalBytes = TotalBytes
            Me.ProgressBytes = ProgressBytes
            Me.ProgressPercent = ProgressPercent
            Me.UserState = UserState
        End Sub
    End Class

    ' The event to raise when the file is downloaded
    Public Event FileDownloaded(sender As Object, e As FileDownloaderFileDownloadedEventArgs)
    ' The event to raise when there is progress
    Public Event Progress(sender As Object, e As FileDownloaderProgressEventArgs)

    ' Pass in the URL and FilePath when creating the downloader object
    Public Sub New(FileURL As String, SaveToPath As String)
        Me.FileURL = FileURL
        Me.SaveToPath = SaveToPath
    End Sub

    ' Call Download() to do the work
    Public Sub Download()
        Using wc As New WebClient
            AddHandler wc.DownloadFileCompleted, AddressOf DownloadFileCompleted
            AddHandler wc.DownloadProgressChanged, AddressOf DownloadProgressChanged
            wc.DownloadFileAsync(New Uri(FileURL), SaveToPath)
        End Using
    End Sub

    ' Catch the download complete and raise our event
    Private Sub DownloadProgressChanged(ByVal sender As Object, ByVal e As DownloadProgressChangedEventArgs)
        RaiseEvent Progress(Me, New FileDownloaderProgressEventArgs(FileURL, SaveToPath, e.TotalBytesToReceive, e.BytesReceived, e.ProgressPercentage, e.UserState))
    End Sub

    Private Sub DownloadFileCompleted(sender As Object, e As AsyncCompletedEventArgs)
        ' Some code you want to run after each file has downloaded
        RaiseEvent FileDownloaded(Me, New FileDownloaderFileDownloadedEventArgs(FileURL, SaveToPath))
    End Sub
End Class

#Region "How to use the FileDownloader class"

    Private Sub Button2_Click(sender As Object, e As EventArgs) Handles Button2.Click
        ' Loop the URLs in the ListBox
        For Each item In ListBox1.Items
            ' Create a FileDownloader object to handler each one
            Dim FD = New FileDownloader(item, "c:\temp\" & IO.Path.GetFileName(item))
            ' Attach the event handlers
            AddHandler FD.FileDownloaded, AddressOf FileDownloaded
            AddHandler FD.Progress, AddressOf Progress
            ' Start the download
            FD.Download()
        Next
    End Sub

    ' Event handler for file download completed
    Private Sub FileDownloaded(sender As Object, e As FileDownloader.FileDownloaderFileDownloadedEventArgs)
        tb_Log.AppendText(e.DownloadedURL & "  Downloaded To:  " & e.SaveToPath & vbCrLf)
    End Sub

    ' Event handler for progress
    Private Sub Progress(sender As Object, e As FileDownloader.FileDownloaderProgressEventArgs)
        tb_Log.AppendText(IO.Path.GetFileName(e.DownloadURL) & " " & e.ProgressPercent & "% downloaded" & vbCrLf)
    End Sub

#End Region

如何使用vb.net在列表框中下载多个文件

雪花飘飘的天空 2025-02-20 19:19:26

我初始化了一个2-d数组( n行 * 2 cols ),我想通过 std :: Sort [...]

排序总是2,然后您应该使用

在这里作为合适的数据结构。
这将有助于通过简单地进行比较 std: std: std: :配对

示例使用 std :: pair&lt&lt&gt; 的数组,您可以做

std::pair<int, int> ministers[1010]; // array of  pair of ints
int n;  std::cin >> n;

for (int i = 0; i < n; i++)
    std::cin >> ministers[i].first >> ministers[i].second;
// compare function is a lambda
std::sort(ministers, ministers + n
       , [](const auto& m1, const auto& m2) { return m1 < m2; });
   // use of std::pair<int, int>::operator<  --> ^^^^^^^^^^^^^^^

实时演示

I initialized a 2-D array (n rows * 2 cols), and I want to sort it by std::sort [...]

If the col count is always 2, then you should have used a

as a suitable data structure here.
This will help to compare the elements by simply the comparison operator of std::pair.

Example using the array of std::pair<int, int> you might do

std::pair<int, int> ministers[1010]; // array of  pair of ints
int n;  std::cin >> n;

for (int i = 0; i < n; i++)
    std::cin >> ministers[i].first >> ministers[i].second;
// compare function is a lambda
std::sort(ministers, ministers + n
       , [](const auto& m1, const auto& m2) { return m1 < m2; });
   // use of std::pair<int, int>::operator<  --> ^^^^^^^^^^^^^^^

Live demo

如何用std ::排序对静态初始估计的2D数组进行排序?

雪花飘飘的天空 2025-02-20 12:50:36

考虑单纯词的一种方法是,它不会创建对象包含它被解析的XML,它只是为提供了访问xml内部数据的API。因此,要使用它,您需要了解XML的结构,并确定要从中获得哪些数据。

在这种情况下, XMLNS 属性代表 XML名称空间,因此您需要了解如何与这些空间一起工作,这将在此处进行详细讨论: Reference-我如何处理名称空间(标签和属性的标签和属性,以其名称为单位) Simplexml?

您实际上并没有说出要出去的数据,因此我将以示例作为示例获取符号从股票元素的内部列表中获取符号。要了解这些,您需要遍历:

  • &lt; diffgr:diffgram&gt; 元素,命名空间中的 urn:schemas-microsoft-com:xml-diffgram-v1 如其 xmlns所示:diffgr 属性
  • ofter &lt; ticker&gt; element,在命名空间中,带有空的URI( xmlns =“”
  • 循环
  • Inner &lt; ticker&gt; 元素,我们希望通过&lt; symbor&gt ; 每个元素,我们要提取字符串内容的元素,
$sx = simplexml_load_string($xml); // Note: no additional options needed here

// Switch to the namespace given by xmlns:diffgr=""...", and select the "diffgram" element
$diffgram = $sx->children('urn:schemas-microsoft-com:xml-diffgram-v1')->diffgram;
// Switch to the namespace with an empty URI, because the elements have xmlns=""
$emptyNamespaceChildren = $diffgram->children("");

// Select the outer Ticker element
$outerTicker = $emptyNamespaceChildren->Ticker;

// Loop over the inner Ticker elements
$symbols = [];
foreach ( $outerTicker->Ticker as $ticker ) {
    // Get some data out, in this case the SYMBOL of each Ticker
    // Using (string) gives us the content of the element, rather than an object
    $symbols[] = (string)$ticker->SYMBOL;
}

请注意,这里的所有额外变量仅用于可读性,实际上,您可能不会说服它。在另一个极端上,您可以将其全部放在一条线上,贯穿所有级别,直到到达想要循环的部分,如下:

$sx = simplexml_load_string($xml);
$symbols = [];
foreach ( $sx->children('urn:schemas-microsoft-com:xml-diffgram-v1')->diffgram->children("")->Ticker->Ticker as $ticker ) {
    $symbols[] = (string)$ticker->SYMBOL;
}

One way to think about SimpleXML is that it doesn't create objects containing the XML it's parsed, it just gives an API for accessing data inside that XML. So to work with it, you need to understand the structure of the XML, and decide what data you want to get out of it.

In this case, the xmlns attributes represent XML namespaces, so you need to understand how to work with those, which is discussed in detail here: Reference - How do I handle Namespaces (Tags and Attributes with a Colon in their Name) in SimpleXML?.

You haven't actually said what data you want to get out, so I'll use as an example getting the SYMBOLS from the inner list of Ticker elements. To get to those, you need to traverse through:

  • The <diffgr:diffgram> element, which is in namespace urn:schemas-microsoft-com:xml-diffgram-v1 as indicated by its xmlns:diffgr attribute
  • The outer <Ticker> element, which is in a namespace with an empty URI (xmlns="")
  • The inner <Ticker> elements, which we want to loop over
  • The <SYMBOL> element in each one, which we want to extract the string content of
$sx = simplexml_load_string($xml); // Note: no additional options needed here

// Switch to the namespace given by xmlns:diffgr=""...", and select the "diffgram" element
$diffgram = $sx->children('urn:schemas-microsoft-com:xml-diffgram-v1')->diffgram;
// Switch to the namespace with an empty URI, because the elements have xmlns=""
$emptyNamespaceChildren = $diffgram->children("");

// Select the outer Ticker element
$outerTicker = $emptyNamespaceChildren->Ticker;

// Loop over the inner Ticker elements
$symbols = [];
foreach ( $outerTicker->Ticker as $ticker ) {
    // Get some data out, in this case the SYMBOL of each Ticker
    // Using (string) gives us the content of the element, rather than an object
    $symbols[] = (string)$ticker->SYMBOL;
}

Note that all the extra variables here are just for readability, and in practice you might not write it so verbosely. At the other extreme, you could put it all on one line, going through all the levels until you get to the part where you want to loop, like this:

$sx = simplexml_load_string($xml);
$symbols = [];
foreach ( $sx->children('urn:schemas-microsoft-com:xml-diffgram-v1')->diffgram->children("")->Ticker->Ticker as $ticker ) {
    $symbols[] = (string)$ticker->SYMBOL;
}

我可以在PHP中读取和解析XML文件

雪花飘飘的天空 2025-02-20 12:01:13

在Python中代表您的伪代码的最PYTHONIC方式是:

x = 0
y = 1
z = 3
mylist = []

if any(v == 0 for v in (x, y, z)):
    mylist.append("c")
if any(v == 1 for v in (x, y, z)):
    mylist.append("d")
if any(v == 2 for v in (x, y, z)):
    mylist.append("e")
if any(v == 3 for v in (x, y, z)):
    mylist.append("f")

The most pythonic way of representing your pseudo-code in Python would be:

x = 0
y = 1
z = 3
mylist = []

if any(v == 0 for v in (x, y, z)):
    mylist.append("c")
if any(v == 1 for v in (x, y, z)):
    mylist.append("d")
if any(v == 2 for v in (x, y, z)):
    mylist.append("e")
if any(v == 3 for v in (x, y, z)):
    mylist.append("f")

雪花飘飘的天空 2025-02-20 05:31:12

我最终尝试了词典列表,并在更快的情况下进行此任务的性能。

dict_list = df.to_dict('records')

dict_length = len(dict_list)

duplicate_flag = False

i = 0

trim_value = 0.005

data = []

for j in range(dict_length - 1):
    for k in range(dict_length - 1):
        if k >= i:
            if(dict_list[i]['Running Date'] == dict_list[k+1]['Running Date'] and
             dict_list[i]['Category'] == dict_list[k+1]['Category'] and
             dict_list[i]['Location From'] >= (dict_list[k+1]['Location From'] - trim_value) and
             dict_list[i]['Location From'] <= (dict_list[k+1]['Location From'] + trim_value) and
             dict_list[i]['Location To'] >= (dict_list[k+1]['Location To'] - trim_value) and
             dict_list[i]['Location To'] <= (dict_list[k+1]['Location To'] + trim_value)):
                duplicate_flag = True
   
    if duplicate_flag == False:
        data.append(dict_list[i])
    
    i += 1    
    
    duplicate_flag = False

data.append(dict_list[-1])
df2 = pd.DataFrame(data)

I ended up experimenting with a list of dictionaries instead and the performance for this task in magnitudes quicker.

dict_list = df.to_dict('records')

dict_length = len(dict_list)

duplicate_flag = False

i = 0

trim_value = 0.005

data = []

for j in range(dict_length - 1):
    for k in range(dict_length - 1):
        if k >= i:
            if(dict_list[i]['Running Date'] == dict_list[k+1]['Running Date'] and
             dict_list[i]['Category'] == dict_list[k+1]['Category'] and
             dict_list[i]['Location From'] >= (dict_list[k+1]['Location From'] - trim_value) and
             dict_list[i]['Location From'] <= (dict_list[k+1]['Location From'] + trim_value) and
             dict_list[i]['Location To'] >= (dict_list[k+1]['Location To'] - trim_value) and
             dict_list[i]['Location To'] <= (dict_list[k+1]['Location To'] + trim_value)):
                duplicate_flag = True
   
    if duplicate_flag == False:
        data.append(dict_list[i])
    
    i += 1    
    
    duplicate_flag = False

data.append(dict_list[-1])
df2 = pd.DataFrame(data)

通过数据框架循环循环并使用条件列表的效率提高?

雪花飘飘的天空 2025-02-19 17:03:38

如果您想将json(本质上是文本)转换为python dict,那么我建议您使用以下方式:

**

import json
# some JSON:
x =  '{ "name":"John", "age":30, "city":"New York"}'
# parse x:
y = json.loads(x)
# the result is a Python dictionary:
print(y["age"])

**

,然后您可以调用y ['键'] =使用数据的值
在这里,y ['name'] =“约翰”

If you're looking to convert JSON (essentially text) to a python dict , then I would suggest you use this:

**

import json
# some JSON:
x =  '{ "name":"John", "age":30, "city":"New York"}'
# parse x:
y = json.loads(x)
# the result is a Python dictionary:
print(y["age"])

**

then you can call y['keys'] = values to use data
here , y['name'] = "John"

是否可以在Python中解析JSON数据?

雪花飘飘的天空 2025-02-19 10:35:21

https://github.com/mkleeehammer/pyodbc/pyodbc/issues/383

pyodbc返回列作为布尔值,因为这是大多数人使用的列。

import pandas as pd
import sqlalchemy as sa

engine = sa.create_engine("mssql+pyodbc://scott:tiger^5HHH@mssql_199")

table_data = """\
SELECT -1 AS id, CAST(NULL AS bit) AS bit_col
UNION ALL
SELECT 0 AS id, CAST(0 AS bit) AS bit_col
UNION ALL
SELECT 1 AS id, CAST(1 AS bit) AS bit_col
"""

df = pd.read_sql_query(table_data, engine)
print(df)
"""
   id  bit_col
0  -1     None
1   0    False
2   1     True
"""

如果您希望PYODBC返回 bit 列作为其他类型,则可以使用GitHub问题中所示的输出转换器函数。诀窍是让Sqlalchemy使用它。这是使用事件侦听器完成的。

import pandas as pd
import pyodbc
import sqlalchemy as sa

engine = sa.create_engine("mssql+pyodbc://scott:tiger^5HHH@mssql_199")

table_data = """\
SELECT -1 AS id, CAST(NULL AS bit) AS bit_col
UNION ALL
SELECT 0 AS id, CAST(0 AS bit) AS bit_col
UNION ALL
SELECT 1 AS id, CAST(1 AS bit) AS bit_col
"""

def handle_bit_type(bit_value):
    return bit_value


@sa.event.listens_for(engine, "connect")
def connect(conn, rec):
    conn.add_output_converter(pyodbc.SQL_BIT, handle_bit_type)


df = pd.read_sql_query(table_data, engine)
print(df)
"""
   id  bit_col
0  -1     None
1   0  b'\x00'
2   1  b'\x01'
"""

编辑:或,如果您

def handle_bit_type(bit_value):
    if bit_value is None:
        rtn = None
    elif bit_value == b"\x00":
        rtn = "0"
    else:
        rtn = "1"
    return rtn

使用

df = pd.read_sql_query(table_data, engine)
print(df)
"""
   id bit_col
0  -1    None
1   0       0
2   1       1
"""

As explained in

https://github.com/mkleehammer/pyodbc/issues/383

pyodbc returns bit columns as boolean values because that is what most people use bit columns for.

import pandas as pd
import sqlalchemy as sa

engine = sa.create_engine("mssql+pyodbc://scott:tiger^5HHH@mssql_199")

table_data = """\
SELECT -1 AS id, CAST(NULL AS bit) AS bit_col
UNION ALL
SELECT 0 AS id, CAST(0 AS bit) AS bit_col
UNION ALL
SELECT 1 AS id, CAST(1 AS bit) AS bit_col
"""

df = pd.read_sql_query(table_data, engine)
print(df)
"""
   id  bit_col
0  -1     None
1   0    False
2   1     True
"""

If you want pyodbc to return bit columns as some other type you can use an output converter function as illustrated in the GitHub issue. The trick is getting SQLAlchemy to use it. That is done using an event listener.

import pandas as pd
import pyodbc
import sqlalchemy as sa

engine = sa.create_engine("mssql+pyodbc://scott:tiger^5HHH@mssql_199")

table_data = """\
SELECT -1 AS id, CAST(NULL AS bit) AS bit_col
UNION ALL
SELECT 0 AS id, CAST(0 AS bit) AS bit_col
UNION ALL
SELECT 1 AS id, CAST(1 AS bit) AS bit_col
"""

def handle_bit_type(bit_value):
    return bit_value


@sa.event.listens_for(engine, "connect")
def connect(conn, rec):
    conn.add_output_converter(pyodbc.SQL_BIT, handle_bit_type)


df = pd.read_sql_query(table_data, engine)
print(df)
"""
   id  bit_col
0  -1     None
1   0  b'\x00'
2   1  b'\x01'
"""

Edit: Or, if you use

def handle_bit_type(bit_value):
    if bit_value is None:
        rtn = None
    elif bit_value == b"\x00":
        rtn = "0"
    else:
        rtn = "1"
    return rtn

you'll get

df = pd.read_sql_query(table_data, engine)
print(df)
"""
   id bit_col
0  -1    None
1   0       0
2   1       1
"""

有没有一种方法可以使SQLalchemy不更改为True 1,而对于位列则为False?

雪花飘飘的天空 2025-02-19 06:50:51

看来您忘了在tsconfig.json中添加“页面”目录中的绝对路径映射。

尝试将其添加到您的tsconfig.json

{...
"paths": {
   ... other paths mappings
  "@pages/*": ["pages/*"],
...
}

It seems you forgot to add the absolute path mapping in your tsconfig.json for the 'pages' directory.

Try adding this to your tsconfig.json

{...
"paths": {
   ... other paths mappings
  "@pages/*": ["pages/*"],
...
}

在Next.js上使用jest无法找到模块错误

雪花飘飘的天空 2025-02-18 18:00:44

您必须使用最新的APIM 4.1.0的U2级进行迁移,因为它包含迁移所需的一些更改。这些更改在GA版本中不可用(从网站或GitHub下载)。

如果您有WSO2订阅,则可以使用U2工具[1]将4.1.0更新为最新版本。

[1] -

You have to use the latest U2 level of APIM 4.1.0 for migration since it contains some changes that are required for the migration. Those changes are not available in the GA release (downloaded from website or github).

If you have a WSO2 subscription, you can update 4.1.0 to latest version using the U2 tool[1].

[1] - https://updates.docs.wso2.com/en/latest/updates/overview/

无法从WSO2 AM 3.0.0到4.1.0迁移错误

雪花飘飘的天空 2025-02-18 01:07:14

使用 sed 非常适合精确的模式匹配,但是对于比较“大于”或“小于”的值,您可能会发现使用 grep awk更容易。例如,给定输入(日期和amp;时间之间的空间,将时间戳与日志输入分开的选项卡):

$ cat foo.txt
22/06/23 19:30:21   [Logs ... 5]
22/06/24 17:58:30   [Logs ... 4]
22/06/24 17:59:48   [Logs ... 3]
22/06/24 18:11:27   [Logs ... 2]
22/06/24 18:11:28   [Logs ... 1]

您可以使用 sed ,如其他答案所示(我将扩展到 awk 比较):

$ sed -n '\#22/06/24 17:58:30#, \#22/06/24 18:11:27#p' foo.txt
22/06/24 17:58:30   [Logs ... 4]
22/06/24 17:59:48   [Logs ... 3]
22/06/24 18:11:27   [Logs ... 2]

基本上是:

$ sed -n '/pattern1/, /pattern2/p' file.txt

请注意需要将/stateres1/,/stater2/更改为允许斜杠的东西(/)的棘手部分在搜索模式中。选择最适合您的数据的方法。我在这里使用

使用 awk 差不多,除了搜索模式中允许/有所不同。因此,

$ awk -F'\t' '/pattern1/, /pattern2/' file.txt

成为为了在模式中允许/允许/

$ awk -F'\t' '$0~v1, $0~v2' v1="pattern1" v2="pattern2" file.txt

但这仅与两个模式之间的界线匹配,并且模式必须完全匹配。我们可以像字母数字一样对待时间戳,而匹配“大于 staters1 到线上”的行小于“ staters2 :

$ awk -F'\t' '$1>=v1 && $1<=v2' v1="22/06/24 17:58:30"  v2="22/06/24 18:11:27" foo.txt  
22/06/24 17:58:30   [Logs ... 4]
22/06/24 17:59:48   [Logs ... 3]
22/06/24 18:11:27   [Logs ... 2]

但这是一个字母数字的比较,因此您可以使用其他日期(例如搜索模式:

$ awk -F'\t' '$1>=v1 && $1<=v2' v1="22/06/24 00:00:00"  v2="22/06/24 18:00:00" foo.txt  
22/06/24 17:58:30   [Logs ... 4]
22/06/24 17:59:48   [Logs ... 3]

您可以切换&gt; = and &lt; = 只需简单&gt; &lt; < /代码>取决于您是否要包含给定日期。

Using sed is good for exact pattern matching, but for comparing values "greater than" or "less than", you might find it easier to use grep or awk. For example, given the input (space between date & time, tab separating timestamp from log entry):

$ cat foo.txt
22/06/23 19:30:21   [Logs ... 5]
22/06/24 17:58:30   [Logs ... 4]
22/06/24 17:59:48   [Logs ... 3]
22/06/24 18:11:27   [Logs ... 2]
22/06/24 18:11:28   [Logs ... 1]

you could use sed as shown in the other answer (which I'll extend to awk by comparison):

$ sed -n '\#22/06/24 17:58:30#, \#22/06/24 18:11:27#p' foo.txt
22/06/24 17:58:30   [Logs ... 4]
22/06/24 17:59:48   [Logs ... 3]
22/06/24 18:11:27   [Logs ... 2]

It's basically:

$ sed -n '/pattern1/, /pattern2/p' file.txt

Note the tricky part about needing to change the /pattern1/, /pattern2/ to something that would allow slash (/) in the search pattern. Pick one that's best for your data. I'm using # here.

Using awk is about the same, except allowing / in the search pattern is a little different; so,

$ awk -F'\t' '/pattern1/, /pattern2/' file.txt

becomes, in order to allow / in the pattern:

$ awk -F'\t' '$0~v1, $0~v2' v1="pattern1" v2="pattern2" file.txt

But this just matches lines between two patterns, and the patterns must match exactly. We could treat the timestamps like alphanumeric patterns, and match lines "greater than" pattern1 up to lines "less than" pattern2:

$ awk -F'\t' '$1>=v1 && $1<=v2' v1="22/06/24 17:58:30"  v2="22/06/24 18:11:27" foo.txt  
22/06/24 17:58:30   [Logs ... 4]
22/06/24 17:59:48   [Logs ... 3]
22/06/24 18:11:27   [Logs ... 2]

But it's an alphanumeric comparison, so you can use other dates like search patterns:

$ awk -F'\t' '$1>=v1 && $1<=v2' v1="22/06/24 00:00:00"  v2="22/06/24 18:00:00" foo.txt  
22/06/24 17:58:30   [Logs ... 4]
22/06/24 17:59:48   [Logs ... 3]

You can switch the >= and <= to just simple > and < depending on whether you want to include the given date or not.

bash脚本以在日志文件中的两个不同时间戳之间提取行

雪花飘飘的天空 2025-02-17 23:29:55

我建议改用年份转换为角色。这应该与传单一起使用。

## Libraries
library(dplyr)
library(lubridate)

df$USER_Year1 = as.character(df$USER_Year)
str(df)

输出

> df$USER_Year1
 [1] "2022" "2021" "2022" "2022" "2022" "2022" "2022" "2022" "2022" "2022"
> df
    USER_Date USER_Year USER_Month USER_Day USER_Year1
1  2022-01-04      2022          1        4       2022
2  2021-01-06      2021          1        6       2021
3  2022-01-19      2022          1       19       2022
4  2022-01-20      2022          1       20       2022
5  2022-01-24      2022          1       24       2022
6  2022-01-27      2022          1       27       2022
7  2022-01-28      2022          1       28       2022
8  2022-01-19      2022          1       19       2022
9  2022-01-31      2022          1       31       2022
10 2022-01-31      2022          1       31       2022
> str(df)
'data.frame':   10 obs. of  5 variables:
 $ USER_Date : Date, format: "2022-01-04" "2021-01-06" "2022-01-19" "2022-01-20" ...
 $ USER_Year : num  2022 2021 2022 2022 2022 ...
 $ USER_Month: num  1 1 1 1 1 1 1 1 1 1
 $ USER_Day  : num  4 6 19 20 24 27 28 19 31 31
 $ USER_Year1: chr  "2022" "2021" "2022" "2022" ...
 - attr(*, "sfc_columns")= chr [1:2] "x" "y"

I'd recommend converting the year to character instead. This should work with leaflet.

## Libraries
library(dplyr)
library(lubridate)

df$USER_Year1 = as.character(df$USER_Year)
str(df)

Output

> df$USER_Year1
 [1] "2022" "2021" "2022" "2022" "2022" "2022" "2022" "2022" "2022" "2022"
> df
    USER_Date USER_Year USER_Month USER_Day USER_Year1
1  2022-01-04      2022          1        4       2022
2  2021-01-06      2021          1        6       2021
3  2022-01-19      2022          1       19       2022
4  2022-01-20      2022          1       20       2022
5  2022-01-24      2022          1       24       2022
6  2022-01-27      2022          1       27       2022
7  2022-01-28      2022          1       28       2022
8  2022-01-19      2022          1       19       2022
9  2022-01-31      2022          1       31       2022
10 2022-01-31      2022          1       31       2022
> str(df)
'data.frame':   10 obs. of  5 variables:
 $ USER_Date : Date, format: "2022-01-04" "2021-01-06" "2022-01-19" "2022-01-20" ...
 $ USER_Year : num  2022 2021 2022 2022 2022 ...
 $ USER_Month: num  1 1 1 1 1 1 1 1 1 1
 $ USER_Day  : num  4 6 19 20 24 27 28 19 31 31
 $ USER_Year1: chr  "2022" "2021" "2022" "2022" ...
 - attr(*, "sfc_columns")= chr [1:2] "x" "y"

r错误中的错误()`:!计算'年=年度(用户_ year)````''。由`as.posixlt.numeric()`::! &#x27; rigins&#x27;必须提供

雪花飘飘的天空 2025-02-17 19:08:16

我怀疑您只是没有加载jQuery,因为代码看起来还不错。

尝试在开始时添加。

<script src="https://ajax.googleapis.com/ajax/libs/jquery/3.6.0/jquery.min.js"></script>

I suspect that you just didn't load jQuery as the codes looks ok.

try add this at the beginning.

<script src="https://ajax.googleapis.com/ajax/libs/jquery/3.6.0/jquery.min.js"></script>

选择下拉菜单而无需提交按钮

雪花飘飘的天空 2025-02-17 09:18:27

我以为在您的情况下,我认为当使用板API时,您的目标可能可以使用。

解决方法1:

此解决方法使用板API。

用法:

1。准备Google电子表格。

  1. 请创建一个新的Google电子表格。

  2. 来自示例。我有一个命名的范围苹果(地址为“ Sheet10!b2:b”),该苹果用于大量板单元的数据验证。可以更改苹果的数据范围(在脚本中),例如“ Sheet10!d2:d”。,请插入“ Sheet10”的表格,然后将样本值放在单元格“ B2:B”和“ D2:D”。

2。示例脚本。

请将以下脚本复制到电子表格的脚本编辑器并保存脚本。并且,请在高级Google Services 启用Sheable Sheable API 。

function myFunction() {
  const namedRangeName = "Apple"; // Please set the name of the named range.

  const ss = SpreadsheetApp.getActiveSpreadsheet();
  const sheet = ss.getSheetByName("Sheet10");
  const requests = [{ updateCells: { range: { sheetId: sheet.getSheetId(), startRowIndex: 0, endRowIndex: 1, startColumnIndex: 0, endColumnIndex: 1 }, rows: [{ values: [{ dataValidation: { condition: { values: [{ userEnteredValue: "=" + namedRangeName }], type: "ONE_OF_RANGE" }, showCustomUi: true } }] }], fields: "dataValidation" } }];
  Sheets.Spreadsheets.batchUpdate({ requests }, ss.getId());
}
  • 在此请求中,命名范围的名称直接放在 userEnteredValue 中。

3。测试。

将此脚本运行到上述样本电子表格时,将获得以下结果。

当看到此演示时,首先,您可以看到具有“ b1:b1000”单元格的“苹果”范围。运行脚本后,将数据验证放在带有“ Apple”范围的单元格“ A1”中。在这种情况下,数据验证的值表示“ B1:B1000”。当名称范围“ Apple”范围从“ B1:B1000”更改为“ D1:D1000”,并且确认了“ A1”的数据验证,发现值从“ B1:B1000”更改为“ D1” :D1000“。

解决方法2:

此解决方法使用Google电子表格服务(电子表格)。在当前阶段,Google电子表格服务(电子表格)似乎无法直接实现您的目标。在评论中的讨论中已经提到了这一点, themaster的答案。当您想实现这一目标时,如何使用onChange检查命名范围的范围是否会像以下可进行2一样更改?

用法:

1。准备Google电子表格。

  1. 请创建一个新的Google电子表格。

  2. 来自示例。我有一个命名的范围苹果(地址为“ Sheet10!b2:b”),该苹果用于大量板单元的数据验证。可以更改苹果的数据范围(在脚本中),例如“ Sheet10!d2:d”。,请插入“ Sheet10”的表格,然后将样本值放在单元格“ B2:B”和“ D2:D”。

2。示例脚本。

请将以下脚本复制到电子表格的脚本编辑器并保存脚本。和,请安装on Change onChange on Change to to function onCode> onCode> on Code> onChange

首先,请运行 CreateAtavalidation 。这样,将数据验证放在“ Sheet10”的单元格“ A1”中。在这种情况下,设定范围是从命名范围“ Apple”中检索的范围。因此,在这种情况下,范围为 Sheet10!b2:b1000

在下一步中,请更改名称范围的范围从 Sheet11!B2:B1000 到Sheet10!D2:D1000 。这样, onChange`函数将通过安装的Onchange触发器自动运行。这样,更新了“ A2”的数据验证。这样,数据验证的值将更改。

const namedRangeName = "Apple"; // Please set the name of the named range.
const datavalidationCell = "Sheet10!A2"; // As a sample. data validation is put to this cell.

function onChange(e) {
  if (e.changeType != "OTHER") return;
  const range = e.source.getRangeByName(namedRangeName);
  const a1Notation = `'${range.getSheet().getSheetName()}'!${range.getA1Notation()}`;
  const prop = PropertiesService.getScriptProperties();
  const previousRange = prop.getProperty("previousRange");
  if (previousRange != a1Notation) {
    const rule = SpreadsheetApp.newDataValidation().requireValueInRange(e.source.getRangeByName(namedRangeName)).setAllowInvalid(false).build();
    e.source.getRange(datavalidationCell).setDataValidation(rule);
  }
  prop.setProperty("previousRange", a1Notation);
}

// First, please run this function.
function createDataValidation() {
  const ss = SpreadsheetApp.getActiveSpreadsheet();
  const rule = SpreadsheetApp.newDataValidation().requireValueInRange(ss.getRangeByName(namedRangeName)).setAllowInvalid(false).build();
  ss.getRange(datavalidationCell).setDataValidation(rule);
  const prop = PropertiesService.getScriptProperties();
  const range = ss.getRangeByName(namedRangeName);
  const a1Notation = `'${range.getSheet().getSheetName()}'!${range.getA1Notation()}`;
  prop.setProperty("previousRange", a1Notation);
}

参考:

I thought that in your situation, I thought that when Sheets API is used, your goal might be able to be used.

Workaround 1:

This workaround uses Sheets API.

Usage:

1. Prepare a Google Spreadsheet.

  1. Please create a new Google Spreadsheet.

  2. From Example. I have a named range Apples (address "Sheet10!B2:B"), which in use for data validation for plenty of sheet cells. The data range for Apples can be changed (in a script), e.g. to "Sheet10!D2:D"., please insert a sheet of "Sheet10" and put sample values to the cells "B2:B" and "D2:D".

  3. Please set the named range Sheet10!B2:B as Apple.

2. Sample script.

Please copy and paste the following script to the script editor of Spreadsheet and save the script. And, please enable Sheets API at Advanced Google services.

function myFunction() {
  const namedRangeName = "Apple"; // Please set the name of the named range.

  const ss = SpreadsheetApp.getActiveSpreadsheet();
  const sheet = ss.getSheetByName("Sheet10");
  const requests = [{ updateCells: { range: { sheetId: sheet.getSheetId(), startRowIndex: 0, endRowIndex: 1, startColumnIndex: 0, endColumnIndex: 1 }, rows: [{ values: [{ dataValidation: { condition: { values: [{ userEnteredValue: "=" + namedRangeName }], type: "ONE_OF_RANGE" }, showCustomUi: true } }] }], fields: "dataValidation" } }];
  Sheets.Spreadsheets.batchUpdate({ requests }, ss.getId());
}
  • In this request, the name of the named range is directly put to userEnteredValue.

3. Testing.

When this script is run to the above sample Spreadsheet, the following result is obtained.

enter image description here

When this demonstration is seen, first, you can see the named range of "Apple" which has the cells "B1:B1000". When a script is run, data validation is put to the cell "A1" with the named range of "Apple". In this case, the values of data validation indicate "B1:B1000". When the range named range "Apple" is changed from "B1:B1000" to "D1:D1000" and the data validation of "A1" is confirmed, it is found that the values are changed from "B1:B1000" to "D1:D1000".

Workaround 2:

This workaround uses the Google Spreadsheet service (SpreadsheetApp). In the current stage, it seems that the Google Spreadsheet service (SpreadsheetApp) cannot directly achieve your goal. This has already been mentioned in the discussions in the comment and TheMaster's answer. When you want to achieve this, how about checking whether the range of the named range is changed using OnChange as following workaround 2?

Usage:

1. Prepare a Google Spreadsheet.

  1. Please create a new Google Spreadsheet.

  2. From Example. I have a named range Apples (address "Sheet10!B2:B"), which in use for data validation for plenty of sheet cells. The data range for Apples can be changed (in a script), e.g. to "Sheet10!D2:D"., please insert a sheet of "Sheet10" and put sample values to the cells "B2:B" and "D2:D".

  3. Please set the named range Sheet10!B2:B as Apple.

2. Sample script.

Please copy and paste the following script to the script editor of Spreadsheet and save the script. And, please install OnChange trigger to the function onChange.

First, please run createDataValidation. By this, data validation is put to the cell "A1" of "Sheet10". In this case, the set range is the range retrieved from the named range "Apple". So, in this case, the range is Sheet10!B2:B1000.

As the next step, please change the range of the named range from Sheet10!B2:B1000 to Sheet10!D2:D1000. By this, onChange` function is automatically run by the installed OnChange trigger. By this, the data validation of "A2" is updated. By this, the values of data validation are changed.

const namedRangeName = "Apple"; // Please set the name of the named range.
const datavalidationCell = "Sheet10!A2"; // As a sample. data validation is put to this cell.

function onChange(e) {
  if (e.changeType != "OTHER") return;
  const range = e.source.getRangeByName(namedRangeName);
  const a1Notation = `'${range.getSheet().getSheetName()}'!${range.getA1Notation()}`;
  const prop = PropertiesService.getScriptProperties();
  const previousRange = prop.getProperty("previousRange");
  if (previousRange != a1Notation) {
    const rule = SpreadsheetApp.newDataValidation().requireValueInRange(e.source.getRangeByName(namedRangeName)).setAllowInvalid(false).build();
    e.source.getRange(datavalidationCell).setDataValidation(rule);
  }
  prop.setProperty("previousRange", a1Notation);
}

// First, please run this function.
function createDataValidation() {
  const ss = SpreadsheetApp.getActiveSpreadsheet();
  const rule = SpreadsheetApp.newDataValidation().requireValueInRange(ss.getRangeByName(namedRangeName)).setAllowInvalid(false).build();
  ss.getRange(datavalidationCell).setDataValidation(rule);
  const prop = PropertiesService.getScriptProperties();
  const range = ss.getRangeByName(namedRangeName);
  const a1Notation = `'${range.getSheet().getSheetName()}'!${range.getA1Notation()}`;
  prop.setProperty("previousRange", a1Notation);
}

References:

如何在Google电子表格中以编程方式(在Google Apps脚本中)设置命名范围?

更多

推荐作者

櫻之舞

文章 0 评论 0

弥枳

文章 0 评论 0

m2429

文章 0 评论 0

野却迷人

文章 0 评论 0

我怀念的。

文章 0 评论 0

更多

友情链接

    我们使用 Cookies 和其他技术来定制您的体验包括您的登录状态等。通过阅读我们的 隐私政策 了解更多相关信息。 单击 接受 或继续使用网站,即表示您同意使用 Cookies 和您的相关数据。
    原文