text:
Q: Why am I getting, "Object reference not set to an instance of an object." but no line of code is implicated? When I try to build my VB.NET solution, I get the error, "Object reference not set to an instance of an object." but in the Error List pane, the File, Line, Column, and Project columns are blank:

How can I solve the problem if it won't tell me where it is?
UPDATE
I selected the Project, then "Show Project Dependency Diagram" and got this:

I don't know what I'm looking at.
UPDATE 2
I don't know if this is unusual or to be expected, but if I mash F5, I do get a page in a browser (http://localhost:2030/) without any err msg; granted, the page looks like North Dakota from an airplane in winter.
UPDATE 3
Now (after fixing a couple of obvious issues, such as unterminated html tags), it won't even say it's fine with a Rebuild All (improving it made it "worse").
With both Rebuild All and Build, I get, "Object reference not set to an instance of an object." but with no indication of where that unset object reference was found.
Scarier yet, when I run Resharper > Inspect > Code Issues in Solution, there are, among other things, 10 VB Compiler Errors, of the following two types:
Cannot resolve symbol '_GridName'
Cannot resolve symbol 'Class1'

Why would there be compiler errors and yet it still compiles? This is getting curiouser and curiouser.
As an idea for how many warnings, errors, etc. this project has, here is an overview of the things that Resharper tsk-tsks about:

20 errors and a thousand other "issues" - it makes me feel like writing a country song!
UPDATE 4
When I right-click the project and select "View in Page Inspector" I see the following:

Could this be the problem and, if so, how do I see to it that the Dev server is running on .NET 4.0 or later?
Or is this a red herring?
UPDATE 5
Now there's a Warning that may shed some light here:
C:\MemberOrderEntry\MembersOrderEntry\MembersOrderEntry\Weyand\Default.aspx: ASP.NET runtime error: Object reference not set to an instance of an object.
This is the line of code the warning implicates:
<%@ Page Language="VB" AutoEventWireup="false" CodeFile="Default.aspx.vb" Inherits="Weyand._Default" title="Web Order Entry" %>

The whole Default.aspx file is:
<%@ Page Language="VB" AutoEventWireup="false" CodeFile="Default.aspx.vb" Inherits="Weyand._Default" title="Web Order Entry" %>

<!DOCTYPE html PUBLIC "-//W3C//DTD XHTML 1.0 Transitional//EN" "http://www.w3.org/TR/xhtml1/DTD/xhtml1-transitional.dtd">

    <title>Order Entry Login Page</title>

<form id="form1" runat="server">

</form>

The other warning is, "Validation (XHTML 1.0 Transitional): Element 'page' is not supported.  C:\MemberOrderEntry\MembersOrderEntry\MembersOrderEntry\Weyand\Default.aspx"
Does this mean anything/make sense to anybody? What needs to be removed or changed in there?
There are many other files with the same exact code:
<%@ Page Language="VB" AutoEventWireup="false" CodeFile="Default.aspx.vb" Inherits="Vinyard._Default" title="Web Order Entry" %>

(except they have "Vinyard" or something else instead of "Weyand"); so why aren't they several Warnings about that same thing, rather than just this?
UDPATE 6
Okay, then! (arghh) If I expand those files in the Solution Explorer, they do elicit warnings. Why would that be? The compiler doesn't notice htem unless they are expanded in Solution Explorer? That makes no sense...
UDPATE 7
Is "Element 'page' is not supported" the root of the problem?
With three of the folders expanded, I see:

The "page" is like so:
<%@ Page Language="VB" AutoEventWireup="false" CodeFile="Default.aspx.vb" Inherits="Vinyard._Default" title="Web Order Entry" %>

<!DOCTYPE html PUBLIC "-//W3C//DTD XHTML 1.0 Transitional//EN" "http://www.w3.org/TR/xhtml1/DTD/xhtml1-transitional.dtd">

It seems that each "Page" is problematic; and for each one, there is a possibly corresponding "ASP.NET runtime error: Object ref not set" warning - which may be what causes the error of the same type.
If the 'Page' element is the/a problem, what is the fix for it?
If I simply remove it, like so:
<%@Language="VB" AutoEventWireup="false" CodeFile="Default.aspx.vb" Inherits="Vinyard._Default" title="Web Order Entry" %>

...then I get, "Element '' is not supported." It's not just a Catch-22, because many more errors are caught than that, when everything is expanded.
UPDATE 8
The errors cause me to wonder: What does the "Inherits" directive signify? I have such as:
Inherits="CapitolCity._Default"

In more context, the appear within Default.aspx files like so:
<%@ Page Language="VB" AutoEventWireup="false" CodeFile="Default.aspx.vb" Inherits="CapitolCity._Default" title="Web Order Entry" %>

There is no "CapitolCity._Default" file anywhere that I can see (which is apparently supposedly what is being "inherited"). What is being inherited here, or trying to be inherited?
In this case, the file with the line above is Default.aspx, beneath/within the \\CapitolCity folder. Beneath it is the Default.aspx.vb file.
There is a \\Default.aspx file, with a Default.aspx.vb beneath it. The first is:
<%@ Page Language="VB" AutoEventWireup="false" CodeFile="Default.aspx.vb" Inherits="_Default" title="Web Order Entry" %>

<!DOCTYPE html PUBLIC "-//W3C//DTD XHTML 1.0 Transitional//EN" "http://www.w3.org/TR/xhtml1/DTD/xhtml1-transitional.dtd">

    <title></title>

<form id="form1" runat="server">

</form>

Is there something wrong with it, and if not, what could be causing this gigantic headache?

A: This was an incredibly strange issue, but since there it has been solved, it might as well get an answer.
I think it's a bug in the .suo files, as my VS was behaving oddly lately, my programs suddenly started crashing, not building and saying the Office references were not valid.
One fix I tried was cleaning and re-building the solution, which worked about 1/4 in times, the other times I had to physically remove and add the references again, and then rebuild the whole solution.
After getting fed up of doing that for a week or so, I just created a backup elsewhere on our work server, deleting the .suo files in the new folder, then opening and building the whole solution.
It fixed it. Not sure why, or what went wrong, but now and then strange things happen in the .suo files and references.


text:
Q: How can I read buffer data from the type script?(Solana) How can I read buffer data from the type script?
I want to use the public key to get all the token lists I own.
I'm trying to get this, but an empty array of objects is being returned.
import {Connection, Keypair} from "@solana/web3.js";

const Solana = new Connection("https://api.testnet.solana.com/","confirmed")
const getInfo = async () => {
    const recentInfo = await Solana.getEpochInfo()
    const DEMO_FROM_SECRET_KEY = new Uint8Array([
       223, 119, 171,   5, 237, 138,  42, 140, 176, 163,  74,
      107,  25, 143,  90,  97, 250, 158, 203, 102, 238,  19,
       77, 228, 211, 238, 147, 149,  40,  50, 211, 155,  51,
      207,  14,  53,  86, 230, 164,  27,  14, 202,  78, 181,
      185, 250,  16,  52, 134, 242,  96,  16,  12,  67,   2,
      178, 106, 241, 156, 212,  11, 150, 114,  72])
    const keypair = Keypair.fromSecretKey(DEMO_FROM_SECRET_KEY)

    console.log("=============get account info==============")
    async function fetchaccountdata() {
        const accountinfo = await Solana.getParsedAccountInfo(keypair.publicKey,"max")
        const accountinfodata =  JSON.stringify(accountinfo)
        const accountinfodata2 = JSON.parse(accountinfodata)
        console.log(accountinfo)
        console.log("=============get account info==============")
        console.log(accountinfodata)
        console.log(accountinfodata2)
    }
    fetchaccountdata()
}
getInfo()

Terminal is
accountinfodata = {"context":{"slot":94636033},"value":{"data":{"type":"Buffer","data":[]},"executable":false,"lamports":42784111360,"owner":{"_bn":"00"},"rentEpoch":231}}

accountinfodata2 = {
  context: { slot: 94636033 },
  value: {
    data: { type: 'Buffer', data: [] },
    executable: false,
    lamports: 42784111360,
    owner: { _bn: '00' },
    rentEpoch: 231
  }
}

The data of accountinfo object is empty array.
How can I read the information?

A: This call is fetching the account data for your wallet.  Your wallet only holds SOL, which is why the data is nothing!
If you want to get all of the token accounts that you own, you'll be better off using getParsedTokenAccountsByOwner: https://github.com/solana-labs/solana/blob/2a42f8a06edd4d33c6cda4d66add0a2582d37011/web3.js/src/connection.ts#L2310

A: The buffer contains account info data in no particular format. Borsh has recently been established as a standard, though.
Example borsh serialization from SPL:
https://github.com/solana-labs/solana-program-library/blob/master/token/program/src/state.rs#L128
Example borsh deserialization for metaplex metadata: https://github.com/metaplex-foundation/metaplex-program-library/blob/master/token-metadata/program/src/instruction.rs#L77-L78
If you aren't trying to decode metaplex metadata, you should look elsewhere for the schema, but follow the same principles of the code. If you know the account isn't using borsh, then it's up to you to decode it.
Visit the solana tech discord for more information/help.
https://discord.com/channels/428295358100013066/517163444747894795/917412508418068510

redpajama_set_name: RedPajamaStackExchange


text:
Q: Various linking issues when adding VCLFixPack.pas When adding VCLFixPack.pas (latest as of 2013-09-27) to my projects I get strange linking errors for some of them. Some compile fine, but for some it complains about not finding TYPES.OBJ or DBGRIDS.OBJ etc when linking.
Any idea what the issue is?
VCLFixPack is found here
http://andy.jgknet.de/blog/

A: It sounds like you're missing the path to the delphi lib files from your link line.
If memory serves, for 2010 you needed $(BDS)\lib and $(BDS)\lib\release in your linker paths
(Project->Options->Paths and Directories->Library Paths)


text:
Q: gcloud app deploy failed: Docker image not found or not in V2 format Running gcloud app deploy exists with the following error:
Updating service [default] (this may take several minutes)...failed.
ERROR: (gcloud.app.deploy) Error Response: [3] Docker image eu.gcr.io/<My Project ID>/appengine/default.20181106t223832:latest was either not found, or is not in Docker V2 format.  Please visit https://cloud.google.com/container-registry/docs/ui.
Preceding Step #1 was done successfully:
$ gcloud app deploy
...
Step #1: yarn install v1.12.1
Step #1: [1/5] Validating package.json...
Step #1: [2/5] Resolving packages...
Step #1: [3/5] Fetching packages...
Step #1: info fsevents@1.1.3: The platform "linux" is incompatible with this module.
Step #1: info "fsevents@1.1.3" is an optional dependency and failed compatibility check. Excluding it from installation.
Step #1: [4/5] Linking dependencies...
Step #1: [5/5] Building fresh packages...
Step #1: success Saved lockfile.
Step #1: Done in 50.02s.
Step #1: Removing intermediate container 0a787554186f
Step #1:  ---> 9032a35b322e
Step #1: Step 5/5 : CMD yarn start
Step #1:  ---> Running in 8f565dd17c36
Step #1: Removing intermediate container 8f565dd17c36
Step #1:  ---> fc272a02adef
Step #1: Successfully built fc272a02adef
Step #1: Successfully tagged eu.gcr.io/<My Project ID>/appengine/default.20181106t225117:latest
Finished Step #1
PUSH
DONE
------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------

Updating service [default] (this may take several minutes)...failed.
ERROR: (gcloud.app.deploy) Error Response: [3] Docker image eu.gcr.io/<My Project ID>/appengine/default.20181106t225117:latest was either not found, or is not in Docker V2 format.  Please visit https://cloud.google.com/container-registry/docs/ui

I have deployed this app a month ago without any problems.
$ gcloud --version
Google Cloud SDK 224.0.0
bq 2.0.36
core 2018.11.02
gsutil 4.34


text:
Q: How to do a toeplitz matrix efficiently matlab Let's suppose I have a vector x and 2 constants initialized as follows:
x = [ones(1,21) zeros(1,79)]; %step of 100 components
p = 2; q = 0;

Now, I want to build this matrix:

But in this case for example x(q-1) = x(-1) doesn't exist, so I want it to be 0, and I was wondering if there is a way to do it with the minimum lines of code. Note that the matrix can be written with the function toeplitz(), but I don't know how to replace nonexistent position of my vector x with zeros.
I hope someone can help me. Thank you for your answers.

A: You need to be careful about zero-based or one-based indexing.
In your question, you state that negative indices are invalid - in MATLAB the index 0 is also invalid. The below code assumes your x(q) is zero-based as described, but I do a +1 conversion. Be aware of this if q+p-1 is near numel(x).
x = [ones(1,21) zeros(1,79)]; %step of 100 components
p = 2; q = 0;

% Set up indexing matrix using implicit expansion (R2016b or newer)
m = ( q:-1:q-p+1 ) + ( 0:1:q+p-1 ).';
% Convert from 0-based to 1-based for MATLAB
m = m + 1;
% Set up output matrix, defaulting to zero
M = zeros( size( m ) );
% Put elements where 'm' is valid from 'x' into output 'M'
M( m > 0 ) = x( m( m > 0 ) );

The output is a (q+p) * p matrix.


text:
Q: Replace Win 10 with Ubuntu completely I've just bought a new Lenovo laptop with Win 10 preinstalled. I want to completely uninstall it and install Ubuntu or another Linux. I don't know yet what kind of protection it has from installing or removing windows, but I figure it's the latest one whatever it is. My question is, can I completely replace Win 10 with Ubuntu or another Linux and are there any difficulties?
update:
I've chosen another Linix distributes and created a bootable usb drive by using my another Linux machine:
dd bs=4M if=/my_linux.iso of=/dev/sdb status=progress && sync

And when I booted and chose "Boot from USB drive" with the name of my usb drive, nothing happened, it just hung for a few seconds and then returned back to the menu where I can choose the boot order.

A: Yes, you can definitely do it:

*

*Download the .iso of the Linux distro you desire.

*Download the Universal USB installer.

*Use the universal USB installer to create a bootable media, preferably a pen drive

*Restart your PC and boot from the pendrive. You may need to go  into the BIOS and change boot device preference.

*You will be guided through the installation procedure. It's quite informative and self explanatory.

*Choose the correct set of options and if you face a doubt, feel free to ask.


text:
Q: Custom attribute filter for product listing not working I am trying to filter products using category and products with categorie and location but the filter not working here's my code
<?php
$ty=array(34,15);
foreach($ty as $categoryid) {
$category = new Mage_Catalog_Model_Category();
$category->load($categoryid); //My cat id is 10
$prodCollection = $category->getProductCollection();
$prodCollection->addAttributeToSelect('name','product_location');
$prodCollection->addAttributeToFilter('product_location', array('like' => 'Bangalore, Karnataka, India'));
foreach ($prodCollection as $product) {
$prdIds[] = $product->getId(); ///Store all th eproduct id in $prdIds array
}
foreach($prdIds as $_prdIds){
$product_id = $_prdIds;
$obj = Mage::getModel('catalog/product');
$_product = $obj->load($product_id); // Enter your Product Id in $product_id
$prdId1s[]=$_product;
}
$_productCollection = $prdId1s;
}
?>

A: I think For product_location you are using multiselect, so you have to use findset in your code and in findset you have to pass optionId for every option not option value right now you have pass option value like banglore,india But you have to pass option Id in array With in fineset
Create array like below with optionId
array(10,20,30)
and after that your addAttributeToFilter Belike
->addFieldToFilter('product_location',
            array(
                array('finset'=> array(your array variable)),
                                )
        )


text:
Q: Копирование TCHAR* строки из другого потока Я хочу скопировать имя клиента из другого потока. При отладке вижу что передается в поток "клиент1", однако вывести с помощью _tprintf() не получается. В потоке, из которого происходит копирование, "клиент1" выводится правильно.

Код потока, который пытается скопировать имя:
static DWORD WINAPI StdinInfo(LPVOID param)
{
   struct msg msg;
   TCHAR buf[1280] = { 0 };
   parameters* p = (parameters*)param;

  while (TRUE)
  {

   _fgetts(buf, 1280, stdin);
   while (_tcslen(buf) > 0 && buf[_tcslen(buf) - 1] == TEXT('\n'))
        buf[_tcslen(buf) - 1] = TEXT('\0');

   buf[128] = TEXT('\0');
   if (!_tcscmp(buf, TEXT("stop")))
   {
        //printf("Terminating...\n");
        msg.isEmpty = 0;
        msg.type = STOP;
        _tcscpy(msg.message, buf);
        _tcscpy(msg.nickName, p->nickName);

        SendMessage(p, &msg);
        break;
   }
   else if (!_tcscmp(buf, TEXT("exit")))
   {
        msg.isEmpty = 0;
        msg.type = DISCONNECT;
        _tcscpy(msg.message, buf);
        _tcscpy(msg.nickName, p->nickName);
        SendMessage(p, &msg);
        break;
   }

   msg.isEmpty = 0;
   msg.type = MESSAGE;
   _tcscpy(msg.message, buf);
   _tcscpy(msg.nickName, p->nickName);

   _tprintf(TEXT(" IN TREAD %s %s\n"), msg.message, p->nickName);

   SendMessage(p, &msg);
  }

  return 0;
}

Так же заметил, что если использовать _tcprintf(), то "клиент1" выведется правильно, однако уже не выведется "текст". Пожалуйста объясните почему так происходит, и как решить проблему

A: SendMessage - это быстрая операция, ее нужно трактовать как "положи в очередь вот эту команду и побежали дальше, дожидаться ее завершения не нужно". Так как потоки работают в паралель, то вполне возможно, что когда второй поток решит выполнить обработку строки, в посылающей функции уже могло пройти несколько итераций и содержимое буфера десять раз поменяться. А Вы же передаете не буфер, а просто указатель на него.
Это была причина. Но что же делать? Есть два основных выхода.

*

*делать копию буфера перед отправкой ( а можно и полную копию переменных). Но только выделять нужно их динамически, через malloc и подобное. Недостаток этого способа - нужно аккуратно подчищать память после обработки. Так как структура половины структур мне не понятна, код написать не смогу.

*делать блокировку. Использовать PostMessage. Изменений в коде будет минимум, но и плата за это соответствующая. Теперь вызывающий поток будет блокироваться на время обработки события.


text:
Q: How to get color of notification for Android? Some notifications have their small notification icon appear as a badge in the bottom left corner of the big icon (See first, second and last notification).

However, post-Lollipop, the OS automatically sets a white color filter to the small icons and whenever I try to obtain them for display from my NotificationListenerService, they're returned in white. Is there any way I can extract the background color for the small icons, or obtain the small icon directly as colored drawables, as-is? Below is my code, which only returns completely white icons.
public void onNotificationPosted(StatusBarNotification sbn) {
    super.onNotificationPosted(sbn);

    Bundle extras = sbn.getNotification().extras;
    int smallNotiIcon = extras.getInt(Notification.EXTRA_SMALL_ICON);

    //Code to display obtained small icon in an imageView shows up as white
}

A: The color can be retrieved from a notification via the color public field:
Notification notification = sbn.getNotification();
// ARGB color set with the notification
int color = notification.color;

There is also COLOR_DEFAULT as the default color of a notification, which you can use to see if a custom color is set at all.


text:
Q: How to get API data from MS Health Band in MATLAB I am trying to get the real time data from MS Health Band to perform analysis in MATLAB. I am trying to follow the documentation, but I can't figure out how to implement this in MATLAB. Any suggestion would be really appreciated.

A: If you would like to get real time (sensor) data from a Microsoft Band, then it's not the MS Health API, but the Microsoft Band SDK that you'll need. It includes functions to enable sensors and receive streaming data.
This SDK exists only for Windows (C#), Android (Java) and iOS (Objective C). There is no MATLAB library. If you need to process the data in real time, one thing you could try is to write an application (using one of these libraries), that writes the incoming sensor data to a file, that is read and processed by your MATLAB code.


text:
Q: SQL LAST() Function not working with phpmyadmin? I try to query last row from databases, so I use this fucntion LAST(column_name). It doesn't work for me I don't know why.
This is an error message that phpmyadmin replys to me
SQL query: Documentation

SELECT LAST(power) FROM f01_r02
LIMIT 0, 25
MySQL said: Documentation

#1064 - 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 '(power) FROM f01_r0 LIMIT 0, 25' at line 1

I do follow this link
SQL LAST() Function
Actually, I know that there are a lot of ways to obtian lastest row data in mysql, but I want to try this function first so, if it impossible to use this fucntion I will go to another solution.

A: In MySQL there is no implementation of the FIRST() and LAST() aggregation functions.

A: Mysql does not support last() function, thetefore you cannot use it in mysql.


text:
Q: Filter processes by command name in Linux How do I filter based on command name? For example, find commands with the text "python". This is what I have now, which doesn't filter:
 ps -u my_user -o pid,rss,command | awk '{print $0}{sum+=$2} END {print "Total", sum/1024, "MB"}'

A: Figured it out. Added
| grep text_i_want

to the end.


text:
Q: Invalid RSS Feed. Undefined item element: media:backLinks When I run my rss http://www.goalscout.com/static/rss2.xml through http://validator.w3.org/feed/ I get the error message
This feed does not validate.
line 14, column 9: Undefined item element: media:backLinks (2 occurrences) [help]

<media:backLinks>

So I'm unable to understand what's wrong with this xml.
XML namespace for media it seems be correctly defined, as RSS Advisory Board reccomends, I had googled around for few hours but no one had same problem.
Thanks to anyone who can point me in the right direction.

A: The rss feed contains additional elements within the item element.
These additional elements are in the namespace http://search.yahoo.com/mrss/, but the validator does not have any schema information for this namespace.
<media:backLinks>

This should be OK as the RSS schema says that the validation on unknown elements should be 'lax' which means only validate them if you know what they are.
However the validator you are using seems a little over zealous, and is flagging these as errors, they should be warnings at most.
To my eye the rss feed looks valid.


text:
Q: how to make camera follow only in + x axis (forward only)? base on this script i got in here..
public GameObject MyCamera; // The camera you want to follow the GameObject
    public GameObject ObjectToFollow; // What you want to follow
private Vector3 CameraPos ; // Variable that contains the Cameras x,y,z position

void Start()
{
    CameraPos = MyCamera.transform.position; // stores the Camera's position in the variable
}

// Update is called once per frame
void Update()
{

    CameraPos.x = ObjectToFollow.transform.position.x; // Change The X position on the camera variable to be the same as the ObjectToFollow X position
    MyCamera.transform.position = CameraPos; // Moves the Camera to the new position

}

this script make camera follow the player in the x axis (forward and backward)
how to change the code? to  make camera follow only for forward or + x axis?

A: void LateUpdate()
{
    if(MyCamera.transform.position.x < ObjectToFollow.transform.position.x){
        CameraPos.x = ObjectToFollow.transform.position.x;
        MyCamera.transform.position = CameraPos;
    }
}

This code will make your camera follow the character just for + x-axis. I also realised that you're using Update instead of LateUpdate. However, you should use LateUpdate for the camera updates. You can check the related documentation about this.


text:
Q: derivation for gradient of a vector in polar coordinates using tensor calculus I am trying to derive the expression for gradient of a vector using tools from tensor calculus and I am not able to get the correct expression. I have written down the derivation down here :
Notation : $Z^i$ are contravariant vector components i.e. $r,\theta$. $\mathbf{Z}_i$ are covariant vectors. $\mathbf{g}$ is metric tensor such that $g_{ij}=\mathbf{Z}_i . \mathbf{Z}_j$
For a scalar function $S(r, \theta)$, the definition gradient is
$$
\nabla S = \frac{\partial S}{\partial Z^i} g^{ij} \mathbf{Z}_j  =\frac{\partial S}{\partial Z^i}\mathbf{Z}^i =  \frac{\partial S}{\partial r} \hat{r} + \frac{1}{r}\frac{\partial S}{\partial \theta} \hat{\theta}
$$
In the above expression $\mathbf{Z}^2 = \hat{\theta}/r$.
Now using above formula, I tried to write gradient of a vector, which gives
$$\nabla \mathbf{V} = \frac{\partial \mathbf{V}}{\partial Z^i}\mathbf{Z^i} = \frac{ \partial \big( V^k \mathbf{Z}_k \big)}{\partial Z^i}\mathbf{Z^i} =g^{ij} \Big( \frac{\partial V^k}{\partial Z^i} + \Gamma^k_{im}V^m \Big) Z_k Z_j = T^{kj} Z_k Z_j.$$

For Polar co-ordinates
$$
\mathbf{g} = \begin{bmatrix}
1 & 0 \\
0 & r^2
\end{bmatrix} \hspace{20pt} \mathbf{g}^{-1} = \begin{bmatrix}
1 & 0 \\
0 & r^{-2}
\end{bmatrix}
$$
and
$$\Gamma_{22}^{1}=-r \quad \Gamma_{12}^{2}=\frac{1}{r} \quad \Gamma_{21}^{2}=\frac{1}{r}
$$
and rest of the value of christoffel tensor are zero.

Now using this information, we can write
$$T^{11} = g^{i1} \Big( \frac{\partial V^1}{\partial Z^i} + \Gamma^1_{im} V^m\Big) $$
$$ = g^{11} \Big( \frac{\partial V^1}{\partial Z^1} + \Gamma^1_{11} V^1 + \Gamma^1_{12} V^2\Big) = \frac{\partial V^1}{\partial r} $$
Which is an expected answer. But other values that I calculate are wrong.
For example,
$$T^{12} = g^{i2} \Big( \frac{\partial V^1}{\partial Z^i} + \Gamma^1_{im} V^m\Big) $$
$$ = g^{22} \Big( \frac{\partial V^1}{\partial Z^2} + \Gamma^1_{21} V^1 + \Gamma^1_{22} V^2\Big) $$
$$ = \frac{1}{ r^2 } \Big( \frac{\partial V^1}{\partial Z^2} + \frac{V^1}{r} - r V^2 \Big)$$
Above calculation implies that
$$T^{12} = \frac{\partial V_r}{\partial \theta} + \frac{V_r}{r^2} -
\frac{V_\theta}{r} $$
but this is not the correct answer. The correct answer is
$$T^{12}= \frac{\partial V_r}{\partial \theta} -
\frac{V_\theta}{r} $$
I am not sure, why am I getting extra $V_r/r^2$ term. Can you please let me know what am I doing wrong. I will then complete the calculation and upload the final answer with all calculations here.


text:
Q: SPARQL results that exists only in one of two languages I have to do a SPARQL query that should output the results that have a label in English but not in Russian. The output should be just the results in English language.
I will put here the code that I was trying to do:
select ?m ?l where {
   ?m rdf:type dbo:Mountain;
      dbo:locatedInArea dbr:Nepal;
      dbo:elevation ?a;
      rdfs:label ?l.
FILTER ((?a >= 8000) && (langMatches(lang(?l), "en")) )

MINUS {

select ?m ?l where {
   ?m rdf:type dbo:Mountain;
      dbo:locatedInArea dbr:Nepal;
      dbo:elevation ?a;
      rdfs:label ?l.
   FILTER ((?a >= 8000) && (langMatches(lang(?l), "ru")) )}
 }
}


text:
Q: I want to check whether all elements(integers) from starting to ending in an array are equal In an array, I have to check whether all elements are same.
For example:
a[]={2,2,2,2,2,2,2}
    for(i=0;i<n;++i)
    {
        if(a[0] == a[i])
        {
            f = 1;
            break;
        }
    }
    if(f == 1)
    printf("All elements are same");

It is giving me true, when any two elements are same. But I have to check whether all elements are same or not.

A: Just invert the logic, really. And you can start iterating from 1, since you're comparing to a[0]:
f = 1;
for (i = 1; i < n; ++i)
  if (a[i] != a[0]) {
    f = 0;
    break;
  }

if (f == 1)
  printf("All elements are the same");

A: Here's another approach, more similar to your idea than other answers
f = 0; // start with 0 equals
for(i=0;i<n;++i)
{
    if(a[0] == a[i])
    {
        f += 1; // add 1 when finds pair of equals
        // break; // don't break: look at **ALL** elements
    }
}
if(f == n) /* if total pairs is total elements */
printf("All elements are same");

Note: this approach has to look at ALL elements. It is much more efficient to use an approach that minimizes the number of elements to compare.

A: A good idea for check if all list items are equal, is to find min and max, and compere them.

*

*If they are equal - that means that the whole list (or arry and etc.) is equal.

*If they are not equal - that means that not the whole list is equal.
Good Luck!

A: f = 1;
...
if(a[0] != a[i])
{
  f = 0;
  break;
}
...
if(f == 1)
    printf("All elements are same");


text:
Q: Android Studio 2.3 stopped finding some files in find Filename (Cmd+Shift+O) I have been using
Android Studio 2.3.3
Build #AI-162.4069837, built on June 6, 2017
JRE: 1.8.0_112-release-b06 x86_64
JVM: OpenJDK 64-Bit Server VM by JetBrains s.r.o

For some reason, recently, it doesn't find files, Java or Kotlin, under a certain subdirectory.
More strange things:

*

*It does find files under any other directory

*If I create a new file, sibling to the files it fails to find, be it Java or Kotlin, Cmd+Shift+O will find them.

*Double Shift (find all) or find class - finds them

*I tried to delete .idea, all *.iml and the build folder, and reopen the project. No success.

*It does find some .puml files. Anything that's not a class file.

Does anybody know what could have happened to Android Studio that its simplest search, find by filename, has gone bad?
Update

*

*Move the subtree to some quarantine folder or a zip

*Then open Android Studio. Let it fail on compilation

*Put the files back

That is not a solution but it does a band-aid fix.

A: Cleaning Android studio, not the project caches worked.
File -> Invalidate caches/Restart (not sure if that would be enough).
To be 100% sure, do it the manual way: they are in:
~/Library/Caches/AndroidStudio2.3

Feel free to kill them all.
Close Android Studio
rm -rf ~/Library/Caches/AndroidStudio2.3

And don't forget to do a wicked grinning before pressing Enter :)
Turn on your Android Studio and: Magic! It's all fixed. You can find your files again.
Note that I suspect it may be a cause of switching versions back and forth. When switching versions, Android Studio has to index a different snapshot of your code along time. It may potentially be a cause for bugs.


text:
Q: imports fail in subfolder I have a Python project, that uses some code from a Github repo. I added the repo using git submodule add. So now I have the following file-structure:
ProjectFolder\
    foo.py
    BarProject\ (the Github repo added with submodule)
        bar.py
        baz.py

In my main file foo.py I want to import the method bar from the file bar.py:
from BarProject.bar import bar

This fails, because the first line of bar.py is :
from baz import *

And Python throws an ImportError, because it cannot find the module baz.

Is there a way to import the file bar.py in a way, so that the relative imports don't get screwed up? I don't really want to modify bar.py or baz.py, because they are part of an external Github project.

A: remember to add __init__.py to BarProject folder to indicate that folder is a package.


text:
Q: Import from wordpress to wordpress I'm trying to import all my stuff from videomarathon.com/dk to videomarathon.com/se (posts etc.)
I'm using wordpress importer.
When uploading the exported file, it shows me this error:

Error 503 Service Unavailable
Service Unavailable
Guru Meditation:
XID: 1333795156
Varnish cache server

Does anyone know what it means?
Is there anyone who might know another plugin for importing?
I'm using multiple sites, so maybe that's an issue?!

*

*Thanks!

A: HTTP Error 503 - Service unavailable
The Web server (running the Web site) is currently unable to handle the HTTP request due to a temporary overloading or maintenance of the server. The implication is that this is a temporary condition which will be alleviated after some delay. Some servers in this state may also simply refuse the socket connection, in which case a different error may be generated because the socket creation timed out.
503 errors in the HTTP cycle
Any client (e.g. your Web browser or our CheckUpDown robot) goes through the following cycle when it communicates with the Web server:
Obtain an IP address from the IP name of the site (the site URL without the leading 'http://'). This lookup (conversion of IP name to IP address) is provided by domain name servers (DNSs).
Open an IP socket connection to that IP address.
Write an HTTP data stream through that socket.
Receive an HTTP data stream back from the Web server in response. This data stream contains status codes whose values are determined by the HTTP protocol. Parse this data stream for status codes and other useful information.
This error occurs in the final step above when the client receives an HTTP status code that it recognises as '503'.
Fixing 503 errors
The Web server is effectively 'closed for repair'. It is still functioning minimally because it can at least respond with a 503 status code, but full service is impossible i.e. the Web site is simply unavailable. There are a myriad possible reasons for this, but generally it is because of some human intervention by the operators of the Web server machine. You can usually expect that someone is working on the problem, and normal service will resume as soon as possible.
Please contact the system operators of the Web site (e.g. your ISP) to determine why the service is down. They will be in a much better position to help you than we are for this type of error.

A: Talk to your web host; it's an error at your web host one.com. The WP import plugin will work fine once the host problems are fixed.
And there's already an answer here to the same quesiton: Varnish: Guru Meditation


text:
Q: Call Javascript functions in succession Goal: I am trying to create a slightly dynamic page animated with basic canvas animations using setInterval(). When the user first goes to the page, a background image displays. Then a canvas appears over it and gradually the opacity increases to completely opaque black. After the canvas is black, I want white text to appear over my black canvas.
Problem: The canvas transition and the text appear at the same time.
I have researched this issue, and there appears to be a panoply of solutions here. I have already tried many variations in my own code. Once I had two separate functions. Another time I tried calling a function which then called both functions in succession. I read a blog about creating an array of functions, and then looping through the functions. That idea is intriguing, but I am wondering if there is something much more simple here that will suffice.
I was working with it on jsfiddle, but the website is not cooperating at the moment. So here is what I have right now:

        <canvas id="myCanvas" width="675" height="600">

Your browser doesn't support canvas.

        </canvas>

#myCanvas{
width:675px;
height:600px;
float:left;
}
#canvasWrapper{
width:675px;
height:600px;
margin:auto;
}
#RtButton{
    float:right;
margin-right:34px;
}
#LftButton{
    float:left;
margin-left:34px;
}
#RtButton, #LftButton{
margin-top:200px;
}

var drawing = document.getElementById("myCanvas");
//Initialize drawing context
var ctx = drawing.getContext("2d");
//Canvas commands follow
var alphaCounter = .033;

function fadeCanvas(){
ctx.fillStyle = "rgba(0,0,0," + alphaCounter + ")";
ctx.fillRect(0,0,675,600);
alphaCounter += .03;
}
function display411(){
ctx.fillStyle=('#fff');
ctx.font='bold 14px + "Courier New, Courier, monospace" +';
ctx.fillText('Click the arrow keys forward to reveal the bigger picture.', 100,100);
}
function init(){
setInterval(fadeCanvas,100);
ctx.save();
setTimeout(display411(), 5000)
}
window.onload = init();

Thoughts?

A: setTimeout(display411(), 5000)
window.onload = init();

You are executing the functions directly then and there, when you just want to pass them around. Get rid of the ():
setTimeout(display411, 5000);
window.onload = init;

A: You have two problems.
1. as another commentor has mentioned, your setTimeout call was incorrect
2. Even if you correct the setTimeout call, the fadeCanvas() interval will immediately overwrite whatever text you display.
In my opinion, the best approach is to test for 100% opacity within fadeCanvas(), and once that goal is reached, clear the interval and call display411() directly.
function fadeCanvas(){
    ctx.fillStyle = "rgba(0,0,0," + alphaCounter + ")";
    ctx.fillRect(0,0,675,600);
    alphaCounter += .03;
    if (alphaCounter >= 1) {
        clearInterval(fadeToBlack);
        display411();
    }
}

function init(){
    fadeToBlack = setInterval(fadeCanvas,100);
    ctx.save();
    //setTimeout(display411(), 5000)
}

A: Here's a fairly simple setup (it's perhaps a bit complex for this simple task, but you can reuse the pattern, and/or abstract it, if you need more effects)
function fadeBlack(callback) {
  var timer,
      context = getElementById('myCanvas').getContext("2d"),
      opacity = 0;

  function step() {
    opacity += 0.03;
    context.fillStyle "rgba(0,0,0," + opacity + ")";
    context.fillRect(0,0,675,600);
    if( opacity >= 1 ) {
      clearInterval(timer);
      if( typeof callback === "function" ) {
        callback();
      }
    }
  }

  setInterval(step, 100);
}

fadeBlack(function() {
  var context = getElementById('myCanvas').getContext("2d");
  context.fillStyle = '#fff';
  context.font      = 'bold 14px + "Courier New, Courier, monospace" +';
  context.fillText('Click the arrow keys forward to reveal the bigger picture.', 100,100);
});

When fadeBlack completes, it calls the callback, which - in this case - draws the text


text:
Q: Let $S^n := \{x \in \mathbb R^{n+1} \mid x_1^2+ \cdots+x_{n+1}^2 = 1\}$. Then $S^n$ is a smooth $n$-dimensional manifold This is my first proof in differential geometry. Could you have a check if I  understand the concepts correctly.
Theorem: Let $S^n := \{x \in \mathbb R^{n+1} \mid x_1^2+ \cdots+x_{n+1}^2 = 1\}$. Then $S^n$ is a smooth $n$-dimensional manifold.
Proof: Let $S^n_{+i} := \{x \in S^n \mid x_{i} > 0\}$ and $S^n_{-i} := \{x \in S^n \mid x_{i} < 0\}$ for $i = 1,\ldots, n+1$, and ${\mathbb B}_n (0, 1)$ be the open ball with center $0 \in \mathbb R^n$ and radii $1$. Notice that

*

*$S^n_{+i}$ and $S^n_{-i}$ are open in $S^n$ w.r.t. the relative topology of $S^n$. This is due to the strict inequality signs "$<$" and "$>$".

*Each $x \in S^n$ belongs to $S^n_{+i}$ or $S^n_{+i}$ for some $i$.
Consider $$\varphi_{+i} : S^n_{+i} \to {\mathbb B}_n (0, 1) \quad \text{and} \quad \varphi_{-i} : S^n_{-i} \to {\mathbb B}_n (0, 1),$$ where $\varphi_{+i} (x)$ and $\varphi_{-i} (x)$ are defined be removing the $i$-th coordinate from $x$. Then $\varphi_{+i}$ and $\varphi_{-i}$ are diffeomorphisms with inverses $\varphi_{+i}^{-1}$ and $\varphi_{-i}^{-1}$ respectively. Here $\varphi_{+i}^{-1} (y)$ and $\varphi_{-i}^{-1} (y)$ are defined by inserting the components $1 - \sqrt{y_1^2+ \cdots + y_{n}^2}$ and $-1 + \sqrt{y_1^2+ \cdots + y_{n}^2}$ respectively between $y_{i-1}$ and $y_{i}$.
Hence we can associate $x \in S^n$ with $\varphi_{+i}$ if $x \in S^n_{+i}$ or with $\varphi_{-i}$ if $x \in S^n_{-i}$. This completes the proof.

A: This could not fit as a comment, so it became an answer.
"Psychologically" it is good to think of $M:=S^n$ defined as a set by
$$
M=\Big\{\ x\in \Bbb R^{n+1}\ :\ \|x\|_2=1\ \Big\}
$$
and organized as topological space by using the cited subspace topology as being something "amorph". (Maybe something visualized as a tar roof.) As it comes so far, we have no smooth structure. So far we have nothing. We have to organize $M$ as a smooth manifold. "Smooth" is usually taken as synonym for "of class $\mathcal C^\infty$". So the problem, the claim also has to give an atlas, when saying "show it is a smooth manifold". Or else just say it can be organized (after given the topological structure) as such. (But the topological structure is also only implicitly given in the claim...)
Now regarding the proof.
The proof introduces maps $\varphi_{+i}$ and $\varphi_{-i}$ from open "pieces" $U_{+i}:=S^n_{+i}$ and
$U_{-i}:=S^n_{-i}$
inside the (so far) "amorph" structure to different copies of the unit ball in the $n$-dimensional space.
The wording "are diffeomophisms" for these maps is at this point, during the proof, premature. We are allowed to work only in the category of topological spaces at this point, maps are not knowing any differentiable structure just now. They are but homeomorphisms, invertible maps in the category of topological spaces, and this is all we need.
Now we want to insure also a "(smooth) differentiable structure". This is done by using the "model" of a "(smooth) differentiable structure" taken from open pieces in $\Bbb R^n$. So we are allowed to use the word diffeomorphism only for pieces inside the "known" $\Bbb R^n$. We use the charts $\varphi_{\pm i}$ to obtain maps between "different $n$-balls" $\Bbb B(0,1)=\Bbb B_n(0,1)$ (of radius one centered in zero) inside $\Bbb R^n$. These are the red maps in the diagram below. (Here i cannot draw oblique arrows...)
$\require{AMScd}$
$$
\begin{CD}
U_{i+}\cap U_{j+} @= U_{i+}\cap U_{j+}\\
@V {\operatorname{inclusion}} V V @VV {\operatorname{inclusion}} V\\
U_{i+} @. U_{j+}\\
@V \varphi_{i+} V V @VV \varphi_{j+} V\\
\Bbb R^n\supset\operatorname{Image}(\varphi_{i+})\qquad  @>> {\color{red}{\varphi_{j+}|\ \circ\ \varphi_{i+}|^{-1}}} > \qquad\operatorname{Image}(\varphi_{j+}) \subset \Bbb R^n \\
@V \operatorname{inclusion} V V @VV  \operatorname{inclusion} V\\
\Bbb R^n\supset\Bbb B(0,1)\qquad @. \qquad\Bbb B(0,1)\subset \Bbb R^n
\end{CD}
$$
There are of course further such compositions of restrictions (that vertical bar) of these maps / charts, take instead of the two plus signs all $\pm$-possibilities.
It remains now to show that the red maps are smooth. The proof starts first at this point... One has maybe to compute compositions, observe that componentwise only "radicals and polynomials" are involved. The radicals are considered on expression that do no vanish.

After all, we have a smooth manifold, and we can speak of smooth maps between smooth manifolds. Also in this case, the "smoothness" test is done in "open affine pieces" (i.e. open sets inside real euclidean spaces of the dimensions related to the dimension of the involved manifolds).


text:
Q: If $R$ is an equivalence relation, does $R^2$ too? I think that yes,

$I_A \subseteq R$
$R = R^{-1}$
$R^2 \subseteq R$

And now we can show.
Reflex: $I_A = I_A^2 \subseteq R \subseteq R^2$
A lil bit struggling with symm. And trans. Can you show me how will you prove it?

A: The key is that $R_1\subseteq R_2$ implies $R_1^2\subseteq R_2^2$. Together with $I_A^2=I_A$ and $(R^{-1})^2=(R^2)^{-1}$ the three properties for $ 2$ follow.
But actually the situation is much simpler: While transitivity (alone) of $R$ in fact just means $R^2\subseteq R$, transitivity plust reflexivity means that $$R^2=(R\cup I_A)^2=R^2\cup RI_A\cup I_AR\cup I_A^2=R^2\cup R\cup I_A=R. $$
Hence $R^2$ is an equivalence relation because it is the same relation as $R$. (We also not that we did not need symmetry to show $R^2=R$, only transitivity and reflexivity; hence $R^2=R$ holds as well for relations such as $\le$)


text:
Q: What should I use to access NFS from console without mounting it?
Network file access  |   Console program |   mounting option
------------------------------------------------------------
HTTP                 |    wget / curl    |   httpfs
FTP                  |    ftp / wget     |   curlftpfs
SMB                  |    smbclient      |   in-kernel or smbnetfs
WebDAV               |    cadaver        |   davfs2, fusedav
SSH                  |    ssh / scp      |   sshfs
NFS                  |       ?           |   in-kernel

How do I just download the file or create a directory on NFS without setting it up permanently?
I see there is libnfs (it also has some utils), but is there a fully fledged tool based on it?


text:
Q: logged in user id not getting in wordpress cron job Whenever I try to get current user id in wordpress cron job it returns 0. Is there any way to get current logged in user id in wordpress cron job.
here is sample code.
add_filter( 'cron_schedules', 'isa_add_every_three_minutes' );
function isa_add_every_three_minutes( $schedules ) {
    $schedules['every_three_minutes'] = array(
        'interval'  => 180,
        'display'   => __( 'Every 3 Minutes', 'textdomain' )
);
    return $schedules;
}

// Schedule an action if it's not already scheduled
if ( ! wp_next_scheduled( 'isa_add_every_three_minutes' ) ) {
    wp_schedule_event( time(), 'every_three_minutes', 'isa_add_every_three_minutes' );
}

// Hook into that action that'll fire every three minutes
add_action( 'isa_add_every_three_minutes', 'every_three_minutes_event_func');
function every_three_minutes_event_func() {
    $user_id = get_current_user_id();
    $user_points = get_user_meta( $user_id, 'remaing_points', true);
    // send mail
    //wp_mail();

}

Method #1
$user_id = get_current_user_id();

Method #2
$current_user = wp_get_current_user();
$current_user->ID;

I have tried these two method to get user id but no luck.

A: If you are manually invoking the cron by running wp-cron.php, there is no user.
If you are relying on WordPress's cron to trigger on a user action request, you may get a non-zero user id if the user is logged in. If the user is a guest/non-logged in user, you will get a user id of 0.

A: You can set the user data in hook by $args.
$args = [ is_user_logged_in(), wp_get_current_user() ];
wp_schedule_event( $time, 'daily', 'close_session_daily_hook', $args );

In function
add_action( 'close_session_daily_hook', 'do_this_daily', 10, 2 );

function do_this_daily( $is_user_logged_in, $current_user ) {
   // do some magic
}

Look more examples in https://developer.wordpress.org/reference/functions/wp_schedule_event/


text:
Q: How to increase storage capacity for Cosmos DB collection? I have a Cosmos DB collection in the Standard pricing tier which I'm loading new data into. Yesterday, I got a "Storage quota for 'Document' exceeded" error, and when I checked the Scale tab, I saw that the default storage capacity is 100 GB. I thought there were no storage limit in the Standard pricing tier. How can I increase the storage capacity, since this collection is supposed to contain several TBs?

A: I got a quick response from Microsoft on my support request that there are some issues with their auto-splitting operations which is limiting the storage scalability at the moment. Microsoft will manually raise the storage limit for me. Hopefully they will soon solve the auto-scaling, so we don't have to monitor the collection size.

A:
How can I increase the storage capacity, since this collection is supposed to contain several TBs?

Currently it only enables us to adjust throughput level under Scale blade on Azure portal after the collection is created.

If possible, you can create a new collection with Unlimited Storage Capacity, and then migrate data from your source collection to that new collection.

Besides, you can create a SUPPORT REQUEST to get help from support.


text:
Q: Wifi access point without infrastructure I need to be able to connect a number of wifi devices to a laptop without proper infrastructure; specifically this is my use case...
I have a number of devices that utilize wifi, I have a laptop with my application running. I need to have connectivity between the laptop and the wifi devices. The environment that this runs in means there will not be proper wifi infrastructure.
So I need a method that will connect to my laptop via USB, CardBus or express card (i.e get power from the laptop) that will provide an access point for my devices to connect to. My devices do not support being connected to an ad hoc wifi network, so it needs to be a 'proper' access point. Also the laptop should then be able to be connected to the network through the medium that powers the device, USB for example.
I have found this device so far.
The problem is I can't figure out if my laptop would have to use its internal wifi to connect to the USB access point or if the connection can be through the USB.
I am not sure if such a product exists or not. Does such a product exist? I hope my question is clear!

A: The USB port on the AP you linked to only uses the USB connection from your computer for power.  You still need to connected your wired (ethernet) port to the AP or connect to it from your internal wireless adapter.  In my research of travel routers powered via USB, I didn't find any that provided a network device over USB to connect to the network.

A: You can use a RT5370 based usb wifi NIC to host a Soft AP. That will still provide you with network connectivity through the NIC, as well as allow other devices to connect to your laptop via the Soft AP.
I've used the generic ebay RT5370s with great success in this area.
http://www.ebay.com.au/itm/RT5370-Mini-150Mbps-USB-Wireless-Network-Card-WiFi-LAN-Adapter-Antenna-/281205282525?pt=AU_Components&hash=item41792416dd  <-- that one comes with windows drivers to allow you to start using the AP fairly easily.


text:
Q: Debitoor API is returning 400 bad request I would like to create invoices by my PHP script. But before I am able to program this I would like to understand the API from Debitoor.
In order to create an invoice you have to create a draft invoice first. You can find this here: /api/sales/draftinvoices/v3.
I have set all the requested parameters to use the the /api/sales/draftinvoices/v3 function however, I always get a 400 Bad Request response back.. The reason is the schema.
Can you guys tell me where my failure is?
I would guess is something with the "lines"... but I would say it's all correct...
This is my request:

Request as text:
{
  "date": "2018-05-06",
  "dueDate": "2018-05-13",
  "notes": "Diese Rechnung ist vom Backend erstellt worden.",
  "customerName": "Max Mustermann",
  "customerAddress": "Mustermann Stra\u00dfe",
  "customerCountry": "DE",
  "currency": "EUR",
  "languageCode": "de-DE",
  "recargoTaxEnabled": false,
  "sent": false,
  "viewed": false,
  "displayAsPaid": false,
  "lines": {
    "taxEnabled": "false",
    "description": "Leistungszeitraum 06.04.2018 - 05.05.2018",
    "taxRate": "1.19",
    "productOrService": "product"
  }
}

This is the response I get back:

As text:
{
  "message": "Error validating against schema",
  "id": "9905636b-fb65-41a0-8d25-4aa096d5347d",
  "code": "schema",
  "errors": [
    {
      "message": "is the wrong type",
      "value": {
        "taxEnabled": "false",
        "description": "Leistungszeitraum 06.04.2018 - 05.05.2018",
        "taxRate": "1.19",
        "productOrService": "product"
      },
      "type": "array",
      "property": "lines"
    }
  ],
  "body": {
    "date": "2018-05-06",
    "dueDate": "2018-05-13",
    "notes": "Diese Rechnung ist vom Backend erstellt worden.",
    "customerName": "Max Mustermann",
    "customerAddress": "Mustermann Stra\u00dfe",
    "customerCountry": "DE",
    "currency": "EUR",
    "languageCode": "de-DE",
    "recargoTaxEnabled": false,
    "sent": false,
    "viewed": false,
    "displayAsPaid": false,
    "lines": {
      "taxEnabled": "false",
      "description": "Leistungszeitraum 06.04.2018 - 05.05.2018",
      "taxRate": "1.19",
      "productOrService": "product"
    }
  }
}

Kind regards and Thank You!

A: Thank you for using the Debitoor API
You are correct. Your problem is with the lines. Lines should be an array. You have only send a single object.
Another issue is that you provide taxEnabled: false and taxRate: 1.19. If you provide taxEnabled as false you should set the taxRate to 0. Remember that taxRate should be between 0 and 100 with a maximum of two decimals
Your request should look something like this instead:
{
 "lines": [
  {
   "taxEnabled": false,
   "description": "Leistungszeitraum 06.04.2018 - 05.05.2018",
   "taxRate": 0,
   "quantity": 1,
   "unitNetPrice": 1,
   "productOrService": "product"
  }
 ]

Best regards,
Carsten
Mobile developer @ Debitoor


text:
Q: Calculate if this Multivariable Limit exist I hope someone can help me. The limit is:
$$\lim_{(x,y)\to(0,0)} \frac{x-y}{\sqrt{3x^2 + 4y^2}}$$
Does this limit exist or not? I tried to solve it by using $x=r\cos\theta$ and $y=r\sin\theta$, but I can't find a solution.
I'm at this point right now:
$$\lim_{r\to 0} \frac{\cos\theta-sin\theta}{\sqrt{3\cos^2\theta+4\sin^2\theta}}$$
Am I on the right track or should I try something else?
Edit: I tried, like recommended, $x=0$
$$\lim_{(0,y)\to(0,0)} \frac{-y}{\sqrt{4y^2}}=\frac{-y}{2y}=\frac{-1}{2}$$
then $y=0$
$$\lim_{(0,y)\to(0,0)} \frac{x}{\sqrt{3x^2}}=\frac{x}{\sqrt3\sqrt{x^2}}=\frac{-1}{\sqrt{3}}$$
So it doesn't exist. Right?

A: Hint:
Choose two routes:  first, $\;x=0\;$ , and then $\;y=0\;$ . What did you get? Then...
In fact, only one route is enough...but whatever.

A: You found by the variables substitution
$$\lim_{r\to 0} \frac{\cos\theta-\sin\theta}{\sqrt{3\cos^2\theta+4\sin^2\theta}}
$$
This result show us that the limit value depends on the direction taken so the limit does not exists.

A: Let $y=mx$ then $(x-y)/(3x^2+4y^2)^{1/2}$ simplifies to $(1-m)/(3+4m^2)^{1/2}$ so the direction of approach to (0,0) gives different values depending on $m$. Thus the limit does not exist.


text:
Q: wp_get_recent_posts stopped working I want to return the 2 newest posts when in single post mode, but exclude the current post. And I did it. The problem is, it just stopped working. It didn't change the code and it stopped on the server as well as on my localhost.
Here's the code:

                Recent posts

            <?php
                $id = $post->ID;
                $recent_posts = wp_get_recent_posts("numberposts=2&exclude=$id");

                foreach( $recent_posts as $recent ) { ?>

                            <a href="<?php echo get_permalink($recent["ID"]); ?>"><?php echo $recent["post_title"]; ?>

                            <?php echo get_excerpt_by_id($recent["ID"]); ?>

            <?php } ?>

Does anyone have an explanation ?
I tried removing the argument, still nothing. It returns an empty array.
Any suggestions which other function should I use to achieve the same effect ?
EDIT:
    <?php

get_header();
get_sidebar();

?>

        <?php the_post() ?>

<?php the_title(); ?>

                        <?php echo get_the_category_list(', '); ?>
                        U by <?php the_author(); ?>

                <?php if (has_post_thumbnail()) : ?>

                    <?php the_post_thumbnail(); ?>

No Will No Skill

                <?php endif; ?>

                    <?php the_content(); ?>

                            <?php the_tags('', '', ''); ?>

                            <time datetime='<?php the_time('Y-m-d'); ?>' pubdate>
                                P
                                <?php relative_post_the_date(); ?>
                            </time>

                                f Like
                                 |
                                g +1
                                 |
                                t Tweet

                                <?php
                                    if(function_exists('display_social4i'))
                                        echo display_social4i("large","align-left");
                                ?>

            <?php comments_template(); ?>

                    Recent posts

                <?php
                    global $post;
                    $id = $post->ID;
                    $qargs = array(
                        'post__not_in'=> array($id),
                        'posts_per_page' => 2
                    );
                    $recent_posts = new WP_Query($qargs);

                    if ($recent_posts->have_posts()) echo 'yes'; else echo 'nope';

                    if($recent_posts->have_posts()) : while($recent_posts->have_posts()) : $recent_posts->the_post(); ?>

                                <a href="<?php the_permalink(); ?>"><?php the_title(); ?>

                                <?php the_excerpt(); ?>

                <?php endwhile;endif; ?>

<?php
get_footer();
?>

A: You're missing your loop, or at least an global instance of the current post object. While I prefer to use the loop myself, you can get away with using the latter.
Change:
$id = $post->ID;
$recent_posts = wp_get_recent_posts("numberposts=2&exclude=$id");

To:
global $post;
$id = $post->ID;
$recent_posts = wp_get_recent_posts("numberposts=2&exclude=$id");

UPDATE:
The loop can be used in a single view to grab information from the default query_posts object. Even though it's just one post, the loop is most often used to populate the_content and other information.
You're correct that the ID should be irrelevant in this instance, since wp_get_recent_posts() should still return some results without any arguments (unless, of course, you're dealing with custom post types).
An alternate solution would be to try getting your recent posts using WP_Query:

            Recent posts

        <?php
            global $post;
            $id = $post->ID;
            $qargs = array(
                'post__not_in'=> array($id),
                'posts_per_page' => 2
            );
            $recent_posts = new WP_Query($qargs);

            if($recent_posts->have_posts()) : while($recent_posts->have_posts()) : $recent_posts->the_post(); ?>

                        <a href="<?php the_permalink(); ?>"><?php the_title(); ?>

                        <?php the_excerpt(); ?>

        <?php endwhile;endif; ?>

WP_Query will default to the standard 'orderby'=>'date' and 'order'=>'DESC' parameters, so those don't need to be explicitly stated (though, you can add them if you like).
As mentioned above and in my comment, I'm unsure if you want just the most recent posts, or if you're trying to query recent custom post types. If the recent posts are of type 'post' and that's what you want, then that is the default for WP_Query's 'post_type' parameter as well as wp_get_recent_posts.
Otherwise, you will need to explicitly state the 'post_type' parameter, so that $qargs looks like:
$qargs = array(
    'post__not_in'=> array($id),
    'posts_per_page' => 2,
    'post_type' => array('post', 'custom_post_type_slug', ...)
);

Just to check, you can also set 'post_type' to 'all' if you want to ensure SOMETHING is returned. If nothing is returned by either WP_Query or wp_get_recent_posts with 'post_type' set to 'all', then the issue is much larger, and I'll need to see all of the code in your single.php template.
Hope this helps.
NEW UPDATE:
Try commenting out the block of code altogether and substitute for:
wp_get_archives(array('type'=>'postbypost'));

If that doesn't work, then I'm fresh out of ideas. Something may have happened on your filehost's end that could possibly explain something happening out of nothing. Check and see if they have any announcements about this kind of activity. I know that many filehosts are in the process of replacing PHP4 and older versions of MySQL, which can probably cause some unforseen issues.
I would try creating a new subdomain with a clean, separate installation of Wordpress and a copy of your theme. Once that's set, just create a new post and see if the same problem occurs.
If so, then comment out chunks of code (possibly start with commenting out from get_sidebar through your first
...
 block) in your single.php file and work out any errors that might pop up. If the block of code we worked on suddenly begins to populate, then post the block of code that was preventing it from happening and I'll try to work with you further (that is, if you're still having trouble).
Otherwise, if the clean installation fixes your issues, then it's probably some kind of discrepancy in your wp_options table. I would start merging tables over (first wp_posts, then wp_postmeta, then wp_terms....) until the problem pops up again.
Unfortunately, I think exhaustive testing might be in order to get this anomaly straightened out. Sorry I don't have a pure code solution. This is a pretty strange issue you're going through. Keep me posted, I'll do what I can to help.


text:
Q: Visual Basic Problems I am trying to create a program that would function as a "shopping list". I have completed all the code and setting it up and what not but when I try and run the program it will not run. I have 0 errors in my code and it will not debug either. There are two programs I am having this problem with. Here is the code for both of the programs.
PROGRAM 1:
Public Class Form1
    Dim Item As String = txtAdd.Text
    Private Sub btnAdd_Click(ByVal sender As System.Object, ByVal e As System.EventArgs) Handles btnAdd.Click
        Item = Me.txtAdd.Text
        Me.lstItems.Items.Add(Item)
    End Sub
    Private Sub btnMoveToList_Click(ByVal sender As System.Object, ByVal e As System.EventArgs) Handles btnMoveToList.Click
        Me.lstItems.Items.Remove(Item)
        Me.lstList.Items.Add(Item)
    End Sub
Private Sub btnMoveToItems_Click(ByVal sender As System.Object, ByVal e As System.EventArgs) Handles btnMoveToItems.Click
    Me.lstList.Items.Remove(Item)
    Me.lstItems.Items.Add(Item)
End Sub
Private Sub btnDelete_Click(ByVal sender As System.Object, ByVal e As System.EventArgs) Handles btnDelete.Click
    Me.lstItems.Items.Remove(Item)
End Sub
End Class

PROGRAM 2:
Public Class Form1
    Dim total As Double
    Dim Cost As Double = Me.txtCost.Text
    Dim Number As Integer = Me.txtNumber.Text

    Private Sub btnCalculate_Click(ByVal sender As System.Object, ByVal e As System.EventArgs) Handles btnCalculate.Click
        total = (Cost * Number)

        If Int32.TryParse(Me.txtCost.Text, Me.txtNumber.Text) Then
            MessageBox.Show("The total cost of your items is:" & total)
        Else
            MessageBox.Show("Enter correct numeric values")
        End If
    End Sub

    Private Sub ExitToolStripMenuItem_Click(ByVal sender As System.Object, ByVal e As System.EventArgs) Handles ExitToolStripMenuItem.Click
        Application.Exit()
    End Sub
End Class

I am receiving a pop up window that says "An error occurred creating the form. See Exception.InnerException for details.  The error is: Object reference not set to an instance of an object."

A: Dim Item As String = txtAdd.Text

won't work class-level; txtAdd doesn't refer to your textbox at that point. You can initialize it in New instead:
Private Item As String

Public Sub New()
    Me.InitializeComponent()
    Me.Item = txtAdd.Text
End Sub

Your second form has the same problem, but seeing as you don't use the two fields in there, you don't need them. If they should reflect the inputs, use properties instead, e.g.
Public ReadOnly Property Cost() As String
    Get
        Return Me.txtCost.Text
    End Get
End Property


text:
Q: Unable to open file in bytes from sd card (ESP32) I want to open a .wav file in bytes from the sd card connected to esp32.
My code is based in this question
I just want upload a file from my sd card to a server but by the moment I can't read the file despites the file exists in the sd card:
Look this lines of code:
 char *fname = "/sdcard/test.wav";
  FILE *fp = fopen(fname, "rb"); // read in bytes

  if(!fp) {
    Serial.println("File doens't exist");
  }

I don't understand why it File file = SD.open("/test.wav") works but the above code not. According to my reference I should read this file in bytes and not in a normal manner like this => File file = SD.open("/test.wav").
I would like know how I can see the full path of my sd card because the original code uses this:
char *fname = "/sdcard/test_text.txt";
  FILE *fp = fopen(fname, "rb");

why that uses this path /sdcard/test_text.txt I don't know exactly. If I try to open by using:
File file = SD.open("/test.wav")

will works but some lines of code after this will throws errors because the file should be read in bytes.
I would like to see your advices guys I will appreciate any idea to fix this problem.
this is the entire code:
#include "Arduino.h"
#include "WiFi.h"
#include "SD.h"
#include "FS.h"
#include "HTTPClient.h"
//SD CARD MODULE
#define SD_CS          5
#define SPI_MOSI      23
#define SPI_MISO      19
#define SPI_SCK       18

// Wifi Credentials
const char* ssid     = "XXX";
const char* password = "XXX";

void setup() {
  Serial.begin(115200);

  WiFi.mode(WIFI_STA);
  WiFi.begin(ssid, password);

  while (WiFi.status() != WL_CONNECTED) {
    delay(500);
    Serial.print(".");
  }

  Serial.println("");
  Serial.println("WiFi connected");
  Serial.println("MY IP address: ");
  Serial.println(WiFi.localIP());

  if (!SD.begin(SD_CS)) {
    Serial.println("SD init failed!");
    return;
  }
   Serial.println("SD init successfull!");

}

void loop()
{
  WiFiClient client;
  Serial.println("starting file upload");
  IPAddress host(192, 168, 18, 8); //server ip
  int port = 80;
  if (!client.connect(host, port))
  { // check connection to host if untrue internet connection could be down
    Serial.println("couldn't connect to host");
  }
  Serial.println("Connect to host!");

  HTTPClient http;
  const char* serverName = "http://192.168.18.8/upload/upload.php";
  http.begin(client, serverName);

  char *fname = "/sdcard/test.wav";
  FILE *fp = fopen(fname, "rb"); // read in bytes

  if(!fp) {
    Serial.println("File doens't exist");
  }

  //get file size
  fseek(fp, 0, SEEK_END); //send file pointer to end of file
  int file_size = ftell(fp); //get end position of file
  fseek(fp, 0, SEEK_SET); //send pointer back to start

  int max_upload_size = 10; // array size, larger = less uploads but too large can cause memory issues
  int num_of_uploads = file_size / max_upload_size; // figure out how many evenly sized upload chunks we need
  int num_of_uploads_mod = file_size % max_upload_size; //find out size of remaining upload chunk if needed
  int i;
  //upload file in even chunks
  if (num_of_uploads > 0)
  {
    char buff1[max_upload_size+1] = {}; // array to save file too. add 1 for end of array symbol '\n'
    for (i = 0; i < num_of_uploads; i++)
    {
      fread(buff1, sizeof(buff1)-1, 1, fp); // -1 as don't want to count the '\n'
      http.addHeader("file_name", "file_name"); //header to say what the file name is
      int httpResponseCode = http.POST((uint8_t *)buff1, sizeof(buff1)-1); //send data. Datatype is (uint8_t *)
    }
  }
  //upload any remaining data
  if (num_of_uploads_mod > 0)
  {
    int remainder = file_size - num_of_uploads * max_upload_size;
    uint8_t buff2[remainder] = {};
    fread(buff2, sizeof *buff2, sizeof buff2 / sizeof *buff2, fp);
    http.addHeader("file_name", "file_name");
    http.addHeader("Content-Type", "application/octet-stream");
    int httpResponseCode = http.POST(buff2, sizeof(buff2));
  }
  http.end(); // Close connection
  delay(10 * 1000);
}

thanks so much.

A: Unfortunately, this isn't straight-forward. You can either use the SD component directly or mount the correct file system driver (typically FatFs for an SD card). To use fopen, you need to register the correct driver first, hints can be found here: https://docs.espressif.com/projects/esp-idf/en/latest/esp32/api-reference/storage/fatfs.html#using-fatfs-with-vfs-and-sd-cards
I haven't tried this myself yet, but the magic function seems to be esp_vfs_fat_sdspi_mount that should enable the use of fopen with the SD card over SPI. The official documentation lacks a real-world example, but you might find something in this thread or via your preferred search engine. For further help, you might want to ask a question on arduino.se instead, where a number of experienced ESP32 experts are present.

A: I struggled myself with using SD Cards (fat32) on my ESP32.
When trying to open my file using
std::ofstream dataFile("/sdcard/data.json", std::ofstream::out);

It wouldn't create my file. a sys/stat would thus give a -1. Turned out that you really need to use the 8.3 naming convention for FAT32. There's no "MS windows-magic" That abbreviates the file to: sdcard.j~1 etc. So just use a correct file name. not "/sdcard/mylomgfilename.exotic_extention" but just a "/mpoint/12345678.123" filename like "/sdcard/data.txt".


text:
Q: Step down ac transformer I bought this small cheap transformer for my nest hello smart bell, it has 3 input options "4 wires" if i use 220v input wires it gives me 30 volt output without load of course.
If i use the 440 input wires it gives me 15 volt output, also without load.
My question is:
Is it safe to use the 440 input wires with my 230v outlet socket?

3:

A: You could power it between the 440V and 110V wires and get 18VAC under full load and probably about 20VAC open, which is well within the 16-24VAC operating range of the bell. The VA is adequate.
It's claimed to be a Class 2 transformer (though notably bereft of any visible markings and file numbers indicating that it has been tested to meet that requirement) so it should (they say) fail safely, however having such things in a grounded metal enclosure or otherwise mounted to something non-flammable is never a bad idea IMHO.

A:
Is it safe to use the 440 input wires with my 230v outlet socket?

It won't damage the transformer and should provide you with about half the VA rated output stated on the label. Given that it is a 40 VA transformer you can expect to use this for a 20 VA load.
However, your load requires a 16 volt AC output and, running at 440 volt AC, the transformer only produces 15 volt AC so there is a shortfall. It may work or it may not but, it should be safe.
If you test it and it all looks fine, keep an eye on it for a couple of hours just to be sure.


text:
Q: what does u stand for in ctrl+u? I was trying to understand and remember keyboard shortcuts for bash. I was wondering why is the char 'u' used in
CTRL-u --- cancel the line before cursor location

A: While unix-line-discard is a good mnemonic, the use of CTRL+U as a line-erase character precedes the invention of UNIX.  It was used as such on various Digital Equipment (DEC) systems, including the PDP-8.  For instance, from my dusty bookshelf I see that CTRL+U was used as line-erase in the PDP-8 Symbolic Editor (page 5-13 of the 1972 edition of the PDP-8 Introduction To Programming (Volume 1) manual published by DEC).  In fact, in the early days of UNIX, the @ character was often the default line-erase character.  Other systems used CTRL+X for the same function, which made some sense since the ASCII control character description for it is Cancel. The DEC convention of CTRL+U eventually won out in the popularity contest.

A: "unix-line-discard": http://cnswww.cns.cwru.edu/php/chet/readline/readline.html#SEC17


text:
Q: Track time for loading screen: Angular2 I've added a loading component in my Angular 2 application where I show the loading animation on every async call to a webapi. I want to add another feature to that loading component. i.e., if loading is taking more than 5 seconds then I want to show a helper message on top of the loading animation. So any suggestions how can I 'track' the time of the loading animation? I'm guessing there should be a Javascript function, but can't find anything yet that can make this work.

A: If you are in a hurry, something like this works for me.
import { Component, OnInit } from '@angular/core';
import { Http } from "@angular/http";
import 'rxjs/add/operator/map';
import 'rxjs/add/operator/delay';

@Component({
  selector: 'your-selector',
  template: `

First Loading...

Second Loading..

  `,
  styles: []
})
export class YourComponent implements OnInit {

  firstLoader: boolean = true;
  secondLoader: boolean = false;

  constructor(
    private _http: Http
  ) { }

  ngOnInit() {
    setTimeout(() => {
      this.secondLoader = true;
    }, 1000); // your second loader interval
    this._http.get('https://jsonplaceholder.typicode.com/photos')
      .map(res => res.json())
      .delay(2000) // add network throttling
      .subscribe(res => {
      // console.log(res);
      this.firstLoader = false;
      this.secondLoader = false;
    })
  }
}


text:
Q: AngularX TS error Cannot invoke an expression whose type lacks a call signature I'm creating a component like this and I'm getting an error on ng serve/ building.
Do not confuse with error on console as some commenters seem to think.
Th expected behavior is for the code the build and run.
TS error TS2349: Cannot invoke an expression whose type lacks a call signature

in the foreach function in ngOnInit()
  import { Component, OnInit, Input } from '@angular/core';
    import { ChartInput, MultiChartInput, ChartColorScheme } from "@shared/models/chart-input";

    @Component({
        selector: 'chart-legend',
        templateUrl: './chart-legend.component.html',
        styleUrls: ['./chart-legend.component.css']
    })
    export class ChartLegendComponent implements OnInit {

        @Input()
        public chartInput: ChartInput[] | MultiChartInput[];
        @Input()
        public legendColors: ChartColorScheme;

        public legends: Map<string, string> = new Map<string, string>();
        constructor() { }

        ngOnInit() {
            this.chartInput.forEach(
                (item, index) => {
                    this.legends.set(item.name, this.legendColors.domain[index]);
                });
            }
        }

export class ChartInput {
    name: string;
    value: number;

}
export class MultiChartInput {
    name: string;
    series: ChartInput[];
}
export class ChartColorScheme {
    domain: string[];
}

Any help that solves is appreciated.
If someone thinks this is related to this question. Please explain. I dont think so.

A: This is known to occur when using union types (Microsoft/TypeScript - Issue #7294). As explained in the issue comment:

This is currently by design because we don't synthesize an intersectional call signature when getting the members of a union type -- only call signatures which are identical appear on the unioned type.

In your case, ChartInput and MultiChartInput do not have compatible signatures because they each have unique attributes; i.e., ChartInput has value: number, while MultiChartInput has series: ChartInput[]. You can quickly test this by commenting out those attributes and seeing the error disappear (demo of experiment).
To resolve the error while maintaining type safety, change the type of chartInput to (ChartInput | MultiChartInput)[]:
class ChartLegendComponent implements OnInit {
    public chartInput: (ChartInput | MultiChartInput)[];
    ...
}

demo of fix 1
...or cast this.chartInput:
(this.chartInput as (ChartInput | MultiChartInput)[])
  .forEach(
      (item, index) => {
          this.legends.set(item.name, this.legendColors.domain[index]);
      });
  }

demo of fix 2


text:
Q: Displaying box divs inline with text under them I have 3 images i want to display them inline style with text under them but without using bootstrap grid-system because i want them to be close to each other and centered, i tried doing it but once i add the text they get displayed under each other, how can i fix that? here is my code:

.box{
display:inline;
}

Test

Test

Test

A: You were close, but it should be display: inline-block. See code snippet:

.box{
display:inline-block;
}

Test

Test

Test

Note: I see you've added the text-center class which is not working here on Stack Overflow, but should do the trick in your own code.

A: You can also use flex on the parent and it will put them side-by-side.

.boxes{
  display:flex;
  justify-content: center;
}
<link href="https://cdnjs.cloudflare.com/ajax/libs/twitter-bootstrap/4.0.0-alpha.6/css/bootstrap.min.css" rel="stylesheet"/>

Test

Test

Test

A: CSS Flexbox to the rescue (along with proper HTML semantics and no inline CSS styles)!

.container { display:flex; justify-content:center; }
.container figure { text-align:center; margin:0; }
.container img { height:120px; }

Test

Test

Test


text:
Q: Insanely slow Mongodb group query I'm trying to aggregate $sum between 2 dates stored as UTC strings (yyyy-mm-dd-hh). It takes 5+ seconds to get the results. My collection has 5 million+ docs.
      {
          $match: {
            start: {
              $gte: '2020-08-01-00',
              $lte: '2021-08-01-00'
            }
          }
        },
        {
          $group: {
            _id: {
                symbol: '$symbol'
            },
            unverifiedCount: {
                $sum: {
                    $cond: {
                        if: { $eq: ['$isVerified', false] }, then: '$count', else: 0
                    }
                }
            },
            verifiedCount: {
                $sum: {
                    $cond: {
                        if: { $eq: ['$isVerified', true]}, then: '$count', else: 0
                    }
                }
              }
          }
        }, {
          $sort: {
            unverifiedCount: -1
          }
        }

Tried using $toDateString but performance remained the same


text:
Q: Making a transaction-like behaviour when interacting with multiple systems Disclaimer
In the following post:
action= Action/Func
I have a long method that does multiple actions(s).Each action is wrapped in a try-catch.If the specific action fails , in the catch i must perform a clear action for all previous ones and the current one.
I do not know a way to stop duplicating code in the catch and aggregate them using a design pattern or something.
What i have currently
public void LongMethod()
{
   try
   {
      try
      {
        action1();
      }catch(Exception ex)
      {
        ClearAction1();
      }
      try{
        action2();
      }catch(Exception ex){
         Clearaction1();
         Clearaction2();
      }
      try
      {
         action3();

      }
      catch(Exception ex)
      {
         Clearaction1();
         Clearaction2();
         Clearaction3();
      }
   catch(Exception ex)
   {
       //how should i aggregate the action clearance here
   }

}

In the above method i do not want to write in all catch blocks all the clear actions up until that point.
I would like for each successful action to set something like a checkpoint , and then when that fails , check the state and perform all required clearing up until that point.
What i would like
public void LongMethod()
{
   try
   {
      int checkpoint=0;
      action1();
      checkpoint=1;
      action2();
      checkpoint=2;
      action3();
      checkpoint=3;
      action4();   //fails here
   }
   catch(Exception ex)
   {
        switch(checkpoint)
        {
            3//does Clearaction1()+Clearaction2()+Clearaction3()+Clearaction4();
        }
    }
}

I was thinking if there is something like a design pattern to wrap each of these actions which might have different return types and pipeline them.Whichever actionN fails it triggers Clearaction1()...ClearactionN() where N is the Action that did fail.
P.S It might be something like a monad.
m a ->(a->m b) -> m b ->  (m b -> (b -> m c) -> m c) -> (m c -> ( c -> m d) -> m d)
where a ,b,c,d are types the difference being that i need to aggregate all failure treatment.
Update
After answers on this forum i felt i needed to do some additions:
This is an endpoint inside a ASP NET Controller.I retrieve data from multiple systems and with the fetched data i am setting other systems.
What i want to this to look like is like a distributed system transaction:
Fetch Input Systems  [A,B]
To Output Systems [X,Y]
Example of sequence

*

*fetch data from A

*set data on X (using A data)  (and get response Z)

*fetch data from B

*set data on Y (using data fetched from  B and Z)

Secenario
Now lets say the the fetch data from B fails i want to:
- clear data from X only
I do not want to attempt to clear data on Y since it would produce irrevocable damage.
I care only about the I/O actions that set data.

A: If your code is not very-very performance/allocation critical you can just create a list of "reverse actions" and boolean variable to track success:
public void LongMethod()
{
   var reverseActions = new List<Action>();
   var success = false;
   try
   {
      int checkpoint=0;
      Action1();
      reverseActions.Add(ClearAction1);
      Action2();
      reverseActions.Add(ClearAction2);
      ...
      success = true;
   }
   finally // or can be catch if you can/want to handle/swallow exception
   {
         if(!success)
         {
            foreach(var a in reverseActions)
            {
             a();
            }
         }
    }
}

A: It seems you could simply build a list of pairs of actions and the corresponding compensating action. Then iterate from 1 to N, applying each action. If an exception is caught in step I, iterate backwards from I to 1 through the list of compensating actions.
Also, it is possible to use monads for compensation, e.g. the cats-saga library for Scala cats

A: If you are able to have one state object, that takes all "side-effects", you can do something like this:
public State LongMethod( State originalState ) // assuming, `State` is your state object type
{
    //                     vv Copy-CTOR == "Begin Transaction"
    State localState = new State(originalState);
    try{
       // mutate _the local copy_
       action1(localState);
       var intermediateResult = func2(localState);
       action3(localState, intermediateResult);
       // ...
       return localState; // return mutated state == "Commit"
    }
    catch(Exception ex)
    {
        // return unchanged state == "Rollback"
        return originalState;
    }
}

Why did I bother to add this after a different answer has already been accepted?
I wanted to present this alternative, regarding Martin's comment:

Perhaps not relevant to your question, but have you considered what will happen if your process terminates in the middle of this "transaction"?

If the process terminates amidst above code, you have a consistent state: the unchanged one.
Downside is: It really only works if you can isolate a state and do not depend on events triggered in the process.
To make it more clear: If in the process, let's say action5 does a HTTP PUT to API XYZ, then this solution is not enough because you would have to actively reverse that PUT.


text:
Q: XML Parsing Data with plant_catalog I am currently having issues with parsing data in my Python class and was wondering if anyone was able to provide a solution to my problem.  Here are the instructions for the assignment I'm doing:
XML is the basis for many interfaces and web services. Consequently, reading and manipulating XML data is a common task in software development.
Description
An online plant distributor has recently experience a shortage in its supply of Anemone plants such that the price has increased by 20%. Their plant catalog is maintained in an XML file and they need a Python utility to find the plant by name, read the current price, change it by the specified percentage, and update the file. Writing this utility is your assignment.
Using Python's ElementTree XML API, write a Python program to perform the following tasks below. Note that your program's execution syntax must be as follows:
python xmlparse.py plant_catalog.xml plantName percentChange

*

*Using ElementTree, read in this assignments XML file plant_catalog.xml specified by a command line parameter as shown above.

*Find the plant by the name passed in as an argument on the command line (plantName above).

*Once found, read the current price and adjust it by the command line argument percentChange. Note that this value could be anything in the range of -90 < percentChange < 100.

For example, if you run your script as follows:
python plant_catalog.xml "Greek Valerian" -20
with the original XML containing:
<PLANT>
    <COMMON>Greek Valerian</COMMON>
    <BOTANICAL>Polemonium caeruleum</BOTANICAL>
    <ZONE>Annual</ZONE>
    <LIGHT>Shade</LIGHT>
    <PRICE>4.36</PRICE>
    <AVAILABILITY>071499</AVAILABILITY>
  </PLANT>

The resulting file should contain:
<PLANT>
    <COMMON>Greek Valerian</COMMON>
    <BOTANICAL>Polemonium caeruleum</BOTANICAL>
    <ZONE>Annual</ZONE>
    <LIGHT>Shade</LIGHT>
    <PRICE>3.48</PRICE>
    <AVAILABILITY>071499</AVAILABILITY>
  </PLANT>

Note: You may reduce the precision of the calculation if you wish but it isn't required.
Hints
Since XML is just a text file, you could write the code to read all the data and the decode the XML information. However, I certainly don't recommend this approach. Instead, let Python do it for you! Using Python's ElementTree module, parse the file into an "in-memory" representation of the XML data. Once parsed, the root (or starting place) is as simple as requesting it from the tree. Once you have the root, you can call methods to find what you are looking for and modify them appropriately. You'll want to "findall" the plants and, "for" each plant "in" the result, you'll want to compare the name with the name passed on the command line. If you find a match you'll apply the percentage change, save the result back to the tree.
When you are done with the search you will "write" the tree back to a file. I suggest using a different file name or you will be having to re-download the original with each run.
One note of caution, be sure to read about XML in the Distributed Systems text. From doing so and reviewing the data file you will not that there are no attributes in the XML file. Consequently, you do not need to use attribute methods when you attempt this assignment.
The following code snippet will give you a good starting point:
# Calling arguments: plant_catalog.xml plantName percentChange
import xml.etree.ElementTree as ET
import sys

# input parameters
searchName = sys.argv[2]
percent = float(sys.argv[3])

# parse XML data file
tree = ET.parse(sys.argv[1])
root = tree.getroot()

Now here is my code:
import xml
import xml.etree.ElementTree as ET
import sys

searchName = sys.argv[2]
percent = float(sys.argv[3])

tree = ET.parse(sys.argv[1])
root = tree.getroot()

def main():
    with open("plant_catalog.xml", "r") as file:
        data = file.read()

for plant in root.findall("PLANT"):
    name = plant.find("COMMON").text
    if name == searchName:
        original_price = float(plant.find("PRICE").text)

with open("plant_catalog - output.xml", "wb") as file:
    file.write(percent)

def change_plant_price(plantName, newPrice):
    root = ET.fromstring(xml)
    plant = root.find(".//*[COMMON='{}']".format(plantName))
    plant.find('PRICE').text = str(newPrice)
    ET.dump(root)

if __name__ == "__main__":
    main()

The problem with my code is that when I write the code, I get an error in the file. Write(percent) line and shows it needs a byte-like object instead of a float.  I'm not sure what's wrong with the code but if anyone is able to provide a solution I would greatly appreciate it.

A: I think what you want to be doing is not file.write(percent) but instead tree.write(file). You want to write the tree to a file


text:
Q: Algorithm speed with double and int? how do algorithms with double compete compared to int values? Is there much difference, or is it neglectable?
In my case, I have a canvas that uses Integers so far. But now as I'm implementing a scaling, I'm probably going to switch everything to Double. Would this have a big impact on calculations?
If so, would maybe rounding doubles to only a few fractions optimize performance?
Or am I totally on the path of over-optimization and should just use doubles without any headache?

A: You're in GWT, so ultimately your code will be JavaScript, and JavaScript has a single type for numeric data: Number, which corresponds to Java's Double.
Using integers in GWT can either mean (I have no idea what the GWT compiler exactly does, it might also be dependent on context, such as crossing JSNI boundaries) that the generated code is doing more work than with doubles (doing a narrowing conversion of numbers to integer values), or that the code won't change at all.
All in all, expect the same or slightly better performance using doubles (unless you have to later do conversions to integers, of course); but generally speaking you're over-optimizing (also: optimization needs measurement/metrics; if you don't have them, you're on the "premature optimization" path)

A: There is a sizable difference between integers and doubles, however generally doubles are also very fast.
The difference is that integers are still faster than doubles, because it takes very few clock cycles to do arithmetic operations on integers.
Doubles are also fast because they are generally natively supported by a floating-point unit, which means that it is calculated by dedicated hardware. Unfortunately, it generally is usually 2x to many 40x slower.
Having said this, the CPU will usually spend quite a bit of time on housekeeping like loops and function calls, so if it is fast enough with integers, most of the time (perhaps even 99% of the time), it will be fast enough with doubles.
The only time floating point numbers are orders of magnitude slower is when they must be emulated, because there is no hardware support. This generally only occurs on embedded platforms, or where uncommon floating point types are used (eg. 128-bit floats, or decimal floats).
The result of some benchmarks can be found at:

*

*http://pastebin.com/Kx8WGUfg

*https://stackoverflow.com/a/2550851/1578925
but generally,

*

*32-bit platforms have a greater disparity between doubles and integers

*integers are always at least twice as fast on adding and subtracting

A: If you are going to change the type integer to double in your program you must also have to rewrite those lines of code that comparing two integers. Like a and b are two integers and you campare if ( a == b) so after changing a, b type to double you also have to change this line and have to use compare method of the double.

A: Not knowing the exact needs of your program, my instinct is that you're over-optimizing. When choosing between using ints or doubles, you usually base the decision on what type of value you need over which will run faster. If you need floating point values that allow for (not necessarily precise) decimal values, go for doubles. If you need precise integer values, go for ints.
A couple more points:
Rounding your doubles to certain fractions should have no impact on performance. In fact, the overhead required to round them in the first place would probably have a negative impact.
While I would argue not to worry about the performance differences between int and double, there is a significant difference between int and Integer. While an int is a primitive data type that can be used efficiently, an Integer is an object that essentially just holds an int. This incurs a significant overhead. Integers are useful in that they can be stored in collections like Vectors while ints cannot, but in all other cases its best to use ints.

A: In general maths that naturally fits as an integer will be faster than maths that naturally fits as a double, BUT trying to force double maths to work as an integer is almost always slower, moving back and forth between the two costs more than the speed boost you get.
If you're considering something like:
I only want 1 decimal places within my 'quazi integer float' so i'll just multiply everything by 10;
5.5*6.5
so 5.5 --> 55 and
so 6.5 --> 65

with a special multiplying function
public int specialIntegerMultiply(int a, int b){
    return a*b/10;
}

Then for the love of god don't, it'll probably be slower with all the extra overhead and it'll be really confusing to write.
p.s. rounding the doubles will make no difference at all as the remaining decimal places will still exist, they'll just all be 0 (in decimal that is, in binary that won't even be true).


text:
Q: How to submit data using ajax and display result without refreshing EDIT:
SOLVED. Thank you all for help. :)

EDIT:
Your suggestions worked. The problem now is that after the first find and displaying the found result, the found set stays the same no matter what i try to find next. Even after restarting the browser. Is it possible that the found data stays somewhere in server cache and is displayed as a result?

I'm trying to send data from the form using jquery to php file process it there and then display the result from it.
After pressing the submit nothing happens. There are no errors in the console.
Everything worked before i added jquery but after that i don't see any result.
My HTML:

<form id="my_form">
Imie:
 <input name="name" id="firstname" type="text" />

<input id="submit_form" type="submit" value="Submit">
</form>

My PHP:
<?php

require 'db_handler.php';

$criterion_name = $_GET['name'];

$query = $fm->newFindCommand("OFERTY tabela");
$query->addFindCriterion('kontrahent_opiekun', "=" . $criterion_name);
$result = $query->execute();

if(FileMaker::isError($result)){
echo($result->getMessage());
return;
}
$i = 0;
// Get array of found records
$records = $result->getRecords();
foreach ($records as $record) {
echo $record->getField('_kp_oferta') . " - ";
echo $record->getField('kontrahent_Skrot') . " - ";
echo $record->getField('kontrahent_opiekun') . '
';
$i++;
}
echo $i . " Pozycje";

?>


text:
Q: dlsym() returns 'symbol not found' I'm using OS X 10.7 (Lion), XCode 4.6.3 and libstdc++ as the C++ Standard Library.
I have this code in my main project:
shared.cpp:
extern "C" int sharedFun()
{
    return 5;
}

And this in my side project, that needs to dynamically load the main one:
loader.cpp:
#include <dlfcn.h>

int main(int argc, const char * argv[])
{
    void* mainApp = dlopen("mainApp.dylib", RTLD_LAZY);

    char* error;
    dlsym(mainApp, "sharedFun");

    if ((error = dlerror()) != nullptr)
    {
         ....
    }
}

nm output:
nm -gU mainApp.dylib | grep sharedFun
002a3a10 - 01 0000   FUN _sharedFun
002a3a10 T _sharedFun

dlopen loads the library just fine, but dlsym returns "symbol not found".
Any ideas?
Thanks.


text:
Q: Are the HBL derivability conditions necessary for Gödel's incompleteness theorems? (For Löb's theorem?) I am currently working with 'proof theory and logical complexity', a monograph on proof theory.
In the exercises of the first chapter one was asked to prove Löb's theorem (https://en.wikipedia.org/wiki/L%C3%B6b%27s_theorem) and two related/similar statements.
(The first chapter essentially gives the setup to prove and proves both incompleteness theorems and some results around them.)
Searching the internet I came across the Hilbert-Bernays-Löb 'derivability conditions' (https://en.wikipedia.org/wiki/Hilbert%E2%80%93Bernays_provability_conditions), that are - apparently - necessary to prove Löb's theorem.
The author never mentions them explicitly, and while the first is very plausible and the second not unplausible, I read that the third's proof is tedious and difficult.
The author never gives a proof for them, and I don't recall that one would have been needed, so I ask myself whether it is possible to prove the incompleteness theorems without them, or if they follow easily from some result, especially since Löb's theorem is in this case an exercise, and would be quite hard if the author intends the student to have the idea and the proof of the derivability conditions all by himself. Or maybe Löb's theorem is itself provable without them?
Thanks,
Ettore
PS: I added the question also on mathoverflow:
https://mathoverflow.net/questions/319402/are-the-hbl-derivability-conditions-necessary-for-g%C3%B6dels-incompleteness-theorem

A: Only the first condition is necessary for the first incompleteness theorem.
(Gödel did in practice use a version of it)
All three are used in standard derivations of the second incompleteness theorem, but Jeroslow 1973 invented a trick which allows to drop the third (it the Wikipedia listing): Thus only 1-2 are really necessary.
See Section 3.2. in:
https://plato.stanford.edu/entries/goedel-incompleteness/


text:
Q: Java - Copy pixels of BufferedImage to list I made a bitmap class with a list of Pixels. The Pixel class has a position and a color. Now I am trying to get a bitmap from a BufferedImage.
This is the code I have tried:
    private static Bitmap fromImage(BufferedImage image) {
        Bitmap bitmap = new Bitmap();
        for (int x = image.getMinX(); x < image.getWidth(); x++) {
            for (int y = image.getMinY(); y < image.getHeight(); y++) {
                bitmap.setPixel(new Pixel(RGBAColor.fromColor(
                        new Color(image.getRGB(x, y))), new Vector2(x, y)));
            }
        }
        return bitmap;
    }
    public static Bitmap fromImage(String path) {
        try {
            BufferedImage img = ImageIO.read(Galaxy2D.class.getResource(
                    "/com/mcmastery/galaxy2d/resources/" + path));
            BufferedImage conImg = new BufferedImage(img.getWidth(), img.getHeight(),
            BufferedImage.TYPE_INT_ARGB);
            conImg.createGraphics().drawImage(img, 0, 0, null);
            return Bitmap.fromImage(conImg);
        } catch (IOException e) {
            e.printStackTrace();
        }
        return null;
    }

It works, but when it paints the image to the screen it distorts it.
Original image: http://gyazo.com/0832ebf26f940b6dbf218e43101e63f8.png
Image painted to screen using bitmap methods: http://gyazo.com/c4b776f0e5fa0e54c167c10947582834.png
I have tried DataBufferInt too, and it still produces the same result. With other images, it just changes some pixel's positions to positions close to where they are supposed to be. But with the crosshair above, it turns it black and distorts it.

A: Not sure what a Bitmap is used for (I can't find it in the JDK7 API).
Maybe you can just use the getSubImage(...) method of the BufferedImage.