text:
Q: How to read/get a PropertyGroup value from a .csproj file using C# in a .NET Core 2 classlib project? I want to get the value of the element <Location>SourceFiles/ConnectionStrings.json</Location> that is child of <PropertyGroup /> using C#. This is located at the .csproj file for a .NET Core 2 classlib project. The structure is as follow:
<PropertyGroup>
  <TargetFramework>netcoreapp2.0</TargetFramework>
  <Location>SharedSettingsProvider.SourceFiles/ConnectionStrings.json</Location>
</PropertyGroup>

Which class can I use from .NET Core libraries to achieve this? (not .NET framework)
Update 1:
I want to read the value when the application (that this .csproj file builds) runs. Both before and after deployment.
Thanks

A: As has been discussed in comments, csproj content only controls predefined build tasks and aren't available at run-time.
But msbuild is flexible and other methods could be used to persist some values to be available at run time.
One possible approach is to create a custom assembly attribute:
[System.AttributeUsage(System.AttributeTargets.Assembly, Inherited = false, AllowMultiple = false)]
sealed class ConfigurationLocationAttribute : System.Attribute
{
    public string ConfigurationLocation { get; }
    public ConfigurationLocationAttribute(string configurationLocation)
    {
        this.ConfigurationLocation = configurationLocation;
    }
}

which can then be used in the auto-generated assembly attributes from inside the csproj file:
<PropertyGroup>
  <ConfigurationLocation>https://my-config.service/customer2.json</ConfigurationLocation>
</PropertyGroup>
<ItemGroup>
  <AssemblyAttribute Include="An.Example.ConfigurationLocationAttribute">
    <_Parameter1>"$(ConfigurationLocation)"</_Parameter1>
  </AssemblyAttribute>
</ItemGroup>

And then used at run time in code:
static void Main(string[] args)
{
    var configurationLocation = Assembly.GetEntryAssembly()
        .GetCustomAttribute<ConfigurationLocationAttribute>()
        .ConfigurationLocation;
    Console.WriteLine($"Should get config from {configurationLocation}");
}


text:
Q: Is there an algorithm to find nearby points using only polar coordinates? Suppose I have a vector of points as polar coordinates.
Suppose one of those points acts as a probe for which I want to find all the other points within a certain distance.
Is there an algorithm to do this without converting them to Cartesian form?

A: You are looking for the distance for polar coordinates. You can find the formula in this link.
The distance between points (r1, a1) and (r2, a2) is:
D = sqrt(r1*r1 + r2*r2 - 2*r1*r2*cos(a1-a2))

A: Be careful, if you plan to scale up your algorithm to many points, probing for points nearby is better done using a spatial index. I'm not aware of the existence of spatial indexes using polar coordinates, and I'm sure they would be a bit complex to implement/use. So if you have:

*

*lots of points,

*probe more frequently than moving points,

ask yourself the question whether you should use Cartesian coordinates and a spatial index.
Do the math yourself according to your typical use case:

*

*Using cartesian alongside polar coordinates:

*

*Converting polar to cartesian is done only when a point moves, and involve two trigonometric functions;

*Finding points nearest than a certain distance to another point may be done in O(1) time (depending on the average distance, the size of the spatial index, the number of points...), and does not involve anything other than adds/multiplies (not even square roots, you compare the distance squared).

*Using polar coordinates only:

*

*Scanning for all points w/o spatial index is O(n);

*This involves one trigonometric function per comparison (thus n trig calls per probe).

Be aware that trigs are bloody expensive in computation time.

redpajama_set_name: RedPajamaStackExchange


text:
Q: want to pass reference between two thread in node.js I am trying to implement below steps in node.js

*

*the order can be placed and paid using my rest-API.

*Once the order status changed to PAID from PLACED, it will be enqueued that order in Queue data structure.

*One separate Thread is continuously running to check whether there is order in the Queue or not.  if there is order in the queue, it will be dequeued and start to PREPARED, SERVED and COLLECTED. Here, there may be many order's in the Queue or not at all.

I am sharing my code here
//order.js
var Queue = require('queuejs');
var queue = new Queue();
queue.enq("hello");
const threads = require('threads');
const spawn   = threads.spawn;
const thread  = spawn(function(){});

exports.payOrder = function (req, res) {

   //after changing order status to PAID in database, I enq it in queue.
    queue.enq(id);
};
exports.processOrder = function () {
   spawn("./routes/helper.js").send();
};
exports.queue = queue;

//helper.js
const Sync = require('sync');
const order = require('./order');
const dao = require('./dao');
const config = require('./config');

 Sync(function () {
    console.log("in sync");

    while (true) {
        // I got queue size always 0(zero), even though I called pay api(meaning put order into the queue by calling api)
        if (order.queue.size() > 0) {
            console.log("here");

            var id = order.queue.deq();
            var query = "query string";
            dao.client.execute(query, [config.orderStatus.preparing, id], {prepare: true}, function (err, result) {
                Sync.sleep(5000);
                dao.client.execute(query, [config.orderStatus.served, id], {prepare: true}, function (err, result) {
                    Sync.sleep(5000);
                    dao.client.execute(query, [config.orderStatus.collected, id], {prepare: true}, function (err, result) {
                        Sync.sleep(5000);
                    });
                });
            });
        }
    }
});

I have exported queue in order.js but it is not sharing reference with helper thread.
I have applied many ways to achieve above functionality but not able to implement it successfully.
Can anyone please suggest me the solution?

A: You cannot share references with the thread module.  You can send messages only.  You can either build it without the queue, or use an out of process queue.  One option would be to just use two processes with the kue module.
Example:
var kue = require('kue')
 , queue = kue.createQueue();

queue.process('email', function(job, done){
  email(job.data.to, done);
});

function email(address, done) {
  if(!isValidEmail(address)) {
    //done('invalid to address') is possible but discouraged
    return done(new Error('invalid to address'));
  }
  // email send stuff...
  done();
}


text:
Q: Classify Isolated Singularity Problem Statement: Suppose that $f$ is analytic in the region $0 < |z| < 1$ and suppose there exists a constant $K$ such that
$$ |f(z)| \leq K \ |z|^{-\frac{1}{2}}$$
on $(0,1)$. What kind of isolated singularity does $f$ have at zero?
Attempted Solution: What I want to do is multiply each side by $|z|$, giving us
$$ |z \ f(z)| \leq K \ |z|^{\frac{1}{2}}$$
which gives that $|g(z)| = |z \ f(z)| \leq K \ |z|^{\frac{1}{2}}$ is bounded in an open neighborhood around zero by $K$. By the Riemann Removability Condition, I should be able to state that since $g$ is bounded around $z = 0$, then it has a removable singularity. Then, by the definition of a non-essential singularity, since there exists
$$ g(z) = (z - 0) f(z)$$
such that $g$ has a removable singularity at $0$, then $f$ has a non-essential singularity at $0$.
Is this a valid statement? And if so, is there anymore that can be said about the singularity of $f$ at $0$? Can I say anything about this singularity being either removable or a pole?
Another thing I had considered was attempting to use Picard's Big Theorem to show that $f$ wouldn't have an essential singularity, as it would be dense in that $\mathbb{C}$, and I would be able to find values to contradict the given inequality. However, with the $|z|^{-\frac{1}{2}}$, I'm not sure if this has a singularity that is essential or not (I've seen things about it being a branch cut, etc., but that doesn't seem relevant here, as I'm not computing integrals). Anyways, any methods for solving this problem using a similar method would also be of interest to me.

A: You're on the right track: note that not only does $g(z)$ have a removable singularity at $z=0$, but in fact the extension of $g$ to a holomorphic function on $\{|z|<1\}$ must satisfy $g(0)=0$.
This means that we can write $g(z)=zh(z)$ with $h$ holomorphic on $\{|z|<1\}$, but since also $g(z)=zf(z)$ it follows that $f$ has a removable singularity at $z=0$.


text:
Q: Is it possible to set android permission level for a broadcast receiver at runtime? Is it possible to programatically set the protection level of an IntentFilter/Intent in java similar to how we can define it in the AndroidManifest.xml:
<receiver
    android:name="my.test.receiver"
    android:protectionLevel="signature" />

We have a core library for our apps which facilitates dynamic broadcasts and receivers at runtime and we would like to make them secure here.
I have found no information on this method online and not sure if it is possible. if we could set an intentFilters permission level = PermissionInfo.PROTECTION_SIGNATURE it would work but going by the docs it seems PermissionInfo is only used for reading. The only alternative method I can find is declaring a special permission, sending it with our broadcasts and adding it to all our manifests: https://stackoverflow.com/a/15316487/1810256
We may fall back on this approach but we would prefer the first method as the signature approach seems more secure.
Any help/suggestions appreciated!

A: Quoting one of the users(Naveed Ahmad):
"Guys now from Android 6.0 Marshmellow onward, you can ask users at runtime to allow permissions dynamically, I found of it, have a look at this link. I hope it will help you getting idea."
https://inthecheesefactory.com/blog/things-you-need-to-know-about-android-m-permission-developer-edition/en
I found it in here:
get Android permission dynamiclly


text:
Q: wine staging 1.9.7 not run application after compilation I have download normal wine(1.9.7) and then apply wine staging patch on it(v1.9.7). Then compile wine. And then If I install any application then it show me below things only.
fixme:winediag:start_process Wine Staging 1.9.7 is a testing version containing experimental patches.
fixme:winediag:start_process Please mention your exact version when filing bug reports on winehq.org.

My os version is : Lubuntu16.04 (64 bit)

A: This is not unusual. I say this to so many people. Read the message!
So just do what it says!
It is telling you it is an experimental version. The other one says to say it is a experimental version when filing a bug!


text:
Q: Android Studio UI: TextView position shift after ImageView resize
My second lines TextView is received text, if received text length more than one line, it will resize ImageView.
After ImageView resize the TextView should be on H's corners(the four red circle), but it will shift  to other position.
I try other Layout like FrameLayout, or set TextView's constraint widget to parent or ImageView, but final result is same.
How to keepe TextView on ImageView's position even if ImageView resize?
My layer structure:
linearlayout(Divider)
linearlayout
    btn_1
    btn_2
    btn_3
linearlayout(Divider)
ConstraintLayout
    ConstraintLayout
        ImageView
        TextView_1
        TextView_2
        TextView_3
        TextView_4
    linearlayout
        linearlayout
            btn_1
            btn_2
            btn_3
        linearlayout
            ....

Code:
    <androidx.constraintlayout.widget.ConstraintLayout
        android:layout_width="match_parent"
        android:layout_height="0dp"
        app:layout_constraintBottom_toTopOf="@+id/linearLayout4"
        app:layout_constraintEnd_toEndOf="parent"
        app:layout_constraintStart_toStartOf="parent"
        app:layout_constraintTop_toTopOf="parent">

        <ImageView
            android:id="@+id/imageView"
            android:layout_width="wrap_content"
            android:layout_height="wrap_content"

            android:scaleType="centerInside"
            android:src="@drawable/chair"
            android:visibility="visible"
            app:layout_constraintBottom_toBottomOf="parent"
            app:layout_constraintEnd_toEndOf="parent"
            app:layout_constraintStart_toStartOf="parent"
            app:layout_constraintTop_toTopOf="parent" />

        <TextView
            android:id="@+id/textview_1"
            android:layout_width="wrap_content"
            android:layout_height="wrap_content"

            android:text="0"
            android:visibility="visible"
            app:layout_constraintBottom_toBottomOf="parent"
            app:layout_constraintEnd_toEndOf="parent"
            app:layout_constraintHorizontal_bias="0.28"
            app:layout_constraintStart_toStartOf="parent"
            app:layout_constraintTop_toTopOf="parent"
            app:layout_constraintVertical_bias="0.101" />

        <TextView
            android:id="@+id/textview_2"
            android:layout_width="wrap_content"
            android:layout_height="wrap_content"
            android:layout_gravity="center|center_horizontal"
            android:layout_marginBottom="16dp"
            android:layout_weight="1"
            android:gravity="center_horizontal|center_vertical"
            android:text="0"
            android:visibility="visible"
            app:layout_constraintBottom_toBottomOf="parent"
            app:layout_constraintEnd_toEndOf="parent"
            app:layout_constraintHorizontal_bias="0.28"
            app:layout_constraintStart_toStartOf="parent"
            app:layout_constraintTop_toTopOf="parent"
            app:layout_constraintVertical_bias="1.0" />

        <TextView
            android:id="@+id/textview_3"
            android:layout_width="wrap_content"
            android:layout_height="wrap_content"
            android:layout_gravity="center|center_horizontal"
            android:layout_weight="1"
            android:gravity="center_horizontal|center_vertical"
            android:text="0"
            android:visibility="visible"
            app:layout_constraintBottom_toBottomOf="parent"
            app:layout_constraintEnd_toEndOf="parent"
            app:layout_constraintHorizontal_bias="0.702"
            app:layout_constraintStart_toStartOf="parent"
            app:layout_constraintTop_toTopOf="parent"
            app:layout_constraintVertical_bias="0.101" />

        <TextView
            android:id="@+id/textview_4"
            android:layout_width="wrap_content"
            android:layout_height="wrap_content"
            android:layout_gravity="center|center_horizontal"
            android:layout_weight="1"
            android:gravity="center_horizontal|center_vertical"
            android:text="0"
            android:visibility="visible"
            app:layout_constraintBottom_toBottomOf="parent"
            app:layout_constraintEnd_toEndOf="parent"
            app:layout_constraintHorizontal_bias="0.702"
            app:layout_constraintStart_toStartOf="parent"
            app:layout_constraintTop_toTopOf="parent"
            app:layout_constraintVertical_bias="0.898" />

    </androidx.constraintlayout.widget.ConstraintLayout>

A: I think you should to position texts depended to image like this(for example in below text will positioned to top and left corner of imageView):
<androidx.constraintlayout.widget.ConstraintLayout xmlns:app="http://schemas.android.com/apk/res-auto"
xmlns:tools="http://schemas.android.com/tools"
android:layout_width="match_parent"
android:layout_height="match_parent"
xmlns:android="http://schemas.android.com/apk/res/android">

<ImageView
    android:id="@+id/imageView"
    android:layout_width="match_parent"
    android:layout_height="200dp"
    app:layout_constraintBottom_toBottomOf="parent"
    app:layout_constraintEnd_toEndOf="parent"
    app:layout_constraintHorizontal_bias="1.0"
    app:layout_constraintStart_toStartOf="parent"
    app:layout_constraintTop_toTopOf="parent"
    app:layout_constraintVertical_bias="0.517"
    tools:srcCompat="@tools:sample/avatars" />

<TextView
    android:id="@+id/textView"
    android:layout_width="wrap_content"
    android:layout_height="wrap_content"
    android:layout_marginTop="16dp"
    android:text="T"
    android:textSize="16dp"
    app:layout_constraintEnd_toEndOf="parent"
    app:layout_constraintHorizontal_bias="0.311"
    app:layout_constraintStart_toStartOf="@+id/imageView"
    app:layout_constraintTop_toTopOf="@+id/imageView" />
</androidx.constraintlayout.widget.ConstraintLayout>

A: What you can do here is use Guideline, Guidelines are small visual helpers to design layouts with. Views can be aligned to a guideline which can simplify layouts, especially if you have the same margin values duplicated on a lot of elements. This is helpful and really solve many of my issue design and simplifications :)
<androidx.constraintlayout.widget.ConstraintLayout
        android:layout_width="match_parent"
        android:layout_height="wrap_content"
        app:layout_constraintBottom_toTopOf="@+id/linearLayout4"
        app:layout_constraintEnd_toEndOf="parent"
        app:layout_constraintStart_toStartOf="parent"
        app:layout_constraintTop_toTopOf="parent">

        <ImageView
            android:id="@+id/imageView"
            android:layout_width="342dp"
            android:layout_height="344dp"
            android:scaleType="centerInside"
            android:src="@drawable/chair"
            android:visibility="visible"
            app:layout_constraintBottom_toBottomOf="@+id/guideline2"
            app:layout_constraintEnd_toEndOf="parent"
            app:layout_constraintStart_toStartOf="parent"
            app:layout_constraintTop_toTopOf="@+id/guideline1" />

        <TextView
            android:id="@+id/textview_1"
            android:layout_width="wrap_content"
            android:layout_height="wrap_content"
            android:text="0"
            android:visibility="visible"
            app:layout_constraintBottom_toBottomOf="@+id/guideline1"
            app:layout_constraintEnd_toEndOf="parent"
            app:layout_constraintStart_toStartOf="parent"
            app:layout_constraintTop_toTopOf="parent"
            app:layout_constraintHorizontal_bias="0.28"
            app:layout_constraintVertical_bias="0.101" />

        <TextView
            android:id="@+id/textview_3"
            android:layout_width="wrap_content"
            android:layout_height="wrap_content"
            android:layout_gravity="center|center_horizontal"
            android:layout_weight="1"
            android:gravity="center_horizontal|center_vertical"
            android:text="0"
            android:visibility="visible"
            app:layout_constraintBottom_toBottomOf="@+id/guideline1"
            app:layout_constraintEnd_toEndOf="parent"
            app:layout_constraintHorizontal_bias="0.702"
            app:layout_constraintStart_toStartOf="parent"
            app:layout_constraintTop_toTopOf="parent"
            app:layout_constraintVertical_bias="0.101" />

        <androidx.constraintlayout.widget.Guideline
            android:id="@+id/guideline1"
            android:layout_width="wrap_content"
            android:layout_height="wrap_content"
            android:orientation="horizontal"
            app:layout_constraintGuide_percent="0.1" />

        <TextView
            android:id="@+id/textview_2"
            android:layout_width="wrap_content"
            android:layout_height="wrap_content"
            android:layout_gravity="center|center_horizontal"

            android:layout_weight="1"
            android:gravity="center_horizontal|center_vertical"
            android:text="0"
            android:visibility="visible"
            app:layout_constraintBottom_toBottomOf="parent"
            app:layout_constraintEnd_toEndOf="parent"
            app:layout_constraintStart_toStartOf="parent"
            app:layout_constraintTop_toTopOf="@+id/guideline2"
            app:layout_constraintHorizontal_bias="0.28"
            app:layout_constraintVertical_bias="0.898" />

        <TextView
            android:id="@+id/textview_4"
            android:layout_width="wrap_content"
            android:layout_height="wrap_content"
            android:layout_gravity="center|center_horizontal"
            android:layout_weight="1"
            android:gravity="center_horizontal|center_vertical"
            android:text="0"
            android:visibility="visible"
            app:layout_constraintBottom_toBottomOf="parent"
            app:layout_constraintEnd_toEndOf="parent"
            app:layout_constraintStart_toStartOf="parent"
            app:layout_constraintTop_toTopOf="@+id/guideline2"
            app:layout_constraintHorizontal_bias="0.702"
            app:layout_constraintVertical_bias="0.898" />

        <androidx.constraintlayout.widget.Guideline
            android:id="@+id/guideline2"
            android:layout_width="wrap_content"
            android:layout_height="wrap_content"
            android:orientation="horizontal"
            app:layout_constraintGuide_percent="0.9" />

    </androidx.constraintlayout.widget.ConstraintLayout>


text:
Q: Understanding representations of affine Lie algebras Please reference this paper for notation in this question.
I'm trying to understand two claims made in the above paper (they may be related). First, in the construction of $\mathcal{H}_\lambda$ on page 4, we start with the usual irreducible representation $V_\lambda$ of the semisimple Lie algebra $\mathfrak{g}$, declare the positive powers of $z$ to act trivially and the central element $c$ to act by multiplication by $l$, and then induce an action of the rest of the affine Lie algebra $\hat{\mathfrak{g}}$ on $V_\lambda$. The result is called $\mathcal{V}_\lambda$ and it is isomorphic to $U(\hat{\mathfrak{g}}_-) \otimes_{\mathbb{C}} V_\lambda$ as a $\hat{\mathfrak{g}}_-$-module. As a consequence, it is a highest weight module, and by theory analogous to that of semisimple Lie algebras, it has a maximal submodule.
I understand all of that. What I do not understand is the claim that this maximal submodule $\mathcal{Z}_\lambda$ is generated by $(X_\theta \otimes z^{-1})^{l - \lambda(H_\theta) + 1} v_\lambda$. Following Remark 3.6 on page 8, I managed to prove that this element is annihilated by $\hat{\mathfrak{g}}_+$, and indeed that no lower nonzero power of $X_\theta \otimes z^{-1}$ acting on $v_\lambda$ is annihilated by all of $\hat{\mathfrak{g}}_+$. Thus I'm lead to believe that this should somehow imply that $\mathcal{Z}_\lambda$ is a highest weight module with $(X_\theta \otimes z^{-1})^{l - \lambda(H_\theta) + 1} v_\lambda$ its highest weight vector, and hence the claim follows, but I can't see why this is the case.
The second claim is labeled (*) on page 7: The endomorphism $X_{-\theta} \otimes f$ of $\mathcal{H}$ is locally nilpotent for all $f \in \mathcal{O}(U)$. From what I can tell, this is equivalent to the claim that $X_{-\theta} \otimes f$ is a locally nilpotent endomorphism of $\mathcal{H}_\lambda$ for any $f \in \mathcal{C}((z))$. Following the given hint, I can see why this is true for $f \in \mathcal{C}[[z]]$, but I don't know about negative powers of $z$. I think this might be related to the first claim: Perhaps once we have pushed any element of $\mathcal{V}_\lambda$ into a suitably low weight space by acting on it by $X_{-\theta} \otimes z^{-1}$ repeatedly, it actually falls into some proper submodule of $\mathcal{V}_\lambda$, and is therefore quotiented out when we pass to $\mathcal{H}_\lambda$. Again, I can't see why this is actually true though.
Any ideas on either claim are greatly appreciated.

A: I answer the first question only.
The space $\mathcal{V}_\lambda$ is highest weight for the affine Lie algebra, hence a quotient of a Verma $\Delta(\mu)$ of the affine Lie algebra. The maximal submodule $\mathcal{Z}_\lambda$ is thus the image of the maximal submodule of the Verma.
The maximal submodule of a Verma is known to be generated by the vectors $f_i^{\langle \mu,\alpha_i^\vee\rangle+1}v_\mu$ as $\alpha_i$ runs over the simple roots for the affine root system. In your case, the vectors in this set corresponding to finite simple roots all map to zero in the quotient $\mathcal{V}_\lambda$ by its construcion from a finite dimensional irreducible. Therefore the maximal submodule of $\mathcal{V}_\lambda$ is generated by the image of the vector for the affine root, which is the generator you have written down.


text:
Q: php json_encode echoes true I have a code to make a query over my db, and get back the response and put them in fields over my html. I want to send the response via JSON, then create the fields using that information. But when I echo my json_encode($json_output) I only get a [true].
If anyone can explain me why I'll be appreciated.
Javascritp code:
$($cadView).find('#cadForm').on('submit', function(e){

e.preventDefault();

var str = $('#srBar').val();

if(str == ""){

alert("Campo de busca vazio.");

}else{

$.post($('#cadForm').attr('action'), {q : str}, function(data){

alert(data);

});
}

PHP code:
<?php

$q = $_POST['q'];

require('connect.php');

$i = 0;

$sql="SELECT `_nome`, `_endereco`, `_telefone`, `_imgstring`, `_dtAcesso`, `_descricao`, `_fkIdUser` FROM `tbvisitante` WHERE _nome = ?";
$stmt= $conn->prepare($sql);
$stmt->bind_param('s', $q);

if ($stmt){
    $stmt->execute();

    $stmt->bind_result($rName, $rEndereco, $rTelefone, $rImgString, $rDtAcesso, $rDescricao, $rFkIdUser);

    while ($row = $stmt->fetch()){

        $json_output[] = $row;

        echo json_encode($json_output);

    }
}

mysqli_close($conn);

?>

A: http://php.net/manual/en/mysqli-stmt.fetch.php
mysqli_stmt::fetch returns null or a boolean.  You are binding the result to variables, those are what you're supposed to use.
Otherwise you may look into get_result instead of fetch.


text:
Q: The meaning of bindings annotation with provider methods Now I'm reading Guice's official document and I saw this code.
    @Provides @PayPal
  CreditCardProcessor providePayPalCreditCardProcessor(
      @Named("PayPal API key") String apiKey) {
    PayPalCreditCardProcessor processor = new PayPalCreditCardProcessor();
    processor.setApiKey(apiKey);
    return processor;
  }

In above code, what does @PayPal mean?
In the page of the document, I understand the meaning of original binding annotations.  We can customize it.  But the usage is like this.
@Inject
  public RealBillingService(@PayPal CreditCardProcessor processor,
      TransactionLog transactionLog)

In the code, @PayPal means this parameter processor should be injected the instance indicated by the annotation.
So, what exactly does it mean in the first code?

A: In the first code, it means "when you find CreditCardProcessor annotated with @Paypal, use this method as provider".
Concretely, the first one is used to define the binding, the second one is used to request the binding.
The first one, could be rewritten as a rule in the configure() method:
protected void configure() {
  PayPalCreditCardProcessor processor = new PayPalCreditCardProcessor();
  processor.setApiKey(apiKey);
  bind(CreditCardProcessor.class).annotatedWith(PayPal.class).toInstance(processor);
}

But... you actually can't because then you'd have a singleton. Never it was written that you wanted a singleton.
So the provide methods are the nice tool to allow you making new instances and initializing them before passing them around.

A: Think of the annotation as part of the method's return type. The @Provides method you listed does not simply provide a CreditCardProcessor, it provides a @PayPal CreditCardProcessor. Thus, the method is written @Provides @PayPal CreditCardProcessor.
You can then request @PayPal CreditCardProcessor as in your second usage, by annotating a parameter in an @Inject-annotated method or constructor, or by adding the annotation to an @Inject-annotated field. (You can also request it directly from an Injector instance by creating a Key.)


text:
Q: Generate random values and print them in Google Form I am creating a google form where I have three sets of values and I want to randomly select one value from all the three sets and print them as a question.
The extension of the script is ".gs"
I tried using RANDBETWEEN(low, high) but the script throws an error. Seems like this is for google sheets.
Requesting for some help on how to create one.

A: For you random number, you'll need to use the Math library:
var nums = Math.floor(Math.random() * 4) + 1;

That should give you a random number between 1 and 5.

A: Seems like a little bit of confusion here:

*

*RANDBETWEEN(low, high) is a special Google Spreadsheet function.

*Inside a Google Script, you must use plain JavaScript (plus a few custom Google functions, like the FormApp.create() function you're using.)

In JavaScript, Math.random() is a way of getting a (pseudo) random number, but it returns a float between 0 and 1. To convert that into an integer in a range we have to use a bit of math. It might be helpful to define your own getRandomInt function, like this:
function getRandomInt(max) {
  return Math.floor(Math.random() * Math.floor(max));
}

Then later on you could call getRandomInt(5), returning 0, 1, 2, 3, or 4.


text:
Q: Validation Pattern MUMPS I am working to create a program in M that reads an input of names in a certain format. Once the user places a null value it prints out all of the values. Where I am getting stuck is reading into a global variable. I look forward to any input I can receive.
          n prompt,val,done
          s prompt="Enter a name (LAST,FIRST MI): "
          s val="" f in=1:1 s val=$O(^ZNAME(val)) q:val=""
          f  w !,prompt r val q:val=""  d   q:done
          . i val'?1.A1",".1" "1.A.1(1" "1A) w !,"Invalid name" q
          . s val=$GET(^ZNAME)
          . s done=1
          i val="" q
          w !,"You entered: ",val
         . s done=1
         q

A: Your code looks strange. In first this line s val="" f in=1:1 s val=$O(^ZNAME(val)) q:val="" is useless, just order all values in first subscript of global. Then your code should fail with UNDEFINED error for done variable when entered val will passed your pattern. And finally it gets new value from global ^ZNAME, and does not matter what was entered, it will get one value for all times.

A: I don't completely understand what you want to do but this is what I built:

*

*read names till you give an empty name

*if the name follows a pattern add him to ^ZNAME

*at the end print all names in ^ZNAME

Here you go:
readlist
    N prompt,val
    S prompt="Enter a name (LAST,FIRST MI): "
    F  W !,prompt R val Q:val=""  D
    .   I val'?1.A1",".1" "1.A.1(1" "1A) W !,"Invalid name"
    .   E  S ^ZNAME(val)=""
    F  S val=$O(^ZNAME(val)) Q:val=""  D
    .   W !,"You entered: ",val
    Q

Example (using GTM):
GTM>D readlist^ZZTEST

Enter a name (LAST,FIRST MI): first,last
Enter a name (LAST,FIRST MI): name,surname
Enter a name (LAST,FIRST MI):
You entered: first,last
You entered: name,surname
GTM>zwr ^ZNAME
^ZNAME("first,last")=""
^ZNAME("name,surname")=""


text:
Q: Nothing happen inside my Clojure loop I have a small code that doesn't want to work at all when I perform a loop like the following:
...

    (defn my-function []
        (println "Hi")   ;this works
        (for [i (range 10)] (println "Hello")  ;this doesn't work!
          )
    )

...

I can't understand what the problem is, all the code inside the loop seem to be ignored, while the "Hi" print without problems
I call 'myfunction' through a GUI button event, like this:
...
    (.append output-text (with-out-str  (time (my-function))))
...

Do you think the problem could reside in the GUI or something else I am missing? Any suggestion?
I know I should use the REPL to test it but it doesn't work with Netbeans... :S
Thanks very much for your help.

A: Another way of making this is using "dorun", if I remember corretly dorun is pretended for when you make side effects (like println).
The function should look like this:
(defn my-function[]
  (println "Hi")
  (dorun (for [i (range 10)] (println "Hello"))))

A: The for macro is lazy, so it will not invoke your function unless the return value is actually needed.
Use the doseq function instead. It will force the evaluation of your code, and thus is not lazy. It has the same "syntax" as for and allows you to account for side effecting functions such as println.


text:
Q: How to access length of inner list in pgffor I have a list of lists, and I'm using nested \foreach loops to iterate through them.  By using [count=\var], I'm able to use \var to access the length of the outer loop (after I've iterated through).  However, I am not able to use this method to access the length of the inner loops.  In my case, all the inner loops should have the same length, but technically I wanted to access the length of the last of the inner loops.  Here's what I have so far:
\documentclass{article}
\usepackage{tikz}
\begin{document}

% The first two work:

\begin{tikzpicture}
  \foreach \from [count=\to] in {2,3,1} {
    \draw (\from,1) -- (\to,2);
  }
  \draw[gray] (0.5,0.5) rectangle (\to+0.5,2.5);
\end{tikzpicture}

\begin{tikzpicture}
  \foreach \from [count=\to] in {1,3,2} {
    \draw (\from,1) -- (\to,2);
  }
  \draw[gray] (0.5,0.5) rectangle (\to+0.5,2.5);
\end{tikzpicture}

% This one does not work:

\begin{tikzpicture}
  \foreach \list [count=\row] in {{2,3,1},{1,3,2}} {
    \foreach \from [count=\to] in \list {
      \draw (\from,\row) -- (\to,\row+1);
    }
  }
  \draw[gray] (0.5,0.5) rectangle (\to+0.5,\row+1.5);
\end{tikzpicture}

\end{document}

Here's what I want to end up with:

A: This uses LaTeX counters in combination with TikZ macros.  All counter operations are global.
\documentclass{article}
\usepackage{tikz}

\newcounter{to}
\newcounter{row}

\begin{document}

\begin{tikzpicture}
  \setcounter{to}{0}
  \foreach \from in {2,3,1} {
    \stepcounter{to}
    \draw (\from,1) -- ({\theto},2);
  }
  \draw[gray] (0.5,0.5) rectangle (\theto+0.5,2.5);
\end{tikzpicture}

\begin{tikzpicture}
  \setcounter{to}{0}
  \foreach \from in {1,3,2} {
    \stepcounter{to}
    \draw (\from,1) -- (\theto,2);
  }
  \draw[gray] (0.5,0.5) rectangle (\theto+0.5,2.5);
\end{tikzpicture}

\begin{tikzpicture}
  \setcounter{row}{0}
  \foreach \list in {{2,3,1},{1,3,2}} {
    \stepcounter{row}
    \setcounter{to}{0}
    \foreach \from in \list {
      \stepcounter{to}
      \draw (\from,\therow) -- (\theto,\therow+1);
    }
  }
  \draw[gray] (0.5,0.5) rectangle (\theto+0.5,\therow+1.5);
\end{tikzpicture}

\end{document}

A: This solution has the disadvantage of needing to iterate through the list multiple times, but it avoids setting a global variable.
\documentclass{article}
\usepackage{tikz}
\begin{document}

\begin{tikzpicture}
  \foreach \list [count=\row] in {{2,3,1},{1,3,2}} {
    \foreach \from [count=\to] in \list {
      \draw (\from,\row) -- (\to,\row+1);
    }
  }
  \foreach \list [count=\count] in {{2,3,1},{1,3,2}} {
    \ifx \count \row
      \foreach \from [count=\to] in \list {
      }
      \draw[gray] (0.5,0.5) rectangle (\to+0.5,\row+1.5);
    \fi
  }
\end{tikzpicture}

\end{document}

The issue with my first version is that \to was out-of-scope when I was trying to use it.  This uses it when it's still in scope.


text:
Q: Allowed interactions for the neutral weak vector boson Just wanted to double check a couple of things for my own sanity!  I am looking at scattering amplitudes for 2 partons going to two partons with the emission of a Z boson (eventually decaying to e+ e-).  I have used madgraph to plot the possible tree level Feynman diagrams for a couple of processes and I'm a bit surprised by the output...See link below for the output diagrams.
Initially I thought that diagram 2 cause of the virtual anti-down quark (displayed as d~).  It looks like a d quark has radiated a Z boson which changed the d quark to an anti-down quark which in turn radiated a gluon which changed it back to a down quark.  I am 99% sure this is not allowed as the Z can't change q's to qbar's.
An alternative way of thinking about it is that the u quark radiates a gluon which then pair produces a d-dbar pair, one of which is final state particle but the other one goes and annihilates the incoming d quark to give a Z...But I am not certain that this is allowed either!

A: You are correct, such a process would violate charge conservation and is therefore not allowed. It should be "d" instead of "d~", i.e. the same as diagram 4 but with "u" and "d" exchanged.


text:
Q: Finding unused files in Xcode I've recently started work on a new app which is basically a copy of a previous app I made, with a few changes. To make this new app I've copied the old app and removed some stuff that isn't needed.
I'm wondering, is there any way to tell which class files are being used in Xcode? Or any tips on how to find unused files?

A: This tool finds unused imports/classes: fui.
From the README page:

Find unused Objective-C imports.

A: update at 2022.4.29
A new tool you can use https://github.com/onevcat/FengNiao

Old answer
See the useful tool. A Mac app for checking Xcode projects for unused resources [Stale link deleted]

A: There isn't any functionality like this built into Xcode, but the issue of unused classes/files etc isn't as simple as one may think.
People have created scripts to try and determine unused files. I have used the script located here, which searches through all your source files, and tries to pair up the resource files. The script also tries to check for source files not included within your project.
The reason its not so trivial is that Obj-C is a very dynamic language; a lot of things are determined at run-time. As such, it sometimes can be tricky to figure out unused files statically. For example, an image name might be determined on the fly depending on user input.
I don't know how big your application is, but you could try a dependency graph, and check for orphan classes. See this blog post on some more information.

A: The AppCode IDE from Jetbrains has some very decent code inspection functions. It can point out unused classes and other resources, and claims to be fully Xcode compatible.

A: Also see this shell scripts http://mfaizanshaikh.wordpress.com/2012/12/17/how-to-remove-unused-images-from-xcode-project/
Basically the shell script below, finds all the png files in your project that are not used in any of the xib files. Of course if you have used the png file in other ways (storyboards, load in the code), this script will still show them as unused.
for reference I paste the scripts here as well:
#!/bin/sh
PROJ=`find . -name '*.xib' -o -name '*.[mh]'`

for png in `find . -name '*.png'`
do
    name=`basename $png`
    if ! grep -q $name $PROJ; then
        echo "$png is not referenced"
    fi
done

A: I've spent much time today to find tool, which helped me a lot a few months ago. Here it is:
https://github.com/peripheryapp/periphery
It can find unused classes, functions, properties etc in Swift code.
P.S. It has more than 3000 stars on the Github. So it is strange that it's not listed here.

A: There's an app called Slender by Martiancraft that is good for suggesting potentially unused images.
http://martiancraft.com/products/slender.html
I believe that Faux Pas does something similar for class files, but I will check. That app does also look for unused methods, translations and resources.
http://fauxpasapp.com/rules/#rule-UnusedResource
I haven't used either app recently, but can remember being impressed with both previously.


text:
Q: Self hosted WCF SOAP Cors preflight How to handle Cors preflight in self hosted WCF soap service? Most examples I have seen are related to WCF Rest or IIS hosted or simple Cors.

A: I realize that your luking for an answer of .NET solution, on the other hand, this might be giving an idea of solution for you.
https://docs.oracle.com/cd/E13222_01/wls/docs103/webserv_adv/handlers.html
Here in SOAPHandler section, when it is an "OutBoundMessage", then you should add CORS headers to avoid getting security error from browser.


text:
Q: Upgrade from Dojo 1.4 to 1.8 I am working on the Migration of Dojo from 1.4 to 1.8. I have a project in which there are some jsp pages in which dojo is written and it takes the path of dojo from an xml file.
I have changed the path from dojo 1.4 Library to dojo 1.8 Library, but after doing this the referneces to the dojo widgets are throwing an error
e.g dijit.byId("idofwidget")
ERROR : dijit.byId("idofwidget") is null or not an object.
Please guide how to resolve the issue and it would be better if basics steps to upgrade can be provided.
Thanks in Advance

A: If you're really going to upgrade to Dojo 1.8, then you will have to rewrite your code into AMD, for example:
// Load the modules you need
require([ "dijit/registry", "dojo/ready", "dojo/parser" ], function(registry, ready) {

    // Wait until DOM is finished + widgets on the page are parsed
    ready(function() {

        // Retrieve widget instance
        registry.byId("idofwidget");
    });
});

One important thing to know is that you don't upgrade Dojo, you migrate it (at least when using pre- and post-1.7). This usually involves that you can not simply change the Dojo library, but you will have to migrate your code as well.
There are some articles about migrating from pre-1.7 to post-1.7, for example this article about migrating.
Sitepen also provided a tool called the Dojo AMD converter which can convert your modules into AMD syntax, it's not 100% guaranteed that it will work, but it puts you one step closer (at least). They also have an article about migrating, which you can find here.


text:
Q: Loop to find space with python c = "ab cd ef gf"
n = []
for x in c:
    if x == " ":
        d = c.find(x)
        n.append(d)
print(n)

I want this code to give me something like this. [2,5,8]
But instead it is giving me this. [2,2,2]
Please help me find the mistake. Thank you.

A: find() will find the first instance, so it always finds the space at index 2. You could keep track of the index as you go with enumerate() so you don't need find():
c = "ab cd ef gf"
n = []
for i, x in enumerate(c):
    if x == " ":
        n.append(i)
print(n)

Alternatively as a list comprehension:
[i for i, x in enumerate(c) if x == " "]

A: One way to do it would be:
space_idxs = []
for idx, char in enumerate(s):
    if char == ' ':
        space_idxs.append(idx)

A: That's because find(pattern) function returns the first entry of the pattern. Let me supplement your code with required function find_all(string, pattern)
def find_all(string, pattern):
    start = 0
    indexes = []
    for char in string:
        start = string.find(pattern, start)
        if start == -1:
            return indexes
        indexes.append(start)
        start += len(pattern)

c = "ab cd ef gf"
n = []
n = find_all(c, " ")
print(n)

A: try
c="ab cd ef gh"
x=" "
print([t for t, k in enumerate(c) if k==x])

it will return [2,5,8]
in your code you are searching for the index value of x in c, three times:

*

*in the for loop you are taking all the characters in your string one by one,

*the if loop validates if it is a space

*now when the character is a space it enters the if loop

*the find command will look for x (space) in c
which is 2
the same is repeated three times and are appended to n

if you want it in a list:
n=([t for t, k in enumerate(c) if k==x])


text:
Q: How to replace single backslash with double backslash in Javascript
I have seen a lot of duplicates but none of them works

I spend a day to get this thing up. Gone through all duplicates
I need to replace a single backslash with a double backslash.
I am able to replace all other characters with a double backslash.

console.log("hello & 100\|".replace(/([&%$#_{}])/g, "\\"));

I know that two backslashes is indeed used to make a single backslash.
I tried all the possible ways of using regex as well. But neither works.
Here is another snippet I am using.

var replaceableString = "A\B";
replaceableString = replaceableString.replace(/\\/g, "\\\\");
console.log(replaceableString);

Unfortunately, this also is not working.
Please share if there are any workarounds.

A: var str = "AAA\\BBB\\CCC\\DDD\\EEE";
var rgx = /\\/g;
var res = str.replace(rgx, "\\\\");
console.log(res);

Comments below questions are very revealing. Single backslash \ is escape character. To obtain single backslash we must use double backslashes. So we must use four backslashes(in reality double) for replace the backslash.


text:
Q: Cannot get group by to work I have two tables Employee and Office and OfficeID is a foreign key in Employee table. I need to find the number of employees in each office along with the rest of the office details like office city and employee first name. I have written the following query:
select o.OfficeID, o.City, o.State, o.Country, o.ZipCode, count(e.EmployeeID)
from Office o
inner join Employee e on o.OfficeID = e.OfficeID
group by o.OfficeID

On executing I get the following message -

Column 'Office.City' is invalid in the select list because it is not
  contained in either an aggregate function or the GROUP BY clause.

How should I correctly use group by to solve this problem?
thanks

A: You either need to include all the non-aggregated columns in the select list in the group by:
select o.OfficeID, o.City, o.State, o.Country, o.ZipCode,
       count(e.EmployeeID)
from Office o inner join
     Employee e
     on o.OfficeID = e.OfficeID
group by o.OfficeID, o.City, o.State, o.Country, o.ZipCode  ;

Or, aggregate the Employee separately.  Here is one method:
select o.*, e.cnt
from Office o inner join
     (select e.OfficeId, count(*) as cnt
      from Employee e
      group by e.OfficeId
     ) e
     on o.OfficeID = e.OfficeID;

This form is handy because you don't have the outer aggregation and can include whatever columns you like from Office in the select.
Another method uses cross apply:
select o.*, e.cnt
from Office o inner join
     (select count(*) as cnt
      from Employee e
      where o.OfficeID = e.OfficeID
     ) e;

This is a bit shorter.

A: select o.OfficeID, o.City, o.State, o.Country, o.ZipCode, e.EmployeeID, e.FirstName, e.LastName , officeCnt.cnt
from Employee e
inner join (select OfficeId, count(*) as cnt from Employee group by OfficeId) as officeCnt
        on e.OfficeID = officeCnt.OfficeID;
inner join Office o on e.OfficeID = o.OfficeID

You need to count in a subquery where you can apply group by


text:
Q: Regular Expression to replace non alpha characters with spaces I have been trying to build a regular expression but haven't been able to get one specific condition to work.
I want a regex to remove all non alpha characters with the exception of dash (-). Dashes should only be replaced if they are prefixed by a space.
I.e.
TEST-TEST -TEST#TEST.TEST

should be changed to
TEST-TEST TEST TEST TEST

I had been using [^a-zA-Z0-9] but haven't been able to include one OR condition init.

A: Here is what I came up with (\s-|[^A-Za-z0-9-])... It will remove all non alphanumerics but keep the "-" except if there is a space before it " -"
Test using sed in Linux, at the moment I don't have access to VS or Mono to test in C#
echo "TEST-TEST -TEST#TEST.TEST -1234" | sed 's/\(\s-\|[^A-Za-z0-9-]\)/ /g'

Output
TEST-TEST TEST TEST TEST 1234

*

*() and | are used for the OR condition

*We first remove all " -" using \s-

*next we keep all alphanumerics and "-" with [^A-Za-z0-9-]

A: // Skip over '-', grab non-word characters or the ' -' sequence to replace
string pattern = @"(?!-)(\W| -)+";
string replacement = "";
Regex regex = new Regex(pattern);
string result = regex .Replace("Replace - this *@#&@#* string-already", replacement);

The (?!-) is a zero-width negative lookahead assertion that will skip over the '-' symbol... the second group will match it if it's preceded by a space.
If you're trying to substitute a space instead of completely removing the characters, just change to
string replacement = " ";

the pattern is greedy, so it will replace groups of non-word characters with a single space.


text:
Q: GIT : disable eol check during comparison of local files with remote files I have a common issue with Git : I am working on Linux , and my colleagues are working on Windows.
When I do a git status, git tells me all files in my workspace have been modified (I guess because of the eol)
I would like git to show me only the files that I have really changed in my workspace.
How can I do that?
I have tried  :
git config --global core.autocrlf false

or changing .gitattributes file , but I can't get anything working.


text:
Q: "ImportError: Failed to import pydot. You must install pydot and graphviz for `pydotprint` to work." However both are installed I have installed pydotplus and graphviz (I run Windows 10 and Python 3.6).

However, when I try to plot my Keras model I am getting an exception and I am asked to install pytdot and graphviz.
keras.utils.plot_model(model, 'my_first_model.png')

---------------------------------------------------------------------------
FileNotFoundError                         Traceback (most recent call last)
C:\Program Files (x86)\Microsoft Visual Studio\Shared\Anaconda3_64\lib\site-packages\pydot.py in create(self, prog, format, encoding)
   1914                 arguments=arguments,
-> 1915                 working_dir=tmp_dir,
   1916             )

C:\Program Files (x86)\Microsoft Visual Studio\Shared\Anaconda3_64\lib\site-packages\pydot.py in call_graphviz(program, arguments, working_dir, **kwargs)
    135         stdout=subprocess.PIPE,
--> 136         **kwargs
    137     )

C:\Program Files (x86)\Microsoft Visual Studio\Shared\Anaconda3_64\lib\subprocess.py in __init__(self, args, bufsize, executable, stdin, stdout, stderr, preexec_fn, close_fds, shell, cwd, env, universal_newlines, startupinfo, creationflags, restore_signals, start_new_session, pass_fds, encoding, errors)
    708                                 errread, errwrite,
--> 709                                 restore_signals, start_new_session)
    710         except:

C:\Program Files (x86)\Microsoft Visual Studio\Shared\Anaconda3_64\lib\subprocess.py in _execute_child(self, args, executable, preexec_fn, close_fds, pass_fds, cwd, env, startupinfo, creationflags, shell, p2cread, p2cwrite, c2pread, c2pwrite, errread, errwrite, unused_restore_signals, unused_start_new_session)
    996                                          os.fspath(cwd) if cwd is not None else None,
--> 997                                          startupinfo)
    998             finally:

FileNotFoundError: [WinError 2] The system cannot find the file specified

During handling of the above exception, another exception occurred:

FileNotFoundError                         Traceback (most recent call last)
C:\Program Files (x86)\Microsoft Visual Studio\Shared\Anaconda3_64\lib\site-packages\tensorflow\python\keras\utils\vis_utils.py in _check_pydot()
     44     # to check the pydot/graphviz installation.
---> 45     pydot.Dot.create(pydot.Dot())
     46   except Exception:

C:\Program Files (x86)\Microsoft Visual Studio\Shared\Anaconda3_64\lib\site-packages\pydot.py in create(self, prog, format, encoding)
   1921                     prog=prog)
-> 1922                 raise OSError(*args)
   1923             else:

FileNotFoundError: [WinError 2] "dot" not found in path.

During handling of the above exception, another exception occurred:

ImportError                               Traceback (most recent call last)
<ipython-input-58-f0e169c88003> in <module>()
----> 1 keras.utils.plot_model(model, 'my_first_model.png')

C:\Program Files (x86)\Microsoft Visual Studio\Shared\Anaconda3_64\lib\site-packages\tensorflow\python\keras\utils\vis_utils.py in plot_model(model, to_file, show_shapes, show_layer_names, rankdir)
    151       This enables in-line display of the model plots in notebooks.
    152   """
--> 153   dot = model_to_dot(model, show_shapes, show_layer_names, rankdir)
    154   _, extension = os.path.splitext(to_file)
    155   if not extension:

C:\Program Files (x86)\Microsoft Visual Studio\Shared\Anaconda3_64\lib\site-packages\tensorflow\python\keras\utils\vis_utils.py in model_to_dot(model, show_shapes, show_layer_names, rankdir)
     70   from tensorflow.python.util import nest
     71
---> 72   _check_pydot()
     73   dot = pydot.Dot()
     74   dot.set('rankdir', rankdir)

C:\Program Files (x86)\Microsoft Visual Studio\Shared\Anaconda3_64\lib\site-packages\tensorflow\python\keras\utils\vis_utils.py in _check_pydot()
     47     # pydot raises a generic Exception here,
     48     # so no specific class can be caught.
---> 49     raise ImportError('Failed to import pydot. You must install pydot'
     50                       ' and graphviz for `pydotprint` to work.')
     51

ImportError: Failed to import pydot. You must install pydot and graphviz for `pydotprint` to work.

It is not clear why I am getting this error message. Since I have already installed the packages, what else is left to do?

graphviz has been downloaded

A: https://stackoverflow.com/a/58498731/12138096
This solved the issue. just install them by conda instead of pip.
conda install pydot
conda install graphviz

A: code: vis_utils.py
try:
  # pydot-ng is a fork of pydot that is better maintained.
  import pydot_ng as pydot
except ImportError:
  # pydotplus is an improved version of pydot
  try:
    import pydotplus as pydot
  except ImportError:
    # Fall back on pydot if necessary.
    try:
      import pydot
    except ImportError:
      pydot = None

code: pydot.py
def get_executable_extension():
    # type: () -> str
    if is_windows():
        return '.bat' if is_anacoda() else '.exe'
    else:
        return ''

If in a Anaconda env, please use
conda install pydot
conda install graphviz

If in a Python env, please use
pip install pydot

and make graphviz bin at you path.


text:
Q: How to update object attributes values in knockout.js I'm new to knockout.js so...
I've got an object:
function My_editor()
{
    this.brushSize = 10;
    this.activeColor = '#ff0000';
};
var editor = new My_editor();

It is some sort or drawing tool.
Here's the Knockout View-Model:
function AppViewModel(ed)
{
    this.brushSize = ko.observable(ed.brushSize);
    this.activeColor = ko.observable(ed.activeColor);
}
ko.applyBindings(new AppViewModel(editor));

I've written some html interface and it works OK.
The problem is that if I change the brushSize value via Knockout it doesn't change the corresponding attribute of the editor object. I'm using Google Chrome developer tools to inspect my object's state.
Piece of html:

Brush Size: <input type="number" data-bind="value: brushSize" />

Active Color: <input type="color" data-bind="value: activeColor" />

Also, if I change brushSize in console, it doesn't update in the interface & knockout.
I'm using:
editor.brushSize = 15;

A: Your values are being copied, a reference to the original editor object isn't being stored.
You are using value types when using strings and int.  Since you pass the editor object it and access the values from it directly, your vm and knockout are copying the values, not a reference to the editor object.
I would say you should use the vm to do all your work and if you want to access data, pull it from the vm.  If you needed to save the data, then I would pull the data from the vm into another object and pass it to the server.
If you provide a little more detail on what you are trying to accomplish, I would be able to better provide an example.

A: Use parentheses:
editor.brushSize(15);

A: Ideally, when using knockout, it's best if you use "observables all the way down"; i.e. if all your objects you want to see live-updates for use observables for properties.
function My_editor()
{
    this.brushSize = ko.observable(10);
    this.activeColor = ko.observable('#ff0000');
};
var editor = new My_editor();

Then in your AppViewModel:
function AppViewModel(ed)
{
//Either this:
    this.brushSize = ed.brushSize; //The editor's observables are shared between both ViewModels
    this.activeColor = ed.activeColor;

//OR  (my preference)
    this.editor = ed;
}
ko.applyBindings(new AppViewModel(editor));

Personally, I prefer the second approach so you can freely add properties to the editor ViewModel without needing to add more code to the AppViewModel.
If you can't, or don't want to make the My_Editor viewModel's properties observables, you might have to find a way to manually trigger updates when the VM changes, (i.e. when you set editor.brushSize = 15, you'd call a line of code that causes the AppViewModel's observables to update) but that's pretty hacky and isn't really utilizing KO properly, so I'd really suggest make the My_editor observable.

A: So, accidentally, I've found the simplest solution: Extenders (http://knockoutjs.com/documentation/extenders.html).
I need to add something like that before AppViewModel:
ko.extenders.updateEditor = function(target, option)
{
  target.subscribe(function(newValue)
  {
    //console.log(option,newValue);
    editor[option] = newValue;
  });
  return target;
};

... and modify the AppViewModel like that:
this.brushSize = ko.observable(ed.brushSize).extend({ updateEditor: 'brushSize' });
this.activeColor = ko.observable(ed.activeColor).extend({ updateEditor: 'activeColor' });

Voila! The 'editor' object attributes are correctly updated now!
Thanks everyone for participating.


text:
Q: Adding secondary axis in the many graphs I am trying to add a secondary axis to the following codes for graphs. I want to add a secondary axes with another metric
plt.style.use('dark_background')
fig, (ax1,ax2,ax3,ax4) = plt.subplots(nrows=4, ncols=1,figsize=(18,12))

funnel.plot(x='date_event_nk', y='Show_Complete', label='Traditional',
ax=ax1)
ax1.set_title("TRADITIONAL FUNNEL AND YOLO CONVERSION PWA")
ax1.xaxis.set_label_coords(1.05, -0.025)

funnel_yolo.plot(x='date_event_nk', y='Show_Complete', label='Yolo', ax=ax2)
ax2.set_title("TRADITIONAL FUNNEL AND YOLO CONVERSION PWA")
ax2.xaxis.set_label_coords(1.05, -0.025)

funnel_smartlock.plot(x='date_event_nk', y='SMRequest_Complete',
label='Smartlock Auto', ax=ax3)
ax3.set_title('SMARTLOCK AUTO CONVERSION PWA')
ax3.set_ylim((0, 0.005))
ax3.xaxis.set_label_coords(1.05, -0.025)

funnel_smartlock_s.plot(x='date_event_nk', y='SMRequest_Complete',
label='Smartlock Select', ax=ax4)
ax4.set_title('SMARTLOCK SELECT CONVERSION PWA')
ax4.set_ylim((0, 0.1))
ax4.xaxis.set_label_coords(1.05, -0.025)

My graphs are:

So as to add a new secondary axes in all the graphs i am trying the following
(i just create in the first graph for simplicity, my problem is illustrate in my first graph)
plt.style.use('dark_background')
fig, (ax1,ax2,ax3,ax4) = plt.subplots(nrows=4, ncols=1,figsize=(18,12))

funnel.plot(x='date_event_nk', y='Show_Complete', label='Traditional',
ax=ax1)
ax1.set_title("TRADITIONAL FUNNEL AND YOLO CONVERSION PWA")
ax1.xaxis.set_label_coords(1.05, -0.025)
ax5 = ax1.twinx()
ax5.plot(kind='bar',x='date_event_nk',y='One_tap_login',ax=ax5)

funnel_yolo.plot(x='date_event_nk', y='Show_Complete', label='Yolo', ax=ax2)
ax2.set_title("TRADITIONAL FUNNEL AND YOLO CONVERSION PWA")
ax2.xaxis.set_label_coords(1.05, -0.025)

funnel_smartlock.plot(x='date_event_nk', y='SMRequest_Complete',
label='Smartlock Auto', ax=ax3)
ax3.set_title('SMARTLOCK AUTO CONVERSION PWA')
ax3.set_ylim((0, 0.005))
ax3.xaxis.set_label_coords(1.05, -0.025)

funnel_smartlock_s.plot(x='date_event_nk', y='SMRequest_Complete',
label='Smartlock Select', ax=ax4)
ax4.set_title('SMARTLOCK SELECT CONVERSION PWA')
ax4.set_ylim((0, 0.1))
ax4.xaxis.set_label_coords(1.05, -0.025)

but is not working correctly


text:
Q: Decide if $\{f_n(x) : n\in\mathbb{N}\}$ converges to $f$ uniformly or not. Can someone please help me with the problem below? I am not confident in my solution. I am working off Munkrees' Topology book and problems in the book.
For each $n\in\mathbb{N}$, let $f_n: [0,1] \to [0,1]$ be defined by $f_n(x) = 0, x > \frac{1}{n}$ and $f_n(x) = 1-nx$ if $0\le x\le\frac{1}{n}$. The collection $\{f_n(x) : n\in\mathbb{N}\}$ converges to a point, call it $f(x)$ for each $x\in [0,1].$ Decide if $\{f_n(x) : n\in\mathbb{N}\}$ converges to $f$ uniformly or not.
$\textbf{Solution:}$ Observe, $f_n(0) = 1$ for all $n$. For $0< x \le 1$ by Archimedean property of real numbers, there exist $N$, a fixed natural number, such that $\frac{1}{N} < x$. So for all $n\ge N, \frac{1}{n} \le \frac{1}{N}.$ Hence, for all $n\ge N, \frac{1}{n} < x$, and $f_n(x)=0$, by definition. We observe this because for $0 < x \le 1$, after finitely many non-zero $f_n(x)$ all other $f_n(x)=0$. So, $f(0)=1$ and $f(x)=0, 0 < x\le 1$ as $x=0$, it is the constant sequence $1$ and for $0<x\le 1$, after finitely many non-zero terms, the sequence is eventually constant sequence $0$.
We will show $f_n(x)$ does not converge to $f(x)$ uniformly.
Take the $\sup|f_n(x)-f(x)| = 1$ where the supremum runs over $0\le x \le 1$. Since, $1$ does not tend to zero. Hence, we are done.
Furthermore, there is a theorem that if the sequences of continuous functions converge uniformly then the limit of the function is continuous. Here, $f_n(x)$ are continuous throughout and $f(x)$ is not continuous at $x=0$. So, they cannot converge uniformly.

A: The pointwise limit, as you correctly showed: for each $x \in [0,1]$ $\lim_n f_n(x) =f(x)$ where $$f(x)=\begin{cases} 1 & x=0\\0 & 0<x \le 1\end{cases}$$
Now, if Munkres treated the theorem that a uniform limit of continuous functions is continuous, we can already conclude that $(f_n)_n$ does not converge uniformly: the pointwise limit is the only candidate for a uniform limit. But this can be shown directly by computing $\sup_x |f_n(x)-f(x)| = 1 $ as you did. But that fact does need justification! Don't just claim it..
Another way is to apply another theorem and compute $f_n(\frac{1}{2n})= 1-n\frac{1}{2n} = \frac12 \not\to 1=f(0)$ (based on the theorem:

$f_n \to f$ uniformly and $x_n \to x$ in the domain, then $f_n(x_n) \to f(x)$

which you might or might not know (the proof is not hard from the definitions, applying the triangle inequality).


text:
Q: How can I bind events to the Squarespace AjaxLoader? I'm working on a Squarespace site at the moment, trying to figure out how I can bind a function to their AjaxLoader without much success.
Here is a demo site that uses this loader
In my console I can see all the XHR requests being triggered when switching between pages, and I've tried using the debug to capture event listeners.
I thought something bound to "readystatechange" would work, but it only triggers on the initial page load.
$(window).on("readystatechange", doStuff);

A: I found a pretty nice solution using mutationObservers on the Squarespace Answers forum – thank you @octopus!
Copy and pasted from here
Hope this helps anyone else struggling.
 window.onload = function(){
   react();
   watch(react);
 };
 function react() {
   var id = document.body.getAttribute('id'),
       target = 'collection-5787c6b0cd0f6801e859286a';
   console.log(id);
   if (id === target) {
     // execute your code for this page
   }
 }
 function watch(callback) {
   MutationObserver = window.MutationObserver || window.WebKitMutationObserver;
   var observer = new MutationObserver(function(mutations) {
     for (var index = 0; index < mutations.length; index++) {
       var mutation = mutations[index];
       if (mutation.type === 'attributes') {
         callback();
       }
     }
   });
   observer.observe(document.body, {
     attributes: true,
     attributeFilter: ['id']
   });
 }

A: The ajaxLoader.js is using the modular pattern and has encapsulated the httpRequest. I don't believe you can bind to it.
  (function(window, document){
    'use strict';

     var DEBUG = true;
     var httpRequest; // THE HTTP REQUEST USED FOR THE AJAX
     var ajaxFired = false;
     var currentEvent;
     var currentTarget;
     var indexNextAnim = true;
     ...

The httpRequest is set and used in the ajax function:
ajax: function (url) {

  httpRequest = new XMLHttpRequest();
  httpRequest.open('GET', url);
  httpRequest.timeout = this.TIMEOUT;
  httpRequest.onreadystatechange = this.handleRequest.bind(this, url);
  httpRequest.ontimeout = this.handleTimeout.bind(this, url);
  httpRequest.send(null);
},

A: This is very easy to solve. Simply modify the AjaxLoader prototype to add an additional custom init function right along side of where Squarespace runs their own block init.
This assumes you've bound some sort of custom object that holds your init function(s). Sometimes to better to use some sort of custom event emitter for this, but that would be some additional dev. This seems much easier.
 window.onload = function() {
   this.AjaxLoader.prototype.initializeSqsBlocks = function () {
     window.SQS.Lifecycle.init();

     console.log( "Foo!" );
     window.CUSTOM.YourCustomInitFunction();
   }
 };

The end result is that when the ajaxloader fires, it will trigger the initializeSqsBlocks init as usual, which you've now hijacked to add your own additional init function. It's kind of a makeshift way of attaching an emitter to the ajaxloader without modifying it too much.


text:
Q: Change width proportions of two blocks with a slider I'm trying to design a component in which you could change the width proportions of two blocks by moving a slider left and right:

codpen and demo:

.outer {
  display: flex;
  flex-direction: row;
}

.block {
  height: 200px;
  width: -webkit-calc(50% - 5px);
  width: -moz-calc(50% - 5px);
  width: calc(50% - 5px);
}

.block-1 {
  background-color: red;
}

.block-2 {
  background-color: green;
}

.slider {
  line-height: 100%;
  width: 10px;
  background-color: #dee2e6;
  border: none;
  cursor: e-resize;
}

      Block 1

      S
l
i
d
e
r

      Block 2

I have tried using draggable-vue-directive and change the width of blocks based on slider position.
However, it didn't work really well, since draggable-vue-directive set the slider to position:fixed which in turn messed up the block alignment.
How can I make the .slider block horizontally draggable without setting position:fixed?
How to correctly resize Block1 and Block2 when slider moves?
Note: I'm not using jQuery

A: You can adjust your flexbox along with resize - the downside is that the slider its not very customizeable:

*

*add resize: horizontal to one of the flex items

*add flex: 1 to the other flex item (so that this flex item will adjust automatically in response to the changing width of the other flex item as it is resized)

See demo below:

.outer {
  display: flex;
  flex-direction: row;
}

.block {
  height: 100px;
  width: 50%; /* 50% would suffice*/
}

.block-1 {
  background-color: red;
  resize: horizontal; /* resize horizontal */
  overflow: hidden; /* resize works for overflow other than visible */
}

.block-2 {
  background-color: green;
  flex: 1; /* adjust automatically */
}

      Block 1

      Block 2

So we'll use vanilla JS instead of the resize solution above:

*

*use a mousedown listener that registers a mousemove listener that updates the block-1 width (and reset the mouseup event)

*also consider min-width: 0 to override min-width: auto of the block-2 element

See demo below:

let block = document.querySelector(".block-1"),
  slider = document.querySelector(".slider");

slider.onmousedown = function dragMouseDown(e) {
  let dragX = e.clientX;
  document.onmousemove = function onMouseMove(e) {
    block.style.width = block.offsetWidth + e.clientX - dragX + "px";
    dragX = e.clientX;
  }
  // remove mouse-move listener on mouse-up
  document.onmouseup = () => document.onmousemove = document.onmouseup = null;
}
.outer {
  display: flex;
  flex-direction: row;
}

.block {
  height: 100px;
  width: 50%; /* 50% would suffice*/
}

.block-1 {
  background-color: red;
}

.block-2 {
  background-color: green;
  flex: 1; /* adjust automatically */
  min-width: 0; /* allow flexing beyond auto width */
  overflow: hidden; /* hide overflow on small width */
}

.slider {
  line-height: 100%;
  width: 10px;
  background-color: #dee2e6;
  border: none;
  cursor: col-resize;
  user-select: none; /* disable selection */
  text-align: center;
}

      Block 1

      S
l
i
d
e
r

      Block 2

Solution
You can adapt the above into Vue easily without using any custom Vue plugins for this - the changes are:

*

*@mousedown listener on slider that triggers the slider

*use of refs to update the width of block-1
See demo below:

new Vue({
  el: '#app',
  data: {
    block1W: '50%'
  },
  methods: {
    drag: function(e) {
      let dragX = e.clientX;
      let block = this.$refs.block1;
      document.onmousemove = function onMouseMove(e) {
        block.style.width = block.offsetWidth + e.clientX - dragX + "px";
        dragX = e.clientX;
      }
      // remove mouse-move listener on mouse-up
      document.onmouseup = () => document.onmousemove = document.onmouseup = null;
    }
  }
});
.outer {
  display: flex;
  flex-direction: row;
}

.block {
  height: 100px;
  width: 50%; /* 50% would suffice*/
}

.block-1 {
  background-color: red;
}

.block-2 {
  background-color: green;
  flex: 1; /* adjust automatically */
  min-width: 0; /* allow flexing beyond auto width */
  overflow: hidden; /* hide overflow on small width */
}

.slider {
  line-height: 100%;
  width: 10px;
  background-color: #dee2e6;
  border: none;
  cursor: col-resize;
  user-select: none; /* disable selection */
  text-align: center;
}

      Block 1

      S
l
i
d
e
r

      Block 2


text:
Q: TS - Local path of image I would like to store the local path of an uploaded image in a variable. I created a FileReader in order to get information on the file. Here is my code:
var reader = new FileReader();
reader.readAsDataURL(event.target.files[0]); // read file as data url
console.log(event.target.files[0]);

This is an example output:
lastModified: 1536526410000
lastModifiedDate: Sun Sep 09 2018 16:53:30 GMT-0400 (GMT-04:00) {}
name: "slider-2.jpg"
size: 627442
type: "image/jpeg"
webkitRelativePath: ""
__proto__: File

I would like to get the local path of the computer, since this is angular, when I tried window.location.pathname but it just returns the path from localhost being localhost:4200/register
How can I get my full path?


text:
Q: Can't find URI from DB2 Service Credentials Hi I'm having this problem when I try to do the following steps.
# Remember the connection string is of the format:
# %sql ibm_db_sa://my-username:my-password@hostname:port/BLUDB?security=SSL
# Enter the connection string for your Db2 on Cloud database instance below
# i.e. copy after db2:// from the URI string in Service Credentials of your Db2 instance. Remove the double quotes at the end.

Only place where I see db2:// is below
"db2://jgd26xxx:ji0BxxxpoZj4zDMA@125fxxx1-xxxx-46f9-9399-c8177b21803b.c1ogj3sd0tgtu0lqde00.databases.appdomain.cloud:30426/bludb?authSource=admin&replicaSet=replset"
So when I enter that after %sql ibm_db_sa:// as follows nothing happens. I feel that this is not the correct connection string.
%sql ibm_db_sa://jgd26xxx:ji0BxxxxZj4xxxA@125xxx61-xxxx-46f9-9399-c8177b21803b.c1ogj3sd0tgtu0lqde00.databases.appdomain.cloud:30426/bludb?authSource=admin&replicaSet=replset
How do I enter the connection string?

A: If you are using db2 hosted on ibm cloud, then you can go to your dashboard at cloud.ibm.com, select the tab under Resource summary on the main page that says Services and software. Once you do that, select your db2 instance. Once it brings you to the next page, select service credentials from the left nav bar. If you dont have a service cred, create one. If you do, select it, and you'll have to do a bit of string building. Find the username by searching for username (using command f or what have you), and do the same for the password. Do the same for hostname,port, and you should be good to go.

A: URI is not a specific line that you can copy/paste from service credentials.
You have to copy them individually (name/password/...) from service credentials with format as  per line 2 of your question.
I have pasted my format in a text file  so that don't have to do it again and again from service credentials.

A: you will have your credentials. from there you can copy and paste each data .
username in place of my-username,
password in place of my-password,
hostname in place of hostname,
port in place of port,
in given format
%sql ibm_db_sa://my-username:my-password@hostname:port/ BLUDB?security=SSL

A: What i did is from service credential of db2 of the ibm console, save the whole credential into the text doc. then i drag it just after db2// of the long characteristics which contain the username password and stuff like that n put it on the new cell of the note book just below the required cell and finally merge the two cells together and removed the double quote at the end. this work for me.


text:
Q: Unable to create logger Tomcat Error I have jdk 1.7
path,classpath,catalina_home are set
this was the error
E:\apache-tomcat-7.0.56\bin>tomcat7.exe
The system cannot find the path specified.
Unable to create logger at ''
[2014-11-23 23:03:48] [error] [ 7388] Failed creating java C:\Program Files\Java
\jre7\bin\server\jvm.dll
[2014-11-23 23:03:48] [error] [ 7388] The system cannot find the path specified.

[2014-11-23 23:03:48] [error] [ 7388] ServiceStart returned 1
[2014-11-23 23:03:48] [error] [ 7388] The system cannot find the path specified.

[2014-11-23 23:03:48] [error] [ 7388] Commons Daemon procrun failed with exit va
lue: 3 (Failed to run service as console application)
[2014-11-23 23:03:48] [error] [ 7388] The system cannot find the path specified.

The system cannot find the path specified.
Failed to run service as console application
E:\apache-tomcat-7.0.56\bin>

A: I had the same problem.  Here is what I was able to figure out:
This error happens because you don't have the privilege to modify the E:\apache-tomcat-7.0.56\logs directory.  In my case, it was because I installed Tomcat by doing starting a CMD shell in "Run as administrator" mode (which forces you to log in as an administrator), and then doing "unzip apache-tomcat-7.0.57-windows-x64.zip".  This seems to not set up the permissions necessary for the files to be accessed correctly by the service installer even when running in the "Run as administrator" privilege.
Now, if I go to my normal user account CMD shell and unzip the .zip file, and then go back to the administrator CMD shell and run service install , it works.
In fact, if I make a copy of the apache-tomcat-7.0.57 directory using COPY /S/D, and then try to install from that directory, it also works when you do a service install as an administrator.
Hope this helps.


text:
Q: Error while installing .NET framework 3.5 The .NET Framework 3.5 installation fails for me. Right after the
"Downloading components" stage, it sits for a few seconds on:

Setup has finished downloading components, you can now disconnect from the
  Internet

Then it starts to roll back. I'm using Windows XP SP2. A glance
in the log files shows that it seems related to MSI error code 1603.

A: Make sure you have the latest Windows Installer - here is a link to the 4.5 download.

A: You should be able to find a more detailed error in one of the locations mentioned in blog post Where to find .NET Framework 2.0 SP1, 2.0 SP2, 3.0 SP1, 3.0 SP2, 3.5 and 3.5 SP1 setup log files.

A: You should rename c:\windows\system32\spupdsvc.exe to something else and retry the .NET Framework 3.5 installation.
If you using a batch file you can use:
"REN c:\windows\system32\spupdsvc.exe spupdsvc2.exe"


text:
Q: How to access (copy) specific elements of Mat in OpenCV? Let's say I have a matrix of single row x. In MATLAB, I can access specific elements of x via
x=[10 6 9 12 15 20 22];
index=[1 3 7];
y=x(index)
y =
    10     9    22

How can I do the same in OpenCV (without for loop)?
I know there are ways to access rows or columns of the matrix, but I couldn't find a way to access only specific elements in OpenCV.
Edit:
I am using C++. What if x is NxM matrix and I want to access some elements in the 5th column. In MATLAB, I can do it as x(index,5). I can sure do it with for loops in OpenCV. My question is, is there any ready OpenCV function that returns me the specific elements of x?

A: As mentioned in the comments you will have to use a loop. Unlike Matlab you can't access all the elements at once. Assuming you have a single row matrix with one channel as you indicated, the following code will work (depending on the datatype you use):
int foo[TheNumberOfColumnsYouNeed];
for(int i = 0; i < matrix.cols; i++)
{
    if(i == TheColumnsYouNeed)
        foo[i] = matrix.at<double>(0, i);
}

If you specifically want the 5th column of a single row matrix, you can do the following without a loop (assuming datatype double):
foo = matrix.at<double>(0, 5);

A: You can retrieve a cv::Mat containing the values by index by using the same mechanism as cv::sortIdx  see Sorting cv::Mat in OpenCv
ie if you have a cv::Mat containing the indices you can pass this to the cv::Mat containing the data and get back that subset.


text:
Q: Soviet Maps projection What was the projection used for the Soviet Topographic Maps? http://maps.vlasenko.net/smtm50/k-37-072-1.jpg i am trying to georeference a map from Georgia. I believe the projection used was GK (3 degrees) with a Pulkovo datum (epsg 2530 in the case of the map above of the Georgian city of Poti)

A: For such a small area as that the projection probably won't matter, the earth is essentially flat at that scale. Just define a few reference points in whatever output coordinate system you want to use (Some UTM Zone, maybe) and that should be fine. I doubt any precision error will be down to not specifying a projection, it'll probably be swamped by the referencing, cartography, surveying, and scanning precision errors.
Different story if you are trying to georeference a map of the whole of the  Soviet Union though.


text:
Q: How to generate a video by looping an image and then concat with another very long video without re-encoding using ffmpeg? I have an image and a very long video (1.5h).
Now I want to generate a heading video about 5 seconds by looping the image, and then concatenate it with the long video. Since the video is long, I don't want to re-encode the videos.
I have tried to generate the heading video using
ffmpeg -loop 1 -i image.png -c:v libx264 -t 5 -pix_fmt yuv420p head.mp4

and then
ffmpeg -f concat -i list.txt -c:v copy concat.mp4

where the list.txt contains
file head.mp4
file longvideo.mp4

I have tried these operations on two machines.
On one machine, the concatenated video has no audio. Moreover, it stucks at 5-10 seconds and directly jump to 11s.
On the other machine, the video and audio are not synchronized.
To provide more information, I have checked the codecs of the two videos by
ffprobe -v error -select_streams v:0 -show_entries stream=codec_name \
  -of default=noprint_wrappers=1:nokey=1 xxxxx.mp4

Both of them are h264.
My question is, how to generate it correctly with ffmpeg? If it is hard using ffmpeg, is there any method to do it fast? As far as I know, Adobe Premiere and Final Cut Pro do not export as fast as I expect because they re-encode the videos.

A: Use:
ffmpeg -framerate 60 -loop 1 -t 5 -i image.png -f lavfi -i anullsrc=cl=stereo:r=48000 -vf "scale=1920x1080,setsar=1,format=yuv420p" -c:v libx264 -c:a aac -video_track_timescale 16k -shortest head.mp4

This will match longvideo.mp4 attributes required for proper concatenation.


text:
Q: How to move file or directories in linux HELP. I need help with moving directories and files in Linux because i don't understand how to it and how it works, i am a student in year 11 so if someone could explain in the most simplest way possible or in a step by step guide would be helpful Thanks.

A: It's mv
mv directoryName newLocation/directoryName
More info here http://linoxide.com/linux-command/mv-command-linux/


text:
Q: Biblatex: how to remove 'In:' (Teoksessa:') from bibliography (for languages other than English)? Is there a way to remove In: and its equivalents from all the entries in the bibliography, no matter the language of the entry? I tried \renewbibmacro*{in:}{}, but that doesn't have an effect on the Finnish entry (Teoksessa: remains):
Täht, Põhja 2020. Taevas. Teoksessa: - Linnunrata. Toim. Kosmo Naut.
(what I want instead is: Täht, Põhja 2020. Taevas. - Linnunrata. Toim. Kosmo Naut.)
Here the MWE:
\documentclass[12pt]{report}
\usepackage{filecontents}
\begin{filecontents*}{\jobname.bib}

@inbook{Taht2020,
langid = {finnish},
title = {Taevas},
booktitle = {Linnunrata},
author = {Põhja Täht},
editor = {Kosmo Naut},
year = {2020},
}

@inbook{Taht2019,
langid = {english},
title = {Taevas},
booktitle = {Linnunrata},
author = {Põhja Täht},
editor = {Kosmo Naut},
year = {2019},
}

\end{filecontents*}

\usepackage[utf8]{inputenc}
\usepackage[T2A, T1]{fontenc}

\usepackage[finnish, english, estonian]{babel}

\usepackage[bibencoding=auto, backend=biber, autolang = other, style=authoryear, sorting=debug, dashed=false, citestyle=authoryear-comp, maxcitenames=2]{biblatex}
\usepackage[babel]{csquotes}

\usepackage{xpatch, filecontents}
\xpatchbibmacro{date+extradate}{%
  \printtext[parens]%
}{%
  \setunit*{\space}%
  \printtext%
}{}{}

\renewbibmacro*{begentry}{%
    \ifnameundef{shortauthor}
        {}
        {\textbf{\printnames{shortauthor}%
         \addspace{=}\space}}}
\renewbibmacro*{in:}{}
\bibliography{\jobname}

\DeclareFieldFormat*{title}{#1}

\xpretobibmacro{author}{\mkbibbold\bgroup}{}{}
\xapptobibmacro{author}{\egroup}{}{}
\xpretobibmacro{bbx:editor}{\mkbibbold\bgroup}{}{}
\xapptobibmacro{bbx:editor}{\egroup}{}{}

\DeclareFieldFormat[inbook]{title}{#1\addperiod{\space}}{}
\DeclareFieldFormat[inbook]{booktitle}{--{\space}#1\addperiod}

\begin{document}

Citing different works \parencite{Taht2019, Taht2020}

\printbibliography

\end{document}

A: Both the Estonian and Finnish language module of biblatex redefine the bibmacro in: in the bibliography language extras. If you want to redefine this macro yourself, you need to do that in \DefineBibliographyExtras{<language>}.
I suggest you redefine in: in such a way that you no longer need to include punctuation commands in the field formats for title and booktitle.
\documentclass[12pt]{article}
\usepackage[utf8]{inputenc}
\usepackage[T2A, T1]{fontenc}
\usepackage[finnish, english, estonian]{babel}
\usepackage[autostyle]{csquotes}
\usepackage[backend=biber,
  style=authoryear-comp,
  maxcitenames=2,
  dashed=false,
  autolang=other
]{biblatex}

\usepackage{xpatch}
\xpatchbibmacro{date+extradate}{%
  \printtext[parens]%
}{%
  \setunit*{\space}%
  \printtext%
}{}{}

\renewbibmacro*{begentry}{%
  \ifnameundef{shortauthor}
    {}
    {\textbf{\printnames{shortauthor}%
     \addspace{=}\space}}}

\DefineBibliographyExtras{estonian}{%
  \renewbibmacro*{in:}{\printunit{\addperiod\addspace--\space}}}
\DefineBibliographyExtras{finnish}{%
  \renewbibmacro*{in:}{\printunit{\addperiod\addspace--\space}}}

\DeclareFieldFormat*{title}{#1}

\xpretobibmacro{author}{\mkbibbold\bgroup}{}{}
\xapptobibmacro{author}{\egroup}{}{}
\xpretobibmacro{bbx:editor}{\mkbibbold\bgroup}{}{}
\xapptobibmacro{bbx:editor}{\egroup}{}{}

\begin{filecontents*}{\jobname.bib}
@inbook{Taht2020,
  langid    = {finnish},
  title     = {Taevas},
  booktitle = {Linnunrata},
  author    = {Põhja Täht},
  editor    = {Kosmo Naut},
  year      = {2020},
}
@inbook{Taht2019,
  langid    = {english},
  title     = {Taevas},
  booktitle = {Linnunrata},
  author    = {Põhja Täht},
  editor    = {Kosmo Naut},
  year      = {2019},
}
\end{filecontents*}
\addbibresource{\jobname.bib}

\begin{document}
Citing different works \autocite{Taht2019, Taht2020}
\printbibliography
\end{document}

A: EDIT: Please see moewe's comment below on why not to do this.
Putting the following in your preamble should work:
\DefineBibliographyStrings{finnish}{
  in = {}
}


text:
Q: How to link libraries in Visual Studio Code I have a school project (a mp3 music player) using C and FMOD.
I have a Mac M1 and try to use Visual Studio Code (im bad with C).
I type these lines
#include <stdlib.h>
#include <stdio.h>
#include <string.h>
#include"api/core/inc/fmod.h"

int main(void){
    printf("hello");
    FMOD_SYSTEM* pSystem;
    FMOD_System_Create (&pSystem, 0);
}

And I have this error :
Undefined symbols for architecture arm64:
  "_FMOD_System_Create", referenced from:
      _main in main-b18886.o
ld: symbol(s) not found for architecture arm64
clang: error: linker command failed with exit code 1 (use -v to see invocation)

But I think Visual Studio Code can't link libraries with fmod.h, I tried the External Libraries add-on for VSC but it's not working, do you have any idea how to figures this out ?


text:
Q: Image inside flex parent with max-height and max-width and object-fit contain Image stretches if I don't use object-fit contains. Stretches in width, losing aspect ratio.
object-fit contain fixes that.
The problem is, the element itself is not contained, just the visible image. Which means if I make the image clickable, the whole element area (even outside the image) is clickable.
https://jsfiddle.net/nyysyngp/10/ (or see code below)
I just want the visible image to be clickable. This seems to work on Firefox, but not Chrome.

body, html
{
  margin: 0;
  padding: 0;
  background-color: red;
  display: flex;
  height: 100%;
  width: 100%;
}

#media
{
    display: flex;
    background-color: #262423;
    justify-content: center;
    align-items: center;
    flex-direction: column;
    flex-grow: 1;
}

#media_split
{
    display: flex;
    flex-direction: column;
    width: 100%;
    height: 100%;
    align-items: center;
}

#media_image_container
{
    height: 50%;
    width: 100%;
    flex-grow: 1;
    flex-shrink: 0;
    display: flex;
    align-items: center;
    justify-content: center;
    background-color: green;
}

#media_image
{
    object-fit: contain;
    max-height: calc(100% - 4em);
    max-width: calc(100% - 4.7em);
    min-height: 100px;
    min-width: 100px;
    cursor: pointer;
}

#media_tv
{
    height: 50%;
    width: 100%;
    flex-grow: 1;
    flex-shrink: 0;
    display: flex;
    align-items: center;
    justify-content: center;
    background-color:blue;
}

A: Well some months later I found a solution. Just by adding "position: absolute" to #media_image the problem went away, which in my case didn't break anything else.

A: In #media_image_container remove display: flex; and add text-align: center;
It will fix the issue.


text:
Q: Error using Max and Min based on Avg to determine lowest average cost and highest average cost (MySQL) I have determined the average subject cost as per the following:
FROM BOOK
JOIN
(SELECT BOOK_SUBJECT,
Avg(BOOK_COST) AS AVGCOST
FROM BOOK
GROUP BY BOOK_SUBJECT) AS SUB USING (BOOK_SUBJECT)
ORDER BY BOOK_TITLE;

However, I now need to display the lowest average cost of books within a subject and the highest average cost of books within a subject.  I know I need to use MIN and MAX but not sure of the syntax now that I have to base it on the AVG.
Here's my attempt......
SELECT BOOK_SUBJECT
FROM BOOK
WHERE BOOK_COST =
(SELECT MIN(AVGCOST)
FROM BOOK)
ORDER BY BOOK_SUBJECT;

SELECT BOOK_SUBJECT
FROM BOOK
WHERE BOOK_COST =
(SELECT MAX(AVGCOST)
FROM BOOK)
ORDER BY BOOK_SUBJECT;

This creates a SQL error: unknown column "AVGCOST" in field list.  How do I get around this? I understand that its looking for an attribute and can't find it, so what needs to be added to the code so that MySQL will calculate the min and max of the avg?  Many thanks to those who respond, your feedback has been fabulous.

A: I think that what you are trying to achieve is
SELECT *
FROM BOOK
JOIN
(
   SELECT BOOK_SUBJECT,
   AVG(BOOK_COST) AS AVGCOST,
   MIN(BOOK_COST) AS MINCOST,
   MAX(BOOK_COST) AS MAXCOST
   FROM BOOK
   GROUP BY BOOK_SUBJECT
) AS SUB USING (BOOK_SUBJECT)
ORDER BY BOOK_TITLE;

Based on
BOOK_SUBJECT BOOK_TITLE BOOK_COST
------------ ---------- ---------------------
MATHS        Book 1     15.99
MATHS        Book 2     14.99
MATHS        Book 3     13.99
ENGLISH      Book A     10.99
ENGLISH      Book B     9.99

Returns
BOOK_SUBJECT BOOK_TITLE BOOK_COST AVGCOST MINCOST MAXCOST
------------ ---------- --------- ------- ------- -------
MATHS        Book 1     15.99     14.99   13.99   15.99
MATHS        Book 2     14.99     14.99   13.99   15.99
MATHS        Book 3     13.99     14.99   13.99   15.99
ENGLISH      Book A     10.99     10.49   9.99    10.99
ENGLISH      Book B     9.99      10.49   9.99    10.99

To pull just the MIN/MAX average costs (rounded to 2 decimal)
SELECT
  ROUND(MIN(MM.AVGCOST), 2) AS MINAVG,
  ROUND(MAX(MM.AVGCOST), 2) AS MAXAVG
FROM
(
   SELECT BOOK_SUBJECT,
   AVG(BOOK_COST) AS AVGCOST
   FROM BOOK
   GROUP BY BOOK_SUBJECT
) MM

Will return
MINAVG    MAXAVG
------    ------
10.49     14.99


text:
Q: How to connect frontend to json data on heroku I'm trying to deploy my first React app on Heroku. I used simple json files for the backend.
Locally, everything runs good: my server is on localhost:8080, and frontend axios calls gets data from it like so:
axios.get(localhost:8080/bench).then( (response) => {
    // my logic here
})

My deployment flow is:

*

*to run a npm build and put everything in the build folder into the server end's public folder. Here's the entry-point file:

    const path = require("path");
    const publicPath = path.join(__dirname, "public");
    console.log(publicPath);
    app.use(express.static(publicPath));
    app.get("*", (req, res) => {
      res.sendFile(path.join(publicPath, "index.html"));
    });

*

*push to build artifacts to Heroku

Doing so,  everything from the frontend part runs good on Heroku.
My concern is that I can't figure out what axios calls  I should use for the frontend to get the data from the server. Is there anything I am missing?

A: Localhost only works on your machine. In your frontend, you'll need to change the axios url to point to the URL of your deployed server like so:
axios.get(`${YOUR_HEROKU_URL}`/bench)


text:
Q: Why can I not use sibling and :first-child on a list of heterogenous elements? I'm stuck trying to access an element via CSS and don't understand why.
I have a random number of
 combinations like this:

I don't know how many element pairs I will get and wanted to set the width depending on the number of elements. However while my selector:
.sample label ~ div

works and returns all three
 in the above example, doing:
.sample label ~ div:first-child

does not work.
Question
Why can I not use first-child? I had hoped my sibling selector would return a group of div elements, so I'm using first-child on homogenous elements? Or is there another problem?

A: The first child is a label element. The first div is the second child.
You could use:
.sample label:first-child + div

A: You can use :
.sample div:first-of-type

to select the first div.
EXAMPLE :

.sample *{
    height:10px;
    display:block;
    margin-top:5px;
    background:teal;
}
.sample div:first-of-type{
    background:gold;
}

A: Ok, found another solution which fits my need best:
.sample :first-child:nth-last-child(2) ~ div {
   width: 60%;
}
.sample  :first-child:nth-last-child(4) ~ div {
   width: 30%;
}
.sample :first-child:nth-last-child(6) ~ div {
   width: 20%;
}
.sample :first-child:nth-last-child(8) ~ div  {
  width: 15%;
}

So I'm not filtering for anything, because I know there will always be pairs of elements, so I'm checking for 2,4,6,8 elements and set the width of sibling divs respectively. Seems to work. Thanks @Huangism for the idea.


text:
Q: Custom ListView inside a dialog in android I am trying to make a custom dialog with listview which is going to contain checkboxes and textviews and i just couldnt find a reasonable tutorial to do it , any help or hints would be appreciated.

A: private void showPopUp()
{
    final AlertDialog.Builder helpBuilder = new AlertDialog.Builder(this);
    helpBuilder.setTitle("");

    LayoutInflater inflater = getLayoutInflater();
    final View PopupLayout = inflater.inflate(R.layout.yourxml, null);
    helpBuilder.setView(PopupLayout);

    final AlertDialog helpDialog = helpBuilder.create();
    helpDialog.show();

    jobList         =   (ListView)PopupLayout.findViewById(R.id.list);

    mylist          =   new ArrayList<HashMap<String, String>>();

    for(int i=0;i<arraylist.size();i++)
    {
        map = new HashMap<String, String>();
        map.put("name", arraylist.get(i));
        mylist.add(map);
    }
    sd = new SimpleAdapter(activity.this,mylist,R.layout.jobslist,
                new String[]{"name"},new int[]{R.id.jobText});
    jobList.setAdapter(sd);

}

joblist.xml
<?xml version="1.0" encoding="utf-8"?>
<LinearLayout
xmlns:android="http://schemas.android.com/apk/res/android"
android:id="@+id/lin01"
android:layout_width="fill_parent"
android:layout_height="wrap_content"
android:background="#fff"
android:padding="10dp"
android:orientation="horizontal">

        <TextView
            android:id="@+id/jobText"
            android:layout_width="0dp"
            android:text="@string/jobtype"
            android:layout_weight="1"
            android:gravity="left|center_vertical"
            android:layout_marginLeft="10dp"
            android:textSize="25dp"
            android:textColor="#000"
            android:layout_height="50dp"/>

        <CheckBox
            android:id="@+id/chk"
            android:layout_width="wrap_content"
            android:text=""
            android:gravity="center_vertical|right"
            android:layout_height="wrap_content"/>

        </LinearLayout>

you can call this showPopUp(); function wherever you want to display the alert dialog with listview. please note that there will be the arraylist which you can add items to it to show the items in a list

A:     ListView myList = new ListView(Activity.this);
    myList.setAdapter(adapter);

    AlertDialog.Builder builder = new AlertDialog.Builder(Activity.this);
    builder.setView(myList);
    Dialog d = builder.create();
    d.show();

you can specify the textviews and checkboxes and whatever else in the adapter.

A: It sounds like what your looking for is multiple choice mode for the ListView. Without knowing that phrase it's pretty hard to get a good example, but here's another SO question with answers that might help you out.
(Doing this in a Dialog is essentially the same process as in the selected answer's example.)


text:
Q: Swift: Filter a Dictionary with Array as Value I'm new to Swift programming. For my particular project, I'm trying to filter a dictionary with some user input, and the dictionary's value consists of an array.
Here is some sample code, and what I'm trying to accomplish:
var dictionary = ["a": ["aberration", "abc"], "b" : ["babel", "bereft"]]

var filteredDictionary = [String: [String]]()

var searchText = "aberration"

//getting the first letter of string
var firstLetter = searchText[searchText.startIndex]

With this particular searchText, I'm trying to get:
filteredDictionary = ["a": ["aberration"]]

Edit: I want the dictionary to return with the first letter as its key, and the values with what searchText matches up with. Sorry if it I wasn't clear.
Here is some code I have tried, but obviously, I can't get it to work:
filteredDictionary = dictionary.filter{$0.key == firstLetter && for element in $0.value { element.hasPrefix(searchText) }}

Any help would be appreciated. Thanks.

A: Here's a solution that maps the values based on the search and then filters out the empty results.
var dictionary = ["a": ["aberration", "abc"], "b" : ["babel", "bereft"]]
var searchText = "aberration"
let filteredDictionary = dictionary.mapValues { $0.filter { $0.hasPrefix(searchText) } }.filter { !$0.value.isEmpty }
print(filteredDictionary)

Output:

["a": ["aberration"]]

A: let firstLetter = String(searchText[searchText.startIndex])
let filteredDictionary = dictionary
    .reduce(into: [String: [String]]()) { (result, object) in
        if object.key == firstLetter {
            let array = object.value.filter({ $0.hasPrefix(searchText) })
            if array.count > 0 {
                result[object.key] = array
            }
        }
    }

Output:

["a": ["aberration"]]

A: Try this:
    var dictionary = ["a": ["aberration", "abc"], "b" : ["babel", "bereft"]]
    var searchText = "aberration"
    var filteredDictionary = dictionary.filter { (key, value) -> Bool in
            return (value as! [String]).contains(searchText)
        }.mapValues { (values) -> [String] in
            return [searchText]
        }
    print(filteredDictionary)

You can use a combination of filter and map to achieve the desired result.
Output:
["a": ["aberration"]]