text:
Q: Why wont coalesce or is null work on results from a left join? In the following sql, why wont coalesce work, or even is null? Does it have something to do because of the left join in there?
There are no rows for the subquery to return in this case. i. e itemId = 'US1' does not exist in table amgb.
I'm on MySql 5.5.25 on Windows 7 64.
SELECT  a.itemName,
  (SELECT coalesce(itemImageName,'default.jpg') // always null
    FROM amgb b
    WHERE a.userId = b.userId AND a.itemId = b.itemId
    LIMIT 1
  ) AS itemImageName
FROM amga a
WHERE a.userId = 1 AND a.itemId = 'US1';

(SELECT if(itemImageName IS null,'default.jpg',itemImageName) // always null

A: The reason it's always NULL is because the COALESCE is inside of the subquery.  Instead move it outside like this:
SELECT  a.itemName,
  COALESCE((SELECT itemImageName
    FROM amgb b
    WHERE a.userId = b.userId AND a.itemId = b.itemId
    LIMIT 1
  ), 'default.jpg') AS itemImageName
FROM amga a
WHERE a.userId = 1 AND a.itemId = 'US1';


text:
Q: Custom framework cannot find other pod that required Bridging-Header file: "No such module 'InsiderMobile'" Currently we are developing a custom framework which need to use InsiderMobile cocoapods. According to this guideline, we will need o create Bridging-Header File to use InsiderMobile. However, Bridging-Header or Umbrella file did not work inside our framework so we have to use MapModule with Build Settings/Import Paths method, then the framework compile just fine.
The actual problem occur when we try to apply our framework to an application. The framework recognize all other pods except InsiderMobile. Here our current settings:

*

*We got both our custom framework and InsiderMobile in Pods folder,

*Our custom framework is Embed,

*MapModule with Build Settings/Import Paths method is also apply,

Here is some methods that we've already tried:

*

*pod install again, delete derived data, clean and rebuild project,

*Manually edit custom framework -umbrella file, but bump into new error: "Include of non-modular header inside framework module ", also try to set Allow Non-modular Includes In Framework Modules in Build Settings to Yes

*Also Embed InsiderMobile framework,

None of these above methods solve the problem. Is there anyway to allow our custom framework to import InsiderMobile? Thanks in advance.

A: In case it's helpful, i have found a way to temporary solve this issue. Not the best but help us unstuck the developing process. Basically, i have been trying to work with .modulemap method the whole time, you can find the docs here. Then i found this topic, and there this guys repo. I just follow the repo with a little change on the .modulemap file and everything work fine for me. Here's my .modulemap file:
module InsiderMobile [system] {
// Framework complier
// header "../../../../Pods/InsiderMobile/InsiderMobile.framework/Headers/Insider.h"

//App complier
header "../../../../../../Pods/InsiderMobile/InsiderMobile.framework/Headers/Insider.h"

export *

}
Cause .modulemap file directory might change when it go remote, so i have to change to suitable path before deploy it. I know it inconvenience but it work for now.

redpajama_set_name: RedPajamaStackExchange


text:
Q: A film about a man in the future looking for a crystal cylindrical element to repair a machine It is a vague memory from the childhood. I remember well that it was a devastated post-apocalyptic world (or another planet) and the main character had to deal with human-like wild creatures in a dry desert-like environment.
I think the film might be from the 80s, or late 70s but I am not sure about the language; it could be a dubbed version and — me as a child — not noticing any difference.

A: The cylindrical crystal is reminiscent of "Demon with the Glass Hand", an old Outer Limits episode, and the desert struggle with
human-like creatures sounds like Tank Girl.


text:
Q: Media files with .mov are not playing in a cordova app I am using Cordova to build my hybrid application. In this application i have a functionality to show preview of files before uploading them to server. For this when i am uploading video files and audio files recorded from device, it works if i am playing video/audio from device storage url. But it fails when i am binding the server url.
First i thought it is issue with content-type received from server so i changed it to video/quicktime. Obviously it didn't solved my problem.
Video files with mp4 extensions are playing perfectly. As iPad is returning .mov file and no other way to change video extension i cannot change encoding type.
My question is, what is issue when i am binding server url? it must not be issue with file codec as local file urls are playing without any issue. Is it a limitation of iOS/Cordova where we need to download and run the file instead of binding it to html5 video tag?
Is there any way where i can run these video files in an iOS/iPad device?
I am using html5  and  tags.
When url is binding to video/audio tag i am getting below issue in Xcode console

Server response for video file with .mov format

When i run the same video on Mac chrome browser it works. Only in case of mobile app it does not play media file. File is downloading as well when url is accessed directly.
Please let me know if you need more information on this particular issue.
Details of platform
Cordova:
"cordova-android": "^8.0.0",
"cordova-browser": "^5.0.4",
"cordova-ios": "^4.5.5",
"cordova-plugin-camera": "^4.0.3",
"cordova-plugin-device": "^2.0.2",
"cordova-plugin-file": "^6.0.1",
"cordova-plugin-file-opener2": "^3.0.0",
"cordova-plugin-geolocation": "^4.0.2",
"cordova-plugin-inappbrowser": "^3.0.0",
"cordova-plugin-media": "^5.0.2",
"cordova-plugin-media-capture": "^3.0.2",
"cordova-plugin-network-information": "^2.0.1",
"cordova-plugin-splashscreen": "^5.0.2",
"cordova-plugin-whitelist": "^1.3.3",

A: Html5 has official support for a VERY limited number of codecs and containers. Mp4/h264/aac is basically the only file that is guaranteed to work in all browsers. Any other format and you must convert it.


text:
Q: Is support of an operator same as row space?
Support of an operator is vector space that is orthogonal to its kernel.

Does this mean support is same as row space? How to calculate support for any matrix?

A: Yes, by Fundamental theorem of linear algebra.

A: Let's try to prove this statement in a slightly more rigorous way. We need to prove the following:
$\textbf{Claim 1.} \,\, \text{span}(r_1,r_2\ldots r_n) = \text{supp}(A)$
where $r_1,r_2 \ldots r_n$ are the rows of the given $n \times n$ operator $A$.
We can show this with the proving the following two claims:
$\textbf{Claim 1.1.} \,\,\text{span}(r_1,r_2\ldots r_n) \subseteq \text{supp}(A).$
$\textbf{Proof 1.1.} \,\, \langle \sum_i a_ir_i, x\rangle = 0$ for all combinations $\{a_i\}$ and $x \in \text{null}(A)$.
$\textbf{Claim 1.2.} \,\, \text{supp}(A) \subseteq \text{span}(r_1,r_2\ldots r_n).$
$\textbf{Proof 1.2.} \,\, $ Assume for contradiction that $\text{span}(r_1,r_2\ldots r_n) \subset \text{supp}(A)$. This implies $\text{dim}(\text{span}(r_1,r_2\ldots r_n)) < \text{dim}(\text{supp}(A))$. If $k \leq n$ is the rank of the operator $A$, then from the relation between dimensions of a subspace and its orthogonal complement along with rank-nullity theorem we get, $\text{dim}(\text{supp}(A)) = k$. Additionally, as the dimension of the row space is same as the operator rank $k$, we get a contradiction.


text:
Q: Open two Excel sheets simultaneously with Robot Framework Is it possible - and if yes, how? - to open two different Excel files with Robot Framework and copy from one Excel to the other?
What I know up to now is how to copy inside one Excel file:
ExcelLibrary.Open Excel Document    ${FileName}    doc_id=doc_id
${val} =   ExcelLibrary.Read Excel Cell    1    1
ExcelLibrary.Write Excel Cell    2    1    ${val}
ExcelLibrary.Save Excel Document    ${FileName}

but there is no selector for the Excel file if there are two files.

A: Yes it is possible. If you check the keyword documentation of Switch Current Excel Document, you can quite easily get the idea. You'll have as many Excel documents open as you wish but only one of them is active at the time, so the keywords only interact with the active one.
In your case it would be something like
Open Excel Document    ${FileName}     doc_id=doc_id
Open Excel Document    ${FileName2}    doc_id=doc_id2
${val} =               Read Excel Cell         1    1
Switch Current Excel Document          doc_id2
Write Excel Cell       2    1          ${val}
Save Excel Document                    ${FileName2}

Notice that if you are working on large set of data and the data is readily available in the first document (no cross-copying required), it usually is more efficient to copy everything you need in one go. Rather than having two documents open at the same time, you'd take everything needed from the first document, close it down and then paste everything to the secondary document in one go.


text:
Q: Facing record lock issue on Parent when loading millions records An external system is pushing data into my org using bulk API. There are about 2 million records. The target object is child__c.
The child__c has a lookup to parent__c. When the external system loads the data I get an error for some records saying: UNABLE_TO_LOCK_ROW:unable to obtain
exclusive access to this record. I have found the root cause of this at this article - https://help.salesforce.com/articleView?id=000229525&type=1 .
Now I am looking for the solution to over come this problem. Following are three things I found:

*

*Reduce the batch size - Batch size is already 2000 for 2 million
record. Will this help?

*Process the records in Serial mode instead of parallel, that way on batch is processed at a time. - Sure , serial mode will resolve
this problem but what is the impact on the time to insert the
records then. Given the size is 2 million. How long it might take if
the batch size is 2000 records.

*Sort main records based on their parent record, to avoid having different child records (with the same parent) in different batches
when using parallel mode.- This does not seem to suit my solution
since the external system have to make changes to the code.
Appreciate any suggestion from the community?

A: Your suggestions are all valid in there own right, but they do become dependent on your data.
I would lean towards #3 the most, as that is what I most often do (because it works with most of my data sets). The only time #3 would be bad is if you have 10's of thousands of records with the same lookup. This also doesn't pair well with number 1.
Consider 6000 child records per parent:
If you reduce your batch size. Now you are in greater risk of lock contention issues. Because you are trying to run 3 batches of 2000 at the same time that all have the same parent. You would be better leaving your batch size at 10000 records.
Now consider, you have 10s of thousands of child records per parent:
You are back in the same boat as you were. Now you are just running much larger batches that are going to have lock contention issues. If this is your scenario, you will more than likely have to run serially.
Like I said, the resolution is completely dependent on what your data looks like.
I know you feel that #3 isn't an option because you aren't getting the data ordered. But you can easily toss that into a local sql database and query it back out sorted. Among other options.


text:
Q: Java JButton positioning inconsistent Basically, I have a JPanel name canvas with a null layout, and I want to add a JButton to it. What I don't understand is how the program works only half of the time. When it works the button is placed in the desired position, but randomly sometimes, it's in a completely different spot to where it should be.
(buttons is an ArrayList containing JButton's.)
Method that creates the JButton:
 public static void createButton(String dialog, int startX, int startY, int
 sizeX, int sizeY) {

        JButton b = new JButton(dialog);
        b.setBounds(startX,startY,sizeX,sizeY);
        b.setVisible(true);
        b.setFocusable(false);
        //b.setLayout(null);
        b.addActionListener(game);

        buttons.add(b);
        canvas.add(buttons.get(buttons.size()-1));
    }

I run createButton in the main method like so:
public static void main(String[] args) {

    createButton("test",100,100,100,100);

    ...
}

I can't figure out this problem, and any help would be appreciated.


text:
Q: Xamarin: Could not install the application AMDeviceSecureInstallApplicationBundle returned: 0xe8008015 I am trying to deploy my app on the device to test.
In Debug mode I can deploy it successfully and it is working perfectly.
But when I am trying to deploy in Release mode it is giving me this error.
error MT1006: Could not install the application
'/Users/development/Library/Caches/Xamarin/mtbs/builds/AppName.iOS/longstring/bin/iPhone/Release/AppName.iOS.app'
on the device 'My iPhone': AMDeviceSecureInstallApplicationBundle returned: 0xe8008015.

Have anyone faced this issue? how I can deploy the App on my testing device in release mode?
I have already tried recreating the certificate and provisioning profile.
I am using visual studio 2019.

A: Check Your Entitlement plist and Enable / Disable push notification.
Then try to debug

A: I thought I should post the answer to this question.
I found the mistake I was doing with Signing Identity and Provisioning Profile. I was using a Distribution Certificate to deploy in release mode but should be using Ad-Hoc.


text:
Q: How to instantiate a Custom UIButton in UITableViewCell I have a UITableViewCell and my cells contain a UIButton subclass (CoolButton).
I have picked the code of CoolButton from raywenderlich tutorial
available here
In the IB I have created a subclass of the UITableViewCell and I have configured the class of my button to CoolButton and set the property type to Custom and configured the IBOutlet for the CoolButton to my UITableView subclass.
My problem is when cells are created, they get a UIButton instead of a CoolButton. As a consequence when I'm setting the properties of the CoolButton I get a crash with "unrecognized selector".
Why UIButton is instantiated instead of a CoolButton? How can I get my CoolButton in the table?
Thanks,
Séb.

A: I'm going to guess you are doing something like:
CoolButton *b = [UIButton ...]

You need to create it using the CoolButton class:
CoolButton *b = [CoolButton ....];

Or, if you used IB, that you created a UIButton but used an IBOutlet of CoolButton. You would need to make the actual class of the button you drag into IB CoolButton, which you can do by selecting the button and tapping (I think) the second to the left top tab in the inspector.


text:
Q: Need advice on Windows Server 2003 security for website use I hope some really cool experts can share their knowledge with me.
We have a dedicated server to host our online store

*

*Runs SQL 2005

*No uploading by web viewers, strictly to sell goods

*Server hosts a secure payment page for credit card processing. We don't store card data

*Subsequently, Server needs to be PCI-compliant

*No mail server function or FTP

*Server not connected to any other servers or PC

Questions:

*

*Do I need anti-virus, firewall or other software?

*If yes, can anyone recommend one?

*How do I backup server?

*In addition, I have a programmer who has user account in the server. How do I setup security policy so that he does not take away company data in database? He tweaks DB code every now and then.

Thanks a lot for the time and for every kind soul who attempted to answer these questions. Merry Christmas

A:
Do I need anti-virus, firewall or other software?

Yes

If yes, can anyone recommend one?

No. that is a shopping question.

How do I backup server?

Seriously?  You run a backup program like ntbackup or something else you buy saveing the results to some form of remote/removeable media.  The are entire books on this subject.

In addition, I have a programmer who has user account in the server. How do I setup security policy so that he does not take away company data in database? He tweaks DB code every now and then.

Setup a dev server for him.  Don't give him direct access to the production database.


text:
Q: multiple GIT repos, adding an existing project to GIT I have Two issues:

*

*I have two separate repos (network Team Foundation Server, GitHub)
I have several projects in a /wamp/www/ folder on my system, where they are served up. They go to the Git repo on the network.
I have a new project, which I want to put into my personal GitHub repo. I'm not sure what will happen if I simply add/commit/push. Pretty sure it'll end up in the default TFS repo. How do I point it at my own personal repo?

*putting an existing project into my repo
GitHub has several options for starting a new project, but it doesn't seem to have an option for dropping in an existing project.
The project is already within Git (since my www folder is Git init'd) so I can't simply git init it. (git init treats my project folder as if it is empty.)
UPDATE
This:

A: If I understood your question correctly, you would like to push your code to a GitHub repository in addition to your TFS repository?
The solution is to add another "remote". The initial repository you clone will link your local git to the remote called "origin". What you want to do if you want to push your repository to another server is to add a remote.
To do this, do the following:
git remote add github https://github.com/xxx/xxx.git
git push -u github master

Where "github" is the name of the remote you'll want. Call it something that makes sense to you, it can be anything. Then, when you'll want to push/pull from the "origin" remote, you'll be able to do a git push or git push origin, and if you'll want to push to the other remote, simply do a git push github.
Hope this helps.

A: It's not very clear for me what is the relation between project, repositories and "wampt/www" folder but the most probably solution with that information could be:

*

*try make a look to git-submodules. They allow include 3rd party git repos into git project e.g. your personal repo into company repos

*if there are no folder/file conflicts - the easiest way could be use git-remote to add 3rd party repo to you cloned repository; merge them and update/reorganize folder structure as needed.


text:
Q: Why are 301 redirects intermittently slow or time out in IIS 6? I'm no IIS wiz, but I can provide any additional info that might be helpful.
My site uses a 301 redirect to send requests for mysite.com to www.mysite.com. They are two separate sites in IIS. Most of the time it works without issue, but from time to time the redirect will take many seconds. Once I left it alone and it sat for about five minutes before timing out. Hitting refresh almost always causes the redirect to happen instantly as intended. I cannot find a pattern for this behavior, server logs look fine, and it doesn't appear to be happening during high volume times. To my eye it's happening at random. Can anyone suggest a way for me to track down the root of this issue or has anyone experienced something similar?


text:
Q: How to add fields that only cache something to ADT? Often I'm in the need of adding fields to an ADT that only memoize some redundant information. But I haven't figured out completely how to do it nicely and efficiently.
The best way to show the problem is to make an example. Suppose we're working with untyped lambda terms:
type VSym = String

data Lambda = Var VSym
            | App Lambda Lambda
            | Abs VSym Lambda

And from time to time we need to compute the set of free variables of a term:
fv :: Lambda -> Set VSym
fv (Var v)    = Set.singleton v
fv (App s t)  = (fv s) `Set.union` (fv t)
fv (Abs v t)  = v `Set.delete` (fv t)

Soon we realize that repeated computations of fv are a bottleneck of our application. We would like to add it to the data type somehow. Like:
data Lambda1 = Var (Set VSym) VSym
             | App (Set VSym) Lambda Lambda
             | Abs (Set VSym) VSym Lambda

But it makes the definition quite ugly. Almost (Set VSym) takes more space than all the rest. Moreover, it breaks pattern matching in all functions that use Lambda. And to make things worse, if we later decide to add some other memoizing field, we'll have to rewrite all patterns again.
How to design a general solution that allows adding such memoizing fields easily and unobtrusively? I'd like to reach the following goals:

*

*The data definition should look as close as possible to the original, so that it's easily readable and understandable.

*Pattern matches too should remain simple and readable.

*Adding a new memoizing field later should not break existing code, in particular:

*

*not to break existing patterns,

*not to require changes where the function we want to memoize was used (like code that used fv in this example).

I'll describe my current solution: To keep the data definition and pattern matches as little cluttered as possible, let's define:
data Lambda' memo = Var memo VSym
                  | App memo (Lambda' memo) (Lambda' memo)
                  | Abs memo VSym (Lambda' memo)
type Lambda = Lambda' LambdaMemo

where the data to be memoized is defined separately:
data LambdaMemo = LambdaMemo { _fv :: Set VSym, _depth :: Int }

Then a simple function that retrieves the memoized part:
memo :: Lambda' memo -> memo
memo (Var c _)   = c
memo (App c _ _) = c
memo (Abs c _ _) = c

(This could be eliminated by using named fields. But then we'd have to name all the other fields as well.)
This allows us to pick specific parts from the memoize, keeping the same signature of fv as before:
fv :: Lambda -> Set VSym
fv = _fv . memo

depth :: Lambda -> Int
depth = _depth . memo

Finally, we declare these smart constructors:
var :: VSym -> Lambda
var v = Var (LambdaMemo (Set.singleton v) 0) v

app :: Lambda -> Lambda -> Lambda
app s t = App (LambdaMemo (fv s `Set.union` fv t) (max (depth t) (depth s))) s t

abs :: VSym -> Lambda -> Lambda
abs v t = Abs (LambdaMemo (v `Set.delete` fv t) (1 + depth t)) v t

Now we can efficiently write things that mix pattern matching with reading the memoized fields like
canSubstitute :: VSym -> Lambda -> Lambda -> Bool
canSubstitute x s t
  | not (x `Set.member` (fv t))
      = True -- the variable doesn't occur in `t` at all
canSubstitute x s t@(Abs _ u t')
  | u `Set.member` (fv s)
      = False
  | otherwise
      = canSubstitute x s t'
canSubstitute x s (Var _ _)
      = True
canSubstitute x s (App _ t1 t2)
      = canSubstitute x s t1 && canSubstitute x s t2

This seems to solve:

*

*Pattern matching is still quite reasonable.

*If we add a new memoizing field it won't disrupt existing code.

*If we decide to memoize a function with signature Lambda -> Something we can easily add it as a new memoizing field.

What I still don't like about this design:

*

*The data definition isn't so bad, but still placing memo everywhere clutters it considerably.

*We need to have smart constructors for constructing values but we use the regular constructors for pattern matching. This is not so bad, we simply add one _, but having the same signature for constructing and deconstructing would be nice. I suppose Views or Pattern Synonyms would solve it.

*The computation of the memoized fields (free variables, depth) is tightly coupled to the smart constructors. As it's reasonable to assume that those memoized functions will be always catamorphisms, I believe this could be solved to some extent by tools like the fixpoint package.

Any ideas how to improve it? Or are there better ways to solve such a problem?

A: I think all of your goals can be met by using plain old memoization in the function instead of by caching results in the ADT itself. Just a couple weeks ago, I released the stable-memo package, which should help here. Checking over your criteria, I don't think we could do any better than this:

*

*Your data definition doesn't change at all.

*Pattern matching doesn't change, either.

*Existing code doesn't have to change merely because you write more memoized functions.

*

*No existing patterns get broken.

*No existing memoized functions get broken.

Using it is very simple. Just apply memo to any function you want to memoize, making sure that you use the memoized version of the function everywhere, even in recursive calls. Here's how to write the example you used in your question:
import Data.StableMemo

type VSym = String

data Lambda = Var VSym
            | App Lambda Lambda
            | Abs VSym Lambda

fv :: Lambda -> Set VSym
fv = memo go
  where
    go (Var v)   = Set.singleton v
    go (App s t) = fv s `Set.union` fv t
    go (Abs v t) = v `Set.delete` fv t


text:
Q: How to use COALESCE in Laravel? Is it possible to use COALESCE in laravel query?
$multipleitems = DB::table('votes')
    ->select('masterItemId',DB::raw('sum(votes) as voteSum'))
    ->whereBetween('voteDate',array($startDate,$endDate))
    ->where($condition)
    ->groupBy('masterItemId')
    ->get();

In the above code I want to get each item and its total votes. If there is no vote I want to get '0'.
But in the above code it returns items that have atleast one vote. Is there any method to get this done in laravel?

A: Well, the OP was not too helpful, but I will give it a shot! I assume, that the votes table contains actual votes cast by users on the items. This means, that if an item did not receive any vote, then that item id (masterItemId) does not exist in the votes table.
This means that the votes table has to be left joined on the main items table on the masterItemId field. I will call the main items table: items, and assume that it has an itemId field that matches the masterItemId field in the votes table.  In SQL terms:
select items.itemId, ifnull(sum(votes.votes),0) as votesSum
from items left join votes on items.itemId=votes.masterItemId
where votes.voteDate between ... and ... and <other conditions>
group by items.itemId

I'm not familiar with Laravel, but you will need something like this, however do not treat is as copy-paste code:
$multipleitems = DB::table('items')
                 ->leftJoin('votes','items.itemId','=','votes.masterItemId')
                 ->select('items.itemId',DB::raw('ifnull(sum(votes.votes),0) as voteSum'))
                       ->whereBetween('votes.voteDate',array($startDate,$endDate))
                       ->where($condition)
                       ->groupBy('items.temId')
                       ->get();


text:
Q: Asp.Net Web Service 415 Unsupported Media Type error I have done some changes and now getting 415 Unsupported Media Type.
I am posting the updated code.
My Web Service Interface.
Service/IWebService.cs
    [OperationContract]
    [WebInvoke(Method = "POST",
        BodyStyle=WebMessageBodyStyle.Wrapped,
        RequestFormat=WebMessageFormat.Json,
        ResponseFormat=WebMessageFormat.Json,
        UriTemplate = "http://localhost:50571/Service/WebService.svc/hello/say")]
    string hello(Deneme deneme );

 [DataContract]
public class Deneme
{
    [DataMember]
    public string say { get; set; }
}

My Web Service.
Service/WebService.svc
 [ServiceBehavior(IncludeExceptionDetailInFaults = true)]
 [AspNetCompatibilityRequirements(RequirementsMode =    AspNetCompatibilityRequirementsMode.Allowed)]
public class WebService : IWebService
{
    public string hello(Deneme deneme) {
        return deneme.say;
    }

Client Side Code.
in Login.aspx
$.ajax({
        type: 'POST',
        url: '/Service/WebService.svc/hello',
        data: { 'say': 'sdfs' },
        contentType: 'application/json; charset=utf-8',
        dataType:'json',
        success: function (s) {
            alert(s.d);
        }
    });

Web Config
<system.serviceModel>
  <services>
      <service name="TETP.Service.WebService">
          <endpoint address=""
            behaviorConfiguration=""
            binding="basicHttpBinding"
            contract="TETP.Service.IWebService" />
      </service>
  </services>
<behaviors>
  <serviceBehaviors >
    <behavior name="">
      <serviceMetadata httpGetEnabled="true" />
      <serviceDebug includeExceptionDetailInFaults="true" />
    </behavior>
  </serviceBehaviors>
</behaviors>
<serviceHostingEnvironment aspNetCompatibilityEnabled="false" multipleSiteBindingsEnabled="true" />
<client>
  <endpoint address="http://localhost:50571/Service/WebService.svc" binding="basicHttpBinding" bindingConfiguration="BasicHttpBinding_IWebService" contract="TETP.Service.IWebService" name="BasicHttpBinding_IWebService" />
</client>

i used to get 400 bad request error. Now i get 415 Unsupported Media Type error Thank you in advance.

A: I think you data request might need quotes differently than what you tried but I am not sure. I would suggest adding an alert of your data before the call to debug it. See below..
var mData = "{userName:'" + $('#usernametxtbx').val() + "',password:'" + $('#passwordtxtbx').val() + "'}";
alert(mData);
$.ajax({
        type: 'GET',
        url: 'Service/WebService.svc/Login',
        data:{userName:$('#usernametxtbx').val(),password:$('#passwordtxtbx').val()},
        dataType: 'application/json; content=utf-8',
        contentType: 'json',
        success: function (res) {
        if(res.d == true)
            window.location.replace(ResolveUrl('Default.aspx'));
            else
                window.location.replace(ResolveUrl('Login.aspx'));
        }
    });


text:
Q: Get two columns (Images Stacked over Text) to sit properly next to each other This is an error which only occurs in Outlook 2010. This email template seems to work on 90% of devices and browsers.
The graphic below is an example of how it looks in Outlook 2010. The crude blue draw over is intended to show how it should look. You can also view the fiddle for the entire code which displays that section how it is supposed to be displayed.
http://postimg.org/image/zacxr5acr/
Here's the full fiddle link  http://jsfiddle.net/Nexus1234/bxp14vcw/
Note - the below sample code is only the relevant section and sending this on its own in an email doesn't cause the issue, it's somewhere within the complete html which is in the jsfiddle

                              The Roman Forum

Here,
                      in a small space hemmed in by the great rocks of the Capitoline
                      and Palatine hills, the greatest names of Roman history fought
                      for power and prestige. Amidst an extraordinary concentration
                      of famed and marvellous buildings jostling for space, you will
                      walk where Antony spoke over Caesar’s body, Cicero
                      delivered stinging orations and the legions processed in
                      triumph.

                              The Villa Adriana & The Villa D'Este

Experience
                      the opulence of two ages in a trip out to the inspiring
                      hillside retreat of Tivoli. In the morning, we visit the
                      massive, brilliantly preserved and sprawling villa of the
                      Emperor Hadrian, where luxury on an unparalleled scale centres
                      on a fantasy rendition of the River Nile. The afternoon is
                      spent amidst the fountains and gardens of the enchanting
                      Renaissance Villa d’Este.

A: One suggestion would be to always keep in mind the 20px rule. Outlook loves to add spacing around tables, making aligned tables a hassle.
My usual equation is,
(Wrapper table - 20px) / 2.
Your example:
(580 - 20px) = 560 / 2.
Percentages are tricky, I would set your tables as a fixed width. Your deviceWidth class will handle your widths on mobile anyway.
I would suggest applying this too all of your aligned tables.
If that doesn't work, let me know.


text:
Q: Operating Micropython-running WeMos D1 mini (ESP8266) pins with HTTP requests What I am trying to ultimately achieve is to control my garage door opener with a relay connected to a WeMos D1 Mini, connected to my home WiFi. I am using the openGarageDoor() function. Everything works fine with serial connection.
I have been trying to run HTTP server on a WeMos D1 Mini with this script.
    customertagsAction() -- try:
    import usocket as socket
except:
    import socket

CONTENT = b"""\
HTTP/1.0 200 OK
Hello #%d from MicroPython!
"""

def main(micropython_optimize=False):
    s = socket.socket()

    # Binding to all interfaces - server will be accessible to other hosts!
    ai = socket.getaddrinfo("0.0.0.0", 8080)
    print("Bind address info:", ai)
    addr = ai[0][-1]

    s.setsockopt(socket.SOL_SOCKET, socket.SO_REUSEADDR, 1)
    s.bind(addr)
    s.listen(5)
    print("Listening, connect your browser to http://<this_host>:8080/")

    counter = 0
    while True:
        res = s.accept()
        client_sock = res[0]
        client_addr = res[1]
        print("Client address:", client_addr)
        print("Client socket:", client_sock)

        if not micropython_optimize:
            # To read line-oriented protocol (like HTTP) from a socket (and
            # avoid short read problem), it must be wrapped in a stream (aka
            # file-like) object. That's how you do it in CPython:
            client_stream = client_sock.makefile("rwb")
        else:
            # .. but MicroPython socket objects support stream interface
            # directly, so calling .makefile() method is not required. If
            # you develop application which will run only on MicroPython,
            # especially on a resource-constrained embedded device, you
            # may take this shortcut to save resources.
            client_stream = client_sock

        print("Request:")
        req = client_stream.readline()
        print(req)
        while True:
            h = client_stream.readline()
            if h == b"" or h == b"\r\n":
                break
            print(h)
        client_stream.write(CONTENT % counter)

        client_stream.close()
        if not micropython_optimize:
            client_sock.close()
        counter += 1
        print()

main()

The requests are received properly and the GET variables are shown on the print(). The best i have been able to do is
req = client_stream.readline()
    print(req)
    while True:
        h = client_stream.readline()
        if h == b"" or h == b"\r\n":
            break
        print(h)
    client_stream.write(CONTENT % counter)
    //my function here:
    if 'opengaragedoor=1' in req:
        openGarageDoor()
    client_stream.close()

I don't know how to parse the request properly. I only have come up with this dirty solution. This probably causes a timeout on the requesting system, as Postman or such needs to wait for the function to run through.


text:
Q: Why is the inverse an element of the stabilisator of a group? $G$ operates on the set $X$. I have to prove:

The stabilisator $G_x$ is a subgroup of $G$.

*

*$G_x\neq \emptyset$, because for the neutral element $1\in G$ is $1.x = x$, therefore $1\in G_x$.

*Let $g, h \in G_x$ be arbitrary. Then $g.x = x$ and $h.x = x$ and therefore $gh.x = g.(h.x) = g.x = x$, i.e. $gh \in G_x$.

Now I have to prove, that for arbitrary $g \in G_x$ the inverse $g^{-1}$ is also an element of $G_x$. I am stuck here, because I have no explanation why there should be a inverse element at all.
For the case $1\in G_x$ I can say, that the inverse of $1$ is $1$. But I cannot explain why an arbitrary element $g$ should have an inverse in $G_x$, except $g$ is inverse to itself.

A: As $G$ defines an operation on $X,$ you know that you have
$$g^{-1}\cdot (g\cdot x)=(g^{-1}g)\cdot x=1\cdot x=x$$ and as $g\cdot x=x$ from the hypothesis $g\in G_x,$ you get your result.


text:
Q: Field extension of finite fields are always separable? I guess the answer is very trivial, but at the moment I don't get it.
Let $p$ prime. Consider the extension $\mathbb{F}_{p^n} | \mathbb{F}_p$ with $n \in \mathbb{N}$ arbitrary.
We know that this is a galois extension.
But why this extension is separable?
Especially for $p|n$ it can't be separable, because there is at least one element who's derivative of his minimal polynomial is zero?
Where is the misstake? Ty for help.

A: No, there are no elements $\alpha\in\Bbb{F}_{p^n}$ such that the minimal polynomial $m(x)$ of $\alpha$ would have zero derivative. For $m'(x)$ to be zero, we must have the form
$$
m(x)=\sum_{i}a_ix^{pi}
$$
for some finite set of coefficients $a_i\in\Bbb{F}_p$. By Little Fermat $a_i^p=a_i$ for all $i$, so in fact
$$
m(x)=\left(\sum_ia_ix^i\right)^p.
$$
But this contradicts the fact that a minimal polynomial is irreducible.


text:
Q: Sizing image but need math equation
Here's my issue.
I have a website mainly of images, but the image producer creates them to be too big for an average screen size so I'm looking for math equations to use to automatically size them to my screen.
In the image you see, the big image box has dimensions IX,IY. and the formatted image box has dimensions X,Y and the screen space has dimensions SX,SY.
X and Y need to be less than SX and SY respectively. IX or IY need to be bigger than SX or SY.
When the image is downsized, the scaling needs to be intact regardless of the orientation of the image and there always needs to be a fixed available width in the screen area for text.
This is a PHP equivalent code I used to try to produce the results:
    $pc=($xsw/$xsh);
    if ($xsw > $xsh){
            $xsh=intval($xsh/$pc);if ($xsh > $ch){$xsh=$ch;}
            $xsw=($xsh*$pc);
    }else{
            $xsw=intval($xsw*$pc);if ($xsw > $cw){$xsw=$cw;}
            $xsh=($xsw/$pc);
    }

But I feel my math is way off.
Here's examples of what I'm trying to achieve:
If the screen size is 800x600 and I want 200px room for text on the side and the image is 1000x500 in size, then I want the image to be 600x300.
If the screen size is 1024x768 and I want 124px room for text on the side and the image is 2000x2000 in size, then I want the image to be 768x768 in size.
The reason why I ask this is because I want to make the website not require side-scrolling from the use of oversized images.
Does anyone have a good equation or set of equations I can try?

A: First, find the maximum $X$ and $Y$ you will accept, which are $SX, SY$ minus the room you want for text.  Then find the reduction factor, which is $\min(\frac X{IX},\frac Y{IY})$  Scale by the reduction factor (which, if the original is small may be greater than $1$ and you are expanding, that is OK).  One dimension will give you extra room for text:  fill it up.

A: In pseudo-code:
RawImageRatio = IY/IX;
X = SX - TextSpace;
Y = X * RawImageRatio;
If IY/Y>IX/X then
    Scale = Y/IY;
else
    Scale = X/IX;


text:
Q: receiving webpages using windows sockets(C ++),but got some unexpected words I am trying to get a webpage with sockets,using http GET.I do get the page,but there is something little wrong.
Sometimes I got it all right,but sometimes I got it with wrong characters like:
        **09</t

1ff8
d>**
it should be :
        09

I donot know why there is a "1ff8" and some "\r\n".
It happens here and there from time to time.And sometimes it occurs like:
            06
again it should be :
   06

this is how I receive and save the page from a socket:
                     ofstream out("webpage.html");
         char text[2050]="";

         int recvbytes=0;
         string content;
         while ( (recvbytes = recv(sock, text, 2048, 0)) > 0)
         {
             content=string(text,recvbytes);
             out << content.c_str();
             //System::Console::Write(gcnew String(content.c_str()));
         }

         closesocket(sock);
         out.close();

I tried :out << text; it did not work.
Please does anyone know what's wrong with my codes.
I am using VS2010,and this is a winform program.

A: It may be normal if your input text is UTF8 encoded and contains characters out of ASCII space

A: Now I got it done.it turns out that those "1ff8" "2000" or whatever are from some http protocols,to indicates something(length?).I just need to delete those lines and rearrange the lines that are interrupted by them.So I add a function:
private: void rearrangment()
    {
        ifstream ifile("webpage.html");
        ofstream ofile("web.html");
        char line1[2048]="";
        char line2[2048]="";
        char line3[2048]="";
        ifile.getline(line1,2047);
        //ifile.getline(line2,2047);
        while(!ifile.eof())
        {
            ifile.getline(line2,2047);

            if(string(line2,0,3)!="   "
                && line2[0]!='<' && line2[1]!='<' && line2[2]!='<')//they are "1ff8"s
            {
                ifile.getline(line3,2047);
                for(int i=0;i<2046;++i)
                {
                    if(line1[i]==13)
                    {
                        line1[i]=0;
                        break;
                    }
                }
                strcat(line1,line3);

            }
            else
            {
                ofile<<line1<<endl;
                strcpy(line1,line2);
                //ofile<<line1;
            }
            //ofile<<line1;
        }
        ifile.close();
        ofile.close();
    }

and now it works well.
Sorry about this stupid question,I should have searched before I  asked.


text:
Q: Parse iOS beginner: getting an exception on PFUser signup I am fairly new to both iOS development and Parse. I am going through the parse documentation and trying to build a proof of concept app that would be relevant to my project.  https://parse.com/docs/ios_guide#users-props/iOS
The following code is directly from the guide:
- (void)myMethod {
    PFUser *user = [PFUser user];
    user.username = @"my name";
    user.password = @"my pass";
    user.email = @"email@example.com";

    // other fields can be set just like with PFObject
    [user setObject:@"415-392-0202" forKey:@"phone"];

    [user signUpInBackgroundWithBlock:^(BOOL succeeded, NSError *error) {
      if (!error) {
          // Hooray! Let them use the app now.
      } else {
          NSString *errorString = [[error userInfo] objectForKey:@"error"];
          // Show the errorString somewhere and let the user try again.
      }
    }];
}

I have integrated this method into my app and running it throws the following exception:
-[PFObject setIsCurrentUser:]: unrecognized selector sent to instance 0x8b63be0
2013-07-02 21:50:00.147 signuptest[58478:c07] *** Terminating app due to uncaught exception 'NSInvalidArgumentException', reason: '-[PFObject setIsCurrentUser:]: unrecognized selector sent to instance 0x8b63be0

I am hoping that someone who has more familiarity with Parse can point me towards the right direction here.  I have dug through the api and I do not see the setIsCurrentUser: method anywhere for PFObject.
My end goal is to basically create the PFUser object and save it on Parse database using the above method.
Does anyone know why that exception is being thrown?  I can provide the full code of my test app if needed.

A: So I finally figured out what the problem was.  Previously in  the same project I had subclassed the PFUser object using MyUser object class and had registered that subclass with parse.  Later on I deleted the subclass and reverted back to the original PFUser object for my app. However XCode had cached the previous build configs and continued to use them.  Therefore I was getting an instance mismatch on the server.  The method itself works fine.
The solution:
Cleared out the caches and any old build files using this as a reference:
How to Empty Caches and Clean All Targets Xcode 4
I hope this will help anyone who has the same problem in the future.


text:
Q: React-native-document-picker not working in android React-native-document-picker not working in android
after selecting image app stopped.
react-native ver:-59.5
react-native-document-picker --v:-3.2.4
I am using this code.
    var results = await DocumentPicker.pickMultiple({
      type: [DocumentPicker.types.images],
    });
    for(var res of results) {
     this.setState({
      getSecondFile:res,
      chosepic_2:res.uri
    })
    console.log(
                  res.uri,
                  res.type, // mime type
                  res.name,
                  res.size
                );
   }
 } catch (err) {
  if (DocumentPicker.isCancel(err)) {
    // User cancelled the picker, exit any dialogs or menus and move on
  } else {
    throw err;
  }
}```

A: In my project. i used another library i.e react-native-open-doc and it not work properly in my project.and i used android studio for found out the error.
you can use this code for find the file in console

  try {
    const res = await DocumentPicker.pick({
      type: [DocumentPicker.types. allFiles],
    });

    console.log(
      res
    );
  } catch (err) {
    if (DocumentPicker.isCancel(err)) {
      // User cancelled the picker, exit any dialogs or menus and move on
    } else {
      throw err;
    }
  }
}````


text:
Q: AWS - Can I launch nodes under a DNS domain (Auto Scale Group)? Use Case
I'm working on an application that uses Presto, and for Presto, I have to set up HTTPS traffic internally (for security compliance reasons).
For this, I preferably need the nodes' FQDN to be in the same domain.  E.g. myhost1.mydomain.com, myhost2.mydomain.com.
My Question
AWS automatically gives a FQDN like ip-10-20-30-40.ec2.internal.  So, my question is:
Is there a way I can have a new node automatically be created with a FQDN like myhost1.mydomain.com?  I know I can create internal "hosted zones" and DNS records for my hosts pretty easily, but I can't figure out how to make that the default domain for a new host.
Also, just FYI, I'm doing this for an auto-scale group; but I suspect that's irrelevant.

A: I'm not familiar with Presto, but here's a couple of ideas.
First, if you are using an AWS managed load balancer, you can enable HTTPS between it and the instance using self-signed cert:  the load balancer will NOT validate the cert, so your connection will be secure.
If that's not what you need, take a look at DHCP option sets for your VPC - I believe you can set your own domain name, rather than use the default ec2.internal.

A: When the Amazon EC2 starts, it can run a script passed in via User Data.
You could code this script to create a CNAME record in Amazon Route 53 that points to the IP address of the instance.
I'm not sure how you'd necessarily determine the number within the name, so you could just create a random name. Also, it might be tricky to remove the CNAME entry when the instance is terminated. One way to both assign and remove the record would be to use Amazon EC2 Auto Scaling Lifecycle Hooks, which allows code to be triggered outside of the instance itself. It's more complex but would be fully effective.


text:
Q: errors: [1] 0: {message: "Undefined offset: 1} I am receiving an php error errors: [1]
0:  {
message: "Undefined offset: 1 (Error Number: 8), (File: /Users/akashpatel/Documents/iOS development/RideShare/RideShareAPI/src/frapi/library/Frapi/Controller/Api.php at line 299)"
name: "PHP Notice error"
at: ""
}.
Below is the code.
if (isset($_SERVER['HTTP_LOGIN']))
    {
        list($userId, $apiKey) = explode(':',  base64_decode($_SERVER['HTTP_LOGIN']));

        $this->setUserId($userId);
        $this->setApiKey($apiKey);

        //check against DB
        $sql = "SELECT * from user WHERE id=:userId AND apiKey=:apiKey";

        $stmt = $db->prepare($sql);

        $stmt->bindParam(':userId', $this->getUserId());
        $stmt->bindParam(':apiKey', $this->getApiKey());

        try
        {
            $stmt->execute();
            $user = $stmt->fetchObject();
        }
        catch(PDOException $err)
        {
            echo $err->getMessage();
        }

        if ($user == null)
            throw new Frapi_Error('STATUS_FORBIDDEN');
    }
    else
    {
        $this->userName = false;
        $this->apiKey = false;

        throw new Frapi_Error(
            Frapi_Error::ERROR_INVALID_ACTION_REQUEST_NAME,
            Frapi_Error::ERROR_INVALID_ACTION_REQUEST_MSG,
            Frapi_Error::ERROR_INVALID_ACTION_REQUEST_NO,
            Frapi_Error::ERROR_INVALID_ACTION_REQUEST_HTTP_MSG
        );
    }

Thanks in advance.
EDIT :
Sorry everyone. I passed incorrect values. Now I use correct one, but getting error ERROR_INVALID_ACTION_REQUEST. May be this is because it goes to else. But not getting what can be the reason. I edited the code.

A: This means the string did not explode into two parts and the resulting array does not have an offset 1. You should not list()-assign variables unless you are 2000% sure you have that many indexes in the array you're assigning. In this case it's out of your control, so you better check first.


text:
Q: XPath/XQuery - matching all elements containing a particular value My XML looks a bit like this:
<root>
  <child1>
    <grandchild1>{tagID1}<grandchild1/>
    <grandchild2>{tag2}<grandchild2/>
  </child1>
  <child2>{newtag1}<child2/>
<root/>

I am looking to retrieve all elements whose text() is like "{*}" i.e. contains a string between 2 curlies, but am not too familiar with xpath.
I thought the xquery syntax would be something like
"//*[matches(., '{*}')]"

but that is failing with unknown method "-->matches(.<--"
I'd be grateful if someone could correct me please.

A: The matches() function is available to XPath 2.0, but your XPath engine probably only supports XPath 1.0.
If that is the case, you'll have to end up with something like this:
//*[./text()[starts-with(., '{') and substring(., string-length(.), 1)='}']]

It looks for
ANY ELEMENT
//*
   THAT HAS A TEXT NODE
   [./text()                                                               ]
            WHICH STARTS WITH A '{'
            [starts-with(., '{')                                          ]
                                 AND ENDS WITH A '}'
                                 and substring(., string-length(.), 1)='}'

The substring() function call does what you would expect of an ends-with() function if there was any in XPath 1.0.

EDIT (to address OP's comment about starts-with() not being found, either)
I haven't ever seen an XPath engine that doesn't know starts-with(). If it at least recognizes the substring() function, you can try the following workaround:
//*[./text()[substring(., 1, 1)='{' and substring(., string-length(.), 1)='}']]

which should do the same.

A: Your XPath looks correct, but the xml and regex are wrong.
The {} are special chars and have to be escaped with \. And a * can not be used alone. So the correct expression is (using text() instead of ., so it does not check the text of all descendants) :
//*[matches(text(), '\{.*\}')]

Although that function is only available in XPath 2 (and XQuery, since it is a superset), you could try the full name fn:matches.
In the xml the closing slashes have to be on the other side:
<root>
  <child1>
    <grandchild1>{tagID1}</grandchild1>
    <grandchild2>{tag2}</grandchild2>
  </child1>
  <child2>{newtag1}</child2>
</root>


text:
Q: Where adding pessimistic lock in using hasMany? Suppose I have this code
Domain
class Parent{
   static hasMany =  [Childs:Child]
}

class Child {
   String name
}

Controller
def ParentInstance = Parent.get(1) //Parent.lock(1)

ParentInstance.Childs.each {
    //it.lock()
    it.name = "titi"
}

ParentInstance.save()

The lock should be added for each child instance or just adding it when getting the parent?


text:
Q: How and where would I combine these two variable in JavaScript? I have this code I've pieced together linked to an action button in this PDF. It is supposed to verify if all required fields are entered and if so, it will pull the name and employee number from the document and generate an email with the PDF attached. If it fails these checks, there's a pop-up that warns the user of the missing information.
The problem I have is that the when the code runs, you can bypass the warning and still email the document.
How do I adjust this to stop until all of the fields are answered?
Desired "Pseudo code":
Check empty fields (get Manager's Name) (get manager's EE nubmer). If required fields (checkbox) and comments are empty, alert user.
If it's good, build email subject line and text from these areas...
Here's the code as it stands:
var emptyFields = [];

for (var i = 0; i < this.numFields; i++) {
    var f = this.getField(this.getNthFieldName(i));

    if (f.type != "button" && f.required) {
        if ((f.type == "text" && f.value == "") || (f.type == "checkbox" && f.value == "Off")) emptyFields.push(f.name);
    }
}

if (emptyFields.length > 0) {
    app.alert("Error! This checklist is incomplete:\n" + emptyFields.join("\n"));
}

// Build the subject line text from several fields form fields
var subj_text = getField("Weekly Management Critical Items:").valueAsString;
subj_text += ": " + getField("Manager Name").value;
subj_text += "- " + getField("Manager EE#").valueAsString;

// Send the email
mailDoc({
    cTo: "dennis.aikens@fedex.com",

    cSubject: subj_text,

    cMsg: "Hey Dennis, here's my checklist for this week. \r" + "Let me know if you have any questions. Thank you."
});

I know it's a little long, so I appreciate you for reading.
Thanks for all your time and input!

A:
You should write down the clean control flow code...
        for now you can use that

var emptyFields = [];

for (var i = 0; i < this.numFields; i++) {
    var f = this.getField(this.getNthFieldName(i));

    if (f.type != "button" && f.required) {
        if ((f.type == "text" && f.value == "") || (f.type == "checkbox" && f.value == "Off")) emptyFields.push(f.name);
    }
}

if (emptyFields.length > 0) {
    app.alert("Error! This checklist is incomplete:\n" + emptyFields.join("\n"));
}else{
sendMail();
}

var sendMail = function(){
// Build the subject line text from several fields form fields
var subj_text = getField("Weekly Management Critical Items:").valueAsString;
subj_text += ": " + getField("Manager Name").value;
subj_text += "- " + getField("Manager EE#").valueAsString;

// Send the email
mailDoc({
    cTo: "dennis.aikens@fedex.com",

    cSubject: subj_text,

    cMsg: "Hey Dennis, here's my checklist for this week. \r" + "Let me know if you have any questions. Thank you."
});
}


text:
Q: Converting C++ to MATLAB I am trying to convert some C++ code to MATLAB and having an issue. Would someone please explain a single line of code from below.
  int *image      = (int *) malloc(size*sizeof(int)) ;

  bool diff = true;
  while (diff)
  {
     diff = false;
    for (unsigned int itt = 0; itt < size; itt++)
    {
      diff = diff || (image[itt] != image[image[itt]]);
      image[itt] = image[image[itt]];
    }
  }

Could someone explain from
  diff = diff || (image[itt] != image[image[itt]]);
  image[itt] = image[image[itt]];

This part
image[image[itt]]

I don't understand how this works in terms of MATLAB
Image = zeros(100,100);

ImageSize = (Image);
diff = true;

while(diff)
    diff = false;
    for x=1:ImageSize(1) % Height
        for y=1:ImageSize(2) % Width
        diff = diff || (image(x,y) ~= ????);
        image(x,y) = ????;
        end
    end
end

Thanks to anyone who can help me understand this.

A: First of all, ImageSize = (Image); is not correct. This will simply assign Image to ImageSize. Use ImageSize = size(Image); instead.
Secondly, you are using double indexing in you Matlab code, while the C++ code is using single indexing.
while(diff)
    diff = false;
    for n=1:numel(Image) %# Total pixels in the image
        diff = diff || (Image(n) ~= Image(Image(n)));
        Image(n) = Image(Image(n));
    end
end

You might have to transpose your matrix, because I'm not certain whether the C++ code operates column-wise or row-wise. Also, because you're initializing you matrix to all zeros (zeros(100,100);), you're going to get all zeros back as the result. Try initializing it to an actual image or at least random integers.
Cheers!


text:
Q: How to get Phalcon to delegate actions to other controllers? The problem
I would like to be able to write controller-like classes and provide them as a vendor to the end applications. Then the end application controller could just instantiate my class and invoke their action methods.
The thing is that I want them to be invoked automatically. I must avoid repeating each action method in the end controller.
First approach
I've tried this:
Code
class IndexController
{
    protected $vendorController;

    public function initialize()
    {
        $this->vendorController = new VendorController();
    }

    public function __call($name, $args)
    {
        call_user_func_args([$this->vendorController, $name], $args);
    }
}

where the VendorController class looks like this:
class VendorController
{
    public function testAction()
    {
        die("this is test action");
    }
}

Result
but it gives me
Action 'test' was not found on handler 'index'

I'm assuming I've checked that Phalcon internally does some checking which looks like this:
if (method_exists($controller, $actionName)) { // ...

which results in not found action.
Perhaps I can override this behavior somehow? I'm using my own dispatcher class that extends Phalcon's native dispatcher if that helps in any way. But I've tried to override methods like getHandlerName() without any success.
Second approach
I also tried to use traits:
Code
trait TVendorController
{
    public function testAction()
    {
        die("this is test action");
    }
}

class IndexController
{
    use TVendorController;
}

And this approach works, but has a major flaw:
The flaw
If the IndexController extends some kind of BaseController that contains methods like initialize() or beforeExecuteRoute() (which is often the case) then it is too easy to forget about calling them. The threat here is that BaseController methods can contain for example authentication logic:
trait TVendorController
{
    public function beforeExecuteRoute()
    {
        // silently overrides the BaseController::beforeExecuteRoute()
    }

    public function testAction()
    {
        die("this is test action");
    }
}

abstract class BaseController
{
    public function beforeExecuteRoute()
    {
        // OOPS: this is never called
        $username = $this->session->get('username', null);
        if (!$username) {
            $this->response->redirect('index/login');
        }
    }
}

class IndexController extends BaseController
{
    use TVendorController;
}

The questions
In case of the first approach: how to tell Phalcon's event-loop that the action actually exists in controller?
Or if it cannot be done then:

*

*How to write my vendor controllers?

*How to combine them into end application controllers so that actions will get called automatically?

A: You may try to add EventManager with dispatch:beforeDispatch attachment. At dispatch:beforeDispatch moment you know action name but it should be possible to hit it before checking if action does actually exists.
In beforeDispatch function you may want to check, if delivered action name is callable inside controller, and if not, you should be able to forward to some king of execvendorAction method.
EDIT:
I have done this event managing:
$di->setShared('dispatcher', function() {

    $dispatcher = new Dispatcher();

    $eventsManager = new EventsManager();

    $eventsManager->attach("dispatch:beforeDispatch", function($event, $dispatcher) {

        $controllerName = $dispatcher->getControllerClass();
        $action = $dispatcher->getActionName();

        if(!method_exists($controllerName, $action . 'Action')) {

            $dispatcher->forward(array(
                // not delivering 'controller' param to make it stay
                // in current one
                'action' => 'vendor',
                'params' => array(
                    'name' => $action,
                    'params' => $dispatcher->getParams()
                )
            ));
        }
    });

    $dispatcher->setEventsManager($eventsManager);
    return $dispatcher;
});

Than, I've added in controllerBase such an action:
public function vendorAction($name, $arguments) {

    var_dump(array(
        'name' => $name,
        'arguments' => $arguments
    ));

    // $name .= 'Action';
    if(method_exists(array($this->vendorController, $name))) {
        call_user_func_args(array($this->vendorController, $name), $arguments);
    } else {
         // work it out
    }
}

and got it working. Every controller extending from controllerBase will run your methods in delivered in it vendorController. You will have to work out your own way to handle notFound exceptions, as this is a very nonstandard implementation.
Tested with classic router/dispatcher/everything on Phalcon.


text:
Q: Is there a Db2 scalar function to retrieve full error message information for a given SQLCODE? I'd like to know if there is any existing solution for getting detailed DB error explanations in code if I have a SQL error code. I'd like to dump this info into log so that I won't have to look up google everytime I meet one.
Target tach stack is - Java, DB2.
Thank you!

A: The function SYSPROC.SQLERRM will return the error message for a given SQLCODE. https://www.ibm.com/support/knowledgecenter/en/SSEPGG_10.5.0/com.ibm.db2.luw.sql.rtn.doc/doc/r0022027.html
E.g. This will return the short message for SQLCODE 100 (i.e SQL100W)
VALUES (SYSPROC.SQLERRM (100))

like this
1
---------------------------------------------------------------------------------------------------
SQL0100W  No row was found for FETCH, UPDATE or DELETE; or the result of a query is an empty table.

  1 record(s) selected.

and this will return the full message
VALUES (SYSPROC.SQLERRM ('SQL100W', '', '', 'en_US', 0))

will return
1
----------------------------------------------------------------------------

SQL0100W  No row was found for FETCH, UPDATE or DELETE; or the result of
      a query is an empty table.

Explanation:

One of the following conditions is true:

*  No row was found that meets the search conditions specified in an
   UPDATE or DELETE statement.

*  The result of a SELECT statement was an empty table.

*  A FETCH statement was executed when the cursor was positioned after
   the last row of the result table.

*  The result of the SELECT used in an INSERT statement is empty.

No data was retrieved, updated, or deleted.

User response:

No action is required. Processing can continue.

sqlcode: +100

sqlstate: 02000

  1 record(s) selected.


text:
Q: Error when checking target: expected lambda_1 to have 1 dimensions, but got array with shape (60000, 10) i am trying to create a invertible networks, when it goes backward , the weight matrix is the transpose of the weight matrix in forward process. so i  define a custom layer
  class Backwardlayer(Dense):
        def __init__(self,output_dim,b_layer,activation=None,use_bias=True,kernel_initializer='glorot_uniform',bias_initializer='zeros',kernel_regularizer=None,bias_regularizer=None,activity_regularizer=None,kernel_constraint=None,bias_constraint=None,**kwargs):
            self.output_dim = output_dim
            self.b_layer = b_layer

            super(Backwardlayer, self).__init__(output_dim,**kwargs)

        def build(self, input_shape):
            assert len(input_shape) >= 2
            input_dim = input_shape[-1]

            self.kernel = K.transpose(self.b_layer.kernel)

            if self.use_bias:
                self.bias = self.add_weight(shape=(self.output_dim,),initializer=self.bias_initializer, name='bias', regularizer=self.bias_regularizer, constraint=self.bias_constraint)
            else:
                self.bias = None
            self.built = True

def direction_cosine(x):
    return K.sqrt(K.sum(x, axis=-1, keepdims=None))
def abs(x):
    return K.abs(x)

        input_img = Input(shape=(784,))
        layer_1 = Dense(512, activation=abs)
        layer_2 = Dense(512, activation=abs)
        layer_3 = Dense(256, activation=abs)
        layer_4 = Dense(128, activation=abs)
        layer_5 = Dense(10, activation=abs)

        encoder_layer_1 = layer_1(input_img)
        encoder_layer_2 = layer_2(encoder_layer_1)
        encoder_layer_3 = layer_3(encoder_layer_2)
        encoder_layer_4 = layer_4(encoder_layer_3)
        encoder_layer_5 = layer_5(encoder_layer_4)

    decoder_layer_1 = Backwardlayer(128,b_layer=encoder_layer_5,activation=abs,name='dl1')(encoder_layer_5)
decoder_layer_2 = Backwardlayer(256,b_layer=layer_4,activation=abs,name='dl2')(decoder_layer_1)
    decoder_layer_3 = Backwardlayer(512,b_layer=layer_3,activation=abs,name='dl3')(decoder_layer_2)
    decoder_layer_4 = Backwardlayer(512,b_layer=layer_2,activation=abs,name='dl4')(decoder_layer_3)
    reconstructed_img = Backwardlayer(784,b_layer=layer_1,activation=abs,name='dl5')
rms = RMSprop()
(x_train,y_train), (x_test,y_test) = mnist.load_data()

x_train = x_train.reshape(-1,784)
x_test = x_test.reshape(-1,784)

x_train = x_train.astype('float32')
x_test = x_test.astype('float32')
x_train /= 255
x_test /= 255

AANN = Model(input=input_img, output=[reconstructed_img,normalised_output])

AANN.summary()

AANN.compile(optimizer=rms,loss=['mse','categorical_crossentropy'],loss_weights=[1,1])

history = AANN.fit(x_train,[x_train,y_train],epochs=3,batch_size=128,verbose=2,validation_data=(x_test,y_test))

here is the error: Error when checking target: expected lambda_1 to have 1 dimensions, but got array with shape (60000, 10)
Traceback (most recent call last):
 File "AANN.py", line 95, in <module>
    history = AANN.fit(x_train,[x_train,y_train],epochs=3,batch_size=128,verbose=2,validation_data=(x_test,y_test))
  File "/Library/Frameworks/Python.framework/Versions/3.6/lib/python3.6/site-packages/keras/engine/training.py", line 955, in fit
    batch_size=batch_size)
  File "/Library/Frameworks/Python.framework/Versions/3.6/lib/python3.6/site-packages/keras/engine/training.py", line 792, in _standardize_user_data
    exception_prefix='target')
  File "/Library/Frameworks/Python.framework/Versions/3.6/lib/python3.6/site-packages/keras/engine/training_utils.py", line 126, in standardize_input_data
    'with shape ' + str(data_shape))
ValueError: Error when checking target: expected lambda_1 to have 1 dimensions, but got array with shape (60000, 10)

A: The error is self explaining: "tensors don't have kernels".

Layers have kernels.

This is not true:
encoder_layer_1 = layer_1(input_img)
encoder_layer_2 = layer_2(encoder_layer_1)
encoder_layer_3 = layer_3(encoder_layer_2)
encoder_layer_4 = layer_4(encoder_layer_3)
encoder_layer_5 = layer_5(encoder_layer_4)

This is true:
layer_1_output_tensor = layer_1(input_img)
layer_2_output_tensor = layer_2(layer_1_output_tensor)
layer_3_output_tensor = layer_3(layer_2_output_tensor)
layer_4_output_tensor = layer_4(layer_3_output_tensor)
layer_5_output_tensor = layer_5(layer_4_output_tensor)

Then you need:
decoder_layer_output_1 = Backwardlayer(128,b_layer=layer_5,activation=abs,name='dl1')(layer_5_output_TENSOR)

To be honest, I don't think your approach will work. You'd need a "matrix division", not a matrix multiplication.
Maybe if you worked on finding kernel^(-1) instead of transpose, and subtracted the bias before applying it....


text:
Q: How do I make Hadoop find imported Python modules when using Python UDFs in Pig? I am using Pig (0.9.1) with UDFs written in Python. The Python scripts import modules from the standard Python library. I have been able to run the Pig scrips that call the Python UDFs successfully in local mode, but when I run on the cluster it appears Pig's generated Hadoop job is unable to find the imported modules. What needs to be done?
For example:

*

*Does python (or jython) need to be installed on each task tracker node?

*Do the python (or jython) modules need to be installed on each task tracker node?

*Do the task tracker nodes need to know how to find the modules?

*If so, how do you specify the path (via an environment variable - how is that done for the task tracker)?

A:
Does python (or jython) need to be installed on each task tracker
  node?

Yes, since it's executed in task trackers.

Do the python (or jython) modules need to be installed on each task
  tracker node?

If you are using a 3rd party module, it should be installed in task trackers as well (like geoip, etc).

Do the task tracker nodes need to know how to find the modules?
  If so, how do you specify the path (via an environment variable - how
  is that done for the task tracker)?

As an answer from the book "Programming Pig" :

register is also used to locate resources for Python UDFs that you use
  in your Pig Latin scripts. In this case you do not register a jar, but
  rather a Python script that contains your UDF. The Python script must
  be in your current directory.

And also this one is important :

A caveat, Pig does not trace dependencies inside your Python scripts
  and send the needed Python modules to your Hadoop cluster. You are
  required to make sure the modules you need reside on the task nodes in
  your cluster and that the PYTHONPATH environment variable is set on
  those nodes such that your UDFs will be able to find them for import.
  This issue has been fixed after 0.9, but as of this writing not yet
  released.

And if you are using jython :

Pig does not know where on your system the Jython interpreter is, so
  you must include jython.jar in your classpath when invoking Pig. This
  can be done by setting the PIG_CLASSPATH environment variable.

As a summary, if you are using streaming then you can use "SHIP" command in pig which would send your executable files to cluster. if you are using UDF, as long as it can be compiled(check the note about jython) and doesn't have 3rd party dependency in it (which you didn't already put in PYTHONPATH / or installed in cluster), the UDF would be shipped to cluster when executed. (As a tip, it would make your life much more easier if you put your simple UDF dependencies in the same folder with pig script when registering)
Hope these would clear things.

A: Adding
pig -Dmapred.child.env="JYTHONPATH=job.jar/Lib" script.pig

Works. Note that you could also add the following lines to your python script:
import sys
sys.path.append('./Lib')

Also note that you're still going to get numerous "module not found" warnings, but the fix works. The fact that you're getting these warnings even though the modules are inf fact found eventually was incredibly confusing for me, and I always killed the hadoop job before it returned correctly, believing this to be a symptom of the fix not actually working...

A: I encountered the same issue using Hadoop 1.2.1 and Pig 0.11.1 and found a workaround from PIG-2433, which was to add -Dmapred.child.env="JYTHONPATH=job.jar/Lib" to my Pig arguments. Example:
pig -Dmapred.child.env="JYTHONPATH=job.jar/Lib" script.pig


text:
Q: I'm having trouble passing a variable from one class function to another class function in Python I'm very new to Python and I'm probably over complicating this.  I have it working without using a class, but I'm trying to learn as much as I can about Python.  I'm trying to access a variable from one function within another function in the same class.  My code will display various items in the PyCharm console, how do I get those items into my GUI?  Here's my entire code:
# Python version 3.5.1
# pyVISA version 1.8
# Collect measurement data from an Agilent U2001A USB Power Sensor

from tkinter import *  # tkinter is for setting up a GUI
from tkinter import ttk
import visa  # Import the Python VISA module

class agilentU2001A(Frame):

    def __init__(self, master):  # Initialize the frame
        Frame.__init__(self, master)
        rm = visa.ResourceManager()
        ports = rm.list_resources()
        self.sensor = rm.open_resource(ports[0])
        print(self.sensor)
        self.grid()
        self.sensorID()
        self.createWidgets()

    def createWidgets(self):  # Create the labels and buttons
        # Create connected instrument labels
        self.label1 = Label(self, text="Connected sensor: ")
        self.label1.grid(row=0, column=0, sticky=E)
        self.instrumentLabel = Label(self, text="sensor_name")
        self.instrumentLabel.grid(row=0, column=1, sticky=W)

        # Create measurement labels
        self.label2 = Label(self, text="Measurement: ")
        self.label2.grid(row=1, column=0, sticky=E, pady=10)
        self.measurementLabel = Label(self, text="numbers")
        self.measurementLabel.grid(row=1, column=1, sticky=W, pady=10)

        # Create measurement button
        self.measureButton = ttk.Button(self, text="Take Measurement!", command=self.measurement)
        self.measureButton.grid(row=2, column=1, pady=25)

        # Create exit button
        self.exitButton = ttk.Button(self, text="Exit", command=self.exit_measurement)
        self.exitButton.grid(row=2, column=2, padx=25, pady=25)

    def sensorID(self):  # Get the ID from the connected sensor
        self.sensor.write("*IDN?")  # Query the instrument ID
        sensor_init = self.sensor.read()
        print("Sensor ID -> " + sensor_init)

    def exit_measurement(self):  # Close the VISA connection and program
        self.sensor.close()  # Close the connection
        sys.exit()

    def measurement(self):  # Take a measurement
        self.sensor.write("INIT:CONT ON")  # Initiate the trigger to continuous on
        self.sensor.write("FETC?")  # Read data using the fetch command
        measure = self.sensor.read()
        print(measure)

root = Tk()
root.title("Agilent U2001A USB Power Sensor")

app = agilentU2001A(root)

w = 485  # set width of window
h = 180  # set height of window
ws = root.winfo_screenwidth()  # get current screen width
hs = root.winfo_screenheight()  # get current screen height
x = (ws / 2) - (w / 2)  # calculate x coordinate for window
y = (hs / 2) - (h / 2)  # calculate y coordinate for window

root.geometry("%dx%d+%d+%d" % (w, h, x, y))  # center window on screen

root.mainloop()  # Constantly checks for input


text:
Q: Symfony 4 doctrine - create entity and controller for new database table I am very new to Symfony and Doctrine.
I needed to add a new table to the existing database and i would like to create the entity and controller for this new table.
Is there a command to do this for just one table?  I have tried the following command:
bin/console doctrine:mapping:convert --from-database annotation src/CRM/CRMBundle/Entity/ --force

When i run this command, all of the entities are recreated and the namespace is removed.  I am only interested in creating 1 new entity and controller for the new table.  Is this possible?  Is there a similar solution if i would like to add columns to an existing table that already has an Entity and Controller created?


text:
Q: How to convert 3GP files to MP3 with Node? I'm making a recorder app with React-Native and the audio file will be sent from the Android device to Node backend. I am able to retrieve it with Multer S3, however I want to also transform the file into an MP3 or MPEG, so that it is playable on any device. I've looked into FFMPEG, but that seems to only be a solution for videos.
What are my options here?

A: use fluent-ffmpeg to convert video to mp3 format
var ffmpeg = require('fluent-ffmpeg');

 function convertInternal(video,sampleRate,mp3path) {
      return ffmpeg(video, {
        nolog: true,
      })
        // options to convert to mp3
        .withAudioCodec('libmp3lame')
        .audioFrequency(sampleRate)
        .toFormat('mp3').saveToFile(mp3path);
    }


text:
Q: Reading USB Barcode scanner into Java Application I am trying to create an application which reads IDs of blood samples via a barcode reader. How do I read a barcode from a barcode reader into a Java Application for further processing (e.g pulling patient details from database)? Example code and explanations much appreciated.
P.S same applies to fingerprint reader, also need to be able to pull data from database based on usb fingerprint reader. how do I get fingerprint reader data into the java application for further processing?
Thanks in advance,
Tumaini

A: It really depends on the hardware you are using (i.e. The Barcode scanner) most scanners simulate keyboard input and will for example write a string of numbers + a termination character.
e.g. 1 2 9 7 6 5 [ENTER]
If your hardware does simmilar you will be able to trap this as text input in Java - no specialist coding needed.
A simple way to test what your hardware does is open up a text editor, scan a barcode - then view the output on the screen (with special characters included)


text:
Q: Grace period for changing close vote reason? First off, the new close vote retraction option is great. Thanks for that. However, I did notice that any retraction of a close-vote is final (not that this is unreasonable), and I was wondering if it would be a good idea to add the ability to change your close vote reason freely within a short time window, say 5 minutes. Sort of like a grace period for close votes.
Sometimes (and I'll admit this is a bad habit), I'll see a vote-to-close comment with a few upvotes that roughly gels with my perspective on why the question is unsuitable for the site, and I'll cast my vote too quickly.
Giving it a couple minutes more of thought though (perhaps in light of incoming comments), it often becomes clear that the close reason I originally went with is subtly incorrect. The question might be more "asks for a tool to solve a problem" than "opinion poll", or better closed as a duplicate than "must demonstrate minimal understanding". My first instinct in this situation is to just leave the wrong close vote there instead of retracting it permanently, because I feel the question cannot be reasonably answered in its current state and should be on hold, just for a different reason.
So, three questions:

*

*Is this problem faced by enough other users to even warrant such a change?

*Could this be exploited in any way?

*Is there a better way to address the problem than a grace period? (short of simply not being a dunce with your close votes, of course)

A: Today, I would have been happy for this feature to be available: I voted to close a question with "needs more focus", but then I realized the question could also be closed as a duplicate of an older one.
As a workaround, I left a comment pointing to the dupe, but I would really liked to have my close vote reason changed directly, so the system could use this information for the automatic generation of the "This question already has answers here..." message.
I actually don't think we need a specific grace period - changing the close reason could be possible for the first voters as long as the question hasn't been closed (of course, the last voter then will have not the chance to change their vote).

Is this problem faced by enough other users to even warrant such a change?

People make errors, and one of the very basic principles in building user interfaces is to allow people to correct their errors. This principle seems to be violated here blatantly.

A:
Is this problem faced by enough other users to even warrant such a
  change?

No. Not at all.

Could this be exploited in any way?

Almost anything can be exploited. However, this would only likely have more bad consequences if you're able to change your vote to close reason after the question is already closed. For example, someone could say it's a duplicate of x question, then after it's closed change it to y question, which is totally not a duplicate but one of their own questions or something, trying to get more views on it.

Is there a better way to address the problem than a grace period?
  (short of simply not being a dunce with your close votes, of course)

Refer to the first question. It's not really a problem for most people. Yes, we want to be helpful to users that ask bad questions, so that they can change their ways, but ultimately we don't need to sacrifice even more time making sure it's always the correct close reason, since the user needs to be able to help themselves and read what is on topic for the site, and what is not. There's only so much help we can give, it's up to them to improve.


text:
Q: How can I run multiple apps which that accept requests in Heroku? Is it possible to configure Heroku where one has two processes that accept HTTP requests?
I would like to run one traditional request/response process (perhaps a Django Gunicorn process), and also run a NodeJS service that provides web-sockets. It would be nice if I could configure Heroku to work to a routing pattern like this:
ws/                                         # NodeJS websocket process
*                                           # Django Process

Where any request with a URL begining with ws/ gets routed to the NodeJS websocket process, and everything else gets routed to Django.

Heroku gives an example of something similar.

https://devcenter.heroku.com/articles/realtime-polyglot-app-node-ruby-mongodb-socketio

But I really do not like this approach and will only consider it as a last resort. The issue is that the NodeJS process and the Rails process, are in separate Heroku apps. This will cause hassle when it comes to billing versioning and staging.


text: Q: Square Wave Generator Problem I was aiming to make a square wave generator which gives 16 kHz -7V,+7V square wave signal. I have used this design however i could not reach a clear square wave. I have shown the LTSpice simulation result and circuit below. If you have any idea, i will be happy. Thank you.


text:
Q: when map value type is Set, why need to re-assign if I modified the value? Here is my Swift code:
var myMap = [String: Set<String>]()

myMap["key"] = Set<String>()

var mySet = myMap["key"]

mySet?.insert("value")

//myMap["key"] = mySet

print("count:", myMap["key"]!.count)

output:
map.count: 0

but if uncomment the 5th line, will output:
map.count: 1

Why I need to assign mySet to map["key"] again? Is mySet not a reference type?

A: The swift Set type is a struct, meaning it conforms to value semantics. Types that behave with value semantics, as opposed to reference semantics, are always copied when attaining a reference to them, you can never reference the same value type from two different references. In your case, this means that var mySet = myMap["key"] creates a copy of the set in your map, not a reference to the set in your map. This means that you have to reassign the modified set back into the map for the change to reflect there.
Check out this swift blog entry from Apple explaining value semantics: https://developer.apple.com/swift/blog/?id=10
Edit: As Nate noted in the comments, Swift doesn't actually create a new copy until the value type is modified, allowing the runtime to share references to value types as long as they aren't mutated, which is a nice optimization.


text:
Q: Android - Convert a date to the date format of the device How do you convert a date to the date format of the device? For example, I have following date: 02/11/2011 (mm/dd/yyyy). How to convert it to the format of the device?

A: You might want to consider storing your dates in a more locale-agnostic way as milliseconds.
Then you can use DateFormat.getDateFormat() like this:
dateTextView.setText(DateFormat.getDateFormat(getActivity()).format(new Date(millis)));

According to the documentation for getDateFormat():

Returns a DateFormat object that can format the date in short form (such as 12/31/1999) according to the current locale and the user's date-order preference.

A: DateFormat has the static methods getDateTimeInstance, getTimeInstance and getDateInstance that are already localized

A: Use SimpleDateFormat to convert a Date into required format.
See this link for more details..
SimpleDateFormat format = new SimpleDateFormat("dd/MM/yyyy");
String formattedDate = format.format(yourdate);


text:
Q: Normal order vs Time order for fermions For a conformal field $X$, Polchinski gives a relation between the time ordering $T$ (or equivalently the radial ordering ${\cal R}$) of a functional of identical fields and the normal ordering, which is
$$
T(\mathscr{F}) ~=~ \exp\left(\frac{1}{2}\int d^2z_1d^2z_2 \Delta(z_1,z_2)\frac{\delta}{\delta X(z_1)}\frac{\delta}{\delta X(z_2)}\right) :\mathscr{F}: \tag{2.2.8}
$$
Is there a similar expression for time order products of different fields, i.e. a fermion pair $\overline{\psi}(x)\psi(y)$?

A: Sure, the generalization to several fields $(\hat{A}_i)_{i\in I}$ is
$$T(f(\hat{A})) ~=~ \exp\left(\frac{1}{2}\sum_{i,j\in I}\hat{C}_{ij}\frac{\partial}{\partial\hat{A}_j}\frac{\partial}{\partial\hat{A}_i} \right):f(\hat{A}):$$ where we have used DeWitt's condensed notation. We stress that for Grassmann-odd fields, it is important to pay attention to sign factors. See my Phys.SE answer here for notation & details.


text:
Q: Using CodingKeys enum in Swift 4.0 to ignore UIImage properties I have the following struct. The first 3 properties are decoded from JSON, and the 4th property is to use as a cache if the image is ever downloaded.
import UIKit

struct Thumbnail: Codable {
    let url: String
    let width: UInt
    let height: UInt

    var image: UIImage?

    enum CodingKeys: String, CodingKey {
        case url
        case width
        case height
    }
}

When I try to compile Xcode tells me that Thumbnail doesn't conform to the Decodable protocol. I get that UIImage doesn't conform to Codable, but as I understand it using the CodingKeys enum should ignore image from the protocol? Any advise would be much appreciated :)


text:
Q: Haml::SyntaxError - Illegal nesting: content can't be both given on the same line as %a and nested within it I'm using "Button dropdowns" from Twitter Bootstrap with HAML.  In the Bootstrap docs I have found the example:

    Action

I have tried rewrite it using HAML:
%div{:class => 'btn-group task_controller'}
  %a{:class => 'btn-mini dropdown-toggle', "data-toggle" => 'dropdown', :href => '#'} Action
    %span{:class => 'caret'}
  %ul{:class => 'dropdown-menu'}
    %a{:class => 'close_task', :name => task.name, :href => '#' } Close

But got the error message:
Haml::SyntaxError - Illegal nesting: content can't be both given on the same line as %a and nested within it.

So Bootstrap said me put the  element inside -tag, but HAML didn't allow to do it.  How can I fix the problem?

A: Don't forget your Haml idioms!
#div{:class => 'btn-group task_controller'}

is equivalent to:
.btn-group.task_controller

…etc.

A: The problem is in these lines:
%a{:class => 'btn-mini dropdown-toggle', "data-toggle" => 'dropdown', :href => '#'} Action
  %span{:class => 'caret'}

The error message: content can't be both given on the same line as %a and nested within it refers to Action which is content "on the same line as %a", and %span{:class => 'caret'}, which is content "nested within it".
More generally, and perhaps easier to see, you can't have something like this:
%tag Some content here
  And something here as well

The fix is to nest both under the %a:
%a{:class => 'btn-mini dropdown-toggle', "data-toggle" => 'dropdown', :href => '#'}
  Action
  %span{:class => 'caret'}

This gives the desired output:

  Action

A: Try this:
%div{:class => 'btn-group task_controller'}
  %a{:class => 'btn-mini dropdown-toggle', "data-toggle" => 'dropdown', :href => '#'}
    Action
    %span{:class => 'caret'}
  %ul{:class => 'dropdown-menu'}
    %a{:class => 'close_task', :name => task.name, :href => '#' } Close

Tag name and content can be on the same line only when there are no more content lines in the tag.


text:
Q: how to count the requeue attempts RABBITMQ - nodejs Everytime there's an error when consuming a message from the queue, i requeue it 5 times. Nowadays I have the requeueing-limit done with conditionals, but i wanna append it to the headers in some way or use the "x-retries" header. I've been trying for a while, I also tried doing an DXL exchange, but the headers always seem to be undefined.
This is my code:
const rabbitMQ= async () => {
  try {
    const connection = await amqp.connect(amqpUrl);
    const channel = await connection.createChannel();
    await channel.assertQueue(queue, { durable: true });

    channel.prefetch(1);

    console.log(` [*] Waiting for messages in ${queue}`);
    channel.consume(queue, consumeMessage(channel), { noAck: false });
  } catch (error) {
    console.error(`Error: ${error}`);
  }
};

let retries = 0;

const consumeMessage = (channel) => async (msg) => {

  try {

    const payload = msg.content.toString();
    console.log(payload)

  } catch (error) {

    console.error(`Error: ${error}`);

    if(retries < 5){
      channel.reject(msg,true)
      retries++;
      console.log(`Requeuing: ${retries}/5`)
    }
    else{
      console.log(`The message was discarded because it reached the requeuing limit`)
      channel.reject(msg,false)
      retries = 0;
    }
  }
};

Could someone give me a hand here?


text:
Q: Encoding and decoding uint8_t using TinyCbor C Library I am implementing C++ 11 based application and I am using TinyCbor C library for Encoding and Decoding application specific data as below:
#include "cbor.h"
#include <iostream>

using namespace std;

int main() {

    struct MyTest {
        uint8_t varA;
        float vabB;
    };

    MyTest obj;
    obj.varA = 100; // If I set it t0 below 20 then it works
    obj.varB = 10.10;

    uint8_t buff[100];

    //Encode
    CborEncode encoder;
    CborEncode array;
    cbor_encoder_init(&encoder, buff, sizeof(buff), 0);

    cbor_encoder_create_array(&encode, &array, CborIndefiniteLength);
    cbor_encode_simple_value(&array, obj.varA);
    cbor_encode_float(&array, obj.varB);
    cbor_encoder_close_container(&encoder, &array);

    // Decode
    CborParser parse;
    CborValue value;
    cbor_parser_init(buff, sizeof(buff), 0, &parser, &value);

    CborValue array;
    cbor_value_enter_container(&value, &array);

    uint8_t val;
    cbor_value_get_simple_type(&array, &val);
    // This prints blank
    cout << "uint8_t value: " << static_cast<int>(val) << endl;

    float fval;
    cbor_value_get_simple_type(&array, &fval);
    cout << "float value: " << fval << endl;

    return 0;
}

Above code works when I set value of uint8_t varA to below 20, I see 20 getting printed on console but if I set more than 20 then sometimes it gives error CborErrorIllegalSimpleType. Or if value is set to 21 then it returns me type as CborBooleanType or CborNullType.

*

*What is wrong with the code

*How to encode and decode uint8_t using TinyCbor.

A: You have a few things going on here.

cbor_encoder_create_array(&encode, &array, CborIndefiniteLength);

Don't use indefinite length unless you plan on streaming the encoding. If you have all the data in front of you when encoring, use defined length. See why here: Serialize fixed size Map to CBOR  also, and I'm not sure what version you are using but indefinite length objects were at least fairly recently a TO DO list item for TinyCBOR.

cbor_value_get_simple_type(&array, &val);

You don't need simple here. Simple types are primatives that are mostly undefined. CBOR's default type is int64_t, signed long long. Simple does allow for a natural stop at 8bit, but 20 in simple is Boolean false. 21 true , 22 null. You discovered this already. It can't store a negative, or float, and while you could use it to represent an 8bit like "100", you really shouldn't. The good news about CBOR's types is that while the default is 64bit, it uses as little memory to encode as needed. So storing 100 in CBOR is one byte, not 8, not counting the overhead for a second. EDIT: Clarification, 2 bytes to store integer 100. CBOR is one byte for 0-23, but 24 and one has a byte of overhead.
By overhead I mean, when you encode a cbor integer, the first three bits mean UNSIGNED INTEGER (binary 000), one bit is reserved, the other 4 bits are value, so if you had a small value that fit in those four bits (value 0-23) you can get it all in one byte. That reserved bit is weird, see the chart here to understand it: https://en.m.wikipedia.org/wiki/CBOR So 24-255 requires 2 bytes encoded, etc etc. A far cry from it always using 8bytes just because it can.
The short version here is that CBOR won't use more space than needed - BUT - it's not a strongly typed serializer! If you mean for 100 inside 8bits to be stored in that array and someone stores a 10000 to be with 16bits, it'll look/work fine until you go to parse and store a large number in an 8bit spot. You need to cast or validate your data. I recommend parse THEN validate.

cbor_value_get_simple_type(&array, &fval);
cout << "float value: " << fval << endl;

I'd have to look in TinyCBOR's code, but I think this is a happy accident and not technically supported to work. Because simple types use the same three major bits you are able to get the value's 64bit precision with get_simple. You should instead examine the type and make the correct call for get full or half precision float.
TinyCBOR is pretty nice, but there are definitely a couple gotchas hidden. It really helps to undersnd the CBOR encoding even though you are trusting the serializer to do the work for you.

A: Use CborError cbor_encode_uint(CborEncoder *encoder, uint64_t value) instead. This function will encode an unsigned integer value with the smallest representation.


text:
Q: Ethernet works with Windows Vista Ultimate, but not in Ubuntu 14.04 When I installed ubuntu 14.04 my ethernet is not connecting. Anyone can help me , please ?
NetworkManager Tool
State: disconnected
Device: eth0
Type: Wired
Driver: r8169
State: unavailable
Default: no
HW Address: 00:24:1D:13:3D:08
Capabilities:
Carrier Detect: yes
Wired Properties Carrier: off


text:
Q: phpMyAdmin doesn't show table list for database that definitely has tables I have a website, written in php, using a MySQL database. After buying a new laptop (Windows 7), I downloaded WAMP 2.2, with MySQL 5.5.20, PHP 5.3.10 and phpMyAdmin 3.4.10.1. I exported the whole database from the live website and imported it into my wamp environment, using MySQL console.
phpMyAdmin lists the database, but says there are no tables in it. Yet, the websites workss within the WAMP environment. Further, if I perform an SQL "SHOW TABLES" within phpMyAdmin, it displays the tables.
I'm completely puzzled as to why these tables aren't listed in the leftmost column of phpMyAdmin.

A: I was having a similar problem. Through some digging I found that phpMyAdmin's table list was failing on this query:
SHOW TABLE STATUS FROM `database`;

And this was the error message:
ERROR 1143 (42000): SELECT command denied to user ''@'localhost'
 for column `column` in table `table`

Which led me to this SO question: mysql forgets who is logged in: command denied to user ''@'%'
Which led me to the conclusion that one of the views that I loaded into the database has privileges that are conflicting. Indeed, when I looked at the SQL dump I was loading the database from, I found the culprit:
CREATE ALGORITHM=UNDEFINED DEFINER=`someotheruser`@`localhost` ..

Where someotheruser did not exist in my local MySQL. I changed it to the following:
CREATE ALGORITHM=UNDEFINED DEFINER=`root`@`localhost` ..

And reloaded the view, and everything is now working properly.

A: The problem is with Definer if you have any view in the database.
Just drop the Views and it should work, or you can open the exported database file in Notepad and change Definer to root.

A: Just to help someone else, in the phpMyAdmin, in config.inc.php, change this:
$cfg['Servers'][$i]['extension'] = '**mysqli**';

to this:
$cfg['Servers'][$i]['extension'] = '**mysql**';


text:
Q: What is the alternative function in HarmonyOS for onMeasure in Android OS? I am writing a custom component in HarmonyOS using Java SDK.
In order to negotiate the width and height of the custom view in Android, we override onMeasure().
@Override
protected void onMeasure(int widthMeasureSpec, int heightMeasureSpec) {}

What is the alternative for the above in HarmonyOS?

A: In Android - onMeasure() is a protected method available in View class so one can directly override it in custom component by extending the View class.
For alternative in HarmonyOS - you will have to implement Component.EstimateSizeListener in your custom component and then write down the implementation in overriden function onEstimateSize.
So in Android, when you have some code like this -
public class CustomView extends View {

   public CustomView(Context context, AttributeSet attrs, int defStyle) {
        super(context, attrs, defStyle);
   }

   @Override
   protected void onMeasure(int widthMeasureSpec, int heightMeasureSpec) {
   }
}

Harmony Code changes will be -
public class CustomComponent implements ComponentContainer.EstimateSizeListener

public CustomComponent(Context context, AttrSet attrSet, String styleName) {
       super(context, attrSet, styleName);
       setEstimateSizeListener(this); //set the listener here
   }

   @Override
   public boolean onEstimateSize(int widthEstimatedConfig, int heightEstimatedConfig) {
   }
}