text:
Q: Div elements of different width, stack subsequent divs on shorter column I want to organize data in two columns of equal width, but they may be different heights per element. It's difficult to explain, but if you have div1 of height 500 and div2 of height 400, then add div3 of any height, it should appear directly below div2 rather than div1 because div2 is shorter. However, if div1 was shorter, div3 would instead appear below it.
Originally I was using tables since it's mostly tabular data, but when one of the two text fields are longer than the either (one in left vs. one in right), it stretches the shorter to match the height. I end up with rows of different height, and the element in the shorter column will stretch to fit that row (which is determined by the taller of either element). I don't want it to stretch, I'd rather it stack to minimize blank space.
Here's a mockup of what I'm trying to achieve. At the top you'll see the page with only one element, then below that you'll see with two elements, then below that with three and four elements. The third element goes below the second element because the overall height of the right column is shorter, but the fourth element goes below the first element because after the third is added, the left column is now shorter.
The only site I can think of off the top of my head that uses a similar organization style is Pinterest.

A: This concept on the web is usually refered to as Masonry.
Here is a link to a javascript library that can help you implement it.
http://masonry.desandro.com/
This can also be accomplished using FlexBox css for modern Browsers.
That has been addressed in this question: using flexbox to get pinterest or jQuery masonry layout


text:
Q: Class Missing Coverage I'm running Intellij and trying to view code coverage. All of my classes are showing some sort of coverage even 0% for some. But I have one class that is not showing anything in the report almost as if it's being excluded. I do have tests that cover this class but even if I didn't I would expect to see 0%.
I have the coverage runner set to Jacoco. I may be missing some details here but please let me know what would be helpful and I will provide it right away.
            <plugin>
                <groupId>org.jacoco</groupId>
                <artifactId>jacoco-maven-plugin</artifactId>
                <version>${jacoco.maven.plugin.version}</version>
                <configuration>
                    <excludes>
                        <exclude>**/*DTO.*</exclude>
                        <exclude>**/*Example.*</exclude>
                        <exclude>**/generated/**/*.*</exclude>
                        <exclude>**/constants/**/*.*</exclude>
                        <exclude>**/dto/**/*.*</exclude>
                        <exclude>**/mapper/**/*.*</exclude>
                        <exclude>**/model/**/*.*</exclude>
                        <exclude>**/domain/**/*.*</exclude>
                        <exclude>**/*.set*</exclude>
                        <exclude>**/*.get*</exclude>
                        <exclude>**/*.toString*</exclude>
                    </excludes>
                    <destFile>${jacoco.exec.path}</destFile>
                    <dataFile>${jacoco.exec.path}</dataFile>
                </configuration>
                <executions>
                    <execution>
                        <id>jacoco-initialize</id>
                        <goals>
                            <goal>prepare-agent</goal>
                        </goals>
                        <configuration>
                            <destFile>target/coverage-reports/jacoco.exec</destFile>
                        </configuration>
                    </execution>
                    <execution>
                        <id>jacoco-site</id>
                        <phase>package</phase>
                        <goals>
                            <goal>report</goal>
                        </goals>
                        <configuration>
                            <destFile>target/coverage-reports/jacoco.exec</destFile>
                        </configuration>
                    </execution>
                </executions>
            </plugin>

redpajama_set_name: RedPajamaStackExchange


text:
Q: How can I calculate two circles intersection in two points?
Where the equation of two circle:
${X_a}^2 + (y_a - p)^2 = {r_a}^2$
${X_b}^2 + (y_b - p)^2 = {r_b}^2$
I want to know how to get $(X_c, Y_c)$.

A: If you take the two equations, set them both equal to zero.
 $$X_a^2+(y_a−p)^2-r_a^2=0$$
$$X_b^2+(y_b−p)^2-r_b^2=0$$
Then subtract them from one another you will get a linear equation which passes through both intersection points.
You can then set that equal to one of the circle equations to get a quadratic for the intersections.

A: This is still a system of equations.
$$\begin{cases}
(x-h_1)^2+(y-k_1)^2=r_1^2\\
(x-h_2)^2+(y-k_2)^2=r_2^2
\end{cases}$$
If you expand it out and subtract them from each other, you can get a linear equation. You can then solve that linear equation for one variable and substitute it into either of the equations, and you end up with a quadratic that you can solve with the quadratic method.

A: Hint:
Let $(0,0)$ be the center of the first circle.
So we need to solve system of two equations:
$$
\left\{
\begin{array}{c}
x^2+y^2=r_1^2 \\
(x-x_2)^2+(y-y_2)^2 = r_2^2 \\
\end{array}
\right.
$$
Subtract the second equation from the first:
$$
\left\{
\begin{array}{c}
x^2+y^2=r_1^2 \\
-2x_2x - 2y_2y + (x_2^2+y_2^2+r_1^2-r_2^2) = 0\\
\end{array}
\right.
$$
Thus, we need to calculate intersection of the first circle and the line $Ax+By+C=0$ where $A = -2x_2, B = -2y_2 , C = x_2^2+y_2^2+r_1^2-r_2^2$


text:
Q: MSBuild script default property best practices explanation In building an MSBuild script, I need to define a series of properties that are default but can be overridden when running the script. According to the following article, you should use a Conditional to default the property:
http://msdn.microsoft.com/en-us/library/ee240983.aspx
How Microsoft recommends:
<PropertyGroup>
    <MyProperty Condition="'$(MyProperty)' == '' ">Default Value</MyProperty>
</PropertyGroup>

However, this behaves exactly the same way:
<PropertyGroup>
    <MyProperty>Default Value Without Conditional</MyProperty>
</PropertyGroup>

So, if I have this Target and invoke it with either of the above, it has the same behavior:
<Target Name="DefaultsTest">
    <Message Text="$(MyProperty)"></Message>
</Target>

Invocation:
msbuild build.xml /t:DefaultsTest /p:MyProperty="Overridden value"
Please explain the benefits of using the Condition attribute if you are only defaulting the same property that can be overridden from the invocation?
Update:
Here is a full simple config file to demonstrate: defaults.xml
<?xml version="1.0" encoding="utf-8" ?>
<Project DefaultTargets="DefaultsTest" xmlns="http://schemas.microsoft.com/developer/msbuild/2003">
    <PropertyGroup>
        <MyProperty Condition=" '$(MyProperty)' == '' ">MyProperty with Conditional</MyProperty>
        <MyOtherProperty>MyOtherProperty without Conditional</MyOtherProperty>
    </PropertyGroup>

    <Target Name="DefaultsTest">
        <Message Text="$(MyProperty)"></Message>
        <Message Text="$(MyOtherProperty)"></Message>
    </Target>
</Project>

This can be run simply as msbuild defaults.xml
or
msbuild defaults.xml /p:MyProperty="Changed Value" /p:MyOtherProperty="Changed as well"

A: You correctly noticed, that you can achieve behavior you want with unconditional assignment of property. The following project when built without /p: override on command line will produce Default Value. And when built using command msbuild myproj.proj /t:DefaultsTest /p:MyProperty=NewValue will produce NewValue.
 <Project xmlns="http://schemas.microsoft.com/developer/msbuild/2003">
    <PropertyGroup>
        <MyProperty>Default Value</MyProperty>
    </PropertyGroup>
    <Target Name="DefaultsTest">
        <Message Text="MyProperty=$(MyProperty)"></Message>
    </Target>
</Project>

This is because any properties specified on MSBuild command line or provided as a parameter of  task will be treated as Global Properties. For global properties, any assignment or modifications, either conditional or unconditional, are simply ignored -- global properties will remain constant throughout lifetime of the project execution.
The only difference in behavior between conditional assignment and unconditional will be if you use TreatAsLocalProperty attribute.
For example, consider the following project:
 <Project TreatAsLocalProperty="Prop1;Prop2" xmlns="http://schemas.microsoft.com/developer/msbuild/2003">
    <PropertyGroup>
        <Prop1>Prop1 Default Value</Prop1>
        <Prop2 Condition="$(Prop2) == ''">Prop2 Default Value</Prop2>
    </PropertyGroup>
    <Target Name="DefaultsTest">
        <Message Text="Prop1=$(Prop1)"></Message>
        <Message Text="Prop2=$(Prop2)"></Message>
    </Target>
</Project>

Two properties -- Prop1 and Prop2 are both declared as local in the Project element. Prop1 is assigned unconditionally, while Prop2 is assigned using non-empty condition. Executing build command:
msbuild b.proj /t:DefaultsTest /p:Prop1=NewValue1 /p:Prop2=NewValue2

will produce output:
Prop1=Prop1 Default Value
Prop2=NewValue2

This means that in general case (if you are not absoluterly sure if property will be global or local), it is safer to use conditional assignment of the default value, because it works always.


text:
Q: C Programming: Drawing shapes on screen (windows compatible) So I have been doing a lot of googling and couldnt find anything of value. I come from web development and I often had fun with the HTML5 canvas api. When I search for information regarding drawing contexts in the basic C programming language, I could only find APIs associated with Apple such as Quartz. Every article is about this so called cocoa or IOs / MAC. Honestly, nothing for microsoft.
How do I draw a basic shape on screen with the C Language?


text:
Q: Get key value of command i'm beginner in Tex
and i have tex file
\documentclass{article}

\addtolength{\jot}{1em}

\begin{document}
\begin{verbatim}
\end{verbatim}
\begin{chestnutStem}
In the following figure, if the spinner is divided into 8 colored sections, what is the probability of it stopping at blue?

\centerline{\includepdf[page=2]{mypdf.pdf}}

\end{chestnutStem}

\chestnutKey{
$        \frac{1}{4}      $
}

\begin{chestnutAnswer}

        \begin{align*}
        \textrm{The probability of the spinner stopping at blue}&=\frac{\textrm{the number of blue sections}}{\textrm{total number of sections}}\\
        &=\frac{2}{8}\\
        &=\frac{1}{4}.
        \end{align*}

\end{chestnutAnswer}

\end{document}

and i have cls file
\ProvidesClass{chestnut}[2016/02/17]
\LoadClass{article}
\RequirePackage{amsmath}
\RequirePackage{kvoptions}
\RequirePackage{graphicx}
\RequirePackage{xkeyval}
\DeclareStringOption{country}{}
\DeclareStringOption{language}{}
\DeclareStringOption{math}{}
\DeclareStringOption{numerals}{}
\ProcessKeyvalOptions*\relax

\DeclareOption{example}{%
\typeout{You are using example object.}

}%

\DeclareOption*{}{}
\ProcessOptions*\relax

\RequirePackage[lmargin=0.5in,rmargin=0.5in,tmargin=0.5in,bmargin=0.5in]{geometry}
\let\country=\chestnut@country
\typeout{ Your country \country}

\let\language=\chestnut@language
\typeout{ Your language \language}

\let\math=\chestnut@math
\typeout{ Your symbols language is \math}

\let\numerals = \chestnut@numerals
\typeout{ Your numerals are in \numerals}

\newenvironment{chestnutStem}{\underline{\textbf{Stem}}\\* }{\hfill \\* }

\newcommand\chestnutKey[1]{\underline{\textbf{Key}}\\*#1\hfill\\* }

\newenvironment{chestnutAnswer}{\underline{\textbf{Answer}}\\*}{\hfill \\* }

\RequirePackage{alternative4ht}
\altusepackage{pdfpages}
\newcommand\chestnutTikZ[1]{\includepdf[pages=-,width=.9\textwidth]{#1}}

\setlength{\parindent}{0pt}
\pagenumbering{gobble}
\IfFileExists{approved.jpg}{%
\RequirePackage{fancyhdr}
\renewcommand\headrule{}
\rhead{\vspace{0.5in}\includegraphics[scale=0.2]{approved.png}}
\pagestyle{fancy}
}%

and alternative4ht.sty file
\ProvidesPackage{alternative4ht}

\newcommand{\altusepackage}[2][]{%
    \ifx\HCode\relax%
    \usepackage[#1]{#2}%
    \else%
    \IfFileExists{#2-alt4ht.sty}{%
      \usepackage[#1]{#2-alt4ht}%
    }{\typeout{alternative4ht: no patch file for #2}}
    \fi%
}
\endinput

and pdfpages-alt4ht.sty file
\ProvidesPackage{pdfpages-alt4ht}
\RequirePackage{graphicx}

\newcommand\includepdf[2][]{%
    \includegraphics{#2}
}

\endinput

and cfg file to convert pdf pages to png images
\Preamble{xhtml}
  \Configure{graphics*}
         {pdf}
         {\Needs{"convert -scene 1 \csname Gin@base\endcsname.pdf
                               \csname Gin@base\endcsname.png"}%
          \Picture[pict]{\csname Gin@base\endcsname .png}% here i want add page number with pdf file name for example <mypdf-2.png>
          \special{t4ht+@File: \csname Gin@base\endcsname.png}
         }
\begin{document}
\EndPreamble

I want get [page] value option in \includepdf command to use it in config file

A: pdfpages is one of packages which causes tex4ht to fail once they are included. In this case, TeX source must be altered, which is something that we try to avoid with tex4ht. helpers4ht bundle provides \altusepackage command, which can be used to load alternative version of packages for tex4ht. These alternative packages are named packagename-alt4ht.sty. They contain definitions for macros used in the document. Definition for pdfpages was only basic, it could be used to include only one paged pdf document.
To support multipage pdf files, I've added pages option to \includepdf command in pdfpages-alt4ht.sty package. It doesn't support all features of original, as it would be quite difficult to implement it and I don't think that it makes sense in HTML output:
\ProvidesPackage{pdfpages-alt4ht}
\RequirePackage{graphicx}
\RequirePackage{xkeyval}
\define@key{includepdf}{pages}{\edef\current@pdf@page{\the\numexpr #1-1\relax}}

\newcommand\includepdf[2][]{%
  \def\current@pdf@page{0}
    \setkeys*{includepdf}{#1}
    \filename@parse{#2}
    \def\current@png@name{\filename@area\filename@base-\current@pdf@page.png}
    \IfFileExists{\current@png@name}{}{%
      \Needs{"convert #2[\current@pdf@page]
      \current@png@name"}
    }
    \includegraphics{\current@png@name}
  }

  \endinput

it saves requested page in \current@pdf@page macro, it must be decremented by 1, because imagemagick counts pages from 0. The png name is constructed as imagename-pagenumber.png and convert program is called only if it doesn't exist yet.
I had to fix one issue in chestnut.cls, there was missing {} in IfFileExists:
\ProvidesClass{chestnut}[2016/02/17]
\LoadClass{article}
\RequirePackage{amsmath}
\RequirePackage{kvoptions}
\RequirePackage{graphicx}
\RequirePackage{xkeyval}
\DeclareStringOption{country}{}
\DeclareStringOption{language}{}
\DeclareStringOption{math}{}
\DeclareStringOption{numerals}{}
\ProcessKeyvalOptions*\relax

\DeclareOption{example}{%
\typeout{You are using example object.}

}%

\DeclareOption*{}{}
\ProcessOptions*\relax

\RequirePackage[lmargin=0.5in,rmargin=0.5in,tmargin=0.5in,bmargin=0.5in]{geometry}
\let\country=\chestnut@country
\typeout{ Your country \country}

\let\language=\chestnut@language
\typeout{ Your language \language}

\let\math=\chestnut@math
\typeout{ Your symbols language is \math}

\let\numerals = \chestnut@numerals
\typeout{ Your numerals are in \numerals}

\newenvironment{chestnutStem}{\underline{\textbf{Stem}}\\* }{\hfill \\* }

\newcommand\chestnutKey[1]{\underline{\textbf{Key}}\\*#1\hfill\\* }

\newenvironment{chestnutAnswer}{\underline{\textbf{Answer}}\\*}{\hfill \\* }

\RequirePackage{alternative4ht}
\altusepackage{pdfpages}
\newcommand\chestnutTikZ[1]{\includepdf[pages=-,width=.9\textwidth]{#1}}

\setlength{\parindent}{0pt}
\pagenumbering{gobble}
\IfFileExists{approved.jpg}{%
\RequirePackage{fancyhdr}
\renewcommand\headrule{}
\rhead{\vspace{0.5in}\includegraphics[scale=0.2]{approved.png}}
\pagestyle{fancy}
}{}%

and also your TeX file, because chestnut class wasn't used:
\documentclass{chestnut}

\addtolength{\jot}{1em}

\begin{document}
\begin{verbatim}
\end{verbatim}
\begin{chestnutStem}
In the following figure, if the spinner is divided into 8 colored sections, what is the probability of it stopping at blue?

\centerline{\includepdf[pages=2]{mypdf.pdf}}

\end{chestnutStem}

\chestnutKey{
$        \frac{1}{4}      $
}

\begin{chestnutAnswer}

        \begin{align*}
        \textrm{The probability of the spinner stopping at blue}&=\frac{\textrm{the number of blue sections}}{\textrm{total number of sections}}\\
        &=\frac{2}{8}\\
        &=\frac{1}{4}.
        \end{align*}

\end{chestnutAnswer}

\end{document}

sample output:


text:
Q: Is there any way to list all swizzled methods in an iOS app? I'm essentially looking for a way to detect when/what third party libraries swizzle.  I recently ran into a situation where an ad library used an oddball fork of AFNetworking. AFNetworking swizzles NSURLSessionTask, and the two swizzles didn't play nicely under certain circumstances.  I'd really like to be able to detect and sanity check this kind of thing, and ideally even keep a versioned dump of every swizzled method in the app so we have some visibility into who's monkey patching what and what the risks are.  Google and stack overflow search have turned up nothing but a bunch of tutorial on how to swizzle.  Anybody run into this issue or have a solution?  It looks like I might be able to code something up using objc/runtime.h but I can't imagine I'm the first person to need this.

A: Here's the closest I was able to get, with a few hours of tinkering. It involves using a fork of mach_override, a couple of DYLD quirks regarding load order, and a stomach for crazy hacks.
It will only work on the simulator, but that should suffice for the use case you seem to have (I certainly hope you don't have device-only dependencies).
The meat of the code looks something like this:
#include <objc/runtime.h>
#include <mach_override/mach_override.h>

// It is extremely important that we have DYLD run this constructor as soon as the binary loads. If we were to hook
// this at any other point (for example, another category on NSObject, in the main application), what could potentially
// happen is other `+load` implementations get invoked before we have a chance to hook `method_exchangeImplementation`,
// and we don't get to see those swizzles.
// It is also extremely important that this exists inside its own dylib, which will be loaded by DYLD before _main() is
// initialized. You must also make sure that this gets loaded BEFORE any other userland dylibs, which can be enforced by
// looking at the order of the 'link binary with libraries' phase.
__attribute__((constructor))
static void _hook_objc_runtime() {
  kern_return_t err;
  MACH_OVERRIDE(void, method_exchangeImplementations, (Method m1, Method m2), &err) {
    printf("Exchanging implementations for method %s and %s.\n", sel_getName(method_getName(m1)), sel_getName(method_getName(m2)));

    method_exchangeImplementations_reenter(m1, m2);
  }
  END_MACH_OVERRIDE(method_exchangeImplementations);

  MACH_OVERRIDE(void, method_setImplementation, (Method method, IMP imp), &err) {
    printf("Setting new implementation for method %s.\n", sel_getName(method_getName(method)));

    method_setImplementation_reenter(method, imp);
  }
  END_MACH_OVERRIDE(method_setImplementation);
}

Which is surprisingly simple, and produces output like this:

Exchanging implementations for method description and custom_description.

There is no good way (without using a breakpoint and looking through the stack trace) to figure out which class is being swizzled, but for most things, just taking a peek at the selectors should give you a hint about where to go from there.
It appears to work with a couple of categories that I've created that swizzle during +load, and from my reading of mach_override and DYLD's internals, as long as you have your library load order properly setup, you can expect this to be initialized before any other user-land code, if you put it in it's own dynamic library.
Now, I can't vouch for safety of this, but it seems useful to keep around as a debugging tool, so I've published my example to github:
https://github.com/richardjrossiii/mach_override_example
It's MIT licensed, so feel free to use as you see fit.


text:
Q: .Net Does the code within a class always run on the thread that created it? In the example code below, will the timer elapsed event always run on the background thread, or on the main thread?
Public Class MainClass
    Dim SomeSubClassInstance As SomeSubClass

    Public Sub New()
        'Create a thread which will then create an instance of the sub class
        Dim T As New Threading.Thread(AddressOf CreateSomeSubClass)
        T.IsBackground = True
        T.Start()
    End Sub

    Private Sub CreateSomeSubClass()
        'This code runs on the background thread, and creates the instance of SomeSubClass
        SomeSubClassInstance = New SomeSubClass
    End Sub

    Public Class SomeSubClass
        Dim WithEvents tmrDoWork As Timers.Timer
        Public Sub New()
            tmrDoWork = New Timer
            tmrDoWork.Interval = TimeSpan.FromMinutes(1).TotalMilliseconds
            tmrDoWork.Start()
        End Sub

        Private Sub tmrDoWork_Elapsed(sender As Object, e As ElapsedEventArgs) Handles tmrDoWork.Elapsed
            'Will this code be run on the background thread that was created in the MainClass constructor?
        End Sub
    End Class
End Class

A: It won't run on either. It will run on a random thread pool thread unless you specify a SynchronizingObject which will marshal the calls to another thread.
If the SynchronizingObject property is null, the Elapsed event is raised on a ThreadPool thread. If processing of the Elapsed event lasts longer than Interval, the event might be raised again on another ThreadPool thread. In this situation, the event handler should be reentrant.
https://msdn.microsoft.com/en-us/library/system.timers.timer(v=vs.110).aspx


text:
Q: How to select Regolith Linux for less RAM usage My computer has 8 GB of RAM. I am using Xubuntu 21.10, it is fast but it has no auto tiling. In my daily work, I mostly use LibreOffice Calc for calculation with complicated sheets and open many windows for watching various documents, so it needs more RAM. From option 2, https://regolith-linux.org/docs/getting-started/install/#ppa-install , will RAM be used more than Option 1, https://regolith-linux.org/docs/getting-started/install/#option-1-regolith-linux-via-installer ? And do I have to move from Xubuntu 21.10 to Ubuntu 21.04 for Option 2 ?

A: It will not make a meaningful difference in memory usage if you install Regolith in Ubuntu then switch to a Regolith session compared to when you would install the Regolith distribution.
Installing Regolith on a 21.10, then upgrading also will not make a meaningful difference over upgrading to 22.04 then installing Regolith.
In all scenario's, you are using essentially similar software on a similar base. Even if one way leads to a few more system services running than another way, you will not, for practical purposes, notice any difference.


text:
Q: Element with only class name and repeats multiple times on the page. Selenium c# I have an element which has only class name as it's locator or property which can be used for it to locate. I have tried multiple different solution but it doesn't click on the right one or doesn't do anything at all. I have tried using X-path but that doesn't help either because it's not reliable.
  <a class="Icon-shadows"
    <i class="fa fas.fw fa-info"
  ::before
  I>
  a>

This information button appears more then 25-40 times on a page if you click on it you get information about The content.
I can add some more information if need be. Any help suggestions will be much appreciated.

A: Try saving them to a list, and click on the specific one you need
IList<IWebElement> infoBtn = driver.FindElements(By.CssSelector("a[class='Icon-shadows']"));
infoBtn[4].Click();


text:
Q: Share Image File from cache directory Via Intent~android I am trying to share image file in cache directory, i have the complete path, but not able to send the file in attachments, the code is
File shareImage=Utils.getBitmapFile();
Log.d("Activity", "get final path in result"+shareImage.getAbsolutePath());
/*MimeTypeMap mime = MimeTypeMap.getSingleton();
String ext=shareImage.getName().substring(shareImage.getName().lastIndexOf(".")+1);
String type = mime.getMimeTypeFromExtension(ext);
shareIntent.setType(type);
Intent shareIntent = new Intent(Intent.ACTION_SEND);
shareIntent.setType("image/*");
Uri shareImageUri = Uri.fromFile(shareImage);
Uri shareImageUri = Uri.fromParts("content", shareImage.getAbsolutePath(), null);//("content://"+shareImage.getAbsolutePath());
*/

Uri shareImageUri = Uri.fromFile(shareImage);
Log.d("Result ","uri is "+shareImageUri.toString());
shareIntent.putExtra(Intent.EXTRA_STREAM, shareImageUri);
startActivity(Intent.createChooser(shareIntent, "Share Results"));

the above commented code is not working
the send mail shows attachment,but not receiving end there is not attachment,
facebook sharing also shows no image in post
what the reason for this??
I have already seen the following SO Links how-to-use-share-image-using-sharing-intent-to-share-images-in-android and many others, none of them are able to resolve the issue
P.S.;
1.The aim is to take screenshot of screen save it in cache directory and share it online from there
2.Yes i do have file, I can pull it via DDMS from device and see on system.

A: I followed @CommonsWare's advice and used a FileProvider. Assuming your image is already in the internal cache directory as cache/images/image.png, then you can use the following steps. These are mostly a consolidation of the documentation.
Set up the FileProvider in the Manifest
<manifest>
    ...
    <application>
        ...
        <provider
            android:name="android.support.v4.content.FileProvider"
            android:authorities="com.example.myapp.fileprovider"
            android:grantUriPermissions="true"
            android:exported="false">
            <meta-data
                android:name="android.support.FILE_PROVIDER_PATHS"
                android:resource="@xml/filepaths" />
        </provider>
        ...
    </application>
</manifest>

Replace com.example.myapp with your app package name.
Create res/xml/filepaths.xml
<?xml version="1.0" encoding="utf-8"?>
<paths xmlns:android="http://schemas.android.com/apk/res/android">
    <cache-path name="shared_images" path="images/"/>
</paths>

This tells the FileProvider where to get the files to share (using the cache directory in this case).
Share the image
File imagePath = new File(context.getCacheDir(), "images");
File newFile = new File(imagePath, "image.png");
Uri contentUri = FileProvider.getUriForFile(context, "com.example.app.fileprovider", newFile);

if (contentUri != null) {

    Intent shareIntent = new Intent();
    shareIntent.setAction(Intent.ACTION_SEND);
    shareIntent.addFlags(Intent.FLAG_GRANT_READ_URI_PERMISSION); // temp permission for receiving app to read this file
    shareIntent.setDataAndType(contentUri, getContentResolver().getType(contentUri));
    shareIntent.putExtra(Intent.EXTRA_STREAM, contentUri);
    startActivity(Intent.createChooser(shareIntent, "Choose an app"));

}

Documentation

*

*FileProvider

*Storage Options - Internal Storage

*Sharing Files

*Saving Files

A:
what the reason for this?

As noted, other apps do not have access to your app's internal storage.

none of them are able to resolve the issue

Feel free to open a fresh StackOverflow question, where you explain, completely and precisely what specific solutions you have tried and what specific problems you have encountered.

but that does not seems to be working as per SO post!!!

Feel free to open a fresh StackOverflow question, where you explain, completely and precisely what "that does not seems to be working" means.
Or, use FileProvider, which offers this capability with no code required beyond an entry for it in your manifest.
Or, store your image on external storage, such as getExternalCacheDir().

A: I share cached image by followed steps .
1.Copy your cached image to target path.

public static File copyImage(String sourcePath, String targetPath){
                  try {
                            InputStream in = new FileInputStream(sourcePath);
                             OutputStream out = new FileOutputStream(targetPath);
                             byte[] buf = new byte[1024];
                             int len;
                             while ((len = in.read(buf)) > 0) {
                                       out.write(buf, 0, len);
                            }
                             in.close();
                            out.close();
                            return new File(targetPath);
                   } catch (IOException e) {
                             e.printStackTrace();
                             return null;
                   }
        }

2.Get the Uri of copy file.

Uri uri = Uri.fromFile(target);

3.Share image by intent

    File dir = new File(Constant.INKPIC_PATH);//your custom path,such as /mnt/sdcard/Pictures
    if(!dir.exists()){
        dir.mkdirs();
    }
    File f = new File(dir,"temporary_file.jpg");
    File target = copyImage(url,f.getAbsolutePath());
    Uri uri = Uri.fromFile(target);
    Intent intent = new Intent();
    intent.setAction(Intent.ACTION_SEND);
    intent.setType("image/*");
    intent.putExtra(Intent.EXTRA_STREAM,uri );
    context.startActivity(intent);


text:
Q: Combining SlickGrid Filter Examples I like the functionality of the Filter in this example:
http://mleibman.github.com/SlickGrid/examples/example-header-row.html
where each column has its own filter, but I also require the functionality of the Filter from:
http://mleibman.github.com/SlickGrid/examples/example4-model.html
In that it can be hidden and shown via button click.
Is it possible to have the Filters from the first link, with the "hide-ability" of the Filter from the second link? Thanks!

A: Yes, it is.  You may use the method grid.hideHeaderRowColumns() in the first example to hide the filter bar. Then use grid.showHeaderRowColumns() to show it again.
For example, navigate to the first link, and replace the contents of the URL bar with:
javascript:grid.hideHeaderRowColumns()

and hit Enter. You should see the filter bar slide up and away. If you are building your app from the first example code, you should be able to call these functions from almost anywhere, ie.
<input type="button" onclick="grid.hideHeaderRowColumns();" value="Hide Filter" />

Note that in the second example, the author uses the following code to add a predefined, but hidden, element to the styled header bar:
// move the filter panel defined in a hidden div into grid top panel
$("#inlineFilterPanel")
    .appendTo(grid.getTopPanel())
    .show();

And the hidden element:

    Show tasks with title including
      <input type="text" id="txtSearch2">
    and % at least


text:
Q: Go - How to know when an output channel is done I tried to follow Rob Pike's example from the talk 'Concurrency is not parallelism' and did something like this:
I'm starting many go routines as workers that read from an input channel, perform some processing and then send the result through the output channel.
Then I start another go routine that reads data from some source and send it to the workers through their input channel.
Lastly I want to iterate over all of the results in the output channel and do something with them.
The problem is that because the work is split between the workers I don't know when all of the workers have finished so I can stop asking the output channel for more results, and my program could end properly.
What is the best practice to know when workers have finished sending results to an output channel?

A: I personally like to use a sync.WaitGroup for that. A waitgroup is a synchronized counter that has three methods - Wait(), Done() and Add(). What you do is increment the the waitgroup's counter, pass it to the workers, and have them call Done() when they're done. Then you just block on the waitgroup on the other end and close the output channel when they're all done, causing the output processor to exit.
Basically:
// create the wait group
wg := sync.WaitGroup{}

// this is the output channel
outchan := make(chan whatever)

// start the workers
for i := 0; i < N; i++ {
   wg.Add(1) //we increment by one the waitgroup's count

   //the worker pushes data onto the output channel and calls wg.Done() when done
   go work(&wg, outchan)
}

// this is our "waiter" - it blocks until all workers are done and closes the channel
go func() {
  wg.Wait()
  close(outchan)
}()

//this loop will exit automatically when outchan is closed
for item := range outchan {
   workWithIt(item)
}

// TADA!

A: Please can I firstly clarify your terminology: a misunderstanding on the ends of channels could cause problems later. You ask about "output channels" and "input channels". There is no such thing; there are only channels.
Every channel has two ends: the output (writing) end, and the input (reading) end. I will assume that that is what you meant.
Now to answer your question.
Take the simplest case: you have only one sender goroutine writing to a channel, and you only have one worker goroutine reading from the other end, and the channel has zero buffering. The sender goroutine will block as it writes each item it until that item has been consumed. Typically this happens quickly the first time.  Once the first item has passed to the worker, the worker will then be busy and the sender will have to wait before the second item can be passed over. So a ping-pong effect follows: either the writer or the reader will be busy but not both. The goroutines will be concurrent in the sense described by Rob Pike, but not always actually executing in parallel.
In the case where you have many worker goroutines reading from the channel (and its input end is shared by all of them), the sender can initially distribute one item to each worker, but then it has to wait whilst they work (similar to the ping-pong case described above). Finally, when all items have been sent by the sender, it has finished its work. However, the readers may not, yet, have finished their work. Sometimes we care that the sender finishes early, and sometimes we don't. Knowing when this happens is most easily done with a WaitGroup (see Not_a_Golfer's answer and my answer to a related question).
There is a slightly more complex alternative: you can use a return channel for signalling completion instead of a WaitGroup. This isn't hard to do, but WaitGroup is preferred in this case, being simpler.
If instead the channel were to contain a buffer, the point at which the sender had sent its last item would happen sooner. In the limit case when the channel has one buffer space per worker; this would allow the sender to complete very quickly and then, potentially, get on with something else. (Any more buffering than this would be wasteful).
This decoupling of the sender allows a fully asynchronous pattern of behaviour, beloved of people using other technology stacks (Node-JS and the JVM spring to mind). Unlike them, Go doesn't need you to do this, but you have the choice.
Back in the early '90s, as a side-effect of work on the Bulk Synchronous Parallelism (BSP) strategy, Leslie Valiant proved that sometimes very simple synchronisation strategies can be cheap. The crucial factor is that there is a need for enough parallel slackness (a.k.a. excess parallelism) to keep the processor cores busy. That means there must be plenty enough other work to be done so that it really doesn't matter if any particular goroutine is blocked for a period of time.
Curiously, this can mean that working with smaller numbers of goroutines might require more care than working with larger numbers.
Understanding the impact of excess parallelism is useful: it is often not necessary to put extra effort into making everything asynchronous if the network as a whole has excess parallelism, because the CPU cores would be busy either way.
Therefore, although it is useful to know how to wait until your sender has completed, a larger application may not need you to be concerned in the same way.
As a final footnote, WaitGroup is a barrier in the sense used in BSP. By combining barriers and channels, you are making use of both BSP and CSP.

A: var Z = "Z"

func Loop() {
    sc := make(chan *string)
    ss := make([]string, 0)
    done := make(chan struct{}, 1)
    go func() {
        //1 QUERY
        slice1 := []string{"a", "b", "c"}
        //2 WG INIT
        var wg1 sync.WaitGroup
        wg1.Add(len(slice1))
        //3 LOOP->
        loopSlice1(slice1, sc, &wg1)
        //7 WG WAIT<-
        wg1.Wait()
        sc <- &Z
        done <- struct{}{}
    }()

    go func() {
        var cc *string
        for {
            cc = <-sc
            log.Infof("<-sc %s", *cc)
            if *cc == Z {
                break
            }
            ss = append(ss, *cc)
        }
    }()
    <-done
    log.Infof("FUN: %#v", ss)
}

func loopSlice1(slice1 []string, sc chan *string, wg1 *sync.WaitGroup) {
    for i, x := range slice1 {
        //4 GO
        go func(n int, v string) {
            //5 WG DONE
            defer wg1.Done()
            //6 DOING
            //[1 QUERY
            slice2 := []string{"X", "Y", "Z"}
            //[2 WG INIT
            var wg2 sync.WaitGroup
            wg2.Add(len(slice2))
            //[3 LOOP ->
            loopSlice2(n, v, slice2, sc, &wg2)
            //[7 WG WAIT <-
            wg2.Wait()
        }(i, x)
    }
}

func loopSlice2(n1 int, v1 string, slice2 []string, sc chan *string, wg2 *sync.WaitGroup) {
    for j, y := range slice2 {
        //[4 GO
        go func(n2 int, v2 string) {
            //[5 WG DONE
            defer wg2.Done()
            //[6 DOING
            r := fmt.Sprintf("%v%v %v,%v", n1, n2, v1, v2)
            sc <- &r
        }(j, y)
    }
}


text:
Q: Nuxt JS installing umd Vue plugin/component throws unknown custom element I've written a Vue JS component/plugin and have it in the following formats:

*

*Common

*ESM

*UMD

I'm trying to import the UMD version into my Nuxt JS project (I'e also tried the others) and use it.
I've added a scripts array to my nuxt.config.js file to the head section:
scripts: [
  { src: '/js/vue-les-offers.umd.js' }
]

My JS file lives in static/js, and I've gone ahead and included my component in my page:
...
<vue-les-offers></vue-les-offers>
...

But I'm getting an error thrown in my console:

[Vue warn]: Unknown custom element:  - did you register the component correctly? For recursive components, make sure to provide the "name" option.

What am I missing?
I've tried:

*

*installing via the plugins array

*installing via the modules (used the ESM variant)

*tried wrapping in a client-only element

*tried both min and non-minified JS variants


text:
Q: Azure - Multiple database queries How can I query multiple tables from multiple azure databases?
Imagine I have "customers" table in Database X and "sales" table in dabtabase Y and I want to join them in a query, how is it possible to do this in Azure?

A: Assuming you're talking about Azure's SQL Database service, then no, you cannot have queries across two separate database instances. The queries are limited to the single database.
If you require queries spanning multiple databases, you'd need to install SQL Server on a VM.

A: David is correct -- currently Azure SQL DB doesn't support cross-database joins.
Is it possible for you to combine the two databases into a single DB, but use separate schema to keep the namespaces of objects separate?  I am curious about the business reasons you are maintaining separate dbs.  You can reach out to me directly at Stuarto  Microsoft  com.

A: You can join them if they're hosted on the same server. Try this
SELECT a.userID, b.usersFirstName, b.usersLastName  FROM databaseA.dbo.TableA a inner join database B.dbo.TableB b  ON a.userID=b.userID


text:
Q: Elasticsearch query won't work with alias wildcard, though it works with multiple alias query We have aliases in Elasticsearch 7.4 with search_routing specified. We have some queries running on endpoints that specify the routing parameter, though we probably never need the value specified due to always using the aliases. Based on Elasticsearch documentation, if search_routing is specified in an alias, it should override routing specified in a query.
To illustrate the problem, I have 2 queries that to me, look like they should have the same results--but they don't:
GET alias-prefix-customer-2020,alias-prefix-customer-2021,alias-prefix-customer-2022/_search?routing=111111111111

This multi-alias version works as expected in Kibana, returning documents.
GET alias-prefix-customer-*/_search?routing=111111111111

The wildcard version returns nothing in Kibana. Why would adding the routing parameter work on one and break the other?
While we could probably remove the adding of the routing parameter to the query in Python, I am still wonder--is there a fix for the version that doesn't work? Is that a bug or by design?
Our aliases are of the following form:
POST _aliases
{
  "actions":
  [
    {
      "add":
      {
        "index": "some-index-name",
        "alias": "alias-prefix-customer-2020",
        "filter":
        {
          "bool":
          {
            "must":
            [
              ... multiple criteria
            ]
          }
        },
        "search_routing": "222222222222"
      }
    }
  ]
}


text:
Q: Opening web page as I see it in browser with Python Using the google CSE utilities I've made a HTML file that is a barebones version of Google Search (about 1/10th page size), which is as follows:
<script>
  (function() {
    var cx = '011947631902407852034:gq02yx0e1mq';
    var gcse = document.createElement('script');
    gcse.type = 'text/javascript';
    gcse.async = true;
    gcse.src = 'https://cse.google.com/cse.js?cx=' + cx;
    var s = document.getElementsByTagName('script')[0];
    s.parentNode.insertBefore(gcse, s);
  })();
</script>
<gcse:searchresults-only></gcse:searchresults-only>

I can open this in my browser like C:\Users\Me\Documents\MyWebpage.html?q=MyQuery and it shows something like this:
 This is obviously not what's in the HTML file, so I assume it's generated via JavaScript. Indeed, when I look at the page in my browser there's a lot more HTML than is in the actual file. The 1/10th size comment refers to the size of all of this, if I download it using Inspect Element, selecting the topmost node, Edit HTML, and copying all the HTML and placing it in a file.
My question is: how can I read in all of this HTML for a given query with Python?


text:
Q: Models not visiable for stuff I've added a Model to admin page with admin.site.register but it's being displayed only if superuser logs in.
Even if i give all permissions to a stuff user the model does not show up there even though Groups and Users model does.
How do i set this right?
EDIT: maybe he needs permissions to the module? How can give those related to user.has_module_perms ?

A: You have to either create a group, give permissions to group and then add assign that group to user or create user and assign permissions to that user.
Add group Stuff-users.
Under available permissions in Available Permissions Select
YourApp | YourModel | Can add...
YourApp | YourModel | Can change...
YourApp | YourModel | Can Delete...
Then make sure you have clicked on the arrow pointing to Change Permissions. This will move the specific permission to Change Permissions.
Click Save.
Create or open Users. Select the user Stuff
Select Active and Staff Users.
Select Stuff-users from Available Groups and click the arrow pointing to Chosen Groups. This will move the Support group to Chosen Group.
Don't make any change to User Permissions unless you want to grant additional permissions to any specific user.
Click save.
Have the user logout and log back in.


text:
Q: Changing the value of a cell based on the first digit Ok, trying and struggling to do it
I am not a pro in excel but try to do something so I can keep track of something.
Cell A1 have a value of 4225566558
Cell A2 have a value of 2225584545
What I need is - If in column A the first digit /s is 4 or 04 I would need the output in Column B to be 0.055 otherwise it will be 0.044

A: Try this function:
=IF(OR(LEFT(A1,1) = "4", LEFT(A1, 2) = "04"), 0.055, 0.044)

LEFT(A1,1) checks the first value and LEFT(A1, 2) checks the first two values.
Just drag the cell (B1) from the bottom right corner to copy the function for additional cells.


text:
Q: How to parse the first attribute in an XML string? Can you help me with this program i'm trying to parse an xml file and my XML Looks like:
This my XML
<pre>
<site>
<restaurant capacite="450" heure_debut_service="11:30:00" heure_fin_service="14:00:00" nom="LE MARCHE">
        <disponibilite>
            <d i="haute" o="0" t="0"/>
            <d i="haute" o="-17" t="10"/>
            <d i="haute" o="-13" t="20"/>
            <d i="haute" o="42" t="30"/>
            <d i="haute" o="109" t="40"/>
            <d i="haute" o="222" t="50"/>
            <d i="complet" o="298" t="60"/>
            <d i="complet" o="323" t="70"/>
            <d i="complet" o="315" t="80"/>
            <d i="complet" o="302" t="90"/>
            <d i="faible" o="285" t="100"/>
            <d i="faible" o="255" t="110"/>
            <d i="haute" o="213" t="120"/>
            <d i="haute" o="152" t="130"/>
            <d i="haute" o="96" t="140"/>
            <d i="haute" o="49" t="150"/>
        </disponibilite>
        <fluidite>
            <f i="fluide" o="0" t="0"/> // I want to search this value i="fluide"
            <f i="fluide" o="13" t="10"/>
            <f i="fluide" o="25" t="20"/>
            <f i="fluide" o="35" t="30"/>
            <f i="fluide" o="84" t="40"/>
            <f i="fluide" o="80" t="50"/>
            <f i="fluide" o="67" t="60"/>
            <f i="fluide" o="66" t="70"/>
            <f i="fluide" o="61" t="80"/>
            <f i="fluide" o="56" t="90"/>
            <f i="fluide" o="48" t="100"/>
            <f i="fluide" o="34" t="110"/>
            <f i="fluide" o="20" t="120"/>
            <f i="fluide" o="13" t="130"/>
            <f i="fluide" o="9" t="140"/>
            <f i="12" o="3" t="150"/>
        </fluidite>
        <stand nom="PIZZA PASTA ETC.">
            <fluidite>
                <f i="pertubé" t="0"/>
                <f i="fluide" t="10"/>
                <f i="fluide" t="20"/>
                <f i="fluide" t="30"/>
                <f i="ralenti" t="40"/>
                <f i="ralenti" t="50"/>
                <f i="fluide" t="60"/>
                <f i="ralenti" t="70"/>
                <f i="fluide" t="80"/>
                <f i="fluide" t="90"/>
                <f i="fluide" t="100"/>
                <f i="fluide" t="110"/>
                <f i="fluide" t="120"/>
                <f i="fluide" t="130"/>
                <f i="fluide" t="140"/>
                <f i="ralenti" t="150"/>
            </fluidite>
            <menuSemaine>
                <menu jour="0">
                    <plat>
                        Kebab   Sauce yaourt
                    </plat>
                </menu>
            </menuSemaine>
        </stand>
        <stand nom="COCOTTES">
            <fluidite>
                <f i="fluide" t="0"/> //My code search this value "i=fluide"
                <f i="fluide" t="10"/>
                <f i="fluide" t="20"/>
                <f i="fluide" t="30"/>
                <f i="ralenti" t="40"/>
                <f i="ralenti" t="50"/>
                <f i="fluide" t="60"/>
                <f i="ralenti" t="70"/>
                <f i="fluide" t="80"/>
                <f i="fluide" t="90"/>
                <f i="fluide" t="100"/>
                <f i="fluide" t="110"/>
                <f i="fluide" t="120"/>
                <f i="fluide" t="130"/>
                <f i="fluide" t="140"/>
                <f i="fluide" t="150"/>
            </fluidite>
            <menuSemaine>
                <menu jour="0">
                    <plat>
                        Escalope de dinde, crème forestière, macaronis
                    </plat>
                </menu>
            </menuSemaine>
        </stand>
</site>
</pre>

My parser code is like this:

*

*(void)parser:(NSXMLParser *)parser didStartElement:(NSString *)elementName namespaceURI:(NSString *)namespaceURI qualifiedName:(NSString *)qualifiedName
attributes:(NSDictionary *)attributeDict {

self.currentElement = elementName;

if ([elementName isEqualToString:@"restaurant"])
{

self.aArticle = [[Article alloc]init];
self.aArticle.key = [NSString stringWithFormat:@"art%d",self.counter];
self.counter++;

}
//Fluidite
if ([elementName isEqualToString:@"f"])
{
    self.aArticle.datePublished2 = [attributeDict valueForKey:@"t"];
    if ([self.aArticle.datePublished2 isEqualToString:@"0"])
    {
        self.aArticle.datePublished = [attributeDict valueForKey:@"i"];
    }
}
}

My code search this value "i=fluide".
stand -> nom="COCOTTES" -> fluidite -> f i="fluide"
but I want this value
stand -> restaurant -> fluidite -> f -> i="fluide" (the first line
Any help would be appreciated......
Thanks

A: Have a look at this class on GitHub as it will save you a lot of time. I use this in many different projects. The methods that will most likely be of interest to you are + (NSDictionary *)dictionaryWithXMLFile:(NSString *)path; and + (NSDictionary *)dictionaryWithXMLData:(NSData *)data;
You will end up with a nested NSDictionary object that you can traverse using standard key/value operations or using blocks as shown below
[dictionary enumerateKeysAndObjectsWithOptions:NSEnumerationConcurrent
                          usingBlock:^(id key, id object, BOOL *stop) {

}];


text:
Q: Como agregar datatable a una lista de ajax Tengo el siguiente formulario que al ingresar dos fechas me lista por ajax el resultado.

este es un js.
$('#frm_range_date').submit(function(event) {
event.preventDefault();
$.ajax({
  url: $(this).attr('action'),
  type: 'POST',
  dataType: 'json',
  data: $(this).serialize(),
  beforeSend: function(){
  $('#body_range_date').html('

Loading...

');
},
success: function (data) {
console.log(data);
  var val = 0;
  var estado = "";
  html3= '';
  $.each(data, function(index, value){
      val = val +1 ;
      html3 += "
";
      html3 += ""+val+"	";
      html3 += ""+value.ruc+"	";
      html3 += ""+value.businessName+"	";
      html3 += ""+value.name+"	";
      html3 += ""+value.total+"	";
      html3 += " S/. "+value.precio+" soles	";
      html3 += "
";
      $('#body_range_date').html(html3);
  });
}
})

});
lo que quisiera es saber si hay manera de agregar datatable a mi resultado en ajax. para poder tener el filtro y la paginacion automaticamente.


text:
Q: What statistics can I use to combine multiple rankings in order to create a final ranking? I have a list of genes and I am checking certain factors for each gene. I have individual scoring system for each factor for each gene. My final table/matrix looks like this:
Gene    Factor1    Factor2    Factor3    Factor4
ALS     0.006      1.0        2.3        0.8
NCLS    0.09       0.8        1.8        0.18
MLB     0.4        0.0        1.8        0.78
BJ      1.1        0.0        0.75       0.18

The scores for each factor are independent and comparable to scores within that factor only, i.e., 1.1 is very good for factor1, but may not be so good for factor3. However, for any given factor, the higher the number the better.
What I am trying to achieve is a ranking of genes. From the example, ALS and MLB should be on the top because for ALS, factors 2-4 have highest values, for MLB, factor2 is 0 but other factors have high values.
Can you suggest what statistics can be used on matrices like this to create a ranking and level of significance? Can I normalize the scores for each factor by calculating Standard Score/z-score (even though all of them don't follow a normal distribution)? What other normalization can be done? Can I instead rank the genes independently for each factor, and then somehow combine the ranks to create a final ranking?

A: Let $r_{g,i}$ be the rank of gene $g$ in ranking $i$ (out of a total of $k$ rankings). Then a statistic which pools these ranks together is the rank product statistic, which is just the geometric mean of the ranks:
$$RP(g) = \left(\prod_{i=1}^k r_{g,i}\right)^{\frac{1}{k}}$$
The rank product statistic was mainly developed to pool together independent replicates, but I think it should work nicely for your use case as well, since you claim that the different scores are independent.
There also exists a R package, which implements this statistic (as well as calculates significance/p-values), though I have never used it.


text:
Q: Enviar formulário sem saber o nome Tenho um formulário que muda o seu nome constantemente , e quero  dar o submit nele por uma função. Nesta função "altera" ele recebe o nome do formulário, mas desta forma que fiz ele não funciona. O "+ide+" do formulário é um numero aleatório, por isso passo ele para a função "altera". Se alguém poder me ajudar e explicar como fazer funcionar o que quero fazer.
<form method='get' action='GG.php' name='alteracao"+ide+"'>
    <button onclick='altera(alteracao"+ide+")'>Enviar</button>
</form>

function altera(ide){
        document.ide.submit();
    }

A: Ao invés de gerar um name aleatório para o formulário, gere um id aleatório:

function altera(ide) {
    var form = document.getElementById(ide);
    alert(form.teste.value); // Para você se certificar que pegou o objeto correto.
    form.submit();
}
<form method='get' action='GG.php' id='alteracao123'>
    <input name="teste" type="hidden" value="Segredo secreto!" />
    <button onclick='altera("alteracao123")'>Enviar</button>
</form>

No exemplo acima, estou partindo do pressuposto de que 123 é o número gerado automaticamente.

A: Pode obter o nome do form pela relação entre o botão e próprio form

function altera(meuForm){
  alert(meuForm.name);
  meuForm.submit();
}
<form method='get' action='GG.php' name="esse form tem um nome muito difícil"  id='alteracao"+ide+"'>
    <button type="button" onclick='altera(this.parentNode)'>Enviar</button>
</form>

A: Você pode dar um id para seu formulario como 'altera'
<form method='get' action='GG.php' name='alteracao"+ide+"' id="altera">
    <button onclick='altera(alteracao"+ide+")>Enviar</button>
</form>

Com isso é possivel verificar quando for dar 'submit' no form e rodar sua função:
document.getElementById('altera').addEventListener('submit', function(
    // Aqui você realiza suas funções
    altera();
));


text:
Q: Javascript query with switch I am new to javascript and trying to complete what should be a simple task of getting the user to interact with a simple contacts array, I am struggling to find the correct syntax to loop through the choice variable until the user enters 0 to quit, i have tried a while loop and for but just not sure exactly where i should be putting the loop and advice would be grateful
var Contact = {
    //Initialise the contact
    init: function(firstName, lastName) {
        this.firstName = firstName;
        this.lastName = lastName;
    },
    //Display the contact details
    describe: function() {
        var description = "Last name : " + this.lastName + ", first name: " + this.firstName;
        return description
    }
};

var contact1 = Object.create(Contact);
contact1.init("John", "Smith");

var contact2 = Object.create(Contact);
contact2.init("Jane", "Doe");

var contacts = [];
contacts.push(contact1);
contacts.push(contact2);

console.log("Welcome to your contacts manager!");
console.log("1: List contacts");
console.log("2: Add a contact");
console.log("0: Quit");

var choice = "";
choice = prompt("Enter 1, 2 or 0");

//while (choice !== "0") {

switch (choice) {
case "1":
    console.log("Here's the list of all your contacts:");
    contacts.forEach(function (contact) {
    console.log(contact.describe());
    });
    console.log("1: List contacts");
    console.log("2: Add a contact");
    console.log("0: Quit");
    break;

case "2":
    contacts.push(prompt("Enter new name: "));
    console.log("Contact added");
    console.log("1: List contacts");
    console.log("2: Add a contact");
    console.log("0: Quit");
    break;

case "0":
    console.log("Goodbye");
    console.log("1: List contacts");
    console.log("2: Add a contact");
    console.log("0: Quit");
    break;

default:
    console.log("Invalid Entry");
    console.log("1: List contacts");
    console.log("2: Add a contact");
    console.log("0: Quit");
    break;
    }

A: Please see the updated while loop

var Contact = {
    //Initialise the contact
    init: function(firstName, lastName) {
        this.firstName = firstName;
        this.lastName = lastName;
    },
    //Display the contact details
    describe: function() {
        var description = "Last name : " + this.lastName + ", first name: " + this.firstName;
        return description
    }
};

var contact1 = Object.create(Contact);
contact1.init("John", "Smith");

var contact2 = Object.create(Contact);
contact2.init("Jane", "Doe");

var contacts = [];
contacts.push(contact1);
contacts.push(contact2);

console.log("Welcome to your contacts manager!");
console.log("1: List contacts");
console.log("2: Add a contact");
console.log("0: Quit");

var choice = "";
while(choice != "0"){

choice = prompt("Enter 1, 2 or 0");

switch (choice) {
case "1":
    console.log("Here's the list of all your contacts:");
    contacts.forEach(function (contact) {
    console.log(contact.describe());
    });
    console.log("1: List contacts");
    console.log("2: Add a contact");
    console.log("0: Quit");
    break;

case "2":
    contacts.push(prompt("Enter new name: "));
    console.log("Contact added");
    console.log("1: List contacts");
    console.log("2: Add a contact");
    console.log("0: Quit");
    break;

case "0":
    console.log("Goodbye");
    console.log("1: List contacts");
    console.log("2: Add a contact");
    console.log("0: Quit");
    break;

default:
    console.log("Invalid Entry");
    console.log("1: List contacts");
    console.log("2: Add a contact");
    console.log("0: Quit");
    break;
    }
}

Update

var Contact = {
    //Initialise the contact
    init: function(firstName, lastName) {
        this.firstName = firstName;
        this.lastName = lastName;
    },
    //Display the contact details
    describe: function() {
        var description = "Last name : " + this.lastName + ", first name: " + this.firstName;
        return description
    }
};

var contact1 = Object.create(Contact);
contact1.init("John", "Smith");

var contact2 = Object.create(Contact);
contact2.init("Jane", "Doe");

var contacts = [];
contacts.push(contact1);
contacts.push(contact2);

console.log("Welcome to your contacts manager!");
console.log("1: List contacts");
console.log("2: Add a contact");
console.log("0: Quit");

var choice = "";
while(choice != "0"){

choice = prompt("Enter 1, 2 or 0");

switch (choice) {
case "1":
    console.log("Here's the list of all your contacts:");
    contacts.forEach(function (contact) {
    console.log(contact.describe());
    });
    console.log("1: List contacts");
    console.log("2: Add a contact");
    console.log("0: Quit");
    break;

case "2":
 firstname = prompt("Enter first name: ");
 lastname = prompt("Enter last name: ")
    var contactnew = Object.create(Contact);
 contactnew.init(firstname, lastname);
 contacts.push(contactnew);
    console.log("Contact added");
    console.log("1: List contacts");
    console.log("2: Add a contact");
    console.log("0: Quit");
    break;

case "0":
    console.log("Goodbye");
    console.log("1: List contacts");
    console.log("2: Add a contact");
    console.log("0: Quit");
    break;

default:
    console.log("Invalid Entry");
    console.log("1: List contacts");
    console.log("2: Add a contact");
    console.log("0: Quit");
    break;
    }
}

A: You want the user to enter multiple things, so you may put prompt into the loop:
var choice = "";
while (choice !== "0") {
  choice = prompt("Enter 1, 2 or 0");
  switch(choice){
   //...
  }
}

A: In switch case you are checking for String "0". Use case 0: or convert input to string and pass the data to switch.


text:
Q: Distributing an Electron app on Windows, Mac and Linux I've spend my weekend experimenting with Electron and this caused a few questions and dilemmas in my head.
I cloned the following Github repository to test with:
electron-vue-typescript-starter
This project uses electron-builder to build the project, based on the host platform you're developing on. Since I'm developing on Windows it builds an .exe file.
Apart from the .exe there are also some other files. The following files were made by electron-builder on windows:
| win-unpacked
|--- (lots of DDL's + electron-application.exe)

--- electron-builder.yaml
--- electron-application setup 0.0.0.exe
--- electron-application setup 0.0.0.exe.blockmap
--- latest.yml

Question 1: If I want to distribute the application for public usage, what should users download? The .exe setup only? Or do they need some/all of the other files aswell?
After setting up a macOS VM I've managed to build the application for the darwin platform too. The following files were made by electron-builder on darwin:
| github
|--- latest-mac.json
| mac
|--- electron-application.app

--- electron-builder.yaml
--- electron-application-0.0.0-mac.zip
--- electron-application-0.0.0.dmg
--- electron-application-0.0.0.dmg.blockmap
--- latest-mac.yml

Question 2: What do the users need from above to use/install the application on the darwin platform?
Question 3: I haven't build the application for linux yet. But how do I distribute the linux edition? Would this be similar to the darwin one?
Note: I have read some parts of the electron-builder documentation but it it's really abstract and doesn't explain (as far as I could see) how someone would distribute the build contents.
The cleanest way would be a single .exe file for windows and a single .zip or .dmg for darwin. But what are the other files for? What should I do with them, because they are there for a reason, right?

A: For distribution, you need to provide an installer (msi) for windows user.

*

*You need to follow below link, which will answer all your questions.

electron-packager-tutorial
electron-windows-installer
Above tutorial also provide information about creating Debian package.

A: You will need to serve them with the entire folder contents. When they run the .exe, it references the other files to complete the installation


text:
Q: Importing a variable in Python? I'm using sympy to write superscript using the pretty_print command. This needs to be imported along with some variables(algebra(x,y,etc.)) in order for the pretty_print command to work. If you dont import the variables(algebra) from sympy.abc, you will need to put the letters in quote marks '' in which the pretty_print command won't work.
So for example if I print x² on the screen, i need to import x so it can be used in the program. Like this:
import sympy
from sympy import pretty_text as exp
from sympy.abc import x

equation= x**2

exp(equation)

This will print x² on the screen. The problem is if i assign a value to x, then it will no longer be equal to itself. If i print x directly after import from sympy.abc, it does this-
(pretending this is IDLE) >
>>> import sympy
>>> from sympy import pretty_text as exp
>>> from sympy.abc import x

>>> x
x

however if a make x 1
>>> import sympy
>>> from sympy import pretty_text as exp
>>> from sympy.abc import x

>>> x
x
>>> x = 1
>>>x
1

Then i need to square x again,
>>> import sympy
>>> from sympy import pretty_text as exp
>>> from sympy.abc import x

>>> x
x
>>> x = 1
>>>x
1
>>> equation = x**2
>>> exp(equation)
1

It will just square 1. Even if it try to make x = 'x' again it is not the same since it will have the '' around it. I can only fix this by importing it again. However, in my program i could end up needing to import any letter again so I would need to import a variable. I tried
from sympy.abc import x[0]

But that's invalid. So, is there any way i could import a varying letter?

A: If you want to preserve symbols, do not assign any values to them - keep using symbols until you really need a solution.
For example:
In [15]: equation=sympy.sin(x**2)

In [16]: exp(equation)
   ⎛ 2⎞
sin⎝x ⎠

In [17]: result = equation.subs({'x': 2})

In [18]: result
Out[18]: sin(4)

In [19]: result.evalf()
Out[19]: -0.756802495307928

This does not change the x itself - later on:
In [23]: exp(sympy.log(x**.5))
   ⎛ 0.5⎞
log⎝x   ⎠

Keep your equations in the symbolic form for as long as needed and don't worry about the values themselves.

A: You don't need to import symbol names in SymPy. The abc module is just there for convenience for one-letter symbol names.
Just create the Symbol object with whatever name you want (this can be any string, including one created dynamically).
>>> x = Symbol('x')
>>> x
x

Also note that the name you give the symbol and the name of the Python variable holding that symbol need not be related. Indeed a Symbol has no idea what Python variable names it is bound to (this is how everything works in Python, not just SymPy)
>>> x = Symbol('y')
>>> x
y

You can also use symbols to create multiple symbols at once
>>> x, y, z = symbols('x y z')

A: If you instead do:
import sympy.abc
x = sympy.abc.x

Then whenever you need your original value, just use sympy.abc.x. If you need to dynamically get a name:
getattr(sympy.abc, "x")

Where the literal could be replaced with any variable.


text:
Q: Cannot access XML node in as3 So I have my XML file loaded in as3 and I can see it is correctly loaded and it is the right file because I can trace it but when I try to trace a specific node, my output window remains empty. Here is my code:
var _textes:XML;
loader = new URLLoader();
requete = new URLRequest("texte_fr.xml");
loader.load(requete);
loader.addEventListener(Event.COMPLETE, finChargement);

function finChargement(pEvt:Event){
    _textes= new XML(pEvt.target.data);
}

If I trace _textes, I can see all my XML code but as soon as I try to trace a node in my XML file, I can't see anything. For exemple if I try to trace _textes.instructions, nothing comes up. What am I doing wrong?
Here is my XML file:
<?xml version="1.0" encoding="utf-8"?>
<textes version="1" xmlns="http://xspf.org/ns/0/">
<instructions>
    Some text
</instructions>
<niveau1>
    <reussi>
        Some other text
    </reussi>
    <fail>
        Some other text
    </fail>
</niveau1>
<niveau2>
    <reussi>
        Some other text
    </reussi>
    <fail>
        Some other text
    </fail>
</niveau2>
<niveau3>
    <reussi>
        Some other text
    </reussi>
    <fail>
        Some other text
    </fail>
</niveau3>
<perdu>
    Some other text
</perdu>
<general>
    Some other text
</general>
<boutons>
    Some other text
</boutons>
</textes>

A: EDIT: @fsbmain beat me to it with a proper solution, while I was editing my answer :) Here is my revised answer anyway...
You aren't getting the contents of that node because you are not referencing the node using the xml document's namespace.
This is how you should access your xml nodes:
function finChargement(pEvt:Event){
    _textes= new XML(pEvt.target.data);
    // The namespace in your xml document:
    var ns:Namespace = new Namespace("http://xspf.org/ns/0/");
    default xml namespace = ns;
    trace(_textes.instructions);
}

For more info see this page

Namespaces are used to separate or identify data. In XML they are used
  to associate one or more nodes with a certain URI (Uniform Resource
  Identifier). Elements with a namespace can have the same tag name as
  other tags but still be separated from them because of their
  association with a URI.

Here is an example:
Say you have this xml data:
<?xml version="1.0" encoding="utf-8"?>
<textes>
    <instructions  xmlns="http://xspf.org/ns/0/">
        Node 1
    </instructions>
    <instructions  xmlns="http://xspf.org/ns/1/">
        Node 2
    </instructions>
</textes>

If you access the "instructions" node using the namespace of the first node, you will get the first node's contents.
function finChargement(pEvt:Event){
    _textes= new XML(pEvt.target.data);
    var ns:Namespace = new Namespace("http://xspf.org/ns/0/");
    default xml namespace = ns;
    trace(_textes.instructions);
    // Will output "Node 1"
}

If you use the second node's namespace, you will get the second node's contents:
function finChargement(pEvt:Event){
    _textes= new XML(pEvt.target.data);
    var ns:Namespace = new Namespace("http://xspf.org/ns/1/");
    default xml namespace = ns;
    trace(_textes.instructions);
    // Will output "Node 2"
}

A: You can set default namespace to empty in order to use e4x without specifying namespace  by this code:
        var xml:XML = Some text
    var ns:Namespace = xml.namespace("");
    default xml namespace = ns;
    trace(xml.instructions.toString()); //output "Some text"


text:
Q: Type Class and Subclassing Suppose I have a type class:
trait ToString[T] {
  def toString(t: T): String
}

And the following pimp:
implicit def ToStr[T: ToString](t: T) = new {
  def toStr: String = implicitly[ToString[T]] toString t
}

Now let´s test it:
class A
implicit object AToString extends ToString[A] {
  def toString(a: A) = "A"
}
(new A).toStr // A

Fine, so far. But if I introduce a subclass B of A:
class B extends A
(new B).toStr // could not find implicit value for evidence parameter of type ToString[B]

So I tried:
implicit def foo[X: ToString, Y <: X]: ToString[Y] = new ToString[Y] {
  def toString(y: Y): String = implicitly[ToString[X]] toString y
}

But then I got:
(new B).toStr // diverging implicit expansion for type ToString[...]

What can I do to automatically use the type class for the superclass if there isn`t a type class for the subclass available?

A: You should make the type parameter of 'ToString' contravariant:
trait ToString[-T] {
  def toString(t: T): String
}

implicit def ToStr[T: ToString](t: T) = new {
    def toStr: String = implicitly[ToString[T]] toString t
}

class A
implicit object AToString extends ToString[A] {
    def toString(a: A) = "A"
}

(new A).toStr // A

class B extends A
(new B).toStr // A

You can find some detailed information about variance in scala here:

*

*http://blogs.atlassian.com/2013/01/covariance-and-contravariance-in-scala/


text:
Q: apache 2 and flask, reportlab registerFont "TTFError: Can't open file ..." but works on dev server am new to python and i am trying to get flask micro-framework to work with apache. I am using the wsgi setup instructions as described in the following article:
https://www.digitalocean.com/community/articles/how-to-deploy-a-flask-application-on-an-ubuntu-vps
unfortunately, although the application works fine, when trying to produce a pdf using reportlab I am getting the following error (extract from apache logs)
[Thu Jan 09 22:47:44 2014] [error] ERROR:flaskapp:Exception on /print/0 [GET]
[Thu Jan 09 22:47:44 2014] [error] Traceback (most recent call last):
[Thu Jan 09 22:47:44 2014] [error]   File "/usr/local/lib/python2.7/dist-packages/flask/app.py", line 1817, in wsgi_app
[Thu Jan 09 22:47:44 2014] [error]     response = self.full_dispatch_request()
[Thu Jan 09 22:47:44 2014] [error]   File "/usr/local/lib/python2.7/dist-packages/flask/app.py", line 1477, in full_dispatch_request
[Thu Jan 09 22:47:44 2014] [error]     rv = self.handle_user_exception(e)
[Thu Jan 09 22:47:44 2014] [error]   File "/usr/local/lib/python2.7/dist-packages/flask/app.py", line 1381, in handle_user_exception
[Thu Jan 09 22:47:44 2014] [error]     reraise(exc_type, exc_value, tb)
[Thu Jan 09 22:47:44 2014] [error]   File "/usr/local/lib/python2.7/dist-packages/flask/app.py", line 1475, in full_dispatch_request
[Thu Jan 09 22:47:44 2014] [error]     rv = self.dispatch_request()
[Thu Jan 09 22:47:44 2014] [error]   File "/usr/local/lib/python2.7/dist-packages/flask/app.py", line 1461, in dispatch_request
[Thu Jan 09 22:47:44 2014] [error]     return self.view_functions[rule.endpoint](**req.view_args)
[Thu Jan 09 22:47:44 2014] [error]   File "/var/www/flaskapp/flaskapp/__init__.py", line 124, in print_rep
[Thu Jan 09 22:47:44 2014] [error]     registerFont(TTFont('DroidSans', 'DroidSans.ttf'))
[Thu Jan 09 22:47:44 2014] [error]   File "/usr/local/lib/python2.7/dist-packages/reportlab/pdfbase/ttfonts.py", line 1009, in __init__
[Thu Jan 09 22:47:44 2014] [error]     self.face = TTFontFace(filename, validate=validate, subfontIndex=subfontIndex)
[Thu Jan 09 22:47:44 2014] [error]   File "/usr/local/lib/python2.7/dist-packages/reportlab/pdfbase/ttfonts.py", line 915, in __init__
[Thu Jan 09 22:47:44 2014] [error]     TTFontFile.__init__(self, filename, validate=validate, subfontIndex=subfontIndex)
[Thu Jan 09 22:47:44 2014] [error]   File "/usr/local/lib/python2.7/dist-packages/reportlab/pdfbase/ttfonts.py", line 412, in __init__
[Thu Jan 09 22:47:44 2014] [error]     TTFontParser.__init__(self, file, validate=validate,subfontIndex=subfontIndex)
[Thu Jan 09 22:47:44 2014] [error]   File "/usr/local/lib/python2.7/dist-packages/reportlab/pdfbase/ttfonts.py", line 189, in __init__
[Thu Jan 09 22:47:44 2014] [error]     self.readFile(file)
[Thu Jan 09 22:47:44 2014] [error]   File "/usr/local/lib/python2.7/dist-packages/reportlab/pdfbase/ttfonts.py", line 263, in readFile
[Thu Jan 09 22:47:44 2014] [error]     self.filename, f = TTFOpenFile(f)
[Thu Jan 09 22:47:44 2014] [error]   File "/usr/local/lib/python2.7/dist-packages/reportlab/pdfbase/ttfonts.py", line 175, in TTFOpenFile
[Thu Jan 09 22:47:44 2014] [error]     raise TTFError('Can\\'t open file "%s"' % fn)
[Thu Jan 09 22:47:44 2014] [error] TTFError: Can't open file "DroidSans.ttf"

it looks like that the registerFont can't access the font.
running it in the development server, it works fine.
I tried several locations, even putting the font in a font folder within the reportlab folder but still nothing.
looked in this article that suggests fast_cgi (for Django) but I am not sure if this will solve my problem.
python reportlab - registerFont - django - font not available after some time
any ideas? Thanks

A: font files must be in paths declared in reportlab.rl_config.TTFSearchpath (search path list)
Try to output list content.
And, no, switching to fast_cgi with Django won't make you understand what went wrong.


text:
Q: Disable page for not logged in users How to show 404 for the unlogged user instead of page?
For now, I have: when the user is not logged the page link does not show in the main menu. But when I type the URL (page.com/my_page) I get redirect to my_page.
Any help would be appreciated. Thanks in advance.

A: Try this one:

/app/etc/modules/Custom_Module.xml

<?xml version="1.0"?>
<config>
    <modules>
        <Custom_Module>
            <codePool>local</codePool>
            <active>true</active>
        </Custom_Module>
    </modules>
</config>

/app/code/local/Custom/Module/etc/config.xml

<?xml version="1.0"?>
<config>
    <modules>
        <Custom_Module>
            <version>0.0.1</version>
        </Custom_Module>
    </modules>
    <global>
        <models>
            <custommodule>
                <class>Custom_Module_Model</class>
            </custommodule>
        </models>
        <helpers>
            <custommodule>
                <class>Custom_Module_Helper</class>
            </custommodule>
        </helpers>
    </global>
    <frontend>
        <events>
            <controller_action_predispatch>
                <observers>
                    <Custom_Module_Model_Observer>
                        <type>singleton</type>
                        <class>custommodule/observer</class>
                        <method>noRoutUrl</method>
                    </Custom_Module_Model_Observer>
                </observers>
            </controller_action_predispatch>
        </events>
    </frontend>
</config>

/app/code/local/Custom/Module/Model/Observer.php

<?php
class Custom_Module_Model_Observer extends Varien_Event_Observer {
    public function noRoutUrl($observer) {
        if ((strpos(Mage::helper('core/url')->getCurrentUrl(),'my_page') != false) && (! Mage::getSingleton('customer/session')->isLoggedIn()))  {
            Mage::app()->getResponse()->setRedirect('/no-route');
        }
    }
}
?>

/app/code/local/Custom/Module/Helper/Data.php

<?php

class Custom_Module_Helper_Data extends Mage_Core_Helper_Abstract{

}

This the step you have to follow by creating all files

A: You can try this below code:
<?php if (strpos(Mage::helper('core/url')->getCurrentUrl(),'my_page') != false && ! Mage::getSingleton('customer/session')->isLoggedIn())  {

            Mage::app()->getResponse()->setRedirect('/no-route');

        }


text:
Q: Keypress event is triggered twice for a single ENTER button press in Windows CE During development i have observed that certain PDAs with Windows CE and possibly Windows Mobile too are sending the Enter key twice in the key pressed event thus i execute twice the code that lies under the control's key press event for the return button.
I suspect that this is a hardware bug and i would like to ask how you resolved it without changing your application logic.

A: I don't know if this will help but if you read the keyboard port Enter is seen as two bytes rather than one.

A: Without changing the logic?  You really can't (unless there is a hardware or firmware fix).  I'd guess the simplest mechanism (that requires a logic change) is to treat two Enter keys or keypresses in a short period (say < 100ms) then ignore the second.

A: This happened to me too and it turned out it was because the "enable character repeat" option was enabled in control panel->keyboard.  The default repeat delay was way too fast for the keypad that we used, so I just slowed it down and the problem went away.


text:
Q: How to find a correct path in Swift I got this code from the documentation, I can't find the path to my file, I need to copy the "contacts.db" file from Supporting Files Folder to the app in the device not in the simulator for offline use.
func copyItemAtPath(_ srcPath: String,
         toPath dstPath: String,
          error error: NSErrorPointer) -> Bool

srcPath = The path to the file or directory you want to move. This parameter must not be nil.
dstPath = The path at which to place the copy of srcPath. This path must include the name of the file or directory in its new location. This parameter must not be nil.
error = On input, a pointer to an error object. If an error occurs, this pointer is set to an actual error object containing the error information. You may specify nil for this parameter if you do not want the error information.
Any help is highly appreciated. :)

A: You can just drag and drop "contacts.db" into Project Navigator and after that you can find a path of that file this way:
let sourcePath = NSBundle.mainBundle().pathForResource("contacts", ofType: "db")

after that you can copy that file into document folder of your app and for that you need that document folder path:
let doumentDirectoryPath = NSSearchPathForDirectoriesInDomains(.DocumentDirectory, .UserDomainMask, true).first as! String
let destinationPath = doumentDirectoryPath.stringByAppendingPathComponent("contacts1.db")

now you have sourcePath and destinationPath so you can copy that file into document folder:
NSFileManager().copyItemAtPath(sourcePath!, toPath: destinationPath, error: &error)

and if you want to check for error you can do it this way:
var error : NSError?
    NSFileManager().copyItemAtPath(sourcePath!, toPath: destinationPath, error: &error)
    if let error = error {
        println(error.description)
    }

If you are getting your sourcePath nil then goto Targets->YouApp->Build Phases->copy Bundle Resources and add your file there.
Hope this will help.


text:
Q: spark 2.4 com.databricks.spark.avro trouble-shooting I have a spark-job, that I usually submit to a hadoop cluster from a local machine. When I submit it with spark 2.2.0 it works fine, but fails to start when i submit it with version 2.4.0.
Just the the SPARK_HOME makes the difference.
drwxr-xr-x  18 me  576 Jan 23 14:15 spark-2.4.0-bin-hadoop2.6
drwxr-xr-x  17 me  544 Jan 23 14:15 spark-2.2.0-bin-hadoop2.6

I submit the job like
spark-submit \
--master yarn \
--num-executors 20 \
--deploy-mode cluster \
--executor-memory 8g \
--driver-memory 8g \
--class package.MyMain uberjar.jar \
--param1 ${BLA} \
--param2 ${BLALA}

Why does the new spark version refuse to take my uberjar? I did not find any changes in the spark 2.4 docu. Btw: The jar was built with spark 2.1 as dependency. Any ideas?
EDIT:
I think my problem is NOT related to spark failing to find things in my uberjar. Much rather I might have a problem with the new built in avro functionality. As before, I read avro files by using the implicit function spark.read.avro from com.databricks.spark.avro._. Spark 2.4.0 has some new built in avro things (most of them to be found in org.apache.spark:spark-avro_2.*11*:2.4.0). The fail might have something to do with this.
java.lang.ClassNotFoundException: Failed to find data source: org.apache.spark.sql.avro.AvroFileFormat. Please find packages at http://spark.apache.org/third-party-projects.html
at org.apache.spark.sql.execution.datasources.DataSource$.lookupDataSource(DataSource.scala:657)
at org.apache.spark.sql.DataFrameReader.load(DataFrameReader.scala:194)
at org.apache.spark.sql.DataFrameReader.load(DataFrameReader.scala:178)
at com.databricks.spark.avro.package$AvroDataFrameReader$$anonfun$avro$2.apply(package.scala:34)
at com.databricks.spark.avro.package$AvroDataFrameReader$$anonfun$avro$2.apply(package.scala:34)
at myproject.io.TrainingFileIO.readVectorAvro(TrainingFileIO.scala:59)
at myproject.training.MainTraining$.train(MainTraining.scala:37)

soo. i think the problem lies deeper. the actual error i get is:

A: It seems spark 2.4.0 needs --packages org.apache.spark:spark-avro_2.11:2.4.0 in order to run the old com.databricks.spark.avro code lines. Here is some description https://spark.apache.org/docs/latest/sql-data-sources-avro.html
So my problem didnt have anything to do with a missing class in my jar, it much rather had some problems with the new built-in avro things in the new spark version.


text:
Q: using sum,count on the same column in mysql I have a table where i have actions and messages as columns i want to count of particular actions on particular datetime i was able to sum on every action but not count on particular action.
SELECT DATE(datetime),carpark_name,
Sum(CASE action when '2' then 1 else 0 end) as AcceptedIMG,
Sum(CASE action when '3' then 1 else 0 end) as RejectedIMG,
Sum(CASE action when '4' then 1 else 0 end) as ChangeIMG,
sum(CASE action when '23' then 1 else 0 end) as AcceptedViolation,
sum(CASE action when '24' then 1 else 0 end) as RejectedViolation,
sum(CASE action when '25' then 1 else 0 end) as SkippedViolation,
FROM customer_1.audit_trail inner join customer_1.carparks on
customer_1.audit_trail.location_id =  customer_1.carparks.id
 where DATE(datetime)> '2013-12-01'and DATE(datetime)< '2013-12-03'  and location_id = '146'

But this is what I need adding it  count(AcceptedIMG, RejectedIMG,ChangeIMG,) or (count(action(2,3,4) as review. I am not able to do this.

A: To get the SUM of action 2,3 and 4, as column REVIEW and 23,24,25 as CONTRAVENTIO you could do:
SELECT DATE(datetime),
       carpark_name,
       Sum(CASE action when '2' then 1 else 0 end) as AcceptedIMG,
       Sum(CASE action when '3' then 1 else 0 end) as RejectedIMG,
       Sum(CASE action when '4' then 1 else 0 end) as ChangeIMG,
       SUM(CASE WHEN action IN ('2','3','4') then 1 else 0 end) as REVIEW
       sum(CASE action when '23' then 1 else 0 end) as AcceptedViolation,
       sum(CASE action when '24' then 1 else 0 end) as RejectedViolation,
       sum(CASE action when '25' then 1 else 0 end) as SkippedViolation,
       SUM(CASE WHEN action IN ('23','24','25') then 1 else 0 end) as CONTRAVENTION
FROM customer_1.audit_trail
INNER join customer_1.carparks
   ON customer_1.audit_trail.location_id =  customer_1.carparks.id
WHERE DATE(datetime) > '2013-12-01'
  AND DATE(datetime) < '2013-12-03'
  AND location_id = '146'
GROUP BY DATE(datetime),carpark_name

I just added the two columns to your query. If you don't need the individual ones, you can remove them.


text:
Q: Error while creating GCP Serverless VPC Connection ("code": 9) - "Operation failed: Insufficient CPU quota in region." Have tried the following:

*

*Created it in another project, it worked perfectly fine (but I need it in this specific project)

*Tried various IP ranges like 10.8.0.0, 10.128.0.0, 10.160.0.0 - no use

*Doesn't work either if I change the region to us-central1 (instead of europe-west1).
See bellow

gcloud compute networks vpc-access connectors create mongo-connector \
    --network default \
    --region europe-west1 \
    --range 10.8.0.0/28

Getting the following:
ERROR: (gcloud.compute.networks.vpc-access.connectors.create) {
  "code": 9,
  "message": "Operation failed: Insufficient CPU quota in region."
}

Here is screenshot of my CPUs usage in europe-west1 in this project which says limit 8, current limit usage 0% :

Also I don't seem to be in  90-day, $300 Free Trial. mode either.
Am I missing something here ?
Thank you for your help


text:
Q: C Glib Hash Not Matching After Loop Insert? I'm not sure why this glib hash table is unable to match the keys - I am curious to know why.  I read a delimited file and insert it into the hash table, it can read the last value, but not the first or any before that.
Any help?
I was reading in a text file in the format:
001$002$Someval
and so on....

And the Code:
FILE *f = fopen(DEFAULT_MSG_CODES, "r");

/* If file does not exist return 1 */
if (f == NULL) {
    return -1;
}

char *line;
char *token;
char *fields[8];
int i;
line = malloc(2048);

 GHashTable* hash = g_hash_table_new(g_str_hash, g_str_equal);

g_hash_table_insert(hash, "000", "test");

while (fgets(line, 2048, f) != NULL) {

    line[strlen(line) - 1] = '\0';
    i = 0;
    token = strtok(line, "$");

    while (token != NULL) {

        fields[i] = token;
        i++;
        token = strtok(NULL, "$");
    }

    printf("cid: %s eid: %s msg %s\n",fields[0],fields[1],fields[2]);
    g_hash_table_insert(hash,fields[0],fields[1]);

}

free(line);

fclose(f);

printf("There are %d keys in the hash\n", g_hash_table_size(hash));
printf("There is a match %s\n", g_hash_table_lookup(hash,"003"));

A: If I'm not mistaken, you're clobbering the data you put into the hash table on the next iteration of the loop by overwriting line with a new call to fgets. An easy fix would be to strdup (or g_strdup or whatever the ugly glib name for it is) the strings before you add them to the hash table. But you should really read the glib documentation on this API to find out the ownership contract for the data you pass in, and whether the arguments are just pointers to data it will immediately read, or pointers to objects that will become a permanent part of the hash table.


text:
Q: Bayesian using PyMC3: PatsyError
I am trying to use PyMC3 to apply Bayesian linear regression.
I want to predict the Age depending on some measurements.
I found an amazing example and want to apply it with some data.
Below is the code.
import pandas as pd
import numpy as np
import pymc3 as pm
from sklearn.model_selection import train_test_split

data = pd.read_csv('data.csv')
X = data.drop(['User_ID','Gender','Age'], axis = 1)   # the features
Y = data['Age']
X_train, X_test, y_train, y_test = train_test_split(X, Y, test_size=0.2)
print(X_train.shape)
print(X_test.shape)

Formula = 'Age ~ ' + ' + '.join(['%s' % variable for variable in X_train.columns[0:]])
print(Formula)

with pm.Model() as normal_model:
   f = pm.glm.families.Normal()
   pm.GLM.from_formula(Formula, data = X_train, family = f)
   normal_trace = pm.sample(draws=2000, chains = 2, tune = 500)

When I run it, I got this error
PatsyError: Error evaluating factor: NameError: name 'Age' is not defined
Age ~ Height + Weight + Duration + Heart_Rate + Body_Temp + Calories
^^^

But if I keep the Age in the X, it worked fine, but in this case the Age also involved in the formula which should not be because Age is the dependent variable while the others are the independent variables .
Any idea how to fix it?
Thanks in advance

A: To use the pm.GLM.from_formula() method, the DataFrame data argument must contain all the variables (predictor and response). A simple way to modify the current code to do this is to reattach the response variable:
pm.GLM.from_formula(Formula, data=pd.concat([X_train, y_train], axis=1), family=f)


text:
Q: AngularJS: Prevent displaying the last separator when repeating multiple arrays Question: What is the most elegant way to ensure the last separator on each line is never shown?
11|18|3|8|12|1|22|31|61|
11:18:3:8:12:1:22:31:
11,18,3,8,12,61,
1 22 31

Note that the data originates from three different arrays, e.g., the data for line 1 is defined as:
$scope.numbers = [11,18,3,8,12];
$scope.specialNumbers = [1,22,31];
$scope.additionalNumbers = [61];

I would like to see a more elegant/angular way, than just finding the last
 and remove separator using $element.find, or similar.
I created a little JSFiddle example to demonstrate the problem.
Thanks

A: Here is a complete solution, using the proposed $last check (only once) in combination with Array.concat, which is supported in Angular expressions and thus supports bindings. However, to correctly repeat literals, you need to moreover track by $index.
"
" +
    "{{ num }}{{ separator }}" +
"
"

A: https://jsfiddle.net/d0ogyfon/
Use Kosta's $last and just concat the lists and iterate once?
    var html = "
" +
                "
" +
    "{{ num }}{{ separator }}" +
    "{{ num }}" +
                "
" +

           "
";

A: And, just for fun, how about a CSS-based solution:
Updated Fiddle
CSS:
li.pipe:not(:last-child):after {
    content: '| ';
}
li.colon:not(:last-child):after {
    content: ': ';
}
li.comma:not(:last-child):after {
    content: ', ';
}
li.space:not(:last-child):after {
    content: ' ';
}

HTML:

Directive
app.directive("test",function(){
    var html =
        "
" +
        "
{{ num }}
" +
            "
{{ num }}
" +
            "
{{ num }}
" +
        "
";

    return {
        template: html,
        scope: {
            separator: "@separatorClass",
            numbers: "=",
            specialNumbers: "=",
            additionalNumbers: "="
        }
    };
});

A: You can make use of $last element:
"
" +
     "{{ num }}{{ separator }}" +
     "{{ num }}" +
"
"


text:
Q: Auth based on Relationships I have a team with many tasks and tasks can have many submissions.
I want team admins to see all tasks for their team only and all submissions for all tasks of their team.

*

*I can do a lambda authenticator (allow: custom) and query DynamoDB. Is this supported for DataStore?

*I can implement through resolvers following this pattern here: https://dabit3.medium.com/intro-to-aws-appsync-pipeline-functions-3df87ceddac1. Is this recommended?

*I can propagate admins and have a ownerField = [] on them. This works but if an admin is removed from the team I have to go and update all the rows async in a lambda

*Finally I can create an auth group and propagate the group name to all the tasks and submissions. However there is a limitation on the number of groups (10,000) I think? so I can only have 10000 teams. Although would like to have a list of subscribers potentially on a task, etc..

How would you recommend I do this?


text:
Q: Hide 'add to cart' button ONLY on woocommerce shop/category pages I want to hide the button on my shop pages, but I would like to show it on other posts and pages.
I've found this code to hide the add to cart button on my whole website:
add_action( 'woocommerce_after_shop_loop_item', 'remove_add_to_cart_buttons', 1 );

function remove_add_to_cart_buttons() {
    remove_action( 'woocommerce_after_shop_loop_item', 'woocommerce_template_loop_add_to_cart' );
}

How can I tweak it, so it only removes the button on woocommerce shop and catagory pages?

A: You can use the Woocommerce conditional tags to check:
http://docs.woothemes.com/document/conditional-tags/
   add_action( 'woocommerce_after_shop_loop_item', 'remove_add_to_cart_buttons', 1 );

    function remove_add_to_cart_buttons() {
      if( is_product_category() || is_shop()) {
        remove_action( 'woocommerce_after_shop_loop_item', 'woocommerce_template_loop_add_to_cart' );
      }
    }

A: This could also be done with CSS by targeting the relevant classes:
.cart{display:none;}

.avia_cart_buttons{display:none;}

In my case there is that avia because i use Enfold Theme. With inspect element find out your class where the buton is located. and declare it invisible.
Another example is:
.woocommerce .products .shop-column.product-hover-style-2 .product-content
.product-add-to-cart-btn{
    display:none !important;
}

A:     add_action('wp','only_add_bierkoerier_in_cart', 'woocommerce_before_cart');

    function only_add_bierkoerier_in_cart() {

    foreach ( WC()->cart->get_cart() as $cart_item_key => $cart_item ) {

    $bierkoerier_in_cart = false;
    $categories = get_categories();

    if ( has_term( 'bierkoerier', 'product_cat', $cart_item['product_id'] ) ) {
        $bierkoerier_in_cart = true;
        break;
    }
    }

    if($bierkoerier_in_cart) {
        wc_print_notice( 'omdat u bierkoerier producten in uw winkelwagen heeft
    kunt u geen winkelitems toevoegen', 'notice' );
       if(is_shop() || is_product() || is_product_category()) {
         remove_action( 'woocommerce_after_shop_loop_item','woocommerce_template_loop_add_to_cart' );
         remove_action( 'woocommerce_single_product_summary', 'woocommerce_template_single_add_to_cart', 30 );
    }
}
}

A: To remove the "Add to cart" button
You need to use hook which not affect other code-
add_action( 'woocommerce_after_shop_loop_item', 'remove_loop_button', 1 );
function remove_loop_button()
{
if( is_product_category() || is_shop()) {
remove_action( 'woocommerce_after_shop_loop_item', 'woocommerce_template_loop_add_to_cart');
}
}

this will remove add to cart button from shop/category pages .

Here you can get WooCommerce Action and Filter Hook
  -https://docs.woothemes.com/wc-apidocs/hook-docs.html

A: Here is a plugin you can use to remove hide disable add to cart button https://wordpress.org/plugins/woo-options/

A: That's quite simple as i have gone through several tutorials when i was trying to fix it . You have to just put this code in woocommerce.php to hide add to cart button for shop page.
function WpBlog() {
  remove_action( 'woocommerce_after_shop_loop_item', 'woocommerce_template_loop_add_to_cart');
  remove_action( 'woocommerce_single_product_summary', 'woocommerce_template_single_add_to_cart');
  return WooCommerce::instance();
}

Hope that would work for you, if not let me know i will guide you

A: To remove add to cart buttons from shop, product category, and single product pages, use below steps:

*

*Locate the functions.php in child theme.  Child theme prevents changes been overwritten by WP updates.
https://www.dreamhost.com/wordpress/create-woocommerce-child-theme/

*Put below code in functions.php:
add_action( 'woocommerce_after_shop_loop_item', 'remove_add_to_cart_buttons', 1 );
function remove_add_to_cart_buttons() {
      if( is_product_category() || is_shop()) {
        remove_action( 'woocommerce_after_shop_loop_item', 'woocommerce_template_loop_add_to_cart' );
      }
    }
add_action( 'woocommerce_single_product_summary', 'woocommerce_before_cart' );
function woocommerce_before_cart() {
      if( is_product()) {
        remove_action( 'woocommerce_single_product_summary', 'woocommerce_template_single_add_to_cart',30);
      }
    }