text:
Q: heroku push suddenly failing I pushed out to heroku last night, and now today my pushes are failing with the following error.  Heroku status appears to be ok.  My heroku config has RAILS_MASTER_KEY set to my master.key.  That did not help.
Any experience this...or, able to point me towards a fix?
Command: 'bin/rails runner "puts %Q{heroku_detecting_active_storage_config=#{Rails.application.config.active_storage.service}}"' failed unexpectedly:
remote:  !     Missing encryption key to decrypt file with. Ask your team for your master key and write it to /tmp/build_996b65d7dc5d21b59fdaad7cc82a7aba/config/master.key
               or put it in the ENV['RAILS_MASTER_KEY'].

A: see : https://github.com/heroku/heroku-buildpack-ruby/pull/739, a fix seems to be merged


text:
Q: Locations of destructive interference for two spherical waves I have looked at this, but it did not help with locations. Really this just comes down to mathematical manipulation, which for some reason I fail to see. Here is my paraphrased setup:

Consider two sources of light separated by some distance $a$, and suppose they are emitting uniformly in all directions, at the same angular frequency, and same wave number. Determine the locations on a plane, which is parallel to the line joining the two light sources, at which the intensity is a minimum.

This is what I have. Let $r_1$ denote the distance from the first source to a point on the screen, $r_2$ for the second source to the point, and $L$ be the distance from the midpoint of the charges to the screen. Consider some point $p = (y,z)$ on the screen. Letting the x-axis be orthogonal to the screen and its origin at the midpoint, and the y and z axes to be parallel to the screen, we can write $$r_1 = \sqrt{L^2+y^2+(z-a/2)^2} \space\space\space \text{&} \space\space\space r_2 = \sqrt{L^2+y^2+(z+a/2)^2}$$ From this, we know that we can write the total wave at a point $p$ as $$E(t) = e^{iwt}(E_1e^{ikr_1}+E_2e^{ikr_2})$$ I am not substituting in yet for clarity, and note that $E_1$ and $E_2$ are the amplitudes of the respective waves. Now we also know that the intensity at this point has the following relationship: $I \propto |E|^2$, and we know from above that
$$|E|^2 = E_1^2+E_2^2+2E_1E_2cos\biggl[k\Bigl(\sqrt{L^2+y^2+(z-\frac{a}{2})^2}-\sqrt{L^2+y^2+(z+\frac{a}{2})^2}\Bigr)\biggr]$$
If things are correct up to this point, then it is clear that the minimum intensity locations occur when this cosine is a minimum. Namely, when
$$\sqrt{L^2+y^2+(z-\frac{a}{2})^2}-\sqrt{L^2+y^2+(z+\frac{a}{2})^2} = \frac{(2n+1)\pi}{k} \space\space n \in \mathbb{Z}$$
However, I cannot seem to put this into a nice simplified form for z as a function of y. I suspect that it is a hyperbolic relationship, but is there a nice way to reduce this to a compact form?

A: I asked the purely mathematical question over here, and received the most complete answer. While I thought there would be a simple trick to seeing the hyperbolic relationship, it looks like you just have to go through the tedious algebra to have it pop out. User JJacquelin found that it can be rearranged to the form $$\frac{z^2}{(\frac{(2n+1)\pi}{k})^2}-\frac{y^2}{L^2-(\frac{(2n+1)\pi}{k})^2}=\frac{1}{4}+\frac{a^2}{L^2-(\frac{(2n+1)\pi}{k})^2}$$ To show how this looks, I set $L = 20 \space \text{cm}$, $a= 2 \space \text{cm}$, and an infrared light source of $\lambda = 1000 \space \text{nm}$. Plotting a modest amount of these produced the following image:

A: Mathematica gives
$$
z=\gamma\frac{\sqrt{\gamma^2-a^2-4(y^2+L^2)}}{2\sqrt{\gamma^2-a^2}},
$$
where
$$
\gamma=\frac{(2n+1)\pi}{k}.
$$

redpajama_set_name: RedPajamaStackExchange


text:
Q: Python 2.7.10 64bit on Win10 - lib/test hangup I am new to python. And I need to run getmail. After lots of error msgs I reduced my claim to run the tests under lib/test first:
python .\test\regrtest.py -v -M 2.0Gb -uall,-bsddb,-largefile
I am getting failure msgs from some of them but at:
test test_re failed -- Traceback (most recent call last):
  File "F:\python27_64\lib\test\test_support.py", line 1287, in wrapper
    return f(self, maxsize)
  File "F:\python27_64\lib\test\test_re.py", line 973, in test_large_search
    s = 'a' * size
OverflowError: cannot fit 'long' into an index-sized integer

Warning -- files was modified by test_sax
test test_shutil failed -- Traceback (most recent call last):
  File "F:\python27_64\lib\test\test_shutil.py", line 138, in test_rmtree_dont_delete_file
    handle, path = tempfile.mkstemp()
  File "F:\python27_64\lib\tempfile.py", line 314, in mkstemp
    return _mkstemp_inner(dir, prefix, suffix, flags)
  File "F:\python27_64\lib\tempfile.py", line 245, in _mkstemp_inner
    _set_cloexec(fd)
  File "F:\python27_64\lib\tempfile.py", line 50, in _set_cloexec
    flags = _fcntl.fcntl(fd, _fcntl.F_GETFD, 0)
AttributeError: 'module' object has no attribute 'F_GETFD'

python is hangup :-(
ALL ideas are welcome


text:
Q: Php Pdo - Selecting last inserted i have a 'insert into' and 'select' querys together in one query.
$_SESSION['LoginUID']=1;
$Mesaj='ffdd';
$Ek=12;
$cid=112;
$Kaydet=$db->query("
               Insert Into Reply (Kimden,Mesaj,Ek,cid)
               Values (".$_SESSION['LoginUID'].",'$Mesaj',$Ek,$cid);
               select r_id,KayitZaman from Reply
               where r_id=LAST_INSERT_ID();")
            ->fetch(PDO::FETCH_ASSOC);

But i cant select last inserted row. It must return like this
m_id  KayitZaman
16      1413130807000
How can i do that in one query? Or other way.

A: You cannot run two queries at the same time, only one at the time
After the insert, run the select:
$stmt = $db->query('select r_id,KayitZaman from Reply where r_id=LAST_INSERT_ID()');

or you can use the built in function to pass the last inserted Id
$stmt = $db->prepare('select r_id,KayitZaman from Reply where r_id= ?');
$stmt->execute(array($db->lastInsertId()));

If you want to do the whole thing at once then create a stored procedure.

EDIT:
DELIMITER //
 CREATE PROCEDURE sp_insert_get_reply(IN `p_Kimden`,
                                      IN `p_Mesaj`,
                                      IN `p_Ek`,
                                      IN `p_cid`)
   BEGIN
   INSERT INTO `Reply` (`Kimden`, `Mesaj`, `Ek`, `cid`)
   VALUES (p_Kimden, p_Mesaj, p_Ek, p_cid);

   SELECT `r_id`, `KayitZaman`
   FROM Reply WHERE r_id=LAST_INSERT_ID()
   END //
 DELIMITER ;

then call the function from PDO:
$stmt = $db->prepare('CALL sp_insert_get_reply(?, ?, ?, ?)');
$stmt->execute(($_SESSION['LoginUID'], $Mesaj, $Ek, $cid));

A: You should try issuing your insert in a PDO exec() call, and following it up with your select in the query call.  You can still use LAST_INSERT_ID() in your select query and retain data integrity.
If, for some reason, you must do the two statements in a single request from your program, you can use the multiple-statement feature of mysqli or you can write a stored procedure.


text:
Q: Cannot EFI boot from Clonezilla disk image I have created a Ubuntu Server 14.04 system that I would like to clone to several other machines with exactly the same hardware specifications. The system is an Intel NUC2820 with 30 GB SSD.
The current working installation contains three partitions:
/sda1 fat32 (efi boot)
/sda2 ext4
/sda3 swap

The system is set up using GPT and uses UEFI for boot.
With Tuxboot I created a CloneZilla USB and wrote the complete disk to an image that I would like to use to restore. However after restoring the image to a new machine I can't seem to find a way to make the system bootable again.
I tried using grub-install from the CloneZilla environment, but I get the following error:
warning : this GPT partition label contains no  BIOS boot Partition; embedding wont be possible
warning : Embedding id not possible. GRUB can only be installed in this setup by using blocklists. However, blocklists are UNRELIABLE and their use is discouraged..
error : will not proceed with blocklists

I guess this has something to do with grub not working in EFI mode. I have no idea if I can force grub to create an EFI partition. When I use efibootmgr i get the message:
efi variables are not supported on this system

I also tried to use the Ubuntu 14.04 Server installer, but re-installing Grub in rescue mode says:
executing 'grub-install' failed
This is a fatal error

When i execute grub-install from the shell I get the a message the Grub is successfully installed
, although still can't find a boot disk upon start up.
Is there any way to get the image to be bootable again

A: After days of searching of course I find the answer myself an hour after I decided to post here.
Using a Ubuntu-based version of CloneZilla I got it to boot in UEFI-mode which was able to update the correct boot records.


text:
Q: Using Spigot to change armor attributes I'm attempting to make a spigot plugin that will turn off the knockback resistance that netherite gives you, but I'm still quite new to the plugin development scene and couldn't find anything pertaining to it in the spigot api, is there a way to go about turning off the knockback resistance or am I just missing something here?

A: At the EntityDamageByEntityEvent you could set the velocity of an player with player.setVelocity() to the direction the damager looks.
Prevent hitting the Player upwards too much and check if the  player is sneaking or jumping.
setVelocity Documentation: https://hub.spigotmc.org/javadocs/spigot/org/bukkit/entity/Entity.html#setVelocity(org.bukkit.util.Vector)


text:
Q: Can rust and serde-xml-rs parse comments from XML files? <foo>
  <!-- 2021-03-17 08:15:00 EST -->
  <row>
     <value>100</value>
  </row>
</foo>

I would like to get the comment from an XML file and was wondering if that was possible and if so how? I didn't see an example of that. In the above example, i would like to get "2021-03-17 08:15:00 EST"

A: No, at this time serde-xml-rs does not support parsing comments from XML files. See here in the source; they skip comments all together.
But there's an open pull request to add support for parsing comments.
So if you want to parse comments right now (with a disclaimer that this is not stable because you use somebody's github fork to do it) you could use the fork of the author of above pull request in this way:
// Cargo.toml contains:
//
// [dependencies]
// serde = {version = "1.0", features = ["derive"]}
// serde-xml-rs = {git = "https://github.com/elmarco/serde-xml-rs.git", branch = "comment"}

use serde::Deserialize;
use serde_xml_rs::from_reader;

#[derive(Debug, Deserialize)]
pub struct Foo {
    #[serde(rename = "$comment")]
    pub date: Option<String>,
    pub row: RowValue,
}

#[derive(Debug, Deserialize)]
pub struct RowValue {
    pub value: i32,
}

fn main() {
    let input = "<foo> \
                   <!-- 2021-03-17 08:15:00 EST --> \
                   <row> \
                      <value>100</value> \
                   </row> \
                 </foo>";

    let foo: Foo = from_reader(input.as_bytes()).unwrap();
    println!("input={:#?}", foo);
}


text:
Q: Ordering MySQL results (in PHP) with natural sort order We have a MySQL table with lots of company names. The table collation is utf8_general_ci. The DB connection has a UTF8 charset during the handshake set.
To sort the company names in a natural sort order via PHP, we used a regular MySQL ORDER BY table.companyName (varchar 255) and an additonal PHP sort via usort() and strnatcasecmp().
    $select->order('table.companyName');

    [...]

    usort($records, function ($a, $b) {
        return strnatcasecmp($a['companyName'], $b['companyName']);
    });

This transformed a list of e.g:
["Company 1", "Crompany", "Cömpany", "Z Company", "ö Company"]

into
["Company 1", "Cömpany", "Crompany", "ö Company", "Z Company"]

for the last couple of years. The usort() change was added in 2016.
Currently, the output with both the ORDER BY clause and the usort() is all of a suddon not correctly sorted:
["Company 1", "Crompany", "Cömpany", "Z Company", "ö Company"]

Removing the usort()/strnatcasecmp() fixes the sort order back to
["Company 1", "Cömpany", "Crompany", "ö Company", "Z Company"].

I'm just not sure if I been missing any change lately to either MySQLs sort order algorithm or the strnatcasecmp() behaviour in PHP, possibly related to UTF8?
We're using PHP 7.2.22 and mysqld 5.7.27 (dev) or 5.7.26 (production).


text:
Q: where is the servlet-api.jar in glassfish installation? We are migrating our project from the Sun App server to Glassfish. For compilation we need the classpath to be set to the servlet-api.jar which is found in the servlet container. Where in the Glassfish installation can I find these jars?
Thanks.

A: I guess you want to use Glassfish 3 or higher.
You can find the servlet-api in
$GLASSFISH_HOME\glassfish\modules\javax.servlet-api.jar

in Glassfish 3 and 4.


text:
Q: Rails: both block arg and actual block given I am trying to make an app in Rails 4.
I have this code in my profiles show page, to show all the projects a user has created.

      <% Project.all_current_for_creator(@creator).sort_by(&:created_at) do |project| %>

                <%= image_tag project.hero_image_url, width: '100%', height: '200px' if project.hero_image.present? %>

 <%= link_to project.title, project %>

                    <%= truncate(project.description, :ommission => "...", :length => 250) %>

     <% end %>

When I try this, I get an error that says:
SyntaxError at /profiles/3
both block arg and actual block given

Can anyone see what's wrong?
The method 'all_current_for_creator' is defined in my project.rb as:
def self.all_current_for_creator(creator)
    if creator.profile.present?
       creator.current.visible
    else
      guest_visible
    end
  end

I have defined three scopes in project.rb as:
scope :creator, lambda { where(@creator_profile = user.profile_id)}

  scope :current, lambda { where('project.start_date >= ?', Date.today)}
  scope :visible, lambda { joins(:sweep => :disclosure).where('disclosures.allusers' => 'true')
    .joins(:sweep => :finalise).where('finalises.draft' => 'false') }

A: .sort_by(&:created_at) do |project|

Should be:
.sort_by(&:created_at).each do |project|

Because in the first case you are passing two blocks &:created_at and do ....


text:
Q: The correct determinant exponent of the weight $k$-operator for defining Hecke operators/adelizing modular forms For $g \in \operatorname{SL}_2(\mathbb R)$, and $\mathbb H$ the upper half plane,  and $k\geq 1$ an integer, the weight $k$-operator on functions $f: \mathbb H \rightarrow \mathbb C$ is defined by
$$f[g](z) = f(g.z) j(g,z)^{-k}$$
where $j(g,z) = (cz+d)^{-1}$, $g = \begin{pmatrix} a & b \\ c & d\end{pmatrix}$.
In order to define Hecke operators, or to adelize modular forms, or to identify modular forms as functions on $\operatorname{GL}_2(\mathbb R)^+$, it is necessary to extend this definition to $g \in \operatorname{GL}_2^+(\mathbb R)$.  In A First Course in Modular Forms, in Chapter 5.1 Diamond and Shurman set
$$f[g](z) = f(g.z)j(g,z)^{-k} \det(g)^{k-1}$$
In Automorphic Forms and Representations, in Chapter 1.4 Bump sets
$$f[g](z) = f(g.z)j(g,z)^{-k} \det(g)^{k/2}$$
Which exponent of the determinant is better to use, and why?  If we adelize a Hecke eigenform for $\operatorname{SL}_2(\mathbb Z)$ and look at the corresponding automorphic representation $\pi = \otimes_p \pi_p$, which normalization is better to define Hecke operators with, if we want the classical Hecke operator $T_p$ to coincide naturally with an action of the spherical Hecke algebra $\mathscr H(\operatorname{GL}_2(\mathbb Q), \operatorname{GL}_2(\mathbb Z_p))$ on the local component $\pi_p$?
Recall that to adelize a modular form $f$ of $\operatorname{SL}_2(\mathbb Z)$ of some given weight, we would first identify $f$ with a function $\phi$ on $\operatorname{GL}_2^+(\mathbb R)$ by setting
$$\phi(g) = f[g](i)$$
and then we would define an automorphic form $\varphi$ on $\operatorname{GL}_2(\mathbb Q) \backslash \operatorname{GL}_2(\mathbb A)$ by using the decomposition $\operatorname{GL}_2(\mathbb A) = \operatorname{GL}_2(\mathbb Q) \operatorname{GL}_2^+(\mathbb R)K$ for $K$ a suitable compact subgroup, writing $g = \alpha g_{\infty}k$, and setting $\varphi(g) = \phi(g_{\infty})$.

A: This is a question which has no "right" answer.
A posh interpretation of the choice of exponent is that a Hecke eigenform $f$ determines an equivalence class of irreducible representations $\Pi = \bigotimes'_v \Pi_v$ of $GL_2(\mathbb{A}_\mathbb{Q})$, differing by twists by powers of the character $g \mapsto \|\det(g) \|$, and the power of $\det$ that you put in the action of $GL_2^+(\mathbb{Q})$ determines which twist you get.
The normalisation that Diamond and Shurman use is the one that makes the eigenvalue of the double coset $\begin{pmatrix} p & 0 \\ 0 & 1 \end{pmatrix}$ on $\Pi_p$ correspond to the Fourier coefficient $a_p(f)$; while Bump's normalisation makes it correspond to $a_p(f) / p^{(k/2-1)}$.
From the perspective of the analytic theory of automorphic forms, Bump's choice is the "obviously right" one, since it makes $\Pi$ be unitary. Then you can find $\Pi$ as a subrepresentation of $L^2(GL_2(\mathbb{Q}) \backslash GL_2(\mathbb{A}))$ and the analytic theory works as it should. Since Bump's text emphasises the analytic theory of automorphic forms, this is the convention he chooses (and Paul Garrett's comment seems to be coming from the same viewpoint).
On the other hand, from the viewpoint of the algebraic theory (Galois representations, special values of L-functions, etc), the factor $k/2$ is extremely inconvenient, particularly when $k$ is odd. The $a_p$'s all lie in some common finite extension of $\mathbb{Q}$, but the eigenvalue of $\Pi_p$ has been multiplied by $p$ to a half-integer power; so the extension of $\mathbb{Q}$ generated by the eigenvalues is not finite, and correspondingly the critical values of the $L$-series are at half-integers rather than integers, meaning that the $L$-series of $\Pi$ cannot correspond to a motive. With Diamond and Shurman's normalisation, the finite part of $\Pi$ is definable over a number field, and its $L$-series is motivic. (This would work with any integer power of $\det$, but $\det^{k-1}$ is the minimal one which makes the Hecke eigenvalues algebraic integers.)
So the Diamond-Shurman normalisation is better for the algebraic theory, and the Bump normalisation for the analytic one.
There is a great quote on this (attributed to Deligne, but possibly apocryphal): "Langlands is very convinced he knows what the square root of $p$ is. I have never been so sure."


text:
Q: Magento 2 don't create Data base tables I have 3 weeks trying to install by composer some modules but when i see the data base i cant found any data table of the module. I recibe different issues but always persist this kind of issue:
2 exception(s):
Exception #0 (Zend_Db_Statement_Exception): SQLSTATE[42S02]: Base table or view not found: 1146 Table 'DatabaseName.aw_raf_summary' doesn't exist, query was: SELECT aw_raf_summary.id FROM aw_raf_summary WHERE (referral_link = :referral_link) AND (website_id = :website_id)
Exception #1 (PDOException): SQLSTATE[42S02]: Base table or view not found: 1146 Table 'DatabaseName.aw_raf_summary' doesn't exist.
This is an example after of install Refer A Friend (Component name: aheadworks/module-raf Component version: 1.1.3)
I'm using Magento 2 CE 2.3.4
My steps on command line are:
composer require aheadworks/module-raf
php bin/magento setup:static-content:deploy -f
php bin/magento setup:upgrade
php bin/magento indexer:reindex
php bin/magento cache:flush
php bin/magento cache:clean


text:
Q: Does anyone have real world example for random point pattern I have been writing a paper and need to give examples for the different patterns that are result of point process. It has to be real world examples. For clustered I give the example of settlements and train stations, with the logic of real estate developers want their estates to be close to local amenities and shop owners want to be next to public transport so it is all clustered. This is in the suburbans I forgot to mention. For dispersed I give the example of gas stations which usually try not to be very close to each other with the logic of drivers not really researching where is the next texaco (if that is what their station of choice) and when they understand they need gas they'll just stop at the first one.
I still can't find a good example for random point pattern in the real world. I watch CSI and they say that crime is random but from two sample data that they gave us it is clustered. And it also makes sense that it's not random because burglars like high class neighborhoods.
Can anyone help with an example for real world random point pattern?


text:
Q: is there a way to track when others have commented on my answers on stackoverflow?
Possible Duplicate:
How do comment @replies work?

I looked through the FAQ page but there was no answer there. Say I post an answer to a question. Then someone else wrote a comment to my post. How do I know a comment is posted without clicking through all my responses?

A: May I point you towards the Global Inbox?
Essentially, when an a comment is left to one of your answers the StackExchange link (upper left, above the Stack Overflow icon) will have a number, with a distinctive red background-colour appended to it to show the number of comments/responses.


text:
Q: MEF: Composition rejection when compose ExportFactory for generic type Bar Please see code below: method Test runs twice, once with type argument Foo and second with type argument
<Bar<Foo>>

Inside Test method we retrieve exported value for T and ExportFactory for the same type.
First invocation pass OK.
The second invocation results in composition rejection below in comments.Please note, on the second invocation the first alert pass ok, the instance was created. It is the creation of the ExportFactory for this type fails...
using System.ComponentModel.Composition;
using System.ComponentModel.Composition.Hosting;
using System.Diagnostics;
namespace MefExportFactoryBug
{
    class Program
    {
        static void Main(string[] args)
        {
            var tc = new TypeCatalog(new []{typeof(Foo),typeof(Bar<>),typeof(ExportFactoryProvider<>)});
            var cc = new CompositionContainer(tc, true);
            Test<Foo>(cc);//Pass OK
            Test<Bar<Foo>>(cc);// Exception below thrown
            /*
             A first chance exception of type 'System.ComponentModel.Composition.ImportCardinalityMismatchException' occurred in System.ComponentModel.Composition.dll
            A first chance exception of type 'System.ComponentModel.Composition.ImportCardinalityMismatchException' occurred in System.ComponentModel.Composition.dll
            A first chance exception of type 'System.ComponentModel.Composition.ChangeRejectedException' occurred in System.ComponentModel.Composition.dll
            System.ComponentModel.Composition Warning: 1 : The ComposablePartDefinition 'MefExportFactoryBug.ExportFactoryProvider(MefExportFactoryBug.Bar(MefExportFactoryBug.Foo))' has been rejected. The composition remains unchanged. The changes were rejected because of the following error(s): The composition produced a single composition error. The root cause is provided below. Review the CompositionException.Errors property for more detailed information.

            1) No exports were found that match the constraint:
                ExportFactory of:
                ContractName    MefExportFactoryBug.Bar(MefExportFactoryBug.Foo)
                RequiredTypeIdentity    MefExportFactoryBug.Bar(MefExportFactoryBug.Foo)
                RequiredCreationPolicy    NonShared

            Resulting in: Cannot set import 'MefExportFactoryBug.ExportFactoryProvider(MefExportFactoryBug.Bar(MefExportFactoryBug.Foo)).Factory (ContractName="System.ComponentModel.Composition.Contracts.ExportFactory")' on part 'MefExportFactoryBug.ExportFactoryProvider(MefExportFactoryBug.Bar(MefExportFactoryBug.Foo))'.
            Element: MefExportFactoryBug.ExportFactoryProvider(MefExportFactoryBug.Bar(MefExportFactoryBug.Foo)).Factory (ContractName="System.ComponentModel.Composition.Contracts.ExportFactory") --> MefExportFactoryBug.ExportFactoryProvider({0}) --> TypeCatalog (Types='MefExportFactoryBug.Foo, MefExportFactoryBug.Bar({0}), ...').

             */
        }

        private static void Test<T1>(ExportProvider cc) where T1:class
        {
            var ev = cc.GetExportedValue<T1>();
            Debug.Assert(ev != null);
            var ef = cc.GetExportedValue<ExportFactoryProvider<T1>>().Factory;
            Debug.Assert(ef != null);
        }
    }
    [Export]
    public class ExportFactoryProvider<T>
    {
        [Import]
        public ExportFactory<T> Factory { get; set; }

    }

    [Export]
    public class Foo
    {
    }

    [Export]
    public class Bar<T>
    {
    }
}

A: I found a workaround: using SatisfyImportOnce inside ExportFactoryProvider resolves the issue and ExportFactory got created. See code below. Still not sure why export is there but ExportFactory is not in the original question's code ...
 using System.ComponentModel.Composition;
 using System.ComponentModel.Composition.Hosting;
 using System.Diagnostics;

 namespace MefExportFactoryBug
 {
  class Program
  {
    static void Main(string[] args)
    {
        var tc = new TypeCatalog(new []{typeof(Foo),typeof(Bar<>),typeof(ExportFactoryProvider<>)});
        var cc = new CompositionContainer(tc, true);
        Test<Foo>(cc);//Pass OK
        Test<Bar<Foo>>(cc);//Pass OK now
    }

    private static void Test<T1>(CompositionContainer cc) where T1:class
    {
        var ev = cc.GetExportedValue<T1>();
        Debug.Assert(ev != null);
        var ef = new ExportFactoryProvider<T1>(cc).Factory;
        Debug.Assert(ef != null);
    }
}
[Export]
public class ExportFactoryProvider<T>
{
    public ExportFactoryProvider(ICompositionService cc)
    {
        cc.SatisfyImportsOnce(this);
    }

    [Import]
    public ExportFactory<T> Factory { get; set; }

}

[Export]
public class Foo
{
}

[Export]
public class Bar<T>
{
}

}


text:
Q: E(fx)clipse completely rendered with Javafx I would like to know if, in some way, it is possible to start an e(fx)clipse instance, whose view parts are completely rendered with Javafx (editors, palette...).
If I develop a plugin with view contribution in Javafx, can I start "all" eclipse rendered in javafx?
Or e(fx)clipse only allows to insert Javafx components into swt canvas?
Thanks

A: I reply myself: no, it is not possible.
Read last comment on
https://tomsondev.bestsolution.at/2011/10/17/efxclipse-0-0-7-released/


text:
Q: Building a Linked-List with another Struct - Append Function runtime error First whack at learning pointers, I'm trying to follow all of this and I thought I had it right but alas I am getting a runtime error when calling the append function. The CSV function appears to be working. I'm guessing I've messed up the Append flow. Any tips or advise is warmly welcomed.
struct Car {
    string carId; // unique identifier
    string title;

};

class LinkedList {

private:

    struct node {
        Car cars;
        node *next; //is this storing the memory address of the struct?
    };

    // alias for node pointer (memory address of node)
    typedef struct node* nodePtr;

    // defining pointer variables for memory positions in the List
    nodePtr head;
    nodePtr curr;
    nodePtr temp;
    nodePtr tail; //is this needed

public:
    LinkedList();
    void Append(Car car);
};

//Default constructor

LinkedList::LinkedList() {
    head = NULL;
    curr = NULL;
    temp = NULL;
    tail = NULL;

}

void LinkedList::Append(Car car) {

    nodePtr n = new node;
        n->cars = car;
        n->next = NULL;

    if (head == NULL){
        head = n;
        tail =n;

    }
    else {
        tail->next = n;
        tail=n;
    }
}

void loadCars(string csvPath, LinkedList *list) {

    csv::Parser file = csv::Parser(csvPath);

    try {
        // loop to read rows of a CSV file
        for ( unsigned int i = 0; i < file.rowCount(); i++) {

            // initialize a bid using data from current row (i)
            Car car ;
            car.carId = file[i][1];
            car.title = file[i][0];

            // add this bid to the end
            list->Append(car);
        }
    }
}

int main(int argc, char* argv[]) {

LinkedList carlist
csvPath = xyz;

loadCars(csvPath, &carlist);

}


text:
Q: Jquery accordion close I'm working on creating a mobile accordion nav for a website. I have a basic accordion set up, the problem I am having is when I open one tab I want the other tabs to automatically close so only one tab can be opened at once. I've tried a few things but I can't get it to work.
Here is the code - http://codepen.io/anon/pen/OVvZev
// Dropdown Menu
var dropdown = document.querySelectorAll('.dropdown');
var dropdownArray = Array.prototype.slice.call(dropdown, 0);
dropdownArray.forEach(function (el) {
    var button = el.querySelector('a[data-toggle="dropdown"]'),
        menu = el.querySelector('.dropdown-menu'),
        arrow = button.querySelector('i.icon-arrow');

    button.onclick = function (event) {
        if (!menu.hasClass('show')) {
            menu.classList.add('show');
            menu.classList.remove('hide');
            arrow.classList.add('open');
            arrow.classList.remove('close');
            event.preventDefault();
        } else {
            menu.classList.remove('show');
            menu.classList.add('hide');
            arrow.classList.remove('open');
            arrow.classList.add('close');
            event.preventDefault();
        }
    };
});

Element.prototype.hasClass = function (className) {
    return this.className && new RegExp("(^|\\s)" + className + "(\\s|$)").test(this.className);
};

What's the best way to go about doing this?

A: Here's a solution: http://codepen.io/merlinmason/pen/KpoBRm
$(".accordian .title").on("click", function () {
  var content = $(this).parent().find(".content");

  if ($(content).hasClass("open")) {
    $(content).slideUp(400).removeClass("open");
  } else {
    $(".content.open").slideUp(400).removeClass("open");
    $(content).slideDown(400).addClass("open");
  }
});

In short - it checks if the accordion is open, if so it closes it, if not it finds all open accordions, closes them and then opens the current one.
Key things:
- using class "open" to preserve the state
- using "this" to reference to accordion currently being actioned


text:
Q: Flows/Processes, Version Control and CI I've started using Processes and Flows and am really excited about these features -- but am still wrapping my mind about how to manage them in Version Control (which I use) and Continuous Integration (which I don't yet... but am trying to work in that direction).
The underlying challenge is that each time a process or flow is edited, the metadata file is renamed to reflect its update version, e.g. MyFlow-1.flow, MyFlow-2.flow, etc.
The Challenge for Version Control
If each version of the flow has its own file name, this makes it more complicated to track changes to flows.  It seems like there could be two strategies here:

*

*Rename the files to remove the version number.  I'd need a script to run through my src folder pre-commit, and remove the number so that my file name is always MyFlow.flow.  This is an annoying extra step, but makes version control simpler.  On the other hand, it probably makes deployment much harder.

*Track each file in version control with its original name.  We'd need to be diligent about deleting MyFlow-1 in the commit where we add MyFlow-2 so that git would recognize this as a rename/move and show helpful diffs.  Otherwise, the whole file appears to change with every change, which makes version control rather less useful.
The Challenge for Deployment/Continuous Integration
From my experiments so far, once a flow has been activated in a given environment, the metadata file can't be deployed again (either it is currently active, or has been active in the past and superseded).
That means that I need to prevent my previous flow versions from being included in a deployment package (either by not tracking them at all, or by using a script to delete earlier versions).  I also need some way to determine whether the current version (in my repo) should be included in the deployment payload for a given environment or not.
I could imagine a script that (1) downloads flows from the target environment, and removes *.flow files from the payload if they already exist in the target environment, but that feels complicated.  And it's even harder if I've removed the version numbers from my flow files.
Are you using flows in VS or CI?  How are you managing these issues?
Note:  I'm not sure whether VC and CI should be one question or two - depends on how integrated the strategy for dealing with these two challenges.  If you think these should be separate questions, comment and I'll re-post.

A: The trick is to disable the deployment of the flows with build property.
Let say you want to skip flows deployment normally and just deploy them if they don't exist.
You have to do following steps:

*

*Add following snippet to you src/package.xml

       <!--TO_REMOVED-->
       <types>
         <members>My_Flow-33</members>
         <name>Flow </name>
       </types>
       <!--TO_DELETE-->

*Use following ant code

    <target name="flowRequired">
        <condition property="includeFlow">
            <equals arg1="${deployFlow}" arg2="true"/>
        </condition>
    </target>

    <target name="deployFlow" unless="includeFlow"  depends="flowRequired">
        <replace file="src/package.xml">
            <replacefilter value="" token="TO_REMOVED--"/>
        </replace>
        <replace file="src/package.xml">
            <replacefilter value="" token="!--TO_DELETE"/>
        </replace>
    </target>

In this setting if you don't pass parameter deployFlow or set it to false to you ant script it will replace the values in a way that that section becomes a comment in your package.xml file.

A: This is not a complete answer, but I'm putting it here in case this idea helps anyone else get a better picture.
FlowDefinition is metadata about the Flows (it sort of relates to Flows the same way that .cls-meta.xml relates to .cls files, and I'm not sure why it was modeled so differently).
The FlowDefinition file (spec) looks like this:
<?xml version="1.0" encoding="UTF-8"?>
<FlowDefinition xmlns="http://soap.sforce.com/2006/04/metadata">
    <activeVersionNumber>5</activeVersionNumber>
</FlowDefinition>

If you track the FlowDefinition in git, you can use ant (or git) to add the proper suffix to your versioned file.
This means the process could look something like this:

*

*In our workspace, we just deal with the flow with suffix.

*A git filter:

*

*on clean: drops the flow suffix when you stage flows if the suffix matches what's in the FlowDefinition (otherwise, you might overwrite an old version).

*on smudge: appends the flow suffix from the FlowDefinition

*Caveat: This is not necessarily a proper git filter since it violates the warning in the man file:

In other words, the intent is that if someone unsets the filter driver definition, or does not have the appropriate filter program, the project should still be usable.:

*If you are deploying from the cloud, you'd need an ant task preprocessor that references FlowDefinition, appends the proper suffix to the flow, and also drops old flow versions.

I'm not sure this would work, but I think the FlowDefinition will help get somewhere workable.
There are two places this falls apart: First, if a flow is inactive, it won't have a FlowDefinition activeVersionNumber.  I'm not even sure what the expected behavior is.  Second, if a new version of the flow is in development but the old version is still active, you're basically toast.  However, I'm not sure why a dev shop would operate that way, and I think it should be discouraged, so I don't mind this.
If anyone gets any further on this, please be in touch.

A: It looks like this answer is properly coming in v44.0 (Winter '19):
Per release notes

When you retrieve or deploy the latest version of a flow, Salesforce no longer adds a number to the end of each flow name. Before you deploy flow metadata using API version 44.0, upgrade your flow files with Metadata API or Salesforce CLI or both to remove the version numbers.


text:
Q: Issue with Highcharts React Wrapper: Getting Highcharts error #18 but the same options passed to plain Highcharts Js is working fine I am using "Highcharts React Wrapper" (https://www.npmjs.com/package/highcharts-react-official) with HighStocks and when using HighCharts wrapped in React Component as controlled component and updating the series or adding new series is giving below mentioned error:
Highcharts error #18: www.highcharts.com/errors/18/

However, when the same chart options is copied and tried with plain JS
  HighStocks example, then it works fine.

Reproduced the issue in below link:
https://codesandbox.io/s/highstock-react-wrapper-issue-hry5u


text:
Q: WordPress ACF 'post-object' and WooCommerce product = error on front page? I have this WP_Query:
$query = new WP_Query(
        array(
            'posts_per_page' => $postsCount,
            'post_type' => 'events',
            'taxonomy' => 'events-category',
            'meta_key' => 'event-start-date',
            'orderby' => $postsOrderBy,
            'order' => $postsOrder,
            'meta_query' => array(
                array(
                        'key' => 'event-start-date',
                        'compare' => '>=',
                        'value' => date("Y-m-d"),
                        'type' => 'DATE',
                ),
            ),
        ),
    );
if ($query->have_posts()):
    while ($query->have_posts()): $query->the_post();
        // content
    endwhile;
    wp_reset_query();
endif;

In 'content' I have something like this:
    <?php
    $post_object = get_field('event-ticket');
        if( $post_object ):
            $post = $post_object;
            setup_postdata( $post );
            $product->get_id(); ?>

<?php woocommerce_get_template( 'single-product/price.php' ); ?>

        <?php if ( $product->is_in_stock() ) {
        echo '
'.__('Dostępne!', 'woocommerce').'
';
        } elseif ( ! $product->is_in_stock() ) {
        echo '
'.__('Wyprzedane!', 'woocommerce').'
';
        } ?>

    <?php
    wp_reset_postdata();
    endif;
    ?>

get_field('event-ticket') is ACF post object field type with 'Post Object' return object. This field pointing on WooCommerce product to get price and quantity stock.
WP_Query is loop of the CPT 'Events'. In every event I'm using post object field to point to the WooCommerce product, which is a ticket.
PROBLEM:
Datas from 'event-ticket' works on every subpages (archives, taxonomy, pages, cpt posts) but not on front (home) page:
Uncaught Error
: Call to a member function get_id() on null

What could be the reason?

A: You have not declared $product before. This is why you get this error. $product->get_id(); when you did not initialized $product earlier.
Maybe you want first:
$product = new WC_Product($post->ID);

A: I figure out: I just add global $product; before $product->get_id(); and now it's working :)


text:
Q: Import error no module in Django I am importing a module named python_contextual_test_manager in forms.py as follows:
from python_contextual_test_manager.main_runner import main as main_runner

Both python_contextual_test_manager.py and forms.py are in the same directory but it shows me the following error:
ImportError: No module named python_contextual_test_manager

What to do?

A: I think adding a dot in front of the file name should get you sorted. Like this:
from .python_contextual_test_manager.main_runner import main as main_runner.
The dot specifies that you want to import from the same folder that the file is in. Another way is to make the path absolute to the project directory, for example if all of that exists inside a Django app called app, then you could also import
from app.python_contextual_test_manager.main_runner import main as main_runner.


text:
Q: How to invoke Xtend code from Java? I have a code generator, which takes a syntax tree and converts it into a source file (text).
Basically, it traverses through all nodes of the tree, maps the node to text and appends the resulting texts to a StringBuilder.
Now I want the node to text mappers to be implemented using Xtend like this:
public class NodeXMapper
{
    private XtendRunner xtendRunner = ...;

    public String map(final NodeX aNode)
    {
        return xtendRunner.runScript("def String map(NodeX aNode) {
            ''' «aNode.fieldX» - «aNode.fieldY» '''
        }", aNode);
    }
}

xtendRunner.runScript(String aScript, final Object... aParams) is a method, which passes the parameters aParams to Xtend script aScript and returns the result.
How can I implement that method?
Update 1: Here I found this piece of code, which seems to run Xtend code in Java:
// setup
XtendFacade f = XtendFacade.create("my::path::MyExtensionFile");

// use
f.call("sayHello",new Object[]{"World"});

But I can't find XtendFacade class in the Type hiearchy view of Eclipse.

A: The interpreter you found was for the old Xtend1 language, which is not what you are looking for.
The new Xtend you are referring to is compiled, so there is no interpreter.
However, you could build an interpreted expression language using Xbase.  See the documentation and Github for an example on how to do that. Then you could run the interpreter of your expression language from Java.


text:
Q: How to disable keepalive in NSURLConnection? Is there any way to force NSURLConnection to not reuse the current persistent connection but to create a new one ?
I am trying to defend myself from this known iOS8 keep-alive bug

If iOS 8 receives a HTTP response with a Keep-Alive header, it keeps this
  connection to re-use later (as it should), but it keeps it for more
  than the timeout parameter of the Keep-Alive header and then when a
  second request comes it tries to re-use a connection that has been
  dropped by the server.

I am looking for a way to solve this issue from Objective c rather than solving from server side.
If any third party libraries provides a way to ignore Keep-alive header then its also welcome.
This issue is somewhat related to following issues(1,2)
Any help is appreciated !

A: The only way I found is to use CFNetwork. Higher level API such as NSURLConnection or NSURLSession's Connection header will be overwritten by system.


text:
Q: How do I remove unwanted classes and tags from newspaper3k object? I want to extract news article contents and I'm currently using newspaper3k library:
a = Article(url, memoize_articles=False, language='en')
a.download()
a.parse()
content = a.text

But for some websites, there are unwanted elements like advertisements and text from images. So I want to remove those unwanted elements and text. Is there a way to remove all the content from those tags and classes?

A: If you want to do it for a particular website, you can use a.top_node, find out XPath or CSS selector of the advertisement, and then remove them.
ads = a.top_node.xpath("./foo")  # find a proper selector
for ad in ads:
    ad.getparent().remove(ad)

# and now conver top_node to text again somehow, probably using
# OutputFormatter

See https://github.com/codelucas/newspaper/blob/56de65af9efbfea6293c82c0b1821e2ca9fbddaa/newspaper/article.py#L281
It could be also possible to implement a custom DocumentCleaner and put this logic there.
In general, this is a hard problem, probably the hardest one in article extraction, if you want to do it in a generic and robust way, without writing and maintaining rules for each website. Open Source libraries can often find the main content with reasonable quality, but they are pretty bad at excluding extra stuff from article body. See https://github.com/scrapinghub/article-extraction-benchmark and https://github.com/scrapinghub/article-extraction-benchmark/releases/download/v1.0.0/paper-v1.0.0.pdf report.
Commercial tools like AutoExtract by Scrapinghub (I work there) solve this issue; they use computer vision and machine learning, as it is hard to solve this problem reliably otherwise.


text:
Q: How to Retain the values in the Check Box in R Shiny App? I am trying to create a Shiny App. In this particular app i have a set of Radio buttons where choosing one will display a set of options below as Check Boxes and Choosing another radio button will choose other set of options. Kindly find the UI and the Server Code below.
library(shiny)
library(shinydashboard)
library(shinyWidgets)

d <-
  data.frame(
    year = c(1995, 1995, 1995, 1996, 1996, 1996, 1997, 1997, 1997),
    Product_Name = c(
      "Table",
      "Chair",
      "Bed",
      "Table",
      "Chair",
      "Bed",
      "Table",
      "Chair",
      "Bed"
    ),
    Product_desc = c("X", "X", "X", "Y", "Y", "Y", "Z", "Z", "Z"),
    Cost = c(1, 2, 3, 4, 2, 3, 4, 5, 6)
  )

ui <- shinyUI(fluidPage(
  useShinydashboard(),
  tabPanel(
    "Plot",
    sidebarLayout(
      sidebarPanel(
        radioButtons(
          "Choose",
          "Choose One",
          c("Year" = "p", "Numbers" = "l")
        ),
        uiOutput('checkbox'),
        #width = 2,
        position = "bottom"),
      mainPanel(uiOutput("graph"))

    )
  )
))

server <- function(input, output, session) {

  output$graph <- renderUI({
    # create tabPanel with datatable in it
    req(input$year)
    tabPanel("Plots",
             fluidRow(lapply(as.list(paste0("plot", seq_along(input$year))), plotOutput)))

  })

  output$checkbox <- renderUI({
    if (input$Choose == "p") {
      checkboxGroupInput("Cross",
                         "Year",
                         choices = (unique(d$year)))

    } else{
      checkboxGroupInput("Cross_1",
                         "Numbers",
                         choices = c("1","2","3"))
    }

  })

}

shinyApp(ui, server)

Now the challenge which I am facing is when i choose the "Year" Radio button the year values get displayed as check boxes and when i select the check boxes a corresponding graphs get displayed in the main panel (I have not given the code over here). Now when I choose the "Number" Radio Button the correct check box options are getting displayed. But when I move back to the "Year" Radio button. The already selected check box values are not retained so the user needs to check the boxes again to get the corresponding graphs.
The choices in CheckboxGroupInput() are dynamic in my case. So i will not be able to give this choices in UI(). Also i tried using updateCheckboxGroupInput() which failed. By doing some investigations in to the code once again, I understood that the place where the issue is taking place is this part of the code.
  output$checkbox <- renderUI({
    if (input$Choose == "p") {
      checkboxGroupInput("Cross",
                         "Year",
                         choices = (unique(d$year)))

    } else{
      checkboxGroupInput("Cross_1",
                         "Numbers",
                         choices = c("1","2","3"))
    }

  })

Please suggest me on how to retain the values in the checkbox even when the another radio button is chosen. Also please be informed that the options of Check boxes under each radio button will change according to the options the user has selected in the previous tab. So i use observe function to obtain the corresponding check boxes.

A: You could store the values of the years you attempt to keep in reactive values.
  global <- reactiveValues(years = NULL)

  observeEvent(input$Cross, {
    global$years <- input$Cross
  })

Then you make your dynamic ui dependent on the reactive values:
checkboxGroupInput(
  "Cross",
  "Year",
  choices = (unique(d$year)),
  selected = global$years
)

Reproducible example:
library(shiny)
library(shinydashboard)
library(shinyWidgets)

d <-
  data.frame(
    year = c(1995, 1995, 1995, 1996, 1996, 1996, 1997, 1997, 1997),
    Product_Name = c(
      "Table",
      "Chair",
      "Bed",
      "Table",
      "Chair",
      "Bed",
      "Table",
      "Chair",
      "Bed"
    ),
    Product_desc = c("X", "X", "X", "Y", "Y", "Y", "Z", "Z", "Z"),
    Cost = c(1, 2, 3, 4, 2, 3, 4, 5, 6)
  )

ui <- shinyUI(fluidPage(
  useShinydashboard(),
  tabPanel(
    "Plot",
    sidebarLayout(
      sidebarPanel(
        radioButtons(
          "Choose",
          "Choose One",
          c("Year" = "p", "Numbers" = "l")
        ),
        uiOutput('checkbox'),
        #width = 2,
        position = "bottom"),
      mainPanel(uiOutput("graph"))

    )
  )
))

server <- function(input, output, session) {

  global <- reactiveValues(years = NULL)

  observeEvent(input$Cross, {
    global$years <- input$Cross
  })

  output$graph <- renderUI({
    # create tabPanel with datatable in it
    req(input$year)
    tabPanel("Plots",
             fluidRow(lapply(as.list(paste0("plot", seq_along(input$year))), plotOutput)))

  })

  output$checkbox <- renderUI({
    if (input$Choose == "p") {
      checkboxGroupInput("Cross",
                         "Year",
                         choices = (unique(d$year)),selected = global$years)

    } else{
      checkboxGroupInput("Cross_1",
                         "Numbers",
                         choices = c("1","2","3"))
    }

  })

}

shinyApp(ui, server)

I think the shinyjs hide/show variant of Ash is also interesting. I havent tested it but i assume you could just replace the static ui with a dynamic there (?).

A: I'd suggest showing/hiding the checkboxs rather than using renderUI. This way they will retain their settings even when they are not shown.
shinyjs is a popular package that can do this for us. I've created a minimal example based on the above code to show this in action:
library(shiny)
library(shinyjs)

ui <- shinyUI(fluidPage(

    useShinyjs(),

    radioButtons("radio_choose", "Choose One", choices = c("Year", "Numbers")),

    checkboxGroupInput("checkbox_years", "Year", choices = c(1995, 1996, 1997, 1997)),

    checkboxGroupInput("checkbox_numbers", "Numbers", choices = c(1, 2, 3))

))

server <- function(input, output, session) {

    #Observe the radio buttons (runs when the radio button changes)
    observeEvent(input$radio_choose, {

        if(input$radio_choose == "Year") {

            shinyjs::show("checkbox_years")
            shinyjs::hide("checkbox_numbers")

        }

        if(input$radio_choose == "Numbers") {

            shinyjs::hide("checkbox_years")
            shinyjs::show("checkbox_numbers")

        }

    })

}

shinyApp(ui, server)

A: Here is my approach to this, using hidden from shinyjs. I've also added default selection to be empty so there is no ambiguity in reactivity. Do try to avoid using numerical variables on their own in names, such as "1", "2" and so on
library(shiny)
library(shinydashboard)
library(shinyWidgets)
library(shinyjs)

d <- data.frame(
    year = c(1995, 1995, 1995, 1996, 1996, 1996, 1997, 1997, 1997),
    Product_Name = c("Table","Chair","Bed","Table","Chair","Bed","Table","Chair","Bed"),
    Product_desc = c("X", "X", "X", "Y", "Y", "Y", "Z", "Z", "Z"),
    Cost = c(1, 2, 3, 4, 2, 3, 4, 5, 6)
)

ui <- shinyUI(fluidPage(
    useShinyjs(),
    useShinydashboard(),
    tabPanel("Plot",
             sidebarLayout(
                 sidebarPanel(
                     radioButtons("Choose","Choose One", c("Year" = "p", "Numbers" = "b"),selected = character(0)),
                     uiOutput('checkbox'),
                     position = "bottom"),
                 mainPanel(
                     uiOutput("graph")
                 )

             )
    )
))

server <- function(input, output, session) {

    output$checkbox <- renderUI({
        hidden(
            tagList(
                checkboxGroupInput("Cross","Year",choices = (unique(d$year))),
                checkboxGroupInput("Cross_1","Numbers",choices = c("1","2","3"))
            )
        )
    })

    observeEvent(input$Choose,{
        toggleElement(id = "Cross", condition = input$Choose == "p")
        toggleElement(id = "Cross_1", condition = input$Choose == "b")
    })

}

shinyApp(ui, server)

Alternatively, since radioButtons default to select the first value you can hide the second element:
ui <- shinyUI(fluidPage(
    useShinyjs(),
    useShinydashboard(),
    tabPanel("Plot",
             sidebarLayout(
                 sidebarPanel(
                     radioButtons("Choose","Choose One", c("Year" = "p", "Numbers" = "b")),
                     uiOutput('checkbox'),
                     position = "bottom"),
                 mainPanel(
                     uiOutput("graph")
                 )

             )
    )
))

server <- function(input, output, session) {

    output$checkbox <- renderUI({
        tagList(
            checkboxGroupInput("Cross","Year",choices = (unique(d$year))),
            hidden(checkboxGroupInput("Cross_1","Numbers",choices = c("1","2","3")))
        )
    })

    observeEvent(input$Choose,{
        toggleElement(id = "Cross", condition = input$Choose == "p")
        toggleElement(id = "Cross_1", condition = input$Choose == "b")
    })

}

shinyApp(ui, server)


text:
Q: How Reuse My Qt Quick Controls in Multiple project like c++ library? I have read article Adding Libraries to Projects for Reusing my c++ classes in my diffrent qt quick applications,
I have many Custom qml types Like MyCustomGridView.qml and I using this in many project But I have to copy the file in my new Project and When I extend this in one project I have to make change by hand in all proejcts.
My question is How can I reuse this qml types like c++ library in diffrent projects?


text:
Q: Where and how to store data locally using $.post I am using this code to edit data on table ,this is allowing me to edit data ,but I am not able to find that where and how should I store data locally on that form itself ,if i don't want to store it in database, I want to know what this "/somewhere" should be(url or some file or what).

    Something

$("#mylist_remark .editable").bind("blur", function(e) {
  console.log($(e.target).text());
  $.post("/somewhere", {remark: $(e.target).text(), candidate_id: $(e.target).nearest("tr").attr("id")}, function() { console.log("success"); });
   });

A:
... how should I store data locally on that form itself ,if i don't want to store it in database...

One solution would be to use localStorage to save the form elements locally.
If you felt like using jQuery, you could make the problem simple:
$("input").change(function(){
    var input = $(this).val();
    localStorage.setItem("input",input);
}

Then when the page loads, you set the val to the localStorage item:
var input = localStorage.getItem("input");
$("input").val(input)

More on localStorage, and even more on localStorage.


text:
Q: C programming: Detect mouse pointer movement I am working on a project in which I need to set a flag only when mouse pointer has not moved for a period of time (e.g: 30s): if the mouse was idle for 30s, set no_movement (no_movement=true;).
So far, I know the X window server is the backend for many desktop environment and I know there is a comprehensive documentation for it on x.org and tronche.com (I got it from there that there is an event for pointer called MotionNotify).
Using apt show xserver-xorg | grep Version I found out the Xserver version installed on my system is 1:7.7+22ubuntu1 (on Ubuntu 21.04)
What is the recommended way to get mouse pointer movement feedback?
Appreciate your time responding me.

A: X11 is pretty well documented for 'Event masks'
https://tronche.com/gui/x/xlib/events/mask.html
Or there is always XQueryPointer)..
// Try this C program as the basis of what you want todo..

    #include <stdio.h>
#include <assert.h>
#include <X11/Xlib.h>
#include <X11/extensions/XInput2.h>

int main(int argc, char **argv)
{
    Display *display;
    Window root_window;

    /* Initialize (FIXME: no error checking). */
    display = XOpenDisplay(0);
    root_window = XRootWindow(display, 0);

    /* check XInput */
    int xi_opcode, event, error;
    if (!XQueryExtension(display, "XInputExtension", &xi_opcode, &event, &error)) {
        fprintf(stderr, "Error: XInput extension is not supported!\n");
        return 1;
    }

    /* Check XInput 2.0 */
    int major = 2;
    int minor = 0;
    int retval = XIQueryVersion(display, &major, &minor);
    if (retval != Success) {
        fprintf(stderr, "Error: XInput 2.0 is not supported (ancient X11?)\n");
        return 1;
    }

    /*
     * Set mask to receive XI_RawMotion events. Because it's raw,
     * XWarpPointer() events are not included, you can use XI_Motion
     * instead.
     */
    unsigned char mask_bytes[(XI_LASTEVENT + 7) / 8] = {0};  /* must be zeroed! */
    XISetMask(mask_bytes, XI_RawMotion);

    /* Set mask to receive events from all master devices */
    XIEventMask evmasks[1];
    /* You can use XIAllDevices for XWarpPointer() */
    evmasks[0].deviceid = XIAllMasterDevices;
    evmasks[0].mask_len = sizeof(mask_bytes);
    evmasks[0].mask = mask_bytes;
    XISelectEvents(display, root_window, evmasks, 1);

    XEvent xevent;
    while (1) {
        XNextEvent(display, &xevent);

        if (xevent.xcookie.type != GenericEvent || xevent.xcookie.extension != xi_opcode) {
            /* not an XInput event */
            continue;
        }
        XGetEventData(display, &xevent.xcookie);
        if (xevent.xcookie.evtype != XI_RawMotion) {
            /*
             * Not an XI_RawMotion event (you may want to detect
             * XI_Motion as well, see comments above).
             */
            XFreeEventData(display, &xevent.xcookie);
            continue;
        }
        XFreeEventData(display, &xevent.xcookie);

        Window root_return, child_return;
        int root_x_return, root_y_return;
        int win_x_return, win_y_return;
        unsigned int mask_return;
        /*
         * We need:
         *     child_return - the active window under the cursor
         *     win_{x,y}_return - pointer coordinate with respect to root window
         */
        int retval = XQueryPointer(display, root_window, &root_return, &child_return,
                                   &root_x_return, &root_y_return,
                                   &win_x_return, &win_y_return,
                                   &mask_return);
        if (!retval) {
            /* pointer is not in the same screen, ignore */
            continue;
        }

        /* We used root window as its reference, so both should be the same */
        assert(root_x_return == win_x_return);
        assert(root_y_return == win_y_return);

        printf("root: x %d y %d\n", root_x_return, root_y_return);

        if (child_return) {
            int local_x, local_y;
            XTranslateCoordinates(display, root_window, child_return,
                                  root_x_return, root_y_return,
                                  &local_x, &local_y, &child_return);
            printf("local: x %d y %d\n\n", local_x, local_y);
        }
    }

    XCloseDisplay(display);

    return 0;
}


text:
Q: Arch Linux fails to tty I'm trying to boot Arch Linux from a USB drive, but I cannot open pacman or whatever. I've downloaded the Arch Linux .ISO file and put it on a USB using Rufus, but it fails to load properly. I am still new to this Linux distro.
Waiting 30 seconds for device /dev/disk/by-label/arch_201509
Error :'/dev/disk/by-label/arch_201509' device did not show up after 30 seconds...
Falling back to interactive prompt
You can try to fix the problem manually, log out when finished
sh: can't access tty ; job control turned off

A: I guess the question is "Why doesn't the Arch Linux installation commence"? Then the likely answer is that the boot disk is labelled something other than "arch_201509". You can verify that by running ls /dev/disk/by-label/arch_201509. The solution is to change the disk label to the required one.


text:
Q: How to execute mssql script directly from file with Golang I have been looking around for the answer to the question above with no luck. Excuse me if it is a duplicate. So basically I am trying to execute a sql script directly from file but I keep on getting the  " Incorrect syntax near ''. " error
func AnotherDatabase() (sql.Result, error) {
     rc, err := os.Open("./myscript.sql")
     if err != nil {
        return nil,err
     }
     buf := new(bytes.Buffer)
     buf.ReadFrom(rc)
     contents := buf.String()

     db, err := sql.Open("mssql", "mydatabase")
     if err != nil {
       return nil,err
     }
     defer db.Close()

     res, err := db.Exec(contents)
     if err != nil {
       return nil,err
     }
    return res,nil
}

A: I have realized the illegal character causing issues was probably an extended ASCII character so I used the below method to strip off unnecessary characters from the file contents :
func stripCtlAndExtFromBytes(str string) string {
  b := make([]byte, len(str))
  var bl int
  for i := 0; i < len(str); i++ {
    c := str[i]
    if c >= 32 && c < 127 {
      b[bl] = c
      bl++
     }
 }
 return string(b[:bl])
}

as stated here https://rosettacode.org/wiki/Strip_control_codes_and_extended_characters_from_a_string#Go


text:
Q: Fill row with color after copy to new sheet I was able to do minimum changes to some coding I found off bits here and there. But I am at wits so I hope I can received some help with this line of VBA code please :
With Worksheets(3)
    Worksheets(1).Range(Worksheets(1).Cells(intCopyRow, 1), _
        Worksheets(1).Cells(intCopyRow, bytColumnsInData)).Copy _
    Destination:=.Cells(.Cells.Rows.Count, 1).End(xlUp).Offset(1, 0)
End With

I hope to add color to the row after I copy the mismatch row to the new sheet3. How should I go about changing this code to do the adding of color?

A: Add this line perhaps?
' colors the row Red
.Cells(.Rows.Count, 1).End(xlUp).EntireRow.Interior.Color = RGB(255, 0, 0)


text:
Q: Hosted tool for software license usage? I have a downloadable software product that I'd like to instrument with tracking so that I know how many people are using it.  I want data something like:
183 unique installations used on October 7, 2011
187 unique installations used on October 8, 2011
...

I do NOT need to know anything else about the users:  not the domain, not a license key, nothing.
This is a J2EE app with a web UI so I could use a Google Analytics-style tracking bug.  However, I've experimented with various permutations of GA page tracking and event tracking and haven't found a robust way to count the # installations used per day.
Is there a hosted service out there that offers this?  Some other approach to suggest?
Thanks!

A: If you want to track unique installations per day, you need to create a unique key per installation per day and then you can track this. If that unique then contains the information as well to which date it belongs to, then the only thing you need to do it to log the keys somehow and then remove the duplicates.
The number of unique keys you will be able to identify per day are the unique installation used on that day.
It should be quite trivial to setup a webservice for that.

A: I figured out a way to do this with Google Analytics, though it's real hacky and I'd prefer a better solution.
Pick a web page that is always going to be hit on the installed system (like the front door).  Fire a Google Analytics event of the format:

*

*Event Category: "SystemID"

*Event Name: [Actual System ID]

In the Google Analytics UI, go to event tracking and create a search that returns all the events in the SystemID category.   The pagination will tell you how many unique system IDs there are. For example:  "Showing events 1 -15 of 15,000 in category SystemID".
I couldn't find anything saying how many unique events Google supports, but Google says it supports collecting up to 50,000 unique URLs a day per profile.  Let's assume that applies to events, too.  So you can set up a profile just for tracking this event, and it may last you up to 50,000 software installs.
Like I said, it's extremely hacky and I'd prefer a better solution, but it's gotta be one that's hosted and cheap to be better than this.


text:
Q: Why do my C# Form closed when displayed? i have 2 forms, those are form1.cs and form2.cs
on the form1, it has button1, which will call form2 to show
here's the button1 code
private void button1_Click(Object sender, EventArgs e )
{
form2 form = new form2();

form2.show();   // to call form2

this.dispose(); //to dispose form1

}

and then form2 showed, and it closed suddenly. anyone know how to solve this ?

A: When you close your main form with this.dispose() you are terminating the program causing form2 to be disposed also because you are diposing the reference to form2. You would be better off passing a reference to your form1 to form2 and using this.Hide() instead.
You can try something like this:
 public partial class Form1 : Form
    {

        public Form1()
        {
            InitializeComponent();
        }

        private void button1_Click(object sender, EventArgs e)
        {
            Form2 form = new Form2();
            form.setParent(this);
            form.Show();
            this.Hide();

        }
    }

And in form2 to go back to form1
public partial class Form2 : Form
    {
        Form parentForm;
        public Form2()
        {
            InitializeComponent();
        }

        public void setParent(Form value)
        {
            parentForm = value;
        }

        private void button1_Click(object sender, EventArgs e)
        {
            parentForm.Show();
            this.Close();
        }
    }

A: private void button1_Click(Object sender, EventArgs e )
{
form2 form = new form2();

form2.show();   // to call form2

this.hide(); //to hide form1

}

A: if form1 is program starter then application will close . Hence instead
this.dispose();

U just write
this.hide();

A: Show() does not wait for form2 to close before continuing to the next command (dispose).
This will end up in closing form2 because it's probably running on a background thread.
Use ShowDialog to hold the execution of Dispose until the second form closes.
Also, you can set the second form to run on a foreground thread. This way the second form will not be dependent on the life of the first.

A: You can either use this.Hide() which should hide your current form or use a thread to open the new form.
Example: C# open a new form, and close a form...


text:
Q: how to properly pytest a function with the same code used to seed a module scope fixture I have a fixture I created that pulls data from a database and puts it into a DataFrame so all subsequent tests can run on the same query output.  The same code is staged in a function that kicks of my data processing pipeline (which I am building all these tests around).  I am not sure I want to mock the db query result because I want to test the returned column names from the query and record uniqueness among other things.
Where I am confused is how to properly test the function I have in my code that is doing the same thing as the output_data fixture.  Is it proper to duplicate the code in my app for the fixture?
# df_service.py
from project.settings import MSSQL_DB_CON_STR as con

def df_from_sql(start_date, months):
    sql = f"SELECT * FROM dbo.awesome_table_value_function('{start_date}', {months})"
    return pd.read_sql(sql=sql, con=con)

Here is the fixture I started with before I recognized I am creating a fixture for functionality I actually want to test and use as a fixture.
# test_df_service.py

import pytest
import pandas as pd

@pytest.fixture(scope="module")
def output_data():
    from project.settings import MSSQL_DB_CON_STR as con

    start_date = "11/1/2019"
    months = 4
    sql = f"SELECT * FROM dbo.awesome_table_value_function('{start_date}', {months})"
    return pd.read_sql(sql=sql, con=con)

    return pd.read_sql(sql=sql, con=con)

def test_columns(output_data):
    expected_columns = ['entity','attribute','value','effective_date']
    df = output_data
    for col in df.columns:
        assert col in expected_columns

A: So, one way you could go about this is the following:
Since the df_from_sql() function is within the domain of your application, it should be also a function you actually want to test. So, I would write a pytest test for the function, asserting things like Does it return X number of columns or Is the number of rows > 0, etc (if you cannot guarantee to return the same data every time).
I see why you would want to use the function to create a fixture, however that introduces the following risks:

*

*The function to get the data for some reason doesn't work. Then all your tests might fail because your ouput data is not what they expected.

*The data in the database might change, so you would get different results to what you expected.

In theory, fixtures are supposed to be as fixed in space and time as possible, so what I would recommend is to actually save the data that you need as the output_data fixture in some file, or maybe in a mock table in your database, ensuring it will never change.


text:
Q: given - when statement doesn't work properly ('Learning Perl' Chapter 15 issue) The example of using the given-when statement presented in chapter 15 of the  "Learning Perl" book does not work properly.
I'm using Perl v5.22.1. and I tried to reproduce the following code (see "Learning Perl", fifth edition, page 227.):
    use 5.010;
    given ($ARGV[0])
    {
       when(/fred/i) {say "Name has fred in it"; continue}
       when(/^Fred/) {say "Name starts with Fred"; continue}
       when('Fred')  {say "Name is Fred";}
       default {say "I don't see a Fred"}
    }

When I run the script, I get the following result:
D:\>Perl D:\Perl\Example113.pl Frederick
given is experimental at D:\Perl\Example113.pl line 5.
when is experimental at D:\Perl\Example113.pl line 7.
when is experimental at D:\Perl\Example113.pl line 8.
when is experimental at D:\Perl\Example113.pl line 9.
Name has fred in it
Name starts with Fred
I don't see a Fred

As you can see, the default block works contrary to expectations.
At the same time if you swap first and last blocks 'when', it is works almost as described in the book:
    use 5.010;
    given ($ARGV[0])
    {
       when('Fred')  {say "Name is Fred"; continue}
       when(/^Fred/) {say "Name starts with Fred"; continue}
       when(/fred/i) {say "Name has fred in it"; }
       default {say "I don't see a Fred"}
    }

What gives us the next output:
D:\>Perl D:\Perl\Example113.pl Frederick
given is experimental at D:\Perl\Example113.pl line 5.
when is experimental at D:\Perl\Example113.pl line 7.
when is experimental at D:\Perl\Example113.pl line 8.
when is experimental at D:\Perl\Example113.pl line 9.
Name starts with Fred
Name has fred in it

Am I doing something wrong or in the book is an incorrect example?

A: First, while exploration and play is good I must repeat what perlsyn says

As previously mentioned, the "switch" feature is considered highly
    experimental; it is subject to change with little notice.

If that isn't enough, here is a bit more, earlier in perlsyn

Exactly what the EXPR argument to when does is hard to describe
      precisely, but in general, it tries to guess what you want done. Sometimes
      it is interpreted as $_ ~~ EXPR, and sometimes it does not. It also
      behaves differently when lexically enclosed by a given block than it
      does when dynamically enclosed by a foreach loop. The rules are far too
      difficult to understand to be described here. See Experimental Details on
      given and when later on.

I don't know what to think about a feature which "is hard to describe precisely." Also note that "Most of the power comes from the implicit smartmatching" (same page). What matters is that it seems crystal clear that this will change, and very likely significantly.
Having cleared that up, the behavior you show is expected. From the example in perlsyn

given ($foo) {
    when (undef) {
        say '$foo is undefined';
    }
    when ("foo") {
       say '$foo is the string "foo"';
    }
    ...
}

where $foo need be equal to the string "foo", not matched by it; this isn't a regex match but string equality.
In  your examples the string 'Fred' is not equal to Frederick. In the second one there is that continue so it does go to the next branch, but in the first one there isn't (while it's also last before default). Run the program with input Fred to see.

A: Without continue, when and default exit the surrounding given or move to the next item of the surrounding for.
With continue, execution proceeds with the next statement.
The default block is unconditionally executed when reached.

For example,
given ($ARGV[0]) {
    say "Checking for 'x'";
    when (/x/) { say 'contains an x'; continue; }
    say "Checking for 'y'";
    when (/y/) { say 'contains a y';            }
    default    { say 'does not contain a y';    }
}

For y:
Checking for 'x'
Checking for 'y'
contains a y

For x:
Checking for 'x'
contains an x
Checking for 'y'
does not contain a y

For xy:
Checking for 'x'
contains an x
Checking for 'y'
contains a y


text:
Q: How to correct sas dates after concatenating them compute calc1 /  character length=250 ;
name= 'new date';
calc1 = cats(PUT(_C4_,date9.),' ^n',PUT(_C5_,date9.),' ^n',PUT(_C6_,date9.));
endcomp;

I used the above code, but for some reason som dates are completely off.
This is an example of  the incorrect dates in the proc report output. Also the same column will have correct dates.
23AUG2068
21DEC2068
Any suggestions how to correct the dates?
Thanks,

A: If you have date times use dtdate9. format instead of date9.
calc1 = cats(PUT(_C4_,dtdate9.),' ^n',PUT(_C5_,dtdate9.),' ^n',PUT(_C6_,dtdate9.));

A: Are you sure _C4_, _C5_ and _C6_ are dates, as opposed to datetimes or times?
Also, I'd try using putn instead of put.


text:
Q: Unable to resize second background space I am just beginning with web coding now and I do apologize for any nonsense things I might come up with.
I am trying to modify a template of a website. This website is divided in two background pictures, one is for the top that goes a bit beyond the middle of the page, and the other one is supposed to be for the bottom of the page.
What I am trying to do is to make the top background picture come further down close to the bottom navigation bar, and than let the second background picture to seat on the bottom of the page where the bottom navigation bar is.
Here is the complete CSS http://pastebin.com/h2KdKtdq
The top background picture part is
.bg1 {background:url(../images/bg1.gif) center 0 repeat-x; min-height:100%;}

While the bottom background picture part
body {
background:url(../images/bg.gif) 50% 0 repeat;
font-family:Arial, Helvetica, sans-serif;
font-size:12px;
line-height:18px;
color:#978e83;
min-width:1003px;
}

What's strange is that whatever I do to the bottom picture part in the CSS wont take any effect, while if I touch the top picture part it will simply mess out the whole layout.
So far I haven't found any options to make the space of the bottom background part coming any further dow, and I am literally stuck into this.
Here's how the style looks now

Thanks

A: Since you say you're new to coding, I'm trying to simplify as much as possible. Forgive me if I've oversimplified.
I actually just wrote out a long explanation and then noticed the address bar is visible in your image - I checked the site and the top and bottom are actually both in bg1.gif. The body background image is just more of the same bottom color to cover past where the bottom of bg1.gif goes.
So there's a simple solution:
    .bg1{background-size: 100% 150%;}

Just change the second value and the size of the color blocks will shift. All it does is scale the background and since, in this case, the background is simple colors it shouldn't have much of a problem interpolating the image.
This is the easiest way to fix your immediate problem. Ideally, you'd code the whole background differently. I'll post another response below with how to do this.

EDIT: I just noticed that there is a small line between the colored areas and there is a barely perceptible texture to the color areas - regardless my above solution still works, with slight distortion. So long as you aren't stretching too much, you should be ok.
If you want to do this without any distortion, the easiest solution is to just edit the image and add more space on the top. Editing the image is a good idea anyway because the way the background is currently formatted uses a lot of overhead. The background is 1309px x 1228px but it could just be 10 px wide with repeat-x. That alone could reduce the file size from 851kb to ~10kb.


text:
Q: Extract numbers from string and add them with php I have a long string like below:
$string = "age1:32,age2:25,age3:52,..."
Now I want to extract the age numbers in this string and then add the numbers together and determine the average age.
I was able to extract the numbers with the help of the following code
$numbers = preg_replace('/[^0-9]/', '', $string );
but the output I get is like this and I cannot add the numbers together.
output:
322552

A: Using preg_match_all to find all age values followed by array_sum to find the total/average we can try:
$string = "age1:32,age2:25,age3:52,...";
preg_match_all("/age\d+:(\d+)/", $string, $matches);
print_r(array_sum($matches[1]) / count($matches[1]));  // 36.333333333333

A: *

*Restart the fullstring match after each colon, then match one or more digits.

*preg_match_all() returns the number of matches ($count).

*Divide the sum of the matches by the number of matches.

Code: (Demo)
$string = "age1:32,age2:25,age3:52,...";
$count = preg_match_all('/:\K\d+/', $string, $m);
echo array_sum($m[0] ?? []) / $count;
// 36.333333333333

If you wanted to grab all numbers, just use \d+. (Demo)
$string = "available12available15available22available11...";
$count = preg_match_all('/\d+/', $string, $m);
echo array_sum($m[0] ?? []) / $count;


text:
Q: Prove the inequality: $a^2+b^2+1≥ab+a+b$ Prove the inequality.
$a^2+b^2+1≥ab+a+b$
I try so many methods, But I have not been successful in any way.Because, I can not find "hint".

A: $$a^2+b^2+1-ab-a-b=\frac{1}{2}((a-b)^2+(a-1)^2+(b-1)^2)\geq0$$

A: This is the $c=1$ case of
$$a^2+b^2+c^2\ge ab+ac+bc.$$
One only needs to prove this for $a$, $b$, $c\ge0$.

A: If $b=1$ it becomes $a^2-2a+1\ge 0$
which is true.
assume $b\ne 1$.
It is equivalent to prove that
$$a^2-a (b+1)+b^2+1-b>0$$
$$\Delta=b^2+2b+1-4b^2-4+4b $$
$$=-3(b^2-2b+1)=-3 (b-1)^2<0$$
Done.

A: All of the quantities on the left are $+ve$ ...
\begin{eqnarray*}
(a-b)^2+(a-1)^2+(b-1)^2 \geq 0
\end{eqnarray*}
divide by $2$ & rearrange ... the inequality follows.

A: Move all to left: $$a^2+b^2+1-ab-a-b\ge 0$$
Find the minimum value of $f(a,b)=a^2+b^2+1-ab-a-b$ using partial differentiation:
$f_a=2a-b-1=0$
$f_b=2b-a-1=0$
$a=b=1$
$f_{aa}=2>0, f_{bb}=2>0, f_{aa}f_{bb}-f_{ab}^2=3>0 \Rightarrow f(1,1)=0$ is minimum.


text:
Q: select ... from select - subquery with Core-Data Is is possible to perform a SELECT ... FROM SELECT query with Core-Data ?
I'm working on just one entity.
Of course I can work with the Dictionary result but I would prefer to make a complicated query which returns a ready-to-go result
EDIT :
Here is the query I want to perform
SELECT zcp, sum(zce), sum(zce)*100/zcpva, sum(zce)/
   (SELECT sum(zis)
    FROM (
       SELECT zis
       FROM zbma
       GROUP BY zim, zis)
    )
FROM zbma
GROUP BY  zcp, zcpva;


text:
Q: Android 5.0+ AudioManager setMode not working i am working on AudioManager which is a Android SystemService.
with Android System 5.0+ , i encounter a problem which AudioManager the setMode method is not working .
i through a test ,
Android M, Lollipop.. 5.0+ version ,  AudioManager setMode is not working .
example :
public void initAudioImageIcon(boolean initLoad) {
    boolean isAudioHeaderMode = IMSharedPreferences.getBooleanExtra(this, IMSPConstant.SP_NAME_MESSAGE,
            IMSPConstant.SP_KEY_AUDIO_HEADER_MODE);

    if (isAudioHeaderMode) {
        mAudioHanderMode.setVisibility(View.VISIBLE);
        // audioManager.setMode(AudioManager.MODE_IN_CALL) , but android system 5.0+ no any change, getMode() == AudioManager.MODE_NORMAL
        setAudioMode(AudioManager.MODE_IN_CALL);
        audioManager.getStreamMaxVolume(AudioManager.STREAM_VOICE_CALL);
        if (!initLoad) {
            showAudioModePrompt(this.getText(R.string.im_audio_in_call), 1000);
        }
    } else {
        mAudioHanderMode.setVisibility(View.GONE);
        setAudioMode(AudioManager.MODE_NORMAL);
        if (!initLoad) {
            showAudioModePrompt(this.getText(R.string.im_audio_in_speeker), 1000);
        }
    }
}

but Android 3.0+,4.0+ is ok ,only 5.0+ .
so ,i don`t know where happen mistakes.

A: With audio mode set to :
setMode(AudioManager.MODE_IN_COMMUNICATION);
setSpeakerphoneOn(false);

while my audio stream is set to STREAM_MUSIC I can easily route audio to earpiece. I have tested it myself in AOSP Lollipop code.
Here in the question you have never mentioned about your stream type. Do set your stream to STREAM_MUSIC or STREAM_VOICE_CALL and the code should work for you too.

A: In android Lollipop setAudioMode(AudioManager.MODE_IN_CALL) is restricted. It can be used only by system application with MODIFY_PHONE_STATE permission. However you can use MODE_IN_COMMUNICATION and MODE_NORMAL in normal applications.


text:
Q: Pull-back of tangent bundles Let's consider two manifolds M and N.
I am trying to figure out if it is true that the tangent bundle of the product $M\times N$ is isomorphic to the cartesian product of the pullbacks of the tangent bundle through the projections.
In formulae:
$T(M\times N)\cong \pi_M^*(TM)\times\pi^*_N(TN)$
I think that is the case but I'm quite struggling proving it.


text:
Q: How to run rails server - execute wkhtmltopdf - stop rails server I've been long time investigating how to generate complex .pdf files (many images and 30 pages aprox). from a html web, of my rails application.
At the end I realized than the best option is wkhtmltopdf from command line.

*

*using pdfKit gem don't work in production, but it works in development

*using wkhtmltopdf from command line, works in development but neither in production.

I have read a lot of issues with wkhtmltopdf, so I abandon use wkhtmltopdf getting info from production web server. --> Instead I have created a new environment "genera_pdf" to run in production database, with development configuration (assets, cache..etc)
And now I need to run some proces than execute this:
1) RAILS_ENV=genera_pdf rails s
2) wkhtmltopdf localhost:3000 result.pdf
3) stops (CTRL+C) rails s
If this is achievable, Whats the best way to do this in Linux?
I'm absolutly missed...with rake tasks? or rails runner? or Cron-task?
Thanks a lot


text:
Q: Determinants and volume of parallelotopes The absolute value of a $2 \times 2$ matrix determinant is the area of a corresponding parallelogram with the $2$ row vectors as sides.
The absolute value of a $3 \times 3$ matrix determinant is the volume of a corresponding parallelepiped with the $3$ row vectors as sides.
Can it be generalized to $n-D$? The absolute value of an $n \times n$ matrix determinant is the volume of a corresponding $n-$parallelotope?

A: Yes it can. In fact, as Jamie Banks noted, a determinant is an intuitive way of thinking about volumes. To summarise the argument, if we consider the vectors as a matrix, switching two rows, multiplying one by a constant or adding a linear combination will have the same effect on the volume as on the determinate. We can use these operations to transform any n-parallelotope to cube and note that the determinate matches the signed volume here, so it will match it everywhere as well.

A: Yes--see the Wikipedia article.
This follows from the change of variables formula with the Jacobian. However, it is probably more accurate to say that the change-of-variables formula is a (nontrivial) consequence of this.  One argument for this fact, which is given in Rudin's Real and Complex Analysis, is the fact that both the determinant and the volume function up to sign behave very nicely satisfying certain specific properties (i.e., multilinear, alternating, normalized) hence are the same.

A: Yes, that is because in its most general form the determinate is defined that way, except without the absolute value part. The determinant is a way to compare volumes of subspaces that have the same grade, which is the multi-vector equivalent of the size of matrix.


text:
Q: How can I get a QObject's children? I am trying to get the children of the a QObject class and add their data to the parent (see QML example below). However, when I call the following code in the constructor, it returns no children. It appears that the child list has not yet been populated. It works if I place the same code in the paint() function, but I need the data earlier than that.
MultiGauge::MultiGauge() :
    QQuickPaintedItem()
{
    QObjectList children = this->children();

    for (int i = 0; i < children.length(); i++)
    {
        this->myQList.append(children[i]->metaObject()->className());
    }
}

Here is the QML file
MultiGauge {

    height: 125
    width: height
    Limits {
        min: 0
        caution: 1250
        max: 2000
    }
    Limits {
        min: 100
        caution: 200
        max: 300
    }
}

EDIT: Solution:
MultiGauge::componentComplete()
{
    // must call the parent's version of the function first
    QQuickPaintedItem::componentComplete();

    // now we can do what we need to
    QObjectList children = this->children();

    for (int i = 0; i < children.length(); i++)
    {
        this->myQList.append(children[i]->metaObject()->className());
    }
}

A: You should delay the iteration until the QML object tree is completed. You can that by using
MultiGauge {
  // ...
  Component.onCompleted: doSomeStuff()
}


text:
Q: Inverse square law, but with multiple sources I'm making a raytracing renderer, and I'm implementing lights. I read about the inverse square law, which I'm sure you know as:
$$intensity = \frac{k}{distance^2}$$
So for each point on an object I calculate the intensity like this, where $k$ is the energy of a light. However, what if there are multiple lights? How would I calculate the final intensity of a point?
Before anyone asks, I have searched for this on the web, but haven't found any relevant solutions.
A few solutions I've thought about, are:
$$intensity = \sum_n\frac{k_n}{distance_n^2}$$
So basically summing all of the intensities.
Another option would be
$$intensity = \prod_n\frac{k_n}{distance_n^2}$$
i.e. multiplying the intensities, but I don't think that would work if you consider any of the intensities being 0.
So is there some way of doing this, which I haven't found by googling my title?

A: In optics, the intensity of unpolarized incoherent light (i.e. white light that you would want to use in a raytracer) is additive, so adding together the intensities should work fine for a renderer, as long as you're not worried about things like diffraction or polarization.

A: Your equation
$$intensity = \sum_n\frac{k_n}{distance_n^2}$$
is correct.
"..lumens (and lux and candela etc etc) are linearly additive but perceived brightness is logarithmic."
from:
http://www.candlepowerforums.com/vb/showthread.php?189362-Do-lumens-add-up


text:
Q: Van Dalen "Logic and Structure" Exercise 2.7.4: Find posets $A$ and $B$ such that $A \vdash \sigma$ and $B \vdash \neg\sigma$ for the given $\sigma$. Let $\sigma = \exists x\forall y (x\leq y\lor y\leq x)$. We wish to find posets $A$ and $B$ such that $A \vdash \sigma$ and $B \vdash\neg\sigma.$ I have found the poset $A$. The natural numbers with $\leq$ does this. There exists an $x$ (in fact, for all $x$, but we don't require this), such that every other natural number is either bigger than or equal to $x$ or less than or equal to $x$. This is obvious.
I am struggling with the second portion. Here is my attempt at how I did it. Firstly, I formed the negation of $\sigma$. $\neg\left[ \exists x\forall y (x\leq y\lor y\leq x)\right] \equiv \forall x\exists y(x>y\land x<y).$ In other words, we want a poset such that for all elements in the set, there's another element that's BOTH bigger than it AND less than it. This feels..... impossible. Maybe this is because I'm restricting my view to very common posets like $\mathbb{N},\mathbb{Q},\mathbb{R},...$ but is this possible? This seems to violate the notion of the $\leq$ sign. One element cannot be bigger than AND less than another element. Can someone help with this?
Or.... perhaps this answer is that it doesn't exist. Van Dalen does not word the question in a way such that this is possible.

A: Poset:

A (non-strict) partial order is a binary relation $≤$ over a set $P$ satisfying axioms ... When $a ≤ b$, we say that $a$ is related to $b$. For $a, b$, elements of a partially ordered set $P$, if $a ≤ b$ or $b ≤ a$, then $a$ and $b$ are comparable. Otherwise they are incomparable.

Thus, for $\mathfrak A \vDash \sigma$ we may assume $A = \{ 0,1 \}$ with $\le^{A} = \{ (0,0), (0,1), (1,1) \}$, while for $\mathfrak B \vDash \lnot \sigma$ we may assume $B = \{ 0,1 \}$ with $\le^{B} = \{ (0,0), (1,1) \}$.
The first case is obvious.
For the second case: $\forall x \exists y \ [\lnot (x \le y) \land \lnot (y \le x)]$, we have that $\lnot (0 \le 1)$ as well as $\lnot (1 \le 0)$.


text:
Q: MS Access VBA DSUM Multiple Criteria I've been trying variations of this for a couple of hours and it has me stumped.
I need to count the quantity of something in a table if a different column in the same table = YES. This is what I have...
= DSum("PO_Qty", "DeliveryByMonth_2_tbl", "[LIFNR]='" & [Combo524] & " And [M_0]=YES" & "'")

Any help is appreciated!
MS ACCESS 2010

A: I always find the answer right after I post! The below works perfectly. Stupid syntax error.
Me.ThisMonth = DSum("PO_Qty", "DeliveryByMonth_2_tbl", "[LIFNR]='" & [Combo524] & "' And [M_0]='YES'")


text:
Q: How to draw social networking graph? I want to implement social networking graph for companies and employees in my PHP CRM System.
Do you know any php related technology or else can do this?
Thanks a lot.
Edit:
chart -> graph

A: If you can install software on your server, check out Graphviz which is great on drawing such diagrams and charts. It is called from the commandline so you have to use shell_exec in PHP.
Update: I made this example page: http://lajm.eu/emil/dump/graphviz/

A: http://pchart.sourceforge.net/

A: Prefuse library: both Java and Flex implementations. You could serve an applet from your PHP system.


text:
Q: How to correctly open a FileStream for usage with an XDocument I want to append some nodes to an xml document using Linq2XML. The file in question is being used by other processes and they should be able to read the file while I update it. So I came up with this solution, which obviously isn't the correct way (The method doc.Save() fails and says that another process is using the file):
using (FileStream fs = new FileStream(filename, FileMode.Open, FileAccess.ReadWrite, FileShare.Read))
{
  doc = XDocument.Load(new StreamReader(fs));
  doc.Root.Add(entry);
  doc.Save(filename);
  fs.Close();
}

Any help is greatly appreceated.

A: Load the document, close the stream, save it again. That also means you can open it in a simpler way :)
XDocument doc;

using (StreamReader reader = File.OpenText(filename))
{
  doc = XDocument.Load(reader);
  doc.Root.Add(entry);
}

doc.Save(filename);


text:
Q: Какой способ использования метода .appendTo() правильнее? Способ 1:
var $root = "#wrap",
$item1 = "arr111",
$item2 = "arr112",
$item3 = "arr113";
$("#"+$item1+", label[for='"+$item1+"'], #"+$item2+", label[for='"+$item2+"'], #"+$item3+", label[for='"+$item3+"']").appendTo($root);

Способ 2:
var $root = "#wrap";
arr = ['arr111', 'arr112', 'arr113'];
$.each(arr, function() {
  $("#"+this+", label[for='"+this+"']").appendTo($root);
});

Второй мне нравится гораздо больше, но он медленней в 2,5 раза.
Подскажите какой способ архитектурно правильней.


text:
Q: Using PDO and PHP to insert data from form into MySQL database I'm currently working on taking data from my form "form.php" and sending that to "index.php" where i'm using PDO statements to insert those values into the MySQL database. In MySQL I have it set up where firstname and lastname can not be null because the data is going to be submitted back to website where the First Name + Last Name = Full Name and that full name pops up on the supporters list.
My question is,
If I don't want to set MySQL to accept a NULL value, what should I change in my PHP to accept values from the form and submit that to the database with the value attached to that instance of that specific user? I tried php.net/docs and the other StackOverflow questions didn't fully solve my challenge, any help is greatly appreciated

FORM.PHP
<form action="../index.php" method="post">
      <fieldset class="form-group">
      First Name
      <input type="text" name="firstname" class="form-control" id="firstname" placeholder="First Name">
    </fieldset>

    <fieldset class="form-group">
      Last Name
      <input type="text" name="lastname" class="form-control" id="lastname" placeholder="Last Name">
    </fieldset>

        <fieldset class="form-group">
          Email address
          <input type="text" name="email" class="form-control" id="email" placeholder="Enter email">
          We'll never share your email with anyone else.
      </fieldset>

      <button type="submit" id="form-button" class="btn btn-primary">Submit</button>

    </form>

I am sending that to index.php which is where I am receiving the error!
"Error in connection to databaseSQLSTATE[23000]: Integrity constraint violation: 1048 Column 'firstname' cannot be null"
Here is my index.php code
$form = $_POST;
$id = $form['id'];
$firstname = $form['firstname'];
$lastname = $form['lastname'];
$email = $form['email'];

try {
$db = new PDO("mysql:host=" . DB_HOST. ";dbname=" .DB_NAME .";port=".DB_PORT,DB_USER,DB_PASS);
$db->setAttribute(PDO::ATTR_ERRMODE, PDO::ERRMODE_EXCEPTION);

$add_supporter = $db->prepare("INSERT INTO supporters (id, firstname, lastname, email)
                             VALUES (:id, :firstname, :lastname, :email)");

$add_supporter->bindParam(":id", $id);
$add_supporter->bindParam(":firstname", $firstname);
$add_supporter->bindParam(":lastname", $lastname);
$add_supporter->bindParam(":email", $email);
$add_supporter->execute();

} catch (Exception $e) {
echo "Error in connection to database" . $e->getMessage() . "
";
die();
}

A: If you're new to PHP (or programming in general), here is one of the better tips and I can give for this (and similar) problem(s):
You have already formulated the problem statement. That is not yet (pseudo) code but the first important step:

what would that look like if I validated "firstname" and "lastname" were not empty?

This questions actually contains the solution: You would add validation for those values. Right now, you're not validating the input values but you pass them right along into the database query. In your current case the database validates these values then. From your question I read that you're not confident with that level of validation. You perhaps would consider the validation that is already done in your own words as an error message. But technically, the database-server is guarding the data-structure in your database so that values that are defined to not come in won't come in.
So what is the actual tip that I can give to you? In programming when you have the problem statement (like validate the input values before doing the database interaction), you just pretend you've solved the problem already. By that you move the problem to write the whole solution to your problem out of view and just write the main part of your software as if that is working already. That helps you to divide control-flow problems from data-handling problems. For example your program always needs to have validated values to work but what represents a validated value might change over time.
So in your code you have all form related data grouped together in the $form variable in form of an array. This is the code of your example where you map that $form variable to the parameters of your SQL query:
$id = $form['id'];
$firstname = $form['firstname'];
$lastname = $form['lastname'];
$email = $form['email'];

So before doing such database related actions, you could for example determine whether or not that form validates:
$formIsValid = validate_form($form);
if (false === $formIsValid) {
    // do what needs to be done with an invalid form
} elseif(true === $formIsValid) {
    // do what needs to be done with a valid form (database interaction)
} else {
    throw new UnexpectedValueException('Should never come here');
}

So this is how your code could look like if you would do validation of the form data. But still yet, it does not show how the form is being validated. For sure you need to validate each field of the $form so you need to write it down (defined) the form validation. For example some should not be null, I use the isset statement for that:
function validate_form(array $form)
{
   if (!isset($form['firstname']) {
       return false;
   }

   if (!isset($form['lastname']) {
       return false;
   }

   return true;
}

I hope this gives you the needed pointers to continue with your script.

A: As I said in comments, use a conditional !empty() against your POST arrays.
if( !empty($_POST['var1']) || !empty($_POST['var2'])){

// do something

}

else{

// do something else

}

You can change the ||- OR to an && - AND.

"and submit that to the database with the value attached to that instance of that specific user?"

As for a specific user, use a WHERE clause.
You would need to use a SELECT if you want to query a particular user.

*

*http://dev.mysql.com/doc/refman/5.7/en/select.html
For all Data Manipulation Statements, consult:

*

*http://dev.mysql.com/doc/refman/5.7/en/sql-syntax-data-manipulation.html

To send mail to a particular user:
Pulled from this Q&A Send php mail to user if form submitted and as an example:
$results = $db->prepare("select $user_email from table where ID=$user_ID");

try{

/*YOUR INSERT STATEMENT FROM ABOVE*/

$to=$results;
$subject="Whatever you want your subject to be";
$headers = "From: WHATEVER@WHATEVER.COM\r\n";
$headers .= "Reply-To: WHATEVER@WHATEVER.COM \r\n";
$headers .= "MIME-Version: 1.0\r\n";
$headers .= "Content-Type: text/html; charset=ISO-8859-1\r\n";
$headers .= "MIME-Version: 1.0\r\n";
$headers .= "Content-Type: text/html; charset=ISO-8859-1\r\n";

$message= "WHATEVER MESSAGE";
mail ($to , $subject , $message, $headers);
echo "Your message has been sent";
}
Catch($error){
Do whatever you want here. Add another mail function to let you know that  the post was not accepted, etc.
}

You can also consult this Q&A on Stack:

*

*Select and send mail from my database