text:
Q: Data not adding to SQL Server 2008 using ASP.net & VB as code behind file I've looked around StackOverflow and also a number of other websites, I found some code to put this together:
Imports System.Data
Imports System.Data.SqlClient
Partial Class _Default
Inherits System.Web.UI.Page

  Dim sqlConnection As SqlConnection
  Dim sqlCommand As SqlCommand
  Dim sqlString, iName, iDescription As String
  Dim iQuantity As Integer
  Dim iPrice As Decimal

  Protected Sub cmdAddStock_Click(ByVal sender As Object, ByVal e As System.EventArgs)
  Handles cmdAddStock.Click

    iName = txtItemName.Text
    iDescription = txtDescription.Text
    iQuantity = txtQuantity.Text
    iPrice = txtPrice.Text

    Using myConnection As New SqlConnection("Server=localhost;Database=BBBLeeds;
    Trusted_Connection=True")
        myConnection.Open()

        sqlCommand = New SqlCommand("INSERT INTO tblItem(ItemName, Description,
        Price, Stock) values('" + iName + "','" + iDescription + "','" + iPrice +
        "','" + iQuantity + "')")

        sqlCommand.ExecuteNonQuery()
        myConnection.Close()
        Response.Redirect(Request.RawUrl, True)
    End Using
End Sub
End Class

The error which comes back is as follows:
"Conversion from string "INSERT INTO tblItem(ItemName, De" to type 'Double' is not valid."
This is the data structure with SQL:
http://i23.photobucket.com/albums/b368/Damo115/Untitled.png
Thanks for any advice you can provide.

A: Change your code to do this, this will avoid any sql injections and you don't have to deal with concatenation and adding quotes around values.
In your table price is money datatype and Stock is int but you are sending values as string by adding single quotes around them.
sqlCommand = New SqlCommand("INSERT INTO tblItem(ItemName, Description,
        Price, Stock) values(@item,@descr,@price,@stock)")

sqlCommand.Parameters.AddWithValue("@item",iName)
sqlCommand.Parameters.AddWithValue("@descr",iDescription)
sqlCommand.Parameters.AddWithValue("@price",iPrice)
sqlCommand.Parameters.AddWithValue("@stock",iQuantity)

sqlCommand.ExecuteNonQuery()

A: You pass in a string parameter (txtPrice.Text) as a number (the db column Price is a number). You need to covert your string to the number first.

A: You should be using the & operator rather than the + operator to concatenate strings
sqlCommand = New SqlCommand("INSERT INTO tblItem(ItemName, Description,
        Price, Stock) values('" & iName & "','" & iDescription & "','" + iPrice &
        "','" & iQuantity & "')")


text:
Q: How to embed a matplotllib histogram onto a tkinter GUI? I have this program that creates a histogram from a list of medians from randomly generated numbers within specific parameters (upper limit, sample size). How can I make it so that the histogram that is created appears in the tkinter GUI, right above the scale? I've looked everywhere and still can't figure it out. Thanks in advance! I am using python 3.
Bonus question (no need to answer but if you would like to it would help a ton): How would I make it so that the scale controls the value of number_lists (which is basically the number of  times a median is generated) and then updates the histogram's appearance by adding the new calculated median?
import random
import matplotlib, sys
matplotlib.use('TkAgg')
from matplotlib.backends.backend_tkagg import FigureCanvasTkAgg, NavigationToolbar2TkAgg
from matplotlib.figure import Figure
import matplotlib.pyplot as plt
import matplotlib.mlab as mlab
import numpy as np
from tkinter import *
from tkinter import ttk

#root
root = Tk()
root.title("Sample Size and the Normal Distribution")

#mainframe
mainframe = ttk.Frame(root, padding = "3 3 12 12")
mainframe.grid(column=0, row=0, sticky=(N, W, E, S))
mainframe.columnconfigure(0, weight=1)
mainframe.rowconfigure(0, weight=1)

def create_list(sampleSize, upperLimit):
    numbList = []
    sampleSize = int(sample.get())
    upperLimit = int(upper.get())
    while sampleSize > 0:
        sampleSize -= 1
        randomNum = random.randrange(0,upperLimit+1)
        numbList.append(randomNum)
    numbList.sort(key=int)
    return numbList

def medians_variance(median_list):
    sum_of_medians = sum(median_list)
    variance = sum_of_medians / len(median_list)
    return variance

def median(numbList):

        srtd = sorted(numbList)
        mid = len(numbList)//2
        if len(numbList) % 2 == 0:
            return (srtd[mid-1] + srtd[mid]) / 2.0
        else:
            return srtd[mid]

def main():

    number_lists = 10
    lists = []
    median_list = []

    binsize = 10

    for i in range(number_lists):
        lists.append(create_list(sampleSize, upperLimit))

    for current_list in lists:
        current_median = median(current_list)
        median_list.append(current_median)
        median_list.sort(key=float)

    plt.hist(median_list, binsize)

    plt.xlabel('Median Value', fontsize = 15)
    plt.ylabel('Frequency', fontsize = 15)

    plt.show()

    med = median(median_list)
    std = np.std(median_list)
    var = (std**2)

#sampleSize Entry
sample = StringVar()
sampleSize = ttk.Entry(mainframe, width = 7, textvariable = sample)
sampleSize.grid(column = 2, row = 1, sticky =(W, E))

#upperLimit Entry
upper = StringVar()
upperLimit = ttk.Entry(mainframe, width = 7, textvariable = upper)
upperLimit.grid(column = 2, row = 3, sticky = (W, E))

#binsize Entry
Bin = StringVar()
binsize = ttk.Entry(mainframe, width = 7, textvariable = Bin)
binsize.grid(column = 2, row = 5, sticky = (W, E))

#sampleSize and upperLimit Labels
ttk.Label(mainframe, text="Sample Size ").grid(column = 1, row = 1, sticky = W)
ttk.Label(mainframe, text="Upper Limit ").grid(column = 1, row = 3, sticky = W)
ttk.Label(mainframe, text="Bin Size").grid(column = 1, row = 5, sticky = W)

#histogram embed
f = Figure(figsize = (5,4), dpi=100)

#button for new histogram
button = ttk.Button(mainframe, text="New Histogram", command=main).grid(column=1, row=7, sticky=W)

#scale
scale = Scale(mainframe, from_=0, to=10, orient=HORIZONTAL,length=400).grid(column = 5, row = 12, sticky= S)

for child in mainframe.winfo_children(): child.grid_configure(padx=5, pady=5)

sampleSize.focus()
upperLimit.focus()
root.bind('<Return>', main)

root.mainloop()

A: Create a FigureCanvasTkAgg object and put it inside the frame:
f = Figure(figsize=(5,4), dpi=100)
canvas = FigureCanvasTkAgg(f, master=mainframe)
canvas.get_tk_widget().grid(row=1, column=3, rowspan=6)

In the main, instead of using plt, use Figure object f:
p = f.gca()
p.hist(median_list, binsize)
p.set_xlabel('Median Value', fontsize = 15)
p.set_ylabel('Frequency', fontsize = 15)
canvas.show()

BTW, slide grid was slightly modified to get above result:
scale = Scale(mainframe, from_=0, to=10, orient=HORIZONTAL,length=400)
scale.grid(column=3, row=12, sticky=S)

redpajama_set_name: RedPajamaStackExchange


text:
Q: Load programs using CreateProcess Hi I have a function that makes CreateProcess load programs in this case try to upload a file with the path c: /test.mp3 c: /test.exe, I try to load my program console but never loaded programs
The code:
program test;

{$APPTYPE CONSOLE}
{$R *.res}

uses
  System.SysUtils, ShellApi, Windows;

procedure cargar(ProgramName: String; Wait: Boolean);
var
  StartInfo: TStartupInfo;
  ProcInfo: TProcessInformation;
  CreateOK: Boolean;
begin
  { fill with known state }
  FillChar(StartInfo, SizeOf(TStartupInfo), #0);
  FillChar(ProcInfo, SizeOf(TProcessInformation), #0);
  StartInfo.cb := SizeOf(TStartupInfo);
  CreateOK := CreateProcess(nil, PChar(ProgramName), nil, nil, False,
    CREATE_NEW_PROCESS_GROUP + NORMAL_PRIORITY_CLASS, nil, nil, StartInfo,
    ProcInfo);
  { check to see if successful }
  if CreateOK then
  begin
    // may or may not be needed. Usually wait for child processes
    if Wait then
      WaitForSingleObject(ProcInfo.hProcess, INFINITE);
  end
  else
  begin
    // ShowMessage('Unable to run '+ProgramName);
  end;

  CloseHandle(ProcInfo.hProcess);
  CloseHandle(ProcInfo.hThread);
end;

begin
  try

    cargar('c:/test.mp3', True);

  except
    on E: Exception do
      Writeln(E.ClassName, ': ', E.Message);
  end;

end.

What am I doing wrong?

A: If you implement error checking (for example by calling RaiseLastOSError on failure), then Windows will tell you what is wrong: 'System Error.  Code: 193. %1 is not a valid Win32 application'.
You cannot use CreateProcess in order to launch an mp3 file directly. You'd have to launch a player application with the mp3 file as command line argument.


text:
Q: System.MissingMethodException: Method not found: 'Microsoft .FSharp.Core.FSharpFunc`2 I've got a problem when launching a Canopy test in a Windows box:
Unhandled Exception: System.MissingMethodException: Method not found: 'Microsoft
.FSharp.Core.FSharpFunc`2<System.String,System.String> canopy.core.get_xpath()'.
at <StartupCode$UITest>.$Program.main@()

I guess this is because when compiling it, my Visual Studio 2012 restored Nuget packages and spitted this in the console output:
Consider app.config remapping of assembly "FSharp.Core, Culture=neutral, PublicKeyToken=b03f5f7f11d50a3a" from Version "4.3.0.0" [C:\Program Files (x86)\Reference Assemblies\Microsoft\FSharp\3.0\Runtime\v4.0\FSharp.Core.dll] to Version "4.4.0.0" [C:\Users\Andres\Documents\Code\endtoendtests\packages\FSharp.Core.4.0.0.1\lib\net40\FSharp.Core.dll] to solve conflict and get rid of warning.
C:\Windows\Microsoft.NET\Framework\v4.0.30319\Microsoft.Common.targets(1605,5): warning MSB3247: Found conflicts between different versions of the same dependent assembly.
C:\Program Files (x86)\Microsoft SDKs\F#\3.0\Framework\v4.0\fsc.exe -o:obj\x86\Debug\UITest.exe -g --noframework --define:DEBUG --optimize- --tailcalls- --platform:x86 -r:C:\Users\Andres\Documents\Code\endtoendtests\packages\canopy.0.9.52\lib\canopy.dll -r:C:\Users\Andres\Documents\Code\endtoendtests\packages\FSharp.Core.4.0.0.1\lib\net40\FSharp.Core.dll -r:"C:\Program Files (x86)\Reference Assemblies\Microsoft\Framework\.NETFramework\v4.0\mscorlib.dll" -r:"C:\Program Files (x86)\Reference Assemblies\Microsoft\Framework\.NETFramework\v4.0\System.Core.dll" -r:"C:\Program Files (x86)\Reference Assemblies\Microsoft\Framework\.NETFramework\v4.0\System.dll" -r:"C:\Program Files (x86)\Reference Assemblies\Microsoft\Framework\.NETFramework\v4.0\System.Drawing.dll" -r:"C:\Program Files (x86)\Reference Assemblies\Microsoft\Framework\.NETFramework\v4.0\System.Numerics.dll" -r:C:\Users\Andres\Documents\Code\endtoendtests\packages\Selenium.WebDriver.2.53.0\lib\net40\WebDriver.dll --target:exe --warnaserror:76 --vserrors --validate-type-providers --LCID:1033 --utf8output --fullpaths --flaterrors --highentropyva- "C:\Users\Andres\AppData\Local\Temp\.NETFramework,Version=v4.0.AssemblyAttributes.fs" AssemblyInfo.fs Program.fs
UITest -> C:\Users\Andres\Documents\Code\endtoendtests\UITest\bin\Debug\UITest.exe

How to exactly add this remapping to fix this problem?

A: Managed to get it to work with this App.config:
<?xml version="1.0" encoding="utf-8"?>
<configuration>
  <runtime>
    <assemblyBinding xmlns="urn:schemas-microsoft-com:asm.v1">
      <dependentAssembly>
        <assemblyIdentity name="FSharp.Core" publicKeyToken="b03f5f7f11d50a3a" culture="neutral"/>
        <bindingRedirect oldVersion="4.3.0.0" newVersion="4.4.0.0"/>
      </dependentAssembly>
    </assemblyBinding>
  </runtime>
</configuration>

This must be because I've never installed F#, so that I'm using the version that comes with my VS2012 (v3.0). I know I know, I should upgrade to 3.1, or 4.0 even.


text:
Q: I show the user's email on my web page but when I pull this page on mobile, it sometimes shows sometimes not I have a page where the user's email would be shown. When I log onto the page on PCs, it always works, but on my mobile, sometimes the email is shown sometimes it is not.
Please see below as my code.
I have installed a plugin where I can write php in html environment.

Please confirm your email address, and the results will display shortly

<input name="email" required="" type="radio" value="<?php global $current_user;
get_currentuserinfo();
echo $current_user->user_email;
?>" /><?php global $current_user;
get_currentuserinfo();
echo "  " . $current_user->user_email . "\n";
?>
<input type="submit" />

A: Well I don't know if you plan on add more inputs on your form later on. But I'd recommend a responsive design to make sure that it will look good on all devices.
You can use a stylesheet or create one of your own.
This link has some examples: http://www.w3schools.com/html/html_responsive.asp


text:
Q: How can I reduce the speed of sound playing on Iphone using Objective C I have an mp3 that I want to play slowly without altering the pitch. Is there a way to do it? I can convert into other forms, if I can do it in other forms. This is for a iPhone app that I am developing.
Thanks

A: A time-pitch modification/stretching algorithm or library could be used for this.  You could develop some DSP analysis/resynthesis code for a phase vocoder, a PSOLA pitch corrector, or use a commecial library such as Dirac.
See the stackoverflow question: iPhone voice changer for some other answers to a similar question.


text:
Q: a mathematical problem on inequalities If $a,b,c,d$ are positive real numbers such that $a+b+c+d=1$,show that
$$  \frac{a^3}{b + c} + \frac{b^3}{c + d} + \frac{c^3}{d + a} + \frac{d^3}{a + b} > \frac 1 8$$

A: By Cauchy-Schwarz Inequality, we have$$\left(\sum_{cyc} \frac{a^3}{b + c} \right)\cdot \sum_{cyc}(b+c) \ge (a^{3/2}+b^{3/2}+c^{3/2}+d^{3/2})^2$$
So it is sufficient to show that $a^{3/2}+b^{3/2}+c^{3/2}+d^{3/2} \ge \frac12$.
But we have from Power Means inequality,
$$\left(\frac{a^{3/2}+b^{3/2}+c^{3/2}+d^{3/2}}{4}\right)^{2/3}\ge \frac{a+b+c+d}{4}=\frac14 \implies a^{3/2}+b^{3/2}+c^{3/2}+d^{3/2} \ge \frac12$$
Equality is attained when $a=b=c=d=\frac14$.


text:
Q: Extend C# file based resource manager I want to store my resources in a different file format than NET's  .resources (in particular, .po), so I wrote a custom resource set with a custom resource reader to retrieve them. I created a ResourceManager using the CreateFileBasedResourceManager static method which creates a new instance of the manager that retrieves resource sets from files in a specific dir, using the specified resource set (the custom one I wrote in my case), using Name.culture.resources filenames.
However, I would like to change the filename convention. I noticed there is an overridable GetResourceFileName method for precisely that purpose. But using reflector I noticed that the constructor used by CreateFileBasedResourceManager is private, and it is impossible to set the "use files instead of assemblies" flag otherwise.
Is there any way to go around this, without needing to reimplement the whole InternalGetResourceSet method?
Thanks a lot!

A: Mono has good little utility that helps with this, its called Msgfmt, which can be used to create .resources files out of .po files directory.
Msgfmt.exe -iMessages.es.po -oMessages.es.resources

I came across an interesting article @ http://weblogs.manas.com.ar/spalladino/2009/10/01/using-gnu-gettext-for-i18n-in-c-and-asp-net/ which helped me and it might well help you too..
Its a different approach but it worked for me!

*

*ref:   http://www.mono-project.com/I18nGettext

*ref: http://www.mono-project.com/I18N_with_Mono.Unix


text:
Q: Return top three transaction on the basis of amount? I have a table transaction(id, quantity, rate, stock_code, user_code), and I want to generate the top three transactions on the basis of their amount in descending order. Amount = quantity * rate
Is there a way to generate using only sql?

A: Yes it's possible:
SELECT id, quantity * rate as amount, stock_code, user_code
FROM transaction
ORDER BY 2 DESC
LIMIT 3;


text:
Q: Passing Function Pointers to Functions, c++ I am trying to get a function to call another function through a pointer, I have gone through some posts and have tried doing it but I keep getting errors.
Print is the function that I want apply to call. Apply should print all the data when print is called.
I get the error: Variable has incompatible type void
      void print(double x) //function I want to pass
{
cout << x << endl;
}

void apply(vector<double> data, void (*f)(double))
    { //function with pointer to other function print
           for(int i = 0; i< data.sizeof(); i++)
               f(data[i]);
        }

A: It should work with the whole code below:
#include <iostream>
#include <vector>

using namespace std;

void print(double x) //function I want to pass
{
    cout << x << endl;
}

void apply(const vector<double>& data, void (*f)(double))
{ //function with pointer to other function print
    for(size_t i = 0; i< data.size(); i++)
        f(data[i]);
}

void test()
{
    vector<double> data;
    data.push_back(1.0);
    data.push_back(2.0);
    data.push_back(3.0);

    apply(data, print);
}

A: I would suggest to clamp to std::function or use and auto for such job:
void apply(const vector<double>& data, std::function<void(double)> f)
{ //function with pointer to other function print
    for(size_t i = 0; i< data.size(); i++)
        f(data[i]);
}

or
void apply(const vector<double>& data, auto f)
{ //function with pointer to other function print
    for(size_t i = 0; i< data.size(); i++)
        f(data[i]);
}

Using auto will depend on the compiler since this usage is only available after c++14 standard.

A: You want something like:
void apply(const vector<double>& data, void (*f)(double) ) {
   for( int i=0; i<data.size(); ++i )
       f(data[i]);
}

A: I don't see exactly what the error is. Your code seems to work (C++11):
#include <iostream>
#include <vector>

using namespace std;

void print(double x) //function I want to pass
{
    cout << x << endl;
}

void apply(const vector<double>& data, void (*f)(double)) { //function with pointer to other function print
    for (size_t i = 0; i < data.size(); i++)
        f(data[i]);
}

int main() {
    vector<double> v{1.1, 2.2, 3.3, 4.4, 5.5, 6.6, 7.7, 8.8, 9.9};
    apply(v, print);

    return 0;
}

Result:
1.1
2.2
3.3
4.4
5.5
6.6
7.7
8.8
9.9

RUN FINISHED; exit value 0; real time: 0ms; user: 0ms; system: 0ms

The only changes I made were:

*

*change data.sizeof() to data.size(), but I think you would have figured that already (a vector does not have a public member function called sizeof())

*not necessary to make it work, but good practice: the first parameter for apply is (in general) best declared as const vector<double>& data. That is you pass a reference to a data type/structure that won't be modified (for memory consuming objects that is expected to be more efficient)


text:
Q: Excel VBA Workbooks.open with optional parameters I'm sure this is a very basic question that has a very basic answer but so far I can't make my Excel macro work.
I am trying to open an Excel workbook and input the optional password parameter. However, whenever I do this, I get the error Compile error expected: Named Parameter.
This is my current code
Sub password_opening_test()
Workbooks.Open Filename:="E:\password protecting macrotest.xlsx",,,,Password:="test"
Range("G7").Select
ActiveCell.FormulaR1C1 = "hello"
ActiveWorkbook.Save
ActiveWindow.Close
End Sub

I've also tried it by adding square brakets in between the commas but I still recieve the error (which is highlighted by the first comma).
Thanks very much for reading

A: I think there are two options available:

*

*As Scott details in his comment - get rid of your commas

2.
Just use the arguments in their correct positions
Sub password_opening_test()
  Workbooks.Open "E:\password protecting macrotest.xlsx",,,,"test"
  Range("G7").Select
  ActiveCell.FormulaR1C1 = "hello"
  ActiveWorkbook.Save
  ActiveWindow.Close
End Sub

For the record I prefer Scott's approach as it is much more readable in future re-visits to the code. I like to use line seperators so it looks like this:
Sub password_opening_test()
  Workbooks.Open _
      Filename:="E:\password protecting macrotest.xlsx", _
      Password:="test"
  Range("G7").Select
  ActiveCell.FormulaR1C1 = "hello"
  ActiveWorkbook.Save
  ActiveWindow.Close
End Sub


text:
Q: IonSearchbar getInputEtlement how to set attribute disabled? I am working in ionic v4 and
I have 2 ion-searchbars when clicked on the second one I want to disable the first search-bar.
I have red in the docs that you could get the native element with the following code:
@ViewChild('searchbar') searchbar: IonSearchbar;

ngOnInit() {
    const elem = this.searchbar.getInputElement;
    console.log(elem);
    // google.maps.places.Autocomplete(elem);
}

But how to I disable that native input element?

A: <ion-searchbar #searchbar1 (ionFocus)="ionFocus()"></ion-searchbar>
<ion-searchbar #searchbar2 ></ion-searchbar>

  @ViewChild('searchbar1') searchbar1: IonSearchbar;

  @ViewChild('searchbar2') searchbar2: IonSearchbar;

  ionFocus(): void {
    this.searchbar2.getInputElement().then( data => {
      data.disabled = true
      console.log(data.disabled = true);
    });
  }


text:
Q: Рисование произвольных фигур на графике OxyPlot с помощью готовой библиотеки WPF DrawTools Добрый день, хочу совместить две готовые библиотеки, только не понятно как это можно сделать. Буду признателен за разного рода идеи.
Есть небольшая готовая реализация задуманного
Репозиторий
Но возникает несколько проблем, как заставить наложенный Canvas прокручиватся вместе с графиком OxyPlot когда добавляются новые точки?
Спасибо.


text:
Q: Unable to start Shiny server I've hosted shiny-server on DigitalOcean Ubuntu 14.04.5 droplet with nginx.
Shiny server was working fine, but stopped working after I rebooted the droplet to resize the config. The issue hasn't occurred earlier.
I tried to restart shiny-server using sudo start shiny-server, but I get the status start: Job failed to start.
When I visit the Shiny app hosted at /srv/shiny-server/, I get the following nginx error.

An error occurred.

Sorry, the page you are looking for is currently unavailable.
Please try again later.

If you are the system administrator of this resource then you should check the error log for details.

Faithfully yours, nginx.

Shiny-server error log:

    fs.js:439
          return binding.open(pathModule._makeLong(path), stringToFlags(flags), mode);
                         ^
        Error: ENOENT, no such file or directory '/var/run/shiny-server/shiny-server.pid'
            at Object.fs.openSync (fs.js:439:18)
            at Object.createPidFile (/opt/shiny-server/lib/core/fsutil.js:121:15)
            at Object. (/opt/shiny-server/lib/main.js:82:15)
            at Module._compile (module.js:456:26)
            at Object.Module._extensions..js (module.js:474:10)
            at Module.load (module.js:356:32)
            at Function.Module._load (module.js:312:12)
            at Function.Module.runMain (module.js:497:10)
            at startup (node.js:119:16)
            at node.js:945:3

There is no shiny-server.pid at /var/run/shiny-server/.
My /etc/shiny-server/shiny-server.conf settings:

    # Instruct Shiny Server to run applications as the user "shiny"
    run_as shiny;
    sanitize_errors off;

    # Define a server that listens on port 3838
    server {
      listen 3838;

      # Define a location at the base URL
      location / {

        run_as shiny;

        # Host the directory of Shiny Apps stored in this directory
        site_dir /srv/shiny-server;

        # Log all Shiny output to files in this directory
        log_dir /var/log/shiny-server;

        # When a user visits the base URL rather than a particular application,
        # an index of the applications available in this directory will be shown.
        directory_index on;
      }
    }

I'm not sure what the problem is. Tried searching online forums too but with no luck! Please help. Thanks!

A: Create a folder sudo mkdir /var/run/shiny-server and then enable write permissions for Shiny user sudo chown shiny:shiny /var/run/shiny-server/


text:
Q: Displaying Children from a Connected List in a Parent List I have 3 Lists, Site, Product and Module, which are all displayed as List WebParts on a Page.
I only want to show the Site List, which needs to show the Product and it's Modules.  I have connected the Site and Product Lists together, and I can now show the Site and the Products they have.
I don't seem to be able to display the Modules that are within the selected Products.  If I click on the Product within the Site List, the pop-up does display the Modules linked to the Product.
However, ideally I'd like to be able to display the Module in a Column in the Site List WebPart, without the need to click on it.
Any help would be greatly appreciated.
Thanks
Dave


text:
Q: How to overcome divide by zero error in following query Please find an table structure below
table A      Table B
10              10
20              10
30              0
40              0

I want to divide A/B.
if there is 30/0 i wan to display it as 0.
I want to output like
O/P
1
2
0
0

How Can we do that?
Table structure queries:
create table #test1(id int)

insert into #test1 values(10)
insert into #test1 values(20)
insert into #test1 values(30)
insert into #test1 values(40)

select top 100 * from #test1

create table #test2(id int)

insert into #test2 values(10)
insert into #test2 values(10)
insert into #test2 values(0)
insert into #test2 values(0)

select top 100 * from #test2

A: Try this
SELECT A.id,B.id, IIF(B.id<>0,A.Id/B.ID,0) AS ExpectedResult,
       COALESCE( A.id/NULLIF(B.ID,0),0)  AS ExpectedResult2
FROM
(
SELECT Id,ROW_NUMBER()OVER(Order BY ID) As Seq FROM #test1
)As A
INNER JOIN
(
SELECT Id,ROW_NUMBER()OVER(Order BY ID DESC) As Seq FROM #test2)AS B
ON A.Seq=B.Seq

Result
 id id  ExpectedResult  ExpectedResult2
10  10     1                    1
20  10     2                    2
30  0      0                    0
40  0      0                    0

A: Try this query:
select A, B, case B when 0 then B else A/B end [A/B]
from (values (10,10),(20,10),(30,0),(40,0)) tbl(A,B)

Above query uses case statement to return 0 when B = 0 and divide when B <> 0.


text:
Q: Can't dismiss FBfriendPickerViewController from delegate method I am using the facebook FBFriendPickerViewController  and want the user to only be able to select one friend and then have it dismiss the view controller. In the FBFriendPickerDelegate, under the selectionDidChange method I am trying to capture what friend they selected and then dismiss the view controller. I can't get it to dismiss, I feel like I have done this type of thing many times before so I feel kind of dumb asking this, but I feel like I have exhausted every variation of this and nothing works.
-(void)friendPickerViewControllerSelectionDidChange:(FBFriendPickerViewController *)friendPicker{
    self.selectedFriends = friendPicker.selection;
    NSLog(@"%@", self.selectedFriends);
    [friendPicker dismissViewControllerAnimated:YES completion:nil];
}

I have also tried
[[friendPicker parentViewController] dismissViewControllerAnimated:YES completion:nil];

[self.friendPickerController dismissViewControllerAnimated:YES completion:nil];

[self.navigationController dismissViewControllerAnimated:YES completion:nil];

[[friendPicker navigationController] dismissViewControllerAnimated:YES completion:nil];

[self dismissViewControllerAnimated:YES completion:nil];

all to no avail.

A: Since it's a navigation Viewcontroller that you likely pushed, you would want to pop it:
[self.navigationController popViewControllerAnimated:YES];

A: If you present the friendpicker controller modally you can dismiss it by using the facebookViewControllerCancelWasPressed and the facebookViewControllerDoneWasPressed methods of the FBViewControllerDelegate protocol. If you conform to FBFriendPickerDelegate you automatically conform to the first one.


text:
Q: How to add Cc and Bcc in Amazon SES SendRawEmail? How to add the list of Cc and Bcc recipients in sendrawemail (java). I'm just adding all the recipients to one list and sending the mail. There is no separate method to set Cc and Bcc for SendRawEmailRequest.
Is there any way to set object of Destination type?
List<String> receipients = new ArrayList<String>();
receipients.addAll(mailToRecipients);
receipients.addAll(mailCcRecipients);
receipients.addAll(mailBccRecipients);

SendRawEmailRequest rawEmailRequest = new   SendRawEmailRequest(rawMessage).withDestinations(receipients);

A: Regarding SendRawEmail, you should be able to differentiate To, Cc, and Bcc destinations by setting them in your raw message headers. If you don't explicitly specify destinations in the request object, the headers will be checked instead. If you do, the headers won't be checked.
Here's a great example regarding this problem that JustinC@AWS shared on the AWS forums:

   Destinations: (empty)
   To: A@example.com
   Cc: B@example.com
   Bcc: C@example.com

The above message will be sent to all three of A@, B@, C@example.com.
     In contrast, if you send the following input:
   Destinations: A@example.com
   To: A@example.com
   Cc: B@example.com
   Bcc: C@example.com

That message will be delivered only to A@example.com.


text:
Q: how to set template in c# how do I set id in Sprite from the template templa
public class templa<T> where T : class , new(){
    public T CreateMe(){
        T temp = new T();
        shortInt si
        si.Set(2, 2);
        //T needs to have id as shortInt else it won't work

        temp.id = si; // temp = si// doesn't work either
        return temp;
    }
}
public struct shortInt{
    public short s;
    public int i;
    public void Set(short s, int i){
        this.s = s;
        this.i = i;
    }
}

Sprite here has id this is what I'm trying to achieve to change id with template
public class Sprite{
    public Sprite(){}
    public shortInt id;
    set{
        id = value;
    }
}

I was searching the web and found only do it with { get; set; } I'm clueless here

A: using  where(generic type constraint)
code like this
 public class Templat<T> where T :
     Sprite, new()  //constraint in here
    {
        public T CreateMe()
        {
            T temp = new T();
            shortInt si = new shortInt();
            si.Set(2, 2);

            temp.id = si;
            return temp;
        }

    }

    public struct shortInt
    {
        public short s;
        public int i;
        public void Set(short s, int i)
        {
            this.s = s;
            this.i = i;
        }
    }

    public class Sprite
    {
        public Sprite() { }
        public shortInt id { get; set; }
    }


text:
Q: Retrieve elements from Mailchimp archive RSS I'm trying to extract the titles and descriptions from the MailChimp RSS feed using jQuery.
I'm trying with:
$.ajax({
    type: 'GET',
    url: 'http://us10.campaign-archive1.com/feed?u=21a65076da97205b5e5ff33e6&id=cc8bfc765e',
    crossDomain: true,
    dataType: 'jsonp',
    success: function (xml) {
        $(xml).find("item").each(function () {
            var title = $(this).find("title").text();
            var description = $(this).find("description").text();
            var linkUrl = $(this).find("link_url").text();
            var link = "Read More";
            $('#feedContainer').append('

' + title + '

' + description + link + '
');
        });
    }
});

But I get the error:
Uncaught SyntaxError: Unexpected token < on
http://us10.campaign-archive1.com/feed?u=21a65076da97205b5e5ff33e6&id=cc8bfc765e&callback=jQuery214010618008393794298_1436280190025&_=1436280190026

If it's not possible through jQuery, is there another method? I tried with Yahoo Developer Console but robots.txt disallows the access..
It seems mailchimp disallow access that doesn't come from browsers, I tried to curl the URL and I get a 404 not found.

A: *

*You need to parse XML before query with jquery (https://api.jquery.com/jQuery.parseXML)
var xmlDoc = $.parseXML(xml);
var $xml = $(xmlDoc);
$xml.find("item");

*Set valid dataType to xml

A:
Uncaught SyntaxError: Unexpected token < on
      http://us10.campaign-archive1.com/feed?u=21a65076da97205b5e5ff33e6&id=cc8bfc765e&callback=jQuery214010618008393794298_1436280190025&_=1436280190026

The above error is caused by the fact that JSONP requires the returned data to be valid JSON/javascript, which XML is not.
Unfortunately JSONP is needed in your case as CORS isn't enabled on this specific server. (see CORS for Apache)
The result is that you cannot use jQuery only if the returned data can be changed to JSON.
I just tried curl, and it seems to work fine, no 404 error for me, maybe you need to use a proxy? And make sure your quote the url, as the character & is handled specially in a shell.
curl 'http://us10.campaign-archive1.com/feed?u=21a65076da97205b5e5ff33e6&id=cc8bfc765e'

And if you're going to use curl, there would be more than one options to parse xml, such as xmllint, see How to parse XML using shellscript?
Here's an example using xmllint:
xmllint --nocdata --xpath '//item[1]/title/text()' <(curl -s \
  'http://us10.campaign-archive1.com/feed?u=21a65076da97205b5e5ff33e6&id=cc8bfc765e')

It prints the first title:
AVVIO ANNO SCOLASTICO 2015/2016


text:
Q: Techniques to keep animated gifs "animating" during periods of high load? In situations where a browser is under intense load I find that animated gifs, for example a throbber, will stop animating until the load subsides.  This behaviour seem to be consistent across the browsers I've tried (Firefox, Safari, IE, Opera, ...).
Am wondering if there are any techniques I can use to ensure that animation continues during these periods.
Thanks!  Matt

A: You might be able to alleviate it by decreasing the length of time the browser spends on any particular task. Split out the JavaScript loading, or defer some of it. See if you really need to be doing all your JavaScript tasks right as the page loads. Defer some of the image loading, especially images below the fold.
Think of the browser as a single-threaded piece of code; you need to break up the tasks it has to do so that there's time in there to update the throbber animation.

A: You have no control on the page side except for reducing the load on the browser that the page actually contributes.
Maybe you could use the services of YSLOW to help you? It's a Firefox/Firebug plugin.


text:
Q: Third derivative at point is greater than 3 f : $I \to \Bbb R$ is differentiable 3 times in open interval $I$ which contains the closed interval [-1,1]. $f(0)=f(-1)=f'(0)=0$ and $f(1)=1$
show that exists a point $c \in (-1,1) s.t. f^{(3)} (c) \ge 3$
What I did:
I used Rolle's theorem to prove that there are points in the derivatives where they equal 0. Don't really know how to get to 3... maybe using the intermediate value somehow- but don't really have an idea...
Thanks in advance

A: A stronger statement holds: there exists $c$ in $(-1,1)$ such that $f^{(3)}(c)=3$.
Observe that the degree $3$ polynomial
$$
g(x)=\frac{1}{2}x^2(x+1)
$$
has exactly the same properties as your function $f$. And note that $g^{(3)}(x)=3$.
Now $h=:f-g$ satisfies
$$
h(-1)=h(0)=h(1)=h'(0)=0.
$$
By Rolle, there exist $-1<a<0<b<1$ such that $h'(a)=h'(0)=h'(b)=0$.
Two more applications of Rolle yield $-1<c<1$ such that
$$
0=h^{(3)}(c)=f^{(3)}(c)-g^{(3)}(c)=f^{(3)}(c)-3.
$$

A: I have a sketch of an answer that might help:
I believe that since $[-1,1]$ is closed, the function $f'''$ must reach a maximum $m$ on the interval.
So we have: $f'''(x) \leq m$
Then you can integrate both sides over the range $[0,x]$, i.e.
$\int^x_0 f'''(t) dt \leq mx$
$f''(x) - f''(0) \leq mx$
$f''(x)  \leq mx +  f''(0)$
Trouble is, we are not given $f''(0)$ so leave as is for now.
Now repeat the process:
$\int^x_0 f''(t) dt \leq \frac{1}{2}mx^2 +  f''(0)x$
$f'(x) - f'(0) \leq \frac{1}{2}mx^2 +  f''(0)x$
$f'(x) \leq \frac{1}{2}mx^2 +  f''(0)x$
and again:
$\int^x_0 f'(t) dt \leq \frac{1}{6}mx^3 +  \frac{1}{2}f''(0)x^2$
$f(x) - f(0) \leq \frac{1}{6}mx^3 +  \frac{1}{2}f''(0)x^2$
$f(x) \leq \frac{1}{6}mx^3 +  \frac{1}{2}f''(0)x^2$
Setting $x=1$ :
$1 \leq \frac{1}{6}m + \frac{1}{2}f''(0)$
So you get an inequality involving $m$ and $f''(0)$.
Now you can repeat the whole process again but this time use the interval $[-x,0]$. You should then get another inequality involving $m$ and $f''(0)$.
Using substitution you should be able to derive an inequality involving just $m$ that should yield your answer.


text:
Q: check if user is logged in I have some basic code that I place at the header of every page to make sure that the user is logged in. I was hoping someone could take a look at it and give me some suggestions:

if ($_SESSION['logged_in'] == 1) {
        $handle = dbconnect::init;
        $result = $handle->select()->from('session_id')
                                   ->where('session_id=?', $_SESSION['SID'])
                                   ->columns('ip');
        $check = $result->fetchAll();
        if ($check[0]->ip != $_SERVER['REMOTE_ADDR']) { //user has changed networks
                                                        // or someone is trying
                                                        // to switch cookies on us
            return false;
        }
    } else {
        return false;
    }
Thanks!

A: function checkLoggedIn () {
    // Return early if we are not logged in. Also, by using empty we
    // avoid warnings of the 'undefined index' kind.
    if (empty($_SESSION['logged_in'])) {
        return false;
    }

    $handle = YourDbClass::getConnection();

    $result = $handle->select()->from('session_id')
                               ->where('session_id=?', $_SESSION['SID'])
                               ->columns('ip');
    $check = $result->fetchAll();
    if ($check[0]->ip != $_SERVER['REMOTE_ADDR']) { //user has changed networks
                                                    // or someone is trying
                                                    // to switch cookies on us
        return false;
    }
    return true;
}

Your code looks pretty good to me. I wrapped it in a function so you don't need to duplicate it on every page, just require your util.php or whatever you want to call your function library. Then just call checkLoggedIn(). If it returns false, the user is not logged in and you may send an error page, exit or whatever. If it returns true, you can proceed.

A: Do you have a special need for pulling the remote ip from the database? Would be easier to store the remote ip within _SESSION instead of bothering the database with another query.
You might want to give the user an option to disable this feature as they might have to connect to your server through transparent proxies with changing ip addresses, e.g. http://webmaster.info.aol.com/proxyinfo.html says:AOL Members' requests for internet objects are usually handled by the AOL Proxy system. When a member requests multiple documents for multiple URLs, each request may come from a different proxy server. Since one proxy server can have multiple members going to one site, webmasters should not make assumptions about the relationship between members and proxy servers when designing their web site.
nit picky: You should first test if there is at least one record before you try to access it. Might be something like:if ( !isset($check[0]) || $check[0]->ip!=$_SERVER['REMOTE_ADDR'] )


text:
Q: Convert a .txt file to .asc using shell I have the following text file:
ifile.txt
1.1 4.5
2.3 2.3
3.4 30.5

I would like to add one line (%file1) at the beginning and then convert it to .asc file.
I used the following command:
(echo "%file1" ; cat ifile.txt)  > ofile.asc

But the output came as:
ofile.asc
%file1
1.1 4.5^M
2.3 2.3^M
3.4 30.5^M

Desired output is:
ofile.asc
%file1
1.1 4.5
2.3 2.3
3.4 30.5

A: You may use tr instead of cat to remove DOS line break characters from original file:
{ echo "%file1"; tr -d '\r' < ifile.txt; } > ofile.asc

Also there is no need to fork a shell as we can use { ... } to group many commands.

A: You can use sed to eliminate ^M characters:
{ echo "%file1" ; sed 's/^M//' file.txt ; } > ofile.asc


text:
Q: Hover button not working correctly I'm trying to change my text in my button to white when I hover over it. However when I hover over my button the text colour does not change to white but to a gray colour but the background changes to the correct colour which implies that I'm hovering over the correct element. I inspected this and it seems the button:hover is being overridden by an existing text hover colour. Is there any way that I can remove the current gray hover colour and use my white hover colour?
My code is as fallows

.button:hover {
  color: white;
  background-color: #1B43F9;
}
 Buy Now

my whole css is as fallows
.columns {
  float: left;
  width: 31%;
  padding: 8px;
}

/* Style the list */

.price {
  list-style-type: none;
  border: 3px solid #eee;
  margin: 0;
  padding: 0;
  -webkit-transition: 0.3s;
  transition: 0.3s;
  text-align: center;
  border-radius: 7%;
}

/* Add shadows on hover */

.price:hover {
  box-shadow: 0 8px 12px 0 rgba(0,0,0,0.2);
}

@media only screen and (max-width: 600px) {
  .columns {
    width: 100%;
  }
}

/* Pricing header */

.price .header {
  background-color: white;
  color: white;
  border-radius: 36px 36px 0px 0px;
}

/* List items */

.price li {
  margin-left: 4%;
  padding: 5%;
  text-align: center;
}

/* Grey list item */

.price .annualPrice {
  background-color: #1BA5E0;
  margin: 0px;
  font-style: bold;
  color: white;
  height: 75px;
}

.subTitle {
  background-color: #1BA5E0;
  padding: 3%;
  color: white;
}

/* The "Sign Up" button */

.button {
  background-color: #1ba5e0;
  border: none;
  color: white;
  padding: 3% 5%;
  text-align: center;
  text-decoration: none;
  font-size: 18px;
}

.button:hover {

  background-color: #1B43F9;
}

/* Change the width of the three columns to 100%
(to stack horizontally on small screens) */

.header {
  margin-bottom: 8.5%;
}

.price li {
  background: url(http://presentationsolutions.eu/new2/wp-content/uploads/2016/11/check.png) no-repeat left top;
  height: 10%px;
  padding-left: 14%;
  padding-top: 0%;
  text-align: left;
}

.buyCompareButton {
  margin: 12% 0% 8% 0%;
  font-family: "myriad-pro","myriad-pro",sans-serif !important;
  font-weight: 300!important;
  font-size: 1.2em;
  line-height: 28px !important;
}

A: The Problem could be that your Website uses different stylesheets.
Try to write !important behind your color.
Your css code:
.button:hover {
    color: white !important;
    background-color: #1B43F9;
}


text:
Q: Safari Extension Contextmenu Icon and Separator I've searched and can't seem to find a way to add a separator item to my Safari extension contextmenu or to add a custom icon for the regular menu item my extension creates. My contextmenu item is working fine with dynamic text based on the selection but I'd like to differentiate the menu item with either an icon or a separator item (or both) to set it off from menu items from other extensions. Are either of these things possible in Safari extensions? Thanks.

A: I have been looking for quite some time and I'm convinced this is not yet possible.


text:
Q: asp.net mvc - value provider and collections I'd like to access in my ActionFilter a property. This propert is a collection.
Usually I access the values using the valueprovider like this
filterContext.Controller.ValueProvider.GetValue("Prop");

but this isn't working in case of a collection.
Is there way to get my collection ?

A: You could use filterContext.ActionParameters. Example:
Model:
public class MyViewModel
{
    public IEnumerable<string> Collection { get; set; }
}

Action filter:
public class MyActionFilterAttribute : ActionFilterAttribute
{
    public override void OnActionExecuting(ActionExecutingContext filterContext)
    {
        var value = filterContext.ActionParameters["model"];
        // TODO: do something with the value
        base.OnActionExecuting(filterContext);
    }
}

Controller:
public class HomeController : Controller
{
    [MyActionFilter]
    public ActionResult Index(MyViewModel model)
    {
        return View();
    }
}

Request: /?collection[0]=foo&collection[1]=bar


text:
Q: main.js:2 Uncaught Reference Error: firebase is not defined Am trying to link my html contact form with firebase, but am facing an error :

Uncaught Reference Error: firebase is not defined

in my main.js file I defined my CDN in my html file well, but in main.js line
is where I face  this error in. I successful installed firebase in my project, but
still I face the same issue In the line below.
var emailRef = firebase.database().ref('emails');

Here in my main.js code
var emailRef = firebase.database().ref('emails');

  // Listen for form submit
  document.getElementById('contactForm').addEventListener('submit', submitForm);

// Submit form
function submitForm(e){
  e.preventDefault();

    //Get values
    var FullName = getInputval('FullName');
    var Email =getInputval('Email');

        // save message
        saveMessage(FullName,Email);

    // Show alert
    document.querySelector('.alert').style.display = 'block';

    // Hide alert after 3 seconds
    setTimeout(function(){
      document.querySelector('.alert').style.display = 'none';
    },3000);

    // Clear form
    document.getElementById('contactForm').reset();
  }

// Function to get  form values
function getInputval(id){
    return document.getElementById(id).value;
}

  // Save message to firebase
  function saveMessage(Fullname, Email,){
    var newEmailRef = emailRef.push();
    newEmailRef.set({
      Fullname: Fullname,
      Email:Email

    });
  }

And in my index.html file here are my CDN format

<script type="module">
  // Import the functions you need from the SDKs you need
  import { initializeApp } from "https://www.gstatic.com/firebasejs/9.1.3/firebase-app.js";
  import { getAnalytics } from "https://www.gstatic.com/firebasejs/9.1.3/firebase-analytics.js";
  // TODO: Add SDKs for Firebase products that you want to use
  // https://firebase.google.com/docs/web/setup#available-libraries

  // Your web app's Firebase configuration
  // For Firebase JS SDK v7.20.0 and later, measurementId is optional
  const firebaseConfig = {
    apiKey: "xxxxx",
    authDomain: "xxxxx",
    projectId: "xxxxx",
    storageBucket: "xxxxx",
    messagingSenderId: "xxxxx",
    appId: "xxxxx",
    measurementId: "xxxxx"
  };

  // Initialize Firebase
  const app = initializeApp(firebaseConfig);
  const analytics = getAnalytics(app);
</script>

<script src="main.js"></script>

A: Your second snippet is importing version 9 of Firebase in ES module format here:
<script type="module">

But then in the first snippet you try to use Firebase in its older syntax with  firebase.database().
That won't work: you will have to either use the new import format and syntax, or use the older namespace syntax.

The equivalent to this v8 code:
var emailRef = firebase.database().ref('emails');

In v9 modular syntax that'd be:
import { getDatabase, ref } from "firebase/database";

// Get a reference to the database service
const database = getDatabase(app);
var emailRef = ref(database, 'emails');

And this code in v8:
function saveMessage(Fullname, Email,){
  var newEmailRef = emailRef.push();
  newEmailRef.set({
    Fullname: Fullname,
    Email:Email

  });
}

Would look like this in v9:
import { getDatabase, ref, push, set } from "firebase/database";

function saveMessage(Fullname, Email,){
  var newEmailRef = push(emailRef);
  set(newEmailRef, {
    Fullname: Fullname,
    Email:Email
  });
}

When you're working with this combination of older and newer syntax, I recommend keeping the upgrade guide handy.


text:
Q: Why do I get a PostgreSQL permission error when specifying a tablespace in the "create database" command? When I create a database in PostgreSQL without explicitly specifying a default tablespace the database is created without issue (I'm logged in as the pgsys user):
postgres=> create database rich1;
CREATE DATABASE
postgres=> \l+
                                                                            List of databases
   Name    |  Owner   | Encoding |  Collation  |    Ctype    |          Access privileges          |   Size    | Tablespace |                Description
-----------+----------+----------+-------------+-------------+-------------------------------------+-----------+------------+--------------------------------------------
 postgres  | pgsys    | UTF8     | en_US.UTF-8 | en_US.UTF-8 |                                     | 7455 kB   | pg_default | default administrative connection database
 rdsadmin  | rdsadmin | UTF8     | en_US.UTF-8 | en_US.UTF-8 | rdsadmin=CTc/rdsadmin               | No Access | pg_default |
 rich1     | pgsys    | UTF8     | en_US.UTF-8 | en_US.UTF-8 |                                     | 7233 kB   | pg_default |
 template0 | rdsadmin | UTF8     | en_US.UTF-8 | en_US.UTF-8 | =c/rdsadmin                         | 7345 kB   | pg_default | unmodifiable empty database
                                                             : rdsadmin=CTc/rdsadmin
 template1 | pgsys    | UTF8     | en_US.UTF-8 | en_US.UTF-8 | =c/pgsys                            | 7345 kB   | pg_default | default template for new databases
                                                             : pgsys=CTc/pgsys
(5 rows)
As you can see, the database is put into the pg_default tablespace, but if I specify the default tablespace in the tablespace clause (also still logged in as pgsys) I get a permission error:
postgres=> create database rich2 tablespace pg_default;
ERROR:  permission denied for tablespace pg_default
Here's the permissions for that user:
postgres=> \du pgsys
               List of roles
 Role name | Attributes  |    Member of
-----------+-------------+-----------------
 pgsys     | Create role | {rds_superuser}
           : Create DB
This is PostgreSQL error, but I should mention that this an AWS Aurora instance in case that makes a difference.

A: Here's the trick, at least with pgAdmin v4:
Leave the tablespace blank. It will default to "pg_default" when creating the database.

A: I've resolved this issue by making the username that is getting the error owner of the pg_default tablespace. The other method of not including the tablespace in the CREATE works as well, but this is a solution for others where taking the tablespace out of the CREATE is not possible.
My environment this works in where the issue is face is an AWS RDS instance for clarification, where rdsadmin is the owner.
ALTER TABLESPACE pg_default
  OWNER TO myusername;

A: grant all on tablespace <tablespace_name> to ;


text:
Q: Couldn't find enough finder patterns:0 patterns found For an web application, I need to build a QR code scanner.
To do this, I have used getUserMedia to access my mobile phone camera.  I take picture, and upload its data_uri(URI) to QR Code Decoder module.  But it is throwing me the mentioned exception.
Any help would be appreciated.
I am using following decoder which is based on Lazarsoft Jsqrcode.
https://github.com/edi9999/jsqrcode
And for camera, I have used following library
https://github.com/jhuckaby/webcamjs


text:
Q: Onnx import failed I am trying to use object detection.
-> https://www.youtube.com/watch?v=a1br6gW-8Ss&ab_channel=WhenMathsMeetCoding
I used TensorFlow to make the .pd and converted it to .onnx.
->https://www.youtube.com/watch?v=L8dbnpzxpQQ&ab_channel=JayanthK
The convert method is "python -m tf2onnx.convert --saved-model TensorFlow-model-path --output model.onnx".
The problem is that when I import .onnx into Unity, It is failed.
success import other people .onnx
Fail import my .onnx
**
Error 1 :
OnnxImportException: Unknown type Loop encountered while parsing layer StatefulPartitionedCall/map/while_loop:0.

Unity.Barracuda.ONNX.ONNXModelConverter.Err (Unity.Barracuda.Model model, System.String layerName, System.String message, System.String extendedMessage, System.String debugMessage) (at Library/PackageCache/com.unity.barracuda@3.0.0/Barracuda/Runtime/ONNX/ONNXModelConverter.cs:3434)
Unity.Barracuda.ONNX.ONNXModelConverter.ConvertOnnxModel (Onnx.ModelProto onnxModel) (at Library/PackageCache/com.unity.barracuda@3.0.0/Barracuda/Runtime/ONNX/ONNXModelConverter.cs:2954)
Unity.Barracuda.ONNX.ONNXModelConverter.Convert (Google.Protobuf.CodedInputStream inputStream) (at Library/PackageCache/com.unity.barracuda@3.0.0/Barracuda/Runtime/ONNX/ONNXModelConverter.cs:170)
Unity.Barracuda.ONNX.ONNXModelConverter.Convert (System.String filePath) (at Library/PackageCache/com.unity.barracuda@3.0.0/Barracuda/Runtime/ONNX/ONNXModelConverter.cs:98)
Unity.Barracuda.ONNXModelImporter.OnImportAsset (UnityEditor.AssetImporters.AssetImportContext ctx) (at Library/PackageCache/com.unity.barracuda@3.0.0/Barracuda/Editor/ONNXModelImporter.cs:65)
UnityEditor.AssetImporters.ScriptedImporter.GenerateAssetData (UnityEditor.AssetImporters.AssetImportContext ctx) (at <d63e58d1bc4b489593159fa6218bc0e6>:0)
UnityEditorInternal.InternalEditorUtility:ProjectWindowDrag(HierarchyProperty, Boolean)
UnityEngine.GUIUtility:ProcessEvent(Int32, IntPtr, Boolean&)

Error 2 :
Asset import failed, "Assets/Models/model.onnx" > OnnxImportException: Unknown type Loop encountered while parsing layer StatefulPartitionedCall/map/while_loop:0.

Unity.Barracuda.ONNX.ONNXModelConverter.Err (Unity.Barracuda.Model model, System.String layerName, System.String message, System.String extendedMessage, System.String debugMessage) (at Library/PackageCache/com.unity.barracuda@3.0.0/Barracuda/Runtime/ONNX/ONNXModelConverter.cs:3434)
Unity.Barracuda.ONNX.ONNXModelConverter.ConvertOnnxModel (Onnx.ModelProto onnxModel) (at Library/PackageCache/com.unity.barracuda@3.0.0/Barracuda/Runtime/ONNX/ONNXModelConverter.cs:2954)
Unity.Barracuda.ONNX.ONNXModelConverter.Convert (Google.Protobuf.CodedInputStream inputStream) (at Library/PackageCache/com.unity.barracuda@3.0.0/Barracuda/Runtime/ONNX/ONNXModelConverter.cs:170)
Unity.Barracuda.ONNX.ONNXModelConverter.Convert (System.String filePath) (at Library/PackageCache/com.unity.barracuda@3.0.0/Barracuda/Runtime/ONNX/ONNXModelConverter.cs:98)
Unity.Barracuda.ONNXModelImporter.OnImportAsset (UnityEditor.AssetImporters.AssetImportContext ctx) (at Library/PackageCache/com.unity.barracuda@3.0.0/Barracuda/Editor/ONNXModelImporter.cs:65)
UnityEditor.AssetImporters.ScriptedImporter.GenerateAssetData (UnityEditor.AssetImporters.AssetImportContext ctx) (at <d63e58d1bc4b489593159fa6218bc0e6>:0)
UnityEditorInternal.InternalEditorUtility:ProjectWindowDrag(HierarchyProperty, Boolean)
UnityEngine.GUIUtility:ProcessEvent(Int32, IntPtr, Boolean&)

UnityEngine.GUIUtility:ProcessEvent (int,intptr,bool&)

Hoping someone can help me!!!


text:
Q: Adobe Air URLRequest to Local File Works Windows 7, Not 10 I developed an Adobe Air App for a small intranet.  All computers have been running Windows 7, but now are beginning to be replaced with Windows 10 systems.  I can access the mapped drive "I" and the local "C" drive using the file class on Windows 7 machines, but only the mapped drive "I" on Windows 10.
Edit:  Capabilities.localFileReadDisable returns false on both Windows 7 and Windows 10 systems.
****I could bypass the need for the local file if Air could get any specific information about the machine it is running on, serial number, mac address, computer name, etc.  It really makes no difference what information I get, it just has to be unique to that computer.  And using cookies isn't an option because they are volatile****
The following code accomplishes two things.
First, it displays the running version of the Air file and looks for a file on a mapped drive with the latest version available.  If they are the same, the computer is running the latest version.  If they aren't the same, the new version is displayed to the user, indicating the app should be updated.
Second, it grabs the name of the specific computer from a text file residing on the local drive.  That name is used on reports to indicate which computer was being used.  There is probably a far superior way to accomplish this, but on Windows 7, it works perfectly for me.  Unfortunately, Windows 10 throws an error when trying to access the file on the local drive.
Error #2044: Unhandled ioError:. text=Error #2032: Stream Error. URL: file:///C:/machineName.txt
Any help would be greatly appreciated.
var appXML:XML =  NativeApplication.nativeApplication.applicationDescriptor;
var ns:Namespace = appXML.namespace();
version_txt.text = "V"+appXML.ns::versionNumber;

// Define path to the version number
var updatePath:URLRequest = new URLRequest("file:///I:/air/update.txt");

// Define path to name of specific pc
var machineName:URLRequest = new URLRequest("file:///C:/machineName.txt");

// Define the URLLoaders
var updateLoader:URLLoader = new URLLoader();
function checkUpdate():void{
    updateLoader.load(updatePath);
}

var nameLoader:URLLoader = new URLLoader();

function checkName():void{
    nameLoader.load(machineName);
}

// Listen for when the file has finished loading.
updateLoader.addEventListener(Event.COMPLETE, loaderComplete);
function loaderComplete(e:Event):void
{
    // The output of the text file is available via the data property
    // of URLLoader.
    if(Number(appXML.ns::versionNumber)<Number(updateLoader.data)){
        update_txt.text = "UPDATE TO V"+updateLoader.data;
    }
}

nameLoader.addEventListener(Event.COMPLETE, nameComplete);
var name_txt:String = new String;

function nameComplete(e:Event):void{
    name_txt = nameLoader.data;
    var holder:String = version_txt.text;
    version_txt.text = name_txt+" ** "+holder;
}


text:
Q: Firefox OS device gps I'm currently searching a way for device using firefox OS to communicate with device's gps, so it can get the exact location positioning, rather than the w3c geolocation api which is not as accurate as gps realtime.. Thanks!

A: Simple answer: it isn't possible to access the "device's GPS" directly. You only have the Geolocation API that you already know.
Long answer: My experience with it is not bad at all. So, I think only of two possibilities for not getting "exact location positioning", as you name it:

*

*maybe you're not using the right options to get a precise position. In this case, you could tweak your options a bit to get better results;

*maybe you're not waiting until the underlying software can use your GPS instead of some less accurate instrument/estimation (like Wi-Fi positioning estimation).

*It can be a combination of both =P

In the first case, you can verify if you're using enableHighAccuracy, like this:
navigator.geolocation.watchPosition(
  successCallback,
  errorCallback,
  { enableHighAccuracy: true }
);

This will ask the browser for better results, as the standard indicates. Watch out that this may use more battery, and this may not be available anyway. This may take more time too, which is related to my other observation.
In the second case, you may be using a value for timeout that is too small, and maybe it's combined with a maximumAge that may be too high.
If maximumAge is high and timeout is small, you get an out dated position, as there won't be enough time to get a new position and you accept an old one.
If both are small, you'll start to get lots of TIMEOUT errors (the value is 3), as there'll be no positions for you.
You need to find the right balance between all 3 options to get the best positions. And you have to be patient sometimes.
Play with all 3 options and take a look at the errors you get. They'll tell you a lot about your issue getting precise and accurate coordinates.
The position object has some attributes that may come in handy to analyze what's happaning:

*

*the position.timestamp attribute will tell you how old that position object is. If this is old, you know you should tweak the options

*the position.coords.accuracy attribute will tell you the accuracy level of the lat/long coordinates. If this is too big (it's in meters), you know you should tweak the options

If you wait forever, on a place where the GPS should work well (say, outdoors, on a clean field), and you keep getting inaccurate results, maybe you can't do much better anyway. I'd say it's not possible anyway, with your software+hardware =(

A: As of now, Firefox OS only has support for GPS positioning (with the latest addition of A-GPS in the mix). That results in the fact, that most of the time you will have to wait from 1 to several minutes at least for the GPS module to acquire lock on your location, and you will need clear look at the sky for the lock to be acquired.
That said, after a lock is acquired, by using the right settings in the call itself (like setting the enableHighAccuracy flag to true) the GPS should provide as accurate position as any other device would.
Right now cell-based and wifi-based geolocation is not available in the current version of the OS (1.0.1 or 1.1.0, either) but is in the pipeline.

A: You can use the Geolocation API Firefox OS or Google Maps (I do not remember where I got it)


text:
Q: what Should be the SQL query for the below result What should be the SQL query if we want a result in the form of table 2 from table 1
Table 1:
Type1 | Type2
------|-------
A     |  Dev
B     |  User
C     |  User1
User  |  Dev
User1 |  User
User2 |  User1

Table 2:
X| Y
------|-------
A     |  Dev
B     |  User
B     |  Dev
C     |  User1
C     |  User
C     |  Dev
User  |  Dev
User1 |  User
User1 |  Dev
User2 |  User1
User2 |  User
User2 |  Dev

A: Try the below script, using a recursive CTE here.
DECLARE @TABLE  TABLE
(
    Type1   NVARCHAR(10)
    ,Type2  NVARCHAR(10)
)
INSERT INTO @TABLE
VALUES ('A','Dev'),('B','User'),('C','User1'),('User','Dev'),('User1','User'),('User2','User1')

;WITH CTE
AS
(   SELECT  Type1,Type2
    FROM    @TABLE
    UNION ALL
    SELECT  C.Type1, T.Type2
    FROM    CTE AS  C
        INNER JOIN  @TABLE  AS  T   ON  T.Type1 =   C.Type2
)
SELECT * FROM CTE
ORDER BY Type1,Type2 DESC

Output
Type1   Type2
A       Dev
B       User
B       Dev
C       User1
C       User
C       Dev
User    Dev
User1   User
User1   Dev
User2   User1
User2   User
User2   Dev

A: select t1.Type1 as X,
       t2.Type2 as Y
from table1 t1
join (select distinct Type2 from table1) t2
   on  t1.Type2 >= t2.Type2
order by x, y desc

Executes as:
SQL>select t1.Type1 as X,
SQL&       t2.Type2 as Y
SQL&from table1 t1
SQL&join (select distinct Type2 from table1) t2
SQL&   on  t1.Type2 >= t2.Type2
SQL&order by x, y desc;
X          Y
========== ==========
A          Dev
B          User
B          Dev
C          User1
C          User
C          Dev
User       Dev
User1      User
User1      Dev
User2      User1
User2      User
User2      Dev

                 12 rows found


text:
Q: Mysql Replication - How it works offline? i have a mysql server on a local machine but the connection is not got for users outside the local network. I want that database to be available on another server wich can handle way more requests and is more stable than the local server.
My question is:
   What is the best way to replicate the data from the local server into the web server?
   I've readed a little about slave servers, are they made for this case?
   If i use a mysql slave server and the internet on the main server goes offline, what happens to the slave?
   If the main server makes some database changes while offline will these changes be written on the slave when the master goes online again?
   Are there any performace loss for using a slave server?
I do not want a backup server, i want a server to redirect ouside queries into it, so the main server wont be affected for huge traffic and etc.

A: Replication sounds like what you need, as long as the slave server you envision will be used as read-only.
Connecting a slave (replica) server to a master imposes very little load on the master.  If the connection between the two is severed for whatever reason, the slave will continue to answer queries, and normally will reconnect to the master as soon as practical and pick up exactly where it left off.  Certain disruptions can cause you to have to take steps to get replication going again, but ordinarily this is automatically done.
Using a replica this way is common.
I produce several hundred scheduled reports every day, many of which evaluate many millions of rows... and the reports are run against slave servers, to relieve the master of this additional workload.  In some cases, the slave is many thousands of miles away from the master, so, naturally, the connections are periodically lost... but they restart themselves.


text:
Q: How to repeat a few characters a few times in bash? In a bash script, I have to include the same file several times in a row as an argument. Like this:
convert image.png image.png image.png [...] many_images.png

where image.png should be repeated a few times.
Is there a bash shorthand for repeating a pattern?

A: This works with a given integer (10 in the example below).
$ echo $(yes image.png | head -n10)
image.png image.png image.png image.png image.png image.png image.png image.png image.png image.png

It can also be used with xargs:
$ yes image.png | head -n10 | xargs echo
image.png image.png image.png image.png image.png image.png image.png image.png image.png image.png

A: #!/bin/bash

function repeat {
    for ((i=0;i<$2;++i)); do echo -n $1 " "; done
}

convert $(repeat image.png 3) many_images.png

A: Here is a solution that uses arrays and is thus robust for strings containing spaces, newlines etc.
declare -a images
declare -i count=5
for ((i=0; i<count; ++i))
do
    images+=(image.png)
done
convert "${images[@]}" many_images.png

A: You can do this using brace expansion:
convert image.png{,,} many_images.png

will produce:
convert image.png image.png image.png many_images.png

Brace expansion will repeat the string(s) before (and after) the braces for each comma-separated string within the braces producing a string consiting of the prefix, the comma-separated string and the suffix; and separating the generated strings by a space.
In this case the comma-separated string between the braces and the suffix are empty strings which will produce the string image.png three times.

A: This might work for you:
convert $(printf "image.png %.s" {1..5}) many_images.png

This will repeat image.png 5 times before many_images.png

A: To avoid slow code that opens unnecessary instances of bash using $(command) or command you can use brace expansion.
To repeat a filename 3 times do:
file="image.png"; convert "${file[0]"{1..3}"}" many_images.png

or a more controversial version that uses a variable to specify number of repeated file names:
n=10; file="image.png"; eval convert \"\${file[0]\"{1..$n}\"}\" many_images.png

How it works.
${file[0]} is same as $file or ${file}
Bash does brace expansion first and so it makes up a sequence like this:
${file[0]1} ${file[0]2} ${file[0]3}

Bash kindly ignore these extra numbers so you get
${file[0]} ${file[0]} ${file[0]}

Which simplifies to
${file} ${file} ${file}

and then
$file $file $file

Which is what we want.

A: Shortest POSIX 7 solution I have found so far:
N=3
S="image.png "
printf "%${N}s" | sed "s/ /$S/g"

since yes, seq and {1..3} are not POSIX.
For your specific example:
N=
convert $(printf "%${N}s" | sed "s/ /image.png /g") many_images.png


text:
Q: C++ instantiate new class as inherited class type So let's say I have an abstract class Car, from which the classes Ford and Mazda are derived.
class Car{
public:
    float fuel_capacity = 0;
    virtual float get_fuel_capacity();
    virtual void set_fuel_consumption(float x);
}

class Ford : public Car
{
public:
    Ford();
    float get_fuel_capacity() {return fuel_capacity}
    void set_fuel_capacity(float x) {fuel_capacity = x};
};

class Mazda: public Car{
public:
    Mazda();
    float get_fuel_capacity() {return fuel_capacity}
    void set_fuel_capacity(float x) {fuel_capacity = x};
};

Using those classes I want to define a garage containing my cars:
class Garage{
    stack<Car> cars;
    void add_car(Car x){cars.push(x)}
    Car get_cars(){return cars;}
}

Now I thought that by requiring the abstract class in add_car I could pass any of the derived types, but it seems I cannot because no suitable constructor exists to convert from "Ford *" to "Car" pops up.
So there I  have it.
How can I call something like:
Garage g;
g.add_car(new Ford());
g.add_car(new Mazda());

I dont even know how to search for this on google :(

A: Your problem in this case is not inheritance but the fact that you pass a pointer as a parameter to a method where a value is requested.
You should change your Garage class to solve this by doing the following:
class Garage {
    stack<Car*> cars;
    void add_car(Car* x) { cars.push(); }
}

Also note that your get_car won't compile, because your return type does not match the thing that you actually return. You should change the return type to something like const stack<Car*>&.
But as idclev463035818 stated: You seem to lack some basics.
Reading C++ compiler errors may be hard at times, but this is something that should be so basic that when the compiler tells you that there is an issue in that line, you simply look at the line and see your mistake. This is a kind of issue that could be resolved by reading a book (or something similar) on C++ instead of asking SO questions.


text:
Q: Сохранение лучшего результата в игре Надо сохранить лучший результат. Какие есть варианты сохранения?
Не использую libgdx.
SharedPreferences prefs = this.OnSharedPreferenceChanged("myPrefsKey", Context.MODE_PRIVATE);
best = prefs.getInt("score", 0);

if (best > player.getScore()) {
    canvas.drawText("BEST: " + best, WIDTH - 215, HEIGHT - 10, paint);
} else {
    best = player.getScore();
    canvas.drawText("BEST: " + best, WIDTH - 215, HEIGHT - 10, paint);
    prefs.edit().putInt("score", best).apply();
}

Решил проблему.
Для меня подошел такой вот код:
SharedPreferences prefs = this.getContext().getSharedPreferences("BEST", Context.MODE_PRIVATE);

А вообще, SharedPreferences очень даже хитрая штука.
Обязателен какой либо Context и учитывайте это! В моём случае - я прописал код при создании новой игры и при окончании. Это тоже учитывайте!

A: Для меня подошел такой вот код:
SharedPreferences prefs = this.getContext().getSharedPreferences("BEST", Context.MODE_PRIVATE);

А вообще, SharedPreferences очень даже хитрая штука.
Обязателен какой либо Context и учитывайте это! В моём случае - я прописал код при создании новой игры и при окончании. Это тоже учитывайте!

A: Все зависит от того какая у вас игра. Если это просто синглплей и данный юзер и его счет не связан с другими игроками то вам вполне хватит SharedPreferences. Если игра более сложная то уточните детали.


text: Q: AWS managed service unable to resolve DNS via Route53 We have defined Route53 Resolver Rule with an Resolver Outbound Endpoint that forwards requests to our on-prem DNS servers, and it works fine from within EC2 instances, I can confirm that from an ssh session nslookup, however, MSK Connect connector that is referencing a schema registry URL throws UnknownHostException being unable to resolve DNS. I checked security group outbound rules for MSK and they allow all traffic, and our network admin actually see requests coming and responding at about the time when MSK connect logs the error. What can obstruct MSK to receive response?


text:
Q: Showing $f_j(0)$ converges to $f(0)$ where $f_j$ and $f$ are rational functions. Let $A=\{z \in \mathbb{C}: \frac{1}{2} < |z| < 1 \}$. Let $\{f_j\}_{j=1}^\infty$ be a sequence of rational functions and let $f$ be a rational function. Suppose none of these functions have poles on $A \cup \{0 \}$, $f_j$ converges uniformly to $f$ on $A$, and each $f_j$ is nonzero on the closed unit disc. I am trying to show that $f_j(0) \rightarrow f(0)$.
I am having trouble with this because it is possible that even though each $f_j$ is nonzero, the numerator has a zero not in the closed unit disc. Otherwise, I would be able to assume the numerator was a constant and perhaps proceed from there. I would appreciate any help with how to start this proof.

A: We need the extra condition that $f$ is not identically zero since otherwise the result doesn't hold as $f_n(z)=\frac{1}{(4z)^n+1}$ satisfies $f_n(0)=1, f_n(z) \to 0$ uniformly on A, $f_n$ rational with no poles on $A$ or at $0$ etc
Local uniform convergence on $A$ and the rest of the hypothesis is enough to conclude that $f_j \to f$ locally uniformly on the open disc; in particular, since $f_j, f$ have no poles at zero, it follows $f_j(0) \to f(0)$
(where local uniform convergence is meant in the sense of meromorphic functions, so if $w$ is not a pole of $f$ then there is a neighborhood $W$ and an $n(W)$ for which $f_n$ has no pole in $W$ for $n \ge n(W)$ and $f_n \to f$ uniformly on $W$ while if $w$ is a pole of $f$, poles of $f_n$ accumulate there with the corresponding order and $1/f_n \to 1/f$ in a neighborhood of $w$ - so for example if $w$ is a pole of order $2$, then for every small enough neighborhood, there is $n(W)$ for which $f_n$ has no zeroes and either two simple poles or a double pole there for $n \ge n(W)$ and $1/f_n \to 1/f$ uniformly in $W$)
Proof: $f$ not identically zero as noted so by Hurwitz $f$ has no zeroes in $A$ and $1/f_n \to 1/f$ locally uniformly in $A$; but if $g_n =1/f_n, g=1/f$, the hypothesis on the zeroes of $f_n$ implies that $g_n$ is holomorphic in the open unit disc, $g_n \to g$ locally uniformly in $A$;
in particular $g_n$ is uniformly locally bounded in $A$ so by maximum modulus ($\sup_{|z| \le 1-\epsilon}|g_n(z)|=\sup_{|z| = 1-\epsilon}|g_n(z)|$) it follows that $g_n$ is locally uniformly bounded in the opne unit disc so it is a normal family;
but now every subsequence $s$ of $g_n$ on the open unit disc has a subsequence converging to a holomorphic function $h_s$ on the open unit disc that is $g$ on $A$, hence by the identity principle, $h_s=h$ for all subsequences of $g_n$, $g_n \to h$ and $h=g$ on $A$, while $h$ is holomorphic on the open unit disc; since $g$ is meromorphic on the open unit disc (rational), it follows that $g=h$ and $1/f$ is holomorphic in the open unit disc too, while $1/f_n \to 1/f$ locally uniformly there and we are done (since that clearly implies $f_n \to f$ in the sense described above)


text:
Q: Making a simple 555 sawtooth VCO stable? I have figured out how to make a sawtooth VCO using a 555 IC , by using a current mirror.
The issues I am having is I can't make it stable at all. Its having random issues like it randomly changes frequency output or if I turn it off for awhile then back on it changes frequency output even if the input voltage on the current mirror stays the same.
So what components can I add to this circuit to make it stable enough? I need this circuit to be able to be able to keep the same frequency output with the same voltage input.

A: As shown the current mirror will be very sensitive to temperature variations. Even the self-heating due to the dissipation in the transistors will cause their temperature to change enough to cause unbalance between the two transistors. That is probably why you notice the change when it has been switched off for a while.
They should be matched and both be at exactly the same temperature, for example clamped together into a common heatsink.
The imbalance can be improved by putting a resistor in the emitter of each of the transistors. The value should be selected so that it drops a few hundred millivolts or more. In that circuit there is about 300uA flowing in the first transistor so a 1 kilohm resistor would be a good place to start. An example is shown below.
What type of capacitor are you using for the timing? A ceramic capacitor such as X7R is probably not good enough for temperature stability. A film capacitor would be better.

A: A current mirror is great on paper, but it rarely works well with real-world components.  Every parameter about a transistor, including its gain and base-emitter junction voltage, is either temperature-dependent, collector-current-dependent, or both.
Commercially available VCO IC's have a lot going on internally, and a lot of that is compensating and offsetting circuits hovering around the main VCO structure.
Linear Technology and Texas Instruments have many app notes on opamp circuit design, with sections on VCO's.  IIRC these are not "simple" circuits.

A: Add some emitter degenration to the current mirror to improve its stability. (perhaps 3.3K in series with each emitter - you have plenty of headroom)
The trick you're pulling on the control-voltage pin is defeating the 555s internal ripple rejection strategy. you may want to reconsider that. perhaps restore the ripple rejection capacitor on pin 5 and use a comparitor to drive the trigger pin if you don't like a trigger level of VCC/3
Use a high stability capacitor such as polystyrene film for the timing capacitor.

A: When the DIS pin is driven low it is forced to sink a very high current for a very short time as it discharges the timing capacitor. You could try putting a small resistor, say 100R, in series with the DIS pin to limit the discharge current. Note that adding the extra resistor will slightly increase the slope of the vertical drops of the output waveform.
If that doesn't improve matters then you could try the circuit below.
The op amp and its associated resistors form a level shifter. It also doubles the amplitude of the output waveform compared to your circuit. If the amplitude is too big for you then you can reduce it by adding a resistive potential divider at the output. The frequency is about 125 Hz, as you can see.


text:
Q: How to join streams based on a key This is for redux-observable but I think the general pattern is pretty generic to rxjs
I have a stream of events (from redux-observable, these are redux actions) and I'm specifically looking to pair up two differnt types of events for the same "resource" - "resource set active" and "resource loaded" - and emit a new event when these events "match up". The problem is these can come in in any order, for any resources, and can be fired multiple times. You might set something active before it is loaded, or load something before it is set active, and other resources might get loaded or set active in between.
What I want is a stream of "this resource, which is now loaded, is now active" - which also means that once a resource is loaded, it can be considered forever loaded.
If these events were not keyed by a resource id, then it would be very simple:
First I would split them up by type:
const setActive$ = action$.filter(a => a.type == 'set_active');
const load = action$.filter(a => a.type == 'loaded');

In a simple case where there is no keying, I'd say something like:
const readyevent$ = setActive$.withLatestFrom(loaded$)

then readyevent$ is just a stream of set_active events where there has been at least one loaded event.
But my problem is that the set_active and loaded events are each keyed by a resource id, and for reasons beyond my control, the property to identify the resource is different in the two events. So this becomes something like:
const setActive$ = action$.filter(a => a.type === 'set_active').groupBy(a => a.activeResourceId);
const loaded$ = action$.filter(a => a.type === 'loaded').groupBy(a => a.id);

but from this point I can't really figure out how to then "re-join
" these two streams-of-grouped-observables on the same key, so that I can emit a stream of withLatestFrom actions.

A: I believe this does what you are describing:

const action$ = Rx.Observable.from([
  { activeResourceId: 1, type: 'set_active' },
  { id: 2, type: 'loaded' },
  { id: 1, type: 'random' },
  { id: 1, type: 'loaded' },
  { activeResourceId: 2, type: 'set_active' }
]).zip(
  Rx.Observable.interval(500),
  (x) => x
).do((x) => { console.log('action', x); }).share();

const setActiveAction$ = action$.filter(a => a.type === 'set_active')
  .map(a => a.activeResourceId)
  .distinct();
const allActive$ = setActiveAction$.scan((acc, curr) => [...acc, curr], []);

const loadedAction$ = action$.filter(a => a.type === 'loaded')
  .map(a => a.id)
  .distinct();
const allLoaded$ = loadedAction$.scan((acc, curr) => [...acc, curr], []);

Rx.Observable.merge(
  setActiveAction$
    .withLatestFrom(allLoaded$)
    .filter(([activeId, loaded]) => loaded.includes(activeId)),
  loadedAction$
    .withLatestFrom(allActive$)
    .filter(([loadedId, active]) => active.includes(loadedId))
).map(([id]) => id)
 .distinct()
 .subscribe((id) => { console.log(`${id} is loaded and active`); });
<script src="https://cdnjs.cloudflare.com/ajax/libs/rxjs/5.5.10/Rx.min.js"></script>

The basic approach is to create a distinct stream for each action type and join it with the distinct aggregate of the other. Then merge the two streams. This will emit the value when there are matching setActive and loaded events. The distinct() on the end of the merge makes it so that you will only get notified once. If you want a notification on each setActive action after the initial one then just remove that operator.

A: groupBy looks somewhat complicated to do this with, there's a key value in there but you get an Observable of Observables - so maybe a little hard to get right.
I would map the id to a common property and then use scan to combine. I use this pattern for grouping in my app.
The accumulator in the scan is an object, which is used as an associative array - each property is an id and the property value is an array of actions accumulated so far.
After the scan, we convert to an observable stream of arrays of matching actions - sort of like withLatestFrom but some arrays may not yet be complete.
The next step is to filter for those arrays we consider complete.
Since you say

where there has been at least one loaded event

I'm going to assume that the presence of two or more actions, with at least one is type 'loaded' - but it's a bit tricky to tell from your question if that is sufficient.
Finally, reset that id in the accumulator as presumably it may occur again later in the stream.
const setActive$ = action$.filter(a => a.type === 'set_active')
  .map(a => { return { id: a.activeResourceId, action: a } });

const loaded$ = action$.filter(a => a.type === 'loaded')
  .map(a => { return { id: a.id, action: a } });

const accumulator = {};
const readyevent$: Observable<action[]> =
  Observable.merge(setActive$, loaded$)
  .scan((acc, curr) => {
    acc[curr.id] = acc[curr.id] || [];
    acc[curr.id].push(curr.action)
  }, accumulator)
  .mergeMap((grouped: {}) => Observable.from(
    Object.keys(grouped).map(key => grouped[key])
  ))
  .filter((actions: action[]) => {
    return actions.length > 1 && actions.some(a => a.type === 'loaded')
   })
  .do(actions => {
    const id = actions.find(a => a.type === 'loaded').id;
    accumulator[id] = [];
  });


text:
Q: Jmeter Inter Thread group communication MxN invocations I Have a setUp Thread group in which i am creating A resource with unique Id,path it will give me a url to test
In main Test group I have to Test each url created in setupthread group needs to be rigorsly tested.
testplan
In tearDown thread group i need to clear the setupgroup creation .
The problem i am facing is , the property value is getting overridden
Suppose say in SetUpthread group i have created 10 resources then its the last resouce always the mainTest thread group is getting executed
I am looking for a way foreach setupThread group resource the mainTest theadgroup must execute the no of times i specified in the TheadCount and LoopCount
eg: setUpThread group ThreadCount is 10 and Loop count is 10 then i will get 100 different unquie resources would be created then its the mainTest ThreadGroup
100 TC , 100 LC i.e., for each resource its 10000 times gets invoked .
please help me in acheiving this attached pic

A: You can take a look at http://jmeter-plugins.org/wiki/InterThreadCommunication/ plugin.
This will help in your case. Let me know if this works.

A: It is hard to suggest anything without having your test plan itself so here is just an approach, I don't guarantee that it'll work, however the idea should be fine.
You need to set up as many properties as many URLs you would like to be hit in the main thread group.
For instance, if you write some URL down in JSR223 Sampler using __counter() function output as postfix like:

This will generate the following properties:
URL_1=http://some.url
URL_2=http://some.other.url
etc.

After that in 2nd Thread Group you can add another JSR223 Sampler to convert JMeter Properties to JMeter Variables like:
Enumeration e = props.propertyNames();
while (e.hasMoreElements()) {
  String propertyName = e.nextElement().toString();
  if (propertyName.startsWith("URL_")) {
      vars.put(propertyName, props.getProperty(propertyName));
  }
}

Then you should be able to use ForEach Controller to iterate the variables.
Also make sure you use Groovy as JSR223 PostProcessor and Sampler language


text:
Q: How to avoid type erasue in JAXB, MOXY implementation while marshalling? I have to marshall following class ;
@XmlRootElement(name = "SYSMessage")
@XmlAccessorType(XmlAccessType.FIELD)
public class Message<T> {

    @XmlPath("Personel")
    private Personel personel;

    @XmlPath("AccountType")
    private T accountType;

    ...

So in production I set generic Account type class with some object called "DebitAccount"
I have to use generic type because debitAccount will change many times.
Message<DebitAccount> msg = new Msg<>();
DebitAccount dAccount= new DebitAccount();
msg.setAccountType(dAccount);

and when I marshalled class Message, I got the following xml result as account type;
    ...
    org.demo.blabla.DebitAccount@123123
    ...
In DebitAccount class;
@XmlRootElement
@XmlAccessorType(XmlAccessType.FIELD)
public class DebitAccount{

    @XmlPath("ID")
    private String id;

    @XmlPath("Visa")
    private String visaNo;

I figured out this is happening because of Type erasure. Moxy just cant simply understand that my object is DebitAccount. So it treats object as string. How can I make moxy understand my composite object.

A: You have to bind DebitAccount class to the same XML context of Message class using @XmlSeeAlso annotation. You can list multiple classes with curly braces. When using generic types (T or ?), you have to specify which classes are part of the same context.
@XmlRootElement(name = "SYSMessage")
@XmlAccessorType(XmlAccessType.FIELD)
@XmlSeeAlso({DebitAccount.class})
public class Message<T> { ... }


text:
Q: Angular - Only a few variables are being printed, what's the mystery? I have 8 (eight) variables

*

*produtoNome

*unidadeUtilizada

*unidadeNome

*codigoSistemaFormatado

*precoPadrao

*precoCusto

*valorCustoMedio

*valorCustoReferencial
These variables are being printed on app.component.html.
The problem:
The variable produtoNome, unidadeUtilizada, unidadeNome, codigoSistemaFormatado, precoPadrao, precoCusto is loaded when the method onChangedProduto is clicked. But loading the page again, just produtoNome, unidadeUtilizada, unidadeNome, codigoSistemaFormatado is printado. And I can't solve.
[app.component.ts]
https://github.com/andersonpablo/ERP/blob/main/produto/produto-ficha-tecnica/produto-ficha-tecnica.component.ts
[app.component.html]
https://github.com/andersonpablo/ERP/blob/main/produto/produto-ficha-tecnica/produto-ficha-tecnica.component.html
app.component.ts

export class ProdutoFichaTecnicaComponent extends AbstractComponent implements OnInit {

    private _produto: Produto;
    produtosComponentes: ProdutoComponente[] = [];
    produtoConsultaCusto: ProdutoConsultaCusto[] = [];
    formGroup: FormGroup;
    produtos: Produto[] = [];
    buscando = false;
    maskQtde = { prefix: '', precision: 3 };

    @Input()
    set fichaTecnica(produto: Produto) {

        this._produto = produto;
        this.preencherForm(produto);
    }

    @Output()
    salvarDados = new EventEmitter<ProdutoComponente[]>();

    constructor(
        private fb: FormBuilder,
        private produtoComponenteService: ProdutoComponenteService,
        private service: ProdutoService
    ) {
        super();
    }

    ngOnInit() {

        this.formGroup = this.fb.group({
            produtos: this.fb.array([])
        });
    }

    get isValid(): boolean {

        if (this.formGroup.valid && this.produtosComponentesformArray.length > 0) {
            return true;
        }

        return this.isFormVazio();
    }

    get produtosComponentesformArray(): FormArray {
        return this.formGroup.controls['produtos'] as FormArray;
    }

    removerLinha(index: number) {

        const control = this.produtosComponentesformArray;
        control.removeAt(index);
        this.produtos.splice(index, 1);

        if (control.length === 0) {
            this.adicionarLinha();
        }

    }

    onProdutoChanged(produto: Produto, index: number) {
        if (this.validarProduto(produto, index)) {
            this.produtos[index] = produto;
            this.produtosComponentesformArray.at(index).patchValue({
                produtoNome: produto.nome,
                unidadeUtilizada: produto.unidadePrincipal.unidade.id,
                unidadeNome: produto.unidadePrincipal.unidade.sigla,
                codigoSistemaFormatado: produto.codigoSistemaFormatado,
                precoPadrao: produto.precoPadrao,
                precoCusto: produto.precoCusto,
                valorCustoMedio: produto.valorCustoMedio,
                valorCustoReferencial: produto.valorCustoReferencial,
            });
        }
    }

    onModalConfirm() {
        let componentes: ProdutoComponente[] = null;

        if (!this.isFormVazio()) {
            const control = this.produtosComponentesformArray;
            componentes = control.value;
        }

        if (this._produto.id) {

            super.subs = this.produtoComponenteService.salvar(this._produto.id, componentes).subscribe(r => {
                NotificationService.success('Ficha técnica alterada com sucesso.');
                this.salvarDados.emit(null);
            }, error => {
                const message = error.error ? error.error.message : error.message;
                NotificationService.error(message);
            });

        } else {
            this.salvarDados.emit(componentes);
        }
    }

    private validarProduto(produto: Produto, index: number) {

        if (this._produto.id === produto.id) {
            this.limparLinha(index, 'Não é possível incluir o próprio produto composto como componente');
            return false;
        }

        if (this._produto.classificacao === 'CONSUMO') {
            if (produto.classificacao !== 'CONSUMO') {
                this.limparLinha(index, 'Só é possível adicionar Material de Uso e Consumo para este composto');
                return false;
            }
        }

        if (produto.metodoControle === 'NAO_ESTOCAVEL') {
            this.limparLinha(index, 'Não é possível adicionar produto Não Estocável');
            return false;
        }

        const produtoJaInserido = this.produtos.find(p => p.id === produto.id);
        if (produtoJaInserido) {
            this.limparLinha(index, 'Produto já inserido na ficha técnica.');
            return false;
        }

        return true;
    }

    private limparLinha(index: number, mensagem: string) {
        NotificationService.error(mensagem);

        const controlArray = this.produtosComponentesformArray;

        if (controlArray.length === 1) {
            this.removerLinha(index);
        } else {
            this.removerLinha(index);
            this.adicionarLinha();
        }
    }

    adicionarLinha(produtoFichaTecnica?: ProdutoComponente) {

        const produtoComponente = produtoFichaTecnica ?? new ProdutoComponente();

        const unidadePrincipal = new UnidadePrincipal();
        unidadePrincipal.unidade = new Unidade();
        unidadePrincipal.unidade.sigla = produtoComponente.unidadeNome;

        const produto: Produto = {
            ...new Produto(),
            id: produtoComponente.produto,
            nome: produtoComponente.produtoNome,
            codigoSistemaFormatado: produtoComponente.codigoSistemaFormatado,
            unidadePrincipal: unidadePrincipal,
            valorCustoMedio: produtoComponente.valorCustoMedio,
            valorCustoReferencial: produtoComponente.valorCustoReferencial,
            precoCusto: produtoComponente.precoCusto,
            precoPadrao: produtoComponente.precoPadrao,
        };

        this.produtos.push(produto);

        const novoGrupo = this.criarProdutoFormGroup(produtoComponente);
        this.produtosComponentesformArray.push(novoGrupo);
    }

    private criarProdutoFormGroup(produtoFichaTecnica: ProdutoComponente): FormGroup {

        return this.fb.group({
            produto: this.fb.control(produtoFichaTecnica.produto, Validators.required),
            quantidade: this.fb.control(produtoFichaTecnica.quantidade, [Validators.required, Validators.min(0.00001)]),
            unidadeUtilizada: this.fb.control(produtoFichaTecnica.unidadeUtilizada),
            produtoNome: this.fb.control(produtoFichaTecnica.produtoNome),
            codigoSistemaFormatado: this.fb.control(produtoFichaTecnica.codigoSistemaFormatado),
            unidadeNome: this.fb.control(produtoFichaTecnica.unidadeNome),
            precoCusto: this.fb.control(produtoFichaTecnica.precoCusto),
            precoPadrao: this.fb.control(produtoFichaTecnica.precoPadrao),
            valorCustoMedio: this.fb.control(produtoFichaTecnica.valorCustoMedio),
            valorCustoReferencial: this.fb.control(produtoFichaTecnica.valorCustoReferencial),
        });
    }

    private isFormVazio(): boolean {

        const controlArray = this.produtosComponentesformArray;

        if (controlArray.length === 1) {
            const value = controlArray.at(0).value;

            if (value.produto === null && value.quantidade === null) {
                return true;
            }
        }

        return false;
    }

    private preencherForm(produto: Produto) {

        if (produto.componentes?.length) {

            produto.componentes.forEach(produtoComponente => {
                this.adicionarLinha(produtoComponente);
            });
        } else if (produto.id) {

            this.buscando = true;

            super.subs = this.produtoComponenteService.obterPorProdutoPai(this._produto.id).pipe(
                concatMap(produtosComponentes => {

                    if (produtosComponentes.length) {

                        this.produtosComponentes = produtosComponentes;
                        const produtosIds = produtosComponentes.map(pc => pc.produto);

                        const consultaCustofiltro: ProdutoConsultaCustoFiltro = {
                            ...new ProdutoConsultaCustoFiltro(),
                            data: new Date(),
                            produtos: produtosIds
                        };

                        return this.service.calcularCustoMedio(consultaCustofiltro);
                    }

                    return of([] as ProdutoConsultaCusto[]);
                }),
            ).subscribe(consultaCustos => {

                console.log(this.produtosComponentes);
                console.log(consultaCustos);

                 this.produtosComponentes.forEach(produto => {
                     const custo = consultaCustos.find(p => p.produto === produto.produto);
                     produto.valorCustoMedio = custo.valorCustoMedio;
                     produto.valorCustoReferencial = custo.valorCustoReferencial;
                 });
                if (consultaCustos.length) {
                    this.produtosComponentes.forEach(produtoComponente => {
                        this.adicionarLinha(produtoComponente);
                    });
                } else {
                    this.adicionarLinha();
                }
                this.buscando = false;
            });
        } else {
            this.adicionarLinha();
        }
    }
} ```

app.component.html
<app-vo-modal keyTitle="Ficha técnica" (onFinished)="onModalConfirm()" [primaryButtonDisabled]="!isValid || buscando">

    <app-vo-loading [exibir]="buscando"></app-vo-loading>

    <form [formGroup]="formGroup" *ngIf="formGroup && !buscando">

                    Item
                    Produto
                    Código
                    Unidade
                    Quantidade
                    Custo Médio
                    Custo Total
                    Preço Venda
                    Preço Total
                    Opção

                    {{i+1}}

                    <app-vo-filtro-produtos (valueSelected)="onProdutoChanged($event, i)" [showLabel]="false"
                        [multiple]="false" formControlName="produto" [itens]="produtos[i]"></app-vo-filtro-produtos>

                    <input type="text" value="{{control.value.codigoSistemaFormatado}}" class="form-control" readonly>

                    <input type="text" value="{{control.value.unidadeNome}}" class="form-control" readonly>

                    <input type="text" formControlName="quantidade" class="form-control minw-110" currencyMask
                        [options]="maskQtde">

                    <input type="text" value="{{control.value.valorCustoMedio | currency: 'R$'}}" class="form-control"
                        readonly>

                    <input type="text" value="{{control.value.precoCusto | currency: 'R$'}}" class="form-control"
                        readonly>

                    <input type="text" value="{{control.value.precoPadrao | currency: 'R$'}}" class="form-control"
                        readonly>

                    <input type="text" value="{{control.value.valorCustoReferencial | currency: 'R$'}}" class="form-control"
                        readonly>

                    <button type="button" class="btn btn-default" (click)="removerLinha(i)" tooltip="Remover"
                        container="body">

                    </button>

                    <button *ngIf="isLast && control.valid" type="button" class="btn btn-default"
                        (click)="adicionarLinha()" tooltip="Adicionar" container="body">

                    </button>

    </form>
</app-vo-modal>