答:
Most likely your subscribe is getting called after your call to forEach
The best fix would be to initialize your notices to an empty array and then loop through this.notices inside the subscribe call:

```<code>notices: notice[] = [];

ngOnInit() {
  this.dataService.getCards().subscribe( data => {
  this.notices = data
  this.notices.forEach(n => {
     console.log('test')
  });
 });
}
</code>```

Title: Angular: ERROR Error: Uncaught (in promise): TypeError: Cannot read properties of undefined (reading 'forEach')

Body:
Most likely your subscribe is getting called after your call to forEach
The best fix would be to initialize your notices to an empty array and then loop through this.notices inside the subscribe call:

notices: notice[] = [];

ngOnInit() {
  this.dataService.getCards().subscribe( data => {
  this.notices = data
  this.notices.forEach(n => {
     console.log('test')
  });
 });
}


来源: stackexchange

问:
Problem calling WCF service internet
I am developing a WCF service that will be called by customer in internet. The service is hosted in IIS7 and accept only http. For clients call us from https we do is have a reverse proxy that forwards the request to the application https to http. The customer give a https url to connect and does so smoothly, adding the reference to the service properly. The problem comes when trying to create a client and add in your endpoint https and execute it, as it reads:

System.ArgumentException: The provided URI scheme 'https' is invalid,

  expected 'http'. Parameter name: via.

I leave part of the service's web.config:

```<code><bindings>
 <wsHttpBinding>
  <binding name="ConfigEP">
   <security mode="Message">
    <message clientCredentialType="Certificate" />
   </security>
  </binding>
 </wsHttpBinding>
</bindings>
<serviceHostingEnvironment aspNetCompatibilityEnabled="true">
 <baseAddressPrefixFilters>
  <add prefix="http://serverInterno/App/"/>
 </baseAddressPrefixFilters>
</serviceHostingEnvironment>
<services>
 <service behaviorConfiguration="App.AppM_NameBehavior" name="App.AppM_Name">
  <endpoint address="" behaviorConfiguration="App.AppM_NameEPBehavior" binding="wsHttpBinding" bindingConfiguration="ConfigEP" name="App.AppM_NameEP" bindingNamespace="http://siteName/AppM_Name" contract="App.IAppM_Name" />
 </service>
</services>
<behaviors>
 <endpointBehaviors>
  <behavior name="App.AppM_NameEPBehavior">
   <wsdlExtensions location="https://urlsegura/App/Appm_Name.svc" singleFile="true" />
  </behavior>
 </endpointBehaviors>
 <serviceBehaviors>
  <behavior name="App.AppM_NameBehavior">
   <serviceDebug includeExceptionDetailInFaults="true" />
   <serviceMetadata httpGetEnabled="true" httpsGetEnabled="false" />
   <serviceCredentials>
    <clientCertificate>
     <authentication customCertificateValidatorType="App.Validador, App" certificateValidationMode="Custom" />
    </clientCertificate>
    <serviceCertificate findValue="XX XX XX XX XX XX XX XX XX XX" x509FindType="FindBySerialNumber" />
   </serviceCredentials>
  </behavior>
 </serviceBehaviors>
</behaviors>
<extensions>
 <behaviorExtensions>
  <add name="wsdlExtensions" type="WCFExtras.Wsdl.WsdlExtensionsConfig, WCFExtras, Version=1.0.0.0, Culture=neutral, PublicKeyToken=null"/>
 </behaviorExtensions>
</extensions>
</code>```

and here the client's app.config:

```<code><system.serviceModel>
 <behaviors>
  <endpointBehaviors>
   <behavior name="NewBehavior">
    <clientCredentials>
     <clientCertificate findValue="XX XX XX XX XX XX XX XX XX XX" x509FindType="FindBySerialNumber" />
    </clientCredentials>
   </behavior>
  </endpointBehaviors>
 </behaviors>
 <bindings>
  <wsHttpBinding>
   <binding name="App.AppM_NameEP" closeTimeout="00:01:00" openTimeout="00:01:00" receiveTimeout="00:10:00" sendTimeout="00:01:00" bypassProxyOnLocal="false" transactionFlow="false" hostNameComparisonMode="StrongWildcard" maxBufferPoolSize="524288" maxReceivedMessageSize="65536" messageEncoding="Text" textEncoding="utf-8" useDefaultWebProxy="true" allowCookies="false">
    <readerQuotas maxDepth="32" maxStringContentLength="8192" maxArrayLength="16384" maxBytesPerRead="4096" maxNameTableCharCount="16384" />
    <reliableSession ordered="true" inactivityTimeout="00:10:00" enabled="false" />
    <security mode="Message">
     <transport clientCredentialType="None" proxyCredentialType="None" realm="" />
     <message clientCredentialType="Certificate" negotiateServiceCredential="true" algorithmSuite="Default" establishSecurityContext="true" />
    </security>
   </binding>
  </wsHttpBinding>
 </bindings>
 <client>
  <endpoint address="https://urlsegura/App/Appm_Name.svc" binding="wsHttpBinding" bindingConfiguration="App.AppM_NameEP" contract="App.IAppM_Name" name="App.AppM_NameEP">
   <identity>
    <certificate encodedValue="XXXX" />
   </identity>
  </endpoint>
 </client>
</system.serviceModel>
</code>```

Thanks in advance.
Best regards.

答:
I don't understand the reverse proxy you describe but it seems you're trying to support access from both HTTP & HTTPS. To do this, you will need to add a second endpoint. You'd configure the service something like this:

```<code><wsHttpBinding>
 <binding name="ConfigEP">
  <security mode="Message">
   <message clientCredentialType="Certificate" />
  </security>
 </binding>
 <binding name="ConfigEPHttps">
  <security mode="TransportWithMessageCredential">
   <message clientCredentialType="Certificate" />
  </security>
 </binding>
</wsHttpBinding>
</code>```

and this add the new endpoint:

```<code><service behaviorConfiguration="App.AppM_NameBehavior" name="App.AppM_Name">
 <endpoint address="" behaviorConfiguration="App.AppM_NameEPBehavior"
   binding="wsHttpBinding"
   bindingConfiguration="ConfigEP"
   name="App.AppM_NameEP"
   bindingNamespace="http://siteName/AppM_Name"
   contract="App.IAppM_Name" />
 <endpoint address="secure" behaviorConfiguration="App.AppM_NameEPBehavior"
   binding="wsHttpBinding"
   bindingConfiguration="ConfigEPHttps"
   name="App.AppM_NameEPHttps"
   bindingNamespace="http://siteName/AppM_Name"
   contract="App.IAppM_Name" />
</service>
</code>```

You also need make this change to get the WSDL over HTTPS:

```<code><serviceMetadata httpGetEnabled="true" httpsGetEnabled="true" />
</code>```

ContentLicense: CC BY-SA 3.0

Title: Problem calling WCF service internet

Body:
I am developing a WCF service that will be called by customer in internet. The service is hosted in IIS7 and accept only http. For clients call us from https we do is have a reverse proxy that forwards the request to the application https to http. The customer give a https url to connect and does so smoothly, adding the reference to the service properly. The problem comes when trying to create a client and add in your endpoint https and execute it, as it reads:

System.ArgumentException: The provided URI scheme 'https' is invalid,

  expected 'http'. Parameter name: via.

I leave part of the service's web.config:

<bindings>
 <wsHttpBinding>
  <binding name="ConfigEP">
   <security mode="Message">
    <message clientCredentialType="Certificate" />
   </security>
  </binding>
 </wsHttpBinding>
</bindings>
<serviceHostingEnvironment aspNetCompatibilityEnabled="true">
 <baseAddressPrefixFilters>
  <add prefix="http://serverInterno/App/"/>
 </baseAddressPrefixFilters>
</serviceHostingEnvironment>
<services>
 <service behaviorConfiguration="App.AppM_NameBehavior" name="App.AppM_Name">
  <endpoint address="" behaviorConfiguration="App.AppM_NameEPBehavior" binding="wsHttpBinding" bindingConfiguration="ConfigEP" name="App.AppM_NameEP" bindingNamespace="http://siteName/AppM_Name" contract="App.IAppM_Name" />
 </service>
</services>
<behaviors>
 <endpointBehaviors>
  <behavior name="App.AppM_NameEPBehavior">
   <wsdlExtensions location="https://urlsegura/App/Appm_Name.svc" singleFile="true" />
  </behavior>
 </endpointBehaviors>
 <serviceBehaviors>
  <behavior name="App.AppM_NameBehavior">
   <serviceDebug includeExceptionDetailInFaults="true" />
   <serviceMetadata httpGetEnabled="true" httpsGetEnabled="false" />
   <serviceCredentials>
    <clientCertificate>
     <authentication customCertificateValidatorType="App.Validador, App" certificateValidationMode="Custom" />
    </clientCertificate>
    <serviceCertificate findValue="XX XX XX XX XX XX XX XX XX XX" x509FindType="FindBySerialNumber" />
   </serviceCredentials>
  </behavior>
 </serviceBehaviors>
</behaviors>
<extensions>
 <behaviorExtensions>
  <add name="wsdlExtensions" type="WCFExtras.Wsdl.WsdlExtensionsConfig, WCFExtras, Version=1.0.0.0, Culture=neutral, PublicKeyToken=null"/>
 </behaviorExtensions>
</extensions>

and here the client's app.config:

<system.serviceModel>
 <behaviors>
  <endpointBehaviors>
   <behavior name="NewBehavior">
    <clientCredentials>
     <clientCertificate findValue="XX XX XX XX XX XX XX XX XX XX" x509FindType="FindBySerialNumber" />
    </clientCredentials>
   </behavior>
  </endpointBehaviors>
 </behaviors>
 <bindings>
  <wsHttpBinding>
   <binding name="App.AppM_NameEP" closeTimeout="00:01:00" openTimeout="00:01:00" receiveTimeout="00:10:00" sendTimeout="00:01:00" bypassProxyOnLocal="false" transactionFlow="false" hostNameComparisonMode="StrongWildcard" maxBufferPoolSize="524288" maxReceivedMessageSize="65536" messageEncoding="Text" textEncoding="utf-8" useDefaultWebProxy="true" allowCookies="false">
    <readerQuotas maxDepth="32" maxStringContentLength="8192" maxArrayLength="16384" maxBytesPerRead="4096" maxNameTableCharCount="16384" />
    <reliableSession ordered="true" inactivityTimeout="00:10:00" enabled="false" />
    <security mode="Message">
     <transport clientCredentialType="None" proxyCredentialType="None" realm="" />
     <message clientCredentialType="Certificate" negotiateServiceCredential="true" algorithmSuite="Default" establishSecurityContext="true" />
    </security>
   </binding>
  </wsHttpBinding>
 </bindings>
 <client>
  <endpoint address="https://urlsegura/App/Appm_Name.svc" binding="wsHttpBinding" bindingConfiguration="App.AppM_NameEP" contract="App.IAppM_Name" name="App.AppM_NameEP">
   <identity>
    <certificate encodedValue="XXXX" />
   </identity>
  </endpoint>
 </client>
</system.serviceModel>

Thanks in advance.
Best regards.

Body:
I don't understand the reverse proxy you describe but it seems you're trying to support access from both HTTP & HTTPS. To do this, you will need to add a second endpoint. You'd configure the service something like this:

<wsHttpBinding>
 <binding name="ConfigEP">
  <security mode="Message">
   <message clientCredentialType="Certificate" />
  </security>
 </binding>
 <binding name="ConfigEPHttps">
  <security mode="TransportWithMessageCredential">
   <message clientCredentialType="Certificate" />
  </security>
 </binding>
</wsHttpBinding>

and this add the new endpoint:

<service behaviorConfiguration="App.AppM_NameBehavior" name="App.AppM_Name">
 <endpoint address="" behaviorConfiguration="App.AppM_NameEPBehavior"
   binding="wsHttpBinding"
   bindingConfiguration="ConfigEP"
   name="App.AppM_NameEP"
   bindingNamespace="http://siteName/AppM_Name"
   contract="App.IAppM_Name" />
 <endpoint address="secure" behaviorConfiguration="App.AppM_NameEPBehavior"
   binding="wsHttpBinding"
   bindingConfiguration="ConfigEPHttps"
   name="App.AppM_NameEPHttps"
   bindingNamespace="http://siteName/AppM_Name"
   contract="App.IAppM_Name" />
</service>

You also need make this change to get the WSDL over HTTPS:

<serviceMetadata httpGetEnabled="true" httpsGetEnabled="true" />


问:
Redux Action is Dispatched but state not updating accordingly
When i click the delete button the action(removeBus) is dispatched and the correct payload value is sent however the store is not updating
here is my busSlice file

```<code>import { createSlice } from "@reduxjs/toolkit";
const initialState = [
  {
    id: "0",
    description: "bus1"
  },
  {
    id: "1",
    description: "bus2"
  }
];
const busSlice = createSlice({
  name: "bus",
  initialState,
  reducers: {
    removeBus: (state, action) => {
      state.filter((bus) => bus.id !== action.payload);
      console.log(action.payload);
    }
  }
});
export const { removeBus } = busSlice.actions;
export default busSlice.reducer;

</code>```

here is where  i created and export the store

```<code>import { configureStore } from "@reduxjs/toolkit";
import busReducer from "../features/busSlice";
export const store = configureStore({
  reducer: {
    busses: busReducer
  }
});

</code>```

the component that uses the state is created in the following code and App is wrapped inside a redux provider Component and the above store is provided as a props in index.js

```<code>import "./styles.css";
import { useSelector, useDispatch } from "react-redux";
import { removeBus } from "./features/busSlice";
export default function App() {
  const dispatch = useDispatch();
  const busses = useSelector((state) => state.busses);
  const handleRemove = (id) => {
    dispatch(removeBus(id));
  };

  return (
    <div className="App">
      {busses.map((bus) => (
        <ul>
          <li key={bus.id}>
            <p>{bus.description}</p>
            <button onClick={() => handleRemove(bus.id)}>delete</button>
          </li>
        </ul>
      ))}
    </div>
  );
}

</code>```

using redux dev tools i can see an action busses\removeBus is dispatched with the appropriate payload value but nothing is happening to the state.

答:
you are not updating state correctly you need to say change my state to filtered state

like this

removeBus(state, action){
      state = state.filter((bus) => bus.id !== action.payload);
      console.log(action.payload);
}
```

ContentLicense: CC BY-SA 4.0

Body:
When i click the delete button the action(removeBus) is dispatched and the correct payload value is sent however the store is not updating
here is my busSlice file

import { createSlice } from "@reduxjs/toolkit";
const initialState = [
  {
    id: "0",
    description: "bus1"
  },
  {
    id: "1",
    description: "bus2"
  }
];
const busSlice = createSlice({
  name: "bus",
  initialState,
  reducers: {
    removeBus: (state, action) => {
      state.filter((bus) => bus.id !== action.payload);
      console.log(action.payload);
    }
  }
});
export const { removeBus } = busSlice.actions;
export default busSlice.reducer;

here is where  i created and export the store

import { configureStore } from "@reduxjs/toolkit";
import busReducer from "../features/busSlice";
export const store = configureStore({
  reducer: {
    busses: busReducer
  }
});

the component that uses the state is created in the following code and App is wrapped inside a redux provider Component and the above store is provided as a props in index.js

import "./styles.css";
import { useSelector, useDispatch } from "react-redux";
import { removeBus } from "./features/busSlice";
export default function App() {
  const dispatch = useDispatch();
  const busses = useSelector((state) => state.busses);
  const handleRemove = (id) => {
    dispatch(removeBus(id));
  };

  return (

      {busses.map((bus) => (

{bus.description}

            <button onClick={() => handleRemove(bus.id)}>delete</button>

      ))}

  );
}

using redux dev tools i can see an action busses\removeBus is dispatched with the appropriate payload value but nothing is happening to the state.


问:
How to use search result after page reload to download csv
I have two functions - 1 showing the results and 1 to download results that are on page.

The problem is that I can't find a way how to download only the results. Instead when I hit Download button it downloads all records in database.

This is what I have in my controler

```<code>public function index(Request $request)
{
    $user = DB::table('downloads')
        ->select('user_id as downloader_id', DB::raw('COUNT(id) as count'))
        ->groupBy('user_id');

    if(isset($request->startDate) && isset($request->dateEnd)) {
        $user = $user->whereBetween(DB::raw("DATE_FORMAT(downloads.created_at, '%Y-%m-%d')"), [$request->startDate, $request->dateEnd]);
    } elseif (isset($request->startDate)) {
        $user = $user->where('created_at',$request->startDate);
    }

    $works=DB::table('users')
        ->joinSub($user, 'downloads_byuser', function ($join) {
            $join->on('id', '=', 'downloads_byuser.downloader_id');
        })
        ->select('users.id as user_id', 'users.name as name', 'users.email as email', 'count')
        ->get();

    return view('admin.downloadsuser', compact("works"));
}

public function download(Request $request){

    $headers = array(
       // some headers
    );

    //creating the download file
    $filename =  public_path("Downloads.csv");
    $handle = fopen($filename, 'w');

    //adding the first row
    fputcsv($handle, [
        "Email",
        "Downlaods",
    ]);

    //adding the data from the array
    foreach ($works as $each_user) {
        fputcsv($handle, [
            $each_user->email,
            $each_user->count,
        ]);

    }
    fclose($handle);

    return Response::download($filename, "Downloads.csv", $headers);
}
</code>```

And this is in the blade

```<code><form>
    <input type="date" name="startDate" id="startDate">
    <input type="date" name="dateEnd" id="dateEnd">
    <button type="submit" class="btn btn-primary"> Filter </button>
</form>
<form action="{{ route('admin.works.download') }}">
    <button type="submit" class="btn btn-primary"> Download </button>
</form>

<table class="table">
<thead>
    <tr>
        <th>User</th>
        <th>Email</th>
        <th>Downloads</th>
    </tr>
</thead>
<tbody>
    @foreach($works as $work)
        <tr>
            <td>{{ $work->name }}</td>
            <td>{{ $work->email }}</td>
            <td>{{ $work->count }}</td>
        </tr>
    @endforeach
</tbody>
</table>
</code>```

Any help is appreciated.

答:
Store the date when the search criteria are provided in the session, like this

```<code>\Session::put('startDate', $request->startDate);
\Session::put('dateEnd', $request->dateEnd);
</code>```

After that in your download function retrieve the session dates. If none exists, the second parameter is returned instead.

```<code>$startDate = Session::get('startDate', '2022-02-11');
$dateEnd = Session::get('dateEnd', '2022-02-11');
</code>```

You could just make them null, and have your query scope ignore them - which is essentially making the default export return all-time (unfiltered) records.

```<code>$startDate = Session::get('startDate', null);
$dateEnd = Session::get('dateEnd', null);
</code>```

Or use carbon and return current date as default - \Carbon\Carbon::parse()

Body:
I have two functions - 1 showing the results and 1 to download results that are on page.

The problem is that I can't find a way how to download only the results. Instead when I hit Download button it downloads all records in database.

This is what I have in my controler

public function index(Request $request)
{
    $user = DB::table('downloads')
        ->select('user_id as downloader_id', DB::raw('COUNT(id) as count'))
        ->groupBy('user_id');

    if(isset($request->startDate) && isset($request->dateEnd)) {
        $user = $user->whereBetween(DB::raw("DATE_FORMAT(downloads.created_at, '%Y-%m-%d')"), [$request->startDate, $request->dateEnd]);
    } elseif (isset($request->startDate)) {
        $user = $user->where('created_at',$request->startDate);
    }

    $works=DB::table('users')
        ->joinSub($user, 'downloads_byuser', function ($join) {
            $join->on('id', '=', 'downloads_byuser.downloader_id');
        })
        ->select('users.id as user_id', 'users.name as name', 'users.email as email', 'count')
        ->get();

    return view('admin.downloadsuser', compact("works"));
}

public function download(Request $request){

    $headers = array(
       // some headers
    );

    //creating the download file
    $filename =  public_path("Downloads.csv");
    $handle = fopen($filename, 'w');

    //adding the first row
    fputcsv($handle, [
        "Email",
        "Downlaods",
    ]);

    //adding the data from the array
    foreach ($works as $each_user) {
        fputcsv($handle, [
            $each_user->email,
            $each_user->count,
        ]);

    }
    fclose($handle);

    return Response::download($filename, "Downloads.csv", $headers);
}

And this is in the blade

<form>
    <input type="date" name="startDate" id="startDate">
    <input type="date" name="dateEnd" id="dateEnd">
    <button type="submit" class="btn btn-primary"> Filter </button>
</form>
<form action="{{ route('admin.works.download') }}">
    <button type="submit" class="btn btn-primary"> Download </button>
</form>

        User
        Email
        Downloads

    @foreach($works as $work)

            {{ $work->name }}
            {{ $work->email }}
            {{ $work->count }}

    @endforeach

Any help is appreciated.

Body:
Store the date when the search criteria are provided in the session, like this

\Session::put('startDate', $request->startDate);
\Session::put('dateEnd', $request->dateEnd);

After that in your download function retrieve the session dates. If none exists, the second parameter is returned instead.

$startDate = Session::get('startDate', '2022-02-11');
$dateEnd = Session::get('dateEnd', '2022-02-11');

You could just make them null, and have your query scope ignore them - which is essentially making the default export return all-time (unfiltered) records.

$startDate = Session::get('startDate', null);
$dateEnd = Session::get('dateEnd', null);

Or use carbon and return current date as default - \Carbon\Carbon::parse()


问:
In the console window I keep getting this error undefined (reading 'takeRecords')
Error handling response: TypeError: Cannot read properties of undefined (reading 'takeRecords')
at Function.e.closeListeners (chrome-extension://clmkdohmabikagpnhjmgacbclihgmdje/content-script.js:1:5858)</p>

答: The problem is in one of the chrome extensions. I searched for "Function.e.closeListeners" and the first on the list is Eno. Look for Eno in my extensions. Eno from CapitalOne is on, I turned it off and the error went away. Just want to share in case somebody else gets the same error.</p>


问:
AWS fargate running 24*7
we have an application which runs for 15 mins * 3 times a day. We dont want container to be running always (24*7). Once applicaiton finish, container should stop.
i dont think we can achieve this in AWS Fargate

Will you please recommend any such container services in AWS?

答:
From your description, you need to setup an ECS Scheduled Task, which will start the Fargate container at certain times of day, the container will stop once the process exits, and it will not be restarted until the next scheduled time.

Alternatively, you can some other process outside of ECS, such as a Lambda function, call the ECS RunTask API to accomplish the same thing.

In the above scenario, you will only be billed for the time the Fargate task is running.

This contrasts with an ECS Service, which typically keeps one or more tasks running 24/7. Although you can setup ECS Service auto-scaling to scale down to 0 tasks, which is another option you might pursue.

Title: AWS fargate running 24*7


问:
Send email out when a select query returns a certain value
I want to send an email out after a select query returns a certain value.

I currently pipe it to a text file just to give me some display.

```<code>echo "SELECT * FROM jobs WHERE status = -20;" | mysql -u user -pXXX -h
          servername --database=chosenDB >> /var/log/DBcheck.txt
</code>```

now when the value returns to "-20" or whatever number I choose how would I go about creating an email alert to send when it turns true.  Using it as a monitoring tool.  The server I am running already is set up with postfix, which is confirmed working.

any info would be greatly appreciated.

thanks!

答:
If your query returns a single line of output, perhaps something like this.

```<code>#!/bin/sh

case `echo "SELECT * FROM jobs WHERE status = -20;" |
    mysql -u user -pXXX -h servername --database=chosenDB` in
  -20) echo It is minus twenty | /usr/lib/sendmail -oi you@example.com ;;
esac
</code>```

More usefully, put the output in a temp file, and erase it if it's uninteresting.

```<code>#!/bin/sh

t=`mktemp -t muesliXXXXXXX`  # Not entirely portable -- google this bit
trap 'rm -f $t' 0
trap 'exit 127' 1 2 3 5 15

mysql -u user -pXXX -h servername --database=chosenDB <<'____HERE' >$t
    SELECT * FROM jobs WHERE status = -20;
____HERE

if grep -qw '-20' $t; then
  ( cat <<'____HERE'; cat $t) | /usr/lib/sendmail -oi -t
From: Friendly Cron Job <root@example.com>
To: you <you@example.com>
Subject: It is Minus Twenty

____HERE
fi
</code>```

Some shells / some cats will allow you to use a here document and a named file at the same time, avoiding the Useless Use of Cat.

```<code>cat - $t <<'____HERE' | /usr/lib/sendmail -oi -t
</code>```

But I am afraid this is not entirely portable.

The grep is just to give you an idea; replace it with something less ad hoc, perhaps actually parsing the output file and performing complex logic on the result of the parse.

Body:
I want to send an email out after a select query returns a certain value.

I currently pipe it to a text file just to give me some display.

echo "SELECT * FROM jobs WHERE status = -20;" | mysql -u user -pXXX -h
          servername --database=chosenDB >> /var/log/DBcheck.txt

now when the value returns to "-20" or whatever number I choose how would I go about creating an email alert to send when it turns true.  Using it as a monitoring tool.  The server I am running already is set up with postfix, which is confirmed working.

any info would be greatly appreciated.

thanks!

Body:
If your query returns a single line of output, perhaps something like this.

#!/bin/sh

case `echo "SELECT * FROM jobs WHERE status = -20;" |
    mysql -u user -pXXX -h servername --database=chosenDB` in
  -20) echo It is minus twenty | /usr/lib/sendmail -oi you@example.com ;;
esac

More usefully, put the output in a temp file, and erase it if it's uninteresting.

#!/bin/sh

t=`mktemp -t muesliXXXXXXX`  # Not entirely portable -- google this bit
trap 'rm -f $t' 0
trap 'exit 127' 1 2 3 5 15

mysql -u user -pXXX -h servername --database=chosenDB <<'____HERE' >$t
    SELECT * FROM jobs WHERE status = -20;
____HERE

if grep -qw '-20' $t; then
  ( cat <<'____HERE'; cat $t) | /usr/lib/sendmail -oi -t
From: Friendly Cron Job <root@example.com>
To: you <you@example.com>
Subject: It is Minus Twenty

____HERE
fi

Some shells / some cats will allow you to use a here document and a named file at the same time, avoiding the Useless Use of Cat.

cat - $t <<'____HERE' | /usr/lib/sendmail -oi -t

But I am afraid this is not entirely portable.

The grep is just to give you an idea; replace it with something less ad hoc, perhaps actually parsing the output file and performing complex logic on the result of the parse.


问:
Why I cannot do TIN Interpolation in QGIS?
I want to do TIN Interpolation on a layer but when I fill all the fields with the right data (vector layer, interpolation attribute, extent etc) the algorithm does not run and shows me this message:

Traceback (most recent call last):
File "C:/PROGRA~1/QGIS 3.14/apps/qgis/./python/plugins\processing\algs\qgis\TinInterpolation.py", line 188, in processAlgorithm
writer.writeFile(feedback)
Exception: unknown
Execution failed after 0.08 seconds

Does anybody have an idea about it?? Thank you

答: It is because of some small lines that are in your file that cannot be handled by Interpolation. You can use Generalizer3 in QGIS plugins to remove those lines.</p>


问:
Unable to start Kestrel. Failed to bind to address address already in use
I want to start a .net core application from an API that I created which is also in .Net Core too.

I added UseUrls() function to Program.cs file so it will use a port that i want it to use. So heres what it looks my Program.cs of that other module.

```<code>public class Program
{
    public static void Main(string[] args)
    {
        BuildWebHost(args).Run();
    }

    public static IWebHost BuildWebHost(string[] args) =>
        WebHost.CreateDefaultBuilder(args)
            .UseStartup<Startup>()
            .UseUrls("http://*:50003")
            .UseKestrel(options =>
            {
                options.Limits.MaxRequestBodySize = null;
            }
            )
            .UseDefaultServiceProvider(options =>
                options.ValidateScopes = false)
            .Build();
}
</code>```

So when I open CMD where this module where is located and type dotnet run it will start running application on http://localhost:50003, which is fine because thats the port where I want to start.

But what I need to do, is to start this app from that API. And heres the code that I wrote the command dotnet run:

```<code>public IActionResult RunPackage(int id)
    {
        try
        {
            var workingDirectory = 'here goes the path of the directory of this module that i want to start running';

            var processStartInfo = new ProcessStartInfo();
            processStartInfo.FileName = "dotnet";
            processStartInfo.Arguments = "run";
            processStartInfo.WorkingDirectory = workingDirectory;
            processStartInfo.UseShellExecute = false;
            processStartInfo.RedirectStandardOutput = true;
            processStartInfo.RedirectStandardError = false;
            processStartInfo.CreateNoWindow = true;
            var process = new Process();
            process.StartInfo = processStartInfo;
            process.Start();
            var reader = process.StandardOutput;
            var output = reader.ReadToEnd();

            return Ok();
        }
        catch (Exception e)
        {
            return BadRequest(e.Message);
        }
    }
</code>```

But when I'm running it, that output variable returns an error which it says

```<code>Unable to start Kestrel.
System.IO.IOException: Failed to bind to address http://127.0.0.1:4221:
address already in use
</code>```

And i dont know why it tries to start the app with 4221 port while it is written in Program.cs to use port 50003.

So the same command dotnet run is working fine if i write manually in CMD and its not working the way it should if i type on my code.

"Using launch settings from C:\Users\StarTech\Desktop\Actibook Actibook\actibook-backend\ServerCore\TimeFrame.Actibook.WebService\wwwroot\Packages\2018-6-Friday031203SampleConverter\Properties\launchSettings.json...\r\ncrit: Microsoft.AspNetCore.Server.Kestrel[0]\r\n      Unable to start Kestrel.\r\nSystem.IO.IOException: Failed to bind to address http://127.0.0.1:4221: address already in use. ---> Microsoft.AspNetCore.Server.Kestrel.Transport.Abstractions.Internal.AddressInUseException: Error -4091 EADDRINUSE address already in use ---> Microsoft.AspNetCore.Server.Kestrel.Transport.Libuv.Internal.Networking.UvException: Error -4091 EADDRINUSE address already in use\r\n   at Microsoft.AspNetCore.Server.Kestrel.Transport.Libuv.Internal.Networking.LibuvFunctions.ThrowError(Int32 statusCode)\r\n   at Microsoft.AspNetCore.Server.Kestrel.Transport.Libuv.Internal.Networking.LibuvFunctions.tcp_getsockname(UvTcpHandle handle, SockAddr& addr, Int32& namelen)\r\n   at Microsoft.AspNetCore.Server.Kestrel.Transport.Libuv.Internal.Networking.UvTcpHandle.GetSockIPEndPoint()\r\n   at Microsoft.AspNetCore.Server.Kestrel.Transport.Libuv.Internal.Listener.ListenTcp(Boolean useFileHandle)\r\n   at Microsoft.AspNetCore.Server.Kestrel.Transport.Libuv.Internal.Listener.CreateListenSocket()\r\n   at Microsoft.AspNetCore.Server.Kestrel.Transport.Libuv.Internal.Listener.<>c.b__8_0(Listener listener)\r\n   at Microsoft.AspNetCore.Server.Kestrel.Transport.Libuv.Internal.LibuvThread.CallbackAdapter1.<>c.<.cctor>b__3_1(Object callback, Object state)\r\n   at Microsoft.AspNetCore.Server.Kestrel.Transport.Libuv.Internal.LibuvThread.DoPostWork()\r\n--- End of stack trace from previous location where exception was thrown ---\r\n   at System.Runtime.ExceptionServices.ExceptionDispatchInfo.Throw()\r\n   at System.Runtime.CompilerServices.TaskAwaiter.HandleNonSuccessAndDebuggerNotification(Task task)\r\n   at Microsoft.AspNetCore.Server.Kestrel.Transport.Libuv.Internal.ListenerPrimary.<StartAsync>d__15.MoveNext()\r\n--- End of stack trace from previous location where exception was thrown ---\r\n   at System.Runtime.ExceptionServices.ExceptionDispatchInfo.Throw()\r\n   at System.Runtime.CompilerServices.TaskAwaiter.HandleNonSuccessAndDebuggerNotification(Task task)\r\n   at Microsoft.AspNetCore.Server.Kestrel.Transport.Libuv.LibuvTransport.<BindAsync>d__20.MoveNext()\r\n   --- End of inner exception stack trace ---\r\n   at Microsoft.AspNetCore.Server.Kestrel.Transport.Libuv.LibuvTransport.<BindAsync>d__20.MoveNext()\r\n--- End of stack trace from previous location where exception was thrown ---\r\n   at System.Runtime.ExceptionServices.ExceptionDispatchInfo.Throw()\r\n   at System.Runtime.CompilerServices.TaskAwaiter.HandleNonSuccessAndDebuggerNotification(Task task)\r\n   at Microsoft.AspNetCore.Server.Kestrel.Core.KestrelServer.<>c__DisplayClass23_01.<g__OnBind|0>d.MoveNext()\r\n--- End of stack trace from previous location where exception was thrown ---\r\n   at System.Runtime.ExceptionServices.ExceptionDispatchInfo.Throw()\r\n   at System.Runtime.CompilerServices.TaskAwaiter.HandleNonSuccessAndDebuggerNotification(Task task)\r\n   at Microsoft.AspNetCore.Server.Kestrel.Core.Internal.AddressBinder.d__5.MoveNext()\r\n   --- End of inner exception stack trace ---\r\n   at Microsoft.AspNetCore.Server.Kestrel.Core.Internal.AddressBinder.d__5.MoveNext()\r\n--- End of stack trace from previous location where exception was thrown ---\r\n   at System.Runtime.ExceptionServices.ExceptionDispatchInfo.Throw()\r\n   at System.Runtime.CompilerServices.TaskAwaiter.HandleNonSuccessAndDebuggerNotification(Task task)\r\n   at Microsoft.AspNetCore.Server.Kestrel.Core.Internal.AddressBinder.d__6.MoveNext()\r\n--- End of stack trace from previous location where exception was thrown ---\r\n   at System.Runtime.ExceptionServices.ExceptionDispatchInfo.Throw()\r\n   at System.Runtime.CompilerServices.TaskAwaiter.HandleNonSuccessAndDebuggerNotification(Task task)\r\n   at Microsoft.AspNetCore.Server.Kestrel.Core.Internal.AddressBinder.d__7.MoveNext()\r\n--- End of stack trace from previous location where exception was thrown ---\r\n   at System.Runtime.ExceptionServices.ExceptionDispatchInfo.Throw()\r\n   at System.Runtime.CompilerServices.TaskAwaiter.HandleNonSuccessAndDebuggerNotification(Task task)\r\n   at Microsoft.AspNetCore.Server.Kestrel.Core.Internal.AddressBinder.AddressesStrategy.d__2.MoveNext()\r\n--- End of stack trace from previous location where exception was thrown ---\r\n   at System.Runtime.ExceptionServices.ExceptionDispatchInfo.Throw()\r\n   at System.Runtime.CompilerServices.TaskAwaiter.HandleNonSuccessAndDebuggerNotification(Task task)\r\n   at Microsoft.AspNetCore.Server.Kestrel.Core.Internal.AddressBinder.d__0.MoveNext()\r\n--- End of stack trace from previous location where exception was thrown ---\r\n   at System.Runtime.ExceptionServices.ExceptionDispatchInfo.Throw()\r\n   at System.Runtime.CompilerServices.TaskAwaiter.HandleNonSuccessAndDebuggerNotification(Task task)\r\n   at Microsoft.AspNetCore.Server.Kestrel.Core.KestrelServer.d__23`1.MoveNext()\r\n"

launchSettings.json contanins:

```<code>{
  "iisSettings": {
    "windowsAuthentication": false,
    "anonymousAuthentication": true,
    "iisExpress": {
      "applicationUrl": "http://localhost:60924/",
      "sslPort": 0
    }
  },
  "profiles": {
    "IIS Express": {
      "commandName": "IISExpress",
      "launchBrowser": true,
      "launchUrl": "api/values",
      "environmentVariables": {
        "ASPNETCORE_ENVIRONMENT": "Development"
      }
    },
    "SampleConverter": {
      "commandName": "Project",
      "launchBrowser": true,
      "launchUrl": "api/values",
      "environmentVariables": {
        "ASPNETCORE_ENVIRONMENT": "Development"
      },
      "applicationUrl": "http://localhost:60925/"
    }
  }
}
</code>```

答:
You have to run the following in visual studio command prompt.

```<code>dotnet dev-certs https --trust
</code>```

if you still face the issue, try

```<code>dotnet dev-certs https --clean
</code>```

and then retry this command

```<code>dotnet dev-certs https --trust
</code>```

Body:
I want to start a .net core application from an API that I created which is also in .Net Core too.

I added UseUrls() function to Program.cs file so it will use a port that i want it to use. So heres what it looks my Program.cs of that other module.

public class Program
{
    public static void Main(string[] args)
    {
        BuildWebHost(args).Run();
    }

    public static IWebHost BuildWebHost(string[] args) =>
        WebHost.CreateDefaultBuilder(args)
            .UseStartup<Startup>()
            .UseUrls("http://*:50003")
            .UseKestrel(options =>
            {
                options.Limits.MaxRequestBodySize = null;
            }
            )
            .UseDefaultServiceProvider(options =>
                options.ValidateScopes = false)
            .Build();
}

So when I open CMD where this module where is located and type dotnet run it will start running application on http://localhost:50003, which is fine because thats the port where I want to start.

But what I need to do, is to start this app from that API. And heres the code that I wrote the command dotnet run:

public IActionResult RunPackage(int id)
    {
        try
        {
            var workingDirectory = 'here goes the path of the directory of this module that i want to start running';

            var processStartInfo = new ProcessStartInfo();
            processStartInfo.FileName = "dotnet";
            processStartInfo.Arguments = "run";
            processStartInfo.WorkingDirectory = workingDirectory;
            processStartInfo.UseShellExecute = false;
            processStartInfo.RedirectStandardOutput = true;
            processStartInfo.RedirectStandardError = false;
            processStartInfo.CreateNoWindow = true;
            var process = new Process();
            process.StartInfo = processStartInfo;
            process.Start();
            var reader = process.StandardOutput;
            var output = reader.ReadToEnd();

            return Ok();
        }
        catch (Exception e)
        {
            return BadRequest(e.Message);
        }
    }

But when I'm running it, that output variable returns an error which it says

Unable to start Kestrel.
System.IO.IOException: Failed to bind to address http://127.0.0.1:4221:
address already in use

And i dont know why it tries to start the app with 4221 port while it is written in Program.cs to use port 50003.

So the same command dotnet run is working fine if i write manually in CMD and its not working the way it should if i type on my code.

"Using launch settings from C:\Users\StarTech\Desktop\Actibook Actibook\actibook-backend\ServerCore\TimeFrame.Actibook.WebService\wwwroot\Packages\2018-6-Friday031203SampleConverter\Properties\launchSettings.json...\r\ncrit: Microsoft.AspNetCore.Server.Kestrel[0]\r\n      Unable to start Kestrel.\r\nSystem.IO.IOException: Failed to bind to address http://127.0.0.1:4221: address already in use. ---> Microsoft.AspNetCore.Server.Kestrel.Transport.Abstractions.Internal.AddressInUseException: Error -4091 EADDRINUSE address already in use ---> Microsoft.AspNetCore.Server.Kestrel.Transport.Libuv.Internal.Networking.UvException: Error -4091 EADDRINUSE address already in use\r\n   at Microsoft.AspNetCore.Server.Kestrel.Transport.Libuv.Internal.Networking.LibuvFunctions.ThrowError(Int32 statusCode)\r\n   at Microsoft.AspNetCore.Server.Kestrel.Transport.Libuv.Internal.Networking.LibuvFunctions.tcp_getsockname(UvTcpHandle handle, SockAddr& addr, Int32& namelen)\r\n   at Microsoft.AspNetCore.Server.Kestrel.Transport.Libuv.Internal.Networking.UvTcpHandle.GetSockIPEndPoint()\r\n   at Microsoft.AspNetCore.Server.Kestrel.Transport.Libuv.Internal.Listener.ListenTcp(Boolean useFileHandle)\r\n   at Microsoft.AspNetCore.Server.Kestrel.Transport.Libuv.Internal.Listener.CreateListenSocket()\r\n   at Microsoft.AspNetCore.Server.Kestrel.Transport.Libuv.Internal.Listener.<>c.b__8_0(Listener listener)\r\n   at Microsoft.AspNetCore.Server.Kestrel.Transport.Libuv.Internal.LibuvThread.CallbackAdapter1.<>c.<.cctor>b__3_1(Object callback, Object state)\r\n   at Microsoft.AspNetCore.Server.Kestrel.Transport.Libuv.Internal.LibuvThread.DoPostWork()\r\n--- End of stack trace from previous location where exception was thrown ---\r\n   at System.Runtime.ExceptionServices.ExceptionDispatchInfo.Throw()\r\n   at System.Runtime.CompilerServices.TaskAwaiter.HandleNonSuccessAndDebuggerNotification(Task task)\r\n   at Microsoft.AspNetCore.Server.Kestrel.Transport.Libuv.Internal.ListenerPrimary.<StartAsync>d__15.MoveNext()\r\n--- End of stack trace from previous location where exception was thrown ---\r\n   at System.Runtime.ExceptionServices.ExceptionDispatchInfo.Throw()\r\n   at System.Runtime.CompilerServices.TaskAwaiter.HandleNonSuccessAndDebuggerNotification(Task task)\r\n   at Microsoft.AspNetCore.Server.Kestrel.Transport.Libuv.LibuvTransport.<BindAsync>d__20.MoveNext()\r\n   --- End of inner exception stack trace ---\r\n   at Microsoft.AspNetCore.Server.Kestrel.Transport.Libuv.LibuvTransport.<BindAsync>d__20.MoveNext()\r\n--- End of stack trace from previous location where exception was thrown ---\r\n   at System.Runtime.ExceptionServices.ExceptionDispatchInfo.Throw()\r\n   at System.Runtime.CompilerServices.TaskAwaiter.HandleNonSuccessAndDebuggerNotification(Task task)\r\n   at Microsoft.AspNetCore.Server.Kestrel.Core.KestrelServer.<>c__DisplayClass23_01.<g__OnBind|0>d.MoveNext()\r\n--- End of stack trace from previous location where exception was thrown ---\r\n   at System.Runtime.ExceptionServices.ExceptionDispatchInfo.Throw()\r\n   at System.Runtime.CompilerServices.TaskAwaiter.HandleNonSuccessAndDebuggerNotification(Task task)\r\n   at Microsoft.AspNetCore.Server.Kestrel.Core.Internal.AddressBinder.d__5.MoveNext()\r\n   --- End of inner exception stack trace ---\r\n   at Microsoft.AspNetCore.Server.Kestrel.Core.Internal.AddressBinder.d__5.MoveNext()\r\n--- End of stack trace from previous location where exception was thrown ---\r\n   at System.Runtime.ExceptionServices.ExceptionDispatchInfo.Throw()\r\n   at System.Runtime.CompilerServices.TaskAwaiter.HandleNonSuccessAndDebuggerNotification(Task task)\r\n   at Microsoft.AspNetCore.Server.Kestrel.Core.Internal.AddressBinder.d__6.MoveNext()\r\n--- End of stack trace from previous location where exception was thrown ---\r\n   at System.Runtime.ExceptionServices.ExceptionDispatchInfo.Throw()\r\n   at System.Runtime.CompilerServices.TaskAwaiter.HandleNonSuccessAndDebuggerNotification(Task task)\r\n   at Microsoft.AspNetCore.Server.Kestrel.Core.Internal.AddressBinder.d__7.MoveNext()\r\n--- End of stack trace from previous location where exception was thrown ---\r\n   at System.Runtime.ExceptionServices.ExceptionDispatchInfo.Throw()\r\n   at System.Runtime.CompilerServices.TaskAwaiter.HandleNonSuccessAndDebuggerNotification(Task task)\r\n   at Microsoft.AspNetCore.Server.Kestrel.Core.Internal.AddressBinder.AddressesStrategy.d__2.MoveNext()\r\n--- End of stack trace from previous location where exception was thrown ---\r\n   at System.Runtime.ExceptionServices.ExceptionDispatchInfo.Throw()\r\n   at System.Runtime.CompilerServices.TaskAwaiter.HandleNonSuccessAndDebuggerNotification(Task task)\r\n   at Microsoft.AspNetCore.Server.Kestrel.Core.Internal.AddressBinder.d__0.MoveNext()\r\n--- End of stack trace from previous location where exception was thrown ---\r\n   at System.Runtime.ExceptionServices.ExceptionDispatchInfo.Throw()\r\n   at System.Runtime.CompilerServices.TaskAwaiter.HandleNonSuccessAndDebuggerNotification(Task task)\r\n   at Microsoft.AspNetCore.Server.Kestrel.Core.KestrelServer.d__23`1.MoveNext()\r\n"

launchSettings.json contanins:

{
  "iisSettings": {
    "windowsAuthentication": false,
    "anonymousAuthentication": true,
    "iisExpress": {
      "applicationUrl": "http://localhost:60924/",
      "sslPort": 0
    }
  },
  "profiles": {
    "IIS Express": {
      "commandName": "IISExpress",
      "launchBrowser": true,
      "launchUrl": "api/values",
      "environmentVariables": {
        "ASPNETCORE_ENVIRONMENT": "Development"
      }
    },
    "SampleConverter": {
      "commandName": "Project",
      "launchBrowser": true,
      "launchUrl": "api/values",
      "environmentVariables": {
        "ASPNETCORE_ENVIRONMENT": "Development"
      },
      "applicationUrl": "http://localhost:60925/"
    }
  }
}

Body:
You have to run the following in visual studio command prompt.

dotnet dev-certs https --trust

if you still face the issue, try

dotnet dev-certs https --clean

and then retry this command

dotnet dev-certs https --trust


问:
Order the plotting of data by the contents of a date column
I have dataset as follows:

```<code>df = data.frame(name = c('Ger1', 'Ger2', 'Ger3', 'Ger4', 'Ger5', 'Ger6'),
            issued = c(UKS, USD, UKS, UKS, USD, USD),
            mat = c(2024-01-31, 2023-01-31, 2026-10-22, 2022-07-22, 2029-01-31, 2025-06-07)
            volume = c(0.476, 0.922, 0.580, 1.259, 0.932, 0.417)
</code>```

I currently plot (and filter) the data using the following code:

```<code>plot1<- ggplot(subset(df, issued == "UKS")) +
  geom_bar(stat="identity", aes(x=volume,y=name),fill="#1170aa")+
  theme(title=element_text(size=12),
        panel.background = element_rect(fill='white',color='black'),
        legend.position='right')+
  labs(title = "Total carriage by Volume on the day", x = "Volume", y = "Name")
</code>```

I'd like to be able to order this data using the 'mat' column as guide, namely with the data that has the earliest 'mat' date at the top of the Y axis and the most distant 'mat' date at the bottom. Does anyone have any advice on how to achieve this?

Edit: I use grid arrange to plot it against another chart.

```<code>grid.arrange(plot1,plot2,ncol=2)
</code>```

Sadly I get the following error:

```<code>Error in `-.POSIXt`(Maturity) : unary '-' is not defined for "POSIXt" objects
</code>```

答:
So, I was able to fix the ordering issue by appending the mat column data to the name, and then adding:

```<code>+scale_y_discrete(limits=rev)
</code>```

To the end of the ggplot code.

Body:
I have dataset as follows:

df = data.frame(name = c('Ger1', 'Ger2', 'Ger3', 'Ger4', 'Ger5', 'Ger6'),
            issued = c(UKS, USD, UKS, UKS, USD, USD),
            mat = c(2024-01-31, 2023-01-31, 2026-10-22, 2022-07-22, 2029-01-31, 2025-06-07)
            volume = c(0.476, 0.922, 0.580, 1.259, 0.932, 0.417)

I currently plot (and filter) the data using the following code:

plot1<- ggplot(subset(df, issued == "UKS")) +
  geom_bar(stat="identity", aes(x=volume,y=name),fill="#1170aa")+
  theme(title=element_text(size=12),
        panel.background = element_rect(fill='white',color='black'),
        legend.position='right')+
  labs(title = "Total carriage by Volume on the day", x = "Volume", y = "Name")

I'd like to be able to order this data using the 'mat' column as guide, namely with the data that has the earliest 'mat' date at the top of the Y axis and the most distant 'mat' date at the bottom. Does anyone have any advice on how to achieve this?

Edit: I use grid arrange to plot it against another chart.

grid.arrange(plot1,plot2,ncol=2)

Sadly I get the following error:

Error in `-.POSIXt`(Maturity) : unary '-' is not defined for "POSIXt" objects

Body:
So, I was able to fix the ordering issue by appending the mat column data to the name, and then adding:

+scale_y_discrete(limits=rev)

To the end of the ggplot code.


问:
Check if a column contains text using SQL
I have a column which is called studentID, but I have millions of records and somehow the application has input some arbitrary text in the column.

How do I search:

```<code>SELECT *
  FROM STUDENTS
 WHERE STUDENTID CONTAINS TEXT
</code>```

答:
riffing from bgs, please upvote them first.

I just wanted to expand on it

SELECT * FROM STUDENTS WHERE STUDENTID == 'Searchstring'
```
<p>Will ONLY find Searchstring<br></p>
<pre class="lang-sql prettyprint-override"><code>SELECT * FROM STUDENTS WHERE STUDENTID like '%Searchstring%'
</code>```

will find

1 Searchstring 1

2 Searchstring 2

3Searchstring3

etc Searchstring etc

SELECT * FROM STUDENTS WHERE STUDENTID like 'Searchstring%'
```

will find

Searchstring 1

Searchstring 2

SearchstringEtc

Will not find

1 Searchstring 1

or any prefixes at all

In this case % is used kinda the same as the same as the * wildcard, just for strings in this case.

Body:
I have a column which is called studentID, but I have millions of records and somehow the application has input some arbitrary text in the column.

How do I search:

SELECT *
  FROM STUDENTS
 WHERE STUDENTID CONTAINS TEXT

Body:
riffing from bgs, please upvote them first.

I just wanted to expand on it

SELECT * FROM STUDENTS WHERE STUDENTID == 'Searchstring'

Will ONLY find Searchstring

SELECT * FROM STUDENTS WHERE STUDENTID like '%Searchstring%'

will find

1 Searchstring 1

2 Searchstring 2

3Searchstring3

etc Searchstring etc

SELECT * FROM STUDENTS WHERE STUDENTID like 'Searchstring%'

will find

Searchstring 1

Searchstring 2

SearchstringEtc

Will not find

1 Searchstring 1

or any prefixes at all

In this case % is used kinda the same as the same as the * wildcard, just for strings in this case.


问:
Encountered an error: Version error for package fivetran/fivetran_utils
I hope someone can help.

When I try and install fivetran/tiktok_ads package via packages.yml I get an error, can anyone help or confirm if it is an ongoing bug?

```<code> package: fivetran/tiktok_ads
 version: 0.1.1
</code>```

I get this error message:

```<code>Encountered an error:
Version error for package fivetran/fivetran_utils: Could not find a satisfactory version from options: ['=0.2.9', '>=0.2.0', '<0.3.0', '>=0.2.0', '<0.3.0', '>=0.2.0', '<0.3.0', '>=0.3.0', '<0.4.0']
</code>```

this is my full packages file

```<code>packages:
  - package: dbt-labs/dbt_utils
    version: 0.7.3

  - package: fivetran/fivetran_utils
    version: 0.2.9

  - package: fivetran/tiktok_ads
    version: 0.1.1

  - package: fivetran/stripe_source
    version: 0.4.3

  - package: fivetran/pinterest_source
    version: 0.4.0

  - package: fivetran/microsoft_ads_source
    version: 0.3.1
</code>```

this is my dbt version info

```<code>installed version: 0.21.1
   latest version: 1.0.0

Your version of dbt is out of date! You can find instructions for upgrading here:
https://docs.getdbt.com/docs/installation

Plugins:
  - bigquery: 0.21.1
  - snowflake: 0.21.1
  - redshift: 0.21.1
  - postgres: 0.21.1
(condaEnv) chris@Chris bla-data %
</code>```

答:
try to update your

package: fivetran/fivetran_utils

from 0.29 to latest version

after that run the dbt command dbt deps

this command will update all your packages.

Hopefully doing this it will work

Body:
I hope someone can help.

When I try and install fivetran/tiktok_ads package via packages.yml I get an error, can anyone help or confirm if it is an ongoing bug?

 package: fivetran/tiktok_ads
 version: 0.1.1

I get this error message:

Encountered an error:
Version error for package fivetran/fivetran_utils: Could not find a satisfactory version from options: ['=0.2.9', '>=0.2.0', '<0.3.0', '>=0.2.0', '<0.3.0', '>=0.2.0', '<0.3.0', '>=0.3.0', '<0.4.0']

this is my full packages file

packages:
  - package: dbt-labs/dbt_utils
    version: 0.7.3

  - package: fivetran/fivetran_utils
    version: 0.2.9

  - package: fivetran/tiktok_ads
    version: 0.1.1

  - package: fivetran/stripe_source
    version: 0.4.3

  - package: fivetran/pinterest_source
    version: 0.4.0

  - package: fivetran/microsoft_ads_source
    version: 0.3.1

this is my dbt version info

installed version: 0.21.1
   latest version: 1.0.0

Your version of dbt is out of date! You can find instructions for upgrading here:
https://docs.getdbt.com/docs/installation

Plugins:
  - bigquery: 0.21.1
  - snowflake: 0.21.1
  - redshift: 0.21.1
  - postgres: 0.21.1
(condaEnv) chris@Chris bla-data %


问:
How to create many divs without actually creating them individually
I'm working on a project with html, css and js and I want to create many divs (let's say, 200) so, how can i create them without actually writing code for 200 different divs... I know I can do it with js but could I do it only with html and css..?</p>

答:
As I already said in my comment, you can't do it without JavaScript.

A JavaScript solution would be the following:

const container = document.getElementById("container");

for (let i = 0; i < 200; i++) {
  const item = document.createElement("div");

  item.classList.add("item", "item-" + i);

  container.appendChild(item);
}```
<pre class="snippet-code-css lang-css prettyprint-override"><code>#container {
  border: 1px solid red;
  padding: .5rem;
}

.item {
  border: 1px solid black;
  height: 3rem;
  margin-bottom: .3rem;
}</code>```

```

Body:
As I already said in my comment, you can't do it without JavaScript.

A JavaScript solution would be the following:

const container = document.getElementById("container");

for (let i = 0; i < 200; i++) {
  const item = document.createElement("div");

  item.classList.add("item", "item-" + i);

  container.appendChild(item);
}

#container {
  border: 1px solid red;
  padding: .5rem;
}

.item {
  border: 1px solid black;
  height: 3rem;
  margin-bottom: .3rem;
}

<div id="container">
</div>


问:
How to compare large text files?
I have a general question on your opinion about my "technique".

There are 2 textfiles (file_1 and file_2) that need to be compared to each other. Both are very huge (3-4 gigabytes, from 30,000,000 to 45,000,000 lines each).
My idea is to read several lines (as many as possible) of file_1 to the memory, then compare those to all lines of file_2. If there's a match, the lines from both files that match shall be written to a new file. Then go on with the next 1000 lines of file_1 and also compare those to all lines of file_2 until I went through file_1 completely.

But this sounds actually really, really time consuming and complicated to me.
Can you think of any other method to compare those two files?

How long do you think the comparison could take?
For my program, time does not matter that much. I have no experience in working with such huge files, therefore I have no idea how long this might take. It shouldn't take more than a day though. ;-) But I am afraid my technique could take forever...

Antoher question that just came to my mind: how many lines would you read into the memory? As many as possible? Is there a way to determine the number of possible lines before actually trying it?
I want to read as many as possible (because I think that's faster) but I've ran out of memory quite often.

Thanks in advance.

EDIT
I think I have to explain my problem a bit more.

The purpose is not to see if the two files in general are identical (they are not).
There are some lines in each file that share the same "characteristic".
Here's an example:
file_1 looks somewhat like this:

```<code>mat1 1000 2000 TEXT      //this means the range is from 1000 - 2000
mat1 2040 2050 TEXT
mat3 10000 10010 TEXT
mat2 20 500 TEXT
</code>```

file_2looks like this:

```<code>mat3 10009 TEXT
mat3 200 TEXT
mat1 999 TEXT
</code>```

TEXT refers to characters and digits that are of no interest for me, mat can go from mat1 - mat50 and are in no order; also there can be 1000x mat2 (but the numbers in the next column are different). I need to find the fitting lines in a way that: matX is the same in both compared lines an the number mentioned in file_2 fits into the range mentioned in file_1.
So in my example I would find one match: line 3 of file_1and line 1 of file_2 (because both are mat3 and 10009 is between 10000 and 10010).
I hope this makes it clear to you!

So my question is: how would you search for the matching lines?

Yes, I use Java as my programming language.

EDIT
I now divided the huge files first so that I have no problems with being out of memory. I also think it is faster to compare (many) smaller files to each other than those two huge files. After that I can compare them the way I mentioned above. It may not be the perfect way, but I am still learning ;-)
Nonentheless all your approaches were very helpful to me, thank you for your replies!

答:
My solution would be to produce an index of one file first, then use that to do the comparison. This is similar to some of the other answers in that it uses hashing.

You mention that the number of lines is up to about 45 million. This means that you could (potentially) store an index which uses 16 bytes per entry (128 bits) and it would use about 45,000,000*16 = ~685MB of RAM, which isn't unreasonable on a modern system. There are overheads in using the solution I describe below, so you might still find you need to use other techniques such as memory mapped files or disk based tables to create the index. See Hypertable or HBase for an example of how to store the index in a fast disk-based hash table.

So, in full, the algorithm would be something like:

Create a hash map which maps Long to a List of Longs (HashMap<Long, List<Long>>)

Get the hash of each line in the first file (Object.hashCode should be sufficient)

Get the offset in the file of the line so you can find it again later

Add the offset to the list of lines with matching hashCodes in the hash map

Compare each line of the second file to the set of line offsets in the index

Keep any lines which have matching entries

EDIT:
In response to your edited question, this wouldn't really help in itself. You could just hash the first part of the line, but it would only create 50 different entries. You could then create another level in the data structure though, which would map the start of each range to the offset of the line it came from.

So something like index.get("mat32") would return a TreeMap of ranges. You could look for the range preceding the value you are looking for lowerEntry(). Together this would give you a pretty fast check to see if a given matX/number combination was in one of the ranges you are checking for.

Title: How to compare large text files?

Body:
I have a general question on your opinion about my "technique".

There are 2 textfiles (file_1 and file_2) that need to be compared to each other. Both are very huge (3-4 gigabytes, from 30,000,000 to 45,000,000 lines each).
My idea is to read several lines (as many as possible) of file_1 to the memory, then compare those to all lines of file_2. If there's a match, the lines from both files that match shall be written to a new file. Then go on with the next 1000 lines of file_1 and also compare those to all lines of file_2 until I went through file_1 completely.

But this sounds actually really, really time consuming and complicated to me.
Can you think of any other method to compare those two files?

How long do you think the comparison could take?
For my program, time does not matter that much. I have no experience in working with such huge files, therefore I have no idea how long this might take. It shouldn't take more than a day though. ;-) But I am afraid my technique could take forever...

Antoher question that just came to my mind: how many lines would you read into the memory? As many as possible? Is there a way to determine the number of possible lines before actually trying it?
I want to read as many as possible (because I think that's faster) but I've ran out of memory quite often.

Thanks in advance.

EDIT
I think I have to explain my problem a bit more.

The purpose is not to see if the two files in general are identical (they are not).
There are some lines in each file that share the same "characteristic".
Here's an example:
file_1 looks somewhat like this:

mat1 1000 2000 TEXT      //this means the range is from 1000 - 2000
mat1 2040 2050 TEXT
mat3 10000 10010 TEXT
mat2 20 500 TEXT

file_2looks like this:

mat3 10009 TEXT
mat3 200 TEXT
mat1 999 TEXT

TEXT refers to characters and digits that are of no interest for me, mat can go from mat1 - mat50 and are in no order; also there can be 1000x mat2 (but the numbers in the next column are different). I need to find the fitting lines in a way that: matX is the same in both compared lines an the number mentioned in file_2 fits into the range mentioned in file_1.
So in my example I would find one match: line 3 of file_1and line 1 of file_2 (because both are mat3 and 10009 is between 10000 and 10010).
I hope this makes it clear to you!

So my question is: how would you search for the matching lines?

Yes, I use Java as my programming language.

EDIT
I now divided the huge files first so that I have no problems with being out of memory. I also think it is faster to compare (many) smaller files to each other than those two huge files. After that I can compare them the way I mentioned above. It may not be the perfect way, but I am still learning ;-)
Nonentheless all your approaches were very helpful to me, thank you for your replies!


问:
How to get all configured receive endpoints in Masstransit
I connect the receive endpoint at runtime using below code, but it will raise an error if a receive endpoint with the same key was already added.

var handle = _bus.ConnectReceiveEndpoint($"some-name", x =>
{
    x.ConfigureConsumeTopology = false;
    x.Consumer<TestConsumer>();

    var rabbitmqConfigurator = (IRabbitMqReceiveEndpointConfigurator)x;

    rabbitmqConfigurator.Bind<QueuedWorkflowItem2>(e =>
    {
        e.RoutingKey = "direct."+"somename";
        e.ExchangeType = ExchangeType.Direct;
    });
});
```

Is there any method I can use to check if the receive endpoint is already added before above code?

答:
Officially, no, there isn't a specific way to return details on all of the configured endpoints at runtime. I would be highly suspect of an application that just randomly connected endpoints to the bus in the hope that it wasn't a duplicate. Seems more like an application implementation problem than anything related to MassTransit.

However, as a hack, you could use the bus health check, which returns all endpoints, and check if the name already exists.

var health = _busControl.CheckHealth();

return health.Endpoints.Any(e => e.Key == 'some-name');
```

Body:
I connect the receive endpoint at runtime using below code, but it will raise an error if a receive endpoint with the same key was already added.

var handle = _bus.ConnectReceiveEndpoint($"some-name", x =>
{
    x.ConfigureConsumeTopology = false;
    x.Consumer<TestConsumer>();

    var rabbitmqConfigurator = (IRabbitMqReceiveEndpointConfigurator)x;

    rabbitmqConfigurator.Bind<QueuedWorkflowItem2>(e =>
    {
        e.RoutingKey = "direct."+"somename";
        e.ExchangeType = ExchangeType.Direct;
    });
});

Is there any method I can use to check if the receive endpoint is already added before above code?


问:
Cppcheclipse seems to have disappeared
I used to work with cppcheck for a long time and for use within eclipse I made use of the plugin cppcheclipse.
Now I am setting up a new development PC and thus am trying to find the way to install it. Obviously the old update site dl.bintray.com disappeared and I did not yet find a new way to get it. The same error comes up when I work with the marketplace.
Does anyone by chance know where to get it nowadays?

Thanks in advance!
Regards,
Christoph

答:
You can find an answer here:
https://github.com/kwin/cppcheclipse/issues/108

and the following download link here.

So work-around to install the plugin:

```<code>Downloads the zip file provided above by AntonKrug
In Eclipse, select Help-> Install New Software
Click "Add..."
In the "Add Repository" dialog, click the "Archive..." button.
Select your Zip file and then click "Open"
Click "Add", Then select the cppcheclipse check box,
Click "Finish" button to install.
</code>```

This will not Auto-Update, but at least you'll be able to install the
plugin. It doesn't seem like there's much active development on the
plugin anyway.

Title: Cppcheclipse seems to have disappeared

Body:
You can find an answer here:
https://github.com/kwin/cppcheclipse/issues/108

and the following download link here.

So work-around to install the plugin:

Downloads the zip file provided above by AntonKrug
In Eclipse, select Help-> Install New Software
Click "Add..."
In the "Add Repository" dialog, click the "Archive..." button.
Select your Zip file and then click "Open"
Click "Add", Then select the cppcheclipse check box,
Click "Finish" button to install.

This will not Auto-Update, but at least you'll be able to install the
plugin. It doesn't seem like there's much active development on the
plugin anyway.


问:
How to declare and use a struct field which can store both string and int values?
I've the following struct:

```<code>type testCase struct {
   input   string
   isValid bool
}
</code>```

I want to use this struct in multiple tests and input could be either a string or an intetc.

I can convert the int input to string and convert it back to int while processing, or I can define two different structs e.g. testCaseInt and testCaseStruct which will solve my problem but how do I solve this by converting input to an interface?

I'm new to Go and tried Googling about this but couldn't find maybe because I don't know what to search for.

答:
Method 1:

```<code>package main

import (
    "fmt"
)

func main() {
    var a interface{}
    a = "hi"
    if valString, ok := a.(string); ok {
        fmt.Printf("String: %s", valString)
    }
    a = 1
    if valInt, ok := a.(int); ok {
        fmt.Printf("\nInteger: %d", valInt)
    }
}
</code>```

Method 2:

```<code>package main

import (
    "fmt"
)

func main() {
    print("hi")
    print(1)
}

func print(a interface{}) {
    switch t := a.(type) {
    case int:
        fmt.Printf("Integer: %v\n", t)
    case string:
        fmt.Printf("String: %v\n", t)
    }
}
</code>```

Body:
I've the following struct:

type testCase struct {
   input   string
   isValid bool
}

I want to use this struct in multiple tests and input could be either a string or an intetc.

I can convert the int input to string and convert it back to int while processing, or I can define two different structs e.g. testCaseInt and testCaseStruct which will solve my problem but how do I solve this by converting input to an interface?

I'm new to Go and tried Googling about this but couldn't find maybe because I don't know what to search for.

Body:
Method 1:

package main

import (
    "fmt"
)

func main() {
    var a interface{}
    a = "hi"
    if valString, ok := a.(string); ok {
        fmt.Printf("String: %s", valString)
    }
    a = 1
    if valInt, ok := a.(int); ok {
        fmt.Printf("\nInteger: %d", valInt)
    }
}

Method 2:

package main

import (
    "fmt"
)

func main() {
    print("hi")
    print(1)
}

func print(a interface{}) {
    switch t := a.(type) {
    case int:
        fmt.Printf("Integer: %v\n", t)
    case string:
        fmt.Printf("String: %v\n", t)
    }
}


问:
Android: ProgressDialog failing
I'm having real problems getting a ProgressDialog up and running. My code:

```<code>ProgressDialog dialog;

try {
  dialog = new ProgressDialog(context);
  dialog.setCancelable(true);
  dialog.setMessage("Loading ...");
  // set the progress to be horizontal
  dialog.setProgressStyle(ProgressDialog.STYLE_HORIZONTAL);
  // set the bar to the default value of 0
  dialog.setProgress(0);

  // set the maximum value
  dialog.setMax(100);
  // display the progressbar
  dialog.show();
 }
catch (Exception e1)
 {
   e1.printStackTrace();
 }
</code>```

Below that I create my background thread to load some stuff and update the progress bar, but it never gets that far. In the stack trace I get "Unable to add window -- token null is not for an application", but the dialog seems (in the debugger) to have all the right things, it isn't null, but I'm getting this error.

Can anyone shine a light on this?

答:
What kind of context are you using to create the ProgressDialog?

I think that the ProgressDialog want work with a ApplicationContext. The API is not very correct the constructor should request an Activity instead of a Context.

Try to pass a reference to a Activity to the constructor instead of an regular Context.

Instead of using:

```<code>Context context = getApplicationContext();
</code>```

use

```<code>Context context = this;
</code>```

Or if you are in an inner class of your Activity (a listener, or Task) use:

```<code>Context context = MyActivityNameComesHere.this;
</code>```

See my Issue in the Android Bugtracker about this.

Title: Android: ProgressDialog failing

Body:
I'm having real problems getting a ProgressDialog up and running. My code:

ProgressDialog dialog;

try {
  dialog = new ProgressDialog(context);
  dialog.setCancelable(true);
  dialog.setMessage("Loading ...");
  // set the progress to be horizontal
  dialog.setProgressStyle(ProgressDialog.STYLE_HORIZONTAL);
  // set the bar to the default value of 0
  dialog.setProgress(0);

  // set the maximum value
  dialog.setMax(100);
  // display the progressbar
  dialog.show();
 }
catch (Exception e1)
 {
   e1.printStackTrace();
 }

Below that I create my background thread to load some stuff and update the progress bar, but it never gets that far. In the stack trace I get "Unable to add window -- token null is not for an application", but the dialog seems (in the debugger) to have all the right things, it isn't null, but I'm getting this error.

Can anyone shine a light on this?

Body:
What kind of context are you using to create the ProgressDialog?

I think that the ProgressDialog want work with a ApplicationContext. The API is not very correct the constructor should request an Activity instead of a Context.

Try to pass a reference to a Activity to the constructor instead of an regular Context.

Instead of using:

Context context = getApplicationContext();

use

Context context = this;

Or if you are in an inner class of your Activity (a listener, or Task) use:

Context context = MyActivityNameComesHere.this;

See my Issue in the Android Bugtracker about this.


问:
Split by comma and how to exclude comma from quotes in split
python 2.7 code

```<code>cStr = '"aaaa","bbbb","ccc,ddd"'
newStr = cStr.split(',')
print newStr  # -> ['"aaaa"','"bbbb"','"ccc','ddd"' ]
</code>```

but, I want this result.

```<code>result = ['"aaa"','"bbb"','"ccc,ddd"']
</code>```

答:
I liked Mark de Haan' solution but I had to rework it, as it removed the quote characters (although they were needed) and therefore an assertion in his example failed. I also added two additional parameters to deal with different separators and quote characters.

```<code>def tokenize( string, separator = ',', quote = '"' ):
    """
    Split a comma separated string into a List of strings.

    Separator characters inside the quotes are ignored.

    :param string: A string to be split into chunks
    :param separator: A separator character
    :param quote: A character to define beginning and end of the quoted string
    :return: A list of strings, one element for every chunk
    """
    comma_separated_list = []

    chunk = ''
    in_quotes = False

    for character in string:
        if character == separator and not in_quotes:
            comma_separated_list.append(chunk)
            chunk = ''

        else:
            chunk += character
            if character == quote:
                in_quotes = False if in_quotes else True

    comma_separated_list.append( chunk )

    return comma_separated_list
</code>```

And the tests...

```<code>def test_tokenizer():
    string = '"aaaa","bbbb","ccc,ddd"'

    expected = ['"aaaa"', '"bbbb"', '"ccc,ddd"']
    actual = tokenize(string)

    assert expected == actual
</code>```

Body:
python 2.7 code

cStr = '"aaaa","bbbb","ccc,ddd"'
newStr = cStr.split(',')
print newStr  # -> ['"aaaa"','"bbbb"','"ccc','ddd"' ]

but, I want this result.

result = ['"aaa"','"bbb"','"ccc,ddd"']

Body:
I liked Mark de Haan' solution but I had to rework it, as it removed the quote characters (although they were needed) and therefore an assertion in his example failed. I also added two additional parameters to deal with different separators and quote characters.

def tokenize( string, separator = ',', quote = '"' ):
    """
    Split a comma separated string into a List of strings.

    Separator characters inside the quotes are ignored.

    :param string: A string to be split into chunks
    :param separator: A separator character
    :param quote: A character to define beginning and end of the quoted string
    :return: A list of strings, one element for every chunk
    """
    comma_separated_list = []

    chunk = ''
    in_quotes = False

    for character in string:
        if character == separator and not in_quotes:
            comma_separated_list.append(chunk)
            chunk = ''

        else:
            chunk += character
            if character == quote:
                in_quotes = False if in_quotes else True

    comma_separated_list.append( chunk )

    return comma_separated_list

And the tests...

def test_tokenizer():
    string = '"aaaa","bbbb","ccc,ddd"'

    expected = ['"aaaa"', '"bbbb"', '"ccc,ddd"']
    actual = tokenize(string)

    assert expected == actual


问:
Accessing res variable from multer disk storage
I'm hung up on this issue using the multer library on my Node server.  I'm trying to upload a file or files and then make a call to the database for each file and then send back success or failure to the client.

So my Node server route for uploading the file(s) looks like this:

app.post('/uploadFiles', (req, res) => {
    upload(req, res, async function (err) {
    ...
```
<p>Then that upload function is simply this:</p>
<pre class="lang-js prettyprint-override"><code>const upload = multer({ storage: multerStorage }).array('file');
</code>```

And then the multerStorage function that handles the destination and filename for multer:

const multerStorage = multer.diskStorage({
    destination: function (req, file, cb) {
        cb(null, process.env.LABELS_LOCATION);
    },
    filename: async function (req, file, cb) {
        // save file info to DB
        const itemID = file.originalname.slice(0, -4);
        const addLabelResult = addLabelToDB(itemID, 0);
        // console.log({ addLabelResult });
        // console.log({ itemID });
        // console.log({ file });
        cb(null, file.originalname);
    },
});
```
<p>And finally the <code>addLabelToDB</code> function:</p>
<pre class="lang-js prettyprint-override"><code>    const addLabelToDB = (itemID, enterType) => {
        const sp = 'insertLabelHistory';
        const inputs = [
            { name: 'itemID', type: sql.NVarChar, value: itemID },
            { name: 'enterType', type: sql.Bit, value: enterType },
        ];
        return executeSP(res, sp, inputs);
    };
</code>```

So the issue is that, if you look at the addLabelToDB function, you can see the call to executeSP takes in a res.  And I want that res from the original /uploadFiles route.  But I don't know how to access it from here.  And if there a better completely different way to do this, I am all ears.

答:
Maybe you already solved your issue but for future people with the same issue here it goes:

Remember that you can access res from req by req.res

In your case you can just pass res to addLabelToDB, here's how:

```<code>const multerStorage = multer.diskStorage({
    destination: function (req, file, cb) {
        cb(null, process.env.LABELS_LOCATION);
    },
    filename: async function (req, file, cb) {
        // save file info to DB
        const itemID = file.originalname.slice(0, -4);
        const addLabelResult = addLabelToDB(req.res, itemID, 0);
        cb(null, file.originalname);
    },
});
</code>```

And then on your addLabelToDB:

```<code>    const addLabelToDB = (res, itemID, enterType) => {
        const sp = 'insertLabelHistory';
        const inputs = [
            { name: 'itemID', type: sql.NVarChar, value: itemID },
            { name: 'enterType', type: sql.Bit, value: enterType },
         ];
        return executeSP(res, sp, inputs);
    };
</code>```

Body:
I'm hung up on this issue using the multer library on my Node server.  I'm trying to upload a file or files and then make a call to the database for each file and then send back success or failure to the client.

So my Node server route for uploading the file(s) looks like this:

app.post('/uploadFiles', (req, res) => {
    upload(req, res, async function (err) {
    ...

Then that upload function is simply this:

const upload = multer({ storage: multerStorage }).array('file');

And then the multerStorage function that handles the destination and filename for multer:

const multerStorage = multer.diskStorage({
    destination: function (req, file, cb) {
        cb(null, process.env.LABELS_LOCATION);
    },
    filename: async function (req, file, cb) {
        // save file info to DB
        const itemID = file.originalname.slice(0, -4);
        const addLabelResult = addLabelToDB(itemID, 0);
        // console.log({ addLabelResult });
        // console.log({ itemID });
        // console.log({ file });
        cb(null, file.originalname);
    },
});

And finally the addLabelToDB function:

    const addLabelToDB = (itemID, enterType) => {
        const sp = 'insertLabelHistory';
        const inputs = [
            { name: 'itemID', type: sql.NVarChar, value: itemID },
            { name: 'enterType', type: sql.Bit, value: enterType },
        ];
        return executeSP(res, sp, inputs);
    };

So the issue is that, if you look at the addLabelToDB function, you can see the call to executeSP takes in a res.  And I want that res from the original /uploadFiles route.  But I don't know how to access it from here.  And if there a better completely different way to do this, I am all ears.

Body:
Maybe you already solved your issue but for future people with the same issue here it goes:

Remember that you can access res from req by req.res

In your case you can just pass res to addLabelToDB, here's how:

const multerStorage = multer.diskStorage({
    destination: function (req, file, cb) {
        cb(null, process.env.LABELS_LOCATION);
    },
    filename: async function (req, file, cb) {
        // save file info to DB
        const itemID = file.originalname.slice(0, -4);
        const addLabelResult = addLabelToDB(req.res, itemID, 0);
        cb(null, file.originalname);
    },
});

And then on your addLabelToDB:

    const addLabelToDB = (res, itemID, enterType) => {
        const sp = 'insertLabelHistory';
        const inputs = [
            { name: 'itemID', type: sql.NVarChar, value: itemID },
            { name: 'enterType', type: sql.Bit, value: enterType },
         ];
        return executeSP(res, sp, inputs);
    };


问:
How to print math operations vertically?
I want to print strings like children in solving math operations, which is like this

```<code>   32      3801      45      123
+ 698    -    2    + 43    +  49
-----    ------    ----    -----
</code>```

I have tried it as follows

```<code>def arithmetic(problems):
# pisahkan setiap value
    atas = [i.split()[0] for i in problems]
    bawah = [i.split()[2] for i in problems]
    operator = [i.split()[1] for i in problems]

    output_atas = ""
    output_bawah = ""

    for j in range( len(problems) ):
        output_atas += f"{atas[j]:>8}"
        output_bawah += f"{operator[j]}  {bawah[j]:>5}"

    print(output_atas)
    print(output_bawah)

arithmetic(["32 + 698", "3801 - 2", "45 + 43", "123 + 49"])
</code>```

how to tidy up the string and adjust the line ---- according to the length of the number?

答: Add a new line /n in after first value and then operation and next value will be on anew line</p>

Body:
I want to print strings like children in solving math operations, which is like this

   32      3801      45      123
+ 698    -    2    + 43    +  49
-----    ------    ----    -----

I have tried it as follows

def arithmetic(problems):
# pisahkan setiap value
    atas = [i.split()[0] for i in problems]
    bawah = [i.split()[2] for i in problems]
    operator = [i.split()[1] for i in problems]

    output_atas = ""
    output_bawah = ""

    for j in range( len(problems) ):
        output_atas += f"{atas[j]:>8}"
        output_bawah += f"{operator[j]}  {bawah[j]:>5}"

    print(output_atas)
    print(output_bawah)

arithmetic(["32 + 698", "3801 - 2", "45 + 43", "123 + 49"])

how to tidy up the string and adjust the line ---- according to the length of the number?


问:
Possibilities to improve performance using vectorization for the following function in C#?
I have a function that estimates correlation between two input arrays.

The input is feeded by a dataDict which is of type Dictionary<string, double[]> which has 153 keys with values as double array of size 1500.

For each individual key, I need to estimate its correlation with all other keys and store the result to a double[,] that has a size of double[dataDict.Count(), dataDict.Count()]

The following function prepares two double[] arrays whose correlation needs to be estimated.

```<code>public double[,] CalculateCorrelation(Dictionary<string, double?[]> dataDict, string corrMethod = "kendall")
        {
            CorrelationLogicModule correlationLogicModule = new CorrelationLogicModule();
            double[,] correlationMatrix = new double[dataDict.Count(), dataDict.Count()];
            for (int i = 0; i < dataDict.Count; i++)
            {
                for (int j = 0; j < dataDict.Count; j++)
                {
                    var arrayA = dataDict[dataDict.ElementAt(i).Key].Cast<double>().ToArray();
                    var arrayB = dataDict[dataDict.ElementAt(j).Key].Cast<double>().ToArray();
                    correlationMatrix[i, j] = correlationLogicModule.Kendall_Formula(arrayA, arrayB);
                }
            }
            return correlationMatrix;
        }
</code>```

The following function (I found it on internet from here) finds correlation between two input arrays using 'Kendall's' method.

```<code>public double Kendall_Formula(double[] Ticker1, double[] Ticker2)
        {
            double NbrConcord, NbrDiscord, S;
            NbrConcord = 0;
            NbrDiscord = 0;
            S = 0;

            for (int i = 0; i < Ticker1.Length - 1; i++)
            {
                for (int j = i + 1; j < Ticker1.Length; j++)
                {
                    //Compute the number of concordant pairs
                    if (((Ticker1[i] < Ticker1[j]) & (Ticker2[i] < Ticker2[j])) | ((Ticker1[i] > Ticker1[j]) & (Ticker2[i] > Ticker2[j])))
                    {
                        NbrConcord++;
                    }
                    //Compute the number of discordant pairs
                    else if (((Ticker1[i] > Ticker1[j]) & (Ticker2[i] < Ticker2[j])) | ((Ticker1[i] < Ticker1[j]) & (Ticker2[i] > Ticker2[j])))
                    {
                        NbrDiscord++;
                    }
                }
            }
            S = NbrConcord - NbrDiscord;
            //Proportion with the total pairs
            return 2 * S / (Ticker1.Length * (Ticker1.Length - 1));
        }
</code>```

Moving this way forward, takes a very long time to calculate the correlations for all the keys.
is there a possible way to optimize the performance?.

I am new to C# but I have been using Python for a long time and in Python using 'Numpys' and 'Pandas' I am sure the above operation would take seconds to compute. For e.g. lets say I had the above data in form of a pandas dataframe, then data[[list of columns]].corr('method') would lead the result in seconds. This is because pandas uses numpy under the hood which takes benefit from vectorization. I would like to learn how can I take benefit from vectorization to improve the performance of the above code in C# and if there are other factors I need to consider. Thank you!

答:
You are using dataDict[dataDict.ElementAt(i).Key] to access the dictionary values in an undefined order. I don't know if that's what you intended, but the following code should give the the same results.

If you call dataDict.Values.ToArray(); you will get the dictionary values in the same order as you would when using foreach to iterate over it. That means that it will be the same as the order when using dataDict[dataDict.ElementAt(i).Key].

Therefore this code should be equivalent, and it should be faster:

```<code>public double[,] CalculateCorrelation(Dictionary<string, double?[]> dataDict, string corrMethod = "kendall")
{
    CorrelationLogicModule correlationLogicModule = new CorrelationLogicModule();

    var values = dataDict.Values.Select(array => array.Cast<double>().ToArray()).ToArray();

    double[,] correlationMatrix = new double[dataDict.Count, dataDict.Count];

    for (int i = 0; i < dataDict.Count; i++)
    {
        for (int j = 0; j < dataDict.Count; j++)
        {
            var arrayA = values[i];
            var arrayB = values[j];
            correlationMatrix[i, j] = correlationLogicModule.Kendall_Formula(arrayA, arrayB);
        }
    }
    return correlationMatrix;
}
</code>```

Note that the .ElementAt() call in your original code is a Linq extension, not a member of Dictionary<TKey,TValue>. It iterates from the start of the dictionary EVERY TIME you call it - and it also returns items in an unspecified order. From the documentation: For purposes of enumeration, each item in the dictionary is treated as a KeyValuePair<TKey,TValue> structure representing a value and its key. The order in which the items are returned is undefined.

Also:

You should change the bitwise & to logical && in your conditions. The use of & will prevent the compiler applying a boolean short-circuit optimisation, meaning that all the < / > comparisons will be performed, even if the first condition is false.

Body:
I have a function that estimates correlation between two input arrays.

The input is feeded by a dataDict which is of type Dictionary<string, double[]> which has 153 keys with values as double array of size 1500.

For each individual key, I need to estimate its correlation with all other keys and store the result to a double[,] that has a size of double[dataDict.Count(), dataDict.Count()]

The following function prepares two double[] arrays whose correlation needs to be estimated.

public double[,] CalculateCorrelation(Dictionary<string, double?[]> dataDict, string corrMethod = "kendall")
        {
            CorrelationLogicModule correlationLogicModule = new CorrelationLogicModule();
            double[,] correlationMatrix = new double[dataDict.Count(), dataDict.Count()];
            for (int i = 0; i < dataDict.Count; i++)
            {
                for (int j = 0; j < dataDict.Count; j++)
                {
                    var arrayA = dataDict[dataDict.ElementAt(i).Key].Cast<double>().ToArray();
                    var arrayB = dataDict[dataDict.ElementAt(j).Key].Cast<double>().ToArray();
                    correlationMatrix[i, j] = correlationLogicModule.Kendall_Formula(arrayA, arrayB);
                }
            }
            return correlationMatrix;
        }

The following function (I found it on internet from here) finds correlation between two input arrays using 'Kendall's' method.

public double Kendall_Formula(double[] Ticker1, double[] Ticker2)
        {
            double NbrConcord, NbrDiscord, S;
            NbrConcord = 0;
            NbrDiscord = 0;
            S = 0;

            for (int i = 0; i < Ticker1.Length - 1; i++)
            {
                for (int j = i + 1; j < Ticker1.Length; j++)
                {
                    //Compute the number of concordant pairs
                    if (((Ticker1[i] < Ticker1[j]) & (Ticker2[i] < Ticker2[j])) | ((Ticker1[i] > Ticker1[j]) & (Ticker2[i] > Ticker2[j])))
                    {
                        NbrConcord++;
                    }
                    //Compute the number of discordant pairs
                    else if (((Ticker1[i] > Ticker1[j]) & (Ticker2[i] < Ticker2[j])) | ((Ticker1[i] < Ticker1[j]) & (Ticker2[i] > Ticker2[j])))
                    {
                        NbrDiscord++;
                    }
                }
            }
            S = NbrConcord - NbrDiscord;
            //Proportion with the total pairs
            return 2 * S / (Ticker1.Length * (Ticker1.Length - 1));
        }

Moving this way forward, takes a very long time to calculate the correlations for all the keys.
is there a possible way to optimize the performance?.

I am new to C# but I have been using Python for a long time and in Python using 'Numpys' and 'Pandas' I am sure the above operation would take seconds to compute. For e.g. lets say I had the above data in form of a pandas dataframe, then data[[list of columns]].corr('method') would lead the result in seconds. This is because pandas uses numpy under the hood which takes benefit from vectorization. I would like to learn how can I take benefit from vectorization to improve the performance of the above code in C# and if there are other factors I need to consider. Thank you!

Body:
You are using dataDict[dataDict.ElementAt(i).Key] to access the dictionary values in an undefined order. I don't know if that's what you intended, but the following code should give the the same results.

If you call dataDict.Values.ToArray(); you will get the dictionary values in the same order as you would when using foreach to iterate over it. That means that it will be the same as the order when using dataDict[dataDict.ElementAt(i).Key].

Therefore this code should be equivalent, and it should be faster:

public double[,] CalculateCorrelation(Dictionary<string, double?[]> dataDict, string corrMethod = "kendall")
{
    CorrelationLogicModule correlationLogicModule = new CorrelationLogicModule();

    var values = dataDict.Values.Select(array => array.Cast<double>().ToArray()).ToArray();

    double[,] correlationMatrix = new double[dataDict.Count, dataDict.Count];

    for (int i = 0; i < dataDict.Count; i++)
    {
        for (int j = 0; j < dataDict.Count; j++)
        {
            var arrayA = values[i];
            var arrayB = values[j];
            correlationMatrix[i, j] = correlationLogicModule.Kendall_Formula(arrayA, arrayB);
        }
    }
    return correlationMatrix;
}

Note that the .ElementAt() call in your original code is a Linq extension, not a member of Dictionary<TKey,TValue>. It iterates from the start of the dictionary EVERY TIME you call it - and it also returns items in an unspecified order. From the documentation: For purposes of enumeration, each item in the dictionary is treated as a KeyValuePair<TKey,TValue> structure representing a value and its key. The order in which the items are returned is undefined.

Also:

You should change the bitwise & to logical && in your conditions. The use of & will prevent the compiler applying a boolean short-circuit optimisation, meaning that all the < / > comparisons will be performed, even if the first condition is false.


问:
Using state in other component
Hi I am learning and new to react and I want to know how to pass state from one component to other,

I have one component as

```<code>const [paneCount, setPaneCount]= useState(1);

const openPane = (paneKey) => {
  setOpeningPaneKeys(oldState => {
    if (!oldState.includes(paneKey)) {
      return [...oldState, paneKey]
    }
    return oldState
  })
  setPaneCount(paneCount+1);
  console.log(paneCount);

  setFocusingPaneKey(paneKey)
}
</code>```

where I want to use paneCount in App.js file

```<code>function App(props) {

const [inactive, setInactive] = useState(false);

return (
<div className="App">

  <Header />
  <Navbar
      onCollapse={(inactive) => {
        setInactive(!inactive);
      }}
    />

  <div class="landing-card">
    <div>

      <h4 class="headingStyle">Recorder Box</h4>
      <h4>Count:{props.paneCount}</h4>
      <img src="landing.jpg" alt="Forest" width="775" height="500"></img>
    </div>
  </div>
</code>```

How to pass paneCount to App.js

答:
Instead of passing paneCount to App.js which I suppose is the parent component. You can create paneCount in App.js and then pass setPaneCount to the openPane component like this.

```<code><openPane setPaneCount = {setPanecount} paneCount = {setPaneCount}/>
</code>```

If you are not calling openPane in the App.js for some reason then go to the parent component that is calling both App and openPane and create and pass the setPaneCount and paneCount from there. If you making something complex instead of drilling the value down like this you might want to look at some stateManagement tools like Redux or Context API.

Title: Using state in other component

Body:
Hi I am learning and new to react and I want to know how to pass state from one component to other,

I have one component as

const [paneCount, setPaneCount]= useState(1);

const openPane = (paneKey) => {
  setOpeningPaneKeys(oldState => {
    if (!oldState.includes(paneKey)) {
      return [...oldState, paneKey]
    }
    return oldState
  })
  setPaneCount(paneCount+1);
  console.log(paneCount);

  setFocusingPaneKey(paneKey)
}

where I want to use paneCount in App.js file

function App(props) {

const [inactive, setInactive] = useState(false);

return (

  <Navbar
      onCollapse={(inactive) => {
        setInactive(!inactive);
      }}
    />

Recorder Box

Count:{props.paneCount}

How to pass paneCount to App.js

Body:
Instead of passing paneCount to App.js which I suppose is the parent component. You can create paneCount in App.js and then pass setPaneCount to the openPane component like this.

<openPane setPaneCount = {setPanecount} paneCount = {setPaneCount}/>

If you are not calling openPane in the App.js for some reason then go to the parent component that is calling both App and openPane and create and pass the setPaneCount and paneCount from there. If you making something complex instead of drilling the value down like this you might want to look at some stateManagement tools like Redux or Context API.


问:
M1 Mac react-native iOS build error (in target 'RCT-Folly' from project 'Pods')
On an M1 Mac, with npm 8.3.1 & node 17.4, when I run npx react-native run-ios I receive 2 errors:

```<code>The following build commands failed:
    CompileC /Users/Steven/Library/Developer/Xcode/DerivedData/HelloSteve-hghgfcwemhoaiacfwlophutqqzbh/Build/Intermediates.noindex/Pods.build/Debug-iphonesimulator/RCT-Folly.build/Objects-normal/arm64/SysUio.o /Users/Steven/Documents/Projects/React\ Native/HelloSteve/ios/Pods/RCT-Folly/folly/portability/SysUio.cpp normal arm64 c++ com.apple.compilers.llvm.clang.1_0.compiler (in target 'RCT-Folly' from project 'Pods')
    CompileC /Users/Steven/Library/Developer/Xcode/DerivedData/HelloSteve-hghgfcwemhoaiacfwlophutqqzbh/Build/Intermediates.noindex/Pods.build/Debug-iphonesimulator/RCT-Folly.build/Objects-normal/arm64/NetOps.o /Users/Steven/Documents/Projects/React\ Native/HelloSteve/ios/Pods/RCT-Folly/folly/net/NetOps.cpp normal arm64 c++ com.apple.compilers.llvm.clang.1_0.compiler (in target 'RCT-Folly' from project 'Pods')
(2 failures)
</code>```

From this answer, the line flipper_post_install(installer) didn't exist in the Podfile.

From this answer, I commented out # use_flipper!() in the Podfile, ran pod install then npx react-native run-ios and received a similar error:

```<code>The following build commands failed:
        CompileC /Users/Steven/Library/Developer/Xcode/DerivedData/HelloSteve-hghgfcwemhoaiacfwlophutqqzbh/Build/Intermediates.noindex/Pods.build/Debug-iphonesimulator/RCT-Folly.build/Objects-normal/arm64/SysUio.o /Users/Steven/Documents/Projects/React\ Native/HelloSteve/ios/Pods/RCT-Folly/folly/portability/SysUio.cpp normal arm64 c++ com.apple.compilers.llvm.clang.1_0.compiler (in target 'RCT-Folly' from project 'Pods')
(1 failure)
</code>```

I tried the solution here, (commenting out the line typedef uint8_t clockid_t; in Time.h) but that didn't work either.

Help appreciated.

答:
I ran into a similar issue when updating the project target OS version.

Actually Xcode will ask you to change the target OS version for the different packages, which then lead to not finding the RCT package anymore for me.

So when xcode tells you there is a good option to change the target settings for different pods, be very careful with that. Either do it step by step and try out or leave it as is, as long as it is building and running.

npm install then pod install respectively arch -x86_64 pod install since I am also running on M1.

Since it might have to do something with that as well I would also disable arm64 in xcode your projects target build phases under build settings "excluded architectures" and only install pods with arch -x86_64 pod install.

Body:
On an M1 Mac, with npm 8.3.1 & node 17.4, when I run npx react-native run-ios I receive 2 errors:

The following build commands failed:
    CompileC /Users/Steven/Library/Developer/Xcode/DerivedData/HelloSteve-hghgfcwemhoaiacfwlophutqqzbh/Build/Intermediates.noindex/Pods.build/Debug-iphonesimulator/RCT-Folly.build/Objects-normal/arm64/SysUio.o /Users/Steven/Documents/Projects/React\ Native/HelloSteve/ios/Pods/RCT-Folly/folly/portability/SysUio.cpp normal arm64 c++ com.apple.compilers.llvm.clang.1_0.compiler (in target 'RCT-Folly' from project 'Pods')
    CompileC /Users/Steven/Library/Developer/Xcode/DerivedData/HelloSteve-hghgfcwemhoaiacfwlophutqqzbh/Build/Intermediates.noindex/Pods.build/Debug-iphonesimulator/RCT-Folly.build/Objects-normal/arm64/NetOps.o /Users/Steven/Documents/Projects/React\ Native/HelloSteve/ios/Pods/RCT-Folly/folly/net/NetOps.cpp normal arm64 c++ com.apple.compilers.llvm.clang.1_0.compiler (in target 'RCT-Folly' from project 'Pods')
(2 failures)

From this answer, the line flipper_post_install(installer) didn't exist in the Podfile.

From this answer, I commented out # use_flipper!() in the Podfile, ran pod install then npx react-native run-ios and received a similar error:

The following build commands failed:
        CompileC /Users/Steven/Library/Developer/Xcode/DerivedData/HelloSteve-hghgfcwemhoaiacfwlophutqqzbh/Build/Intermediates.noindex/Pods.build/Debug-iphonesimulator/RCT-Folly.build/Objects-normal/arm64/SysUio.o /Users/Steven/Documents/Projects/React\ Native/HelloSteve/ios/Pods/RCT-Folly/folly/portability/SysUio.cpp normal arm64 c++ com.apple.compilers.llvm.clang.1_0.compiler (in target 'RCT-Folly' from project 'Pods')
(1 failure)

I tried the solution here, (commenting out the line typedef uint8_t clockid_t; in Time.h) but that didn't work either.

Help appreciated.