text:
Q: Logging issue in Wildfly server with JDK11 setup Facing issue related to logging in Wildfly deployment of Java web application.
Wildfly version used: wildfly-15.0.0
The web application is having a Spring MVC configuration. Spring framework version is 4.3.1 and logging is configured using logback.xml with slf4j.
Applications' JDK compliance level is 1.8 and it is set up to run on JDK11 on Wildfly.
The application logs are being printed in wildfly server logs. It should get printed in the file provided in the application's logback.xml
Below are the Jars added for logging into the application's WEB-INF/lib folder.

*

*log4j-1.2.16.jar

*log4j-api-2.11.2.jar

*log4j-to-slf4j-2.11.2.jar

*logback-classic-1.2.3.jar

*logback-core-1.2.3.jar

Tried adding a module in the Wildfly server under $JBOSS_HOME/modules/system/layers/base/ but it didn't work.
Also added the following configuration to the subsytem "urn:jboss:domain:logging:6.0 in $JBOSS_HOME/standalone/configuration/standalone.xml

After this, the application logs are printed at the proper location. However, the logs inside of the application's custom jars aren't getting print. Neither in server logs nor in application logs.
The same configuration is working as expected in tomcat 9. But it seems like the logback.xml is not being bootstrapped properly in Wildfly.
Any idea what can be the issue?

A: By default WildFly has it's own slf4j binding which writes to the servers log manager. If you'd like to use your own log manager you need to do one of the following.

*

*Exclude the logging subsystem from your deployment in a jboss-deployment-structure.xml

*Exclude the logging dependencies you want to provide yourself, in your case it looks like org.slf4j.api, org.slf4j.impl and org.apache.log4j in a jboss-deployment-structure.xml

*Change the logging subsystem attribute add-logging-api-dependencies to false.

For more details have a look at the documentation. Note the per-deployment logging link seems to be broken there which we will get fixed.


text:
Q: What is the method to add a payment and a subscription in my apple and android app? I'm developing an app in which a professional creates an account to display his informations and user can access to this app and see the informations of the professional.
To obtain an account, the professional have to pay first a unique payment for the first twelve months and after he will pay for a subscription.
My questions :
- do I have to use the apple and google payment system ? (apple in-app purchase and google in-app purchase) ?

- what are the differences between google in-app purchase and google in-app billing ?

- can I use another purchase system like Braintree ?

- If not, with apple and google system, can the professional use only his credit card without any google pay or apple pay account ?

Thanks

A: With iOS apps, you have to use Apple Pay to facilitate the payment. You'd have to use this (https://developer.apple.com/in-app-purchase/)
Use of Braintree may be possible with the Android ecosystem. Check out https://www.braintreepayments.com/blog/braintree-android-pay/
Differences;
https://developer.android.com/distribute/best-practices/earn/in-app-purchases
https://developer.android.com/google/play/billing
Basically Play Billing is for a one-off purchase or subscription-based items. You'd usually use this when you're buying app subscription or paid apps.
In ap is more relevant for games, that unlock features based on purchases.
Hope this helps.

redpajama_set_name: RedPajamaStackExchange


text:
Q: The match in mapbox expression is an exact match,how to use fuzzy match in the expression I use this method,but the result is exact match,can not fuzzy match
map.setPaintProperty('building_layeres', 'fill-extrusion-color', [
      'case',
      ['==', ['get', 'NAME'], '腾讯大厦'],
      'red',
      ['==', ['get', 'NAME'], '彩讯科技大厦'],
      'red',
      '#aaa',])

A: Mapbox-GL only supports a very small range of string manipulation operators, which don't include regular expressions or other forms of wildcard.
You can see them here: https://docs.mapbox.com/mapbox-gl-js/style-spec/#expressions-string


text:
Q: java - exception handing I created this program that should let the user enter the loan amount and loan period in the number of years from text fields, and it should display the monthly and total payments for each interest rate starting from 5 percent to 8 percent, with increments of one-eighth, in a text area. This may sound stupid but not sure how to add exception handling to add exception handling for when a non-numeric value is entered.For example instead of entering 5 for the number of years, the user enters five.The application should display an error message. thanks in advance.
package loan;
import javafx.application.Application;
import javafx.scene.Scene;
import javafx.stage.Stage;
import javafx.scene.control.Label;
import javafx.scene.control.TextField;
import javafx.scene.control.TextArea;
import javafx.scene.control.Button;
import javafx.scene.control.ScrollPane;
import javafx.scene.layout.HBox;
import javafx.scene.layout.BorderPane;
import javafx.geometry.Pos;

public class loan extends Application {
    protected TextField tfLoanAmount = new TextField();
    protected TextField tfNumberOfYears = new TextField();
    protected TextArea textArea = new TextArea();

    @Override // Override the start method in the Application class
    public void start(Stage primaryStage) {
        tfNumberOfYears.setPrefColumnCount(2);
        tfLoanAmount.setPrefColumnCount(7);
        textArea.setPrefColumnCount(30);

        // Create a button
        Button btShowTable = new Button("Show Table");

        // Create a hbox
        HBox paneForControls = new HBox(10);
        paneForControls.setAlignment(Pos.CENTER);
        paneForControls.getChildren().addAll(new Label("Loan Amount"), tfLoanAmount,
            new Label("Number of Years"), tfNumberOfYears, btShowTable);

        // Create a scrollPane
        ScrollPane scrollPane = new ScrollPane(textArea);

        // Create a pane
        BorderPane pane = new BorderPane();
        pane.setTop(paneForControls);
        pane.setCenter(textArea);

        // Create and register handler
        btShowTable.setOnAction(e -> {
            print();
        });

        // Create a scene and place it in the stage
        Scene scene = new Scene(pane);
        primaryStage.setTitle("loans"); // Set the stage title
        primaryStage.setScene(scene); // Place the scene in the stage
        primaryStage.show(); // Display the stage
    }

    private void print() {
        // Create a output string
        String output = "";
        double monthlyInterestRate; // Monthly interest rate
        double monthlyPayment;  // Monthly payment

        // Add table header
        output += "Interest Rate       Monthly Payment          Total Payment\n";

        // Calculate and add table with interest rates to output
        for (double i = 5.0; i <= 8; i += 0.125) {
            monthlyInterestRate = i / 1200;
            monthlyPayment = Double.parseDouble(tfLoanAmount.getText()) *
                monthlyInterestRate / (1 - 1 / Math.pow(1 + monthlyInterestRate,
                Double.parseDouble(tfNumberOfYears.getText()) * 12));

            output += String.format("%-24.3f%-34.2f%-8.2f\n", i,
                monthlyPayment, (monthlyPayment * 12) *
                Double.parseDouble(tfNumberOfYears.getText()));
        }

        textArea.setText(output);
    }
        public static void main(String[] args) {
            launch(args);
    }
}

A: TextField(tfNumberOfYears) [TextField]: https://docs.oracle.com/javase/8/javafx/api/javafx/scene/control/TextField.html,
this TextField has a method public final String getText(), this method returns a String.
When you use [Double.parseDouble(tfNumberOfYears.getText())]: https://docs.oracle.com/javase/7/docs/api/java/lang/Double.html
public static double parseDouble(String s) throws NumberFormatException
Throws:
NullPointerException - if the string is null
NumberFormatException - if the string does not contain a parsable double.
So you can put that code inside a try/catch block and make what you desire when the user enters five instead of 5.
Like:
`private void print() {
    // Create a output string
    String output = "";
    double monthlyInterestRate; // Monthly interest rate
    double monthlyPayment;  // Monthly payment

    // Add table header
    output += "Interest Rate       Monthly Payment          Total Payment\n";

    // Calculate and add table with interest rates to output
    for (double i = 5.0; i <= 8; i += 0.125) {
        monthlyInterestRate = i / 1200;
        try{
            monthlyPayment = Double.parseDouble(tfLoanAmount.getText()) *
            monthlyInterestRate / (1 - 1 / Math.pow(1 + monthlyInterestRate,
            Double.parseDouble(tfNumberOfYears.getText()) * 12));
        }
        catch(NumberFormatException e){
            //Here you write the code to manage this exception

        }
        try{
            output += String.format("%-24.3f%-34.2f%-8.2f\n", i,
            monthlyPayment, (monthlyPayment * 12) *
            Double.parseDouble(tfNumberOfYears.getText()));
        }
        catch(NumberFormatException e){
            //Here you write the code to manage this exception

        }
    }

    textArea.setText(output);
}
    public static void main(String[] args) {
        launch(args);
}`

This is just an example of how to handle that exception.

A: There are probably many ways to approach this, some I can think of off the top of my head are if statements if you know what kinds of errors to expect, regex matching to only filter on valid input, or try/catches, for example
// if the userinput string matches a number
if( userInputNumber.matches("-?\\d+(\\.\\d+)?") ) {
    // put your code here
else {
    System.out.println("Input unrecognized. Please type in a number (e.g. "5")
}

or perhaps
try {
    double userInputNumber = Double.parseDouble(loan.getText());
    // do some code
catch (Exception ex) {
    System.out.println("Error, unrecognized input.");
    System.out.println(ex);
}


text:
Q: Query string url to seo friendly url i am trying to rewrite a URL for SEO purpose.
The old URL is:
http://www.example.com/recipe_local.php?hl_cusine=1

The new URL should be like bellow and automatic redirect to this url if user come above url
http://www.example.com/recipes/healthy-recipes

My Code in the .htaccess is:
RewriteEngine on
RewriteRule ^recipes/healthy-recipes/$ recipe_local.php?hl_cusine=$1 [NC,L]
RewriteRule ^recipes/healthy-recipes$ recipe_local.php?hl_cusine=$1 [NC,L]

Even after hours of research, i have no clue why this is not working :(

A: The $1 in your rewrite is pointing to a backreference you never capture.
Unless you have a RewriteCond you are not showing?
try:
RewriteEngine on
RewriteRule ^recipes/healthy-recipes/$ recipe_local.php?hl_cusine=1 [NC,L]
RewriteRule ^recipes/healthy-recipes$ recipe_local.php?hl_cusine=1 [NC,L]


text:
Q: How can I cancel line break between items in bibliography biblatex? I use biblatex. I have problem with linebreak between bibliography items.
I have for short url:

The space between the organization and url is not optimal.
I want nolinebreak between organisation and url and hyphenation in url like for long url:

I use
\documentclass{article}
\usepackage[utf8]{inputenc}
\usepackage[USenglish]{babel}

\usepackage[bibstyle=authortitle,
        citestyle=authoryear-ibid,
        natbib=true,
        urldate=long,
        firstinits=true,
        uniquename=false,
        backend=bibtex]{biblatex}

%==== online sources format =====
\DeclareFieldFormat{url}{\url{#1}}
\DeclareFieldFormat{urldate}{\printtext{Last accessed}\addcolon\space#1}
\urlstyle{rm}

\DeclareBibliographyDriver{online}{%
\printnames{author}%
\newunit\newblock
\printfield{note}%
\newunit\newblock
\printlist{organization}\addcolon%
\newunit\newblock
\printfield{url}%
\newunit
\printurldate%
\finentry}
%===================================

\addbibresource{my.bib}

\begin{document}

\citet[UDE][]{ARUS}
\citep{AESOPComplexity}

\raggedright
\printbibliography

\end{document}

and my.bib
@ELECTRONIC{AESOPComplexity,
  author = {AESOP},
  note = {Association of European Schools of Planning},
  organization = {Thematic group Planning and Complexity},
  date={2015},
  urldate = {2015-01-22},
  url = {http://www.aesop-planning.eu/blogs/en_GB/planning-and-complexity}
}

@ELECTRONIC{ARUS,
  author = {ARUS},
  note = {Advanced Research in Urban Systems},
  organization = {Structured PhD program at the University of Duisburg Essen},
  institution = {UNIVERSIT\"AT DUISBURG-ESSEN},
  address = {Germany},
  date={2015},
  urldate = {2015-01-22},
  url = {https://www.uni-due.de/urbane-systeme/advanced-research-in-urban-systems_en.shtml}
  }

Could I solve this problem without delete \raggedright?
Thank you!

A: This is rooted with how you output URLs in \DeclareFieldFormat{url} and \DeclareBibliographyDriver{online}. Effectively this means the last whitespace before a URL is a normal space and biblatex is much less reluctant to break at said space instead of breaking the URL.
We can make the last space before the URL non-breaking forcing biblatex to break the URL somewhere (URL breaking is a very delicate matter though, and in my view best avoided).
\DeclareBibliographyDriver{online}{%
\printnames{author}%
\newunit\newblock
\printfield{note}%
\newunit\newblock
\printlist{organization}%<--- no \addcolon anymore
\printunit{\addcolon\addnbspace}% <---- this is new
\printfield{url}%
\newunit
\printurldate%
\finentry}

MWE
\documentclass{article}
\usepackage[utf8]{inputenc}
\usepackage[USenglish]{babel}
\usepackage{filecontents}
\usepackage[bibstyle=authortitle,
        citestyle=authoryear-ibid,
        natbib=true,
        urldate=long,
        firstinits=true,
        uniquename=false]{biblatex}

%==== online sources format =====
\DeclareFieldFormat{url}{\url{#1}}
\DeclareFieldFormat{urldate}{\printtext{Last accessed}\addcolon\space#1}
\urlstyle{rm}

\DeclareBibliographyDriver{online}{%
\printnames{author}%
\newunit\newblock
\printfield{note}%
\newunit\newblock
\printlist{organization}%
\printunit{\addcolon\addnbspace}%
\printfield{url}%
\newunit
\printurldate%
\finentry}
%===================================
%===================================
\begin{filecontents*}{\jobname.bib}
@ELECTRONIC{AESOPComplexity,
  author = {AESOP},
  note = {Association of European Schools of Planning},
  organization = {Thematic group Planning and Complexity},
  date={2015},
  urldate = {2015-01-22},
  url = {http://www.aesop-planning.eu/blogs/en_GB/planning-and-complexity}
}

@ELECTRONIC{ARUS,
  author = {ARUS},
  note = {Advanced Research in Urban Systems},
  organization = {Structured PhD program at the University of Duisburg Essen},
  institution = {UNIVERSIT\"AT DUISBURG-ESSEN},
  address = {Germany},
  date={2015},
  urldate = {2015-01-22},
  url = {https://www.uni-due.de/urbane-systeme/advanced-research-in-urban-systems_en.shtml}
  }
\end{filecontents*}

\addbibresource{\jobname.bib}

\begin{document}

\citet[UDE][]{ARUS}
\citep{AESOPComplexity}

\raggedright
\printbibliography

\end{document}


text:
Q: Why do CSS Margin Collapse? I understand that sometimes the vertical margins can collapse, what I don't understand is why they chose this behavior in the W3C specs.
I can only see this being useful when I want to define the same margin for everything and avoid the margins from summing up, but this is also useful on horizontal margins, and those can't collapse!
Does anyone knows why margins are allowed to collapse?

A: Imagine you have 2 HTML boxes. The first one has a margin-bottom of let's say 30px and the second one a margin-top of 20px. After rules of collapsing margins have been applied we have a margin of 30px (not 50px) between these two boxes  . This is because no addition of both margins takes place but the maximum of both is applied. This behavior is called collapsing margins and does only apply to vertical margins.
Oftentimes it is a good behavior but collapsing margins can be annoying, too.


text:
Q: What is the meaning of a LinkerPleaseInclude.cs file in a Xamarin application or library? In MvvmCross library there is a class Playground.Droid.LinkerPleaseInclude.cs
https://github.com/MvvmCross/MvvmCross/blob/develop/ContentFiles/Android/LinkerPleaseInclude.cs
At line 103 there is a method:
public void Include(MvxTaskBasedBindingContext context)
{
  context.Dispose();
  var context2 = new MvxTaskBasedBindingContext();
  context2.Dispose();
}

Inside this method it is created an instance of MvxTaskBasedBindingContext class and then immediately it is disposed.
Question: Why it is necessary here to create this instance and after to dispose it?

A: The LinkerPleaseInclude.cs is a concept used to prevent Mono's linker from stripping these types from your application. You can read more about this here:
https://github.com/mono/linker/blob/master/src/linker/README.md
What the code you're seeing does prevents these types from being marked and swept by the linker so they are "included" in your application even after the linker strips IL code.
It uses static analysis of your application to determine what assemblies, types, and members are used. If it does not detect these items to be valid, they are marked and swept.
https://learn.microsoft.com/en-us/xamarin/android/deploy-test/linker


text:
Q: Build against .Net 2.2 fails after .Net Core 3.1 installation with "Could not load file or assembly NuGet.ProjectModel" Build started failing suddenly
Our solution contains projects targeted against .Net Standard 2.0, .Net Core 2.2 and .Net Framework 4.5. Quite a nice mix. It is being built with dotnet -c Release MyProject.sln.
One day we started suffering from the following error, but only on one of our build slaves:
C:\Program Files\dotnet\sdk\3.1.101\Sdks\Microsoft.NET.Sdk\targets\Microsoft.PackageDependencyResolution.targets(234,5): error MSB4018: The "ResolvePackageAssets" task failed unexpectedly. [D:\MyProject\MyProject.csproj]
C:\Program Files\dotnet\sdk\3.1.101\Sdks\Microsoft.NET.Sdk\targets\Microsoft.PackageDependencyResolution.targets(234,5): error MSB4018: System.IO.FileNotFoundException: Could not load file or assembly 'NuGet.ProjectModel, Version=5.4.0.2, Culture=neutral, PublicKeyToken=31bf3856ad364e35'. The system cannot find the file specified. [D:\MyProject\MyProject.csproj]
C:\Program Files\dotnet\sdk\3.1.101\Sdks\Microsoft.NET.Sdk\targets\Microsoft.PackageDependencyResolution.targets(234,5): error MSB4018: File name: 'NuGet.ProjectModel, Version=5.4.0.2, Culture=neutral, PublicKeyToken=31bf3856ad364e35' [D:\MyProject\MyProject.csproj]
C:\Program Files\dotnet\sdk\3.1.101\Sdks\Microsoft.NET.Sdk\targets\Microsoft.PackageDependencyResolution.targets(234,5): error MSB4018:    at Microsoft.NET.Build.Tasks.ResolvePackageAssets.CacheReader.CreateReaderFromMemory(ResolvePackageAssets task, Byte[] settingsHash) [D:\MyProject\MyProject.csproj]
C:\Program Files\dotnet\sdk\3.1.101\Sdks\Microsoft.NET.Sdk\targets\Microsoft.PackageDependencyResolution.targets(234,5): error MSB4018:    at Microsoft.NET.Build.Tasks.ResolvePackageAssets.CacheReader..ctor(ResolvePackageAssets task) [D:\MyProject\MyProject.csproj]
C:\Program Files\dotnet\sdk\3.1.101\Sdks\Microsoft.NET.Sdk\targets\Microsoft.PackageDependencyResolution.targets(234,5): error MSB4018:    at Microsoft.NET.Build.Tasks.ResolvePackageAssets.ReadItemGroups() [D:\MyProject\MyProject.csproj]
C:\Program Files\dotnet\sdk\3.1.101\Sdks\Microsoft.NET.Sdk\targets\Microsoft.PackageDependencyResolution.targets(234,5): error MSB4018:    at Microsoft.NET.Build.Tasks.ResolvePackageAssets.ExecuteCore() [D:\MyProject\MyProject.csproj]
C:\Program Files\dotnet\sdk\3.1.101\Sdks\Microsoft.NET.Sdk\targets\Microsoft.PackageDependencyResolution.targets(234,5): error MSB4018:    at Microsoft.NET.Build.Tasks.TaskBase.Execute() [D:\MyProject\MyProject.csproj]
C:\Program Files\dotnet\sdk\3.1.101\Sdks\Microsoft.NET.Sdk\targets\Microsoft.PackageDependencyResolution.targets(234,5): error MSB4018:    at Microsoft.Build.BackEnd.TaskExecutionHost.Microsoft.Build.BackEnd.ITaskExecutionHost.Execute() [D:\MyProject\MyProject.csproj]
C:\Program Files\dotnet\sdk\3.1.101\Sdks\Microsoft.NET.Sdk\targets\Microsoft.PackageDependencyResolution.targets(234,5): error MSB4018:    at Microsoft.Build.BackEnd.TaskBuilder.ExecuteInstantiatedTask(ITaskExecutionHost taskExecutionHost, TaskLoggingContext taskLoggingContext, TaskHost taskHost, ItemBucket bucket, TaskExecutionMode howToExecuteTask) [D:\MyProject\MyProject.csproj]
C:\Program Files\dotnet\sdk\3.1.101\Sdks\Microsoft.NET.Sdk\targets\Microsoft.PackageDependencyResolution.targets(234,5): error MSB4018:  [D:\MyProject\MyProject.csproj]
C:\Program Files\dotnet\sdk\3.1.101\Sdks\Microsoft.NET.Sdk\targets\Microsoft.PackageDependencyResolution.targets(234,5): error MSB4018:  [D:\MyProject\MyProject.csproj]

We have had some issues in the past, after .Net Core 3.1 was installed on the slaves, but pointing to 2.2.100 in global.json fixed them.
Now, we have tried to fix the new problem searching multiple sources for Could not load file or assembly 'NuGet.ProjectModel... and similar stuff, tried many different solutions and workarounds, updates and repairs of .Net Core and Visual Studio Build Tools. No luck.

A: Finally we have spot something weird in the output of dotnet build -c Release MyProject.sln -v diag:
MSBuildSDKsPath=C:\Program Files\dotnet\sdk\3.1.101\Sdks\
MSBuildToolsPath=C:\Program Files\dotnet\sdk\2.2.110

It turned out, that we've had MSBuildSDKsPath variable set in the system and pointing to the SDK, which broke the SDK downgrade with global.json. No idea, if this was set manually by some of my colleagues or during installation of "something", but it was there and sucked ~2 days of my life :-)


text:
Q: How can I create a minimal testcase that demonstrates the cost of /EHs? I'm trying to investigate the difference in generated code when I switch Visual Studio 2019 from /EHsc (Structured and C++ exceptions only) to /EHs (also do not assume that extern "C" functions won't throw – ref), but I can't seem to coax VS into providing a useful testcase when I've minimised it.
I'm surprised the following doesn't do it (the assembly in both cases is identical), since the contents of the function referred to by fptr (a possible definition being included in comments for exposition) are unknown to the optimiser.
void foo();

/*void foo()
{
    throw 0;
}*/

extern "C"
void bar(void (*fptr)())
{
    fptr();
}

int main()
{
    try
    {
        bar(&foo);
    }
    catch (...) {}
}

Granted, it knows that any hypothetical exception will be immediately caught, and since with /EHsc the result of this exception propagation is "undefined" per Microsoft, it "appearing to work" is of course a valid outcome. But that's not much help to me here!
So how can I perform this experiment, without introducing different translation units? Ideally I want to be able to come up with a Compiler Explorer snippet for this.
My goal is to prove that permitting extern "C" to throw (or, rather, propagate) C++ exceptions in a well-defined manner does not have a higher runtime cost than I'm willing to accept in trade.
Yes, I am aware of general advice not to let exceptions cross module boundaries or flow through third-party C code. Yes, I am doing that anyway. Yes, that's fine in our project!

A: The following MCVE may give you some ideas for a test framework. You could easily add more 'thorough' test code, but this will compile and run. Note that, with the /EHsc option set, this warning is generated:

warning C5039: 'FuncTst': pointer or reference to potentially throwing
  function passed to extern C function under -EHc. Undefined behavior
  may occur if this function throws an exception.

However, when using /EHs the warning goes away - which suggests at least the possibility of different code generation.
Here's the suggested code:
#pragma warning(disable:4514) // These two lines de-fluff the hundreds of other
#pragma warning(disable:4710) // warning generated when /Wall is used.

#include <iostream>

using pFunc = int(__stdcall*)(int);

extern int __stdcall FuncOne(int p) {
    int answer = 0;
    for (int i = 0; i < p; ++i) answer += i / p; // Possible divide-by-zero
    return answer;
}

extern "C" int __stdcall FuncTst(int i, pFunc fnc) noexcept // Expects noexcept but "FuncOne" can throw!
{
    return fnc(i);
}

int main()
{
    int q;
    std::cout << "Enter test number: ";
    std::cin >> q;
    int z = FuncTst(q, FuncOne);
    std::cout << "Result = " << z << std::endl;
    return 0;
}

Hope it helps! Feel free to offer critique and/or ask for any 'improvements' or explanation.
Note: Although you can't specifically enable the C5039 warning when you compile with (say) \W4, you can force it to flag as an error (though this may be a bit harsh), with:
#pragma warning(error:5039)

A: This seems a sort of bug on Compiler Explorer, that forces /EHc even if /EHs is explicitly set.
Try to compile this code on some MSVC version with /EHs:
extern "C" void foo() {
    throw 1;
}

static_assert(noexcept(foo()), "");

Surprisingly, the function foo is assumed noexcept, and the compiler output states the reason:

example.cpp (2): warning C4297: 'foo': function assumed not to
throw an exception but does (2): note: The function is extern
"C" and /EHc was specified

Here you can find this test. You may also see this by adding something like throw 1; in your example.
Nevertheless, you can fix it compiling with /EHc- /EHs (also replace /O3 with /O2, as it is not supported on MSVC), but the output is still the same.
You can find your example, fixed, here. In the /EHc- /EHs case, the output states

cl : Command line warning D9025 : overriding '/EHc' with '/EHc-'

and a static assertion will state that bar is actually not assumed noexcept.


text:
Q: TypeError: can only concatenate tuple (not "list") to tuple for project router planner project This is the function I want to excuate, I want to show the graph in jupyter notebook.
def show_map(M, start=None, goal=None, path=None):
    G = M._graph
    pos = nx.get_node_attributes(G, 'pos')
    edge_trace = Scatter(
        x=[],
        y=[],
        line=Line(width=0.5, color='#888'),
        hoverinfo='none',
        mode='lines')

    for edge in G.edges():
        x0, y0 = G.node[edge[0]]['pos']
        x1, y1 = G.node[edge[1]]['pos']
        edge_trace['x'] += [x0, x1, None]
        edge_trace['y'] += [y0, y1, None]

this is the error i get
    109         x0, y0 = G.node[edge[0]]['pos']
    110         x1, y1 = G.node[edge[1]]['pos']
--> 111         edge_trace['x'] += [x0, x1, None]
    112         edge_trace['y'] += [y0, y1, None]
    113

TypeError: can only concatenate tuple (not "list") to tuple

I don't understand why it is a tuple?
The attributes are:
map_10_dict = {
    0: {'pos': [0.7798606835438107, 0.6922727646627362], 'connections': [7, 6, 5]},
    1: {'pos': [0.7647837074641568, 0.3252670836724646], 'connections': [4, 3, 2]},
    2: {'pos': [0.7155217893995438, 0.20026498027300055], 'connections': [4, 3, 1]},
    3: {'pos': [0.7076566826610747, 0.3278339270610988], 'connections': [5, 4, 1, 2]},
    4: {'pos': [0.8325506249953353, 0.02310946309985762], 'connections': [1, 2, 3]},
    5: {'pos': [0.49016747075266875, 0.5464878695400415], 'connections': [7, 0, 3]},
    6: {'pos': [0.8820353070895344, 0.6791919587749445], 'connections': [0]},
    7: {'pos': [0.46247219371675075, 0.6258061621642713], 'connections': [0, 5]},
    8: {'pos': [0.11622158839385677, 0.11236327488812581], 'connections': [9]},
    9: {'pos': [0.1285377678230034, 0.3285840695698353], 'connections': [8]}
}


text:
Q: Trac XML-RPC encoding problems when using phpxmlrpc I am using trac 1.0.1 with the latest XmlRpcPlugin. When adding a ticket using python like this, non-ASCII characters (ä in this example) get inserted correctly:
import xmlrpclib
server = xmlrpclib.ServerProxy('https://user:pwd@localhost/trac/login/xmlrpc')
server.ticket.create("Täst", "Täst")

Now I want to add add a ticket using phpxmlrpc like this:
$client = new xmlrpc_client("https://localhost/trac/xmlrpc");
$client->setCredentials("usr", "pwd", CURLAUTH_BASIC);

$xmlrpc_msg = new xmlrpcmsg('ticket.create', array(new xmlrpcval("Täst"), new xmlrpcval("Täst"));
$xmlrpc_resp = $client->send($xmlrpc_msg);

I now get this error: not well-formed (invalid token): line 6, column 57 and the ticket is not being inserted.
When setting $client->request_charset_encoding to either UTF-8 or ISO-8859-1, both times the ticket is being inserted but all non-ascii characters are malformed.
How can I get this working?

A: The main question is: is your example pertinent, ie. is your source string saved as part of your php sources, or is it gotten from somewhere else like a database?
If it is stored in php sources, then you should make sure that you control the character set that is used by your text editor when saving that file:

*

*if you save the php source as utf8: nothing to do

*if you save the php source as latin-1: you can call utf8_encode on your string

Once this is done, you have to tell the phpxmlrpc library that the charset used internally by your app is utf8. this is not done by setting $client->request_charset_encoding, but instead PhpXmlRpc\PhpXmlRpc::$xmlrpc_internalencoding

A: Note that PHP is known to have issues with Unicode characters.  There is another SO question that discusses this in more detail.
Try using the utf8_encode() function to encode your strings before passing them to the xmlrpc functions.


text:
Q: How to resolve "Invalid or missing account ID" problem in Google Tag Manager with test environment ? (>m_auth) I have created a testing environment in GTM under Admin > Environments in order to test my tags on my stagging website before to push them live.
So I created the environment and then, pasted the code as high in the  of the page as possible and same for the code dedicated to the body tag.
But when I go test my setup with tag assistant I have 2 errors and I dont understand these.
FIRST ONE :
Account ID
GTM-XXXXXX>m_auth
HTML Snippet <script async= "" src= "https://www.googletagmanager.com/gtm.js?id=GTM-XXXXXX>m_auth=xxxxxxxxxxxxxxxxxxx>m_preview=env-104>m_cookies_win=x" > </script>
Optimizations
Invalid or missing account ID
Of course I have change the ID, XXX is just for the message :)
SECOND ONE :
Account ID
GTM-XXXXXX>m_auth=xxxxxxxxxxxxxx>m_preview=env-104>m_cookies_win=x
URL
https://www.googletagmanager.com/gtm.js?id=GTM-XXXXXX>m_auth=xxxxxxxxx>m_preview=env-104>m_cookies_win=x
Optimizations

*

*Invalid or missing account ID

*HTTP response code indicates tag
failed to fire: Status 404. This could be due to an empty or
un-published container

*Non-standard implementation

Please, anyone encountered this situation before ?
Best,
Anneso


text:
Q: Как в Java проверить, пустой ли элемент в массиве? Есть массив типа int. Туда занесены различные числа.
Организован цикл, который поочередно будет выводить числа.
Необходима проверка на то, есть ли в массиве пустой элемент, чтоб не выводить его.
Код на Java с ошибкой:
for (int i = 0; i < num.length; i++) {
    if (num.length > 0 && num[i] != null) {
        System.out.print(num[i] + ", ");
    }
}

A: Вам нужен не int[], а массив с элементами ссылочного типа Integer[].

A: Для массива объектов можно использовать метод Objects.nonNull:
Integer[] arr = {1, null, 3, null, 5, null};

Arrays.stream(arr).filter(Objects::nonNull).forEach(System.out::println);
// 1
// 3
// 5

Если имеется массив примитивов int[], тогда пустое значение в нем будет 0, а не null:
int[] arr = {1, 0, 3, 0, 5, 0};

Arrays.stream(arr).filter(i -> i != 0).forEach(System.out::println);
// 1
// 3
// 5


text:
Q: compile Qt project without installing qt I have created a Qt 5 project in Qt Creator.
I want to open and compile this project with Visual Studio 2012 on a computer that doesn't have anything about Qt installed. How can I make the qt libraries follow with my project ?

A: There is also a Visual Studio plugin enabling Qt projects to be build inside Visual Studio IDE as for example this one :

*

*Visual Studio Add-in 1.2.2 for Qt5
(supports versions 2008, 2010 and 2012, does not work with the Express edition)
Qt Project other downloads
With this Add-in and a Qt SDK version for Visual Studio you don't need to install or build with the Qt Creator IDE.
But as drescherjm said the installation of a minimal Qt SDK is further a necessary dependency.

A: You can use cmake to resolve dependencies to the qt dll files. For example put dynamic libraries in a include-qt5 folder and include the directory in your CMakeLists as follows,
include_directories ("/include-qt5")

To run your program, you need to copy appropriate dll files next to to your executable (you can use windeployqt to do so).
Note! To use qt classes in your code use relative path to the corresponding header files such as #include <QtWidgets/QMainWindow> and so on. You may need to add the following directives in your code to specify the library that you want the linker to search for,
#if defined(NDEBUG)
    #pragma comment(lib, "Qt5Widgets.lib")
#else
    #pragma comment(lib, "Qt5Widgetsd.lib")
#endif


text:
Q: how to add bullet navigation to slider I have created a simple fade slider and got it working.
I want to incorporate the bullet navigation circles to the slider dynamically and link to images that are in the slide dynamically, but i'm finding this too difficult.
For now i have manually put in the bullet navigation circles
Can someone help me please?
Thankyou
here's my fiddle http://jsfiddle.net/kingkhan/f5zBy/60/
HTML

1

2

3

4

    Prev
    Next

CSS
#quickslider{width:990px; margin:0 auto; position: relative;}
.quickslider{position: relative; float: left; display: block; width: 990px; height:400px;}
.quickslider img{display: none; margin: 0; padding: 0; position: absolute;}

.nav-thumbs{position: absolute; clear:both; bottom:15px; left:42%;}
.nav-thumbs ul{list-style-type: none;}
.nav-thumbs ul li{float:left; margin-top:20px;}
.nav-thumbs ul li a{
display:block;
width:10px;
height:10px;
float: left;
margin:0 5px;
background-color: #fff;
text-indent: -9999px;
border-radius: 10px;
-moz-border-radius:10px;
-webkit-border-radius:10px;
}
.nav-thumbs ul li a:hover, .nav-thumbs ul li a.active{background-color: #a89d8a !important;}
.active{background-color: #a89d8a !important;}

.quickslider-nav{position:relative; clear:both; color:#000;}
.quickslider-nav a{text-decoration: none;}
.quickslider-nav .left{float: left; background-color: #fff; padding:5px 10px;}
.quickslider-nav .right{float: right; background-color: #fff; padding:5px 10px;}
.quickslider-nav .left:hover, .quickslider-nav .right:hover{background-color: #000; color:#fff;}

jQuery 1.9.1
 sliderInt = 1; //slider default on load
 sliderNext = 2; //next image in order

 $(document).ready(function(){

 $('.quickslider > img#1').fadeIn(300); // initially load first slider on load
 $('.nav-thumbs a:first').addClass('active'); // add active class to first dot
 startSlider();
 $('.left').click(function(){
    prev();
    $('.nav-thumbs a').removeClass('active');
 });
 $('.right').click(function(){
    next();
    $('.nav-thumbs a').removeClass('active');
 });

 });

 function startSlider(){
 count = $('.quickslider > img').size(); //variable to count all the list items or img
 loop = setInterval(function(){

    if(sliderNext>count){
        sliderNext = 1; // set to beginning after completion of slides list
        sliderInt = 1; // set the Integer number back to 1 also
    }

    $('.quickslider > img').fadeOut(300); // fadeout all images
    $('.quickslider > img#'+sliderNext).fadeIn(300); // use sliderNext to calculate the next slider id
    sliderInt = sliderNext; // update so that the current slide = 2 as set globally
    sliderNext = sliderNext + 1; // calculate the next image

 }, 3000); // after milliseconds loop
 }

 //previous function
 function prev(){
 //calculate the slide which comes before the current slide
 newSlide = sliderInt - 1; // current slide minus 1 added to variable called newSlide
 showSlide(newSlide); // pass information from  newSlide above to function showSlide

 }

 function next(){
 //calculate the slide which comes after the current slide
 newSlide = sliderInt + 1; // current slide plus 1 added to variable called newSlide
 showSlide(newSlide); // pass information from  newSlide above to function showSlide
 }

 function stopLoop(){
 window.clearInterval(loop); //clear interval of loop so that it does not skip images when in between intervals, ie. the 300 miliseconds just about to complete, and clicking on next will make it seem as though the you have clicked through two images

 }

 function showSlide(id){ // id is the variable name of what we will be calling which will be passed
 stopLoop(); // call function that we have declared above so that the interval is cleared and restarted

    if(id > count){
        id = 1; // if id = more than the count of images then set back to 1
    }else if(id < 1){
        id = count; // if id = less than count of list then set back to 4 or whatever number of images
    }

    $('.quickslider > img').fadeOut(300); // fadeout all images
    $('.quickslider > img#'+id).fadeIn(300); // use sliderNext to calculate the next slider id

    $('.nav-thumbs > a#'+id).addClass('active');

    sliderInt = id; // update so that the current slide = 2 as set globally
    sliderNext = id + 1; // calculate the next image
    startSlider(); // start the slider process again, as it was stopped before
 }

 $('.quickslider > img').hover(function(){
    stopLoop(); // stops the loop when image is hovered over
 },
 function(){
 startSlider(); // starts where the loop left off
 });

A: Updated Fiddle.
I just added a data-attribute to the links in the nav-thumb. When they are clicked, this value is read and the slide shows the image.


text:
Q: Cannot install java 64bit when 32 bit works fine I can Install Java 32 bit but not 64 bit.
I am using Fujitsu T902 running Windows 7 64 Bit with 4 Gigabytes of ram.
getting error code 1603
Image
System Specs
EDIT: Solved - Download a complete JRE and paste it in the correct folder, then configure enviroment variables. Thanks!

A: 64bit jdk can only run on 64bit system, please make sure your windows system is 64bit. you can right click "my computer" and click property to check out

A: Only explanation if you are actually using Windows 7 64 bit is if you are running a virtual machine where windows is 32 bit.

A: this error is java update error. Maybe you are using online installer. Download an offline JDK/JRE installer and then try.
Your system is x64 so you need to install 64 bit java.
Also please follow this link for additional information:
https://www.java.com/en/download/help/error_1603.xml

A: Download a complete JRE and paste it in the correct folder, then configure enviroment variables.
Thanks for your help though!


text:
Q: Adding a battery backup to a circuit with external power supply I want to add a LiPo rechargeable battery backup to an existing RTC circuit, but I can't alter the preexisting circuit. Basically, the regulator, D2 and RTC (Existing Circuit) are all fixed and can not be reconfigured. All I have to work with is a power and ground connection which I can get 5V-Vf(diode) from. Obviously a diode, as shown, isn't enough, since the battery will also supply the charger when the supply is off:

simulate this circuit – Schematic created using CircuitLab
I know this can be done with a MOSFET, but unfortunately my theory there is a bit weak still. What type of MOSFET would I need and how would I hook it up? (Or if you have a good idea for which charger IC can feed power back, that would be welcome as well.)

A bit of detail for the curious/if required: This will be attached to a M68HC11EVBU (yes yes, you can stop laughing) on P3 to supply power to the onboard MC68HC68T1. I will put a diode at D3 and cut the trace but solder a wire at D4 so that power can get to the circuit in question. Section 6.4 of the EVBU datasheet has the schematic; the supply is on the first page of figure 6-2 (page 98), and the RTC is on the third page (page 100).

A: The problem with the original schematic, as you know, is that when the supply is removed, the charger is still being powered by the battery itself! So when the system is running on battery power, it constantly drains itself by attempting to charge itself. To remedy this, we should not supply power to the charger from the battery.
One way to do this, like you suggest, is to use a power FET to gate off the power supply from the charger. The challenge comes in with the fact that we can't reconfigure the preexisting circuit. So we need both the battery and the regulator to be able to power the same node, VSTABLE, but we need to gate power from the charger when the regulator is off. One way we can know whether the regulator is on or off is by the voltage of VSTABLE. As you specified, the supply voltage is 5V, and the battery is 3.7V, so we can use a voltage comparator to indicate if VSTABLE is closer to 5V or 3.7V. If it is closer to 5V, we know the regulator is powering the circuit and we should power the charger as well. If VSTABLE is closer the 3.7V, we assume the regulator is powered down, and we gate off the charger with our power FET, M1:

simulate this circuit – Schematic created using CircuitLab
The comparator voltage, 4.35V is based on a 0V voltage drop across the diode. If the voltage drop from the diodes is 0.7V, for example, the comparator voltage should be 3.65V instead.
General case
The above should work well for your situation. However, what if the external power supply and the battery were the same voltage? In this case, using a voltage comparator won't work. We need to add some signal to indicate if the regulator is active. Lets call this signal RGOODN, and say that RGOODN is low when the regulator is on, and high when the regulator is off:

simulate this circuit
RGOODN could be generated from a jumper, switch, circuit, etc. It is up to the designer to figure out how to generate the signal.


text:
Q: docker compose prompted error: no configuration file provided: not found I had setup docker desktop with windows WSL integration version 2 and I run into issue when execute certain docker compose command with following errors
docker compose logs
no configuration file provided: not found

However, there were no problem found when executing the following
docker compose up

and image built and fired up successfully.
Is there anyone can help on this?
docker info
Client:
 Context:    default
 Debug Mode: false
 Plugins:
  buildx: Docker Buildx (Docker Inc., v0.7.1)
  compose: Docker Compose (Docker Inc., v2.2.1)
  scan: Docker Scan (Docker Inc., 0.9.0)

Server:
 Containers: 3
  Running: 3
  Paused: 0
  Stopped: 0
 Images: 4
 Server Version: 20.10.11
 Storage Driver: overlay2
  Backing Filesystem: extfs
  Supports d_type: true
  Native Overlay Diff: true
  userxattr: false
 Logging Driver: json-file
 Cgroup Driver: cgroupfs
 Cgroup Version: 1
 Plugins:
  Volume: local
  Network: bridge host ipvlan macvlan null overlay
  Log: awslogs fluentd gcplogs gelf journald json-file local logentries splunk syslog
 Swarm: inactive
 Runtimes: io.containerd.runc.v2 io.containerd.runtime.v1.linux runc
 Default Runtime: runc
 Init Binary: docker-init
 containerd version: 7b11cfaabd73bb80907dd23182b9347b4245eb5d
 runc version: v1.0.2-0-g52b36a2
 init version: de40ad0
 Security Options:
  seccomp
   Profile: default
 Kernel Version: 5.10.60.1-microsoft-standard-WSL2
 Operating System: Docker Desktop
 OSType: linux
 Architecture: x86_64
 CPUs: 8
 Total Memory: 24.95GiB
 Name: docker-desktop
 ID: FUMA:ZOXR:BA4L:YSOZ:4NQT:HHIZ:ASAD:EJGA:NJRG:SO4S:GXN3:JG5H
 Docker Root Dir: /var/lib/docker
 Debug Mode: false
 Registry: https://index.docker.io/v1/
 Labels:
 Experimental: false
 Insecure Registries:
  127.0.0.0/8
 Live Restore Enabled: false

WARNING: No blkio throttle.read_bps_device support
WARNING: No blkio throttle.write_bps_device support
WARNING: No blkio throttle.read_iops_device support
WARNING: No blkio throttle.write_iops_device support

UPDATED
It was my mistake that I should execute the docker compose command under the correct directory where docker-compose.yml file located at.
The issue resolved

A: execute docker-compose command where docker-compose.yml file located at should resolved it.
or specify the docker-compose.yml file as bellow
docker-compose -f <docker-compose.yml> logs

as suggested

A: For anyone who's getting
no configuration file provided: not found

I was getting the same message on Mac trying to execute
docker-compose up

The problem was with docker-compose.yml file. I saved it from Visual Studio Code as a text file though OS determined it like a proper YAML file. Look at the screenshot: left file is wrong but seems the same.

Make sure you select YAML format when you saving it.

A: I was facing the same issue on Windows PowerShell . I was using the docker-compose up command from within the newly created directory located in C:\WINDOWS\system32\ .
In my case, I rectified the problem by moving it to C:\Users\

A: Faced the same issue on a Windows PC. The problem was with the extension of the file being assumed by the OS as a known file type.
Solution
Go to Folder options  and disable the Hide extensions for known file types.
You should be able to see the actual file extension which may looked like proper .txt files now (instead of .yml). Rename the file(s) accordingly, run the command again and viola!

A: I was also receiving this error and I had mis-spelt the file name(oops), so also double check spelling of files if anyone else finds their way to this post!

A: Create the following docker-compose.yaml file in an empty directory of your choice


text:
Q: Differences between times in Ruby I am trying to figure out the difference between two times within a current timezone. I'm trying to figure out whether to call a support telephone number between two times. I.e., I am using the active_support gem and I want to do something like

*

*t = current time

*o = open time according to current date (9AM)

*c = close time according to current date (5PM)

*call_open = are we open?

Would someone be able to help?

A: I believe you could do
call_open = t.between?(o, c)

A: t = Time.zone.now
o = Time.zone.today + 8.hours
c = Time.zone.today + 17.hours
call_open = t <= c && t >= o

A: You can use Time to create ranges, which allows easy testing for inclusion:
t1 = Time.now
sleep 1
t2 = Time.now
sleep 1
t3 = Time.now

(t1.to_i .. t3.to_i) === t2.to_i # => true
(t1.to_f .. t3.to_f) === t2.to_f # => true
(t1.to_f .. t2.to_f) === t3.to_f # => false

You can use parsing to figure it out:
starttime = Time.parse('2013/01/24 9AM')                               # => 2013-01-24 09:00:00 -0700
endtime = Time.parse('2013/01/24 5PM')                                 # => 2013-01-24 17:00:00 -0700
(starttime.to_f .. endtime.to_f) === Time.parse('2013/01/24 3PM').to_f # => true

And you can work with hours only, which makes it date agnostic:
(t1.hour .. t3.hour) === t2.hour # => true


text:
Q: Insert con Inner Join MSSQL Buen día a todos.
Hoy se presentó un inconveniente en SQL Server cuando intentaba realizar un insert en una tabla utilizando datos de otras tablas:
INSERT INTO OtraDB..UnaTablaX (
    [nombre],
    [apellido],
    [region],
    [ciudad]
)
SELECT
    p.[nombre],
    p.[apellido],
    r.[value],
    c.[value]
FROM
    UnaDB..Persona p
    INNER JOIN UnaDB..Regiones r ON r.[id] = p.[regionId]
    INNER JOIN UnaDB..Ciudades c ON c.[id] = p.[ciudadId]
WHERE
    p.[id] = 1

Eso funciona sin problemas en condiciones normales. Sin embargo, no tengo control del formulario que inserta datos en la tabla Persona, y los campos [regionId] y [ciudadId] pueden recibir campos en blanco, lo cual guardan como 0.
El problema final viene que, al ejecutar la instrucción, si alguno de esos 2 campos viene en 0, no se insertan los datos, ya que no existe el id 0 en las tablas Regiones o Ciudades, ambas comienzan desde el id 1 y es identity. No arroja ningún error, solo dice que fueron afectadas 0 filas.
Cabe destacar que no tengo control sobre las tablas ni sobre el formulario, solo debo realizar las inserciones. Además, la tabla de inserción no acepta nulos en ninguno de sus campos.
Solucioné este problema con un procedimiento algo largo, seteando variables y usando cases, pero siento que no es lo más correcto, debe haber alguna forma elegante de solucionar aquello y por eso vengo aquí.
Gracias de antemano a cualquier que lea esto y todos los comentarios son aporte.

A: La inserción se puede lograr utilizando el enfoque que ya traías, de usar una sentencia insert/select, pero hay que hacer algunos ajustes, veamos:
La inserción afecta 0 filas porque el select devuelve 0 filas. Así que, para comenzar, concentrémonos en que el select devuelva la fila que esperamos aún cuando no haya registros coincidentes en las tablas relacionadas.
Lo que podemos hacer es un left join y no un inner join, de esta manera, aunque se haya insertado registros cuyo id de región o de ciudad no exista, nos devolverá los datos de la persona, siempre que esta si exista.
select   p.nombre
       , p.apellido
       , r.value
       , c.value
  from UnaDB..Persona p
       left join UnaDB..Regiones r on r.id = p.regionId
       left join UnaDB..Ciudades c on c.id = p.ciudadId
 where p.id = 1

El problema que tenemos ahora es que, al no existir registro que coincida en la tabla Regiones, r.value nos devolverá null y no el nombre de una región, igual pasa con ciudad. Dado que has dicho que la tabla donde vas a insertar la información no soporta nulls en dichas columnas, podemos resolverlo al definir un valor default, que iría en cada campo en caso de no haber coincidencia en región, ciudad o ambas. Puede ser cualquier cadena, por ejemplo: 'desconocida'.
Para lograr esto, nos podemos valer de la función coalesce().
Poniendo las piezas juntas:
insert into OtraDB..UnaTablaX (nombre, apellido, region, ciudad)
select   p.nombre
       , p.apellido
       , coalesce(r.value, 'desconocida')
       , coalesce(c.value, 'desconocida')
  from UnaDB..Persona p
       left join UnaDB..Regiones r on r.id = p.regionId
       left join UnaDB..Ciudades c on c.id = p.ciudadId
 where p.id = 1

Esto debiera realizar la inserción de manera exitosa.


text:
Q: object Error on epenusing dojo.xhrPost and dijit.byID together in IE6 I am new in DOJO and facing some problem on using dojo.xhrPost and dijit.byID together.
Any pointer highly appreciated.
Using two functions, both are working fine independently but on using them together. I'm getting "object error" on IE6.
See below two function
function submitForm(obj,form){
dojo.xhrPost( {
    url : pageFlowURL,
    preventCache : true,
    timeout : ajaxTimeout,
    form : pageFormElem,
    load : function(response, ioArgs) {
        if (condition) {
                    do something...
        }else{
        loaderCheck();
        }
        },
        error: function(error) {
        // an error has occurred
        alert("error : "+error);
            }
});
}

function loader() {
dojo.require("dijit.Dialog");
if (!parsed) {
    dojo.parser.parse(dijit.byId("loaderdiv"));
    parsed = true;
}
alert(dijit.byId("loaderdiv"));
loaderdiv = dijit.byId("loaderdiv");
loaderdiv.titleBar.style.display = "none";
dijit.byId("loaderdiv").show();
dojo.addClass("dijit_DialogUnderlay_0", ["loaderdiv_underlay"]);}

getting "object error" in (IE6) function loader() on line
loaderdiv = dijit.byId("loaderdiv");
whereas getting successful alert just above that on code alert(dijit.byId("loaderdiv"));
HTML code is:

test

A: Are you sure that the dijit.Dialog has a titleBar property?  According to the docs http://dojotoolkit.org/api/dijit.Dialog it doesn't...  It sounds more like you're getting an error trying to set style.display on the undefined loaderDiv.titleBar...
(You can test by alerting loaderDiv.titleBar or by using a more modern browser's built-in debugging console).


text:
Q: Can I get the current URL without an address bar? I use the code below to get the current url, and the hash ID it has after the forward slash for my domain. I would like to get the current URL of a page loaded in an iframe which means there's no address bar of course. How would I go about doing this?
the code I'm using now:
var currentURL = (document.URL);
var part = currentURL.split("SLASH")[1];
alert(part); // alerts "XdAs2" !!!

A: For security reasons, you can only get the url for as long as the contents of the iframe, and the referencing javascript, are served from the same domain. As long as that is true, something like this will work:
document.getElementById("iframe_id").contentWindow.location.href

If the two domains are mismatched, you'll run into cross site reference scripting security restrictions.

A: if it's an iframe  using jquery you can do
$('iframe').attr('src')

example :
http://jsfiddle.net/aFX8b/

A: The current URL is always in window.location, be it inside an iframe or in the root frame of the browser. The window object always refers to the current viewport.
Demonstration.


text:
Q: Longitudinal waves We see that, in longitudinal waves, particles move to (forward) and fro (backward), but why? When a particle has been shifted forward, why will it even come back and vibrate around it's initial position. Why not just move forward and ultimately stop due to losing its energy, unless again pushed by some other wave or energy?
Is it because of pressure difference and diffusion process? If yes then why only to and fro?

A: A longitudinal wave is created by something shaking forward and then backward. When moving forward, it sets a volume of air right next to its surface in motion in that direction, but since air is compressible, the forward-moving slice of air is also compressed. That compressed air looks for the first opportunity it can to expand out again, which it does by pressing forward on the next slice of air, which compresses slightly, starts to move, and then begins compressing the next slice.
Note also that because each slab or slice of air here has mass, it resists being set into motion, enhancing the compression effect.
Meanwhile, the vibrating object has begin moving in the opposite direction and is now expanding the slab of air sitting right next to it, and sets it in motion backwards. That slice of air wants to shrink back to its original volume and it begins doing so by pulling backwards on the air slab right next to it, which is set in motion backwards, which expands it, which makes it pull on the next slab, and so on.
Note also that once again because of the inertia of the air in the slab, it resists being pulled backwards once it has been set into forward motion, which enhances the decompression effect.
In this way, a zone of low pressure propagates away from the backwards-moving surface, following right on the heels of the zone of higher pressure which is also moving away from the vibrating surface.
Then the moving surface reverses direction , starts pushing on the adjacent air slab again, and there whole process repeats itself. A moving wave train of alternating high and low pressure zones is the final result.
The key to understanding wave propagation in a medium like this is to separate the bulk volume of the medium up into thin slabs next to one another and realizing that each discrete slab possess both mass and compliance, and that those slabs communicate with each other by exerting forces on one another.
That is how you get longitudinal waves.

A: There must be a restoring force which acts to move each particle back towards its equilibrium position. Without a restoring force you cannot have a wave.
Typically the restoring force will be provided by repulsive forces between adjacent particles which make it energetically favourable for each particle to occupy a position mid-way between its neighbours.

A:
When a particle has been shifted forward, why will it even come back and vibrate around it's initial position.

You are inhibited in your reflections by the example of air. Instead, take a metal rod and strike one end. The longitudinal wave will propagate to the other end, but all atomic structures (except possibly at the point of impact) will remain in place after the oscillation. The elasticity of the material allows the wave to propagate, but not permanent material displacements.
It is similar with air, but there one should speak of viscosity. There are also side effects, such as air turbulence at the edge of the sound cone.


text:
Q: JSON has the same identifier for a property and a field, how can I get around this? The following is a snippet of some JSON that I am receiving from a 3rd party API.
    {"for":
        {
          "total":
            {"home":0,"away":0,"total":0},
          "average":
            {"home":"0.0","away":"0.0","total":"0.0"},

          "total":1,
          "average":"0.5"
        }
    }

The classes I have for deserialisation:
     public class For {
        public int total { get; set; }
        public string average { get; set; }

        public Total total { get; set; }
        public Average average { get; set; }
        public Minute minute { get; set; }

        public int home { get; set; }
        public int away { get; set; }
    }

    public class Total {
        public int home { get; set; }
        public int away { get; set; }
        public int total { get; set; }
    }

    public class Average {
        public string home { get; set; }
        public string away { get; set; }
        public string total { get; set; }
    }

The error:

An unhandled exception of type 'Newtonsoft.Json.JsonReaderException' occurred in Newtonsoft.Json.dll

Additional information: Unexpected character encountered while parsing value: {. Path 'response[0].for.total', line 1, position 1047.

The error when changing the case of a property and using [JsonProperty(PropertyName = "total")]

Additional information: A member with the name 'total' already exists on 'namespace1.For'. Use the JsonPropertyAttribute to specify another name.

A: Jason tolerates  duplicate keys, but only the last one will be assumed. C# doesn't allow any double properties, so the easiest way I see is to rename json keys. And since nobody creates Json manually, but computer will always create the same pattern, the easiest way to do this , just to use the string functions ( or you can try regex for example).
Try this
json=json.Replace("total\":{", "totalDetails\":{").Replace("average\":{","averageDetails\":{");

var jsonDeserialized = JsonConvert.DeserializeObject<Root>(json);

output
{"for":{"totalDetails":{"home":0,"away":0,"total":0},"averageDetails":{"home":"0.0","away":"0.0","total":"0.0"},"total":1,"average":"0.5"}}

classes
public class Root
{
    public For @for { get; set; }
}

public class TotalDetail
    {
        public int home { get; set; }
        public int away { get; set; }
        public int total { get; set; }
    }

    public class AverageDetail
    {
    public string home { get; set; }
    public string away { get; set; }
    public string total { get; set; }
}

public class For
{
    public TotalDetail totalDetails { get; set; }
    public AverageDetail averageDetails { get; set; }
    public int total { get; set; }
    public string average { get; set; }
}


text:
Q: Memory Mapped File VS Named Pipe - C# In this Article:
https://blogs.msdn.microsoft.com/salvapatuel/2009/06/08/working-with-memory-mapped-files-in-net-4/
It exclaims that:

The memory mapped file is the most efficient way for multiple processes on a single machine to communicate with each other.

If this statement is valid, then what exactly is the difference between using a MMF for inter-process comms and using a Named Pipe?

A: Named Pipe is used for short message between 2 or more processess, and in my experience, it's slow.
If you want to share much data then the use of MMF is correct.


text:
Q: Polymer: write demo and tests for a component that reacts to server response I wrote an element that is meant as a container of , and that sets fields as invalid depending on the server response.
I would love to write demo and tests for this component. However, both demo and tests require the component to receive a response from a server (the form gets submitted, and fields are set accordingly).
Is there a way to write something like this in Polymer?

A: The answer is simple and straightforward: use SinonJs. Specifically, use the fakeServer feature which rewrites the Ajax call in the browser so that you application actually "thinks" it's talking to a server. Easy.
I am using it myself in hot-form-validator.


text:
Q: Getting "collect2: error: ld returned 1 exit status" I see this error message when I try to run almost any code
cant figure out why
 collect2: error: ld returned 1 exit status

for example when i run this simple code
#include <stdio.h>
#include <omp.h>

int main() {

  printf ("Hello, world:");
  #pragma omp parallel
    printf (" %d", omp_get_thread_num ());
  printf ("\n");
  return 0;
}

tried other simple codes but nothing is working

A: You need to compile your code with the flag -fopenmp. For example:
gcc -fopenmp -O3 -w -Wall -pedantic main.c

From source one can read:

Enabling OpenMP
To activate the OpenMP extensions for C/C++ and Fortran, the
compile-time flag -fopenmp must be specified. This enables the OpenMP
directive #pragma omp in C/C++ and !$omp directives in free form,
c$omp, *$omp and !$omp directives in fixed form, !$ conditional
compilation sentinels in free form and c$, *$ and !$ sentinels in
fixed form, for Fortran. The flag also arranges for automatic linking
of the OpenMP runtime library (Runtime Library Routines).


text:
Q: Get Latitude and Longitude from a column in a dataframe I'm trying to get the latitude and longitude from the 'coordinates' column in the following dataframe and create the respective 'latitude' and 'longitude' columns in the same df without success.
import pandas as pd
test_df = pd.DataFrame({'name': ['Wakefield', 'Co-op City'],
                   'coordinates': ['[[-73.84720055104846, 40.89470566842616]]', '[[-73.82993909620285, 40.87429474550749]]']})

The code:
test_df['Lat'] = test_df.coordinates.str.split('[[',1)[1].split(']]')[0].split(', ')[1]
test_df['Lon'] = test_df.coordinates.str.split('[[',1)[1].split(']]')[0].split(', ')[0]

Output:
error: unterminated character set at position 0

However if I do the same on a single string it works.
coord = '[[-73.84720055104846, 40.89470566842616]]'
#longitute
longitude = coord.split('[[',1)[1].split(']]')[0].split(', ')[0]
print('Longitude: ',longitude)

Longitude:  -73.84720055104846

Does anyone know how to solve it?
Thanks

A: In this dataframe you have a string not a list, so you need to use pandas string accessor, .str and using string methods.
Use this code:
test_df[['Lat', 'Long']] = test_df['coordinates'].str.strip('\[|\]')\
                                                 .str.split(',', expand=True)

test_df

Output:
         name                                coordinates                 Lat                Long
0   Wakefield  [[-73.84720055104846, 40.89470566842616]]  -73.84720055104846   40.89470566842616
1  Co-op City  [[-73.82993909620285, 40.87429474550749]]  -73.82993909620285   40.87429474550749


text:
Q: What error should be thrown for impossible conditions? public static double findLCM (int num1, int num2) {

        for (int i = 1; i <= num2; i++) {
            double mult = big * i;
            if (mult % small == 0) {
                return mult;
            }
        }
        throw new Error("Error");
    }

As we know, it is impossible to not have an LCM. Please dont suggest me workarounds for the code like return variable after breaking from for loop etc. This code is custom made to understand the exception to be thrown.

A: The closest fit may be an IllegalArgumentException:

Thrown to indicate that a method has been passed an illegal or inappropriate argument.

A: I think you can use Exception
You can say:
throw new Exception("Error");

This will solve you problem. I am not 100 % sure but it worked for me many times.

A: Since this is a high-ranking search result, I felt the need to add a response.  @UnknownJoe left a comment on the question that, in my opinion, should be the correct answer for the general case, while @manouti's answer (accepted) is the correct answer for the specific case.
If there is any chance that a section of code could be accessed during the execution of the program due to invalid arguments being passed to the method, then IllegalArgumentException is the correct exception to throw; after all, it was an illegal argument that led to that code being executed.  In the example provided, if I passed a 0 in as the second argument, I'd have the exception thrown.
My personal use case for this was with MessageDigest algorithms. Since a known set of algorithms has been provided since Java 1.5, I can feel free to directly reference any of these by name and not worry about the potential NoSuchAlgorithmException.  While I could swallow the exception, wrapping it in an IllegalStateException allows me to pass it up the chain if my code's being run on a non-standard implementation, or if something's very wrong with the environment; more importantly, however, I'll know why my program is failing.
So in short: if your code can be accessed accidentally by providing invalid arguments, use InvalidArgumentException.  If your code cannot be accessed normally and only by a fluke of the JVM, use IllegalStateException.


text:
Q: Visual Studio 2010 Problem with .NET 4.0 Today I opened an C++ Project, but I just receive the "Project Target Framework Not Installed" (Targeted framework:  .NETFramework,Version=v4.0)
At first my Project does not use any .NET Framework / CLR. (Win32 Console Application)
At second I have 4.0 installed.
At third in the Project XML File I does not found an TargetFramework Setting.
I reinstalled VS2010, I tried to (re)install .NET 4.0, Nothing -.-
Why VS2010 ask for .NET 4.0 in a Win32 Project ?
So I tried to open a older Project, but just the same.

A: I got my own Solution for my problem here is it, if someone have the same.
I just added:
<TargetFrameworkVersion>v3.5</TargetFrameworkVersion>

at
<PropertyGroup Label="Globals">

I don´t know why it don´t find 4.0 but 3.5. But no matter. Win32 without CLR dont need any .NET.


text:
Q: How to make an OUTGOING websocket connection request in GO I find a lot of examples of how to make a websocket service in Go that accepts ws connections, but not one to send them.
Since the ws request is initially executed as a normal rest request, I try something like this
request, err := http.NewRequest("GET", "ws://localhost:8081/ws", nil)
if err != nil {
    fmt.Println(err)
    return
}

_, err = http.DefaultClient.Do(request)
if err != nil {
    fmt.Println(err)
    return
}
client := newClient(*websocket.Conn) // how i can get *websocket.Conn?
go client.Read()
go client.Write()
clientsMap.Add(client)

But this obviously doesn't work, I get an unsupported protocol scheme "ws" error.
How do I make a ws connection and get *websocket.Conn?

A: If you are using gorilla websocket, you can use Dialer.Dial or Dialer.DialContext from that package. Below is the example on how to use it.
dial, _, err := websocket.DefaultDialer.Dial("ws://localhost:8081/ws", nil)
if err != nil {
    log.Fatalln(err)
}
defer dial.Close()

err = dial.WriteMessage(websocket.TextMessage, []byte("hello"))
if err != nil {
    log.Fatalln(err)
}

err = dial.WriteMessage(websocket.TextMessage, []byte("world"))
if err != nil {
    log.Fatalln(err)
}

For the full code, you can check this.
package main

import (
    "log"
    "net/http"
    "sync"

    "github.com/gorilla/websocket"
)

func main() {
    wg := sync.WaitGroup{}
    wg.Add(2)

    // Server
    go func() {
        defer wg.Done()

        var (
            upgrader = &websocket.Upgrader{}
            stopChan = make(chan struct{})
        )

        http.HandleFunc("/ws", func(w http.ResponseWriter, r *http.Request) {
            defer func() {
                close(stopChan)
            }()

            upgrade, err := upgrader.Upgrade(w, r, nil)
            if err != nil {
                return
            }
            for {
                msgType, msg, err := upgrade.ReadMessage()
                if err != nil {
                    log.Println("connection closed,", err)
                    return
                }
                log.Println(msgType, string(msg))
            }
        })

        go func() {
            err := http.ListenAndServe("localhost:8081", nil)
            if err != nil {
                log.Fatalln(err)
            }
        }()

        <-stopChan
    }()

    // Dialer (Client)
    go func() {
        defer wg.Done()

        dial, _, err := websocket.DefaultDialer.Dial("ws://localhost:8081/ws", nil)
        if err != nil {
            log.Fatalln(err)
        }
        defer dial.Close()

        err = dial.WriteMessage(websocket.TextMessage, []byte("hello"))
        if err != nil {
            log.Fatalln(err)
        }

        err = dial.WriteMessage(websocket.TextMessage, []byte("world"))
        if err != nil {
            log.Fatalln(err)
        }
    }()

    wg.Wait()
}

// output
// 2022/09/17 07:18:57 1 hello
// 2022/09/17 07:18:57 1 world
// 2022/09/17 07:18:57 connection closed, websocket: close 1006 (abnormal closure): unexpected EOF


text:
Q: Accessing s3 bucket from .net I can successfully view files in an S3 bucket using WinSCP, by supplying the following settings:

*

*file protocol = Amazon S3

*host name = s3.amazonaws.com

*access key ID

*secret access key

*remote directory = my subfolder (under advanced)

However, I want to do the same using .NET Core and I'm having trouble. I've installed the AWSSDK.S3 nuget package and have the following code:
foreach (var region in RegionEndpoint.EnumerableAllRegions)
{
    try
    {
        var request = new ListObjectsV2Request()
        {
            BucketName = bucket,
            MaxKeys = 10
        };

        using (var client = new AmazonS3Client(accessID, secret, region))
        {
            var response = await client.ListObjectsV2Async(request);
            Console.WriteLine(response.S3Objects.Count);
        }
    }
    catch (Exception e)
    {
        Console.WriteLine(e.Message);
    }
}

I don't know the region, so I tried them all and I get exceptions saying: "The specified bucket does not exist".
WinSCP works so I must have the right settings, but I don't know if I've configured the .NET library correctly. Are the credentials I've been supplied not the standard type? Am I using the wrong library/protocol in .net?


text:
Q: Cannot access localhost subdomain created with Traefik I write a simple docker-compose file as such:
version: '3'

services:
  traefik:
    image: traefik:v2.9
    command:
      - "--providers.docker=true"
      - "--entrypoints.web.address=:80"
      - "--api.insecure=true"
    ports:
      - "80:80"
    volumes:
      - /var/run/docker.sock:/var/run/docker.sock:ro
    labels:
      - "traefik.enable=true"
      - "traefik.http.routers.traefik.rule=Host(`traefik.localhost`)"
      - "traefik.http.routers.traefik.entrypoints=web"
      - "traefik.http.routers.traefik.service=api@internal"
    networks:
      - traefik-net

  swagger:
    image: swaggerapi/swagger-ui
    labels:
      - "traefik.enable=true"
      - "traefik.http.routers.swagger.rule=Host(`swagger.traefik.localhost`)"
      - "traefik.http.routers.swagger.entrypoints=web"
      - "traefik.http.services.swagger.loadbalancer.server.port=8080"
    networks:
      - traefik-net

networks:
  traefik-net:
    driver: bridge

The idea was to have Traefik dashboard accessible at traefik.localhost, while the swagger-ui can be reached at swagger.traefik.localhost. It works on my personal machine perfectly, but on my work machine, with proxies to corpo network, traefik.localhost works, but not swagger.traefik.localhost. I did exclude *.localhost and 127.0.0.1 from docker config proxy, but it still does not work and I cannot debug why.
Traefik shows that swagger status as success which I also do not understand. Any help is appreciated. Thanks!
Tried adding *.localhost to docker config no_proxy. Did not succeed with that.
Expected result: swagger.traefik.localhost is accessible via browser.


text:
Q: HTML форма регистрации Помогите пожалуйста разобраться.
Есть форма регистрации.

HTML
<form class="form" method="post" action="yourpage.html">
    <input type="text" class="name" placeholder="Name" autocomplete="off" id="name">

Please enter your first and last name.

    <input type="email" class="email" placeholder="Email" id="email" autocomplete="off">

Please enter your current email address.

    <%--<input type="password" class="name" placeholder="Password" id="password" autocomplete="off">--%>
    <%--
--%>
        <%--
Please enter your password.
--%>
    <%--
--%>

    <input type="submit" class="submit" value="Register">
</form>

если убрать коммент с пасворда, то получается это

Собственно вопрос: почему имайл переквалифицировался (самостоятельно) в юзер, почему на эти два инпута не действует CSS, почему это так происходит и как это можно исправить?
Заранее спасибо.


text:
Q: How to handle routes on page refresh in angular2 I have parent routes like this
export const routes: Routes = [
  { path: '', redirectTo: 'posts', pathMatch: 'full' },
  { path: 'posts', component: PostsComponent, children: PostRoutes }
];

Now the children routes are like this
export const PostRoutes = [
  { path: '', component: PostsListComponent },
  { path: ':id', component: PostDetailComponent }
]

Now when I navigate to localhost:4200 or localhost:4200/posts it select the first child route and render PostsListComponent, which lists all the posts. when i click on single post then it takes me to the URL localhost:4200/posts/1 and render PostListComponent which list one single post and it details.
Now the problem is when i reload the page with this this route localhost:4200/posts/1, It takes me to the base URL localhost:4200 and gives me error that cannot read property comments of undefined, since posts has many comments.
The problem is since on reloading the page, posts array is null, so it is not able to select a post with the postId from the URL. so it is giving me above error.
So how to manage that on reloading the page, first all posts must be loaded.
Below is my posts.component.html

  <router-outlet></router-outlet>

Below is my posts-list.component.html

{{post.description}}

A: Use a guard for the routes that depend on data to be loaded, that only completes after the data is available.
See https://angular.io/docs/ts/latest/guide/router.html#!#guards for documentation.


text:
Q: Is there a way to automate specific data extraction from a number of pdf files and add them to an excel sheet? Regularly I have to go through a list of pdf files and search for specific data and add them to an excel sheet for later review. As the number of pdf files are around 50 per month, it is both time taking and frustrating to do it manually.
Can the process be automated in windows by python or any other scripting language? I require to have all the pdf files in a folder and run the script which will generate an excel sheet with all the data added. The pdf files with which I work are tabular and have similar structures.

A: Yes. And no. And maybe.
The problem here is not extracting something from a PDF document. Extracting something is almost always possible and there are plenty of tools available to extract content from a PDF document. Text, images, whatever you need.
The major problem (and the reason for the "no" or "maybe") is that PDF in general is not a structured file format. It doesn't care about columns, paragraphs, tables, sentences or even words. In the general case it cares only about characters on a page in a specific location.
This means that in the general case you cannot query a PDF document and ask it for every paragraph or for the third sentence in the fifth paragraph. You can ask a library to get all of the text or all of the text in a specific location. And then you have to hope the library is able to extract the text you need in a legible format. Because there doesn't even have to be the case that you can copy and paste or otherwise extra understandable characters from a PDF file. Many PDF files don't even contain enough information for that.
So... If you have a certain type of document and you can test that it predictably behaves a certain way with a certain extraction engine, then yes, you can extract information from a PDF file.
If the PDF files you receive are different all the time or the layout on the page is totally different every time than the answer is probably that you cannot reliably extract the information you want.
As a side note:
There are certain types of PDF documents that are easier to handle than others so if you're lucky that might make your life easier. Two examples:

*

*Many PDF files will in fact contain textual information in such a way that it can be extracted in a legible way. PDF files that follow certain standards (such as PDF/A-1a, PDF/A-2a or PDF/A-2u etc...) are even required to be created this way.

*Some PDF files are "tagged" which means they contain additional structural information that allows you to extract information in an easier and more meaningful way. This structure would in fact identify paragraphs, images, tables etc and if the tagging was done in a good way it could make the job of content extraction much easier.

A: You could use pdf2text2 in Python to extract data from your PDF.
Alternatively you can use pdftotext that is part of the Xpdf suite


text:
Q: It there 32-bit version of OpenCL (any vendor) for Linux? Bypassing the obvious "why??", does anyone know of any 32-bit versions of OPENCL from Nvidia or Intel for Ubuntu?
I looked but, i could not find anything recent. Have they finally just jumped to 64-bit only?
Thanks,
Paul

A: The AMD App SDK allows you to execute OpenCL on your CPU.
Otherwise you can try out pocl which also allows OpenCL execution on your CPU.
Beignet (OpenCL on Intel GPUs) might compile on a 32bit linux.
Probablye you also need an OpenCL ICD like this one: khronos
That said, I recommend that you move to a 64bit system, I could imagine that especially with OpenCL where vectorization is important you might loose quite some performance, since you cannot use all AVX/AVX2 registers on x86-32.
Best Regards,
Michael


text:
Q: Accidentally zeroed first 20GB of 2.73TB ext4 partition. Any way to recover the rest? I accidentally repartitioned a wrong hard drive and seems like the first 20GB of the 2.7TB disk was lost (some belonging to old partition).
If I examine the disk with (new partition sdd1 starts after 20GB):

dd if=/dev/sdd1 count=1000000 | strings | sed -nr '/^.{8,149}$/p'

I will see some contents of my old files, but nothing on the first 20GB of /dev/sdd.
Is there some way to recover the files that exist in the hard drive after the first 20GB?


text:
Q: What is the most popular generic collection data structure library for C? I'm looking for a C library that provides generic collection data structures such as lists, associative arrays, sets, etc. The library should be stable and well tested. I'm basically looking for something better than the crappy C standard library.
What C libraries fit this description?
EDIT: I'd prefer that the library was cross-platform, but failing that, anything that works on Mac/Linux.

A: Apache Portable Runtime has collections (e.g. hash table, linked list) and is, well, portable.

A: if you are on linux, i would use GLIB.  it provides all the helper libraries you would expect, plus its very well maintained and very active (always a +).  the link above is straight to the section on data structures, but there is plenty of other things in GLIB so take a look around!


text:
Q: Delete all fields having value 5x lower then top field I have a table (prices) with two fields, code (char) and price (decimal).
I need to find all fields with same code, having price 5x lower then top price. E.g, in this case:
id   code   price
1    1001   10
2    1001   101
3    1001   40
4    1002   10
5    1002   122
6    1002   50

I need to delete fields with id 1 and 4. I'm trying smth. like this:
DELETE FROM `prices` WHERE `code` IN (SELECT `code` FROM `prices` sa WHERE `code` IN (SELECT `code` FROM `prices` WHERE `price`>sa.`price`*5) and sa.code=prices.code);

But I'm not sure this is right way.
The next task is to delete all fields, 3x lower then two top fields. So, if we have minimum two fields higher than 100, we need to delete all fields lower than 25.

A: You would use join and aggregation:
delete p
    from prices p join
         (select p.code, max(price) as max_price
          from prices p
          group by p.code
         ) pp
         on pp.code = p.code and pp.price < p.price * 0.2;


text:
Q: Which responsibilities should repository finder methods have? TL;DR
Should a DDD repository:

*

*perform generic searches refined later by a domain services?

findAllByPurchaseId(purchaseId)

*

*or maybe detailed searches tailored to a specific use case?

findAllOfPurchaseDueBefore(purchaseId, limitDate)

*

*do additional simple calculations (like summing)?

amountExpectedToBePaidBefore(purchaseId, limitDate)
Background of the question
My domain model has two aggregates:

*

*Purchase(purchaseId)

*Installment(purchaseId, dueDate, amount)
In one of my application services I have to answer the question about the total installment amount expected to be paid before a certain date.
Initial InstallmentRepository implementation (Groovy + Grails + GORM + Hibernate):
def findAllByPurchaseId(purchaseId) {
    Installment.executeQuery(
        'from Installment where purchaseId = :purchaseId',
        [purchaseId: purchaseId]
    )
}

The application service did further filtering and calculation:
def amountExpectedToBePaidBefore(purchaseId, limitDate) {
    def installments = installmentRepository.findAllByPurchaseId(purchaseId).
        findAll { it.dueBefore limitDate }
    installments*.amount.sum()
}

I realised that my application service had domain logic - it did additional filtering and calculations. On the other hand my repository seemed to be too DAOish - it did simple aggregate access without any additional business value.
I consider two refactoring options:

*

*place the filtering by dueDate in the repository and sum amounts in a domain service

*do everything in the repository (amount sum is a simple calculation)

Since a repository should be mimicking a specialized collection of aggregates, with the API based on the ubiquitous language, option 2. is more appealing to me.
Which abstraction/detail level should a DDD repository have?

*

*Should it perform generic searches, used by possibly many services?

*Should/could repository finders be application service/use case specific?

*Is it OK to have additional (though simple) calculations in a repository?

A: *

*No. The Domain repository queries are usually GetById(). It's not a hard rule, but this is what domain needs 99% of time. Don't re-use the domain repository interface for presentation/reporting queries. That is, the concrete class can handle everything but the abstraction should be tailored by the context needs.

*If the Domain needs that yes, the repository method gets a criteria to work with.

*If processing doesn't require business rules then it's ok. However that's not really a repository semantic, that's a service which happens to be implemented in DAL. So yes, but don't call it a repository :)


text:
Q: iOS / Xcode 4: View won't load This is really frustrating as I've tinkered with previous versions of Xcode and have done this before but playing around with a new app now, it's not working for some reason.
I have the app open to a UITableView and want it to load to a detail UIView once I select a cell. However, when I choose a cell in the iPhone simulator, it just highlights the cell blue and doesn't load the view.
Here is the code I'm using the the RootViewController:
-(void)tableView:(UITableView *)tableView didSelectRowAtIndexPath:(NSIndexPath *)indexPath {
WorkoutViewController *workoutViewController;
workoutViewController = [[WorkoutViewController alloc] initWithNibName:@"WorkoutViewController" bundle:nil];
workoutViewController.workoutName = [workouts objectAtIndex:indexPath.row];
[self.navigationController pushViewController:workoutViewController animated:YES];
[workoutViewController release];
workoutViewController = nil;

I have the view linked to the File Owner in the WorkoutViewController.xib file. When I put in a breakpoint at @implementation WorkoutViewController, it does get to that breakpoint but it goes to the @synthesize line and then jumps right back out to [self.navigationController ...etc]; and never returns back to the WorkoutViewController.m file.

A: I would guess that you didn't set the ViewController to be the TableView's delegate. To check, open your ViewController xib-file and rightclick FilesOwner. Under Referencing Outlet you would usually have both delegate and data source" connected to your TableView. If that is not the case, drag New Referencing Outlet to your TableView.
If I'm wrong and they are all connected, you might want put a breakpoint at the beginning of your didSelectRowAtIndexPath method. Does the debugger stop there, once you select a row?
It might also be worth mentioning that a breakpoint at @implementation usually doesn't make much sense, you would rather want to place it in a method like init. Also, even though you are using Xcode 4 now, this is unlikely to be the cause of your problem, it looks more like an implementation issue.
Hope this helps, if you need further help just let me know!

A: Doh! Problem resolved. I had forgotten to actually put the RootViewController into a navigation controller on the MainWindow.xib. Appreciate the responses.


text:
Q: No index signature with a parameter of type 'string' was found on type '{}' First I'll put out the layout of my problem:
interface FilteredProducts {
    [key: string]: {
        [key: string]: object;
    };
};

I initialise filterProducts to an empty object because the only time I put values in it is in an if, so I need to do that for later use
products: FilteredProducts
let filteredProducts: object = {};

Here I assign an object to filterProducts ->
if (filters.season && filters.dimension) {
        filteredProducts = (products[filters.season] || {})[filters.dimension];
    };

If a specific filter is set I want to delete a property of this object
if (productKey && Object.entries(filteredProducts).length > 0) {
       delete filteredProducts[productKey];
}

The problem is that it says that:

Element implicitly has an 'any' type because expression of type 'string' can't be used to index type '{}'.
No index signature with a parameter of type 'string' was found on type '{}'

when I try to delete this key.
I tried to set the type for filteredProducts ->
interface FilteredInterface {
    [key: string]: object;
}

But then I get

Type 'object' is not assignable to type 'FilteredInterface'.
Index signature is missing in type '{}'.

When I try to assign that object to filterProducts. (the code in the first if)
Here is the full code for this part:
interface FilteredProducts {
    [key: string]: {
        [key: string]: object;
    };
};

const filter = (products: FilteredProducts, filters: UserFiltersInterface): object => {
    let filteredProducts: FilteredInterface = {};
    // console.log('products', products);
    // console.log('filters', filters);
    if (filters.season && filters.dimension) {
        filteredProducts = (products[filters.season] || {})[filters.dimension];
    };
    if (filters.tire_size) {
        // console.log('filteredProducts tire_size', filters.tire_size);
        if (Object.entries(filteredProducts).length > 0) {
            // console.log('filteredProducts', filteredProducts);
            if (filters.tire_size !== 'all') {
                Object.entries(filteredProducts).forEach((product) => {
                    const productKey: string = product[0];
                    const productInfo = product[1];
                    if (productInfo.size !== filters.tire_size) {
                        if (productKey && Object.entries(filteredProducts).length > 0) {
                            delete filteredProducts[productKey];
                        }
                    }
                });
            };
        };
    };
    // console.log('filteredProducts', filteredProducts);
    return filteredProducts;
};

A: You need to specify that what you want to be returned (products[filters.season])[filters.dimension] is a FilteredInterface object. Because you want to store it in filteredProducts: FilteredInterface.
You can do it here (replace object):
interface FilteredProducts {
    [key: string]: {
        [key: string]: FilteredInterface;
    };
};

Or here (a cast, and you keep the object in FilteredProducts:
filteredProducts = (products[filters.season])[filters.dimension] as FilteredInterface;

Edit: see this TS Playground


text:
Q: Sequential, subsequent loading of files gets much slower over time I've got the following code to read and process multiple very big files one after another.
for(j = 0; j < CORES; ++j) {
    double time = omp_get_wtime();
    printf("File: %d, time: %f\n", j, time);

    char in[256];
    sprintf(in, "%s.%d", FIN, j);

    FILE* f = fopen(in, "r");
    if (f == NULL)
        fprintf(stderr, "open failed: %s\n", FIN);
    int i;
    char buffer[1024];
    char* tweet;
    int takeTime = 1;
    for (i = 0, tweet = TWEETS + (size_t)j*(size_t)TNUM*(size_t)TSIZE; i < TNUM; i++, tweet += TSIZE) {
        double start;
        double end;
        if(takeTime) {
            start = omp_get_wtime();
            takeTime = 0;
        }
        char* line = fgets(buffer, 1024, f);
        if (line == NULL) {
            fprintf(stderr, "error reading line %d\n", i);
            exit(2);
        }
        int fn = readNumber(&line);
        int ln = readNumber(&line);
        int month = readMonth(&line);
        int day = readNumber(&line);
        int hits = countHits(line, key);
        writeTweet(tweet, fn, ln, hits, month, day, line);

        if(i%1000000 == 0) {
            end = omp_get_wtime();
            printf("Line: %d, Time: %f\n", i, end-start);
            takeTime = 1;
        }
    }
    fclose(f);
}

Every file contains 24000000 tweets and I read 8 files in total, one after another.
Each line (1 tweet) gets processed and writeTweet() copies a modified line in one really big char array.
As you can see, I measure the times to see how long it takes to read and process 1 million tweets. For the first file, its about 0.5 seconds per 1 million, which is fast enough. But after every additional file, it takes longer and longer. File 2 takes about 1 second per 1 million lines (but not everytime, just some of the iterations), up to 8 seconds on file number 8. Is this to be expected? Can I speed things up? All files are more or less completely the same, always with 24 million lines.
Edit:
Additional information: Every file needs, in processed form, about 730MB RAM. That means, using 8 files we end up with memory need of about 6GB.
As wished, the content of writeTweet()
void writeTweet(char* tweet, const int fn, const int ln, const int hits, const int month, const int day, char* line) {
    short* ptr1 = (short*) tweet;
    *ptr1 = (short) fn;
    int* ptr2 = (int*) (tweet + 2);
    *ptr2 = ln;
    *(tweet + 6) = (char) hits;
    *(tweet + 7) = (char) month;
    *(tweet + 8) = (char) day;

    int i;
    int n = TSIZE - 9;

    for (i = strlen(line); i < n; i++)
        line[i] = ' '; // padding

    memcpy(tweet + 9, line, n);
}

A: Probably, writeTweet() is a bottleneck. If you copy all processed tweets in memory, the huge data array with which the operating system has to do something is formed over time. If you have not enough memory, or other processes in system actively use it, OS will dump (in most cases) part of data on a disk. It increases time of access to the array. There is a more hidden from user eyes mechanisms in OS which can affect performance.
You shouldn't store all processed lines in memory. The simplest way: to dump the processed tweets on a disk (write a file). However solution depends on how you use further the processed tweets. If you not sequentially use data from array, it is worth thinking of special data structure to storage (B-trees?) . Already there is a many libraries for this purpose -- better to look for them.
UPD:
Modern OSs (Linux including) use virtual memory model. For maintenance of this model in a kernel there is a special memory manager who creates special structures of references to real pages in memory. Usually it's maps, for large memory volumes they referenced to sub-maps -- it is rather big branched structure.
During work with a big piece of memory it is necessary to address to any pages of memory often randomly. For address acceleration OS uses a special cache. I don't know all subtleties of this process, but I think that in this case cache should be often invalidate because there is no memory for storage all references at the same time. It is expensive operation brings to performance reduction. It will be that more, than memory is more much used.
If you need to sort large tweets array, it isn't obligatory for you to store everything in memory. There are ways to sorting data on a disk. If you want to sort data in memory, it isn't necessary to do the real swap operations on array elements. It's better to use intermediate structure with references to elements in tweets array, and to sort references instead of data.


text:
Q: Stringify a JSON object with the property name in uppercase using stringify and replace I have to complete this function, how i can replace name of property with its corresponding name in upper case.
function stringify(v){

  function replacer(k,v){
    // to be completed
  }

  return JSON.stringify(v,replacer)
}

console.log(stringify(JSON.parse(process.argv[2])))

For instance, the command:

node json_upper_case.js '[{"city":"Milano","Air Quality":"red","Temperature":10},{"air quality":"yellow","Temperature":20,"Sea conditions":3,"City":"Genova"}]'

is expected to print the following output:

[{"CITY":"Milano","AIR QUALITY":"red","TEMPERATURE":10},{"AIR QUALITY":"yellow","TEMPERATURE":20,"SEA CONDITIONS":3,"CITY":"Genova"}]

A: A simple Array.prototype.map() along with some dynamic property name access does the job:

let json = `[{
  "city": "Milano",
  "Air Quality": "red",
  "Temperature": 10
}, {
  "air quality": "yellow",
  "Temperature": 20,
  "Sea conditions": 3,
  "City": "Genova"
}]`

function keysToUppercase(j) {
  if (typeof j === 'string') { // so it works for javascript arrays as well
    try {
      j = JSON.parse(j);
    } catch (err) {
      console.error('Invalid JSON input');
      console.error(err);
    }
  }
  j = j.map(x => {
    for (let prop in x) {
      x[prop.toUpperCase()] = x[prop];
      delete x[prop];
    }
    return x;
  })
  return j;
}

console.log(keysToUppercase(json));

A: https://developer.mozilla.org/en-US/docs/Web/JavaScript/Reference/Global_Objects/JSON/stringify#The_replacer_parameter shows almost the right answer, try to modify the given function to fit your needs:
function replacer(key, value) {
  // Filtering out properties
  if (typeof value === 'string') {
    return undefined;
  }
  return value;
}


text:
Q: How to detect/recover from slow SQL server I/O in a C# program I have a C# .NET based program which runs 24/7 checking for and processing data in SQL Server.  This program runs fine all day long, but a little after 2AM each morning, something happens on my customer's server which causes SQL to report slow I/O.  SQL reports something like the following in its logs:

SQL Server has encountered 129 occurrence(s) of I/O requests taking longer than 15 seconds to complete on file [C:\Program Files\Microsoft SQL Server\MSSQL13.MSSQLSERVER\MSSQL\DATA\tempdb.mdf] in database id 2.  The OS file handle is 0x0000000000000D9C.  The offset of the latest long I/O is: 0x00000007ce0000

There are usually several of these message logged each morning, one after another.
Sometimes my program loses the connection to SQL server and exits, after which it is automatically restarted by a service.  Other times my program stops responding and I have to manually kill and restart the process in the morning.
My customer's IT has not been able to identify the cause of the slowdown, so I'm trying to change my program or connection settings to reliably detect the problem and exit, or overcome it in some other way.
 I've searched, but can't find anything online related to this sort of issue.
Any help would be greatly appreciated.

A: I would suggest you a little different solution as you said any help would be appreciated.
As I understand you do not know what is causing the problem and in my opinion you should focus on getting the knowledge what it is.
In your situation the best would be to ask your customer to set SQL Server Profiler for the time that is being under suspection that causes the problems. This is the tool that harvest all SQL Server activity. I have used this many times at my work.
For the question how to set SQL Server Profiler you would find easily the answer on google. This is quite easy and intuitive.
Be prepare to catch lots of queries, but you can filter them easily too.
Based on the logs in SQL Server Profiler you would know what is causing the problem and you can fix it in your application.
Let me know if this helped.


text:
Q: Flutter post request parse I have a POST request:
  static String url = 'https://checkout.test.paycom.com/api';
  static Map<String, String> headers = {
    'Host': 'checkout.test.paycom.com',
    'X-Auth': '1234',
    'Cache-Control': 'no-cache'
  };

Future<Map<String, dynamic>> createCard() async {
try {
  Map<String, dynamic> body = {
    "id": '123',
    "method": "receipts.create",
    "params": {
      "amount": '2500',
      "account": {"order_id": '106'}
    }
  }

  final response = await http.post(url, body: body, headers: headers);
  print(response.body);
} catch (e) {
  print(e.toString());
}
return null;
}

and give an error
type '_InternalLinkedHashMap<String, Object>' is not a subtype of type 'String' in type cast
What I am doing wrong?

A: your body needs to be as string, best case for you could be convert your body as JSON String as below:
  final response = await http.post(url, body: jsonEncode(body), headers: headers);