text:
Q: Cannot fit requested classes in a single dex file, even for earlier commits which previously compiled fine So I've just hit the maximum method count limit for my android project, which fails to build with the following error message:

Error: null, Cannot fit requested classes in a single dex file (# methods: 117407 > 65536)

I understand what the message means, and how to resolve it (running proguard, enabling multidex etc). My problem is that I don't understand why I'm suddenly getting this message - I was doing was removing some old bits of code which were redundant, hit build, and now I get this message.
Question 1: How can it be possible that my method count (117407 according to the error message) is suddenly massively over the limit (65536), even though I did not add any library dependencies? I actually removed code, and suddenly I have like 50 thousand methods too many?
Now this is where it gets really weird: I wanted to analyse the APK to figure out what's causing the problem, but of course I can't build it. So instead of enabling multidex I decided to revert my code to yesterday (which definitely absolutely did build fine yesterday - I have the app on my phone to prove it!), but I still get this build error message. I don't understand how this is possible. I tried reverting to several days ago, same thing (cloning a new repo and checking out an earlier commit).
So, question 2: How am I getting this build error for the exact same code which just yesterday built fine without error?
The only thing I can think of is that a library that I am using as a dependency has suddenly increased in size - but I'm declaring specific versions of everything in my gradle build, for example:
// RxJava
implementation 'io.reactivex.rxjava2:rxandroid:2.1.0'
implementation 'io.reactivex.rxjava2:rxjava:2.2.4'

// Retrofit
implementation 'com.squareup.retrofit2:retrofit:2.5.0'
implementation 'com.squareup.retrofit2:converter-gson:2.5.0'

So, surely my dependencies should not have changed?
Any ideas what I can do to figure this out are greatly appreciated. I've tried cleaning my project, and invalidating caches/restart in android studio. I really don't want to enable multidex or have to run proguard on my debug build.
Here's the full build.gradle:
apply plugin: 'com.android.application'
apply plugin: 'kotlin-android'
apply plugin: 'kotlin-android-extensions'
apply plugin: 'kotlin-kapt'

android {
    compileSdkVersion 28
    defaultConfig {
    applicationId "XXXXXXXXX"
    minSdkVersion 19
    targetSdkVersion 28
    versionCode 1
    versionName "0.1"
    testInstrumentationRunner "android.support.test.runner.AndroidJUnitRunner"
    vectorDrawables.useSupportLibrary = true  // see https://developer.android.com/studio/write/vector-asset-studio#sloption
}
buildTypes {
    release {
        minifyEnabled false
        // Do code shrinking!
        proguardFiles getDefaultProguardFile('proguard-android.txt'), 'proguard-rules.pro'
    }
}
}

dependencies {
implementation fileTree(dir: 'libs', include: ['*.jar'])

// Core stuff
implementation "org.jetbrains.kotlin:kotlin-stdlib-jdk7:$kotlin_version"
implementation 'com.android.support:appcompat-v7:28.0.0'
implementation 'com.android.support:recyclerview-v7:28.0.0'
testImplementation 'junit:junit:4.12'
androidTestImplementation 'com.android.support.test:runner:1.0.2'
androidTestImplementation 'com.android.support.test.espresso:espresso-core:3.0.2'
implementation 'android.arch.lifecycle:extensions:1.1.1'
implementation 'com.android.support:design:28.0.0'
implementation 'com.android.support:support-vector-drawable:28.0.0'
implementation 'com.google.android.gms:play-services-wearable:16.0.1'

// Dagger
implementation 'com.google.dagger:dagger:2.21'
kapt 'com.google.dagger:dagger-compiler:2.21'
// Dagger for Android
implementation 'com.google.dagger:dagger-android:2.21'
implementation 'com.google.dagger:dagger-android-support:2.21' // if you use the support libraries
kapt 'com.google.dagger:dagger-android-processor:2.21'

// Constraint layout
implementation 'com.android.support.constraint:constraint-layout:1.1.3'

// Associated WearOS project
wearApp project(':wear')

// Common library project
implementation project(':common')

// These were added to resolve gradle error on the 'com.android.support:appcompat-v7:28.0.0' implementation:
// All com.android.support libraries must use the exact same version specification (mixing versions can lead to
// runtime crashes). Found versions 28.0.0, 26.1.0. Examples include com.android.support:animated-vector-drawable:28.0.0
// and com.android.support:support-media-compat:26.1.0
// This seems to be related to linking the wear project. If the wear project was not linked, the error went away.
implementation 'com.android.support:support-media-compat:28.0.0'
implementation 'com.android.support:support-v4:28.0.0'

// RxJava
implementation 'io.reactivex.rxjava2:rxandroid:2.1.0'
implementation 'io.reactivex.rxjava2:rxjava:2.2.4'

// Retrofit
implementation 'com.squareup.retrofit2:retrofit:2.5.0'
implementation 'com.squareup.retrofit2:converter-gson:2.5.0'
// Retrofit RxJava
implementation 'com.squareup.retrofit2:adapter-rxjava2:2.5.0'
// Retrofit logging:
implementation 'com.squareup.okhttp3:logging-interceptor:3.12.1'

// Room
def room_version = "1.1.1"
implementation "android.arch.persistence.room:runtime:$room_version"
implementation "android.arch.persistence.room:common:$room_version"
implementation "android.arch.persistence.room:rxjava2:$room_version"
kapt "android.arch.persistence.room:compiler:$room_version"

// For modern time handling (java.time requires API 26 or higher)
implementation 'com.jakewharton.threetenabp:threetenabp:1.1.1'

// Graphing
implementation 'com.github.PhilJay:MPAndroidChart:v3.1.0-alpha'

// Dropbox
implementation 'com.dropbox.core:dropbox-core-sdk:3.0.11'

// OpenCSV
implementation 'com.opencsv:opencsv:4.5'

}

EDIT
So after enabling multidex, there are some heavy dependencies showing up under the following TLDs when I analyse the APK using Android Studio (I'm not sure if I should be looking at defined or referenced method numbers?):

*

*com.dropbox: 26000 defined methods, 34000 referenced methods

*com.android (mainly support libraries): 18700 defined, 24600 referenced

*org.apache (commons, log etc): 15000 defined, 15700 referenced

These alone take me up to the limit. I still don't get why this is suddenly happening though :( Surely if I have not added any libraries, these numbers should not have changed?

A: After looking at your entire build gradle file, your issue definitely stems from your dependencies! Attempt to clean them up and remove as many as you can that you don't use. Chances are  you were very close to the limit and any of those dependencies may have been cached using older versions. You can attempt to remove the entire build folder (and clean your gradle cache) but I am fairly certain the issue will not go away.
If all of these dependencies are required unfortunately you will have to go the routes you mentioned, either multi-dex or minifying debug builds. Multi-dex should be ok and shouldn't cause any unforeseen issues while minifying will slow down your builds and potentially cause Android Studio to become unstable (especially instant run/apply changes!)
Good luck, one thing to take from this is to keep your dependencies clean and precise, only add when absolutely needed, and if all else fails, multi-dex is your friend.

A: None of the answers they gave you were exhaustive. The problem lies in the Multidex. You must add the library in the app gradle:
implementation 'com.android.support:multidex:1.0.3'

After, you should add in the defaultConfig of the app gradle:
multiDexEnabled true

A: Simple add this to your gradle (Module: app) >> multiDexEnabled true
android {
    defaultConfig {
        ...
        minSdkVersion 21
        targetSdkVersion 28
        multiDexEnabled true
    }
    ...
}

then Rebuild Project
in Menu click => Build>Rebuild Project.

A: From the Android docs:
"If your minSdkVersion is set to 21 or higher, multidex is enabled by default and you do not need the multidex support library."
As an alternative to manually enabling multidex, you could simply increase your minSdkVersion if possible.

A: I would recommend building the application with multidex, and then extracting the method ids from the multiple dex files from the new apk, and also extract the method ids from the old, single-dex apk and comparing the two lists.
roughly, something like:
baksmali list dex new.apk
baksmali list method new.apk/classes.dex > new.list
baksmali list method new.apk/classes2.dex >> new.list
sort new.list > new.sorted.list

baksmali list method old.apk > old.list
diff new.sorted.list old.list

Although, if you're using proguard, you may need to figure out some way to apply the reverse proguard name mangling before comparing the lists.

A: After reading your question I can only suggest try invalidate cache and restart after and force refresh your dependency using this .
./gradlew build --refresh-dependencies

A: As your problem, I had to delete the build folder and the *.iml files (Android Studio project files) y I had to recreate the project, then the build and then all worked fine again.

A: I encountered the same issue and the solution was to enable Instant Run under File -> Setting -> Build, Execution, Deployment -> Instant Run and that solved my problem. Hope it's helpful.

A: I tried this.
 hopes it helps, found it on some documentation
( forgot the url :( )
build.gradle app
dependencies {...
grdef multidex_version ='2.0.1'

implementation "androidx.multidex:multidex:$multidex_version"
}...

A: in bulid.gradle app
implementation 'com.android.support:multidex:2.0.1'

android {
    multiDexEnabled true

}

A: android > app > build.gradle

*

*android {

    defaultConfig {
        versionCode 1
        versionName "1.0"
      +  multiDexEnabled true
    }
}

*Add implementation 'com.android.support:multidex:1.0.3'
in dependencies block
dependencies {
 + implementation 'com.android.support:multidex:1.0.3'
}

A: Community wiki
Its easy just increase this minSdkVersion, targetSdkVersion :
Old:
defaultConfig { minSdkVersion 19 targetSdkVersion 28 versionCode flutterVersionCode.toInteger() versionName flutterVersionName }
New:
defaultConfig { minSdkVersion 21 targetSdkVersion 29 versionCode flutterVersionCode.toInteger() versionName flutterVersionName }
also this compileSdkVersion:
Old:
android { compileSdkVersion 28
New:
android { compileSdkVersion 29


text:
Q: How to get a client-side object reference to a RadButton which is inside an EditTemplate of a FormView I am trying to get a javascript reference to a RadButton object which is inside an EditTemplate. This is working fine with a RadTextBox but not with the RadButton. Looking at the generated code, I see that the ClientID of the RadButton instead of
ctl00_ContentPlaceHolder1_EmployerFormView_rdBtnLegal
it is
ctl00_ContentPlaceHolder1_EmployerFormView_rdBtnLegal_input. As a result the javascript code below:
var checkbox = document.getElementById('<%=EmployerFormView.FindControl("rdBtnLegal").ClientID%>');

returns an undefined object reference. The strange thing, that I do not understand is why <%=EmployerFormView.FindControl("rdBtnLegal").ClientID%> evaluates to ctl00_ContentPlaceHolder1_EmployerFormView_rdBtnLegal (without the _input) and the ClientID is with the _input
Thank you in advance

redpajama_set_name: RedPajamaStackExchange


text:
Q: WPF - Bound Control Not Updating When Property Changed? I've bound the Text property of a TextBox to a base object's property and it seems to work just fine.  Unfortunately, when I programatically change the value of the property, it doesn't seem to update on the GUI.
Here's the property:
public string SealedDate
{
    get
    {
        string result = string.Empty;

        if (_DACase.SealedDate != DateTime.MinValue)
        {
            result = Formatting.FormatDate(_DACase.SealedDate);
        }

        return result;
    }
    set
    {
        DateTime theDate = DateTime.MinValue;

        if (DateTime.TryParse(value, out theDate)
            && _DACase.SealedDate != theDate)
        {
            _DACase.SealedDate = theDate;
            base.OnChanged(); //fires event so I know the value of the object has changed
        }
    }
}

And the value of that property is being set when another property it being set:
public bool IsSealed
{
    get
    {
        return _DACase.SealedId > 0
            || _DACase.SealedDate != DateTime.MinValue;
    }
    set
    {
        if (value != (_DACase.SealedId > 0 || _DACase.SealedDate != DateTime.MinValue))
        {
            if (value)
            {
                this.SealedId = Authentication.CurrentUser.Id;
                this.SealedDate = Formatting.FormatDate(DateTime.Now);
            }
            else
            {
                this.SealedId = 0;
                this.SealedDate = DateTime.MinValue.ToString();
            }
            base.OnChanged();
        }
    }
}

And the XAML of the TextBox that isn't updating when I think it should:
<TextBox Name="txtSealedDate" Text="{Binding SealedDate}" Grid.Column="5" Grid.Row="3" IsReadOnly="True" />

A: Vlad's solution (in the comments) was correct.


text:
Q: Understanding equivalence testing. Why there are two hypothesis? I have to two groups and I would like to test that difference between means of these two groups is at least 0.02. I am using TOSTER R package. Here are details:
library(TOSTER)
TOSTtwo.raw(m1 =0.05, m2 = 0.07,
   sd1 =0.25, sd2 = 0.27, n1 = 10000, n2 = 11000,
   low_eqbound = - 0.02, high_eqbound = 0.02, alpha = 0.05)

Here is output:
TOST results:
t-value lower bound: -0.000000000000000967  p-value lower bound: 0.500
t-value upper bound: -11.15     p-value upper bound: 0.00000000000000000000000000004
degrees of freedom : 20990.93

Equivalence bounds (raw scores):
low eqbound: -0.02
high eqbound: 0.02

TOST confidence interval:
lower bound 90% CI: -0.026
upper bound 90% CI:  -0.014

NHST confidence interval:
lower bound 95% CI: -0.027
upper bound 95% CI:  -0.013

Equivalence Test Result:
The equivalence test was non-significant, t(20990.93) = -0.000000000000000967, p = 0.500, given equivalence bounds of -0.020 and 0.020 (on a raw scale) and an alpha of 0.05.

Null Hypothesis Test Result:
The null hypothesis test was significant, t(20990.93) = -5.573, p = 0.0000000253, given an alpha of 0.05.

Based on the equivalence test and the null-hypothesis test combined, we can conclude that the observed effect is statistically different from zero and statistically not equivalent to zero.

My first question is why there are two tests results TOST and NHST?
My second question. Would it be correct for me to conclude that since we fail to reject null hypothesis |m1-m2| >=0.02, then |m1-m2| >=0.02 is true.


text:
Q: "Run-Time Check Failure #0" error when casting glGenBuffers() #include <GL/glew.h>
#include <GL/GL.h>
#include <GLFW/glfw3.h>
#include <thread>
#define GLEW_STATIC

int main(){
    glewInit();
    glewExperimental = GL_TRUE;

    glfwInit();

    glfwWindowHint(GLFW_CONTEXT_VERSION_MAJOR, 3);
    glfwWindowHint(GLFW_CONTEXT_VERSION_MINOR, 2);
    glfwWindowHint(GLFW_OPENGL_PROFILE, GLFW_OPENGL_CORE_PROFILE);

    glfwWindowHint(GLFW_RESIZABLE, GL_FALSE);

    GLFWwindow* window = glfwCreateWindow(800, 600, "OpenGL", nullptr, nullptr); // Windowed
    //GLFWwindow* window = glfwCreateWindow(1920, 1080, "OpenGL", glfwGetPrimaryMonitor(), nullptr); fs
    glfwMakeContextCurrent(window);
    typedef void (*GENBUFFERS) (GLsizei, GLuint*);
    GENBUFFERS glGenBuffers = (GENBUFFERS)glfwGetProcAddress("glGenBuffers");

    float vertices[] = {
     0.0f,  0.5f, // Vertex 1 (X, Y)
     0.5f, -0.5f, // Vertex 2 (X, Y)
    -0.5f, -0.5f  // Vertex 3 (X, Y)
    };
    GLuint vertexBuffer;
    glGenBuffers(1, &vertexBuffer);
    printf("%u\n", vertexBuffer);
    glBindBuffer(GL_ARRAY_BUFFER, vertexBuffer);
    glBufferData(GL_ARRAY_BUFFER, sizeof(vertices), vertices, GL_STATIC_DRAW);

    glfwSetWindowShouldClose(window, GL_FALSE);

    while(!glfwWindowShouldClose(window)){
    glfwSwapBuffers(window);
    glfwPollEvents();
    if (glfwGetKey(window, GLFW_KEY_ESCAPE) == GLFW_PRESS)
        glfwSetWindowShouldClose(window, GL_TRUE);
    }

    glfwTerminate();
}

Hi I'm just a clueless programmer, this is my issue, when I compile this I get

Run-Time Check Failure #0 - The value of ESP was not properly saved
  across a function call.  This is usually a result of calling a
  function declared with one calling convention with a function pointer
  declared with a different calling convention.

This code is from http://open.gl/context
I know it's some sort of initialization issue but I'm simply too retarded to understand what's going on. Could someone please explain to me what I did wrong and what I'm meant to do instead?
EDIT: Code fixing progress
(Solution to last problem: Make glfwMakeContextCurrent(window); first, then call glewInit();  )
#include <GL/glew.h>
#include <GL/GL.h>
#include <GLFW/glfw3.h>
#include <thread>
#define GLEW_STATIC

int main(){

    glewExperimental = GL_TRUE;

    glfwInit();

    glfwWindowHint(GLFW_CONTEXT_VERSION_MAJOR, 3);
    glfwWindowHint(GLFW_CONTEXT_VERSION_MINOR, 2);
    glfwWindowHint(GLFW_OPENGL_PROFILE, GLFW_OPENGL_CORE_PROFILE);

    glfwWindowHint(GLFW_RESIZABLE, GL_FALSE);

    GLFWwindow* window = glfwCreateWindow(800, 600, "OpenGL", nullptr, nullptr); // Windowed
    //GLFWwindow* window = glfwCreateWindow(1920, 1080, "OpenGL", glfwGetPrimaryMonitor(), nullptr); fs

    typedef void (*GENBUFFERS) (GLsizei, GLuint*);
    GENBUFFERS glGenBuffers = (GENBUFFERS)glfwGetProcAddress("glGenBuffers");

    glfwMakeContextCurrent(window);

    glewInit();

    GLuint vertexBuffer;

    glGenBuffers(1, &vertexBuffer);
    printf("%u\n", vertexBuffer);

    float vertices[] = {
     0.0f,  0.5f, // Vertex 1 (X, Y)
     0.5f, -0.5f, // Vertex 2 (X, Y)
    -0.5f, -0.5f  // Vertex 3 (X, Y)
    };

    glBindBuffer(GL_ARRAY_BUFFER, vertexBuffer);

    glBufferData(GL_ARRAY_BUFFER, sizeof(vertices), vertices, GL_STATIC_DRAW);

    //glfwSetWindowShouldClose(window, GL_FALSE);

    while(!glfwWindowShouldClose(window)){
    glfwSwapBuffers(window);
    glfwPollEvents();
    if (glfwGetKey(window, GLFW_KEY_ESCAPE) == GLFW_PRESS)
        glfwSetWindowShouldClose(window, GL_TRUE);
    }

    glfwTerminate();
}

Current error: First-chance exception at 0x00000000  Access violation executing location 0x00000000.
RIGHT! Final progress report:
Turns out, GLEW does the typedef thing for you ( //typedef void (*GENBUFFERS) (GLsizei, GLuint*);
    //GENBUFFERS glGenBuffers = (GENBUFFERS)glfwGetProcAddress("glGenBuffers");
so remove this, I was basically redefining the crap that had already been defined, which is dumb. OK LESSON LEARNED, read the documentation from the API you're using before you blindly follow tutorials
FINAL CODE IMPROVEMENT FROM THIS
#include <GL/glew.h>
#include <GL/GL.h>

#include <GLFW/glfw3.h>
#include <thread>
#define GLEW_STATIC

int main(){
    //printf("%s\n", glGetString(GL_EXTENSIONS))
    glewExperimental = GL_TRUE;

    glfwInit();

    glfwWindowHint(GLFW_CONTEXT_VERSION_MAJOR, 3);
    glfwWindowHint(GLFW_CONTEXT_VERSION_MINOR, 2);
    glfwWindowHint(GLFW_OPENGL_PROFILE, GLFW_OPENGL_CORE_PROFILE);

    glfwWindowHint(GLFW_RESIZABLE, GL_FALSE);

    GLFWwindow* window = glfwCreateWindow(800, 600, "OpenGL", nullptr, nullptr); // Windowed
    //GLFWwindow* window = glfwCreateWindow(1920, 1080, "OpenGL", glfwGetPrimaryMonitor(), nullptr); fs

    //typedef void (*GENBUFFERS) (GLsizei, GLuint*);
    //GENBUFFERS glGenBuffers = (GENBUFFERS)glfwGetProcAddress("glGenBuffers");

    printf("%s\n", glGetString(GL_EXTENSIONS));

    glfwMakeContextCurrent(window);

    glewInit();

    GLuint vertexBuffer;

    glGenBuffers(1, &vertexBuffer);
    printf("%u\n", vertexBuffer);

    float vertices[] = {
     0.0f,  0.5f, // Vertex 1 (X, Y)
     0.5f, -0.5f, // Vertex 2 (X, Y)
    -0.5f, -0.5f  // Vertex 3 (X, Y)
    };

    glBindBuffer(GL_ARRAY_BUFFER, vertexBuffer);

    glBufferData(GL_ARRAY_BUFFER, sizeof(vertices), vertices, GL_STATIC_DRAW);

    //glfwSetWindowShouldClose(window, GL_FALSE);

    while(!glfwWindowShouldClose(window)){
    glfwSwapBuffers(window);
    glfwPollEvents();
    if (glfwGetKey(window, GLFW_KEY_ESCAPE) == GLFW_PRESS)
        glfwSetWindowShouldClose(window, GL_TRUE);
    }

    glfwTerminate();
}


text:
Q: listbox vlookup codes based on another worksheet i am sort of novice with VBA. i am trying to work with 2 listboxes, listbox1 (.lstdatabase) and listbox2 (.lstdatabase1). what i am trying to do is, when i click update cost button, selected rows from listbox1 (.lstdatabse) transfer to listbox2 (.lstdatabase1). while doing this it only transfers column 1 to 4 from listbox1 as required.
I have manage to work above by suing codes. Now, I am struggling to populate listbox2 (.lstdatabase1) column 5 (this value is from worksheet (Cost)) based on value reference to column 4 in listbox2 (.lstdatabase1).
Codes I have as below,
Private Sub cmdcostupdates_Click()
With UserForm1.lstdatabase1
Dim sh As Worksheet
Set sh = ThisWorkbook.Sheets("cost")
    .ColumnCount = 10
    .ColumnHeads = True
    .ColumnWidths = "40,60,60,60,60,100,100,250,80,80"

Dim i As Integer
For i = 0 To UserForm3.lstDatabase.ListCount - 1
If UserForm3.lstDatabase.Selected(i) = True Then
 UserForm1.lstdatabase1.AddItem
 UserForm1.lstdatabase1.Column(0, (UserForm1.lstdatabase1.ListCount - 1)) = UserForm3.lstDatabase.Column(0, i)
 UserForm1.lstdatabase1.Column(1, (UserForm1.lstdatabase1.ListCount - 1)) = UserForm3.lstDatabase.Column(1, i)
 UserForm1.lstdatabase1.Column(2, (UserForm1.lstdatabase1.ListCount - 1)) = UserForm3.lstDatabase.Column(2, i)
 UserForm1.lstdatabase1.Column(3, (UserForm1.lstdatabase1.ListCount - 1)) = UserForm3.lstDatabase.Column(3, i)
 UserForm1.lstdatabase1.Column(4, (UserForm1.lstdatabase1.ListCount - 1)) = UserForm3.lstDatabase.Column(4, i)
 UserForm1.lstdatabase1.Column(5, (UserForm1.lstdatabase1.ListCount - 1)) = Application.WorksheetFunction.VLookup(.List(3, i), Sheets("sh").Range("A1:G1000"), 7, False)

Can someone help to correct code for vlookup? below code gives me error.
UserForm1.lstdatabase1.Column(5, (UserForm1.lstdatabase1.ListCount - 1)) = Application.WorksheetFunction.VLookup(.List(3, i), Sheets("sh").Range("A1:G1000"), 7, False)

A: Found the code,
Private Sub cmdcostupdates_Click()
Dim i As Long, n As Long, f, f1 As Range
r As Rang

With UserForm1.lstdatabase1
.ColumnCount = 10
.ColumnHeads = True
.ColumnWidths = "40; 60; 60; 60; 200; 100; 100; 250; 80; 80"
For i = 0 To UserForm3.lstDatabase.ListCount - 1
If UserForm3.lstDatabase.Selected(i) = True Then
.AddItem
n = .ListCount - 1
.Column(0, n) = UserForm3.lstDatabase.Column(0, i)
.Column(1, n) = UserForm3.lstDatabase.Column(1, i)
.Column(2, n) = UserForm3.lstDatabase.Column(2, i)
.Column(3, n) = UserForm3.lstDatabase.Column(3, i)
.Column(4, n) = UserForm3.lstDatabase.Column(5, i)
Set f = Sheets("cost").Range("A4:I400").Find(.Column(4, n), , xlValues, xlWhole)
Set f1 = Sheets("cost1").Range("A4:I400").Find(.Column(4, n), , xlValues, xlWhole)
Set r = Sheets("cost2").Range("A4:I400").Find(.Column(4, n), , xlValues, xlWhole)

If Not f Is Nothing Then
.Column(5, n) = Sheets("cost").Range("I" & f.Row)
End If
If Not f1 Is Nothing Then
.Column(6, n) = Sheets("cost1").Range("I" & f1.Row)
End If
If Not r Is Nothing Then
.Column(7, n) = Sheets("cost2").Range("I" & r.Row)
End If

End If
Next i
UserForm1.Show
End With
End Sub


text:
Q: BigQuery Nested Table - if nested record do not exist? Have a straight question.
If the record is is null in SQL we use WHERE XXX is null
How about if nested records do not exist at all, like this:

WHERE XXX is empty???
What I would like to do? - Need to filter out records which do not have anything in OrderLines

A: Nested record is an array - to check if array is empty - I would use
WHERE ARRAY_LENGTH(OrderLines) = 0


text:
Q: Amazon IAM permissions list only one bucket Currently I have group with a policy that looks like this:
{
    "Version": "2012-10-17",
    "Statement": [
        {
            "Sid": "Stmt1449507915000",
            "Effect": "Allow",
            "Action": [
                "s3:*"
            ],
            "Resource": [
                "arn:aws:s3:::artmakeit",
                "arn:aws:s3:::artmakeit/*"
            ]
        },
        {
            "Sid": "ListAllBuckets",
            "Action": "s3:ListAllMyBuckets",
            "Effect": "Allow",
            "Resource": "*"
        }
    ]
}

So, the IAM user, my client, can access his bucket correctly. But I am wondering if I can only let him see his bucket and not the complete list of my buckets. Is there a way to achieve this? I guess I should change the ListAllBuckets permission, but I don't know what to write instead, any ideas?

A: If users intend to access their buckets via the AWS Management Console, then they require the ListAllBuckets permission.
It is not possible to 'hide' the complete bucket list when using the console -- either they see them all or none at all.
Access via other methods (eg the AWS Command-Line Interface (CLI) or an API call) does not require that this permission be assigned.


text:
Q: TDD type methodology for WPF / Silverlight Has anyone got a TDD-ish methodology for designing complex WPF xaml components (i.e., ControlTemplates, Custom Controls with dependency properties)?
Is eyeballing the UI the closest you can come to asserting your code is correct? How about incremental development; any aids to dividing up the logic incrementally?
If there isn't any methodologies for doing this now, do you think there will be as the platform continues to mature and gain adoption?
Cheers,
Berryl
To be more focused and avoid introductions to TDD, please consider the topic for an audience that is fairly seasoned in applying TDD to a traditional code base (including MVVM).

A: The silverlight toolkit provides all the unit test and the source code...
on
http://silverlight.codeplex.com/
For UI testing I think some folks use the Silverlight Accessibility api
http://msdn.microsoft.com/en-us/library/cc707824(VS.95).aspx
....
And there are also tools for UI testing, too
MSDN Magazine article on UI-Testing
http://msdn.microsoft.com/en-us/magazine/dd483216.aspx
Testing using WPF UI automation
http://blogs.msdn.com/b/llobo/archive/2007/09/06/testing-using-wpf-ui-automation.aspx
It is surely not an easy and obvious topic and it always depends on the business case...
And for TDD in general look at this book: The art of Unit Testing...


text:
Q: Does backing up Azure API Management service take the service down during the backup process at all? I'm wondering what implications ,if any, backing up a production API Management Service has on production traffic. The reason for me asking is that I recently tested running the backup cmdlet
Backup-AzApiManagement ..

and during the process ( which took anywhere between 15-25 minutes), within the Azure Portal on the main APIMS page for the service I was backing up, it stated "Updating service..."
I just want to be sure I understand if there are any potential downtime that need to be accounted for during the backup. Perhaps I need to run the backup during non-peak hours if so. I would hate to run the backup operation during peak hours, just unaware of potential downtime just to kick myself later when I find out that the service is expected to be down intermittently during the backup operation.
Any insight is appreciated. Thank you in advance for the help.

A: There will be no downtime if you are within the same region, however if its different region If you use the same Use the same API Management instance name there will be a downtime.

A: There will be no downtime. The API's is still working even when doing backup. However the developer portal is locked for editing. (I have tested running queries against API's when doing backup)
The only downside is that the APIM also throws an event in the Resource health log. Which means that if you have alerts configured for you APIM there will be an alert every time you are running a backup! I am digging for a solution for this, thats why I ended up here.


text:
Q: What is the best way to exit out of an unbounded loop after n failures in Python? I am newbie in Python. And I am wondering how to exit out of an unbounded loop after n failures. Using counter seems for me unpythonic.
This is my code:
while(True):
#get trigger state
    trigState = scope.ask("TRIG:STATE?")
    #check if Acq complete
    if( trigState.endswith('SAVE') ):
      print 'Acquisition complete. Writing into file ...\n'
      #save screen
      #rewrite in file

    #check if trigger is still waiting
    elif( trigState.endswith('READY') ):
      print 'Please wait ...\n'
    #if trigger neither in SAVE nor in READY mode
    else:
      #THIS IS FAILURE!!!
      print 'Failure: k tries remaining'

    #wait for several seconds before next iteration
    time.sleep(2)

Note that loop must be unbounded - it may iterate arbitrarily many times until number of tries exceeded.
Is there an elegant (or at least pythonic) method to meet the requirements?

A: To be "pythonic" you'll want to write code that conforms to the Zen of Python and a relevant rules here are:

Explicit is better than implicit.
Readability counts.

You should be explicit about the number of failures you allow, or the number of failures remaining. In the former case:
for number_of_failures in range(MAX_FAILURE):
    ...

expresses that intent, but is clunky because each time through the loop you are not necessarily failing, so you'd have to be be contorted in counting successes, which would impact readability. You can go with:
number_of_failures = 0
while number_of_failures < MAX_FAILURES:
    ...
    if this_is_a_failure_case:
        number_of_failures += 1
    ...

This is perfectly fine, as it says "if I haven't failed the maximum number of times, keep going. This is a little better than:
number_of_failures = 0
while True:
    ...
    if this_is_a_failure_case:
        number_of_failures += 1
    ...
    if number_of_failures == MAX_FAILURES: #you could use >= but this isn't necessary
        break

which hides the exit case. There are times when it is perfectly fine to exit the loop in the middle, but in your case, aborting after N failures is so crucial to what you want to do, that the condition should be in the while-loop condition.
You can also rephrase in terms of number of failures remaining:
failures_remaining = MAX_FAILURES
while failures_remaining > 0:
    ...
    if this_is_a_failure_case:
        failures_remaining -= 1
    ...

If you like functional programming, you can get rid of the loop and use tail recursion:
def do_the_thing():
    def try_it(failures_remaining = MAX_FAILURES):
        ...
        failed = ....
        ...
        try_it(failures_remaining-1 if failed else failures_remaining)

    try_it()

but IMHO that isn't really an improvement. In Python, we like to be direct and meaningful. Counters may sound clunky, but if you phrase things well (after all you are counting failures, right?) you are safely in the realm of Pythonic code.

A: Using an if statement to number your attempts seems simple enough for your purposes. It's simple, and (to my eyes anyway) easily readable, which suits your Pythonic criterion.
Within your while loop you you can do:
failure_no = 0
max_fails = n #you can substitute an integer for this variable
while:
  #...other code
  else:
    failure_no += 1
    if failure_no == max_fails:
      break
  print 'Failure: '+str(max_fails - failure_no)+' tries remaining'

This will only iterate the number of attempts if a else/failure condition is met, if you wanted to count the total number of run throughs, not just failures, you could put the failure_no +=1 right after your while rather than within the else block.
NB You could easily put a notification inside your escape:
eg
    if failure_no == max_fails:
      print 'Maximum number of failures reached'
      break

A: E.g. you can use an if statement and raise an error after n tries.
You only need a limit and a counter.
while(True):
#get trigger state
limit = 5
counter = 0
trigState = scope.ask("TRIG:STATE?")
#check if Acq complete
if( trigState.endswith('SAVE') ):
  print 'Acquisition complete. Writing into file ...\n'
  #save screen
  #rewrite in file

#check if trigger is still waiting
elif( trigState.endswith('READY') ):
  print 'Please wait ...\n'
#if trigger neither in SAVE nor in READY mode
else:
  #THIS IS FAILURE!!!
  counter +=1
  print 'Failure: ', limit - counter ,' tries remaining'
  if k => limit: raise RuntimeError('too many attempts')

#wait for several seconds before next iteration
time.sleep(2)

...


text:
Q: Add a 'destroyAll' action and route to my RESTful rails app I want to add a destroyAll action that destroys all posts in a blog app that I am writing. I have my routes.rb like this :
Rails.application.routes.draw do
  resources :writings
  root "writings#index"
end

And inside my controller I want to add the following action :
def destroyAll
  @writing = Writing.all
  @writing.each.destroy
end

please guide me through how to add a route to the destroyAll action and how to use it inside my view to make a link to use that action.
Thanks so much in advance

A: It should be defined as collection route of writings:
resources :writings do
  collection do
    delete :destroy_all
  end
end

Having it, you can link to delete_all action like this:
link_to 'delete all', [:destroy_all, :writings], method: :delete

You should notice that I wrote delete_all instead of deleteAll, because the former sticks to Ruby naming convention.

A: I think Marek Lipka's answer is perfectly adequate, but I'd like to offer an alternative, which IMO is a tad bit more RESTful. I'd model the collection of all writings as a separate resource. Since this resource does not have an id and there can only be one instance of this resource, it must be a singular resource:
resource :writings, only: :destroy

The problem with this is, that Rails will map this action to WritingsController#destroy, since Rails uses plural controllers for singular resources (any our singular resource has a plural name anyway), so this will conflict with the destroy action for individual writings. In that case you could either create a custom controller for this and implement a destroy action there:
resource :writings, only: :destroy, controller: 'collections/writings'

or you could still use the old controller, but specify another action:
resource :writings, only: :destroy, action: :destroy_all

In that case, you could use the following in your views:
link_to 'delete all', writings_path, method: :delete

A: Very late to the party, but wanted to add that perhaps another way is to consider all of the writings as a kind of resource itself, so you can keep the controllers adhering to the basic RESTful actions Rails typically uses.
resource :writings_collection, only: :destroy
# DELETE /writings_collection --> WritingsCollectionController#destroy

The advantage is the route helpers will not conflict with the writings ones.
You could even name the collection resource something meaningful that represents the collection concept.


text:
Q: PHP openssl_pkcs7_verify Not Working I`m using pkcs7 to sign a document and everything works fine, the problem is that the command to verify the sign is not working, always return false. I try to use the terminal command into the file and works fine.
Sign command:
openssl_pkcs7_sign(
    $tempdoc,
    $tempsign,
    $this->signature_data['signcert'],
    array($this->signature_data['privkey'],
    $this->signature_data['password']),
    array(),
    PKCS7_BINARY | PKCS7_DETACHED);

Verify command:
openssl_pkcs7_verify($tempsign, PKCS7_NOVERIFY)

Terminal command:
openssl pkcs7 -inform DER -in signature.pkcs7 -print_certs -text

EDIT 1

I make tests in my code and discover if i create my sign with only PKCS7_DETACHED or PKCS7_BINARY works fine the verify, but both together i receive the error. Why this is happening?

A: Here with PHP 7 i can reproduce your problem. With both flags the verify fails.
Maybe THIS URL can help you., this part talks about it.

SMIME -sign "detached" "attaches" content similarly as-is  with
  -binary and text-canonicalized without, and signs that.  SMIME -verify recognizes "detached", but (in multi_split)  always canonicalizes both
  parts before using them. For content  that was sent noncanonical (with
  -sign -binary or equivalent)  this changes the signed content, and verify fails.  Content that was canonical as sent (originally
  canonical  or canonicalized by sender) does verify and similarly  is
  output without determining if sender changed it.

In the docs you can read that the parser isn't that smart:

BUGS
The MIME parser isn't very clever: it seems to handle most messages
  that I've thrown at it but it may choke on others.

Hope it helps!


text:
Q: File extensions in asp.net and their definitions Any one please give me File extensions (like aspx, ascx etc) in asp.net and there definitions and were they use.
Thanks in advance

A: A complete list can be found on MSDN:
http://msdn.microsoft.com/en-us/library/2wawkw1c(v=vs.100).aspx
For the ones you mentioned:
aspx

An ASP.NET Web forms file (page) that can contain Web controls and
  presentation and business logic. For more information, see Creating
  ASP.NET Web Pages and ASP.NET Web Server Controls Overview.

ascx

A Web user control file that defines a custom, reusable control. For
  more information, see ASP.NET User Controls.


text:
Q: Is there a difference in how threads work in Linux vs Unix vs Solaris I'm just curious to if there is any difference to how threads work in the different flavors of Unix.
In particular Linux, Solaris and the original Unix
Any thoughts?

A: The original Unix does not use threads for multiprogramming. An article from 1987 comparing the Mach and Unix kernel states that "neither Unix System V nor 4.3 BSD provide a way to manage more than one thread of control within an address space".
Modern Unix clones adhere to the POSIX Threads specification. The POSIX Threads standard only appeared in 1995. The underlying implementation in Linux is based on the clone() and futex() system calls, which are implemented by the kernel. The clone() system call creates a new lightweight process that can share a memory space with its child. So, for example, the pthread_create() library call internally calls the clone() system call. The futex() system call implements a synchronization primitive that can be used for creating larger synchronization operations, like mutexes, semaphores, etc. So, for example, pthread_mutex_lock() will call futex() internally.
Using POSIX terminology, Linux implementation model is a "kernel-thread model", also known as 1:1 model, where 1 kernel lightweight process is used for 1 user visible thread.
Linux also had different threading implementations over time. More description about threading support in Linux in pthreads(7), clone(2) and futex(2) manual pages.
Other implementations may be completely different and still implement the POSIX threads API. FreeBSD used a M:N implementation, or "hybrid model", where an user visible thread could be managed either by the kernel, or by a user space library. See the kse(2) manual page for a complete description. I have once traced the current 1:1 FreeBSD threading implementation to an article in kerneltrap:
http://web.archive.org/web/20110512021159/http://kerneltrap.org/node/624
OpenSolaris doesn't seem to describe its own threading implementation on man pages. I could find instead a document comparing the OpenSolaris kernel with Linux 2.6 and Windows Vista. There, a main difference between the Linux and OpenSolaris implementation is that in Linux, each process is a lightweight process, unifying threads and processes, while in OpenSolaris one process contains multiple lightweight processes, in practice separating in the kernel the process from the kernel thread.
References:
http://en.wikipedia.org/wiki/Thread_(computing)
http://en.wikipedia.org/wiki/POSIX_Threads
http://repository.cmu.edu/cgi/viewcontent.cgi?article=2728&context=compsci
http://man7.org/linux/man-pages/man7/pthreads.7.html
http://man7.org/linux/man-pages/man2/clone.2.html
http://man7.org/linux/man-pages/man2/futex.2.html
http://pubs.opengroup.org/onlinepubs/7908799/xsh/threads.html
http://www.freebsd.org/cgi/man.cgi?query=kse&apropos=0&sektion=0&manpath=FreeBSD+7.2-RELEASE&format=html
http://web.archive.org/web/20110512021159/http://kerneltrap.org/node/624
http://www.unix.com/man-page/opensolaris/5/threads/
http://www.infoq.com/articles/kernel-comparison-unix-zhu


text:
Q: How can I define a point that is perpendicular to the endpoints on a line segment? I am currently working on a problem statement that requires me to find the equation of a line given two points, normalizing the line ($Ax+By+C = 0$) and then introducing a third point into the same plane. I have to find the distance of this third point to the line itself when it is normalized.
I am currently using this as reference:
Distance from a point to a line
Pretty easy to follow. One minor question (before moving on) is if I take the sum of equation (2') in the reference:
dist$(P,\text{line}) = Au + Bv + C$
This should be the distance of the point to the line correct? (Just making sure)
The next big question I have is how can I find *two distinct lines that are perpendicular  to the endpoints $P_1$ and $P_2$ that are creating a line/segment? What I want to do is find two lines perpendicular to the endpoints and then say that if the projection of the third point ($Q$) lies outside of these, then it is not on the line created by P1 and P2. This is going to be done through code but I don't need help on that.
I figured that I could plug in coordinates of the two endpoints like equation 2' but this doesn't seem right.

A: If I understand the latter part of your question correctly, you want, given a line segment from a point $P_1$ to a point $P_2$ in the plane, to have points $Q_1$ and $Q_2$ in the plane, such that the line segment of the points $\overline{Q_1Q_2}$ intersects $\overline{P_1P_2}$ and is perpendicular.
Using vector notation this can easily be done by letting for example $m = \frac{1}{2}(p_1+p_2)$, $d = \frac{1}{2}(p_2-p_1)$ and setting $q_1 = m + \begin{bmatrix}0&-1\\1&0\end{bmatrix}\cdot d$ and $q_2 = m + \begin{bmatrix}0&1\\-1&0\end{bmatrix}\cdot d$.
In words: we first calculate the midpoint $m$ and a direction $d$ of the line-segment $\overline{P_1P_2}$ and then we calculate the points obtained by going from the midpoint in the direction of $d$ rotated clockwise / counterclockwise.


text:
Q: "An" in Shakespeare's Taming of the Shrew In Act 1, Scene 1, Katherine says to Bianca,

A pretty peat! It is best / Put finger in the eye, an she knew why".

I understand "Put finger in the eye" means she is fake crying for sympathy, but what does "an she knew why" mean?
I'm guessing that "an," somehow means "if," since this makes the most sense.

A: In Shakespeare's English, 'an' could be a clipped form of 'and', which had several meanings that have disappeared. See A Shakespeare Glossary by C. T. Onions, enlarged and revised by Robert D. Eagleson (Oxford University Press, 1986):

and, an, an'
(…)
sub. conj.

*

*If; even if, though. 1H4 2.4.283: "Ah, no more of that, Hal, an thou lovest me!" (…)

This conjunction is sometimes duplicated, i.e. when Shakespeare writes "and if". See for example Caliban's words in The Tempest, Act 2, scene 2:

These be fine things, an if they be not sprites.

Returning to The Taming of the Shrew, Katherine is saying, "The best thing she can do is to make herself weep, if she knew of some excuse". (See The Taming of the Shrew, edited by G. R. Hibbard. The New Penguin Shakespeare. 1968. Page 181.)


text:
Q: What's the best way to deprecate a column in a database schema? After reading through many of the questions here about DB schema migration and versions, I've come up with a scheme to safely update DB schema during our update process.  The basic idea is that during an update, we export the database to file, drop and re-create all tables, and then re-import everything.  Nothing too fancy or risky there.
The problem is that this system is somewhat "viral", meaning that it is only safe to add columns or tables, since removing them would cause problems when re-importing the data.  Normally, I would be fine just ignoring these columns, but the problem is that many of the removed items have actually been refactored, and the presence of the old ones in the code fools other programmers into thinking that they can use them.
So, I would like to find a way to be able to mark columns or tables as deprecated.  In the ideal case, the deprecated objects would be marked while updating the schema, but then during the next update our backup script would simply not SELECT the objects which have been marked in this way, allowing us to eventually phase out these parts of the schema.
I have found that MySQL (and probably other DB platforms too, but this is the one we are using) supports the COLUMN attribute to both fields and tables.  This would be perfect, except that I can't figure out how to actually use it in a meaningful manner.  How would I go about writing an SQL query to get all column names which do not contain a comment matching text containing the word "deprecated"?  Or am I looking at this problem all wrong, and missing a much better way to do this?

A: "Deprecate" usually means (to me at least) that something is marked for removal at some future date, should not used by new functionality and will be removed/changed in existing code.
I don't know of a good way to "mark" a deprecated column, other than to rename it, which is likely to break things! Even if such a facility existed, how much use would it really be?
So do you really want to deprecate or remove? From the content of your question, I'm guessing the latter.
I have the nasty feeling that you may be in one of those "if I wanted to get to there I wouldn't start from here" situations. However, here are some ideas that spring to mind:

*

*Read Recipes for Continuous Database Integration which seems to address much of your problem area

*Drop the column explicitly. In MySQL 5.0 (and even earlier?) the facility exists as part of DDL: see the ALTER TABLE syntax.

*Look at how ActiveRecord::Migration works in Ruby. A migration can include the "remove_column" directive, which will deal with the problem in a platform-appropriate way. It definitely works with MySQL, from personal experience.

*Run a script against your export to remove the column from the INSERT statements, both column and values lists. Probably quite viable if your DB is fairly small, which I'm guessing it must be if you export and re-import it as described.

A: Maybe you should refactor to use views over your tables, where the views never include the deprocated columns.


text:
Q: Tkinter hangs while sensing (in a for loop) while True:
    x = []

    while True:
        sense = 0
        for i in range(0,4):
            k = gpio.input(sensor)
            if k = 1:
                sense += 1
                time.sleep(.005)
        if sense == 0:
            x = abc()

the above code snippet is for a GUI i've made using 'Tkinter' that has a couple of buttons (Executed on, System : Raspberry Pi; OS : Fedora). one is get a sensor running and the second,  to sense if an object is present. when the sensor (active low) senses an object for more than 20 mills (after the second button is pressed) it is to execute abc() (which is a computation related to the list x).
"the code without the GUI part works just fine" but hangs when the GUI is introduced!
could someone please point out to any potential mistake in this block of code?
ive gone through a few questions posted here and have done a few changes to check which part of the complete code makes the GUI hang, and kind of narrowed it down to this part

A: You have two loops constantly running (but I don't think the first one is not necessary, since you never break the second one) and a call to time.sleep. If you run this code on the Tkinter thread, the GUI will be unresponsive because the thread is "busy", constantly executing this loops.
You can execute this on a different thread and communicate, or even better, rewrite it so you can call Tk.after periodically (instead of time.sleep) to retrieve the value of the sensor and then update the content of the GUI.


text:
Q: Calculating the number of protons in the sun The central density of the Sun is ρ = 150 gm/cm3.
Suppose that the center of
the Sun is composed only of free protons with a mass of  1.67 × 10−24 gm.
What is the number of protons per cm3 at the Sun's center?
how would you do this?

A: Let me rephrase your question:

The (mass to volume) density of a material is $\rho = 10 \frac{\text{g}}{\text{cm}^3}\,$. It is composed by objects with a mass of $m = 1\,\text{g}\,$.
  Calculate the number (to volume) density of these objects.

As said before, given these two numbers you can calculate the number density, often denoted as $n$, simply by dividing:
$n = \frac{\rho}{m} = \frac{10 \frac{\text{g}}{\text{cm}^3}}{1\,\text{g}} = 10 \frac{1}{\text{cm}^3}$
As you can see the unit of mass cancels out in that process. That way you get the number of objects per $\text{cm}^3$ of the material, nothing more. In particular you don't get the absolute number (as your title suggests) without knowing any volume.
If you do that with your numbers you get the desired result. Simple as that.


text:
Q: Masstransit - Mediator fails to responde to a scoped background service on Asp.Net So I have an Asp.Net core app. I need to host a background service that sends periodicly messages to mediator. Problem is that when consumer tries to send a response back, it always fails. The fail is: loopback://localhost/response => The message was not consumed
There is no timeout, fail is immediate.
StackTrace:
    at MassTransit.Pipeline.Filters.FaultDeadLetterFilter.Send(ReceiveContext context, IPipe`1 next)
    at GreenPipes.Pipes.FilterPipe`1.GreenPipes.IPipe<TContext>.Send(TContext context)
    at MassTransit.Pipeline.Filters.DeadLetterFilter.<GreenPipes-IFilter<MassTransit-ReceiveContext>-Send>d__3.MoveNext()
    at System.Runtime.ExceptionServices.ExceptionDispatchInfo.Throw()
    at System.Runtime.CompilerServices.TaskAwaiter.ThrowForNonSuccess(Task task)
    at System.Runtime.CompilerServices.TaskAwaiter.HandleNonSuccessAndDebuggerNotification(Task task)
    at System.Runtime.CompilerServices.ConfiguredTaskAwaitable.ConfiguredTaskAwaiter.GetResult()
    at MassTransit.Transports.ReceivePipeDispatcher.<Dispatch>d__17.MoveNext()
    at System.Runtime.ExceptionServices.ExceptionDispatchInfo.Throw()
    at MassTransit.Transports.ReceivePipeDispatcher.<Dispatch>d__17.MoveNext()
    at System.Runtime.ExceptionServices.ExceptionDispatchInfo.Throw()
    at MassTransit.Transports.ReceivePipeDispatcher.<Dispatch>d__17.MoveNext()
    at System.Runtime.ExceptionServices.ExceptionDispatchInfo.Throw()
    at System.Runtime.CompilerServices.TaskAwaiter.ThrowForNonSuccess(Task task)
    at System.Runtime.CompilerServices.TaskAwaiter.HandleNonSuccessAndDebuggerNotification(Task task)
    at System.Runtime.CompilerServices.ConfiguredTaskAwaitable.ConfiguredTaskAwaiter.GetResult()
    at MassTransit.Mediator.Endpoints.MediatorSendEndpoint.<SendMessage>d__26`1.MoveNext()
    at System.Runtime.ExceptionServices.ExceptionDispatchInfo.Throw()
    at MassTransit.Mediator.Endpoints.MediatorSendEndpoint.<SendMessage>d__26`1.MoveNext()
    at System.Runtime.ExceptionServices.ExceptionDispatchInfo.Throw()
    at System.Runtime.CompilerServices.TaskAwaiter.ThrowForNonSuccess(Task task)
    at System.Runtime.CompilerServices.TaskAwaiter.HandleNonSuccessAndDebuggerNotification(Task task)
    at System.Runtime.CompilerServices.TaskAwaiter.GetResult()
    at Service.Recieve.<Consume>d__7.MoveNext() in C:\...\Recieve.cs

So in my startup I set up mediator and background service:
        services.AddMediator(cfg =>
        {
            cfg.AddRequestClient<Service.Command.RecieveCommand>();
            cfg.AddConsumer<Service.Recieve>();
        });

        services.AddHostedService<RecieveMarketingMessagesService>();
        services.AddScoped<IRecieveScopedMarketingMessageService, RecieveScopedMarketingMessageService>();

My background service does initialize new scope on every run.
public class RecieveMarketingMessagesService : BackgroundService, IDisposable
{
    private readonly IServiceProvider serviceProvider;

    public RecieveMarketingMessagesService(IServiceProvider serviceProvider)
    {
        this.serviceProvider = serviceProvider;
    }

    protected override async Task ExecuteAsync(CancellationToken stoppingToken)
    {
        while (!stoppingToken.IsCancellationRequested)
        {
            using (var scope = serviceProvider.CreateScope())
            {
                var service = scope.ServiceProvider.GetRequiredService<IRecieveScopedMarketingMessageService>();
                await service.Process(stoppingToken);
            }
        }
    }
}

And gets scoped service:
public class RecieveScopedMarketingMessageService : IRecieveScopedMarketingMessageService
{
    private readonly ILogger logger;
    private readonly IRequestClient<RecieveCommand> client;

    public RecieveScopedMarketingMessageService(ILoggerFactory loggerFactory, IRequestClient<RecieveCommand> client)
    {
        this.logger = loggerFactory.CreateLogger<RecieveScopedMarketingMessageService>();
        this.client = client;
    }

    public async Task Process(CancellationToken stoppingToken)
    {
        try
        {
            await client.GetResponse<RecieveResponse>(new RecieveCommand(), cancellationToken: stoppingToken);
        }
        catch (Exception ex)
        {
            logger.LogCritical(ex, "---------FAIL FAIL----------");
        }
    }
}

Inside the scope service I inject the Request client and call 'GetResponse'.
Here is the consumer:
public class Recieve : IConsumer<RecieveCommand>
{
    private readonly ILogger logger;

    public Recieve(ILoggerFactory loggerFactory)
    {
        this.logger = loggerFactory.CreateLogger<Recieve>();
    }

    public async Task Consume(ConsumeContext<RecieveCommand> context)
    {
        try
        {
            /* HERE BE SOME WORK ... */

            await context.RespondAsync(new RecieveResponse()); /* <------ HERE ALWAYS FAILS */
        }
        catch(Exception ex)
        {

        }
    }
}

I have no idea where is the problem. Thanks for help.


text:
Q: How to make DAL integration tests less brittle? First. We do not use ORM. And won't use it in near future. (it's not my decision).
We create stored procedures for multiple read/write cases.
Most of the reading SPs are for populating DTOs which are sent to client.
Each DAL method usually calls single SP.
Integration test consists of running insert script, then initialization of expectations  according to the script, calling method and then checking returned result. I.e. standard AAA pattern.
However, even small DB schema refactoring usually breaks about a hundred of tests.
Prepare are the cause: whereas DTO usually needs a subset of columns. Insert requires all of them. Thus every ыскшзе that touches refactored table breaks.
I consider correcting bunch of the scripts every time after refactoring a kind of monkey job. Looking for ways of improving tests robustness.

A: You could try to write generalized functions that prepare one table and use this always instead of repeating the prepare statements across your tests.
Also you could look into T4 template with interaction to the database to generate the prepare statements before compiling the tests.
Generate from T4


text:
Q: How can I detect edges on an image of a document, and cut sections into seperate images? The task is to take an image of a document, and leverage straight lines surrounding different 'sections' in order to split up the image into different documents for further parsing.  Size of the different 'sections' is completely variable from page to page (we're dealing with several thousand pages).  Here is an image of what one of these images looks like:
Example of how the documents are laid out:

Image analysis/manipulation is completely new to me.  So far I've attempted to use Scikit-image edge detection algorithms to find the 'boxes', with hopes to use those 'coordinates' to cut the image.  However, the two algorithms I've tried (Canny, Hough) are picking up lines of text as 'edges' on high sensitivity, and not picking up the lines that I want on low sensitivity.  I could write something custom and low level to detect the boxes myself, but I have to assume this is a solved problem.
Is my approach headed in the right direction?  Thank you!

A: You don't seem to be getting any OpenCV answers, so I had a try with ImageMagick, just in the Terminal at the command-line. ImageMagick is installed on most Linux distros and is available for macOS and Windows for free. The technique is pretty readily adaptable to OpenCV so you can port it across if it works for you.
My first step was to do a 5x5 box filter and threshold at 80% to get rid of noise an scanning artefacts and then invert (probably because I was planning on using morphology, but didn't in the end).
convert news.jpg -depth 16 -statistic mean 5x5 -threshold 80% -negate z.png

I then ran that through "Connected Components Analysis" and discarded all blobs with too small an area (under 2000 pixels):
convert news.jpg -depth 16 -statistic mean 5x5 -threshold 80% -negate  \
   -define connected-components:verbose=true                           \
   -define connected-components:area-threshold=2000                    \
   -connected-components 4 -auto-level output.png

Output
Objects (id: bounding-box centroid area mean-color):
  110: 1254x723+59+174 686.3,536.0 901824 srgb(0,0,0)
  2328: 935x723+59+910 526.0,1271.0 676005 srgb(0,0,0)
  0: 1370x1692+0+0 685.2,712.7 399651 srgb(0,0,0)
  2329: 303x722+1007+911 1158.0,1271.5 218766 srgb(0,0,0)
  25: 1262x40+54+121 685.2,140.5 49820 srgb(255,255,255)
  109: 1265x735+54+168 708.3,535.0 20601 srgb(255,255,255)
  1: 1274x64+48+48 675.9,54.5 16825 srgb(255,255,255)
  2326: 945x733+54+905 526.0,1271.0 16660 srgb(255,255,255)
  2327: 312x732+1003+906 1169.9,1271.5 9606 srgb(255,255,255)  <--- THIS ONE
  421: 403x15+328+342 528.6,350.1 4816 srgb(255,255,255)
  7: 141x23+614+74 685.5,85.2 2831 srgb(255,255,255)

The fields are labelled in the first line, but the interesting ones are the second (block geometry) and fourth field  (blob area). As you can see, there are 11 lines so it has found 11 blobs in the image. The second field, AxB+C+D means a rectangle A pixels wide by B pixels tall with its top-left corner C pixels from the left edge of the image and D pixels down from the top.
Let's look at the one I have marked with an arrow, which starts 2327: 312x732+1003+906 and draw a rectangle over that one:
convert news.jpg -fill "rgba(255,0,0,0.5)" -draw "rectangle 1003,906 1315,1638" oneArticle.png

If you want to crop that article out into a new image:
convert news.jpg -crop 312x732+1003+906 article.jpg

If we draw in all the other boxes , we get:


text:
Q: keep variable type in json.dump I am reading a bunch of csv files which lines contain characters and numbers as follows:
"T55BSU","@","IT-196","IT","NO","@",1,385.82,1.4011825391667,"LFA","Economy", ...
"343OA3","A:1893BC6","FR-7139","FR","NO","@",1,805.01,1.4011825391667,"LFA","Economy", ...
...

I have a little python script which loops over the files and dumps their content into JSON format:
#!/usr/bin/python

import csv
import json

from os import listdir
from os.path import isfile, join

csvpath = "path to csv dir"
jsonpath = "path to json dir"

onlyfiles = [ f for f in listdir(csvpath) if isfile(join(csvpath,f)) ]

fieldnames = ("names of columns")

for files in onlyfiles:
    name = files.split('.')
    csvname = str(csvpath) + str(files)
    jsoname = str(jsonpath) + str(name[0]) + '.json'

    print "Opening " + str(csvname) + "\n"
    csvfile = open(csvname, 'r')

    print "Writing " + str(jsoname) + "\n"
    jsonfile = open(jsoname, 'w')

    reader = csv.DictReader(csvfile, fieldnames)

    for row in reader:
        json.dump(row, jsonfile)
        jsonfile.write('\n')

My problem is that all the values in the JSON file are converted to strings as such:
{"REFUND_SW": "N", "DEST_COUNTRY": "IT", "LOWCOST_CAR": "NO", "CURRATE": "1.4011825391667", "DEFAULT_CLIENT_GROUP_CD": "IT-196", "MAIN_SUPPLIER_CODE": "BV", "DEST_CITY": "ROME", "TRAVEL_PURPOSE": "C", "FARE_TYPE": "C", "CONNECTION_TIME": "0", "BOOKING_DATE": "2014-04-14", "FLIGHT_DURATION": "70"}

But, I would like:
{"REFUND_SW": "N", "DEST_COUNTRY": "IT", "LOWCOST_CAR": "NO", "CURRATE": 1.4011825391667, "DEFAULT_CLIENT_GROUP_CD": "IT-196", "MAIN_SUPPLIER_CODE": "BV", "DEST_CITY": "ROME", "TRAVEL_PURPOSE": "C", "FARE_TYPE": "C", "CONNECTION_TIME": 0, "BOOKING_DATE": "2014-04-14", "FLIGHT_DURATION": 70}

How do I force json.dump to not convert everything to strings? In the original csv file, they are written as numbers ...
Thanks

A: The problem is not json.dumps, but the csv reader.
Every value is interpreted as string (Read data from csv-file and transform to correct data-type)
If you know the data type of the columns you can convert them after reading:
#!/usr/bin/python

import csv
import json

csvfile = [
    '"name","age","grade"',
    '"ann",42,1.3',
    '"hans",23,1.7'
]
row_types = {'name': str, 'grade': float, 'age': int}

reader = csv.DictReader(csvfile)

jsonfile = open('test.json', 'w')
for row in reader:
    print('reader produces strings only:')
    print(row)
    print('convert to known types')
    row_converted = {k: row_types[k](v) for k, v in row.items()}
    print(row_converted)
    json.dump(row_converted, jsonfile)
    jsonfile.write('\n')

A: It's not json.dump that's at fault here - it will happily record integer objects if this is what the source dictionary includes.
It is more on the side of the CSV reader - it does not possess special intelligence to figure out which of the columns should be automatically converted to an int, and treats every column as a string.
You need to do post-processing on specific columns to convert them to an int, as per this post: CSV reader and DictReader turn numeric fields into strings .


text:
Q: What does it mean by DiskCookies Crash on iOS App? I use Fabric to log crash on my iOS App.
Today, I came across some crash related to DiskCookies. I really don't know what it means.
Crashed: diskcookies
0  CoreFoundation                 0x1bd00136 CFNotificationCenterPostNotification + 53
1  libsystem_malloc.dylib         0x1b5d9cf3 szone_malloc_should_clear + 3240
2  CFNetwork                      0x1c44a359 DiskCookieStorage::writeFileCompletely0(DiskCookieStorage*, FilePathStat*, MemoryCookies const*, __CFData const*, TracerData*, int) + 634
3  CFNetwork                      0x1c44a49d DiskCookieStorage::_asyncWriteFileCompletely(void*) + 174
4  libdispatch.dylib              0x1b4a1783 _dispatch_client_callout + 22
5  libdispatch.dylib              0x1b4ada35 _dispatch_barrier_sync_f_invoke + 50
6  CFNetwork                      0x1c44b09d DiskCookieStorage::syncStorageWithCompletionLocked(unsigned char, void () block_pointer) + 2220
7  CFNetwork                      0x1c44277b ___CFHTTPCookieStorageFlushCookieStores_block_invoke + 86
8  CoreFoundation                 0x1bcf5447 __CFDictionaryApplyFunction_block_invoke + 20
9  CoreFoundation                 0x1bce0634 CFBasicHashApply + 120
10 CoreFoundation                 0x1bce94c1 CFDictionaryApplyFunction + 152
11 CFNetwork                      0x1c44270f _CFHTTPCookieStorageFlushCookieStores + 140
12 libsystem_c.dylib              0x1b53720d __cxa_finalize_ranges + 290
13 libsystem_c.dylib              0x1b4f61b3 exit + 12
14 Comico                         0x97a74f UnityGetGLViewController + 4756906
15 Comico                         0x97a265 UnityGetGLViewController + 4755648
16 Comico                         0x980a6b UnityGetGLViewController + 4782278
17 Comico                         0x96dfb5 UnityGetGLViewController + 4705808
18 Comico                         0x96da59 UnityGetGLViewController + 4704436
19 Comico                         0x200fe3 -[AppDelegate setUpAppGuardWithUserID:] (AppDelegate.m:1303)
20 Comico                         0x1ff967 __36-[AppDelegate dologinInCallLoginAPI]_block_invoke (AppDelegate.m:1026)
21 Comico                         0x13f69b __42-[NCLoginRAPIManager loginWithCompletion:]_block_invoke (NCLoginRAPIManager.m:97)
22 Comico                         0xde19f -[NCRAPICompletion performBlockWithOperation:] (NCRAPICompletion.m:94)
23 CoreFoundation                 0x1bd06323 -[NSArray makeObjectsPerformSelector:withObject:] + 218
24 Comico                         0x3adf0d -[NCRAPIOperationRegister performCompletionBlockOfOperation:] (NCRAPIOperationRegister.m:67)
25 Comico                         0x251ce1 __51-[NCRAPIManager callRAPIWithAPIRequest:completion:]_block_invoke_2 (NCRAPIManager.m:65)
26 libdispatch.dylib              0x1b4a1797 _dispatch_call_block_and_release + 10
27 libdispatch.dylib              0x1b4a1783 _dispatch_client_callout + 22
28 libdispatch.dylib              0x1b4a5d05 _dispatch_main_queue_callback_4CF + 902
29 CoreFoundation                 0x1bd8fd69 __CFRUNLOOP_IS_SERVICING_THE_MAIN_DISPATCH_QUEUE__ + 8
30 CoreFoundation                 0x1bd8de19 __CFRunLoopRun + 848
31 CoreFoundation                 0x1bce11af CFRunLoopRunSpecific + 470
32 CoreFoundation                 0x1bce0fd1 CFRunLoopRunInMode + 104
33 GraphicsServices               0x1d48bb41 GSEventRunModal + 80
34 UIKit                          0x21069a53 UIApplicationMain + 150
35 Comico                         0x20dc39 main (main.m:19)
36 libdyld.dylib                  0x1b4ce4eb start + 2

I believe someone is trying to modify the path where network library put data to. Does anyone have any other theory or have some experience on this crash?

A: From the stack trace you posted here is my theory.

*

*Frame 14 indicates that you've got a Unity application, and it's doing its thing running OpenGL.

*Frame 13 is really interesting. It seems like the Unity UnityGetGLViewController (which I assume is not written by you) has called exit. This is surprising behavior, but it gives lots of clues on the rest of the stack.

*Frames 12-2 look like the network stack is just doing some work on application exit (triggered by UnityGetGLViewController). Seems like it is just writing some cookie-related stuff to disk. I wouldn't worry about this.

*Frame 0 and 1 are really suspect. I have a very hard time believing that malloc calls into CoreFoundation. If I had to guess, I would say that frame 0 is correct, and frame 1 has been mis-symbolicated or incorrectly unwound.

It's very unusual to call exit in iOS applications. While it is technically API, I doubt it is heavily tested. My bet is that there are some dangling pointer and/or object lifecycle issues related to the use of exit and you are seeing it here.
What I would do is see if Unity has any documentation around UnityGetGLViewController calling exit. I'd also check in with the Fabric people about frames 1 and 0. I don't see how both could be correct. And, finally, I might consider opening a bug with Apple. However, Apple usually doesn't like looking at non-Apple crash reports. So, that last one is probably a long-shot.


text:
Q: select where one column part of another I want to select all rows from my table where value of one column begins with value of another column.
Table
column_a         column_b

abc              abcdef
pqr              rstrv
xyz              xyzabc
uvw              abcdef

I want to get
pqr              rstrv
uvw              abcdef

I'm using the query
SELECT * FROM table_name WHERE column_b NOT LIKE column_a + '%'

I'm getting the error

1064 - You have an error in your SQL syntax; check the manual that corresponds to your MySQL server version for the right syntax to use near '+ '%' LIMIT 0, 30' at line 1

I've tried solutions from these questions
Compare Columns Where One is Similar to Part of Another
Oracle: LIKE where any part of one string matches amy part of another string
SQL search column where one item in column is substring of another item
SQL search column where one item in column is substring of another item Update. But still resulting in error or wrong results
My mysql version is Server version: 5.5.44-0ubuntu0.14.04.1 (Ubuntu).
I'm using phpMyAdmin to execute queries.

A: You have the right idea, but MySQL doesn't support the + operator for string concatination, only for mathematical addition. Instead, just use the concat function:
SELECT * FROM table_name WHERE column_b NOT LIKE CONCAT(column_a, '%')

A: In MySQL, you should use CONCAT() instead of +:
select *
from TableName
where column_b not like CONCAT(column_a,'%')

In SQL Server:
select *
from TableName
where column_b not like column_a+'%'

A: Try
SELECT * FROM table_name WHERE column_b NOT LIKE CONCAT(column_a,'%')

or
SELECT * FROM table_name WHERE column_b LIKE CONCAT('%', column_a, '%')


text:
Q: How to convert MS SQL queries to MySQL queries I have a MSSQL queries file(.sql), now I need to convert it to MYSQL queries.
Please help me. The script like this:
CREATE TABLE [dbo].[Artist](
    [ArtistId] [int] IDENTITY(1,1) NOT NULL,
    [Name] [nvarchar](120) NULL,
PRIMARY KEY CLUSTERED

(
    [ArtistId] ASC

)WITH (PAD_INDEX  = OFF, STATISTICS_NORECOMPUTE  = OFF, IGNORE_DUP_KEY = OFF, ALLOW_ROW_LOCKS  = ON, ALLOW_PAGE_LOCKS  = ON) ON [PRIMARY]

) ON [PRIMARY]

A: If you want to convert the DDL by hand, then you can do this by building up rules on a case by case basis, e.g. as follows:

*

*[] need to be replaced with backticks

*IDENTITY(1,1) can be replaced with AUTO_INCREMENT

*Most of the ANSI options and Device settings
can be ignored (these seem to be present only because the table has
been rescripted)

*w.r.t. dbo, MySQL doesn't implement schemas in the same way as SQL Server - you will either need to separate schemas into databases, or drop the schema, or mangle the schema name into the tablename (e.g. as a Prefix)

This will leave you with something like the following:
CREATE TABLE `Artist`(
    `ArtistId` int NOT NULL AUTO_INCREMENT,
    `Name` nvarchar(120) NULL,
    PRIMARY KEY CLUSTERED
    (
       `ArtistId` ASC
    )
);

Fiddle here
However, it is usually much easier to do this migration with a migration tool - search for the section on How to Transition from SQL Server to MySQL


text:
Q: Why doesn't my Rust code with dependent types compile? Why doesn't my Rust code compile?
pub struct BinaryFormatWithoutFieldUid<'a, T>(pub &'a T);

pub struct BinaryFormatWithoutLength<'a, T>(pub &'a T);

pub trait Serialize {}

impl<'a, T> Serialize for BinaryFormatWithoutFieldUid<'a, T>
    where BinaryFormatWithoutLength<'a, T>: Serialize
{}

impl<'a, T> Serialize for BinaryFormatWithoutFieldUid<'a, Option<T>>
    where BinaryFormatWithoutFieldUid<'a, T>: Serialize
{}

impl<'a, T> Serialize for BinaryFormatWithoutLength<'a, Option<T>>
    where BinaryFormatWithoutLength<'a, T>: Serialize
{}

error[E0275]: overflow evaluating the requirement `BinaryFormatWithoutLength<'_, std::option::Option<_>>: Serialize`
   |
   = help: consider increasing the recursion limit by adding a `#![recursion_limit = "256"]` attribute to your crate (`xrpl_async`)
note: required for `BinaryFormatWithoutLength<'_, std::option::Option<std::option::Option<_>>>` to implement `Serialize`
  --> src/lib.rs:15:13
   |
15 | impl<'a, T> Serialize for BinaryFormatWithoutLength<'a, Option<T>>
   |             ^^^^^^^^^     ^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^
   = note: 127 redundant requirements hidden
   = note: required for `BinaryFormatWithoutLength<'_, std::option::Option<std::option::Option<std::option::Option<...>>>>` to implement `Serialize`
   = note: the full type name has been written to '/home/porton/Projects/bugs/rust-overflow/target/debug/deps/xrpl_async-97a5b377c31d9cdb.long-type-8508140246639481262.txt'

For more information about this error, try `rustc --explain E0275`.
error: could not compile `xrpl_async` due to previous error

I wrote the code to downstep from Option<T> to T in type arguments, but in a reason that I don't understand, Rust started to add more and more Option<Option<...>>. Why?
A funny thing is that commenting out any of the three last definitions makes the file compile. That's outrageous, have I found a bug in Rust?
rustc 1.67.1 (d5a82bbd2 2023-02-07)


text:
Q: Rails multi level model security I have the need to do the following in Rails to mirror a desktop application:
a User and an Office 'owns' a record, if you don't own the record on a user or office level you're kicked into the public realm.
user gets read,write,delete to the model record
office gets read/write/delete to the model record
other or public gets read/write/delete to the model record
e.g.
UserA owns a model record with read/write/delete
OfficeA owns a model with read/write
other/public gets read
I was wondering if a plugin/gem existed to grant this functionality?

A: You need an authorization framework like cancan or declarative_authorization for that.

A: Good if somewhat old survey of plugins here: http://steffenbartsch.com/blog/2008/08/rails-authorization-plugins/  (last updated 2009)
Sounds like you want one that works at the model level.  So choose one that has a "yes" in the "M" column.

A: I recommend using Grant.  It's an easy to use, though fairly bare-bones, model-level security framework.  I describe in a little more detail in this answer.


text:
Q: USBWebserver Runtime error 75 I am using USBWebserver. I have made the necessary configuration and my php application runs on a my pc. Now I copied the files  to a CD and tried to run it buut I get Run-time error 75
Path/File access error.
I have searched on the interenet for a solution and tried this one but it has not worked for me.


text:
Q: Register certain events on client machine and notify to another C# Please don't get confuse yourself with the title of this question, I don't know what is the exact technical term of what I want to accomplish :). My requirement may be little strange and I already implemented it but I need some best practice/method to do it properly.
Here is my situation.
I am developing a client system monitoring windows application (Tracking software in client side and monitoring software in my system). I have many systems connected to a LAN and I have a monitoring system. If any certain actions happen on client system, I will get notified. I cannot use any databases in my network so what I am doing is, Since my system is also connected to LAN I shared one folder in my system. Whenever some actions happens in client system, Tracking software will create a file containing event to the shared folder in my system. The monitoring software uses a timer which will continuously check for any new files in the shared folder on a certain interval(15 Minutes). If any file found, monitoring system will know some event has happened and will show the event.
But the problem I will get notified only after 15 minutes. Also is I don't think this is the best way. There may be some good and best methods. Is there any way like registering event directly to my Monitoring application from client machine?
Please NOTE: I cannot use any Database for this purpose.
Any suggestions will be appreciated.

A: Take a look at SignalR - it provides real time notification and can be used exactly as you describe.
You would not require a database (but remember if your server isn't running you will miss events - this may or may not be acceptable).

A: Take a look at FileSystemWatcher.  This will monitor directories and raise events.  IME, it works well, but can fail with large amounts of traffic.

A: This sounds like a perfect candidate for MSMQ (MS Message Queue) and Triggers.
Create an MSMQ that all your Tracking Softwares can write to. Then have an MSMQ trigger (perhaps connecting to a front-end through WCF/named pipes) to display an alert in your Monitoring Software

A: You may want to use WCF Framework.
Here is two links that can help you:
wcf-tutorial-events-and-callbacks
wcf-tutorial-basic-interprocess-communication


text:
Q: Naming PDF files in FPDF while generating PDF online on my website I am generating PDFs and emailing it to users , on my website dynamically using FPDF. But the name of the PDFs generated contains slashes and plus signs ( + , / , \ , [ , ] ) etc. due to which the following error occurs :
fopen:( Unable to find the file or directory )

as soon as I remove the slashes and braces , the PDF is generated successfully and emailed too.
Need a solution to deal with the file-names?
The filenames are created dynamically , so it is not in my hand to change them ? So I think I need to first strip off all those special characters from the PDF file name and then send it to FPDF output. But how to do this ?

A: You can urlencode:
 file_put_contents(urlencode('asd#$%21234 /&11 /!@##$$%&&*()_'), 'test');

But then you get strange chars.
Or you just can strip and leave allowed chars
 file_put_contents(preg_replace('/[^A-Za-z0-9_\-]/', '','asd#$%21234 /&11 /!@##$$%&&*()_'), 'test');

A: I think that slashes cannot be used in file name because it is also used to determine file path. For instance a file nammed foo/bar.php is actually a file named bar.php but in foo folder.
A workaround may be to first create foo directory. Then when you ask for "foo/bar.php" file, you'll get bar.php file from foo directory (not tested).
Or you can remove all unwanted characters. For my projects I use this to "normalize" text:
$string = preg_replace('#[^a-z0-9]+#', '-', $string);

A: OWASP ESAPI4PHP library has some very decent sanitizers for file names and other types data.
See also comparison of filename limitations.


text:
Q: Detecting first non silent sample index I have an audio file that I read with [tabread~]). The audio starts with some silence and I am trying to find the first non silent sample index.
I have tried to use [bonk~], [fiddle~] or [sigmund~] but the results were approximate and not constants.
Does anyone have a solution for this? Thanks.
Pascal

A: I already answered this question in the Pure Data forum, but I am copying it here (slightly adapted) in case someone else find it useful:
If the sound completely silent up to the point you marked (that is, is the table filled with zeroes up to that point) then you can simply go through the array's elements using [tabread ], starting at the first sample and checking if the absolute value of the subsequent ones is larger than zero. If the signal is not completely silent but near silent, then you will can either use sort of attack detection (such as [bonk~]) or simply use something like this:
...
|
[tabread array1]
|
{abs]
|
[> 0.001]
|
[sel 1]
|
...

Note how I used [> 0.001] instead of [> 0]. Adjust this number (either directly as an argument or via the rightmost inlet of [>]) to control the sensitivity of the detection. Then once [sel 1] receives a float of value 1, you can use its bang to stop the process since you found your first non-silent element.


text:
Q: Method Overriding: In Extended classes In the following code given, I understand the first part that when i call the c1.show(),it will override only the public and protected part. But I don't understand when i call c2.show(), why it is overriding the pac() as well.
  package P1;

  public class Base {
  private void pri( ) { System.out.println("Base.pri()"); }
          void pac( ) { System.out.println("Base.pac()"); }
  protected void pro( ) { System.out.println("Base.pro()"); }
  public void pub( ) { System.out.println("Base.pub()"); }

       public final void show( ) {
         pri();  pac();  pro();  pub(); }
       }

  package P2;

  import P1.Base;

  public class Concrete1 extends Base {
   public void pri( ) { System.out.println("Concrete1.pri()"); }
   public void pac( ) { System.out.println("Concrete1.pac()"); }
   public void pro( ) { System.out.println("Concrete1.pro()"); }
   public void pub( ) { System.out.println("Concrete1.pub()"); }

    Concrete1 c1 = new Concrete1();
    c1.show( );

Output:
Base.pri()
Base.pac()
Concrete1.pro()
Concrete1.pub()
package P1;

 import P2.Concrete1;

  public class Concrete2 extends Concrete1 {
   public void pri( ) { System.out.println("Concrete2.pri()"); }
   public void pac( ) { System.out.println("Concrete2.pac()"); }
   public void pro( ) { System.out.println("Concrete2.pro()"); }
   public void pub( ) { System.out.println("Concrete2.pub()"); }
  }

   Concrete2 c2 = new Concrete2();
   c2.show( );

Output:
Base.pri()
Concrete2.pac()
Concrete2.pro()
Concrete2.pub()

A: Well, let's go.
In the definition of the class Base, the method pac() has package-private visibility, that is, it's only accessible for classes in the same package. As Concrete1 is not on the same package, it can only override the methods with public/protected visibility.
Concrete2 is at the same package of Base (P1), this explains why it can override pac() and also the difference in the output of the two cases.


text:
Q: What's wrong with this pointer? I though I had finally understood pointers but then I encountered this issue:
typedef struct {
    unsigned int a;
    unsigned int b;
} Bar;

Bar *foo;

foo->a = 3;

This last instruction doesn't work (if I try to access foo->a somewhere else in the code, I either get 0 or rubish)... What am I missing?

A: You need to actually create an object of type Bar and make the pointer foo point to it.
Bar *foo = malloc(sizeof *foo); // Create a new Bar on the heap
foo->a = 3;                     // Now it works

Or alternately, set the pointer to the address of another object:
Bar actualObject;               // Create a new Bar on the stack
Bar *foo = &actualObject;       // Set the pointer to the address of the actual object using '&'
foo->a = 3;                     // Now it works

//NOTE: actualObject.a will also be 3 because it is the same object internally.


text:
Q: Adding babel-polyfill to my webpack file when using an entries object According to Babel polyfill's docs, I'm supposed to add it to my webpack config's entry value like this:
entry: ['babel-polyfill', './app/js']

However I specify my entry values with an object instead of an array:
entry: { app: './client' }

How should I add babel-polyfill?

A: You can use an array as the value of entry.app:
entry: { app: [ "babel-polyfill", "./client" ] }

For details see webpack's documentation of the entry option. webpack 2 should behave the same way according to its documentation.

A: You can create multiple entries with object notation, for example:
  entry: {
    polyfill: resolve('src', 'config', 'polyfill.js'),
    vendor: resolve('src', 'config', 'vendor.js'),
    app: resolve('src', 'index.js')
  },

It is better to use separate entry for babel-polyfill because you may want to use babel-preset-env with useBuiltIns option:

This option enables a new plugin that replaces the statement import "babel-polyfill" or require("babel-polyfill") with individual requires for babel-polyfill based on environment.


text:
Q: Clicking "Done" on keyboard to dismiss keyboard, but it will not be dismissed I am trying to dismiss the keyboard by clicking the "Done" button but it will not be dismissed. Here is what I have done so far:
I have also added protocol UITextFieldDelegate.
override func viewDidLoad() {
    super.viewDidLoad()

    texts.layer.cornerRadius = 10
    texts.delegate = self
    texts.keyboardType = .numbersAndPunctuation
    texts.returnKeyType = .done
}

func textFieldShouldReturn(textField: UITextField!) -> Bool {   //delegate method
    var number = CGFloat((texts.text! as NSString).floatValue)

    slide.setValue(Float(number), animated: true)

    textField.resignFirstResponder()

    return true
}

I want it to dismiss so that entered value can be stored in the number variable and the app can move on.

A: Setting .endEditing to true should do the trick
func textFieldShouldReturn(_ textfield: UITextField) -> Bool {
    self.view.endEditing(true)
    return false
}

A: Most likely your textFieldShowReturn isn't being called since it has the wrong signature. Some quick use of the debugger (or a print statement) will confirm.
It should be:
func textFieldShouldReturn(_ textField: UITextField) -> Bool {
    // your code here
}

Note the _ for the parameter label.


text:
Q: Field error proc with field name in error rails I am trying to add field errors in rails with field_error_proc. But I could not find a way to add the error with the field name. Below is the code that I am using to generate a field with errors in rails.
ActionView::Base.field_error_proc = proc do |html_tag, instance|
  if html_tag =~ /^<label/
    %(#{html_tag}).html_safe
  else
    %(#{html_tag}

#{instance.error_message.first}

).html_safe
  end
end

below is the output of the above code. What I want is to have an error with field name like "Email is required" so as to have the common pattern for error(same as FE validation error)

This is the output of the FE validation.

A: If you display the content of your instance block argument you should see something like this:
#<ActionView::Helpers::Tags::TextField:0x00007f54102118d8 @method_name="email", @object_name="user" # ...(more)

So in order to get the method name of the validated input you could use:
ActionView::Base.field_error_proc = proc do |html_tag, instance|
  method_name = instance.instance_variable_get("@method_name").humanize
  if html_tag =~ /^<label/
    %(#{html_tag}).html_safe
  else
    %(#{html_tag}

#{method_name} #{instance.error_message.first}

).html_safe
  end
end


text:
Q: GetResource returning null depending on file separator I have the following code.
URL resourcePath = this.getClass().getResource( File.separator + folder);
Objects.requireNonNull(resourcePath, "Path must not be null.");

Running on Windows, File.separator is giving me "\", when using "\" + folder, the getResource method returns null, using "/" + folder works correctly.


text:
Q: NoSuchMethod Error while using Exposed with H2 I'm trying to used exposed and h2 for storage inside a ktor server.
After setting up an in memory connection with Database.connect("jdbc:h2:mem:test", driver = "org.h2.Driver")
Whenever I try to read/write to the database I get the following error:

java.lang.NoSuchMethodError:
org.h2.jdbc.JdbcConnection.getSettings()Lorg/h2/jdbc/JdbcConnection$Settings;
at org.jetbrains.exposed.sql.vendors.H2Kt.isMySQLMode(H2.kt:17)

My build.gradle.kts contains the following:
implementation("com.h2database", "h2", "1.4.197")
implementation("org.jetbrains.exposed", "exposed-core", "0.24.1")
implementation("org.jetbrains.exposed", "exposed-dao", "0.24.1")
implementation("org.jetbrains.exposed", "exposed-jdbc", "0.24.1")

Any ideas?

A: As pointed out by Evgenij Ryazanov in the comments above, turns out this is an issue with my the combination of versions i'm using.
As a temporary fix I've updated my H2 version to 1.4.200


text:
Q: Kotlin wait for async with coroutine I would like to open a new activity when phoneViewModel and ScanViewModel are instantiated. They are instantiated by calling an async function InitialRead(). I'm logging each step, atm they are logged as done3 => done2 => done1
I would like to have them in this order:
done1 => done2 => done3
I have following code:
class MainBusinessActivity : AppCompatActivity() {

private lateinit var scanViewModel: ScanViewModel
private lateinit var phoneViewModel: PhoneViewModel

override fun onCreate(savedInstanceState: Bundle?) {
    super.onCreate(savedInstanceState)
    setContentView(R.layout.activity_main_business)
}

private fun startEntitySetListActivity() = GlobalScope.async {
    val sapServiceManager = (application as SAPWizardApplication).sapServiceManager
    sapServiceManager?.openODataStore {
        phoneViewModel =  ViewModelProvider(this@MainBusinessActivity).get(PhoneViewModel::class.java).also {it.initialRead{Log.e("done", "done1")}}
        scanViewModel = ViewModelProvider(this@MainBusinessActivity).get(ScanViewModel::class.java).also {it.initialRead{Log.e("done", "done2")}}
    }
}

override fun onResume() {
    super.onResume()
    //startEntitySetListActivity()
    runBlocking {
        startEntitySetListActivity().await()
        val intent = Intent(this@MainBusinessActivity, HomeActivity::class.java)
        intent.addFlags(Intent.FLAG_ACTIVITY_NEW_TASK or Intent.FLAG_ACTIVITY_CLEAR_TASK)
        Log.e("done", "done3")
        startActivity(intent)
    }
}

}
What am I doing wrong? Can someone correct my code?

A: Never use runBlocking in an Android app. runBlocking completely defeats the purpose of using coroutines, and can lead to an ANR. You also probably should never use GlobalScope, which leads to UI leaks. You might possibly need it for some kind of long-running task that doesn't make sense to put in a service but doesn't have dependency on any UI components, but I can't think of any examples
You also shouldn't be instantiating your ViewModels in the background. That should be done in onCreate().
Make this function a suspend function, and it can break down the two tasks in the background simultaneously before returning.
Start your coroutine with lifecycleScope.
Assuming sapServiceManager?.openODataStore is an asynchronous task that takes a callback, you will need to wrap it in suspendCoroutine.
override fun onCreate(savedInstanceState: Bundle?) {
    super.onCreate(savedInstanceState)
    setContentView(R.layout.activity_main_business)
    phoneViewModel = ViewModelProvider(this@MainBusinessActivity).get(PhoneViewModel::class.java)
    scanViewModel = ViewModelProvider(this@MainBusinessActivity).get(ScanViewModel::class.java)
}

private suspend fun startEntitySetListActivity() = coroutineScope {
    val sapServiceManager = (application as SAPWizardApplication).sapServiceManager
    sapServiceManager ?: return
    suspendCoroutine<Unit> { continuation ->
        sapServiceManager.openODataStore { continuation.resume(Unit) }
    }
    listOf(
        launch {
            phoneViewModel.initialRead{Log.e("done", "done1")}
        },
        launch {
            scanViewModel.initialRead{Log.e("done", "done2")}
        }
    ).joinAll()
}

override fun onResume() {
    super.onResume()
    lifecycleScope.launch {
        startEntitySetListActivity()
        val intent = Intent(this@MainBusinessActivity, HomeActivity::class.java)
        intent.addFlags(Intent.FLAG_ACTIVITY_NEW_TASK or Intent.FLAG_ACTIVITY_CLEAR_TASK)
        Log.e("done", "done3")
        startActivity(intent)
    }
}


text:
Q: Compare two file_csv using pandas DataFrame to find the difference and join F2 into F1 I need help to resolve this problem. If anyone has an idea to create a script using panda DataFrame with python3:
I have two CSV dataset files too long to fit into panda DataFrame display. They have the following structure:
F1:
   gene disease
0  g1   d1
1  g1   d2
2  g1   d3
3  g2   d2
4  g2   d3
5  g2   d4
6  g3   d2
7  g3   d4
8  g4   d1
9  g4   d3

F2:
  gene  phenotype
0  g1   ph1
1  g1   ph2
2  g2   ph2
3  g2   ph3
4  g2   ph4
5  g3   ph4
6  g4   ph1
7  g4   ph3
8  g5   ph4
9  g6   ph2

g= gene_name(strig, interger, Float), d = disease_name(string) ph= phenotype
The main goal is to compare all the genes in F2 with the genes in F1, and if they equal, append the name of gene and the phenotype associated to the disease in order to get an output file F3 containing all the diseases associated to phenotype by genes.
This is the expected output:
gene disease phenotype
g1   d1      ph2
g1   d2      ph2
g2   d2      ph1
g2   d3      ph2
ect.

Can anybody help me create the script? Any help would be much appreciated. Thanks!

A: You have a 1 to many relationship between the gene and phenotype and a one to many relationship between the gene and disease. If you join on gene, there will be a many to many. See Example output. Is this what you are looking for?
data = [
    ["g1", "d1"],
    ["g1", "d2"],
    ["g1", "d3"],
    ["g2", "d2"],
    ["g2", "d3"]
]
f1 = pd.DataFrame(data, columns={"gene", "disease"})

data = [
    ["g1", "ph1"],
    ["g1", "ph2"],
    ["g2", "ph2"],
    ["g2", "ph3"]
]
f2 = pd.DataFrame(data, columns={"gene", "phenotype"})

f1.merge(f2)

idx gene disease phenotype
0   g1  d1  ph1
1   g1  d1  ph2
2   g1  d2  ph1
3   g1  d2  ph2
4   g1  d3  ph1
5   g1  d3  ph2
6   g2  d2  ph2
7   g2  d2  ph3
8   g2  d3  ph2
9   g2  d3  ph3


text:
Q: How to access Google Drive appdata folder file with Flutter? I have this very old Android project that I haven't touched for a long while.
It stores some user data on the users Google Drive appdata folder.
Now I'm updating the app to a Flutter version and since Google Drive API is being deprecated, there's no plugin for Flutter, I believe I need to use googleapi for that now. But I can't find much regarding my problem for flutter.
I got to the point of signing in with google_sign_in: ^4.0.7
GoogleSignIn _googleSignIn = GoogleSignIn(
    scopes: [
      'email',
      'https://www.googleapis.com/auth/drive.appdata',
      'https://www.googleapis.com/auth/drive.file',
    ],
  );
  try {
    GoogleSignInAccount account = await _googleSignIn.signIn();
  } catch (error) {
    print(error);
  }

That works fine, but I got stuck there. How can I go from there and read a file inside the appdata folder on the user's Google Drive?
EDIT1: This answer helped, I managed to get the httpClient but I'm still stuck on how to get the appdata folder and its files How to use Google API in flutter?
It seems that googleapi doesn't support the appfolder since Google MAY be deprecating it in the future (seems like they already did it) in order to force us to pay for storage using firebase. Ok, fine, but how do I migrate it if I can't access the folder via googleapi? If I reset my app now and my users lose all their data I'll lose the few users I have...

A: The following works for me, (using the http package for get and post)
Auth Token
You can retrieve the auth token from the accoutn returned by signIn.
Future<String> _getAuthToken() async {
  final account = await sign_in_options.signIn();
  if (account == null) {
    return null;
  }
  final authentication = await account.authentication;
  return authentication.accessToken;
}

Search
To search files in the AppData directory you need to add the spaces queryParameters and set it to appDataFolder. The documentation is kind of misleading on that part.
final Map<String, String> queryParameters = {
  'spaces': 'appDataFolder',
  // more query parameters
};
final headers = { 'Authorization': 'Bearer $authToken' };
final uri = Uri.https('www.googleapis.com', '/drive/v3/files', queryParameters);
final response = await get(uri, headers: headers);

Upload
To upload a file you need to set the parents to appDataFolder property of the body for the initial upload request. To download the file you only need the fileId.
final headers = { 'Authorization': 'Bearer $authToken' };
final initialQueryParameters = { 'uploadType': 'resumable' };
final Map<String, dynamic> metaData = {
  'name': fileName,
  'parents': ['appDataFolder ']
};
final initiateUri = Uri.https('www.googleapis.com', '/upload/drive/v3/files', initialQueryParameters);
final initiateResponse = await post(initiateUri, headers: headers, body: json.encode(metaData));
final location = initiateResponse.headers['location'];

Download
To download the file you only need to know the fileId, if you don't know it you need to use the search API to retrieve it (see above).
final headers = { 'Authorization': 'Bearer $authToken' };
final url = 'https://www.googleapis.com/drive/v3/files/$fileId?alt=media';
final response = await get(url, headers: headers);


text:
Q: SQLAlchemy - Self referential Many-to-many relationship with extra column I have a model representing user and I want to create a relationship between users representing that they are friends. My functional model with association table and methods to list all the friends look like this
friendship = db.Table('friend',
    db.Column('id', db.Integer, primary_key=True),
    db.Column('fk_user_from', db.Integer, db.ForeignKey('user.id'), nullable=False),
    db.Column('fk_user_to', db.Integer, db.ForeignKey('user.id'), nullable=False)
)

class User(db.Model):
   ...
   ...
   friends = db.relationship('User',
        secondary=friendship,
        primaryjoin=(friendship.c.fk_user_from==id),
        secondaryjoin=(friendship.c.fk_user_to==id),
        backref = db.backref('friend', lazy = 'dynamic'),
        lazy = 'dynamic')

    def list_friends(self):
        friendship_union = db.select([
                        friendship.c.fk_user_from,
                        friendship.c.fk_user_to
                        ]).union(
                            db.select([
                                friendship.c.fk_user_to,
                                friendship.c.fk_user_from]
                            )
                    ).alias()
        User.all_friends = db.relationship('User',
                       secondary=friendship_union,
                       primaryjoin=User.id==friendship_union.c.fk_user_from,
                       secondaryjoin=User.id==friendship_union.c.fk_user_to,
                       viewonly=True)
        return self.all_friends

The problem is that I need to implement asking for frienship and status pending before confirmation (just like you know it from Facebook) so it is necesarry to add an extra column to the frienship table. According to the SQLAlchemy tutorial I should create an Association Object but how to make it self referential again?
Or is it possible to just add this column to my current frienship table and access and change the status value there somehow?
Thanks

A: All you need is to add primaryjoin in your table and also making two foreignkey in table of Friendship, 'primary_key' too. you also need to make friendship as a class.
class Friendship(db.Model):
    __tablename__ = 'friend'
    fk_user_from = db.Column(db.Integer, db.ForeignKey('user.id'), primary_key=True)
    fk_user_to = db.Column(db.Integer, db.ForeignKey('user.id'), primary_key=True)
    extra_field = db.Column(db.Integer)

class User (db.Model):
    __tablename__ = 'user'
    id = db.Column(db.Integer, primary_key=True)
    user_to = db.relationship('Friendship',backref='to', primaryjoin=id==Friendship.fk_user_to)
    user_from = db.relationship('Friendship',backref='from', primaryjoin=id==Friendship.fk_user_from )

And to add a friend you need to define Friendship like:
friend = Friendship(extra_field=0 , to=me , from=my_friend)

A: I have answered to a similar question that solves Self-referential many-to-many relationship with Association Object.
See https://stackoverflow.com/a/62281276/9387542
Also, if you solely looking for establing a frienship model, I suggest you to establish Many-to-many relationship with the model from https://stackoverflow.com/a/7317251/9387542