问:
how to integrate tensorflow lite model to Android App
I have a ML model which i have exported as tensorflow Lite file. I need to integrate it to the Android Application(Java - Android Studio) to generate results according to the Cough Input via mic. I'm newbie to this. I have attached the python code and also java code below:

Here's the project file

https://github.com/zeshannaveed568/CoughDetectionSystem

Here's the snippets to the the ML model code.

```<code>%pip install keras
%pip install --upgrade pip
%pip install requests
%pip install tqdm
%pip install pillow
%pip install tensorflow
%pip install tensorflow==2.0.0-rc0
%pip install -U imbalanced-learn
%pip install matplotlib
%pip install scipy
%pip install pandas-datareader
%pip install pandas
%pip install numpy
%pip install jsonlib
%pip install protobuf
%pip install oc

labels = {"Asthma" : 0, "Covid" : 1, "Flu" : 2, "COPD" : 3, "Lung Cancer" : 4}
import json
import os
import numpy as np
X = []
y = []
for disease, label in labels.items():
    folder_path = "./pulmonary-diseaes-dataset/" + disease
    for file_name in os.listdir(folder_path):
        with open(folder_path + "/" + file_name) as file:
            arr = np.array(json.load(file))
            X.append(arr)
            for i in range(arr.shape[0]):
                y.append(label)
a = X[0]
for i in range(1,len(X)):
  a = np.vstack((a, X[i]))
X = a
X.shape
import matplotlib.pyplot as plt

counts = [0] * len(labels)
for i in y:
    counts[i] += 1

names = list(labels.keys())

plt.figure(figsize=(9, 3))

plt.bar(names, counts)
from sklearn.model_selection import train_test_split
X_train, X_test, y_train, y_test = train_test_split(X, y, test_size = 0.2, random_state = 42)
from imblearn.over_sampling import SMOTE
X_train = np.reshape(X_train, (X_train.shape[0], int(X_train.shape[1] * X_train.shape[2])))
X_train.shape
sm = SMOTE()
X_train , y_train = sm.fit_resample(X_train, y_train)
X_train = np.reshape(X_train, (X_train.shape[0],  45, 216))
X_train.shape
counts = [0] * len(labels)
for i in y_train:
    counts[i] += 1

names = list(labels.keys())

plt.figure(figsize=(9, 3))

plt.bar(names, counts)
X_train, X_test = X_train[..., np.newaxis] , X_test[..., np.newaxis]
X_train.shape, X_test.shape
from tensorflow.keras.utils import to_categorical
y_test_2 , y_train_2 = y_test.copy(), y_train.copy()
y_test , y_train = to_categorical(y_test) , to_categorical(y_train)
import tensorflow as tf
from tensorflow import keras
def get_model():
    model = keras.Sequential()

    model.add(keras.layers.Conv2D(32, (3, 3), activation='relu', input_shape=(X_train.shape[1], X_train.shape[2], 1)) )
    model.add(keras.layers.MaxPooling2D((3, 3), strides=(2, 2), padding='same'))
    model.add(keras.layers.BatchNormalization())

    model.add(keras.layers.Conv2D(32, (3, 3), activation='relu'))
    model.add(keras.layers.MaxPooling2D((3, 3), strides=(2, 2), padding='same'))
    model.add(keras.layers.BatchNormalization())

    model.add(keras.layers.Conv2D(32, (2, 2), activation='relu'))
    model.add(keras.layers.MaxPooling2D((2, 2), strides=(2, 2), padding='same'))
    model.add(keras.layers.BatchNormalization())

    model.add(keras.layers.Flatten())
    model.add(keras.layers.Dense(64, activation='relu'))
    model.add(keras.layers.Dropout(0.3))

    model.add(keras.layers.Dense(len(labels),   activation='softmax'))

    optimiser = tf.keras.optimizers.Adam(learning_rate=0.0001)
    model.compile(optimizer=optimiser,
                      loss='categorical_crossentropy',
                      metrics=['categorical_accuracy'])
    return model
model = get_model()
history = model.fit(X_train, y_train, validation_data=(X_test, y_test), batch_size=32, epochs=100)
import matplotlib.pyplot as plt
def plot_history(history):
    plt.plot(history.history['categorical_accuracy'])
    plt.plot(history.history['val_categorical_accuracy'])
    plt.title('model accuracy')
    plt.ylabel('accuracy')
    plt.xlabel('epoch')
    plt.legend(['train', 'test'], loc='upper left')
    plt.show()
    # summarize history for loss
    plt.plot(history.history['loss'])
    plt.plot(history.history['val_loss'])
    plt.title('model loss')
    plt.ylabel('loss')
    plt.xlabel('epoch')
    plt.legend(['train', 'test'], loc='upper left')
    plt.show()
plot_history(history)
def print_classification_report():
    pred = model.predict(X_test)
    y_pred = []
    for i in range(pred.shape[0]):
      index = -1
      maxVal = 0
      for j in range(pred.shape[1]):
        if pred[i][j] > maxVal:
          index = j
          maxVal = pred[i][j]
      y_pred.append(index)
    from sklearn.metrics import classification_report
    print(classification_report(y_test_2, y_pred))
print_classification_report()
X_train = X_train[ : , 4 : 17, : ]
X_test = X_test[: , 4:17, : ]
X_train.shape, X_test.shape
model = get_model()
history = model.fit(X_train, y_train, validation_data=(X_test, y_test), batch_size=32, epochs=100)
import pickle
pickle.dump(model, open("model.pkl", "wb"))
plot_history(history)
print_classification_report()
converter = tf.lite.TFLiteConverter.from_keras_model(model)
tflite_model = converter.convert()

with open('model.tflite', 'wb') as f:
  f.write(tflite_model)
</code>```

Here the code of java where I need to Implement this functionality:

Here's the layout Ss

https://imgur.com/JQkq1jX

This is where i need to implement this model to fetch results

```<code>

        floatRecord.setOnLongClickListener(new View.OnLongClickListener() {
            @Override
            public boolean onLongClick(View v) {
                startRecording();
                return true;
            }
        });

        return view;

    }
    private void startRecording() {
        //start on press and hold and stop on release
        //check if permission is granted
        if (ContextCompat.checkSelfPermission(getActivity(), Manifest.permission.RECORD_AUDIO) == PackageManager.PERMISSION_GRANTED) {
            //Passing an intent to record audio
            Intent intent = new Intent(MediaStore.Audio.Media.RECORD_SOUND_ACTION);
            startActivityForResult(intent, 1);

        } else {
            requestPermissions(new String[]{Manifest.permission.RECORD_AUDIO}, 1);
        }
    }

</code>```

Let me know if you need more details

I'm expecting if you can tell me details of how to implement the press and hold to record audio functionality in android studio. and also integration of tslite model to this particular applicaiton

Body:
I have a ML model which i have exported as tensorflow Lite file. I need to integrate it to the Android Application(Java - Android Studio) to generate results according to the Cough Input via mic. I'm newbie to this. I have attached the python code and also java code below:

Here's the project file

https://github.com/zeshannaveed568/CoughDetectionSystem

Here's the snippets to the the ML model code.

%pip install keras
%pip install --upgrade pip
%pip install requests
%pip install tqdm
%pip install pillow
%pip install tensorflow
%pip install tensorflow==2.0.0-rc0
%pip install -U imbalanced-learn
%pip install matplotlib
%pip install scipy
%pip install pandas-datareader
%pip install pandas
%pip install numpy
%pip install jsonlib
%pip install protobuf
%pip install oc

labels = {"Asthma" : 0, "Covid" : 1, "Flu" : 2, "COPD" : 3, "Lung Cancer" : 4}
import json
import os
import numpy as np
X = []
y = []
for disease, label in labels.items():
    folder_path = "./pulmonary-diseaes-dataset/" + disease
    for file_name in os.listdir(folder_path):
        with open(folder_path + "/" + file_name) as file:
            arr = np.array(json.load(file))
            X.append(arr)
            for i in range(arr.shape[0]):
                y.append(label)
a = X[0]
for i in range(1,len(X)):
  a = np.vstack((a, X[i]))
X = a
X.shape
import matplotlib.pyplot as plt

counts = [0] * len(labels)
for i in y:
    counts[i] += 1

names = list(labels.keys())

plt.figure(figsize=(9, 3))

plt.bar(names, counts)
from sklearn.model_selection import train_test_split
X_train, X_test, y_train, y_test = train_test_split(X, y, test_size = 0.2, random_state = 42)
from imblearn.over_sampling import SMOTE
X_train = np.reshape(X_train, (X_train.shape[0], int(X_train.shape[1] * X_train.shape[2])))
X_train.shape
sm = SMOTE()
X_train , y_train = sm.fit_resample(X_train, y_train)
X_train = np.reshape(X_train, (X_train.shape[0],  45, 216))
X_train.shape
counts = [0] * len(labels)
for i in y_train:
    counts[i] += 1

names = list(labels.keys())

plt.figure(figsize=(9, 3))

plt.bar(names, counts)
X_train, X_test = X_train[..., np.newaxis] , X_test[..., np.newaxis]
X_train.shape, X_test.shape
from tensorflow.keras.utils import to_categorical
y_test_2 , y_train_2 = y_test.copy(), y_train.copy()
y_test , y_train = to_categorical(y_test) , to_categorical(y_train)
import tensorflow as tf
from tensorflow import keras
def get_model():
    model = keras.Sequential()

    model.add(keras.layers.Conv2D(32, (3, 3), activation='relu', input_shape=(X_train.shape[1], X_train.shape[2], 1)) )
    model.add(keras.layers.MaxPooling2D((3, 3), strides=(2, 2), padding='same'))
    model.add(keras.layers.BatchNormalization())

    model.add(keras.layers.Conv2D(32, (3, 3), activation='relu'))
    model.add(keras.layers.MaxPooling2D((3, 3), strides=(2, 2), padding='same'))
    model.add(keras.layers.BatchNormalization())

    model.add(keras.layers.Conv2D(32, (2, 2), activation='relu'))
    model.add(keras.layers.MaxPooling2D((2, 2), strides=(2, 2), padding='same'))
    model.add(keras.layers.BatchNormalization())

    model.add(keras.layers.Flatten())
    model.add(keras.layers.Dense(64, activation='relu'))
    model.add(keras.layers.Dropout(0.3))

    model.add(keras.layers.Dense(len(labels),   activation='softmax'))

    optimiser = tf.keras.optimizers.Adam(learning_rate=0.0001)
    model.compile(optimizer=optimiser,
                      loss='categorical_crossentropy',
                      metrics=['categorical_accuracy'])
    return model
model = get_model()
history = model.fit(X_train, y_train, validation_data=(X_test, y_test), batch_size=32, epochs=100)
import matplotlib.pyplot as plt
def plot_history(history):
    plt.plot(history.history['categorical_accuracy'])
    plt.plot(history.history['val_categorical_accuracy'])
    plt.title('model accuracy')
    plt.ylabel('accuracy')
    plt.xlabel('epoch')
    plt.legend(['train', 'test'], loc='upper left')
    plt.show()
    # summarize history for loss
    plt.plot(history.history['loss'])
    plt.plot(history.history['val_loss'])
    plt.title('model loss')
    plt.ylabel('loss')
    plt.xlabel('epoch')
    plt.legend(['train', 'test'], loc='upper left')
    plt.show()
plot_history(history)
def print_classification_report():
    pred = model.predict(X_test)
    y_pred = []
    for i in range(pred.shape[0]):
      index = -1
      maxVal = 0
      for j in range(pred.shape[1]):
        if pred[i][j] > maxVal:
          index = j
          maxVal = pred[i][j]
      y_pred.append(index)
    from sklearn.metrics import classification_report
    print(classification_report(y_test_2, y_pred))
print_classification_report()
X_train = X_train[ : , 4 : 17, : ]
X_test = X_test[: , 4:17, : ]
X_train.shape, X_test.shape
model = get_model()
history = model.fit(X_train, y_train, validation_data=(X_test, y_test), batch_size=32, epochs=100)
import pickle
pickle.dump(model, open("model.pkl", "wb"))
plot_history(history)
print_classification_report()
converter = tf.lite.TFLiteConverter.from_keras_model(model)
tflite_model = converter.convert()

with open('model.tflite', 'wb') as f:
  f.write(tflite_model)

Here the code of java where I need to Implement this functionality:

Here's the layout Ss

https://imgur.com/JQkq1jX

This is where i need to implement this model to fetch results

        floatRecord.setOnLongClickListener(new View.OnLongClickListener() {
            @Override
            public boolean onLongClick(View v) {
                startRecording();
                return true;
            }
        });

        return view;

    }
    private void startRecording() {
        //start on press and hold and stop on release
        //check if permission is granted
        if (ContextCompat.checkSelfPermission(getActivity(), Manifest.permission.RECORD_AUDIO) == PackageManager.PERMISSION_GRANTED) {
            //Passing an intent to record audio
            Intent intent = new Intent(MediaStore.Audio.Media.RECORD_SOUND_ACTION);
            startActivityForResult(intent, 1);

        } else {
            requestPermissions(new String[]{Manifest.permission.RECORD_AUDIO}, 1);
        }
    }

Let me know if you need more details

I'm expecting if you can tell me details of how to implement the press and hold to record audio functionality in android studio. and also integration of tslite model to this particular applicaiton


来源: stackexchange

问:
Django Using Default Form & File Submission with Drag and Drop functionality
I have a django application that allow user to upload their image and then another dialog opens to collect user data related to them. After the dialog form has been submitted, I have added the javascript eventlistener to successfully submit the form with data and it redirects to the form's action attribute.
I wanna implement the same functionality, if user drop their image in the browser then dialog opens to collect user data, then do the same as above and redirect to the form's action attribute.
How can I achieve it?

Here is my code

#--urls.py

```<code>from django.urls import path
from . import views
from django.conf import settings
from django.conf.urls.static import static

urlpatterns = [
    path('', views.index, name='index'),
    path('success/', views.success_function, name='success page'),
] + static(settings.MEDIA_URL, document_root=settings.MEDIA_ROOT)
</code>```

#--views.py

```<code>def index(request):
    form = userForm()
    return render(request, 'polls/hello_world.html', {'form': form})

def success_function(request):
    if request.method == 'POST':
        form = userForm(request.POST, request.FILES)
        user_files = request.FILES.getlist('django_image_field')

        if form.is_valid():
            images_data = []
            for eachfile in user_files:
                #handle_uploaded_file(eachfile)
                file_path = file_upload(eachfile)
                img_details = {'file_path': file_path, 'file_name': eachfile.name}
                images_data.append(img_details)

            return render(request, 'polls/success.html', {'data': images_data})
        else:
            print(form.errors)
            return HttpResponse("Not valid form")
    else:
        return HttpResponse("Not a valid method")
</code>```

--under forms.py

```<code>class NameForm(forms.Form):

    your_name = forms.CharField(required=False, label='Your name', max_length=100)

    django_image_field = forms.ImageField(required=True,
        label="",
        widget=forms.ClearableFileInput(attrs={
            'multiple': True,
            'id':'file-input'
            }))
</code>```

--#inside index

```<code><form enctype="multipart/form-data" action="{% url 'success' %}" id="myform" method="POST">
    {% csrf_token %}
    {{ form.django_image_field }}

<dialog id="user_dialog">

<form method="dialog" id="more_details">

</h6>
<p>Enter Name: </p>
    {{ form.your_name.label_tag }}
    {{ form.your_name }}

<button id="submit_btn" type="submit">Submit</button>

</form>

</dialog>

</form>
</code>```

ContentLicense: CC BY-SA 4.0

Body:
I have a django application that allow user to upload their image and then another dialog opens to collect user data related to them. After the dialog form has been submitted, I have added the javascript eventlistener to successfully submit the form with data and it redirects to the form's action attribute.
I wanna implement the same functionality, if user drop their image in the browser then dialog opens to collect user data, then do the same as above and redirect to the form's action attribute.
How can I achieve it?

Here is my code

#--urls.py

from django.urls import path
from . import views
from django.conf import settings
from django.conf.urls.static import static

urlpatterns = [
    path('', views.index, name='index'),
    path('success/', views.success_function, name='success page'),
] + static(settings.MEDIA_URL, document_root=settings.MEDIA_ROOT)

#--views.py

def index(request):
    form = userForm()
    return render(request, 'polls/hello_world.html', {'form': form})

def success_function(request):
    if request.method == 'POST':
        form = userForm(request.POST, request.FILES)
        user_files = request.FILES.getlist('django_image_field')

        if form.is_valid():
            images_data = []
            for eachfile in user_files:
                #handle_uploaded_file(eachfile)
                file_path = file_upload(eachfile)
                img_details = {'file_path': file_path, 'file_name': eachfile.name}
                images_data.append(img_details)

            return render(request, 'polls/success.html', {'data': images_data})
        else:
            print(form.errors)
            return HttpResponse("Not valid form")
    else:
        return HttpResponse("Not a valid method")

--under forms.py

class NameForm(forms.Form):

    your_name = forms.CharField(required=False, label='Your name', max_length=100)

    django_image_field = forms.ImageField(required=True,
        label="",
        widget=forms.ClearableFileInput(attrs={
            'multiple': True,
            'id':'file-input'
            }))

--#inside index

<form enctype="multipart/form-data" action="{% url 'success' %}" id="myform" method="POST">
    {% csrf_token %}
    {{ form.django_image_field }}

<dialog id="user_dialog">

<form method="dialog" id="more_details">

Enter Name:

    {{ form.your_name.label_tag }}
    {{ form.your_name }}

<button id="submit_btn" type="submit">Submit</button>

</form>

</dialog>

</form>


问:
Sorting tuples with divide-and-conquer algorithm inside DB
I saw a lecture explaining that the database engine uses the divide-and-conquer algorithm for sorting to split the data set into separate runs and then sort them if the data that we need to sort couldn't fit in memory.
In this algorithm when the pages are sorted and then written to disk, then merge the pages and compare each value, the output page is written to disk, this will finally merge two big pages which contain all tuples, my question is if the size of the tuple is very large more than memory size how will it handle at the last point when merging two big pages if these two pages size is large than memory size?</p>


问:
Gradle multi-module app shadow-jar exits with exit-code 0 on run
I have Gradle multi-module project on Kotlin with Spring boot application. In order to pack contents of the modules together I'm using shadow-jar plugin:
`

```<code>id("com.github.johnrengelman.shadow") version "7.0.0"

</code>```
```<code>tasks.withType<ShadowJar> {
    mergeServiceFiles()
    duplicatesStrategy = DuplicatesStrategy.EXCLUDE
    archiveBaseName.set("shadow")
    archiveFileName.set("app-fat.jar")
    manifest {
        attributes["Main-Class"] = mainClassPath
    }
}

</code>```

`
Plugin creates runnable fat-jar with spring boot application which creates beans, starts and then suddenly stops with exit-code 0 without any errors. Of course, when I run my app not from fat-jar application works as expected.

I have following dependency so I expect app not to exit:

```<code>implementation("org.springframework.boot:spring-boot-starter-web")
</code>```

Body:
I have Gradle multi-module project on Kotlin with Spring boot application. In order to pack contents of the modules together I'm using shadow-jar plugin:
`

id("com.github.johnrengelman.shadow") version "7.0.0"

tasks.withType<ShadowJar> {
    mergeServiceFiles()
    duplicatesStrategy = DuplicatesStrategy.EXCLUDE
    archiveBaseName.set("shadow")
    archiveFileName.set("app-fat.jar")
    manifest {
        attributes["Main-Class"] = mainClassPath
    }
}

`
Plugin creates runnable fat-jar with spring boot application which creates beans, starts and then suddenly stops with exit-code 0 without any errors. Of course, when I run my app not from fat-jar application works as expected.

I have following dependency so I expect app not to exit:

implementation("org.springframework.boot:spring-boot-starter-web")


问:
Using Class to create TkInter Countdown timer
I'm trying to create a coundown timer using Tkinter in Python. The code works fine when I run without using Class but when I introduce class, for some reason the code is not running: the reset button does not make the first cell 00 and the 00 is not there by default to get started with. Thanks for the help!</p>
```<code>#**--This is working--*
#Practicisng above Code#
#-------------------------------------------

import time
from tkinter import *

WinD = Tk()

WinD.geometry("300x350")
WinD.title("Time Counter")

Hours = StringVar()

Hours.set("00")

hoursEntry = Entry(WinD, width=3, font=("Cambria",18,""),
                 textvariable=Hours)
hoursEntry.place(x=80,y=20)

def reset():
    #change the value of global variable
#     global count
#     count=1
    Hours.set("00")

btn = Button(WinD, text='Reset', bd='5',
             command= reset)
btn.place(x = 70,y = 120)

WinD.mainloop()

</code>```
```<code>#**--This is not Working--**

#My Stopwatch Project
#importing req. modules
from tkinter import *
import sys
import time
global count

class Stopwatch():
    def __init__(self):
        #Create object of Tkinter, providing geometry and title
        self.root = Tk()
        self.root.title("Stop Watch")
        self.root.geometry("600x200")

        #Declaration of variables
        self.hour = StringVar()

        #Set the default value to 0
        self.hour.set = ("00")

        #Use of Entry class to take inputs from the user
        self.hourEntry = Entry(self.root, width = 3, font = ("Arial", 18, ""), textvariable=self.hour)
        self.hourEntry.place(x=80, y=20)

        self.bt3 = Button(self.root, text = "Reset", command = self.reset, font=("Times", 12, "bold"), bg=("#DE1738"), bd=5)
        self.bt3.place(x=320, y=100)

        self.root.mainloop()

    def reset(self):
        #change the value of global variable
        self.hour.set = ("00")

a = Stopwatch()

</code>```

Body:
I'm trying to create a coundown timer using Tkinter in Python. The code works fine when I run without using Class but when I introduce class, for some reason the code is not running: the reset button does not make the first cell 00 and the 00 is not there by default to get started with. Thanks for the help!

#**--This is working--*
#Practicisng above Code#
#-------------------------------------------

import time
from tkinter import *

WinD = Tk()

WinD.geometry("300x350")
WinD.title("Time Counter")

Hours = StringVar()

Hours.set("00")

hoursEntry = Entry(WinD, width=3, font=("Cambria",18,""),
                 textvariable=Hours)
hoursEntry.place(x=80,y=20)

def reset():
    #change the value of global variable
#     global count
#     count=1
    Hours.set("00")

btn = Button(WinD, text='Reset', bd='5',
             command= reset)
btn.place(x = 70,y = 120)

WinD.mainloop()

#**--This is not Working--**

#My Stopwatch Project
#importing req. modules
from tkinter import *
import sys
import time
global count

class Stopwatch():
    def __init__(self):
        #Create object of Tkinter, providing geometry and title
        self.root = Tk()
        self.root.title("Stop Watch")
        self.root.geometry("600x200")

        #Declaration of variables
        self.hour = StringVar()

        #Set the default value to 0
        self.hour.set = ("00")

        #Use of Entry class to take inputs from the user
        self.hourEntry = Entry(self.root, width = 3, font = ("Arial", 18, ""), textvariable=self.hour)
        self.hourEntry.place(x=80, y=20)

        self.bt3 = Button(self.root, text = "Reset", command = self.reset, font=("Times", 12, "bold"), bg=("#DE1738"), bd=5)
        self.bt3.place(x=320, y=100)

        self.root.mainloop()

    def reset(self):
        #change the value of global variable
        self.hour.set = ("00")

a = Stopwatch()


问:
Bigcommerce Bundle visually-hidden" failed to @extend "%visually-hidden Nod incompatible
I am trying to Bundle Bigcommerce Theme but I am getting this kind of error. I tried deleting the line but another one will appear from a different file. I have tried following the recommendation

```<code>npm install --use-old-node-sass-fork.
</code>```

but it didn't work and I keep getting the same error

```<code>Error: ".visually-hidden" failed to @extend "%visually-hidden".
   The selector "%visually-hidden" was not found.
   Use "@extend %visually-hidden !optional" if the extend should be able to fail.
    on line 22 of base/base.scss
>>   @extend %visually-hidden;
 ----------^
:

---------WARNING---------
We are currently in the process of deprecating node-sass fork
https://github.com/bigcommerce-labs/node-sass
Your scss files were compiled using latest node-sass version
https://github.com/sass/node-sass
This error might indicate that your scss file is not compatible with it.
There is still an option to compile scss file old fork by using --use-old-node-sass-fork.
But note, that this will lead to 500 error in production in near future.
---------WARNING---------
</code>```

I saw a thread that " I had to just upgrade my bootstrap version in Base.html file and the error was solved." but I do not have that on the theme that I am using

```<code><head>
<meta http-equiv="X-UA-Compatible" content="ie=edge" />

 <title>{{head.title}}</title>

 {{{head.meta_tags}}}
 {{{head.config}}}

 <link href="{{head.favicon}}" rel="shortcut icon">
 <meta name="viewport" content="width=device-width, initial-scale=1, maximum-scale=1">
 <script>document.documentElement.className = document.documentElement.className.replace(/\bno-js\b/,'js');</script>

{{> components/common/polyfill-script }}

 {{!-- Load Lazysizes script ASAP so images will appear --}}
 <script>
{{!-- Only load visible elements until the onload event fires,
  after which preload nearby elements. --}}
window.lazySizesConfig = window.lazySizesConfig || {};
window.lazySizesConfig.loadMode = 1;
</script>
<script async src="{{cdn 'assets/dist/theme-bundle.head_async.js'}}"></script>

{{{stylesheet '/assets/css/theme.css'}}}

{{ getFontsCollection }}

{{{head.scripts}}}
{{{head.rsslinks}}}
{{inject 'themeImageSizes' theme_images}}
{{> components/common/global-injects}}
{{{snippet 'html_head'}}}

{{> core/structured-data/website}}
</head>
</code>```

Body:
I am trying to Bundle Bigcommerce Theme but I am getting this kind of error. I tried deleting the line but another one will appear from a different file. I have tried following the recommendation

npm install --use-old-node-sass-fork.

but it didn't work and I keep getting the same error

Error: ".visually-hidden" failed to @extend "%visually-hidden".
   The selector "%visually-hidden" was not found.
   Use "@extend %visually-hidden !optional" if the extend should be able to fail.
    on line 22 of base/base.scss
>>   @extend %visually-hidden;
 ----------^
:

---------WARNING---------
We are currently in the process of deprecating node-sass fork
https://github.com/bigcommerce-labs/node-sass
Your scss files were compiled using latest node-sass version
https://github.com/sass/node-sass
This error might indicate that your scss file is not compatible with it.
There is still an option to compile scss file old fork by using --use-old-node-sass-fork.
But note, that this will lead to 500 error in production in near future.
---------WARNING---------

I saw a thread that " I had to just upgrade my bootstrap version in Base.html file and the error was solved." but I do not have that on the theme that I am using

<meta http-equiv="X-UA-Compatible" content="ie=edge" />

 <title>{{head.title}}</title>

 {{{head.meta_tags}}}
 {{{head.config}}}

 <link href="{{head.favicon}}" rel="shortcut icon">
 <meta name="viewport" content="width=device-width, initial-scale=1, maximum-scale=1">

{{> components/common/polyfill-script }}

 {{!-- Load Lazysizes script ASAP so images will appear --}}

{{{stylesheet '/assets/css/theme.css'}}}

{{ getFontsCollection }}

{{{head.scripts}}}
{{{head.rsslinks}}}
{{inject 'themeImageSizes' theme_images}}
{{> components/common/global-injects}}
{{{snippet 'html_head'}}}

{{> core/structured-data/website}}


问:
Unity - How to log into Facebook without SDK?
I want to see if I can make my Unity application login to Facebook without using the Facebook SDK. Instead, I want to use the Graphs API, because the SDK does not play nice with other plugins and has lots of baggage I don't need.

I'm sending a GET request from my Unity app, which uses the API for getting auth token:

```<code>https://www.facebook.com/v15.0/dialog/oauth?
client_id={app-id}
&redirect_uri={redirect-uri}
&response_type=token
</code>```

From my knowledge, this is supposed to either open the redirect URL with the auth token attached, or prompt me to sign-in/approve this app logging in. It works well pasting this request into a browser and hitting enter.

However, when sending this request via Unity, I get an HTML file as response. Opening this HTML file shows a page where Facebook tells me that Facebook does not support this browser and tells me to go download Chrome or Firefox.

Has anyone managed to get Facebook sign-in to work without the SDK? Or any idea how to avoid this error and get redirected to the page as expected?

Thanks in advance!

Body:
I want to see if I can make my Unity application login to Facebook without using the Facebook SDK. Instead, I want to use the Graphs API, because the SDK does not play nice with other plugins and has lots of baggage I don't need.

I'm sending a GET request from my Unity app, which uses the API for getting auth token:

https://www.facebook.com/v15.0/dialog/oauth?
client_id={app-id}
&redirect_uri={redirect-uri}
&response_type=token

From my knowledge, this is supposed to either open the redirect URL with the auth token attached, or prompt me to sign-in/approve this app logging in. It works well pasting this request into a browser and hitting enter.

However, when sending this request via Unity, I get an HTML file as response. Opening this HTML file shows a page where Facebook tells me that Facebook does not support this browser and tells me to go download Chrome or Firefox.

Has anyone managed to get Facebook sign-in to work without the SDK? Or any idea how to avoid this error and get redirected to the page as expected?

Thanks in advance!


问:
Issue with an event from a javascript widget (Tradingview) where only first added event is triggered when created on a loop
I have the following issue with a javascript chart widget Im using. I think my issue is more to do with my logic than with a problem with the chart library itself. I have already asked this on their GitHub repo, but again I believe this is just me not doing this properly.

This  javascript widget provides events that I can act upon. This is a javascript  library from TradingView (chart library), it has a function to create a line on the chart. This function is called .createOrderLine(). When you create an orderLine, it returns an object that you can manipulate (set price, events, etc)

This object has an event called onMove(), with a callback function that I can write code to. So what I am doing is, looping through an array of orders and creating a line on the chart for each order that exists. So every time I move a line on the chart, this callback is called.

When the chart is loaded initially, I add each line object to a Map by setting its key to the orderID and the value to the object itself. If I can’t find the orderID on the map, I will set it to the map.

The issue Im having that I can not figure out is, every time I move ANY of the lines created, only the code from the first order added is triggered, ie: the console.log(order.OrderID) always returns the id of the first line created, no matter which line I move. So in essence, it seems the onMove() from the first order is the only one that runs.

Here is some simplified version of my logic / code:

```<code>
var objectMapOrders = new Map();

for(var order of currentSelectedMarketOrderIds){

    var apiOrderObject = objectMapOrders.get(parseInt(order.OrderID))
    if(!apiOrderObject){

        var apiOrderObject = widget.activeChart()
        .createOrderLine()
        .setPrice(order.EntryPrice)

        objectMapOrders.set(parseInt(order.OrderID), apiOrderObject);

    }else{

        apiOrderObject
        .setPrice(order.EntryPrice)
        .onMove(async function() {
            //Call function that updates the order price
            console.log(order.OrderID)
            updateOrder(order.OrderID,this.price())

        })

    }

}

</code>```

Not sure if Im using the Map correctly or if there’s an alternative way that I can make this work?

I have tried all sorts of changes around (setting the onMove on inside each if block) to no avail

Body:
I have the following issue with a javascript chart widget Im using. I think my issue is more to do with my logic than with a problem with the chart library itself. I have already asked this on their GitHub repo, but again I believe this is just me not doing this properly.

This  javascript widget provides events that I can act upon. This is a javascript  library from TradingView (chart library), it has a function to create a line on the chart. This function is called .createOrderLine(). When you create an orderLine, it returns an object that you can manipulate (set price, events, etc)

This object has an event called onMove(), with a callback function that I can write code to. So what I am doing is, looping through an array of orders and creating a line on the chart for each order that exists. So every time I move a line on the chart, this callback is called.

When the chart is loaded initially, I add each line object to a Map by setting its key to the orderID and the value to the object itself. If I can’t find the orderID on the map, I will set it to the map.

The issue Im having that I can not figure out is, every time I move ANY of the lines created, only the code from the first order added is triggered, ie: the console.log(order.OrderID) always returns the id of the first line created, no matter which line I move. So in essence, it seems the onMove() from the first order is the only one that runs.

Here is some simplified version of my logic / code:

var objectMapOrders = new Map();

for(var order of currentSelectedMarketOrderIds){

    var apiOrderObject = objectMapOrders.get(parseInt(order.OrderID))
    if(!apiOrderObject){

        var apiOrderObject = widget.activeChart()
        .createOrderLine()
        .setPrice(order.EntryPrice)

        objectMapOrders.set(parseInt(order.OrderID), apiOrderObject);

    }else{

        apiOrderObject
        .setPrice(order.EntryPrice)
        .onMove(async function() {
            //Call function that updates the order price
            console.log(order.OrderID)
            updateOrder(order.OrderID,this.price())

        })

    }

}

Not sure if Im using the Map correctly or if there’s an alternative way that I can make this work?

I have tried all sorts of changes around (setting the onMove on inside each if block) to no avail


问:
Can I create a double-morphed many-to-many relationship in Laravel?
I have two models: Product and Group, which I want to both give a many-to-many 'shown' and a 'recommended' relation with itself and the other (so both have has to be morphed in both ways).

So a 'shown' resource of either type has a set of 'recommended' resources of either type (the Groups are actually acting as a container for grouped Products).

The table should be pretty straightforward:

```<code>        Schema::create('recommendables', function (Blueprint $table) {
            $table->id();
            $table->morphs('shown');
            $table->morphs('recommendable');
            $table->timestamps();
        });

</code>```

Then relations are defined in the trait 'RecommendableTrait' which is then given to both classes. As far as these relationships are concerned both classes are then handled pretty much the same later on (even to be merged into a single collection), so there is merit in trying to do it this way.

The problem is that the following relation definitions won't work, because it will look for group_id if I call the morphed relations on Group, similarly with `morphedByMany'.

```<code>trait RecommendableTrait {

    // RECOMMENDED GROUPS
    public function recommendedGroups()
    {
        return $this->morphToMany(Group::class, 'recommendable', 'recommendables')
            ->withTimestamps();
    }

    // RECOMMENDED PRODUCTS
    public function recommendedProducts()
    {
        return $this->morphToMany(Product::class, 'recommendable', 'recommendables')
            ->withTimestamps();
    }

    // SHOWN GROUPS
    public function shownGroups()
    {
        return $this->morphToMany(Group::class, 'shown', 'recommendables')
            ->withTimestamps();
    }

    // SHOWN PRODUCTS
    public function shownProducts()
    {
        return $this->morphToMany(Product::class, 'shown', 'recommendables')
            ->withTimestamps();
    }
}
</code>```

Now I know, I'm looking to create a bit of a weird relation tangle here. But I'm hoping defining a double-morphed many-to-many is possible in Laravel?

If not, I guess I'll have to either split it up in two single-morphed many-to-Many relationship sets for both classes. Which would be annoying because of the code that goes on top of these relations would have to be needlessly duplicated. Or I'll have to forego relations and just DB query the results directly. Thus giving up some of Eloquence's convenience, but at least allowing me to keep the code confined to a single shared trait.

Body:
I have two models: Product and Group, which I want to both give a many-to-many 'shown' and a 'recommended' relation with itself and the other (so both have has to be morphed in both ways).

So a 'shown' resource of either type has a set of 'recommended' resources of either type (the Groups are actually acting as a container for grouped Products).

The table should be pretty straightforward:

        Schema::create('recommendables', function (Blueprint $table) {
            $table->id();
            $table->morphs('shown');
            $table->morphs('recommendable');
            $table->timestamps();
        });

Then relations are defined in the trait 'RecommendableTrait' which is then given to both classes. As far as these relationships are concerned both classes are then handled pretty much the same later on (even to be merged into a single collection), so there is merit in trying to do it this way.

The problem is that the following relation definitions won't work, because it will look for group_id if I call the morphed relations on Group, similarly with `morphedByMany'.

trait RecommendableTrait {

    // RECOMMENDED GROUPS
    public function recommendedGroups()
    {
        return $this->morphToMany(Group::class, 'recommendable', 'recommendables')
            ->withTimestamps();
    }

    // RECOMMENDED PRODUCTS
    public function recommendedProducts()
    {
        return $this->morphToMany(Product::class, 'recommendable', 'recommendables')
            ->withTimestamps();
    }

    // SHOWN GROUPS
    public function shownGroups()
    {
        return $this->morphToMany(Group::class, 'shown', 'recommendables')
            ->withTimestamps();
    }

    // SHOWN PRODUCTS
    public function shownProducts()
    {
        return $this->morphToMany(Product::class, 'shown', 'recommendables')
            ->withTimestamps();
    }
}

Now I know, I'm looking to create a bit of a weird relation tangle here. But I'm hoping defining a double-morphed many-to-many is possible in Laravel?

If not, I guess I'll have to either split it up in two single-morphed many-to-Many relationship sets for both classes. Which would be annoying because of the code that goes on top of these relations would have to be needlessly duplicated. Or I'll have to forego relations and just DB query the results directly. Thus giving up some of Eloquence's convenience, but at least allowing me to keep the code confined to a single shared trait.


问:
Pipelined vs blocking data exchange in a Flink job
I've been reading about pipelined region scheduling in Flink and am a bit confused about what they mean. My understanding of it is that a Streaming job is always pipelined whereas a Batch job can produce intermediate results that are blocking. This makes sense since an operator can load the entire datastream into memory and process all of it to produce a result that only then can go into the next operator for further processing in case of a Batch job.

The blog post then describes pipelined regions that consists of 4 different regions and has pipelined and blocking data exchanges in the same topology. My question is, how would one go about creating such a job in Flink where it is able to handle both pipelined and blocking data exchanges? A simple code example would be very much appreciated where this capability is showcased.


问:
Need to update mobile number status in csv file on a particular response using Python
Please find the below code which I tried, I want to save mobile number status whether it is Delivered or Failed to Deliver response.

Below Is My Code:

```<code>import pandas as pd
import time
from collections import ChainMap
from sendSMS import sendSMS, deliveryRespo

#Reads the Contact List from .csv file.
mobileNumbers = pd.read_csv("contactLists.csv")
contacts = mobileNumbers.get('mobileNumber')

for contact in contacts:
    # send_SMS = sendSMS(contact)

    # Msg Response Example:
    msg_response = {'status': 'Success', 'code': '011', 'description': 'Message submitted successfully', 'data': {'messageid': 'NzQ0MDQ=', 'totnumber': 1, 'totalcredit': 1}}

    #This will gibe message id so that we can track the delivery status
    # msg_response = send_SMS.json()
    print(msg_response)
    msg_id = msg_response['data']['messageid']
    print(contact)

    # time.sleep(15)

    #This will give delivery status: [Submitted, Delivered, Failed]
    # respo = deliveryRespo(msg_id)
    # dr = respo.json()

    # Delivery Report Response Example:
    dr = {'status': 'Success', 'code': '004', 'totRecord': 1, 'data': [{'id': 'NzQ0MDQ=', 'mobile': '91993XXXXX51', 'status': 'Delivered', 'delvd_time': '18-12-2022 15:43:35'}]}
    print(dr)
    dd = dr['data']
    md = dict(ChainMap(*dd))
    deliveryStatus = md['status']
    toMobile = md['mobile']

    if deliveryStatus == 'Delivered':
        # contacts.loc[contacts['mobileNumber'] == 'Delivered', 'isFailed'] = 'No'
        print(f'SMS has been {deliveryStatus} to mobile no.: {toMobile}')

        if deliveryStatus == 'Failed':
            # deliveryStatus.loc[deliveryStatus['status'] == 'Failed', 'isFailed'] = 'Yes'
            print(f'SMS has been Failed to mobile no.: {toMobile}.')

    else:
        print(f'SMS has been {deliveryStatus} to mobile no.: {toMobile}')
</code>```

The delivery report response will be used to update the isFailed column

I want to update the isFailed column in CSV with the given conditions.

Body:
Please find the below code which I tried, I want to save mobile number status whether it is Delivered or Failed to Deliver response.

Below Is My Code:

import pandas as pd
import time
from collections import ChainMap
from sendSMS import sendSMS, deliveryRespo

#Reads the Contact List from .csv file.
mobileNumbers = pd.read_csv("contactLists.csv")
contacts = mobileNumbers.get('mobileNumber')

for contact in contacts:
    # send_SMS = sendSMS(contact)

    # Msg Response Example:
    msg_response = {'status': 'Success', 'code': '011', 'description': 'Message submitted successfully', 'data': {'messageid': 'NzQ0MDQ=', 'totnumber': 1, 'totalcredit': 1}}

    #This will gibe message id so that we can track the delivery status
    # msg_response = send_SMS.json()
    print(msg_response)
    msg_id = msg_response['data']['messageid']
    print(contact)

    # time.sleep(15)

    #This will give delivery status: [Submitted, Delivered, Failed]
    # respo = deliveryRespo(msg_id)
    # dr = respo.json()

    # Delivery Report Response Example:
    dr = {'status': 'Success', 'code': '004', 'totRecord': 1, 'data': [{'id': 'NzQ0MDQ=', 'mobile': '91993XXXXX51', 'status': 'Delivered', 'delvd_time': '18-12-2022 15:43:35'}]}
    print(dr)
    dd = dr['data']
    md = dict(ChainMap(*dd))
    deliveryStatus = md['status']
    toMobile = md['mobile']

    if deliveryStatus == 'Delivered':
        # contacts.loc[contacts['mobileNumber'] == 'Delivered', 'isFailed'] = 'No'
        print(f'SMS has been {deliveryStatus} to mobile no.: {toMobile}')

        if deliveryStatus == 'Failed':
            # deliveryStatus.loc[deliveryStatus['status'] == 'Failed', 'isFailed'] = 'Yes'
            print(f'SMS has been Failed to mobile no.: {toMobile}.')

    else:
        print(f'SMS has been {deliveryStatus} to mobile no.: {toMobile}')

The delivery report response will be used to update the isFailed column

I want to update the isFailed column in CSV with the given conditions.


问:
Simple spell checker using Levenshtein distance
I have to implement a simple spell checker. Basically I have to user input an incorrect sentence or a word, then a number N, and then N correct words each on new line. The program has to output "incorrect word: suggestion". If there is no suggestions available it should output "incorrect word: no suggestions" and if all the words from sentence are correct it should display "Correct text!". The typos can be:

Misspeled word.

Swapped letters.

Extra letter.

Missing letter.

To do this I implemented Levensthein minumim distance algorithm, which calculates the minimum number of modifications that a string has to take to be transformed into another string. All the test cases are fine but I want to reduce the cyclomatic complexity of the main method from 27 to below 26. Any suggestion would be helpful. For the example:

```<code>Thsi is an texzt fr tet
5
This
an
text
for
test

It displays:
Thsi: This
an: no suggestions
texzt: text
fr: for
tet: text test
</code>```
```<code>using System;
using System.Collections.Generic;

namespace MisspelledWords
{
    class Program
    {
        static void Main(string[] args)
        {
            string sentence = Console.ReadLine();
            sentence = sentence.ToLower();
            int numWords = int.Parse(Console.ReadLine());
            const int doi = 2;
            const int doi2 = 3;
            int index = 0;
            int index1 = 0;
            string[] correctWords = new string[numWords];
            for (int i = 0; i < numWords; i++)
            {
                correctWords[i] = Console.ReadLine();
            }

            foreach (string word in sentence.Split(' '))
            {
                index++;
                int minDistance = int.MaxValue;
                string closestWord = "";
                foreach (string correctWord in correctWords)
                {
                    int distance = GetLevenshteinDistance(word, correctWord);
                    if (distance < minDistance)
                    {
                        minDistance = distance;
                        closestWord = correctWord;
                    }
                }

                Message(minDistance, closestWord, word, index, ref index1, correctWords);
                if (index1 != 0)
                {
                    return;
                }
            }

            static void Message(int minDistance, string closestWord, string word, int index, ref int index1, string[] correctWords)
            {
                if (minDistance >= doi)
                {
                    // Print the misspelled word followed by "no suggestions"
                    Console.WriteLine(word + ": (no suggestion)");
                }
                else if (minDistance < doi && closestWord != word || minDistance >= doi2)
                {
                    // Find all correct words that have the same minimum distance
                    List<string> suggestions = new List<string>();
                    foreach (string correctWord in correctWords)
                    {
                        int distance = GetLevenshteinDistance(word, correctWord);
                        if (distance == minDistance)
                        {
                            suggestions.Add(correctWord);
                        }
                    }

                    // Print the misspelled word followed by the suggestions
                    Console.Write(word + ": ");
                    Console.WriteLine(string.Join(" ", suggestions));
                }
                else if (minDistance == 0 && index > 1)
                {
                    Console.WriteLine("Text corect!");
                    index1++;
                }
            }

            static int Min(int value1, int value2, int value3)
            {
                return Math.Min(Math.Min(value1, value2), value3);
            }

            static int GetLevenshteinDistance(string word1, string word2)
            {
                int[,] distance = new int[word1.Length + 1, word2.Length + 1];

                InitializeDistanceMatrix(distance, word1, word2);
                CalculateLevenshteinDistance(distance, word1, word2);

                return distance[word1.Length, word2.Length];
            }

            static void InitializeDistanceMatrix(int[,] distance, string word1, string word2)
            {
                for (int i = 0; i <= word1.Length; i++)
                {
                    for (int j = 0; j <= word2.Length; j++)
                    {
                        if (i == 0)
                        {
                            distance[i, j] = j;
                        }
                        else if (j == 0)
                        {
                            distance[i, j] = i;
                        }
                    }
                }
            }

            static void CalculateLevenshteinDistance(int[,] distance, string word1, string word2)
            {
                for (int i = 0; i <= word1.Length; i++)
                {
                    for (int j = 0; j <= word2.Length; j++)
                    {
                        CLD(i, j, distance, word1, word2);
                    }
                }
            }

            static void CLD(int i, int j, int[,] distance, string word1, string word2)
            {
                const int v = 2;
                if (i <= 0 || j <= 0)
                {
                    return;
                }

                distance[i, j] = Min(
                    distance[i - 1, j] + 1,
                    distance[i, j - 1] + 1,
                    distance[i - 1, j - 1] + (word1[i - 1] == word2[j - 1] ? 0 : 1));

                // Check if swapping the characters at positions i and j results in a new minimum distance
                if (i <= 1 || j <= 1 || word1[i - 1] != word2[j - v] || word1[i - v] != word2[j - 1])
                {
                    return;
                }

                distance[i, j] = Math.Min(distance[i, j], distance[i - v, j - v] + 1);
            }

            Console.ReadLine();
        }
    }
}

</code>```

Body:
I have to implement a simple spell checker. Basically I have to user input an incorrect sentence or a word, then a number N, and then N correct words each on new line. The program has to output "incorrect word: suggestion". If there is no suggestions available it should output "incorrect word: no suggestions" and if all the words from sentence are correct it should display "Correct text!". The typos can be:

Misspeled word.

Swapped letters.

Extra letter.

Missing letter.

To do this I implemented Levensthein minumim distance algorithm, which calculates the minimum number of modifications that a string has to take to be transformed into another string. All the test cases are fine but I want to reduce the cyclomatic complexity of the main method from 27 to below 26. Any suggestion would be helpful. For the example:

Thsi is an texzt fr tet
5
This
an
text
for
test

It displays:
Thsi: This
an: no suggestions
texzt: text
fr: for
tet: text test

using System;
using System.Collections.Generic;

namespace MisspelledWords
{
    class Program
    {
        static void Main(string[] args)
        {
            string sentence = Console.ReadLine();
            sentence = sentence.ToLower();
            int numWords = int.Parse(Console.ReadLine());
            const int doi = 2;
            const int doi2 = 3;
            int index = 0;
            int index1 = 0;
            string[] correctWords = new string[numWords];
            for (int i = 0; i < numWords; i++)
            {
                correctWords[i] = Console.ReadLine();
            }

            foreach (string word in sentence.Split(' '))
            {
                index++;
                int minDistance = int.MaxValue;
                string closestWord = "";
                foreach (string correctWord in correctWords)
                {
                    int distance = GetLevenshteinDistance(word, correctWord);
                    if (distance < minDistance)
                    {
                        minDistance = distance;
                        closestWord = correctWord;
                    }
                }

                Message(minDistance, closestWord, word, index, ref index1, correctWords);
                if (index1 != 0)
                {
                    return;
                }
            }

            static void Message(int minDistance, string closestWord, string word, int index, ref int index1, string[] correctWords)
            {
                if (minDistance >= doi)
                {
                    // Print the misspelled word followed by "no suggestions"
                    Console.WriteLine(word + ": (no suggestion)");
                }
                else if (minDistance < doi && closestWord != word || minDistance >= doi2)
                {
                    // Find all correct words that have the same minimum distance
                    List<string> suggestions = new List<string>();
                    foreach (string correctWord in correctWords)
                    {
                        int distance = GetLevenshteinDistance(word, correctWord);
                        if (distance == minDistance)
                        {
                            suggestions.Add(correctWord);
                        }
                    }

                    // Print the misspelled word followed by the suggestions
                    Console.Write(word + ": ");
                    Console.WriteLine(string.Join(" ", suggestions));
                }
                else if (minDistance == 0 && index > 1)
                {
                    Console.WriteLine("Text corect!");
                    index1++;
                }
            }

            static int Min(int value1, int value2, int value3)
            {
                return Math.Min(Math.Min(value1, value2), value3);
            }

            static int GetLevenshteinDistance(string word1, string word2)
            {
                int[,] distance = new int[word1.Length + 1, word2.Length + 1];

                InitializeDistanceMatrix(distance, word1, word2);
                CalculateLevenshteinDistance(distance, word1, word2);

                return distance[word1.Length, word2.Length];
            }

            static void InitializeDistanceMatrix(int[,] distance, string word1, string word2)
            {
                for (int i = 0; i <= word1.Length; i++)
                {
                    for (int j = 0; j <= word2.Length; j++)
                    {
                        if (i == 0)
                        {
                            distance[i, j] = j;
                        }
                        else if (j == 0)
                        {
                            distance[i, j] = i;
                        }
                    }
                }
            }

            static void CalculateLevenshteinDistance(int[,] distance, string word1, string word2)
            {
                for (int i = 0; i <= word1.Length; i++)
                {
                    for (int j = 0; j <= word2.Length; j++)
                    {
                        CLD(i, j, distance, word1, word2);
                    }
                }
            }

            static void CLD(int i, int j, int[,] distance, string word1, string word2)
            {
                const int v = 2;
                if (i <= 0 || j <= 0)
                {
                    return;
                }

                distance[i, j] = Min(
                    distance[i - 1, j] + 1,
                    distance[i, j - 1] + 1,
                    distance[i - 1, j - 1] + (word1[i - 1] == word2[j - 1] ? 0 : 1));

                // Check if swapping the characters at positions i and j results in a new minimum distance
                if (i <= 1 || j <= 1 || word1[i - 1] != word2[j - v] || word1[i - v] != word2[j - 1])
                {
                    return;
                }

                distance[i, j] = Math.Min(distance[i, j], distance[i - v, j - v] + 1);
            }

            Console.ReadLine();
        }
    }
}


问:
How can I find and fit enough string in a container in flutter
I have a Container with a fixed size and I want to put as much as text possible inside of it, without needing to change container or text size (I receive a long text from an API and I want to make a substring(0,n), with n as big as possible to be able to be shown in my container)

I tried Justifying the text, but it doesn't help with the amount of text I should cut from my main string.


问:
confusionMatrix(Y_test, Y_pred, mode="everything") error: 'the data cannot have more levels than the reference'
I have one error when I run the command confusionMatrix(Y_test, Y_pred, mode="everything"):

confusionMatrix(Y_test, Y_pred, mode="everything")
Error in confusionMatrix.default(Y_test, Y_pred, mode = "everything") :
the data cannot have more levels than the reference

Here are the commands that I am using:

```<code>dat<-read.csv("C:/Salaries.csv")
dat$rank<-as.factor(dat$rank)
dat$discipline<-as.factor(dat$discipline)
dat$sex<-as.factor(dat$sex)
datOHE <- model.matrix(sex~.-1, dat)
train<-datOHE[1:317,]
test<-datOHE[318:nrow(datOHE),]
table(dat[1:317,]$sex)
table(dat[318:nrow(dat),]$sex)
X_train <- data.matrix(train)
Y_train <- data.matrix(dat[1:317,]$salary)
X_test <- data.matrix(test)
Y_test <- data.matrix(dat[318:nrow(dat), ]$salary)
set.seed(42)
cv.ridge <- cv.glmnet(X_train, Y_train, family='gaussian', alpha=0, type.measure='mse')
plot(cv.ridge)
Y_pred <- as.numeric(predict.glmnet(cv.ridge$glmnet.fit, newx=X_test, s=cv.ridge$lambda.min)>
.5)
Y_pred <- as.factor(Y_pred)
Y_test <- as.factor(Y_test)
confusionMatrix(Y_test, Y_pred, mode="everything")
</code>```

Body:
I have one error when I run the command confusionMatrix(Y_test, Y_pred, mode="everything"):

confusionMatrix(Y_test, Y_pred, mode="everything")
Error in confusionMatrix.default(Y_test, Y_pred, mode = "everything") :
the data cannot have more levels than the reference

Here are the commands that I am using:

dat<-read.csv("C:/Salaries.csv")
dat$rank<-as.factor(dat$rank)
dat$discipline<-as.factor(dat$discipline)
dat$sex<-as.factor(dat$sex)
datOHE <- model.matrix(sex~.-1, dat)
train<-datOHE[1:317,]
test<-datOHE[318:nrow(datOHE),]
table(dat[1:317,]$sex)
table(dat[318:nrow(dat),]$sex)
X_train <- data.matrix(train)
Y_train <- data.matrix(dat[1:317,]$salary)
X_test <- data.matrix(test)
Y_test <- data.matrix(dat[318:nrow(dat), ]$salary)
set.seed(42)
cv.ridge <- cv.glmnet(X_train, Y_train, family='gaussian', alpha=0, type.measure='mse')
plot(cv.ridge)
Y_pred <- as.numeric(predict.glmnet(cv.ridge$glmnet.fit, newx=X_test, s=cv.ridge$lambda.min)>
.5)
Y_pred <- as.factor(Y_pred)
Y_test <- as.factor(Y_test)
confusionMatrix(Y_test, Y_pred, mode="everything")


问:
Delete Cookies on Blazor Server
Can you show me how to remove the password that Google Chrome has saved?

I have designed a login form.

There are 2 Textboxes (account and password).

I see Google Chrome has saved the password and account for the next login.

→ Now I want to delete it when I log out.

I am new to Blazor Server, so can you guide me in detail how to do it.

I looked at this Link, but I don't know how to apply it.
delete-cookie-by-name

Thank you.

Title: Delete Cookies on Blazor Server


问:
How to Get data from a window to another one with Angular and Subject?
I would like to make a little quizz game with 2 differents views.
One is for the player, answering questions by gambling points on a web server (nodejs).
The other one is for a streamer, observing the game.

I would like to get data from a first browser and display them on another one in my Angular code. Player and Observer are not in the same place. I can't use cookies or local storage so I'm trying to do that via a Subject.

I created a service

```<code>import { Injectable } from '@angular/core';
import { Subject } from 'rxjs';

@Injectable({
  providedIn: 'root'
})
export class SharedService {
    private dataSubject = new Subject<any>();

    sendData(data: any) {
      this.dataSubject.next(data);
    }

    clearData() {
      this.dataSubject.next();
    }

    getData() {
      return this.dataSubject.asObservable();
    }

}

</code>```

I made 2 components, one for each window.

In the first component, I have a button to send data

```<code>import { Component, OnInit } from '@angular/core';
import { SharedService } from '../shared-service.service';

@Component({
  selector: 'app-page1',
  templateUrl: '<button (click)="click()">Send data</button>',
  styleUrls: ['./page1.component.css']
})
export class Page1Component implements OnInit{

  constructor(private sharedService: SharedService) { }

  ngOnInit(): void {
    this.sharedService.getData().subscribe((data) => {
      console.log(data)
    });
  }

  click(){
    this.sharedService.sendData('test');
  }
}
</code>```

In the second document, I would like to get the 'test' string from the first window to the console

```<code>import { Component, OnInit } from '@angular/core';
import { SharedService } from '../shared-service.service';

@Component({
  selector: 'app-page2',
  templateUrl: './page2.component.html',
  styleUrls: ['./page2.component.css']
})
export class Page2Component implements OnInit{

  constructor(private sharedService: SharedService) { }

  ngOnInit() {

    this.sharedService.getData().subscribe((data) => {
      console.log(data)
    });
  }
}

</code>```

I'm new with Angular. Is someone can give me some advice ? Is this the good way to do or should I do something else ?

Body:
I would like to make a little quizz game with 2 differents views.
One is for the player, answering questions by gambling points on a web server (nodejs).
The other one is for a streamer, observing the game.

I would like to get data from a first browser and display them on another one in my Angular code. Player and Observer are not in the same place. I can't use cookies or local storage so I'm trying to do that via a Subject.

I created a service

import { Injectable } from '@angular/core';
import { Subject } from 'rxjs';

@Injectable({
  providedIn: 'root'
})
export class SharedService {
    private dataSubject = new Subject<any>();

    sendData(data: any) {
      this.dataSubject.next(data);
    }

    clearData() {
      this.dataSubject.next();
    }

    getData() {
      return this.dataSubject.asObservable();
    }

}

I made 2 components, one for each window.

In the first component, I have a button to send data

import { Component, OnInit } from '@angular/core';
import { SharedService } from '../shared-service.service';

@Component({
  selector: 'app-page1',
  templateUrl: '<button (click)="click()">Send data</button>',
  styleUrls: ['./page1.component.css']
})
export class Page1Component implements OnInit{

  constructor(private sharedService: SharedService) { }

  ngOnInit(): void {
    this.sharedService.getData().subscribe((data) => {
      console.log(data)
    });
  }

  click(){
    this.sharedService.sendData('test');
  }
}

In the second document, I would like to get the 'test' string from the first window to the console

import { Component, OnInit } from '@angular/core';
import { SharedService } from '../shared-service.service';

@Component({
  selector: 'app-page2',
  templateUrl: './page2.component.html',
  styleUrls: ['./page2.component.css']
})
export class Page2Component implements OnInit{

  constructor(private sharedService: SharedService) { }

  ngOnInit() {

    this.sharedService.getData().subscribe((data) => {
      console.log(data)
    });
  }
}

I'm new with Angular. Is someone can give me some advice ? Is this the good way to do or should I do something else ?


问:
How do I download a YouTube playlist with over 100 videos?
Pytube is able to generate a list of up to 100 links to download.  How do I download a YouTube playlist with up to 400 videos?

I am using github code by Mohit23x https://github.com/mohit23x/youtube-playlist-downloader/blob/master/ytdown.py


问:
How to configure redis asynchronously using lettuce library
I want to implement Redis asynchronously using the lettuce-core library and also implement the connection pool with desired timeout and pool size.</p>


问:
Job Scheduler Quartz not working on the Server
In ASP.NET MVC project, I am using Quartz library to run some Scheduler Job, it working right when running on the development environment

But when hosting on the server, it not works

The Quartz version is 3.0.7

I tried to add this to Web.config but not works, in spite of it works right without this add to web.config in development environment

```<code><configSections>
    <section name="quartz" type="System.Configuration.NameValueSectionHandler, System, Version=3.0.7000.0,Culture=neutral, PublicKeyToken=b77a5c561934e089" />
  </configSections>

  <!-- See http://quartz-scheduler.org/documentation/quartz-2.x/configuration/ for additional setting details-->
  <quartz>
    <add key="quartz.scheduler.instanceName" value="MyInstance" />
    <add key="quartz.threadPool.type" value="Quartz.Simpl.SimpleThreadPool, Quartz" />
    <add key="quartz.threadPool.threadCount" value="5" />
    <add key="quartz.threadPool.threadPriority" value="Normal" />
    <add key="quartz.plugin.xml.type" value="Quartz.Plugin.Xml.XMLSchedulingDataProcessorPlugin, Quartz" />
    <add key="quartz.plugin.xml.fileNames" value="~/quartzJobsAndTriggers.xml" />
  </quartz>
</code>```

Body:
In ASP.NET MVC project, I am using Quartz library to run some Scheduler Job, it working right when running on the development environment

But when hosting on the server, it not works

The Quartz version is 3.0.7

I tried to add this to Web.config but not works, in spite of it works right without this add to web.config in development environment

<configSections>

  </configSections>

  <quartz>
    <add key="quartz.scheduler.instanceName" value="MyInstance" />
    <add key="quartz.threadPool.type" value="Quartz.Simpl.SimpleThreadPool, Quartz" />
    <add key="quartz.threadPool.threadCount" value="5" />
    <add key="quartz.threadPool.threadPriority" value="Normal" />
    <add key="quartz.plugin.xml.type" value="Quartz.Plugin.Xml.XMLSchedulingDataProcessorPlugin, Quartz" />
    <add key="quartz.plugin.xml.fileNames" value="~/quartzJobsAndTriggers.xml" />
  </quartz>


问:
Are there any embeddable socks proxy servers that tunnels traffic through a remote host via ssh?
ssh -D 9191 ronald@ssh.somehost.com will create a socks proxy locally that will tunnel all traffic through the remote host. Is it possible to build this in to an application C++ or C and make it possible for this application direct all its traffic through the tunnel?

Short question:
Are there any embeddable socks proxy servers that tunnels traffic through a remote host via ssh? just like ssh -D xxxx ...

ContentLicense: CC BY-SA 3.0


问:
one or more threads of w3wp.exe are waiting to finish network I/O
I'm currently experiencing some hangs on production environmen of our web application server and after some investigation I'm not seeing too much request queued up in the worker process of the Application Pool just normall one may be 10 or 15 , the state of most of this request is ExexuteRequestHandler , when i monitor w3wp.exe in Resource monitor and right click it and choose Analyze wait chain , i found i got the atatched error message "one or more threads of w3wp.exe are waiting to finish network I/O"

enter image description here

and in this point the system become very slow and i have to end process of the hanging w3pw.exe to make it normal again, but this issue happen like 4 times daily.

any help please where to check

I followed the instrcutions in this issue but withour any resulte

How prevent CPU usage 100% because of worker process in iis


问:
I'm trying to do that but it allway says that module ''sp_recognition'' has no attribute 'Recognizer'. What should i do?
```<code>import sp_recog

robot_ear = sp_recog.Recognizer()
with sp_recog.Microphone() as mic:
    print("Robot: I'm Listening")
    audio = robot_ear.listen(mic)

try:
    you = robot_ear.recognize_google(audio)
except:
    you = ""

print("You: " + you)
</code>```

module ''sp_recognition'' has no attribute 'Recognizer'. What should i do?

Body:
import sp_recog

robot_ear = sp_recog.Recognizer()
with sp_recog.Microphone() as mic:
    print("Robot: I'm Listening")
    audio = robot_ear.listen(mic)

try:
    you = robot_ear.recognize_google(audio)
except:
    you = ""

print("You: " + you)

module ''sp_recognition'' has no attribute 'Recognizer'. What should i do?


问:
Iframe - add the same content hidden but searchable
I have a website with a lot of "guides" explaining processes. The guides are designed in a graphical way with many icons and illustrations. They are embedded (from canva) and therefore come as an iframe. The problem is that the content of that iframe is not searchable on my website. So I thought of adding the same content (text), that is written in those guides, somehow to the page itself, but hidden. I know that hidden content is problematic, on the other hand I want the content to be searchable - does anybody have an idea how to do that best (without violating Google guidelines)?
Here an example of a page with such a guide in an iframe: https://shivat-zion.com/k2100-opening-bank-account/

Most of the ways of hiding content are bad for SEO and may even end in a google penalty, which of course I want to avoid. I certainly don't have the intention of cloaking, since the text I want to put is exclusively what already is visible to the visitor in the iframe.


问:
Play Video with Headers in Exoplayer Android
I have a video with some headers files. I want to play that video in Exoplayer. I tried, But some of the methods are deprecated or some do not work.

Video Path: https://{{account-info}}.r2.cloudflarestorage.com/test/test-video.mp4

```<code>String url = "https://{{account-info}}.r2.cloudflarestorage.com/test/test-video.mp4";
simpleExoPlayer = new ExoPlayer.Builder(this).setMediaSourceFactory(new DefaultMediaSourceFactory((headers() /* header method*/ ))).setTrackSelector(trackSelector).setLoadControl(loadControl).build();
        mediaItem = MediaItem.fromUri(url);
        simpleExoPlayer.addMediaItem(mediaItem);
        simpleExoPlayer.prepare();
        simpleExoPlayer.play();

//headers method
private DataSource.Factory headers() {
        Map<String, String> headersMap = new HashMap<>();
        headersMap.put("Authorization", "auth");
        headersMap.put("X-Amz-Content-Sha256", "Content");
        headersMap.put("X-Amz-Date", "20221217T154926Z");
        headersMap.put("Content-Type", "application/json");
        return new DefaultHttpDataSource.Factory().setDefaultRequestProperties(headersMap);
    }

</code>```

Above code thorows an error that is Source error

Error log:

```<code>E/ExoPlayerImplInternal: Playback error
      com.google.android.exoplayer2.ExoPlaybackException: Source error
        at com.google.android.exoplayer2.ExoPlayerImplInternal.handleIoException(ExoPlayerImplInternal.java:641)
        at com.google.android.exoplayer2.ExoPlayerImplInternal.handleMessage(ExoPlayerImplInternal.java:613)
        at android.os.Handler.dispatchMessage(Handler.java:103)
        at android.os.Looper.loop(Looper.java:214)
        at android.os.HandlerThread.run(HandlerThread.java:67)
     Caused by: com.google.android.exoplayer2.upstream.HttpDataSource$InvalidResponseCodeException: Response code: 403
        at com.google.android.exoplayer2.upstream.DefaultHttpDataSource.open(DefaultHttpDataSource.java:396)
        at com.google.android.exoplayer2.upstream.StatsDataSource.open(StatsDataSource.java:84)
        at com.google.android.exoplayer2.source.ProgressiveMediaPeriod$ExtractingLoadable.load(ProgressiveMediaPeriod.java:1009)
        at com.google.android.exoplayer2.upstream.Loader$LoadTask.run(Loader.java:412)
        at java.util.concurrent.ThreadPoolExecutor.runWorker(ThreadPoolExecutor.java:1167)
        at java.util.concurrent.ThreadPoolExecutor$Worker.run(ThreadPoolExecutor.java:641)
        at java.lang.Thread.run(Thread.java:919)
</code>```

Any other method to request a Video with Headers and play in Exoplayer?

Thank you :)

Body:
I have a video with some headers files. I want to play that video in Exoplayer. I tried, But some of the methods are deprecated or some do not work.

Video Path: https://{{account-info}}.r2.cloudflarestorage.com/test/test-video.mp4

String url = "https://{{account-info}}.r2.cloudflarestorage.com/test/test-video.mp4";
simpleExoPlayer = new ExoPlayer.Builder(this).setMediaSourceFactory(new DefaultMediaSourceFactory((headers() /* header method*/ ))).setTrackSelector(trackSelector).setLoadControl(loadControl).build();
        mediaItem = MediaItem.fromUri(url);
        simpleExoPlayer.addMediaItem(mediaItem);
        simpleExoPlayer.prepare();
        simpleExoPlayer.play();

//headers method
private DataSource.Factory headers() {
        Map<String, String> headersMap = new HashMap<>();
        headersMap.put("Authorization", "auth");
        headersMap.put("X-Amz-Content-Sha256", "Content");
        headersMap.put("X-Amz-Date", "20221217T154926Z");
        headersMap.put("Content-Type", "application/json");
        return new DefaultHttpDataSource.Factory().setDefaultRequestProperties(headersMap);
    }

Above code thorows an error that is Source error

Error log:

E/ExoPlayerImplInternal: Playback error
      com.google.android.exoplayer2.ExoPlaybackException: Source error
        at com.google.android.exoplayer2.ExoPlayerImplInternal.handleIoException(ExoPlayerImplInternal.java:641)
        at com.google.android.exoplayer2.ExoPlayerImplInternal.handleMessage(ExoPlayerImplInternal.java:613)
        at android.os.Handler.dispatchMessage(Handler.java:103)
        at android.os.Looper.loop(Looper.java:214)
        at android.os.HandlerThread.run(HandlerThread.java:67)
     Caused by: com.google.android.exoplayer2.upstream.HttpDataSource$InvalidResponseCodeException: Response code: 403
        at com.google.android.exoplayer2.upstream.DefaultHttpDataSource.open(DefaultHttpDataSource.java:396)
        at com.google.android.exoplayer2.upstream.StatsDataSource.open(StatsDataSource.java:84)
        at com.google.android.exoplayer2.source.ProgressiveMediaPeriod$ExtractingLoadable.load(ProgressiveMediaPeriod.java:1009)
        at com.google.android.exoplayer2.upstream.Loader$LoadTask.run(Loader.java:412)
        at java.util.concurrent.ThreadPoolExecutor.runWorker(ThreadPoolExecutor.java:1167)
        at java.util.concurrent.ThreadPoolExecutor$Worker.run(ThreadPoolExecutor.java:641)
        at java.lang.Thread.run(Thread.java:919)

Any other method to request a Video with Headers and play in Exoplayer?

Thank you :)


Title: Anyone has idea which library is needed to fix this error?

Body:
enter image description here

from ui_interface import *
########################################################################

########################################################################
# IMPORT Custom widgets
from Custom_Widgets.Widgets import *
# INITIALIZE APP SETTINGS
settings = QSettings()
########################################################################

########################################################################
## MAIN WINDOW CLASS
########################################################################
class MainWindow(QMainWindow):
    def __init__(self, parent=None):
        QMainWindow.__init__(self)
        self.ui = Ui_MainWindow()

I'm having pyside pyqt and all the other libraries downloaded it to run ...

But still no idea what to do with it


问:
Environment Variable set in .bashrc file visible in terminal but not through Python program
I have set the environment variable for one of my API keys in Ubuntu. For that I used the way to set it through using .bashrc file and export statement. Till now, everything is working fine and when I type env command in terminal, it shows the environment variable from which I may conclude that the variable has been set successfully.

But when I try to access it in the Python by OS module, I am not able to see that environment variable.

Code:

```<code>import os

    print("Environment Variable Keys: ")
    print("---------------------------")
    env_keys = list(os.environ.keys())
    env_keys.sort()
    for key in env_keys:
        print(key)
</code>```

For simplicity,I have converted keys into list and have sorted them.

Why I am not able to see the required variable? ( Other env variables are being shown by python but not the one set by me)

Body:
I have set the environment variable for one of my API keys in Ubuntu. For that I used the way to set it through using .bashrc file and export statement. Till now, everything is working fine and when I type env command in terminal, it shows the environment variable from which I may conclude that the variable has been set successfully.

But when I try to access it in the Python by OS module, I am not able to see that environment variable.

Code:

import os

    print("Environment Variable Keys: ")
    print("---------------------------")
    env_keys = list(os.environ.keys())
    env_keys.sort()
    for key in env_keys:
        print(key)

For simplicity,I have converted keys into list and have sorted them.

Why I am not able to see the required variable? ( Other env variables are being shown by python but not the one set by me)


问:
Raspberry Pi self hosted wordpress
I am setting up my old Raspberry Pi 3 as a home server. I want to just tinker around and see what I can use it for.

Right now I am trying to self host a wordpress site in my network, but cant seem to get it running.

I always get this error message in portainer, when I am trying to deploy the stack:

failed to deploy a stack: db Pulling no matching manifest for linux/arm/v7 in the manifest list entries

My Code is:

```<code>version: '2'

services:
   db:
     image: mysql:5.7
     volumes:
       - db_data:/var/lib/mysql
     restart: always
     environment:
       MYSQL_ROOT_PASSWORD: password
       MYSQL_DATABASE: wordpress
       MYSQL_USER: wordpress
       MYSQL_PASSWORD: wordpress

   wordpress:
     image: wordpress:latest
     ports:
       - 80
     restart: always
     environment:
       WORDPRESS_DB_HOST: db:3306
       WORDPRESS_DB_USER: wordpress
       WORDPRESS_DB_PASSWORD: wordpress

volumes:
    db_data:
</code>```

Is this error popping up because the mysql image is not supported on arm32?

is there an alernative way like replacing mysql with another service like mariadb or something?

I am no it guy so apologies for my incompetencies.

best regards

Title: Raspberry Pi self hosted wordpress

Body:
I am setting up my old Raspberry Pi 3 as a home server. I want to just tinker around and see what I can use it for.

Right now I am trying to self host a wordpress site in my network, but cant seem to get it running.

I always get this error message in portainer, when I am trying to deploy the stack:

failed to deploy a stack: db Pulling no matching manifest for linux/arm/v7 in the manifest list entries

My Code is:

version: '2'

services:
   db:
     image: mysql:5.7
     volumes:
       - db_data:/var/lib/mysql
     restart: always
     environment:
       MYSQL_ROOT_PASSWORD: password
       MYSQL_DATABASE: wordpress
       MYSQL_USER: wordpress
       MYSQL_PASSWORD: wordpress

   wordpress:
     image: wordpress:latest
     ports:
       - 80
     restart: always
     environment:
       WORDPRESS_DB_HOST: db:3306
       WORDPRESS_DB_USER: wordpress
       WORDPRESS_DB_PASSWORD: wordpress

volumes:
    db_data:

Is this error popping up because the mysql image is not supported on arm32?

is there an alernative way like replacing mysql with another service like mariadb or something?

I am no it guy so apologies for my incompetencies.

best regards


问:
cannot use pyswip on windows
```<code>try:
    from ctypes import *
except ImportError:
    print("A required module: 'ctypes' not found.", file=sys.stderr)
    sys.exit(1)

try:
    if sys.platform[:3] == "win":
        # we're on windows
        _lib = CDLL("libpl.dll")
    elif sys.platform[:3] == "dar":
       # we're on Mac OS
       _lib = CDLL("libpl.dylib")
    else:
        # UNIX-like
        try:
            _lib = CDLL("libpl.so")
        except IndexError:
            # let's try the cwd
            _lib = CDLL("./libpl.so")

except OSError:
    print("libpl (shared) not found. Possible reasons:", file=sys.stderr)
    print("1) SWI-Prolog not installed as a shared library. Install SWI-Prolog (5.6.34 works just fine)", file=sys.stderr)
    sys.exit(1)
</code>```

When I try to run my file it always have OSError pop up even I have swi prolog install.

Below is the bulitin OsError Function

```<code>class OSError(Exception):
    errno: int
    strerror: str
    # filename, filename2 are actually str | bytes | None
    filename: Any
    filename2: Any
    if sys.platform == "win32":
        winerror: int

EnvironmentError = OSError
IOError = OSError
if sys.platform == "win32":
    WindowsError = OSError
</code>```

the error message is this
libpl (shared) not found. Possible reasons:

SWI-Prolog not installed as a shared library. Install SWI-Prolog (5.6.34 works just fine)

I tried to delete the except error statement but it doesn't work. I expected to have no error since I'm on windows and swiprolog is already installed.

Title: cannot use pyswip on windows

Body:
try:
    from ctypes import *
except ImportError:
    print("A required module: 'ctypes' not found.", file=sys.stderr)
    sys.exit(1)

try:
    if sys.platform[:3] == "win":
        # we're on windows
        _lib = CDLL("libpl.dll")
    elif sys.platform[:3] == "dar":
       # we're on Mac OS
       _lib = CDLL("libpl.dylib")
    else:
        # UNIX-like
        try:
            _lib = CDLL("libpl.so")
        except IndexError:
            # let's try the cwd
            _lib = CDLL("./libpl.so")

except OSError:
    print("libpl (shared) not found. Possible reasons:", file=sys.stderr)
    print("1) SWI-Prolog not installed as a shared library. Install SWI-Prolog (5.6.34 works just fine)", file=sys.stderr)
    sys.exit(1)

When I try to run my file it always have OSError pop up even I have swi prolog install.

Below is the bulitin OsError Function

class OSError(Exception):
    errno: int
    strerror: str
    # filename, filename2 are actually str | bytes | None
    filename: Any
    filename2: Any
    if sys.platform == "win32":
        winerror: int

EnvironmentError = OSError
IOError = OSError
if sys.platform == "win32":
    WindowsError = OSError

the error message is this
libpl (shared) not found. Possible reasons:

SWI-Prolog not installed as a shared library. Install SWI-Prolog (5.6.34 works just fine)

I tried to delete the except error statement but it doesn't work. I expected to have no error since I'm on windows and swiprolog is already installed.


问:
R Studio shows error "Error in lm.fit(x, y, offset = offset, singular.ok = singular.ok, ...) : NA/NaN/Inf in 'x'"
I have a dataset that looks like that:

click here to view dataset

I am running a multiple regression equation on my data where the column year3 is my Y and I have 2 Xs which are year1 and year2. When I run the regression equation, fit it, and print the summary; it prints perfectly and shows me all the data I need.

However, I am now trying to run the multiple regression equation but using LOG on the same dataset, and I get the following error:

Error in lm.fit(x, y, offset = offset, singular.ok = singular.ok, ...) :    NA/NaN/Inf in 'x'"

I have tried everything, I can see that my dataset does not have any NULL/NA/INF values, I cant get it to work.

Here is my code below:

```<code>
# LOADING THE DATASET
library(readxl)

# Read Excel file into a data frame
data <- read_excel("/Users/yassindinana/Desktop/assignment_2_data.xlsx", col_types = "numeric")

# View the data frame
head(data)

#Three Analyses:

#1)

# Load required library
library(stats)

#Estimate multiple regression model (this will show your F-test, P-Value, R-Squared, DF)
#The estimation is done on the third year (latest year) as the Y value as requested based on Year 1 and Year 2.
model <- lm(year3 ~ year1 + year2, data = data)
summary(model)

# Checking if there are any nulls in my dataframe
data <- na.omit(data)

# The line below confirms my dataset is of data type NUMERIC.
str(data)

# Running multiple regression model on the log of my y and x values. (THE ERROR IS HERE)
model1 <- lm(log(data$year3) ~ log(data$year1) + log(data$year2), data = data)
summary(model1)
</code>```

I am expecting to fit my multiple regressor function and fit it on the log values of my dataset using the following:

Estimate one of the following forms of multiple regression models:
log = (log1 , log2 .....,), log = (1, 2 .....,), y = (log1 , log2 .....,),

Body:
I have a dataset that looks like that:

click here to view dataset

I am running a multiple regression equation on my data where the column year3 is my Y and I have 2 Xs which are year1 and year2. When I run the regression equation, fit it, and print the summary; it prints perfectly and shows me all the data I need.

However, I am now trying to run the multiple regression equation but using LOG on the same dataset, and I get the following error:

Error in lm.fit(x, y, offset = offset, singular.ok = singular.ok, ...) :    NA/NaN/Inf in 'x'"

I have tried everything, I can see that my dataset does not have any NULL/NA/INF values, I cant get it to work.

Here is my code below:

# LOADING THE DATASET
library(readxl)

# Read Excel file into a data frame
data <- read_excel("/Users/yassindinana/Desktop/assignment_2_data.xlsx", col_types = "numeric")

# View the data frame
head(data)

#Three Analyses:

#1)

# Load required library
library(stats)

#Estimate multiple regression model (this will show your F-test, P-Value, R-Squared, DF)
#The estimation is done on the third year (latest year) as the Y value as requested based on Year 1 and Year 2.
model <- lm(year3 ~ year1 + year2, data = data)
summary(model)

# Checking if there are any nulls in my dataframe
data <- na.omit(data)

# The line below confirms my dataset is of data type NUMERIC.
str(data)

# Running multiple regression model on the log of my y and x values. (THE ERROR IS HERE)
model1 <- lm(log(data$year3) ~ log(data$year1) + log(data$year2), data = data)
summary(model1)

I am expecting to fit my multiple regressor function and fit it on the log values of my dataset using the following:

Estimate one of the following forms of multiple regression models:
log = (log1 , log2 .....,), log = (1, 2 .....,), y = (log1 , log2 .....,),


问:
How to split a dataframe into multiple dataframe in pandas dynamically based on the column count?
I am still a newbie in pandas. I have an excel file which contains more than 700 columns with 600 rows. I am trying to split it into multiple dataframes so I can insert it into sql table. The reason why I am trying to split is because I am getting an error saying The statement has been terminated. (3621); [42000] [Microsoft][ODBC Driver 17 for SQL Server][SQL Server]Cannot create a row of size 8349 which is greater than the allowable maximum row size of 8060. I want to split it by 250 columns per dataframe and also take the first row so I can join it in the sql.

Another reason why I cannot specify the dataframe range is because, different excel files might have different number of columns. Lets say the excel file contains 800 columns, but I set it as 700: 850, it gives me an error saying iloc giving 'IndexError: single positional indexer is out-of-bounds'.

If there is a way to do it dynamically by splitting it by 250 rows, it would be great. Below is my code which is working but I need to specify the range of index:

```<code> def sqlcol(dfparam):
     dtypedict = {}
     for i,j in zip(dfparam.columns, dfparam.dtypes):
        if "object" in str(j):
            dtypedict.update({i: sqla.types.NVARCHAR(length=255)})

        if "datetime" in str(j):
            dtypedict.update({i: sqla.types.DateTime()})

        if "float" in str(j):
           dtypedict.update({i: sqla.types.Float()})

        if "int" in str(j):
           dtypedict.update({i: sqla.types.BIGINT()})

        if "decimal" in str(j):
           dtypedict.update({i: sqla.types.DECIMAL()})

    return dtypedict

def import_varchar_to_hst03(db:str,tb_name:str,df):
    n= 1

    import pandas as pd
    import sqlalchemy as sqla
    import urllib
    import pyodbc
    t=sqlcol(df1)
    a=sqlcol(df2)
    c=sqlcol(df3)
    quoted = urllib.parse.quote_plus("DRIVER={ODBC Driver 17 for SQL Server};SERVER=localhost;DATABASE="+db+";Trusted_Connection=yes;")
engine = sqla.create_engine('mssql+pyodbc:///?odbc_connect={}'.format(quoted), fast_executemany = True)
    df1.to_sql(tb_name, schema='dbo', con = engine, index=False,dtype=t,if_exists='replace')
    df2.to_sql(tb_name + ( "A" * n), schema='dbo', con = engine, index=False,dtype=a,if_exists='replace')
    df3.to_sql(tb_name + ( "B" * n), schema='dbo', con = engine, index=False,dtype=c,if_exists='replace')

import pandas as pd
import numpy as np

Ex=pd.read_excel(r'C:\Users\sriram.ramasamy\Desktop\Testsriram.xlsx',sheet_name=None)

for sh,v in Ex.items():
    df=pd.DataFrame(v)
    df1 = df.iloc[:,:255]
    df2 = df.iloc[:,np.r_[0:1,256:500]]
    df3 = df.iloc[:,np.r_[0:1,501:700]]
    import_varchar_to_hst03('InsightMaster',sh,df)

print('data imported to database')
</code>```

Body:
I am still a newbie in pandas. I have an excel file which contains more than 700 columns with 600 rows. I am trying to split it into multiple dataframes so I can insert it into sql table. The reason why I am trying to split is because I am getting an error saying The statement has been terminated. (3621); [42000] [Microsoft][ODBC Driver 17 for SQL Server][SQL Server]Cannot create a row of size 8349 which is greater than the allowable maximum row size of 8060. I want to split it by 250 columns per dataframe and also take the first row so I can join it in the sql.

Another reason why I cannot specify the dataframe range is because, different excel files might have different number of columns. Lets say the excel file contains 800 columns, but I set it as 700: 850, it gives me an error saying iloc giving 'IndexError: single positional indexer is out-of-bounds'.

If there is a way to do it dynamically by splitting it by 250 rows, it would be great. Below is my code which is working but I need to specify the range of index:

 def sqlcol(dfparam):
     dtypedict = {}
     for i,j in zip(dfparam.columns, dfparam.dtypes):
        if "object" in str(j):
            dtypedict.update({i: sqla.types.NVARCHAR(length=255)})

        if "datetime" in str(j):
            dtypedict.update({i: sqla.types.DateTime()})

        if "float" in str(j):
           dtypedict.update({i: sqla.types.Float()})

        if "int" in str(j):
           dtypedict.update({i: sqla.types.BIGINT()})

        if "decimal" in str(j):
           dtypedict.update({i: sqla.types.DECIMAL()})

    return dtypedict

def import_varchar_to_hst03(db:str,tb_name:str,df):
    n= 1

    import pandas as pd
    import sqlalchemy as sqla
    import urllib
    import pyodbc
    t=sqlcol(df1)
    a=sqlcol(df2)
    c=sqlcol(df3)
    quoted = urllib.parse.quote_plus("DRIVER={ODBC Driver 17 for SQL Server};SERVER=localhost;DATABASE="+db+";Trusted_Connection=yes;")
engine = sqla.create_engine('mssql+pyodbc:///?odbc_connect={}'.format(quoted), fast_executemany = True)
    df1.to_sql(tb_name, schema='dbo', con = engine, index=False,dtype=t,if_exists='replace')
    df2.to_sql(tb_name + ( "A" * n), schema='dbo', con = engine, index=False,dtype=a,if_exists='replace')
    df3.to_sql(tb_name + ( "B" * n), schema='dbo', con = engine, index=False,dtype=c,if_exists='replace')

import pandas as pd
import numpy as np

Ex=pd.read_excel(r'C:\Users\sriram.ramasamy\Desktop\Testsriram.xlsx',sheet_name=None)

for sh,v in Ex.items():
    df=pd.DataFrame(v)
    df1 = df.iloc[:,:255]
    df2 = df.iloc[:,np.r_[0:1,256:500]]
    df3 = df.iloc[:,np.r_[0:1,501:700]]
    import_varchar_to_hst03('InsightMaster',sh,df)

print('data imported to database')


问:
How to implement activiti signal intermediate catch event
Need to design a process flow such that it will be paused in the middle until a external event/process completes and then resumes the flow.

I have chosen to use "Signal intermediate catch event"   with signal scope=processinstance
(let me know if this is not the right option)....

Ideally the expectation is
When the process arrives this stage it waits for external event to complete.

When the external event completes, I need to send signal to the process instance

SignalIntermediateCatchEvent --> should consume the signal and continue the process.

Can any share the example java implementations of signal sending and consuming code .

New to the bpmn signal event usage, trying to find examples.