text:
Q: MySQL script is executing commented lines The weirdest thing is happening here. I have a script that creates a bunch of sql tables. Here's a quick example:
FileName is create_mydb.sql

    --Drops/Creates table UserGroup
    DROP TABLE IF EXISTS UserGroup;
    CREATE TABLE UserGroup (
        user_group_id int NOT NULL AUTO_INCREMENT,
        user_id int,
        group_id int,
        PRIMARY KEY (user_group_id)
    ) ENGINE=INNODB;

    -- Drops/Creates table Group
    DROP TABLE IF EXISTS Group;
    CREATE TABLE Group (
        group_id int NOT NULL AUTO_INCREMENT,
        group_name varchar(50),
        PRIMARY KEY (group_id)
    ) ENGINE=INNODB;

When I run this from the command line like:
mysql>\. create_mydb.sql

I get errors like this for every comment:
ERROR 1064 (42000): You have an error in your SQL syntax; check the manual that corresponds to your MySQL server version for the right syntax to use near '--Drops/Creates table Group

Any ideas?

A: MySQL Requires that the double-dash comment format be followed by some whitespace or a control character in order to differentiate your comments from potentially valid syntax.
9.6. Comment Syntax

From a "-- " sequence to the end of the line. In MySQL, the "-- " (double-dash) comment style requires the second dash to be followed by at least one whitespace or control character (such as a space, tab, newline, and so on). This syntax differs slightly from standard SQL comment syntax, as discussed in Section 1.8.5.5, "'--' as the Start of a Comment".

1.8.5.5. '--' as the Start of a Comment

MySQL Server 3.23.3 and up also supports a variant of the "--" comment style. That is, the "--" start-comment sequence must be followed by a space (or by a control character such as a newline). The space is required to prevent problems with automatically generated SQL queries


text:
Q: php silently ignoring include on localhost, but not on external server I'm running Ubuntu 10.04 with Apache2 and PHP5.
I have a directory structure like this:
\www\
    \index.php
    \parts
         \head.php
         \body.php

Inside my index.php I have a command
  <?php include("parts/head.php") ?>

and the equivalent for body.
These files both exist and they contain more php and html code.
The only thing that shows up when I test the website on localhost (\var\www) is the html outside of the PHP commands. There is no error message, it's as if the file is included but empty.
It is exactly the same as on the website (not localhost) but it works perfectly on the website. I don't understand what is different. Any help would be appreciated.

A: Check your php.ini file to see if "." is on the path?
You could also try this:
include(basename(__FILE__).'parts/head.php');

A: It's almost always about permissions. When you have something working locally, and then upload and find it doesn't work (include is ignoring file) check the remote files/folders so that you have read/write/execute permissions set as required. (You can do this in FTP) - then run the script again and it should work.

redpajama_set_name: RedPajamaStackExchange


text:
Q: generalisation of Knonecker matrix product In the Kronecker matrix product  $C = A\otimes B$
we have that $C(i,j)=A(i,j)*B$
where the elements $A(i,j)$ are just numeric scalar values.
What if the $A(i,j)$ are matrix operators which act on $B$?  Is there a name for that formalism or matrix product?

A: I don't think that this operation has a name. In fact, this operation can be conveniently with the help of the Kronecker product, e.g. for the $2\times 2$ case the product you give is
$$
\begin{bmatrix}
A_{11} B & A_{12}B\\ A_{21}B & A_{22}B
\end{bmatrix}
$$
which is the same as
$$
\begin{bmatrix}
A_{11} & A_{12}\\ A_{21} & A_{22}
\end{bmatrix}
\begin{bmatrix}
B & 0\\ 0 & B
\end{bmatrix} =
\begin{bmatrix}
A_{11} & A_{12}\\ A_{21} & A_{22}
\end{bmatrix}
(I_2\otimes B)
$$
(where $I_2$ denotes the $2\times 2$ identity).
The $n\times m$ case is similar, replace the $2$ by $m$.


text:
Q: incompatible SDK for ARC with mac osx 10.10 I am getting annoying warning messages for my targets after upgrading to osx 10.10, and the latest xcode (I can't remember which actually triggered it)
e.g: Incompatible SDK for ARC in target ApplicationName: macosx
If I change it from 'latest' to '10.10' then I get the same error:
Incompatible SDK for ARC in target ApplicationName: macosx10.10
Everything works and compiles, but still warning.  The code is mixed swift and objective C, with ARC.  Anyone else had this issue?

A: I had some older SDKs (10.5 and 10.6) from previous xcode versions that I had saved, in the xcode SDKs directory, which seemed to cause this error.  I deleted these and replaced them with fresh ones downloaded from the apple website and the error went away.

A: I have same problem. But I found a solution:
In the Build Settings turn off the "Objective-C Automatic Reference Counting" paramter.


text:
Q: Block type not working in layout/catalog.xml I'm working with the AW Mobile2 extension which works fine more or less.
I notice the product image doesn't show up on the product view page. Unfortunately I do not see any related issue in the log files like "exception 'Mage_Core_Exception' with message 'Invalid block type'".
Debugging turned out out that Magento doesn't show the image because of the block type:
app/design/frontend/aw_mobile2/iphone/layout/catalog.xml
[Does not work]
<block type="aw_mobile2/catalog_product_view_media" name="product.info.media" as="media" template="catalog/product/view/media.phtml"/>

[Works]
<block type="catalog/product_view_media" name="product.info.media" as="media" template="catalog/product/view/media.phtml"/>

app/code/local/AW/Mobile2/etc/config.xml
    <global>
        <blocks>
            <aw_mobile2>
                <class>AW_Mobile2_Block</class>
            </aw_mobile2>
        </blocks>
        ...

app/code/local/AW/Mobile2/Block/Catalog/Product/View/Media.php
class AW_Mobile2_Block_Catalog_Product_View_Media extends Mage_Catalog_Block_Product_View_Media
{
    /**
     * @return array|Varien_Data_Collection
     */
    public function getGalleryImages()
    {
        if ($this->_isGalleryDisabled) {
            return array();
        }
        return $this->_getMediaGalleryImages($this->getProduct());
    }

    /**
     * @param Mage_Catalog_Model_Product $product
     * @return Varien_Data_Collection
     */
    protected function _getMediaGalleryImages($product)
    {
        if (!$product->hasData('media_gallery_images') && is_array($product->getMediaGallery('images'))) {
            $images = new Varien_Data_Collection();
            foreach ($product->getMediaGallery('images') as $image) {
                if ($image['disabled'] && !$this->_isBaseImage($image, $product)) {
                    continue;
                }
                $image['url'] = $product->getMediaConfig()->getMediaUrl($image['file']);
                $image['id'] = isset($image['value_id']) ? $image['value_id'] : null;
                $image['path'] = $product->getMediaConfig()->getMediaPath($image['file']);
                $images->addItem(new Varien_Object($image));
            }
            $product->setData('media_gallery_images', $images);
        }

        return $product->getData('media_gallery_images');
    }

    /**
     * @param array $image
     * @param Mage_Catalog_Model_Product $product
     * @return bool
     */
    protected function _isBaseImage($image, $product)
    {
        return (strcasecmp($product->getImage(), $image['file']) == 0);
    }
}

The file permissions are also correct. Sure I could go with the working solution but I'm really wondering why the aw_mobile2 block type doesn't work. This part wasn't modified and should work though.
I stuck and appreciate any hint. Thanks!

A: The only difference between this block and the original block is that it excludes all but the base image:
if ($image['disabled'] && !$this->_isBaseImage($image, $product)) {
    continue;
}

So it looks like either you don't have a base image set for your products, or it does not recognize them. To debug further, you can add some logging to the _isBaseImage() method, like this:
protected function _isBaseImage($image, $product)
{
    Mage::log(__METHOD__ . ': ' . $product->getImage() . ' - ' . $image['file']);
    return (strcasecmp($product->getImage(), $image['file']) == 0);
}

and then see in var/system.log what it actually compares. I guess, the comparision used there is not reliable.

A: In my case "someone" disabled the Module's Output in System > Config > Advanced. Set it to "Enable" fixed the issue. Thanks everyone.


text:
Q: Where does python under conda look for a package? I am trying to manually install a python3.8 module under conda. My module is a python wrapper of a C++ library. It comes with CMakeLists.txt. By specifying -DCMAKE_INSTALL_PREFIX to miniconda3 directory, I achieve that the corresponding .so module appears in miniconda3/lib/python3.8/dist-packages/.
Then, I run python in the same terminal and I can successfully import the module. But if I open another terminal, then the module cannot be found.
I have checked that both terminals run the same python (which python), and have identical environment (by comparing printenv outputs). I also have checked that sys.path values are identical and include  miniconda3/lib/python3.8/. Still, the behavior is different.
So where does python look for modules?
The official documentation says that sys.path is the place, but it seems not the only place.

A: EDIT: This answer is most likely not related to the current problem.
Try running this command in your terminal before you open up python:
export LD_LIBRARY_PATH=$LD_LIBRARY_PATH:/path/to/miniconda3/lib/python3.8/dist-packages

This isn't python looking for .so files, but rather ld (linker).
EDIT: The issue stemmed from different working directories in the used terminal windows. Python searches within sys.path and cwd (current working directory) for imported modules. More in the discussion under the question.


text:
Q: Telerik.Web.Mvc.UI intellisense doesn't work I have a Class Library plugin for nopCommerce that acts like a MVC3 application and in the Index.cshtml I want to use the Html.Telerik().Grid<MyModel>(Model) and added in my Index.cshtml this @using Telerik.Web.Mvc.UI and it points that it's not found, but when I run the application I don't get an error saying that I don't have the references for that library and compiles my code fine, but I don't have intellisense for the Telerik library, also I added <add namespace="Telerik.Web.Mvc.UI" /> in my root web.config Class Library project and still don't have intellisense.
What I'm doing wrong ?

A: I found how to resolve the issue:
1. using gacutil.exe to install the assembly in cmd like this c:\Program Files (x86)\Microsoft SDKs\Windows\v7.0A\Bin\NETFX 4.0 Tools\x64>gacutil.exe /i Telerik.Web.Mvc.dll
2. finding the the PublickKeyToken for the assembly in cmd with gacutil.exe like this c:\Program Files (x86)\Microsoft SDKs\Windows\v7.0A\Bin\NETFX 4.0 Tools\x64>gacutil.exe /l Telerik.Web.Mvc
3. adding in my Class Library project web.config file the assembly like this:
 <add assembly="Telerik.Web.Mvc, Version=2012.1.214.340, Culture=neutral, PublicKeyToken=121fae78165ba3d4" />
            </assemblies>
        </compilation>

4. adding the namespace in the web.config like this:
                <add namespace="Telerik.Web.Mvc.UI" />
        </namespaces>
    </pages>

5. save, build, close visual studio, open again


text:
Q: how to indicate raw string with regex() if my pattern come from another string? I have a csv table from which I get my regex pattern, e.g. \bconden
 Problem : I don't manage to specify to python that this is a raw string
How to put r before a pattern when it comes from a string ?
import re
a =  'de la matière condensée'
fromcsv = '\bconden'
print(re.search('r' + fromcsv, a))

result is None

A: You can use the str_to_raw function below to make a raw string out of an already declared plain string variable:
import re
a =  'de la matière condensée'
pattern = '\bconden'

escape_dict = {
    '\a': r'\a',
    '\b': r'\b',
    '\c': r'\c',
    '\f': r'\f',
    '\n': r'\n',
    '\r': r'\r',
    '\t': r'\t',
    '\v': r'\v',
    '\'': r'\'',
    '\"': r'\"',
    '\0': r'\0',
    '\1': r'\1',
    '\2': r'\2',
    '\3': r'\3',
    '\4': r'\4',
    '\5': r'\5',
    '\6': r'\6',
    '\7': r'\7',
    '\8': r'\8',
    '\9': r'\9'
}

def str_to_raw(s):
    return r''.join(escape_dict.get(c, c) for c in s)

print(re.search(r'\bconden', a))
print(re.search(str_to_raw(pattern), a))

Output:
<re.Match object; span=(14, 20), match='conden'>
<re.Match object; span=(14, 20), match='conden'>

note: I got escape_dict from this page.


text:
Q: MySQL View: Union Query Fails I'm trying to create a view based on the following query, which works fine as a query:
SELECT x_doc_status.Status, sort_order FROM x_doc_status WHERE sort_order IS NOT NULL
UNION
SELECT "[All]", -2
UNION
SELECT "[Open/App] (Trk/Pnd/App)", -1
UNION
SELECT "[Open] (Tracking & Pending)", 0
ORDER BY sort_order, STATUS;

But it fails when I try to create the view from this. Any suggestions would be most appreciated!

A: Use single quotes for literals
SELECT
      x_doc_status.Status
    , sort_order
FROM x_doc_status
WHERE sort_order IS NOT NULL
UNION
SELECT
      '[All]'
    , -2
UNION
SELECT
      '[Open/App] (Trk/Pnd/App)'
    , -1
UNION
SELECT
      '[Open] (Tracking & Pending)'
    , 0
ORDER BY
      sort_order
    , STATUS
;

I suggest you also use UNION ALL instead of just UNION. The former is faster because it does not attempt to remove duplicate rows.


text:
Q: C++: Optimized atomics for a rapid single-producer multiple-consumer environment I'm currently on a project which has quite tight loops and real-time requirements. Premature optimization is definitely not a vice here. I want to exploit the possible relaxed options of C++ atomics as much as possible to achieve my goals. Here is my (thread-unsafe) setup:
// Shared data structure
uint8 data[100];
uint64 timeStamp = 0;

// Consumer threads 1...N run this
void loopConsume() {
    uint64 lastTimeStamp = 0;
    uint8 localData[100];
    for (;;) {
        while (timeStamp == lastTimeStamp);
        memcpy(localData, latestData.data, 100);
        lastTimeStamp = timeStamp;
        doSomething(localData);
    }
}

// Producer callback (singleton)
void produce(uint8 *newData) {
    memcpy(latestData.data, newData, 100);
    latestData.timeStamp++;
}

Here is a clumsy (but ostensibly, correct) attempt at making it thread-safe (and thread-correct) using 2 default sequential consistency atomics:
#include <atomic>

// Shared variables
uint8 data[100];
std::atomic<uint64> timeStamp = 0;
std::atomic<int32> numReaders = 0; // -1 means producer is writing

// Consumer threads 1...N run this
void loopConsume() {
    uint64 lastTimeStamp = 0;
    uint8 localData[100];
    for (;;) {
        uint64 t = timeStamp.load();
        while (t == lastTimeStamp) t = timeStamp.load();
        lastTimeStamp = t;
        for (;;) {
            int32 r = numReaders.load();
            if (r >= 0 && numReaders.compare_exchange_weak(r, r + 1))
                 break;
        }
        memcpy(localData, data, 100);
        doSomething(localData);
        numReaders.fetch_sub(1);
    }
}

// Producer callback (singleton)
void produce(uint8 *newData) {
    while (!numReaders.compare_exchange_weak(0, -1));
    memcpy(data, newData, 100);
    timeStamp.fetch_add(1);
    numReaders.store(0);
}

As you can see, there is a lot of atomic operations, all of which by default use sequential consistency. I'm fairly certain many of them can be relaxed. But which ones? Can I get away with fewer operations or a simpler setup?
Another question is contention. I expect there to be few readers and for them to copy over their data to their local variable quickly. Is there then any real advantage to having a kind read-write lock (as above), or just a regular mutex? If a regular mutex is faster in this case, can I get away with incorporating it into the time stamp atomic variable somehow?
Thanks a lot!


text:
Q: Variable Scope in Tcl I have the following basic code:
proc test {} {
    set my_var2 3
    foreach iter {1 2 3} {
        set my_var1 4
        set my_var2 5
        puts "Inside: $my_var1 $my_var2\n"
    }
    puts "outside $my_var1, $my_var2\n"    ;#WHY IT DOES NOT GIVE ERROR HERE!
}
test  ;#calling the function

The output of the program is this:
Inside: 4 5

Inside: 4 5

Inside: 4 5

outside 4, 5

Now my confusion is since my_var1 is define only in the local scope of foreach loop why its value is available even outside the loop? In other words what determines the scope of a variable in Tcl?
Thanks a lot for the help!

A: From the Tcl Manual:

Tcl evaluates variables within a scope delineated by procs, namespaces
  [...], and at the topmost level, the global scope.

So the foreach loop does not create a new scope and all your variables are scoped by the proc.


text:
Q: Adapt design to all devices with xcode in swift I'm actually working on an IOS application, and i would like to see a background UIImageView in ScrollView.
My problem is that, i'm using Images.xcassets with this two pictures.

And there is my controller with those constraints.

On iphone6 and Iphone6+ i got this display which is correct

on Iphone5 i got that display with an horizontal scrollView

Can i adapt the background image to the device screen, without the horizontally scroll on iphone5 ?
I'm actually using Xcode 7.0.1 with swift.
UPDATED:
Screen with the same width between my imageview, scrollview and rootview.

The other screen with the programming way using swift.

A: As it stands, you've added the image as actual content of the scrollview.
Which is fine, if it's supposed to scroll with the scrollview. If you didn't want it to scroll at all you could put it behind the ScrollView.
You can disable horizontal scrolling, better yet, add constraints to the image view, such that it has its width = to the superview of the scrollview, i.e. the view controller's root view.
Once this is done, you may also wish to add "centre" as the content mode for the image view, or whatever you wish, as there will be extra content and scaling will look worse. If your view isn't wide enough for all form factors you may be force to use aspect fill.


text: Q: What is the formal definition of a macrostate? In thermodynamics, and in particular with regards to entropy, we talk about different microstates giving rise to the same macrostate, that is the same gross overall features. This informal definition has been bothering me for some time. Is there a rigorous and formal definition of a macrostate?


text:
Q: Create vector using for loop with if else condition How can I turn the 3 item output of the for loop below into a data frame. In attempting a solution, I've tried:
-Creating an object related to the for loop, but couldn't succeed
-Creating a matrix, to no effect
What code would turn the output into a vector or list?
> for(i in X$Planned)ifelse(is.na(i),print("ISNA"),print("NOTNA"))
[1] "NOTNA"
[1] "NOTNA"
[1] "ISNA"

A: sapply(x$Planned, function(elem) if (is.na(elem)) {"isNA"} else {"notNA"})

# this will do it!

# however, it will be slower than the vectorized form

ifelse(is.na(x$Planned), "isNA", "notNA")


text:
Q: Yield Rails 2 vs Rails 3 I was in process of migrating a rails 2 app to rails 3. While doing this i came accross a wiered behaviour with yield.
I have a code snippet where i get the return value of yield.
x= true if yield 'xyz'

So if content_for exists for 'xyz' the value of x will be set true else nothing happens. It works fine in rails 2. But in rails 3, always true is set to x because rails returns an empty string even if 'xyz' is not available.
In Rails 2:
yield 'xyz' # nil if xyz is not available
yield 'xyz' # "hi" if xyz is available. "hi" is the rendered content

In Rails 3:
yield 'xyz' # "" if xyz is not available
yield 'xyz' # "hi" if xyz is available. "hi" is the rendered content

Why is this change? render_template has been changed completly?

A: I can not answer your questions but I'd recommend to use this approach:
if content_for?(:xyz)
  yield(:xyz)
  x = true
end


text:
Q: Doubt in the proof of area theorem I was going through the proof of following version of area theorem, in which I have some doubts at the start of the proof.
Theorem: If f is analytic and one-one on open unit disc with $f(0)=0$ and $f'(0)>0$, then area($f(\mathbb D)$), where $\mathbb D$ is domain which is open disc is given by $\pi \sum_{n=1}^{\infty} n \mid a_n \mid ^2$.
Now they have started the proof with this equality. Say $f(\mathbb D)=D$, then
area$(D)=\frac{1}{2i}\int_{\partial D}\bar w
 dw$, by green's theorem which is ok to me. But why are we assuming here that $f(\mathbb D)=D$, is going to be bounded set, otherwise $\partial D$, won't make any sense na?
and immediately they gave following equality.
By applying change of variable we have,
$\frac{1}{2i}\int_{\partial D}\bar w
 dw=\frac{1}{2i}\int_{\mathbb D}\bar {f(z)}
 f'(z)dz$. Everything is ok here but I am not convinced how we can say that boundary of domain will get mapped to boundary of $D$. The remaining proof is fine to me. Just stuck on this two doubts for some time. Thanks.

A: Usually, the proof proceeds by taking $r\mathbb{D}$ for $0<r<1$ and that is mapped by $f$ into an analytic Jordan domain, for which the result holds by the usual computations and then we take the limit $r \to 1$ where we allow both sides in the limit to be infinite of course - that is part of the conclusion in the sense that if the area of the image is finite than the LHS series is finite and equal to it, while if the area is infinite, the LHS series is infinite too; that boundary goes to boundary is an easy topological fact given that $f$ is an open map (note that for $r\mathbb{D}$ we have a homeomorphism between the closed domains $\bar{r\mathbb{D}}$ and $\bar{f(r\mathbb{D})}$)


text:
Q: Reduced CPU uses in Java application I have an Application in java and when i runs it in IDE of even in Desktop that is consuming much cpu because of that my pc hangs and I am not able to work even. so is there any way that I can reduced that application uses CUP never about 20 to 30 instead of 101 or 100 see Screen shot.![enter image description here][1]
can any body tell me how it is possible?

A: What you can do is to identify where your bottleneck in your program is, and then control how much of the time your application is idle by sleeping your thread(s) that is working. Let's say that you have identified your bottleneck and that it's a loop. Then you can measure the time it takes to compute one iteration in your loop. After you have this number you simply calculate how long you want your processor to sleep based on the percentage you want your application to be idle.
For example, lets say that you want your application to only use 20% of your processor, and it takes 20 ms to complete one iteration in your loop. Then you want to sleep 80 ms in the end of your loop before the next iteration to make the processor go idle 80% of the time. If you don't have a "gameloop" or similar this can be a bit harder to achieve, but at least you can try to approximate how much time to sleep to not make it work at 100%


text:
Q: Let users withdraw earnings to Paypal I'm looking for a Wordpress plugin(if exists) by which users can withdraw their earnings made on my website to their Paypal accounts.
Just like Freelance websites: Withdraw your earnings to Paypal
Any plugin suggestion or idea how to achieve this would be greatly appreciated.

A: I don't know of any readily available plugins for this, however, you could build it using the PayPal Pay API.
Just add a simple interface for the user to see their balance and trigger the payment of what they're owed, and then make a call to the Pay API to send them the payment directly when the action is triggered.
This PHP SDK for PayPal will make the Pay request (and any other PayPal classic API for that matter) very quick and easy for you.


text:
Q: How to (seriously) troubleshoot high CPU/Memory issues in MacOS X? In Windows I have Sysinternals Process Explorer but for Mac the built-in "Activity Monitor" is not enough.
I would need to figure out for each process:

*

*Files open

*CPU usage for each thread (in real time... not just a "sample")

*Network connections open

*etc...

I'm a bit new in the Mac OS X world, so any other troubleshooting methodologies are welcome.
Thanks!

A: don't really if this would help you, but i've seen tool called: atMonitor
which is an "upgraded" version of the Activity Monitor , you can find this at:
http://www.atpurpose.com/atMonitor/
hope this helps

A: Are you looking for an all in one application or where you access the information?
It is possible to look at the specific sections using the CLI tools as well for more in depth information:
eg.

*

*Open Files: lsof -c "APP_NAME", lsof +d 'DIRECTORY' or for real time file system usage: sudo fs_usage "APP_NAME"

*Network Connections: lsof -i | grep "APP_NAME"
As always for more options check out the man page fpr each utility.

A: You may be able to use instruments (part of the developer tools) to do this, it can provide alot more granularity than activity monitor however it does require some configuration to get exactly what you want from it, i don't think it will be much good if you are looking at system wide performance but for performance of particular processes it may be useful.


text:
Q: Azure DIsk Management I just started using azure virtual machines and I must admit I still have a few questions regarding the disk management:
I manage my machines via the Node JS API in the following way:
 azure vm create INSTANCE  b39f27a8b8c64d52b05eac6a62ebad85__Ubuntu-12_10-amd64-server-    20130227-en-us-30GB  azureuser XXXXXX --ssh  --location "West US" -t ./azure.pem
 azure vm start INSTANCE

 //do whatever
 azure vm shutdown INSTANCE
 azure vm delete INSTANCE

*

*After deleting the instance I still have a buch of disks left, which are not deleted but which I am charged (i.e. deducted from my free trial). Are they not deleted by default?
Is there an API call to delete them (only found the corresponding REST calls, but kind of unwilling to mix NODE JS and Rest api calls).

*Can I specify one of those existing disks when starting a new instance?
Thanks for your answers!
Jörg

A:
After deleting the instance I still have a buch of disks left, which are not deleted but which I am charged (i.e. deducted from my free trial). Are they not deleted by default? Is there an API call to delete them (only found the corresponding REST calls, but kind of unwilling to mix NODE JS and Rest api calls).

Yes, the disks are not deleted by default. I believe the reason for that is to reuse those disks to spin off new VMs. To delete the disk (which is a page blob stored in Windows Azure Blob Storage) you could possibly use Azure SDK for Node: https://github.com/WindowsAzure/azure-sdk-for-node.

Can I specify one of those existing disks when starting a new
  instance?

Yes, you can. For that you would need to find the disk image and then use the following command:
azure vm create myVM myImage myusername --location "West US"

Where "myImage" is the name of the image. For more details, please visit: http://www.windowsazure.com/en-us/develop/nodejs/how-to-guides/command-line-tools/#VMs

A: Yes when a VM is deleted the disk is left behind. Within the portal you can apply this disk image to a new VM instance on creation. There's some specific guidance on creating VMs from the API with existing disk images here:
http://www.windowsazure.com/en-us/develop/nodejs/how-to-guides/command-line-tools/#VMs


text:
Q: Retrofit2: Modifying request body (Json) in OkHttp I want to make a request in Android modifying the BODY with a JSON but at the same time modifying the HEADER, thus being able to obtain a response service.
Now I only have the code to modify the header but now I have to do the same (modify the header) and send a Json to the body to get another Json answer
public String abc="Basic "+Login.enco;
public Service getClientService() {

        OkHttpClient client = new OkHttpClient.Builder().addInterceptor(new Interceptor() {

            @Override
            public Response intercept(Interceptor.Chain chain) throws IOException {

                Request newRequest = chain.request().newBuilder()
                        .addHeader("Authorization", abc)
                        .build();

                return chain.proceed(newRequest);
            }
        }).build();

        Retrofit retrofit = new Retrofit.Builder()
                .baseUrl(Constants.ROOT_URL)
                .client(client)
                .addConverterFactory(GsonConverterFactory.create())
                .build();

        return retrofit.create(Service.class);
    }
enter code here
    try {
        final List<String> lista = new ArrayList();

        RestApiAdapter restApiAdapter = new RestApiAdapter();
        Service service = restApiAdapter.getClientService();
        Call<JsonObject> call = service.getDataUser();
        call.enqueue(new Callback<JsonObject>() {
            @Override
            public void onResponse(Call<JsonObject> call, Response<JsonObject> response) {
                JsonObject userJson = response.body().getAsJsonObject("LogOnResult");
                Log.d("response2", userJson.get("Usuario").getAsString());
                Log.d("response3", userJson.get("Token").getAsString());
                Log.d("response4", userJson.get("TipoUser").getAsString());
                Log.d("response5", userJson.get("IdUsuario").getAsString());
                UserModel user = new UserModel(
                        userJson.get("Usuario").getAsString(),
                        userJson.get("Token").getAsString(),
                        userJson.get("TipoUser").getAsString(),
                        userJson.get("IdUsuario").getAsString()
                );

            }

            @Override
            public void onFailure(Call<JsonObject> call, Throwable t) {
                Toast.makeText(getApplicationContext(), "No existe conexion", Toast.LENGTH_LONG).show();
            }
        });
    }catch (Throwable e){
        Toast.makeText(getApplicationContext(), "No existe conexion", Toast.LENGTH_LONG).show();
    }
    }

A: In Retrofit2 you can pass header, query, body params via method params. All you need just specify annotations. Below is an example.

Java Example:
@POST("adduser")
Call<User> addUser(@Header("Authorization") String header, @Body User userModel);

Check this links for more examples.


text:
Q: Callback in Polymer(); when element is shown Is there a callback available in the Polymer({}) object which fires everytime the element is shown ?
ready is not suitable because it's called when the element is created on initial page load.
I need an event or callback every time the route changes and my element is displayed.
Why do I need this ? I have an element which is behaving differently if a certain request parameter is set. So I need to check on each load whether the parameter is set or not.
Edit:
I worked around my requirement by doing the stuff I need to be done on element display in my routing functions:
page("/app/list", function() {
    document.querySelector("my-list").$.loadList.generateRequest();
    app.route = "list";
});

A: In the meantime I came also accross app-route which as well has functionality to call methods on route or view changes.
You can read about it here:
https://www.polymer-project.org/1.0/toolbox/routing#take-action-on-route-changes
Here is a working example:
<!DOCTYPE html>

    <link rel="import" href="bower_components/polymer/polymer.html" />
    <link rel="import" href="bower_components/app-route/app-location.html" />
    <link rel="import" href="bower_components/app-route/app-route.html" />
    <link rel="import" href="bower_components/iron-pages/iron-pages.html" />

    <container-element></container-element>

<dom-module id="container-element">
    <template>
        <app-location route="{{route}}" use-hash-as-path></app-location>
        <app-route route="{{route}}" pattern=":view" data="{{routeData}}"></app-route>
        Page 1 | Page 2
        <iron-pages selected="[[routeData.view]]" attr-for-selected="name">

This is Page 1.

            <x-element1 name="element1"></x-element1>
        </iron-pages>
    </template>

</dom-module>

<dom-module id="x-element1">
    <template>
This is Element 1.
</template>

</dom-module>

A: Maybe the attached callback is what you're looking for.
This lifecycle callback is called when an element is attached to the DOM and should therefore be the right choice. It is always called after the ready callback.
From the polymer docs:
https://www.polymer-project.org/1.0/docs/devguide/registering-elements.html#initialization-order
attached: function() {
   this.async(function() {
      // access sibling or parent elements here
   });
}


text:
Q: Align button with formgroups (bootstrap 3) How do I vertically align a button to the text box controls?

      Stuff 1
      <select class="form-control">
        <option value="1">Item 1</option>
        <option value="2">Item 2</option>
        <option value="3">Item 3</option>
      </select>

      Stuff 2
      <select class="form-control">
        <option value="1">Item 1</option>
        <option value="2">Item 2</option>
        <option value="3">Item 3</option>
      </select>

      Stuff 3
      <select class="form-control">
        <option value="1">Item 1</option>
        <option value="2">Item 2</option>
        <option value="3">Item 3</option>
      </select>

    <button class="btn btn-primary btn-lg btn-block">Search</button>

https://jsfiddle.net/2nn422ax/

A: It appears that the button is aligned to the text email above the form field, as it should be. If you use margin:top for the button about maybe 30px, it should align with the text fields if you are talking about the search button. Hope that helps.

A: See a css solution in jsfiddle below:
https://jsfiddle.net/2nn422ax/1/
CSS:
.row{
  position: relative;
 }

.button-container{
  position: absolute;
  bottom: 0;
  right: 0;
}

.form-group{
 margin-bottom: 0px;
}

A: Just use modern and agile flexbox:
.row {
  display: flex;
  align-items: center;
}

Jsfiddle


text:
Q: REST web services vs JSON services REST webservices imply the server-side is stateless (for the most part) and urls correspond to resources and HTTP GET/POST/DELETE/PUT methods correspond to operations on those resources.
I am planning to work on a JSON services layer that is dependent on server-side state, having urls that correspond to resources and having urls like /add /update /delete corresponding to different operations and all of those urls using HTTP POST.

*

*What is the right terminology for this? Should this be called JSON
web services? Is there any specific term for this?

*It looks like Jersey+JAX-RS would be very useful for this purpose. Is it ok?

*Would it make sense to use Struts for this kind of application?

A: *

*JSON is a file format which your rest service may (or may not) use to send its answers. If you use this format to communicate with your webservice, you cann say that your service is a JSON web service.

*Indeed, Jersey is a good JAX-RS implementation. However it is not the only one.

*If you need a webapp to interact with the webservice you can use Struts. However, you can use any other tool (included some more recent technology, struts is really old) for the front-end of your system.

A: Well, it's not REST.  However trying to defeat that tide of general misunderstanding just isn't going to happen.
What you are describing is actually what most of the world views as REST and therefor should be mostly OK with just calling it as such.
In the presence of a true Restifarian, you will get some push-back because they will be correct - however, there isn't really much need to add a tremendous amount of confusion to your daily life as the distinctions (and the MASSIVE benefits they afford...) are largely lost on anyone you work with.
(1) is accurate enough, or simply rest. (2) is redundant but it is a good framework for the technology.  (3) I would say no, but noticing when this question was asked, I'm sure you already decided.


text:
Q: Extract json objects to json in c# i got an JArray in c# which i wannt to transpose/transform into :

Currently i do something like :
var mockDataPath = "...\\DummyData.json";
var rawJSON = System.IO.File.ReadAllText(mockDataPath);
JArray jArray = JArray.Parse(rawJSON);

Maybe linq will do the job, but i do not know how.
jArray.Children().Select(...);

And the objects (Obj2,Obj3) contain complex hierarchical data.
Here an Link to a json pastiebin with the original json data (this would be "...\DummyData.json")
I am looking for
something like an XSL Transformation
for json. Or if LINQ will do the job, this would be even better.

A: You can use Json.Net to  Deserialize your json:
 Newtonsoft.Json.JsonConvert.Deserialize("yuor json string");

Just look for Newtonsoft.Json in nuget Packages.

A: Finally I did:
            JArray resultJArray = new JArray();
            foreach(JObject item in jArray)
            {
                JObject obj = JObject.FromObject( new { Obj2 = item.GetValue("Obj2"), Obj3 = item.GetValue("Obj3") } );
                resultJArray.Add(obj);
            }

            var transformedJson = JsonConvert.SerializeObject(resultJArray, Formatting.Indented);


text:
Q: pass class as parameter for a method in java Im trying to make a method that creates a new object of a class, but I want to be able to make objects of many different classes, so making a method for each class won't work for me. Is there any way I can pass in a class to a method, so that a new object can be created? All of my classes have the same constructor.

A: You could use
public <T> T instanciate(Class<? extends T> clazz) throws Exception {
    return clazz.newInstance();
}

and call it like
MyObject o = instanciate(MyObject.class);

If you do it that way, the classes you want to instanciate must have a default constructor with no argument. Otherwise, you'll catch a java.lang.InstantiationException.

A: Have you read about Abstract Factory pattern?
EDITED
BTW, I do not think that reflection is good way to make your architecture, if you have a lot of classes with the same constructor try to use useful patters like Factory or Builder instead of creating one method with reflection.

A: You can use reflection to switch on a type name and do what you gotta do.

A: I believe that you are looking for reflection.
Check out this question: What is reflection and why is it useful?

A: I think that Class.forName might be what you're looking for

A:
package com.loknath.lab;
public class HasHash {
public static void main(String[] args) throws Exception {
  HasHash h = createInstance(HasHash.class);
            h.display();

}
  //return the instance of Class of @parameter
public static  T createInstance(Class className)
            throws Exception {      return className.newInstance();     }
private void display() {        System.out.println("Disply ");  }
}


text:
Q: Not receiving the broadcast while running the LocationPollerDemo I've searched through a number of the questions and answers in regards to the LocPoller from Commonsware and haven't found the answer to my problem.  I have tried using the demo of the latest from github and I'm having issues.  First I must admit that I modified the PERIOD in the demo so the alarm fires every 15 seconds.  I realize this will be a large drain on the batter and it's just for testing.  I would expect that the LocationReceiver's onReceive() would be called ever 15 seconds but that isn't happening.
Debugging things I see that the alarm is triggering and everything seems good in that it's getting to the PollerThread and calling sendBroadcast.  So I assume I have something setup wrong, but I'm not sure what.  Other than changing the PERIOD in the demo everything else is as is.  I've tried running this on a device and emulator (Level 8).  Any help in debugging this would be appreciated.
In the end the functionality I'm looking for is to have the ability to keep track of a phones location so at any point my app can get the current location.  I saw this in my research and though it fit the bill perfect.  If someone has a better idea of different approach I'd love to hear it.
Thanks,
Rindress

A:
In the end the functionality I'm looking for is to have the ability to keep track of a phones location so at any point my app can get the current location. I saw this in my research and though it fit the bill perfect.

No, it is not.

If someone has a better idea of different approach I'd love to hear it.

Step #1: Call requestLocationUpdates() when you want to start receiving location updates in your app
Step #2: Use the location fixes delivered to your LocationListener, or call getLastKnownLocation(), as needed
Step #3: Call removeUpdates() when you no longer want to receive location updates in your app


text:
Q: Bounds on the determinant of a $3 \times 3$ matrix I have a matrix $$B = A + \epsilon I$$
where $A$ is a $3 \times 3$ matrix, $I$ is an identity matrix and $\epsilon$ is a positive scalar.
Is there a lower bound on the determinant of $B$?
If A is a symmetric positive semi-definite matrix (say a co-variance matrix), is there a lower bound, when $\epsilon$ is a positive?

A: The way your question is posed, there is no lower bound. Simply choose $A=(c-\epsilon)I$ with arbitrary $c$ and your matrix will have determinant $c^3$, which runs through $\mathbb{R}$, i.e. the determinant can take any value.
Or maybe, you want a lower bound in terms of the determinant of $A$? In that case, you can always just transform A into Jordan form (I won't be affected) and just read off the determinant. This should also (given some knowledge about $A$) give you lower bounds.
For instance, it's clear that $\operatorname{det} B=0$ is always possible, regardless of the determinant of $A$ (you only need one entry $-\epsilon$ on the diagonal of $A$), so a lower bound must be $<0$. If the determinant is not zero, it will be a polynomial in $\epsilon$, which should give you some real bounds given some assumptions on $A$.

A:
If A is a symmetric positive semi-definite matrix (say a co-variance matrix), is there a lower bound, when $\epsilon$ is a positive?

Given that the determinant is a product of all the eigenvalues of a matrix, that a positive semidefinite matrix has only nonnegative eigenvalues $\lambda_k(A) \ge 0$, that $\lambda_k(A + \epsilon I) = \lambda_k(A) + \epsilon$, and that $\epsilon \ge 0$, the lower bound is $\det A$ (for $\epsilon = 0$).


text:
Q: Iptables and Postfix Examine configuration of Postfix and iptables, what will be response of mail server and why?
First:
main.cf
mynetwork=127.0.0.1/8
smtpd_sender_restrictions=permit_inet_interfaces

iptables
iptables -P FORWARD DROP
iptables -i lo -A INPUT -j ACCEPT
iptables -o lo -A OUTPUT -j ACCEPT

Telnet session
telnet localhost 25
hello carlo.ru
mail from:<test@localhost>
rep to:<test@localhost>
data
test
.
exit

Second:
main.cf
mynetwork=127.0.0.1/8
smtpd_recipient_restrictions=permit_mynetworks

iptables
iptables -P FORWARD DROP
iptables -i lo -A INPUT -j ACCEPT
iptables -o lo -A OUTPUT -j DROP

Telnet session
telnet localhost 25
hello carlo.ru
mail from:<test@localhost>
rep to:<test@localhost>
data
test
.
exit

A: Assuming that your mail server accepts the TCP connection (instead of telnet waiting for the connection to be dropped and you just typing away:)), try the following (you have errors in your SMTP conversation):
telnet localhost 25
helo carlo.ru
mail from:<test@localhost>
rcpt to:<test@localhost>
data
test
.
exit

It's helo or ehlo not hello and it's also rcpt to instead of rep.


text:
Q: $f(x)$ leaves the same remainder of $2018$ when divided by each of $x+4$, $x-1$, $x+7$, $x+8$ Let $f(x) = x^4 + ax^3 + bx^2 + cx + d$, where $a, b, c, d$ are real numbers. If $f(x)$ leaves the same remainder of $2018$ when divided by each of $x+4$, $x-1$, $x+7$, $x+8$, find the value of $d$.
A way to approach this is to solve the set of equations: $f(-4) = f(1) = f(-7) = f(-8) = 2018$, but the computation is really tedious when I try it out. However, I couldn't think of any other way to solve this innocent-looking question. Any hints? Thanks very much.

A: While this has been practically solved in comments, for closure's sake:
As $P(x)-2018$ is a monic quartic with roots $-4, 1,-7,-8$, by Vieta we must have $d-2018=(-4)(1)(-7)(-8)$.


text:
Q: Salesforce custom object and attachments Ok, I've been tasked with creating a custom salesforce object that saves some data. That's the easy part.
Where I'm struggling is adding a piece to upload files associated with the record created in the custom object.
The custom object is essentially a form with fields on it. But I also need to upload relevant files.
So I built the form part of the custom object. I used an Apex class and a VisualForce page for the "upload" part.
Unfortunately, in the course of testing, I keep getting errors on the VisualForce/Apex piece.
The errors I get are the following:
Parent: Parent ID: id value of incorrect type: 00590000000yBOmAAM
And my Apex class looks like this:
    public with sharing class FileToDocument {
    public Attachment attachment{
        get{
            if(attachment == null)
                attachment = new Attachment();
            return attachment;
        }
        set;
    }

    public PageReference upload(){
        attachment.OwnerId = UserInfo.getUserId();
        attachment.ParentId = '00590000000yBOm';
        attachment.IsPrivate = false;

        try{
            insert attachment;
        }
        catch(DMLException e){
            ApexPages.addMessage(new ApexPages.message(ApexPages.severity.ERROR, 'Error Uploading Attachment'));
            return null;
        }
        finally{
            attachment = new Attachment();
        }

        ApexPages.addMessage(new ApexPages.message(ApexPages.severity.INFO, 'Attachment Uploaded Successfully'));

        return null;
    }
}

I am very much a novice at SalesForce. I think the problem is the ParentID line, but I don't know exactly how to fix it.
What I'm trying to do is to be able to upload/attach documents to a record, while I'm filling out the form for the record.
My VisualForce looks like this:
<apex:page controller="FileToDocument">
    <apex:form enctype="multipart/form-data">
        <apex:pageMessages />
        <apex:pageblock >
            <apex:pageBlockButtons >
                <apex:commandButton action="{!upload}" value="Attach"/>
            </apex:pageBlockButtons>

            <apex:pageBlockSection showHeader="false" columns="2" id="block1">
                <apex:pageBlockSectionItem >
                    <apex:outputLabel value="File Name" for="fileName"/>
                    <apex:inputText value="{!attachment.name}" id="fileName"/>
                </apex:pageBlockSectionItem>

                <apex:pageBlockSectionItem >
                    <apex:outputLabel value="File" for="file"/>
                    <apex:inputFile value="{!attachment.body}" filename="{!attachment.name}" id="file"/>
                </apex:pageBlockSectionItem>
            </apex:pageBlockSection>
        </apex:pageblock>
    </apex:form>
</apex:page>

So what could I be doing wrong? My other thought is that there's simply no way to upload appropriate files until after the record has been created. Even then, I think I'd still need to know how to associate it with the Parent ID.
Any help is greatly appreciated, as always.

A: This is no longer relevant. The project was reassigned to a different group.


text:
Q: Javascripts in html file included using ng-include does not execute I'm using ng-inculde to include an html file that aslo includes some javascript codes for that page, but the javascripts are not executed,
here is my Code :

  <meta charset="utf-8">
  <meta http-equiv="x-ua-compatible" content="ie=edge">
  <title ng-cloak>{{Page.Title}}</title>
  <link rel="stylesheet" href="/media/css/bootstrap.min.css">
  <link rel="stylesheet" href="/media/css/swiper.min.css">
  <link rel="stylesheet" href="/media/css/owl.carousel.css">
  <link rel="stylesheet" href="/media/css/style.css">
  <link href="/media/css/nprogress.css" rel="stylesheet">

  <meta name="description" content="">
  <meta name="fragment" content="!">
  <meta name="viewport" content="width=device-width, initial-scale=1">

  <link rel="apple-touch-icon" href="apple-touch-icon.png">

And my home.html page:

Welcome, this is the home page!!

And this is my home_s.html:

A: Either:
<ng-include src="'/template/include/home_s.html'"></ng-include>

Or:

However, Angular on its own doesn't support loading scripts inside templates. For this to work you need to include jQuery (make sure you load it before Angular).
Demo without jQuery: http://plnkr.co/edit/Qh27ArEyIk53VRB7e61C?p=preview
Demo with jQuery: http://plnkr.co/edit/TxOmx5ksEFC2larJiJBA?p=preview


text:
Q: Listen to double key press using Chrome Commands API Is there a way to listen for a double key press using the Chrome Commands API.
For example, I want to open a search window when the user double taps the shift key.
I have tried this;
"commands": {
    "_execute_page_action": {
        "suggested_key": {
            "default": "Shift+Shift"
        },
        "description": "..."
    }
}

But attempting to load the extension returns the following;
Failed to load extension from: /example_path
Invalid value for 'commands[1].default': Shift+Shift.

A: From the docs:

Supported keys: A-Z, 0-9, ,, ., Home, End, PageUp, PageDown, Space, Insert, Delete, Arrow keys (Up, Down, Left, Right) and the Media Keys (MediaNextTrack, MediaPlayPause, MediaPrevTrack, MediaStop).
Note: All key combinations must include either Ctrl* or Alt.

You can read more about commands API here.


text:
Q: Is this approach of barriers right? I have found that pthread_barrier_wait is quite slow, so at one place in my code I replaced pthread_barrier_wait with my version of barrier (my_barrier), which uses an atomic variable. I found it to be much faster than pthread_barrier_wait. Is there any flaw of using this approach? Is it correct? Also, I don't know why it is faster than pthread_barrier_wait? Any clue?
EDIT

*

*I am primarily interested in cases where there are equal number of threads as cores.
atomic<int> thread_count = 0;

void my_barrier()
{
  thread_count++;

  while( thread_count % NUM_OF_THREADS )
   sched_yield();
}

A: Your barrier implementation does not work, at least not if the barrier will be used more than once. Consider this case:

*

*NUM_OF_THREADS-1 threads are waiting at the barrier, spinning.

*Last thread arrives and passes through the barrier.

*Last thread exits barrier, continues processing, finishes its next task, and reenters the barrier wait.

*Only now do the other waiting threads get scheduled, and they can't exit the barrier because the counter was incremented again. Deadlock.

In addition, one often-overlooked but nasty issue to deal with using dynamically allocated barriers is destroying/freeing them. You'd like any one of the threads to be able to perform the destroy/free after the barrier wait returns as long as you know nobody will be trying to wait on it again, but this requires making sure all waiters have finished touching memory in the barrier object before any waiters wake up - not an easy problem to solve. See my past questions on implementing barriers...
How can barriers be destroyable as soon as pthread_barrier_wait returns?
Can a correct fail-safe process-shared barrier be implemented on Linux?
And unless you know you have a special-case where none of the difficult problems apply, don't try implementing your own for an application.

A: AFAICT it's correct, and it looks like it's faster, but in the high contended case it'll be a lot worse. The hight contended case being when you have lots of threads, way more than CPUs.
There's a way to make fast barriers though, using eventcounts (look at it through google).
struct barrier {
    atomic<int>       count;
    struct eventcount ec;
};

void my_barrier_wait(struct barrier *b)
{
    eventcount_key_t key;

    if (--b->count == 0) {
        eventcount_broadcast(&b->ec);
        return;
    }
    for (;;) {
        key = eventcount_get(&b->ec);
        if (!b->count)
            return;
        eventcount_wait(&b->ec);
    }
}

This should scale way better.
Though frankly, when you use barriers, I don't think performance matters much, it's not supposed to be an operation that needs to be fast, it looks a lot like too early optimization.

A: Your barrier should be correct from what I can see, as long as you don't use the barrier to often or your thread number is a power of two. Theoretically your atomic will overflow somewhere (after hundreds of millions of uses for typical core counts, but still), so you might want to add some functionality to reset that somewhere.
Now to why it is faster: I'm not entirely sure, but I think pthread_barrier_wait will let the thread sleep till it is time to wake up. Yours is spinning on the condition, yielding in each iteration. However if there is no other application/thread which needs the processing time the thread will likely be scheduled again directly after the yield, so the wait time is shorter. At least thats what playing around with that kind of barriers seemed to indicate on my system.
As a side note: since you use atomic<int> I assume you use C++11. Wouldn't it make sense to use std::this_thread::yield() instead of sched_yield() in that case to remove the dependency on pthreads?
This link might also be intressting for you, it measures the performance of various barrier implementations (yours is rougly the lock xadd+while(i<NCPU) case, except for the yielding)


text:
Q: Bootstrap dropdown menu jumbing on hover in ie8 i have bootstrap dropdown menu which is working fine in all the browser other than IE8, can anyone look into this and help me please
.navbar.navbar-default ul li:hover{
            .dropdown-menu {
                display: block;
                }
        }

.dropdown-menu {
  background-image: url(../pics/Responsive/dropdown-bg.png);
  background-size: 100% auto;
  background-position: top left;
  background-repeat: no-repeat;
  background-color: transparent;
  top: 100%;
  left: 10%;
  position: absolute;
  text-align: center;
  border: 0;
  box-shadow: none;
  width: 1048px !important;
  float: none !important;
  margin: 0 auto !important;
  top: 56px !important;
  min-height: 200px!important;
  border: 0 none !important;
  padding: 10px 6% 0;
  -ms-behavior: url(backgroundsize.min.htc);
}

thx in advance, can anyone help on this issue?


text:
Q: Prevent new file from opening on add I'm doing a GAX project and I have an action that adds all the files from a folder to a new "Solution Items" folder. This serves to insert the files needed at the project root as the Local.testsettings and the like.
My problem is that when I add a file, it opens immediately. For a .txt file or the like, it's not too bad. For .testsettings file, it opens a modal window that blocks all the process.
What can I do to prevent this opening? I can't use a .close on the ProjectItem.Document because the code is not executed after the mySolution.ProjectItems.AddFromFile(file) statement.
If you know of any way to prevent a file from opening on add (whether it is added by hand or by code) I'd like to know.
The full code, as asked, is :
        DTE dte = GetService<DTE>();

        string folderPath = System.IO.Directory.GetCurrentDirectory() + SolutionFolderPath;

        var solution = dte.Solution as Solution2;
        var solutionItems = solution.AddSolutionFolder("Solution Items");

        foreach (var file in Directory.GetFiles(folderPath))
        {
            var item = solutionItems.ProjectItems.AddFromFile(file);
        }

Thanks a lot!

A: A bit of a blast from the past here but I came across this question when I was looking to do exactly the same thing recently for a custom VS multi-project wizard I've written. In VS2017, the quick and simple solution was after adding the files (using similar code to the OP), I called this in my wizard implementation's IWizard.RunFinished method:
DTE.Documents.CloseAll(vsSaveChanges.vsSaveChangesNo);

Note that in my wizard code, I store the _DTE object in a member property in IWizard.RunStarted for later use (outside of the RunStarted method). Now when my template wizard has completed, there are no open documents!


text:
Q: Strange arithmetic with relativedelta for date calculations I am using relativedelta to calculate difference between two dates. However, it seems like the year part of the datetime object isn't being recognized. If the dates were of the same year-months, the calculations obtained would make sense.
# lease dates
start = json_obj['lease'][0]['start']
end = json_obj['lease'][0]['end']

print(end, start)
2026-10-31 2020-10-07

startdt = datetime.strptime(start, '%Y-%m-%d')
print(startdt)
2020-10-07 00:00:00

enddt = datetime.strptime(end, '%Y-%m-%d')
print(enddt)
2026-10-31 00:00:00

# Total months
calc = relativedelta.relativedelta(enddt, startdt)
calc.days
24

calc.months
0

A: There are no months, so calc.months return 0:
# Total months
calc = relativedelta.relativedelta(enddt, startdt)
print (calc)
relativedelta(years=+6, days=+24)

If need all months mutiple years by 12 and add months:
print (calc.months + calc.years * 12)
72


text:
Q: Can I add a button for Skype for business in my website I know its easy to add Skype link using https://www.skype.com/en/developer/create-contactme-buttons/ .
But can the similar stuff be done for SkypeForBusiness ?

A: Creating a link like this works with my employer.
Chat with Skype

I didn't see anything useful on the SDK site.

A: A quick Google search for "Skype for Business button" returned many results. I don't see anything explicitly saying that you can. Have you tried to use a Skype for Business account when creating a Contact Me button? If so and it didn't work I'd say the answer is no, the functionality isn't available..

A: Skype for Business has extensive set web APIs available through Web SDK which you can use to achieve your functionality. Is the user on your website an anonymous user or authenticated to Skype for Business?
If the user is authenticated then you can do P2P calls through the SDK, else you would need to create meeting to let the anonymous user talk to a Skype for Business authenticated user.
Also, follow the Web SDK sample and check out Conversation Control that should solve your purpose.

A: No, you can't create a Skype Button for Skype For Business, because SFB uses email addresses as the handle, and these aren't accepted by the contact me button creator here: https://www.skype.com/en/developer/create-contactme-buttons/


text:
Q: postman does not validate existing email golang I am doing a project in Go language, I already created my collection in mongodb and I made functions to insert the user data and to validate email and nickname (if they have so many characters or if they already exist in the db) the problem is that when try it in postman, it is validated if any of the two have the characters, but it is not validated if they exist in the db, just insert them in the db always with the same user and the same email, I feel that the code is not bad, What do you think?
//It is the function to validate if the user exists or not, I made another one exactly the same for the email
func CheckUserExist(nick string) (models.Useer, bool, string) {
ctx, cancel := context.WithTimeout(context.Background(), 15*time.Second)
defer cancel()

db := MongoC.Database("DebMan_N01")
col := db.Collection("users")

condition := bson.M{"nick": nick}

var results models.Useer

err := col.FindOne(ctx, condition).Decode(&results)

ID := results.ID.Hex()
if err != nil {
    return results, false, ID
}
return results, true, ID }

//Here I call the function and indicate that if the value it returns is true, that is, if it is true that the user already exists
    _, founded, _ := bd.CheckUserExist(t.Nick)
if founded == true {
    http.Error(w, "Ya existe un nombre de usuario registrado", 400)
    return
}
_, foundedE, _ := bd.CheckEmailExist(t.Email)
if foundedE == true {
    http.Error(w, "Ya existe un usuario con el email", 400)
    return
}

enter image description here


text:
Q: In MongoDb, how can you set a value on an object in a array property? My goal is to put a "deleted at" timestamp on specific object in an array of a document.
If the document looks like this:
{
    "subdoc": [
        {
            "key": 1,
            "value": "abc",
            "isActive": true
        },
        {
            "key":5,
            "value": "ade",
            "isActive":true
        }
    ]
}

I would like to be able to say "look for the document that has subdoc.key == 5 and subdoc.value == "ade"; set subdoc.isActive to false and set subdoc.deleteAt = current db timestamp. With a resulting document like this:
{
    "subdoc": [
        {
            "key": 1,
            "value": "abc",
            "isActive": true
        },
        {
            "key":5,
            "value": "ade",
            "isActive": false,
            "deletedAt": Timestamp(1425911075,1)
        }
    ]
}

Is this doable?
Update: After further review of the mongo docs, this does seem doable with the "$ (update)" operator.  That gets me what I need, but I'm hoping for a less magical-strings way of doing this using the C# driver?
My working find/update looks like this:
// find
{
    "subdoc.key":"2",
    "subdoc.value":"ade"
}
// update
{
    "$currentDate": {
        "subdoc.$.deleteAt": {
            "$type": "timestamp"
        }
    }
}

Update: I should clarify that this updated time stamp field is used for synchronization by many sometimes-connected mobile clients in a load-balanced environment (multiple web servers, multiple worker processes, and a mongo cluster) with a high transaction volume, which makes it crucial that this time stamp has a single point truth, is logically sequential in the context of the app, and is as high precision as possible (fractions of a second).  Otherwise, records could be missed in a sync.
For the moment, I'm using the above approach to ensure time stamped values are generated by the mongo database instance.  And I'm pretty satisfied with this approach.

A: you can use the c# driver to wrap the mongo entities in c# objects. Then in your code you can use linq to query the DB and update your objects as required. Then just save them to the DB to persist your changes.
Below is a small piece of code to query a Parent collection in the test DB.
The C# driver provides as AsQueryable extension to allow us to write our queries directly in Linq. The driver will then automatically build the required query and execute it against the collection.
The sample below looks for any sub documents in the subdoc list that have a value on the key field of 5
If it finds any, it updates the deletedAt date and then saves it back to the DB.
var client = new MongoClient();
var database = client.GetServer().GetDatabase("test");
var parentCollection = database.GetCollection<Parent>("Parent");

var parent = parentCollection.AsQueryable().FirstOrDefault(p => p.subdoc.Any(f => f.key == 5));

if (parent != null)
{
    var fooList = parent.subdoc.Where(f => f.key == 5);
    foreach (var foo in fooList)
    {
        foo.deletedAt = DateTime.UtcNow;
    }
}

parentCollection.Save(parent);

Below are the two c# entities used to map to the Mongo documents. We can use the [BsonIgnoreIfNull] attribute of the mongo c# driver to only serialize the deletedAt field if it contains a value. We also use a nullable DateTime object in our code to allow nulls to be stores if required.
 public class Foo
{
    [BsonId]
    public ObjectId Id { get; set; }
    public int key { get; set; }
    public string value { get; set; }
    public bool isActive { get; set; }

    [BsonIgnoreIfNull]
    public DateTime? deletedAt { get; set; }
}

public class Parent
{
    [BsonId]
    public ObjectId Id { get; set; }
    public List<Foo> subdoc { get; set; }
}

A: See most recent update. A combination of the positional and $currentDate operators is serving my purpose.


text:
Q: Removing purchased ringtones from iPhone I purchased ringtones from Apple when I had my iPhone 6s. When I bought a new iPhone 8 Plus, everything as expected transferred to my new iPhone, so my ringtones are in Settings app → Sounds & Haptics. I wish to remove the purchased ringtones.
I chatted with Apple Support and they suggest I back up new iPhone and reset to factory settings to get rid of the custom ringtones.
Is there any other way?

A: Backing up and restoring your iPhone would restore the ringtones again, and thus is a pointless exercise.
Connect your iPhone to a Mac/PC with iTunes installed. Select you iPhone in the toolbar, locate your iPhone under Devices in the sidebar and click on Tones. You'll should be able to locate the purchased and custom ringtones.

Select the desired ringtones to remove, right click and select Delete from Library option in the context menu.

You'll be prompted to confirm your action. Click on Delete button to complete deleting downloaded and custom ringtones that were installed on you iPhone.


text:
Q: Mixing expression, plain text and newline in ggplot2 expression I am trying to create some labels/stickers using ggplot2.
I am pulling the text for the labels from a source and tyring to plot. I am able to do that as follows:
labtxt1 <- c("This text should be bold", "This text should also be bold", "Another text to be bold")
labtxt1 <- strwrap(labtxt1, width = 20)

labtxt2 <- c("This text should not be bold", "This text should also not be bold", "Another text to be plain")
labtxt2 <- strwrap(labtxt2, width = 20)

library(ggplot2)
library(Hmisc)

labtxt <- c(labtxt1, labtxt2)
labtxt <- paste(labtxt, collapse = "\n", sep = "")
labtxt <- escapeRegex(labtxt)

ggplot(x=1, y = 1) +
  annotate("text", x = 0.5, y = 0.5,
           label = labtxt,
           colour = "red", parse = F, lineheight = 0.8)

How to now make the text in labtxt1 to bold, along with the text in labtxt2 as plain maintaining the justification and linewidth?
I have tried with expression with \n, which messes up the justification, and  with atop, but which messes up the linewidth.
If I try to annotate separately, then positioning is difficult as the lenght of labtxt1 and labtxt2 varies in for different labels/stickers.
How to get the desired result?

A: You could wrap the text in an invisible table,
library(ggplot2)
library(gridExtra)

label <- "plain text\nbold('bold line')\nitalic('italic line')\nplain again"
disect <- strsplit(label, "\\n")[[1]]

mytheme <- ttheme_minimal(core = list(fg_params = list(parse=TRUE, col="red",
                                                       hjust=0, x=0.1)))
tg <- tableGrob(as.matrix(disect), theme=mytheme)

ggplot(x=1, y = 1) +
  annotation_custom(tg)


text:
Q: Wordpress : Add 1 to a variable each time a new post is published Is it possible to detect when the post of a member is published ?
I would like to add 1 to a variable each time a new post is published.
if(new_post_of_specific_user_is_published) {
$variable = $variable + 1;
}

A: you dont need a variable.. a variable is not persistent. you can know how many posts a user has posted though. at any time
$user_post_count = count_user_posts( $userid , $post_type );

yout post type will most likely be 'post'

A: Store the piggy bank as a user meta and each time the members post a new post use the save_post or save_post_custom_post_type filter to add the user meta.
add_action( 'save_post_piggy_bank', 'my_function', 10, 2 );
function my_function($post_id, $post){
    if (defined('DOING_AUTOSAVE') && DOING_AUTOSAVE) return;
    if($post->post_status == 'auto-draft' || $post->post_status == 'trash'){
        return;
    }

    $user_id = get_current_user_id();

    //get the user's piggy bank
    $piggy_bank_amount = get_user_meta($user_id, 'piggy_bank', true);

    //increment their bank by 1
    update_user_meta($user_id, 'piggy_bank', $piggy_bank_amount + 1);
}


text:
Q: curl requests to nginx:alpine docker image being rejected Recv failure: Connection reset by peer I'm trying to debug why my curl requests being sent to a docker container are being rejected on my ubuntu 20.04 machine. I'm running the stock nginx:alpine image.
chris@chris-Precision-7920-Tower  ~  docker images
nginx          alpine                  629df02b47c8   2 months ago    22.3MB
hello-world    latest                  bf756fb1ae65   13 months ago   13.3kB
openjdk        8-jdk-alpine            a3562aa0b991   21 months ago   105MB
 chris@chris-Precision-7920-Tower  ~  docker run  -p 8081:80 nginx:alpine                                                                                 ✔  5437  08:20:32
/docker-entrypoint.sh: /docker-entrypoint.d/ is not empty, will attempt to perform configuration
/docker-entrypoint.sh: Looking for shell scripts in /docker-entrypoint.d/
/docker-entrypoint.sh: Launching /docker-entrypoint.d/10-listen-on-ipv6-by-default.sh
10-listen-on-ipv6-by-default.sh: info: Getting the checksum of /etc/nginx/conf.d/default.conf
10-listen-on-ipv6-by-default.sh: info: Enabled listen on IPv6 in /etc/nginx/conf.d/default.conf
/docker-entrypoint.sh: Launching /docker-entrypoint.d/20-envsubst-on-templates.sh
/docker-entrypoint.sh: Configuration complete; ready for start up

and then i try to send a request to the container with
curl http://0.0.0.0:8081/
curl: (56) Recv failure: Connection reset by peer

I've had this happen to me on more sophisticated images/containers, but this seems to be the minimal reproducible example. With my more sophisticated examples, i have made sure to bind to 0.0.0.0 rather than 127.0.0.1/localhost inside of the container.
docker versions
chris@chris-Precision-7920-Tower  ~  docker --version                        ✔  5447  08:39:08
Docker version 20.10.3, build 48d30b5
 chris@chris-Precision-7920-Tower  ~  dockerd --version                       ✔  5449  08:46:24
Docker version 20.10.3, build 46229ca

A: For dummies (like myself) in the future that have this problem, this was caused by my VPN.
Everything works as expected once my VPN is turned off.


text:
Q: Detach ZF2 event listener during unit tests I have an event listener set up in the module (it checks user permissions) in the onBootstrap method:
// attach permission listener to route event
$eventManager = $e->getApplication()->getEventManager();
$sm = $e->getApplication()->getServiceManager();
$permissionsListener = $sm->get('MyModule\Listener\Permissions');
$permissionsListener->attach($eventManager);

It works OK in the normal application.
For the unit tests, it would be great if I could disable this permission system to easily check that all pages are working correctly without worrying about setting up a fake admin user.
But I don't know how to do it.
In my test, which extends AbstractHttpControllerTestCase, I have done something like this:
// detach permission listener to route event
$sm = Bootstrap::getServiceManager();
$eventManager = $this->getApplication()->getEventManager();
$permissionsListener = $sm->get('MyModule\Listener\Permissions');
$permissionsListener->detach($eventManager);

But this doesn't disable the permission system. How can this be done?

A: In such test case you should not use the real listener instance from your application, but you should set a mock. You can read a lot on how to use mocks in PHP unit-test tutorials. For example here:

It basically involves replacing the actual object with a fake, or 'mock', object that we fully control, removing all dependencies on outside systems or code that we really have no need to test

$className = 'MyModule\Listener\Permissions';
$mock = $this->getMockBuilder($className)->getMock();

Now you can also use the $mock to set values you want to use during the test.


text:
Q: How to make universal gallery and improve admin side of managing galleries? I will describe here steps I made to make my galleries for my first WP theme.
I wanted to have a few links in my menu which will take user to page with thumbnails. Each thumbnail takes user to gallery with bunch of horizontally displayed images.
First, in my functions.php file I've added new size for my icons:
add_image_size( 'wide-image-icon', 200, 150, true );

Then, I've made my template file for gallery category (lets call it Gallery1) and category "Gallery1". In my gallery1.php template file I used query for posts with galleries:
query_posts(array('category_name'=>'Gallery1','posts_per_page'=>-1))

Then, in posts loop I've displayed my gallery icons (which are featured images of posts):
the_post_thumbnail('wide-image-icon');

So now, after creating new page with "Gallery1" template, I can add post, select "Gallery1" category for it, add pictures using standard "Insert gallery", choose one as featured image and I'm good to go.
The problem is that's not universal way of doing this. What if I would like to make another gallery page (Gallery2). Then I need to make new template file, create new category, change category name in query inside template file, add new page with this template attached to it. How do you do it?
I'd also like to ask about some admin side improvements for gallery. I've seen themes where there was a completely new tab inside admin area where you saw all galleries, you could easily change images order, add/remove galleries etc. Right now on my website I add my news ( I use the same system here ), galleries, blog posts and normal pages like "Bio" as posts only which is definitely not good.
PS.
Any articles, video tutorials, books or tips and tricks are welcome.
@edit:
How can I manage display of my galleries on admin side? I'd like to remove whole editor and leave just pictures if you know what I mean.

A: This is all sorts of wrong, you need to first decide if you want to use posts, pages or custom post types.
You alluded at the end that you wanted a new tab like you have seen in some themes, this would be the right way to do it using Custom Post Types.
You can learn how to create them here,
http://codex.wordpress.org/Post_Types#Custom_Types
http://codex.wordpress.org/Function_Reference/register_post_type
After that you can create a template file for your post type that is specific to how you want it to look. For instance say you created a CPT called "Gallery", your theme file can be single-gallery.php. There you can use the loop anyway you want to display and style your photos, and every post made in this post type (Gallery) will use that theme file.

To answer your second question, when you register a new custom post type there are parameters, one of them can enable or disable the editor. The one your looking for is supports --> 'editor'
By default to manage the post's photos you click on Add Photo--->Gallery--> there you find the management options. If you want to customize a new photo management "console" you will have to make another question as it would be to complicated to go into details here, I have seen them but I'm not entirely sure what the best method is to accomplish this.


text:
Q: How to customise the appearance of notify-send? I am running linux mint and use the notify-send command for various purposes, and of course also receive notifications from regular applications e.g. discord or MS Teams
When using Cinnamon DE, they look pretty normal, and I can even add icons to my custom notify-send calls to make it clear what is going on
However, I recently started using XMonad WM, and I'm finding that not only are the regular application notifications ugly, but my custom ones which have nice icons in them also follow that same ugly style (please excuse blurry screenshot):

For example, the above notification should contain an icon as per this command:
notify-send --hint=int:transient:1 'Connecting to VPN... Check 2FA Device.' -i myicon

Where is this configured?

A: Systems that do not use a desktop environment usually require installing a separate notification daemon to handle notifications. It appears that you already have the dunst notification daemon installed.
To configure its appearance, you can edit ~/.config/dunst/dunstrc. If it is not available, you can create a copy from /etc/dunst/dunstrc.
You can modify many different settings such as width, height, font, background and foreground, etc.
Once you have modified the config file, you will have to restart dunst by killing the process (pkill dunst) and starting dunst again as a background process (dunst & disown $!). Generating a new notification will also usually start the dunst daemon but it is recommended to explicitly start dunst in case there are multiple notification daemons.
See man 'dunst(5)' for details on the configuration file.


text:
Q: Page 99 of Hindry's Arithmetics, follows from exact sequence that $\text{N}(IJ) = \text{N}(J)\text{card}(J/IJ)$? Considering the following excerpt from page 98-99 of Hindry's Arithmetics.

Why does it follow from the exact sequence that $\text{N}(IJ) = \text{N}(J)\text{card}(J/IJ)$? Thanks in advance.

A: In an exact sequence
$$0\to A\to B\to C\to 0 $$of abelian groups we have $|B|=|A|\cdot |C|$.


text:
Q: EEPlus excel error only in T.TEST formula I have the following code:
worksheet.Cells[row, 1].Value = Strain.OfficialName;
worksheet.Cells[row, 2].Value = data.Average;
worksheet.Cells[row, 3].Value = data.StandardError;
worksheet.Cells[row, 4].Formula = "T.TEST({" + string.Join(",", controlData) + "},{" + string.Join(",", data.Values) + "},2,3)";

controlData and data.Values are both double[].
The excel file is beeing written, first three values work fine.
The 4th cell on the other hand shows #NAME? error in excel. When I check the formula in the excel file, it looks fine. for example: =T.TEST({98.1578163604527,91.0169216716966,57.6033090316311,153.22195293622},{98.1578163604527,91.0169216716966,57.6033090316311,153.22195293622},2,3)
When I click on the check mark next to the formula it suddenly works and gives a proper value.
I tried adding this after inserting the formula:
worksheet.Cells[row, 4].Calculate();

Didn't work.
I then tried another function:
    worksheet.Cells[row, 4].Formula = "SUM(" + string.Join(",", data.Values) + ")";
    worksheet.Cells[row, 5].Formula = "SUM({" + string.Join(",", data.Values) + "})";

Both cells worked fine. What is so special about the T.TEST function? why am I getting this error?


text:
Q: How to run countdown timer in background I'm doing a project that need countdown timer to limit time for 1 hour.
I have coded this but the countdown timer goes to start at begin every time that I refresh activity.
How should I do.
Here is my code
new CountDownTimer(3600000, 1000) {
                     @Override
                     public void onTick(long millisUntilFinished) {
                         long millis = millisUntilFinished;
                         mTimer.setText("" + String.format("%02d:%02d:%02d", TimeUnit.MILLISECONDS.toHours(millis),
                                 TimeUnit.MILLISECONDS.toMinutes(millis) - TimeUnit.HOURS.toMinutes(TimeUnit.MILLISECONDS.toHours(millis)),
                                 TimeUnit.MILLISECONDS.toSeconds(millis) - TimeUnit.MINUTES.toSeconds(TimeUnit.MILLISECONDS.toMinutes(millis))));
                     }
                     @Override
                     public void onFinish() {
                         mTimer.setText("");
                         unlock();
                         mStatus.setTextColor(Color.parseColor("#f9d540"));
                     }
                 }.start();

Thank you :)
These are my activity codes. I have tried to do it in AsyncTask (just only //waiting)
String ipParse;
long CountTimer;
TextView mName,mUsername,mLicense,mLot,mStatus, mDate, mPayment, mTel,mTimer,mconfirm;
ImageView imageView,Ask;
Button unlock, layout, logout;
private String login_name, user_license, lot_lot;
private IPManager ipManager;
private LoginManager loginManager;
AlertDialog alertDialog;

@Override
protected void onCreate(Bundle savedInstanceState) {
    super.onCreate(savedInstanceState);
    setContentView(R.layout.activity_main);

    loginManager = new LoginManager(this);
    ipManager = new IPManager(this);
    ipParse = ipManager.Read_ip();

    login_name = getIntent().getStringExtra("username");
    user_license = getIntent().getStringExtra("license");
    lot_lot = getIntent().getStringExtra("lot");

    mName     = (TextView) findViewById(R.id.name);
    mUsername = (TextView) findViewById(R.id.user_username);
    mLicense  = (TextView) findViewById(R.id.license_user);
    mLot      = (TextView) findViewById(R.id.yourlot);
    mStatus   = (TextView) findViewById(R.id.status_parking);
    mDate     = (TextView) findViewById(R.id.date);
    mPayment  = (TextView) findViewById(R.id.payment);
    mTel      = (TextView) findViewById(R.id.tel);
    mTimer    = (TextView) findViewById(R.id.Timer);
    mconfirm  = (TextView) findViewById(R.id.confirmation);

    imageView = (ImageView) findViewById(R.id.pic_parking);
    Ask       = (ImageView) findViewById(R.id.pic_Ask);

    unlock = (Button) findViewById(R.id.button_unlock);
    layout = (Button) findViewById(R.id.layout_building);
    logout = (Button) findViewById(R.id.log_out);

    unlock.setVisibility(View.GONE);

    PostFunction postM =new PostFunction();

    //Check Status
    try {
        String resp = postM.postCheck2a(ipParse, user_license, lot_lot);
        JSONObject object = new JSONObject();
        try {
            object = new JSONObject(resp);
            int status = object.getInt("status");
            int status_2a = object.getInt("status_2a");

            //waiting
             if (status == 0 && status_2a == 1){

                 unlock.setVisibility(View.VISIBLE);

                 Ask.setVisibility(View.GONE);

                mconfirm.setText("time for confirmation");
                 mStatus.setTextColor(Color.parseColor("#20b2aa"));

                 new UpdateCountdownTask().execute();

            }

            //wrong lot!!!!
            else if (status == 0 && status_2a == 2){

                 unlock.setVisibility(View.VISIBLE);
                 Ask.setVisibility(View.GONE);

                alertDialog = new AlertDialog.Builder(this).create();
                alertDialog.setTitle("                                      Smart Parking");
                alertDialog.setMessage("             Wrong lot!!  please go to your lot....");
                alertDialog.show();
                TextView textView = (TextView) alertDialog.findViewById(android.R.id.message);
                textView.setTextSize(25);
                textView.setTextColor(Color.RED);
                 mStatus.setTextColor(Color.RED);

                 Ask.setVisibility(View.GONE);

            }

             //Parking
            else if (status == 0 && status_2a == 3){

                 unlock.setVisibility(View.VISIBLE);
                 Ask.setVisibility(View.GONE);

                 mStatus.setTextColor(Color.parseColor("#0dce5e"));
             }

             // getting out
            else if (status == 0 && status_2a == 4){

                 mStatus.setTextColor(Color.parseColor("#f9d540"));

             }

            else if (status == 1) {
                Toast.makeText(MainActivity.this, "Sorry the connection failed......" , Toast.LENGTH_LONG).show();
            }
        } catch (JSONException e) {
            e.printStackTrace();
        }
    } catch (IOException e) {
        e.printStackTrace();
    }

    //show User info
    try {
        String resp = postM.postMain(ipParse,login_name);
        JSONObject object = new JSONObject();
        try {
            object = new JSONObject(resp);
            int status = object.getInt("status");
            if (status == 0) {

                mName.setText(object.getString ("name"));
                mUsername.setText(object.getString("username"));
                mLicense.setText(object.getString("license"));
                mLot.setText(object.getString("lot"));
                mStatus.setText(object.getString("user_status"));
                mDate.setText(object.getString("date"));
                mPayment.setText(object.getString("payment"));
                mTel.setText(object.getString("tel"));

            } else if (status == 1) {
                Toast.makeText(MainActivity.this, "Sorry something wrong..." , Toast.LENGTH_LONG).show();
            }
        } catch (JSONException e) {
            e.printStackTrace();
        }
    } catch (IOException e) {
        e.printStackTrace();
    }

    imageView.setOnClickListener(new View.OnClickListener() {
        @Override
        public void onClick(View v) {
            Intent intent = getIntent();
            finish();
            startActivity(intent);

        }

    });

    Ask.setOnClickListener(new View.OnClickListener() {
        @Override
        public void onClick(View v) {
            Intent intent = new Intent(MainActivity.this, AskFloor.class);
            intent.setFlags(Intent.FLAG_ACTIVITY_CLEAR_TOP);
            intent.putExtra("username", login_name);
            intent.putExtra("license", user_license);
            intent.putExtra("lot", lot_lot);
            startActivity(intent);
        }

    });

    layout.setOnClickListener(new View.OnClickListener() {
        @Override
        public void onClick(View v) {
            Intent intent = new Intent(MainActivity.this, Layout.class);
            startActivity(intent);

        }

    });

    logout.setOnClickListener(new View.OnClickListener() {
        @Override
        public void onClick(View v) {

            loginManager.remove_ExistLogin();
            Intent intent = new Intent(MainActivity.this, LoginActivity.class);
            intent.addFlags(Intent.FLAG_ACTIVITY_CLEAR_TOP);
            intent.addFlags(Intent.FLAG_ACTIVITY_SINGLE_TOP);
            intent.addFlags(Intent.FLAG_ACTIVITY_CLEAR_TASK);
            intent.addFlags(Intent.FLAG_ACTIVITY_NEW_TASK);
            startActivity(intent);
            finish();

        }

    });

    unlock.setOnClickListener(new View.OnClickListener() {
        @Override
        public void onClick(View v) {
            unlock();

        }
    });

}

public void unlock(){
    PostFunction postM =new PostFunction();
    try {

        String resp = postM.postUnlock(ipParse ,login_name, user_license);
        JSONObject object = new JSONObject();
        try {
            object = new JSONObject(resp);
            int status = object.getInt("status");

            if (status == 0) {

                Toast.makeText(MainActivity.this, "UNLOCKED! thank you for coming......", Toast.LENGTH_LONG).show();
                Intent intent = getIntent();
                startActivity(intent);
                finish();

            } else if (status == 1) {
                Toast.makeText(MainActivity.this, "UNLOCK FAILED...", Toast.LENGTH_LONG).show();

            }
        } catch (JSONException e) {
            e.printStackTrace();
        }
    } catch (IOException e) {
        e.printStackTrace();
    }
}

private class UpdateCountdownTask extends AsyncTask<Long, Long, Void> {
    @Override
    protected Void doInBackground(Long... millisUntilFinished) {
        CountDownTimer myCounter = new CountDownTimer(3600000, 1000) {
            @Override
            public void onTick(long millisUntilFinished) {
                publishProgress(millisUntilFinished);
            }
            @Override
            public void onFinish() {
                mTimer.setText("");
                unlock();
                mStatus.setTextColor(Color.parseColor("#f9d540"));
            }
        };
        myCounter.start();
        return null;
    }
    @Override
    protected void onProgressUpdate(Long... millisUntilFinished) {
        super.onProgressUpdate(millisUntilFinished);
        long millis = millisUntilFinished[0];
        mTimer.setText("" + String.format("%02d:%02d:%02d", TimeUnit.MILLISECONDS.toHours(millis),
                TimeUnit.MILLISECONDS.toMinutes(millis) - TimeUnit.HOURS.toMinutes(TimeUnit.MILLISECONDS.toHours(millis)),
                TimeUnit.MILLISECONDS.toSeconds(millis) - TimeUnit.MINUTES.toSeconds(TimeUnit.MILLISECONDS.toMinutes(millis))));
    }
    protected void onPostExecute(Void result) {
        super.onPostExecute(result);
        mTimer.setText("");
    }
}

}

A: Creating CountDown Timer :
Use Static variables so that it will not start as your Activity loads again as :
static long v1=60000;
static long v2=1000;
    new CountDownTimer(v1, v2) {
        public void onTick(long millisUntilFinished) {
            /*for one second*/
            textViewFacebook.setText("seconds remaining: " + millisUntilFinished / v2);
            //here you can have your logic to set text to edittext
        }
        public void onFinish() {
            textViewFacebook.setText("done!");
        }
    }.start();

Just put this code inside AsyncTask backgroud event to run it in background.


text:
Q: writing and opening xlsx file on MAC using numbers I am trying to write a xlsx file on MAC using the following the code.
rm(list=ls())
library(openxlsx)
fn<-"RTest.xlsx"
wb<-createWorkbook()
HomeSheet = addWorksheet(wb,"Home")
writeData(wb,HomeSheet,"R Test",startCol = 2,startRow = 2)
saveWorkbook(wb,fn,overwrite = T)

When I try to open the using the Numbers app, it says file format invalid. But I tried opening another xlsx file that was manually created, it was able to open it.
I am not sure if there is something wrong with the code or if there is something that I am missing. I am new to MAC so dont have much idea about it.

A: library(XLConnect)
wb = loadWorkbook("RTest.xlsx")
new_dataset = readWorksheet(wb, sheet = "Home", header = TRUE)


text:
Q: PHP mb substring functionality with emoji's I have a text

 @Mention text

And I have $start and $length values for @Mention text part, but I am unable to change the text correctly, when string contains emoticons, it is few letter ahead
javascript is passing $start and length from text, it understands
$start = " @Mention ".indexOf('@') //9

Result what I need is something like
 @Mention text

What is the correct function in PHP, with what I can substring replace text.
I've looked online, but no solution
Current output
 @Mention text

$formatted = ' @Mention text ';
$content = $this->mb_substr_replace(
                    $formatted ?: '',
                    "" . mb_substr($formatted ?: '', $mention->getStart() ?: 0, $mention->getLength() ?: 0, 'UTF-8') . "",
                    9,
                    5,
                    'UTF-8'
                );

and the function itself
public function mb_substr_replace($string,$replacement,$start,$length=null,$encoding = null){
    if ($encoding == null){
        if ($length == null){
            return mb_substr($string,0,$start).$replacement;
        }
        else{
            return mb_substr($string,0,$start).$replacement.mb_substr($string,$start + $length);
        }
    }
    else{
        if ($length == null){
            return mb_substr($string,0,$start,$encoding).$replacement;
        }
        else{
            return mb_substr($string,0,$start,$encoding). $replacement. mb_substr($string,$start + $length,mb_strlen($string,$encoding),$encoding);
        }
    }
}


text:
Q: How do I inject dependencies in a Moq for a Unit Test I have a DbContext that I am unit testing with Moq. The DbContext has two dependencies that I Inject with Autofac in my main program. When I unit test Moq tells me it cannot find a parameterless constructor. I add a parameterless constructor in my DbContext and the unit tests pass. Is there not a way to inject the DbContext dependencies with Autofac like I do in my main program?
Here is my unit test:
    [TestMethod]
    public void GetAllPersons_orders_by_name()
    {
        var data = new List<Person>
        {
            new Person { FirstName = "John", LastName = "Doe"},
            new Person { FirstName = "Bill" , LastName = "Smith"},
            new Person { FirstName = "Fred" , LastName = "Williams"}
        }.AsQueryable();

        var mockSet = new Mock<DbSet<Person>>();
        mockSet.As<IQueryable<Person>>().Setup(m => m.Provider).Returns(data.Provider);
        mockSet.As<IQueryable<Person>>().Setup(m => m.Expression).Returns(data.Expression);
        mockSet.As<IQueryable<Person>>().Setup(m => m.ElementType).Returns(data.ElementType);
        mockSet.As<IQueryable<Person>>().Setup(m => m.GetEnumerator()).Returns(data.GetEnumerator());

        var mockContext = new Mock<MyContext>();

        mockContext.Setup(c => c.People).Returns(mockSet.Object);

        var service = new PeopleService(mockContext.Object);
        var people = service.GetAllPeople();

        Assert.AreEqual(3, people.Count);
        Assert.AreEqual("John", people[0].FirstName);
        Assert.AreEqual("Bill", people[1].FirstName);
        Assert.AreEqual("Fred", people[2].FirstName);
    }

A: You can add your constructor args when you create the mock object. So in this case it would be like:
var mockContext = new Mock<MyContext>(myDependecy1, myDependency2 ...);