text:
Q: Unable to get user hometown and location from Facebook graph API I am trying to get user hometown and location using Facebook graph API for the logged-in user
Public permissions to fetch location and hometown is granted by the user.
Graph API version v2.8
/me?fields=name,picture,location,hometown

A: You need to ask for permissions: user_hometown and user_location. The hometown/location is not included in the public permissions.
You can also check the scope of your access token here

A: Here is how you can get the complete user profile using FB token:
I am assuming you have given permission before getting token from graph api explore which is:
https://developers.facebook.com/tools/explorer/

public Profile GetProfile(string facebookID)
        {
            var url = "?fields=first_name,last_name,name,age_range,birthday, education, gender, hometown, locale, location, third_party_id, timezone, email";

            dynamic result = _facebookClient.Get(facebookID + url);

            var profile = new Profile();

            if (result != null)
            {
                string resultStringify = result.ToString();
                var resultBlock = JObject.Parse(resultStringify);

                //if (result.ToString().Contains("first_name")) {
                //    profile.First_Name = resultBlock["first_name"].ToString();
                //}
                profile.First_Name = resultStringify.ExtractIfValueIsAvailable("first_name", resultBlock);
                //if (result.ToString().Contains("last_name")) {
                //    profile.Last_Name = resultBlock["last_name"].ToString();
                //}
                profile.Last_Name = resultStringify.ExtractIfValueIsAvailable("last_name", resultBlock);
                //if (result.ToString().Contains("name")) {
                //    profile.Name = resultBlock["name"].ToString();
                //}
                profile.Name = resultStringify.ExtractIfValueIsAvailable("name", resultBlock);

                if (result.ToString().Contains("age_range"))
                {
                    if (result.age_range.min != null) profile.Age_Range_Min = result.age_range.min;
                    if (result.age_range.max != null) profile.Age_Range_Max = result.age_range.max;
                }

                //if (result.ToString().Contains("birthday")) {
                //    profile.Birthday = DateTime.ParseExact(result.birthday, "MM/dd/yyyy", CultureInfo.InvariantCulture);
                //}
                profile.Birthday = resultStringify.ExtractIfDateTime("birthday", resultBlock);
                //if (result.ToString().Contains("gender")) {
                //    profile.Gender = resultBlock["gender"].ToString();
                //}
                profile.Gender = resultStringify.ExtractIfValueIsAvailable("gender", resultBlock);
                //if (result.ToString().Contains("hometown")) {
                //    profile.Hometown = resultBlock["hometown"]["name"].ToString();
                //}
                profile.Hometown = resultStringify.ExtractIfNameValueIsAvailable("hometown", resultBlock);
                //if (result.ToString().Contains("locale")) {
                //    profile.Locale = resultBlock["locale"].ToString();
                //}
                profile.Locale = resultStringify.ExtractIfValueIsAvailable("locale", resultBlock);
                //if (result.ToString().Contains("location")) {
                //    profile.Location = resultBlock["location"]["name"].ToString();
                //}
                profile.Location = resultStringify.ExtractIfNameValueIsAvailable("location", resultBlock);
                //if (result.ToString().Contains("third_party_id")) {
                //    profile.Third_Party_ID = resultBlock["third_party_id"].ToString();
                //}

                profile.Third_Party_ID = resultStringify.ExtractIfValueIsAvailable("third_party_id", resultBlock);

                profile.Timezone = resultStringify.ExtractIfValueIsAvailable("timezone", resultBlock);

                profile.EMail = resultStringify.ExtractIfValueIsAvailable("email", resultBlock);

            }

            return profile;
        }

public static string ExtractIfValueIsAvailable(this string result, string fieldName, dynamic resultBlock) => result.Contains(fieldName) ? resultBlock[fieldName].ToString() : string.Empty;

Hope it helps.


text:
Q: Javascript flood fill algorithm getting caught in an infinite loop Hello I am trying to implement a simple flood fill type algorithm in javascript. Basically I have a 3x3 board which I represent as a 1 dimensional array. I want to append the index for every equal value that is "touching" to a separate array. So for instance this board:
[1][1][0]
[3][1][3]
[0][0][0]
Would be represented as a 1D array ie [1,1,0,3,1,3,0,0,0]. And after running the floodFill on one of the [1] it would result with an array that looks like this [4, 1, 0] because those are the indexes in the 1d array that are touching, which have the same value.
Here is the code:
var boardArray = new Array(1,1,0,3,1,3,0,0,0);
var comboArray = new Array();
function floodFill(n, diceVal) {
    if(boardArray[n] != diceVal) {
        return;
    }
    comboArray.push(n);

    if (n >0 && n < 8) {
    // right
    if(!(n%3==2)) {
        floodFill(n+1, diceVal);
    }

    // left
    if(!(n%3==0)) {
        floodFill(n-1, diceVal);
    }

    // up
    if(n>2) {
        floodFill(n-3, diceVal);
    }

    // down
    if(n<5) {
        floodFill(n+3, diceVal);
    }
    } else {
        return;
    }
}
floodFill(4,1);

Can anyone tell me why this is getting stuck in an infinite loop?

A: In your "up" case, the first time through, you'll call floodFill(1,1);. That call, in its "down" case, will call floodFill(4,1);, which will soon call floodFill(1,1)
You're already keeping track of the matching squares - the only ones that will really cause any trouble. Just confirm that you're not checking the same square again:
function floodFill(n, diceVal) {
  if(boardArray[n] != diceVal) {
    return;
  }

  // have we been here before?
  if (comboArray.indexOf(n) >= 0)
    return;

  comboArray.push(n);

  // ...
}

redpajama_set_name: RedPajamaStackExchange


text:
Q: How do we compare ASLR across different Operating Systems? Address space layout randomization (ASLR) is a computer security technique which involves randomly arranging the positions of key data areas, usually including the base of the executable and position of libraries, heap, and stack, in a process's address space.
This is the description from Wikipedia.
Is it fair to estimate effectiveness of ASLR in two different OS by estimating the "randomness" of the positions of the key data areas?
Are there any other measurable factors by which we can compare ASLR effectiveness?
Any tips on how to proceed?

A: I can think of several parameters that ASLR can implement in different degrees.
The variance of address randomization
The spatial "stickiness" of this randomization - how long do the address remain fixed
The temporal "stickiness" of this randomization - in how many objects e.g. processes does the address stay the same
The performance penalty during exe load
The runtime performance penality
The degree to which it break legacy coding practices (how ever bad they maybe)
It reliance on hardware features (memory protection, virtual memory)
The "wastage" of virtual address space
A requirement for recompilation of kernel or lack there of
A requirement for recompilation of other system support modules


text: Q: Multivariate regression with a mix of ordinal and continuous dependent variables I would like to run a multivariate mixed regression MCMC model with two response (independent) variables, namely x and y. x is continuous while y is ordinal. There is one predictor variable that is continuous and one random effect. I would much appreciate if someone lets me know how to do this, and which package to use, preferably in R. Thank you very much in advance!


text:
Q: Correct schema for multiple one to many relationships? I'm trying to figure out how to properly create several one-to-many relationships for one row in the database.
Say I have a product table.
CREATE TABLE `product` (
`productID` int(11) NOT NULL AUTO_INCREMENT,
`productName` varchar(45) NOT NULL,
PRIMARY KEY (`productID`)
) ENGINE=InnoDB DEFAULT CHARSET=utf8

The product can have a one-to-one category relationship or one-to-many.
CREATE TABLE `category` (
`categoryID` int(11) NOT NULL AUTO_INCREMENT,
`categoryName` varchar(45) NOT NULL,
PRIMARY KEY (`categoryID`)
) ENGINE=InnoDB DEFAULT CHARSET=utf8

I've created a lookup table with foreign keys, but I don't think it's going to work because there can be products which are associated with various different category groups.
CREATE TABLE `category_to_product` (
`categoryID` int(11) NOT NULL,
`productID` int(11) NOT NULL,
KEY `categoryID` (`categoryID`),
KEY `productID` (`productID`),
CONSTRAINT `category_to_product_ibfk_2` FOREIGN KEY (`productID`)
REFERENCES `product` (`productID`) ON DELETE CASCADE ON UPDATE CASCADE,
CONSTRAINT `category_to_product_ibfk_1` FOREIGN KEY (`categoryID`)
REFERENCES `category` (`categoryID`) ON DELETE CASCADE ON UPDATE CASCADE
) ENGINE=InnoDB DEFAULT CHARSET=utf8

EDIT

The queries in my database are based on levels and each higher level of query is dependent on the previous level. level 1 would be a base level query, and would contain the most general information, lets say this category is electronics.
The level 2 query, would be a slightly more refined query and would be a sub-category of electronics so something like electronics->televisions. Think of it as a breadcrumb. This seems difficult in itself to do, but in this case, the product needs to be able to relate to several different category groups which can contain the same level or different levels. I hope this makes sense.

How would I structure my database for this type of relationship? Initially I had the category levels separated under different columns in the lookup table, which worked nicely but there were too many NULL values.

A: Your example dictates a third table, but first you need to add a primary key to your category_to_product_table(* id int(11) NOT NULL AUTO_INCREMENT)
Third table for the groups:
CREATE TABLE category_to_product_groups (
id int(11) NOT NULL AUTO_INCREMENT,
categoryProductGroupName varchar(40),
category_to_product_id int(11) NOT NULL,
) ENGINE=InnoDB DEFAULT CHARSET=utf8
This third table will have multiple rows per group names(and a group could simply be one or more category_to_product rows).

A: Your approach is very generic. A product doesn't have any fixed attribute in your model (except its name), but has a set of optional associated attributes. So there can be trousers of unknown color and material. Or a computer made of cotton and trousers made of tin. An Xbox mirror with twenty colors and a bike that is both leightweight and heavyweight.
You don't even see that red and green are colors and plastic and metal are materials.
So you must start from scratch: What do you actually need? Aren't there product groups like "computer" and "washing machine"? Then each group could have mandatory attributes like cpu for a computer and energy class for a washing machine, and optional attributes like the color maybe, which can be given but is not considered necessary, or like screen for the computer, which it may have or not. Then each product would belong to a product group and you'd know what attributes can or must be entered for it (and by which attributes you can filter certain products).
Then think about what attributes you have:

*

*cpu = Intel i5| Intel i7|AMD FX = a list of possible values for the one cpu

*color = white | black | ... = also a list, but there can be more than one color per product

*mouse = yes | no = a boolean flag

*modelno = ____ = free text attributes

And then think of an appropriate table design for these.
If you even want hierarchic attributes like color = luminous bright orange => bright orange => orange (so one can search for all orange products or just light orange products or even just luminous bright orange products), then you need some structure for that, too. But then: Shouldn't one be able to also look for luminous orange products, as well, or for any light color products? Then this would no longer be a hierarchic tree.
As you see this all can become quite complicated. Think about what you really need. Make it as complicated as needed, but only as complicated as that.


text:
Q: Evaluation of $\int \frac{\sqrt{1+x^4}}{1-x^4}dx$ Evaluation of $\displaystyle \int \frac{\sqrt{1+x^4}}{1-x^4}dx$
$\bf{My\; Try::}$ Given $\displaystyle \int\frac{\sqrt{1+x^4}}{1-x^4}dx\;,$ Then  We can write the above Integral as $$\displaystyle \int\frac{\left(1+x^4\right)}{\left(1-x^4\right)\sqrt{1+x^4}}dx = \frac{1}{2}\int\left\{\frac{1}{1-x^2}+\frac{1}{1+x^2}\right\}\cdot \frac{(1+x^4)}{\sqrt{1+x^4}}dx$$
So Integral is $$\displaystyle = \frac{1}{2}\int\frac{1+x^4}{(1-x^2)\sqrt{1+x^4}}dx+\frac{1}{2}\int\frac{1+x^4}{(1+x^2)\sqrt{1+x^4}}dx$$
Now Let $$\displaystyle I = \int\frac{1+x^4}{(1-x^2)\sqrt{1+x^4}}dx$$ and $$\displaystyle J = \int\frac{1+x^4}{(1+x^2)\sqrt{1+x^4}}dx$$
Now How can I evaluate $I$ and $J\;,$ plz help me
Thanks

A: We can write the integral as
$$
I=\int\frac{\sqrt{1+x^4}}{1-x^4}\textrm{d}x=\int\frac{\left(1+x^4\right)}{\left(1-x^4\right)\sqrt{1+x^4}}\textrm{d}x.
$$
Let $t=\frac{1+x^4}{1-x^4}$ so that $x^4=\frac{t+1}{t-1}$ and $\textrm{d}x=\pm\left(\frac{t+1}{t-1}\right)^{\frac{1}{4}}\cdot\frac{-1}{2(t-1)(t+1)}\textrm{d}t$.
The integral above becomes
$$
\pm \int t\left(\frac{t-1}{2t}\right)^{\frac{1}{2}}\left(\frac{t+1}{t-1}\right)^{\frac{1}{4}}\frac{-1}{2(t-1)(t+1)}\textrm{d}t=\mp\frac{1}{2\sqrt 2}\int t (t^2-1)^{-3/4}\textrm{d}t
$$
where the last integral is
$$
\int t (t^2-1)^{-3/4}\textrm{d}t
=2\sqrt[4]{t^2-1}+\text{constant}.$$

A: Thanks  Claude Leibovici and Lucian, Using Lucian Hint.
$\bf{Another \; Try::}$ Let $\displaystyle \mathcal{I} = \int \frac{\sqrt{1+x^4}}{1-x^4}dx\;,$ Now Let $x^2=\tan \phi\;,$
Then $\displaystyle 2xdx = \sec^2 \phi d\phi \Rightarrow dx = \frac{\sec^2 \phi}{2\sqrt{\tan \phi}}d\phi$.
So $$\displaystyle \mathcal{I} = \int\frac{\sec \phi}{1-\tan^2 \phi}\times \frac{\sec^2 \phi}{2\sqrt{\tan \phi}}d\phi = \frac{1}{2}\int \frac{\sec \phi}{\cos 2\phi}\times \frac{1}{\sqrt{\tan \phi}}d\phi = \frac{\sqrt{2}}{2}\int\frac{1}{\cos 2\phi\cdot \sqrt{\sin 2\phi}}d\phi$$
So $$\displaystyle \mathcal{I} = \frac{1}{2}\int\frac{\cos 2\phi}{\left(1-\sin^2 2\phi\right)\cdot \sqrt{\sin 2\phi}}d\phi$$
Now Let $\displaystyle \sin 2\phi = t^2\;,$ Then $\displaystyle \cos 2\phi d\phi = 2tdt$.
So $$\displaystyle \mathcal{I} = \frac{1}{2}\int\frac{1}{1-t^4}dt = \frac{1}{4}\int \left(\frac{1}{1-t^2}+\frac{1}{1+t^2}\right)dt = \frac{1}{4}\cdot \frac{1}{2}\ln \left|\frac{1+t}{1-t}\right|+\frac{1}{4}\tan^{-1}(t)+\mathcal{C}$$
So $$\displaystyle \mathcal{I} = \frac{1}{4}\cdot \frac{1}{2}\ln \left|\frac{1+\sqrt{\sin 2\phi}}{1-\sqrt{\sin 2\phi}}\right|+\frac{1}{4}\tan^{-1}(\sqrt{\sin 2\phi})+\mathcal{C}$$
Where $\phi = \tan^{-1}(x^2).$


text:
Q: SSL and mixed content due to CSS background images I have a web page containing am entry form. HTTPS is enabled via an Apache redirect for all requests matching that page. Unfortunately, because the CSS pulls in external images using  'background-image: url(/images/...)', the browser will generate a warning message that the page contains mixed content.
What's the best way to resolve this issue?

A: You should also enable HTTPS for your static resources, and then make sure that the <link> refers explicitly to the HTTPS url for the CSS resource (whose relative urls will then be interpreted relative to the HTTPS base of the CSS file).

A:
Update 2014.12.17:
Now that SSL is encouraged for everyone and doesn't have performance
  concerns, this technique is now an anti-pattern. If the asset you > need is available on SSL, then always use the https:// asset.
Allowing the snippet to request over HTTP opens the door for attacks
  like the recent Github Man-on-the-side attack. It's always safe to
  request HTTPS assets even if your site is on HTTP, however the reverse
  is not true.
More guidance and details in Eric Mills' guide to CDNs & HTTPS.

Source: Paul Irish – The Protocol-relative URL

Here is a very popular solution:
There's this little trick you can get away with that'll save you some headaches:
In HTML
<img src="//domain.com/img/logo.png">

In CSS
div{background: url(//path/to/image.png);}

A: You should use full URL for your image:
https://your.domain.com/img/image.png`

or
https://your.domain.com/route/to/img/image.png

This solved my problem some time ago.


text:
Q: Does the Unity WebGL exporter work? Has the Unity WebGL exporter improved in the last year? Thinking about using it for a project but the last time I checked it wasn't fit for purpose..huge file sizes and bugs with different browsers...

A: I just finished porting my mobile game to WebGL using Unity 2017.1. It has stabilized quite a bit and I found no major issues using it. The biggest annoyance was the long compilation times.

A: I've found it to be quite good now in 2017.1. It compresses things pretty nicely and load times are not too bad. If you want to see some examples of different games exported to WebGL, I have a site up called SIMMER.io to host these games. Most uploads were created in Unity 2017.1.

There's also a WebGL compressor asset available here, but I have not tried it: https://www.assetstore.unity3d.com/en/#!/content/30335


text:
Q: Screen resolution detector putting browser in endless refresh state - WHY? I've been working on a landing page for my company (http://apptest.wgsdac.org/ctc_parts).  I'm using a javascript code to detect the my users' screen resolution and automatically redirect accordingly.  Here's the code:
<script type="text/javascript">
if (screen.width>1279){
 window.location="index.html";
}
else
{
 window.location="index_1024.html";
}
</script>

The problem is that when the page loads and the first condition is evaluated and satisfied the code works fine.  So I change my screen's resolution in order to trigger the second condition - upon refreshing the page the browser goes into a continuous refreshing loop.
Is there something wrong with the code, or am I doing it wrong?  Your help would be appreciated.
Thanks.

A: Because it loading the same page with that code on it and keeps saying, yep I am in that range and loads it.
Why have two separate pages? Use css3 media queries to have different styles based on different widths


text:
Q: Query records through its belongs_to relation in Rails 4 I'm hoping for a little clarification on the correct way of querying records through its belongs_to relation in Rails 4.
I would like to find all parts that have a specific category name.
I can make it work with category ID using: Part.where(category_id: "1")
But I can't get it to take with the name.
If I do this:
Part.joins(:categories).where("categories.name = 'cars'").first

I get back this error:

ActiveRecord::ConfigurationError: Association named 'categories' was not found on Part; perhaps you misspelled it?

I don't see where I misspelled anything and I can't figure out why it's not working. Any help would be greatly appreciated!
Category Model:
class Category < ActiveRecord::Base
  has_many :parts
end

Parts Model:
class Part < ActiveRecord::Base
  belongs_to :category
end

Category Table:
CREATE TABLE categories
(
  id serial NOT NULL,
  name character varying(255),
  CONSTRAINT categories_pkey PRIMARY KEY (id)
)

Parts Table:
CREATE TABLE parts
(
  id serial NOT NULL,
  category_id integer,
  CONSTRAINT parts_pkey PRIMARY KEY (id)
)

A: Your belongs_to association name is singular (which is correct, as it the standard) in the Part model, but you tried to join using the pluralized association name (you tried :categories). A common mistake; you probably got mixed up between the database naming convention, and the rails association naming convention. Try instead this:
Part.joins(:category).where('categories.name = "cars"').first

Side note:
This is not related to the question, but in case you did not already know, you can use a hash in the where clause if you like as well. It would look like:
where(categories: {name: "cars"})

And the result would be the same. In your case, it is not relevant since you're clearly passing a literal string, but it may come in handy when you're using form data, or something equally non-secure, since the hash method will properly treat the parameter as text, rather than dangerously placing it in the query as-is.

A: Use: Part.joins(:category)
The association name you pass to joins should mimic your declaration of it: belongs_to :category. Here you use :category, so give joins the same symbol.


text:
Q: Scala: what if I used class instead of object for an Enumeration? Would anything bad happen if I wrote:
class TaskType extends Enumeration {
  type TaskType = Value
  val LINEAR_REGRESSION, POISSON_REGRESSION, LOGISTIC_REGRESSION, SMOOTHED_HINGE_LOSS_LINEAR_SVM, NONE = Value
};

The IDE and compiler seem fine with it. It gets me out of some import TaskType._ which I have to insert if TaskType is an object rather than a class.

A: It defeats the purpose of having an enumeration as a set of unique stable identifiers.
To use members of a class, we need an instance. The members of each instance will be different. In practical terms, LINEAR_REGRESSION instantiated in some part of the system will not be the same as a LINEAR_REGRESSION instantiated somewhere else.
eg.:
class TaskType extends Enumeration {
  type TaskType = Value
  val LINEAR_REGRESSION, POISSON_REGRESSION, LOGISTIC_REGRESSION, SMOOTHED_HINGE_LOSS_LINEAR_SVM, NONE = Value
}
val instance = new TaskType
val otherInstance = new TaskType

import instance._

val lr = LINEAR_REGRESSION

val lr2 = otherInstance.LINEAR_REGRESSION

lr == lr2
// false


text:
Q: why is flex start in child is not working i want to make it 100% of its parent? how to apply display flex to make it full width. I am getting full length of parent div

        Task Total Budget:
        $940.00

here is CSS code
.tb-additonoltitle .tb-startingprice {
    align-items: flex-start;
}

A: .tb-startingprice {
    width:100%
    display:flex;
    align-items: flex-start;
}

please remove .tb-additonoltitle class .


text:
Q: BizTalk Send Port OutOfMemory Exception I have a BizTalk solution deployed at a customer site.
(BizTalk 2006 R2 with the non WCF adapters)
One of the orchestrations issues an RFC call to a SAP system and returns a big message.
The message is mapped to a SQL Adapter Send Port schema which is calling a stored procedure.
Recently I'm running into a OutOfMemory exception when the message is sent to the SQL Adapter.
I did a trace with SQL profiler which resulted in a 90MB+ tracefile for just a few seconds.
As I imagined, the Stored Procedure is executed rapidly one after another.
But even this does not explain why I get the error message. The Server has 32GB RAM and I can't even see it peaking out...
Any suggestions what else I could check?

A: Have you looked at how much memory the host of the Send Port is configured to use? 32GB of memory is irrelevant if the host is not set to take advantage of it. That being said, I think the default is 25% of the available memory. So barring any change this may not be the problem.
You could also try playing with the throttling settings for the host. Although I have never had much luck with it myself.
One way to get more information is to hook up Perfmon and look at the memory around that specific host process.


text:
Q: File storage for Java based web application I'm in the processing of designing a Java based web application (Spring based to be specific). One of the key requirement is that, this application has to accept many files of various formats (pdf, jpeg, dwg, png etc.) uploaded by the user. Also, to be able to download back to user's local computer. There will be thousands of files being uploaded/downloaded.
I am thinking of two approaches:

*

*Upload the documents to the same box where server is running. Mostly all the documents will be uploaded to, and downloaded from box where Tomcat is running. I'm worried that, as the documents grow in number, this may impact overall performance.

*Upload/download documents to another server dedicated for storing/retrieving of documents.
If 2nd approach is taken, how Spring application can upload/download files to/from remote server? Or which approach is being used in the similar applications.
Or could you suggest any other optimal way of handling this requirement.
Thanks in advance.
Ganesh

A: Many modern applications built like this are going to use an external storage system like Amazon S3 to store these files, which buys you all kinds of nice features - high availability for downloads, an effectively unlimited pool of disk space, data replication, and so on.
There's a tutorial available for integrating spring with Amazon S3.  You should check that out.  Regardless of whether you choose S3 or something else, the approach will be similar.

A: Have you thought about using a DB. You could store those files as BLOBs. Here is a tutorial for this: link
"This tutorial walks you through the steps of building an interesting Spring MVC web application that allows the user to upload files from her computer to the server. The files are stored in database using Hibernate."
As to two approaches you consider:
Either way you will have to manage those files, back them up and check if there is enough space to store more files. Also this may cause some security issues as you accept all files.

A: I recommend you using a JCR like Apache Sling or Apache Jackrabbit.
Apache Sling™ is a framework for RESTful web-applications based on an extensible content tree with the following feautures:

*

*Content resolution that maps a request URL to a content node in the content repository

*Servlet resolution that maps a content node and a request method to a Servlet handling the request

*Default servlets supporting WebDAV, content creation from web forms and JSON representation

*A Javascript client library, allowing access to the content repository through AJAX

*Support for server-side scripting with Javascript, JSP, Ruby, Velocity and Scala

*OSGi-based extensibility through Apache Felix – the Felix Web Console was originally developed by the Apache Sling project


text:
Q: xamarin.forms: Changing language at runtim doesnt affect UI Hi I am having an app where the user picks his or her language:
I have two resources files, both of which work because I can see the text showing up in Xaml.
A short overview:
Eng Resource:
 <data name="Next" xml:space="preserve">
    <value>next</value>
    </data>

    <data name="German" xml:space="preserve">
    <value>German</value>
    </data>

    <data name="Arabic" xml:space="preserve">
    <value>Arabic</value>
    </data>

The Labels:
<Label Text="{x:Static resources:AppResources.German}"
                       VerticalOptions="Center"
                       Grid.Row="0"/>
                <Label Text="{x:Static resources:AppResources.Arabic}"
                       VerticalOptions="Center"
                       Grid.Row="1"/>
                <Label Text="{x:Static resources:AppResources.English}"
                       VerticalOptions="Center"
                       Grid.Row="2"/>

I know that they work, becaause when I change from one emulator to another (one in germany, one in england) the language changes automatically.
But I want the user to be able to change the language upon button click.
I tried:
 case "english":
                    CultureInfo culture = new CultureInfo("en-US");
                    CultureInfo.DefaultThreadCurrentCulture = culture;
                    mainPage.FlowDirection = FlowDirection.LeftToRight;
                    break;

But the phone simply ignores the language change.
Any ideas why?

A: You can create a LocalizationResourceManager class that handles language changes and also will have a property with the translation. When the language changes it will invalidate that string so it will force the property to change.
 public class LocalizationResourceManager : INotifyPropertyChanged
    {
        public static LocalizationResourceManager Instance { get; } = new LocalizationResourceManager();

        public string this[string text]
        {
            get
            {
                return AppResources.ResourceManager.GetString(text, AppResources.Culture);
            }
        }

        public void SetCulture(CultureInfo language)
        {
            Thread.CurrentThread.CurrentUICulture = language;
            AppResources.Culture = language;

            Invalidate();
        }

        public event PropertyChangedEventHandler PropertyChanged;

        public void Invalidate()
        {
            PropertyChanged?.Invoke(this, new PropertyChangedEventArgs(null));
        }
    }

Instead of binding our strings directly to the AppResources class, a Translate Extension that returns a BindingProperty is used and binds to our new LocalizationResourceManager.
[ContentProperty("Text")]
public class TranslateExtension : IMarkupExtension<BindingBase>
{
    public string Text { get; set; }
    public string StringFormat { get; set; }
    object IMarkupExtension.ProvideValue(IServiceProvider serviceProvider)
    {
        return ProvideValue(serviceProvider);
    }

    public BindingBase ProvideValue(IServiceProvider serviceProvider)
    {
        var binding = new Binding
        {
            Mode = BindingMode.OneWay,
            Path = $"[{Text}]",
            Source = LocalizationResourceManager.Instance,
            StringFormat= StringFormat

        };
        return binding;
    }
}

Usage:
<?xml version="1.0" encoding="UTF-8"?>
<ContentPage xmlns="http://xamarin.com/schemas/2014/forms"
             xmlns:x="http://schemas.microsoft.com/winfx/2009/xaml"
             x:Class="MultilingualXFSample.Views.ChangeLanguagePage"
             xmlns:helpers="clr-namespace:MultilingualXFSample.Helpers">

         <Label  Text="{helpers:Translate SelectLanguage}" />
</ContentPage>

For more, you can check: Mastering Multilingual in Xamarin.Forms
And there is a sample here: https://github.com/CrossGeeks/MasteringMultilingualSample .


text:
Q: Locking Postgres Tables with Twisted Python I have a twisted daemon that does some xml feed parsing.
I store my data in PostgreSQL via twisted.enterprise.adbapi , which IIRC is wrapping psycopg2
I've run into a few problems with storing data into database -- with duplicate data periodically getting in there.
To be honest, there are some underlying issues with my implementation which should be redone and designed much better.  I lack the time and resources to do that though - so we're in 'just keep it running' mode for now.
I think the problem may happen from either my usage of deferToThread or how I've spawned the server at the start.
As a quick overview of the functionality I think is at fault:
Twisted queries Postgres for Accounts that should be analyzed , and sets a block on them
SELECT
    id
FROM
    xml_sources
WHERE
    timestamp_last_process < ( CURRENT_TIMESTAMP AT TIME ZONE 'UTC' - INTERVAL '4 HOUR' )
    AND
    is_processing_block IS NULL ;

lock_ids = [ i['id'] for i in results ]

UPDATE xml_sources SET is_processing_block = True WHERE id IN %(lock_ids)s

What I think is happening, is (accidentally) having multiple servers running or various other issues results in multiple threads processing this data.
I think this would likely be fixed - or at least ruled out as an issue - if I wrap this quick section in an exclusive table lock.
I've never done table locking through twisted before though.  can anyone point me in the right direction ?

A: You can do a SELECT FOR UPDATE instead of a plain SELECT, and that will lock the rows returned by your query.  If you actually want table locking you can just issue a LOCK statement, but based on the rest of your question I think you want row locking.
If you are using adbapi, then keep in mind that you will need to use runInteraction if you want to run more than one statement in a transaction.  Functions passed to runInteraction will run in a thread, so you may need to use callFromThread or blockingCallFromThread to reach from the database interaction back into the reactor.
However, locking may not be your problem.  For one thing, if you are mixing deferToThread and adbapi, something's likely wrong.  adbapi is already doing the equivalent of deferToThread for you.  You should be able to do everything on the main thread.
You'll have to include a representative example for a more specific answer though.  Consider your question: it's basically "Sometimes I get duplicate data, with a self-admittedly problematic implementation, that is big and I can't fix and I also can't show you."  This is not a question which it is possible to answer.


text:
Q: Document.links empty after calling document.close When you execute following example using Firefox 3:

Open Same Content and Show Links Report

Show Links Report

You will see that both the number of links shown when clicking on 'Show Links Report' as when clicking on 'Open Same Content and Show Links Report' will be 2. However when having an external JavaScript file reference from this page the behavior seems different (just make an empty file some.js if you want). When clicking 'Open Same Content and Show Links Report' the number of links will be 0.

Open Same Content and Show Links Report

Show Links Report

It is probably a matter of loading the page and the moment that reportLinks executed exactly. I assume that the external some.js is added that the document is not completely build up. Is there a way that I can register this reportLinks call for onload event so that I can be sure that document.links is complete?
By the way the example works fine in both cases with Google Chrome.
(added after answer1)
As suggested by Marcel K. I rewrote the example, added also the code the way I really would like to have the thing going. And now testing it, and this simple example seems to work with Firefox and with Chrome.

Open Same Content and Show Links Report

Show Links Report

I had hoped with this simple example to show a simple case of the actual code I am writing. A print preview screen of complicated html in which I want to disable all hrefs once opened. But in that one the onload handler is never called... How can I register an onload handler in this case in the most robust way?
Many thanks,
Marcel

A: As I said in a comment, this is a very strange issue. But I think it happens because the inclusion of an external script causes a delay in page rendering (of the new page) and its DOM might not be ready to inspect.
My suspicion is supported by the fact that adding the (new) defer attribute seems to solve this issue:

This Boolean attribute is set to indicate to a browser that the script is meant to be executed after the document has been parsed.

The defer attribute can be set on the original page, as you want an exact copy of it. You can set it if it doesn't matter where a script is being included (e.g., when using document.write in your included file it does matter at which place you include it).
As defer is a Boolean attribute, it is activated when it is simply present (defer) or (when using XHTML) set to itself (defer="defer"). In your case, the script inclusion would read:

Update regarding your update: you should still insert a Doctype in the main page (consider using the HTML 5 one).
And I think the way you attached your onload event is the best you can do.
But considering the goal you want to achieve (a print preview without hyperlinks): you can also use the "print" media attribute and style hyperlinks like text; that's way more easy than the thing you are doing and it works when JavaScript is disabled.

A: The only way I could make the example above work portable over Firefox, Chrome and IE is by registering the onload listener through inlined JavaScript in the HTML loaded in the popup window. Following example code shows how.

Open Same Content and Show Links Report

Show Links Report

This page uses a script in script.js file. Following shows the content of that file.
function openWindow(){
  var w = window.open('', 'otherWin', 'width=600,height=600');
  w.document.write(
    '<!DOCTYPE HTML PUBLIC "-//W3C//DTD HTML 4.01//EN" "http://www.w3.org/TR/html4/strict.dtd">\n\n'+
    document.getElementsByTagName("html")[0].innerHTML+
    '\n \n'+
    '');
  w.document.close();
}

function reportLinks(links){
  var report = 'links: '+links.length;
  for (var i=0;i<links.length;i++){
    report += '\n (link='+links[i].href+')';
  }
  alert(report);
}

When putting the function addOnloadListener directly in the JavaScript file (not inlined in the page) it doesn't work in IE6 because, I believe, it cannot handle the order of script entries correctly. When addOnloadListener was not inlined the inlined call to addOnloadListener didn't work, it simply couldn't find the function in the earlier:

The code is only a simple example that doesn't really do a lot. I used it for disabling all links in a print preview popup page.
A simpler way to register an onload listener for a popup window portable over browser is always welcome.
Thanks,
Marcel


text:
Q: SharePoint Online workflow IPaddresses I am using SharePoint online in the US region. There is an option in a custom 2013 workflow to send an HTTP request. For firewall purposes, what are the IP addresses that SharePoint online uses for outgoing http requests from workflows?

A: The IP will depend on the region and server cluster. The admin section of SP Online will not provide that information - mine does not. To find out your IP, you will have to create a test server and the connections logs. A simple apache or Nginx will go.


text:
Q: Android: Fragment And Activity Working Together Following is the app flow
Activity => fragment
Fragment had some empty space. When clicking on the empty space of fragment, I'm accessing the functions of activity. How to get rid this?
Here's my xml code:
<?xml version="1.0" encoding="utf-8"?>
<RelativeLayout xmlns:android="http://schemas.android.com/apk/res/android"
    android:layout_width="match_parent"
    android:background="#FFFFFF"
    android:layout_height="match_parent" >

    <RelativeLayout
        android:id="@+id/rl_send_email_top"
        android:layout_width="match_parent"
        android:layout_height="51dp"
        android:background="@color/top_layout" >

        <ImageView
            android:id="@+id/iv_send_email_layout_back"
            android:layout_width="40dp"
            android:layout_height="40dp"
            android:layout_alignParentLeft="true"
            android:layout_centerVertical="true"
            android:layout_marginLeft="5dp"
            android:contentDescription="@string/empty"
            android:src="@drawable/icon_back" />
    </RelativeLayout>

    <RelativeLayout
        android:id="@+id/rl_send_email_middle"
        android:layout_width="match_parent"
        android:layout_height="match_parent"
        android:layout_below="@+id/rl_send_email_top"
        android:background="@color/white"
        android:padding="10dp" >

        <TextView
            android:id="@+id/tv_send_email_layout_desc"
            android:layout_width="wrap_content"
            android:layout_height="wrap_content"
            android:layout_centerHorizontal="true"
            android:layout_marginTop="10dp"
            android:text="@string/send_email_layout_desc"
            android:textColor="@color/forgot"
            android:textSize="12sp" />

        <EditText
            android:id="@+id/et_send_email_layout_email"
            android:layout_width="match_parent"
            android:layout_height="35dp"
            android:layout_below="@+id/tv_send_email_layout_desc"
            android:layout_marginTop="20dp"
            android:background="@drawable/edit_text_radius_boarder"
            android:hint="@string/send_email_layout_email"
            android:inputType="textEmailAddress"
            android:paddingLeft="5dp"
            android:textSize="12sp" />

        <EditText
            android:id="@+id/et_send_layout_name"
            android:layout_width="match_parent"
            android:layout_height="35dp"
            android:layout_below="@+id/et_send_email_layout_email"
            android:layout_marginTop="20dp"
            android:background="@drawable/edit_text_radius_boarder"
            android:hint="@string/send_email_layout_name"
            android:inputType="text"
            android:paddingLeft="5dp"
            android:textSize="12sp" />

        <EditText
            android:id="@+id/et_send_layout_phone"
            android:layout_width="match_parent"
            android:layout_height="35dp"
            android:layout_below="@+id/et_send_layout_name"
            android:layout_marginTop="20dp"
            android:background="@drawable/edit_text_radius_boarder"
            android:hint="@string/send_email_layout_phone"
            android:inputType="phone"
            android:paddingLeft="5dp"
            android:textSize="12sp" />

        <EditText
            android:id="@+id/et_send_layout_message"
            android:layout_width="match_parent"
            android:layout_height="100dp"
            android:layout_below="@+id/et_send_layout_phone"
            android:layout_marginTop="20dp"
            android:background="@drawable/edit_text_radius_boarder"
            android:gravity="top"
            android:hint="@string/send_email_layout_message"
            android:inputType="textShortMessage|textAutoCorrect|textCapSentences|textMultiLine"
            android:maxLength="2000"
            android:maxLines="5"
            android:minLines="5"
            android:padding="5dp"
            android:scrollHorizontally="false"
            android:textSize="12sp" />

        <Button
            android:id="@+id/btn_send_email_layout_submit"
            android:layout_width="150dp"
            android:layout_height="35dp"
            android:layout_below="@+id/et_send_layout_message"
            android:layout_centerHorizontal="true"
            android:layout_marginTop="30dp"
            android:background="@color/forgot"
            android:text="@string/send_email_layout_submit"
            android:textColor="@color/white"
            android:textSize="12sp" />
    </RelativeLayout>

</RelativeLayout>

A: Short question, short answer.
The fragment must be inside a holder.
Just make the holder Match_Parent.
Hope this helps.

A: you can access activity public methods in fragment like below
((BaseActivity) getActivity()).replaceFragmentWithStack(new ReportFragment());

Place some code to it helps you more :-)


text:
Q: Jenkins and JUnit I've read over the Jenkins site and its JUnit plugin, and for some reason something that is very basic is just not apparent to me.
Jenkins has an Email-ext plugin for sending custom/advanced notification emails whenever a build is ran. In these emails you can place "content tokens" that are runtime variables that get replaced with dynamic values when the email is being generated.
One of these tokens is TEST_COUNTS which allows you to display the number of JUnit tests that ran, or which failed, etc.
How does one go about getting Jenkins to display this information correctly? Is there a plugin I need, and if so, which one? I have my build running JUnit and generating an XML report. I assume Jenkins somehow parses JUnit results out of that XML and uses it to give values to that token.
But on the other hand, I've read "literature" (mailing list posts) that seems to suggest that in order to use that token you need to use Jenkins to run the unit tests, not a junit Ant task from inside your build script.
Can someone clarify this for me and perhaps even set out the "order of operations" for what steps I need to take in order to be able to make use of this token?
It would be supremely useful to get test counts in our build notifications.

A: Add something like this to the content in the "Editable Email Notification" configuration:
Total = $TEST_COUNTS
Failed = ${TEST_COUNTS,var="fail"}

I also recommend the Jenkins users mailing list for Jenkins questions, usually helpful.

A: Your first explanation is right. You tell Jenkins where to search for JUnit output files, and it parses them to find out the test results:

The test results appear on each project and build page, so as long as you're seeing the correct results there, you should get the correct token replacements in your e-mails


text:
Q: Rails: update user but password is invalid I have a payment api that takes bank account info and user info. I catch the api response and use ajax to send the infomation into my controller where I try to save the information to my user. When I save I get the error Validation failed: Password can't be blank, Password is invalid: Any ideas?
Bank Controller:
def addbank
  @user = current_user
  @user.phone_number = params[:phone_number]
  @user.birth_year = params[:year]
  @user.bank_uri = (params['bank_acct_uri'])
  @user.save! # <------- ERROR here!
  # Code was removed to be more clear
end

User Controller:
def update
  # update user controller has been commented out but the error is still there
end

User Model:
class User < ActiveRecord::Base
attr_accessible :email,:password,:password_confirmation,:phone_number,:birth_year

      attr_accessor :password
      before_save :encrypt_password
      before_save { |user| user.email = email.downcase }

      VALID_PASSWORD_REGEX = # some reg-expression
      VALID_PHONE = # some reg-expression
      validates_confirmation_of :password
      validates :password, presence: true, format:{  with: VALID_PASSWORD_REGEX }
      validates :phone_number, format: { with: VALID_PHONE }, if: :phone_number
end

Edit: Why is saving user not hitting my update user controller?

A: If you want to avoid the validation of one particular field (password in your case), but you want to do all the other validations (for example phone number), you can do something like this:
attr_accessor :skip_password

validates :password, presence: true, format:{  with: VALID_PASSWORD_REGEX }, unless: :skip_password

Then, in your controller, you could do:
def addbank
  @user = current_user
  @user.skip_password = true # We don't want to validate this..
  @user.phone_number = params[:phone_number]
  @user.birth_year = params[:year]
  @user.bank_uri = (params['bank_acct_uri'])
  @user.save! # <------- ERROR here!
  # Code was removed to be more clear
end

Do this at your own risk ~~

A: You can try to save without validation:
@user.save(:validate => false)

UPDATE:
if !@user.valid? && @user.errors[:phone_number].any?
  #do not save
else
 @user.save(:validate => false)
end

A: Where are you storing the encrypted password?
If you store it in password then it will fail validation every save because it doesn't equal password_confirmation.
I'd recommend putting the password in a separate field.
#from the User Model
attr_accessor :password, :password_confirmation

validates_presence_of :password, :on => :create
validates_confirmation_of :password

def password=(password)
    @password = password
    self.password_digest = BCrypt::Password.create(@password, :cost => 14)
end

def authenticate(password)
    BCrypt::Password.new(self.password_digest) == password
end

This way the password gets hashed and saved to password_digest and won't trigger a validation error on save.

A: I'll post this as I am about 95% certain this is the cause, but I apologize if I'm off.
I believe the cause of this is because the user's password is indeed blank. If you look at your database, you'll see a column probably called encrypted_password, which is never directly accessed via your model, nor is it ever de-crypted into your accessible password and password_confirmation attributes.
In order to update the user, you will have to enter re-enter the password, or use the save(false) method to (potentially dangerously) bypass validations.


text:
Q: How to fetch data in Room Android using MVVM architecture So I'm following the MVVM architere where I have a database with banking transactions:
@Database(entities = {Transaction.class}, version = 1, exportSchema = false) @TypeConverters({DateConverter.class})
public abstract class TransactionsRoomDatabase extends RoomDatabase {

        public abstract TransactionDao transactionDao();
        private static volatile TransactionsRoomDatabase INSTANCE;

        private static final int NUMBER_OF_THREADS = 4;
        private static final ExecutorService databaseWriteExecutor =
                Executors.newFixedThreadPool(NUMBER_OF_THREADS);

        public static ExecutorService getDatabaseWriteExecutor() {
            return databaseWriteExecutor;
        }

        public static TransactionsRoomDatabase getDatabase(final Context context) {
            if (INSTANCE == null) {
                synchronized (TransactionsRoomDatabase.class) {
                    if (INSTANCE == null) {
                        INSTANCE = Room.databaseBuilder(context.getApplicationContext(),
                                TransactionsRoomDatabase .class, "database")
                                .build();
                    }
                }
            }
            return INSTANCE;
        } }

I have the Dao class with 2 queries:
@Dao
public interface TransactionDao {
   // first query
    @Query("SELECT * " +
            "FROM transactions_table " +
            "ORDER BY bookingDate, valueDate DESC")
    LiveData<List<Transaction>> getAllTransactions();

  // second query that I don't know how to call it in my fragment
    @Query("SELECT * " +
            "FROM transactions_table " +
            "WHERE debtorAccount = :debtorAccount " +
            "ORDER BY valueDate DESC "
    )
    LiveData<List<Transaction>> getTransactionsFiltered(String debtorAccount);

   // insert the list of transactions in databse
   @Insert(onConflict = OnConflictStrategy.REPLACE)
   void insertTransactions(List<Transaction> transactionList);
}

Repository:
public class TransactionRepository {
    private TransactionDao transactionDao;
    private LiveData<List<Transaction>> transactionList;

    public TransactionRepository(Application application) {
        TransactionsRoomDatabase roomDatabase = TransactionsRoomDatabase.getDatabase(application);
        transactionDao = transactionsRoomDatabase.transactionDao();
        transactionList = transactionDao.getAllTransactions();
    }

   // get all transactons
   public LiveData<List<Transaction>> getAllTransactions() {
    return transactionList;
   }

   // insert transactions in database using DAO. Are done in another thread so the main thread is not blocked
    public void insertTransactions(List<Transaction> transactionList) {
        TransactionsRoomDatabase.getDatabaseWriteExecutor().execute(() ->       transactionDao.insertTransactions(transactionList));
    }
}

ViewModel:
public class HomeAdvancedViewModel extends AndroidViewModel {
    private TransactionRepository transactionRepository;
    private LiveData<List<Transaction>> allTransactions;

    public HomeAdvancedViewModel(Application application) {
        super(application);
        transactionRepository = new TransactionRepository(application);
        allTransactions = transactionRepository.getAllTransactions();
    }

    public LiveData<List<Transaction>> getAllTransactions() {
        return allTransactions;
    }
}

In the main fragment, I'm populating a recyclerView with all the transactions in the databse:
public class MainFragment extends Fragment {
    private HomeAdvancedViewModel homeAdvancedViewModel;

    @Override
    public void onCreate(Bundle savedInstanceState) {
        super.onCreate(savedInstanceState);
        homeAdvancedViewModel = new ViewModelProvider(this).get(HomeAdvancedViewModel.class); // define viewModel
    }

    @Override
    public void onViewCreated(@NonNull View view, @Nullable Bundle savedInstanceState) {
        super.onViewCreated(view, savedInstanceState);

        /* Here I'm using the observable pattern. When transactions in database are changed, I call my setCurrentTransactions(...) function that populates again the recycler view */
        homeAdvancedViewModel.getAllTransactions().observe(getViewLifecycleOwner(), transactions -> setCurrentTransactions(transactionListAdapter, recyclerViewTransactions, transactions));
    }
}

My question is: How can I call the function from DAO
getTransactionsFiltered(String debtorAccount)

to populate the SAME recyclerView (when some button is pressed)? I cannot have something like
        public void getTransactionsFiltered(String account) {
            TransactionsRoomDatabase.getDatabaseWriteExecutor().execute(() ->       transactionDao.getTransactionsFiltered(account)); // calling the 2nd query in DAO
        }

in my DAO because the queries should be done on another thread (I'm NOT allowed to do it on the main thread), so my DAO cannot return a List of transactions.

Can you provide any help?

A: ANSWER
This is how I solved it:
Added in Repository class the following function:
public class TransactionRepository {
    private TransactionDao transactionDao;
    private LiveData<List<Transaction>> transactionList;

    public TransactionRepository(Application application) {
        TransactionsRoomDatabase roomDatabase = TransactionsRoomDatabase.getDatabase(application);
        transactionDao = transactionsRoomDatabase.transactionDao();
        transactionList = transactionDao.getAllTransactions();
    }

   // get all transactons
   public LiveData<List<Transaction>> getAllTransactions() {
    return transactionList;
   }

   // NEW FUNCTION ADDED
   public LiveData<List<Transaction>> getTransactionsFiltered(String account) {
     return accountsRoomDatabase.transactionDao().getTransactionsFiltered(account);
   }
}

By doing so, the main thread is not blocked. Don't know for sure if it's the best approach, but it solved my problem


text:
Q: Can you retrieve documents in the status poll request? Is there anyway to use the DocuSign API (polling) to retrieve and envelopes with status changes and all the documents in the same request? If not, is there a better way to do the following.
Currently, I am retrieving the envelope information using the polling for envelope status recipe.
Afterward, I am using the provided EnvelopeId from the summary to get a list of the documents to loop through and download:
EnvelopeDocumentsResult docList = envelopesApi.ListDocuments(accountId, envelopeId);

for (int i = 0; i < docList.EnvelopeDocuments.Count; i++)
        {
            // GetDocument() API call returns a MemoryStream
            MemoryStream docStream = (MemoryStream)envelopesApi.GetDocument(accountId, envelopeId, docList.EnvelopeDocuments[i].DocumentId);
            // More code below to process the documents

This requires that I make 3 service calls (one for status, then for the list of documents in the envelope, followed by downloading the actual document). This seems redundant and I imagine there is a better way to do this.

A: Instead of polling for Envelope status, you can use DocuSign Connect.
DocuSign Connect will send an HTTP POST request to the endpoint that you specify for the Connect configuration settings. You can subscribe for different triggering events in your Connect configuration, based on trigger event DocuSign will publish the message to your listerner.
When your "listener" application that resides at that endpoint receives a message from Connect, then you can do the processing of the message to know the envelope status, you may also receive envelope's documents in the XML but including document PDF Bytes in an XML message will make XML pretty big and might impact performance on your end if documents are very big.
You can find Connect details at DS Connect
This will save lot of API calls for you, and it is better design to retrieve the data which you are interested in.


text:
Q: javascript prototype I AM trying to understand js prototype property: my sample code
function Container(param) {
    this.member = param;
}

var newc = new Container('abc');

Container.prototype.stamp = function (string) {
    return this.member + string;
}

document.write(newc.stamp('def'));

function Box() {
    this.color = "red";
    this.member = "why";
}

Container.prototype = new Box();
Box.prototype.test = "whatever";
var b = new Box();

document.write(newc.test);

here the last line is undefined - even though Container's prototype is a Box and Box's prototype has a property test, why is the newc which refers to test in Box doesnt work? can any one please explain how the 'Prototype' works in my above context.
Thanks...

A: You are setting Container prototype to Box() after the newc instance was already created.
Reorder the statements as follows:
function Container(param) {
    this.member = param;
}

function Box() {
    this.color = "red";
    this.member = "why";
}

Container.prototype = new Box();
Box.prototype.test = "whatever";
Container.prototype.stamp = function (string) {
    return this.member + string;
}

//Here the containers prototype setup is complete.
var newc = new Container('abc');

document.write(newc.stamp('def'));

document.write(newc.test);

A: If sounds like you want to know WHY it is behaving the way it is, and not just "fix" the code. So here's what's going on.
As you saw, if you change the prototype of "Container", you will actually change the properties for new objects AND objects already instantiated. So:
function Container(param) {
    this.member = param;
}

var newc = new Container('abc');

// setting a new property of the prototype, after newc instantiated.
Container.prototype.stamp = function (string) {
    return this.member + string;
}

// This already-instantiated object can access the stamp function
document.write(newc.stamp('123')); // output: abc123

So there's no problem with the above, as long as you don't call the new method before it's defined. Now the next point. Add this to the above:
// Our Box object
function Box() {
    this.color = "red";
    this.member = "why";
}

Container.prototype = new Box();
var newd = new Container('fgh');
document.write(newd.stamp('456')); // output: ERROR

Error! But that makes sense, right? You totally wiped out the "Container" prototype and replaced it with the one from "Box", which has no "stamp" function.
I am going to assume you want "Box" to inherit from "Container". That would be logical from the naming convention. If you want to do that, replace the previous section with this:
// Our Box object
function Box() {
    this.color = "red";
    this.member = "why";
}

// This inherits from Container. Note that we can
//   do this before or after we declare "Box"
Box.prototype = new Container();

Box.prototype.test = "Whatever";
var b = new Box("jkl"); // note: "jkl" is ignored because "Box" sets "member" to "why"

document.write(b.test); // output: Whatever
document.write("<br>");
document.write(b.stamp("345")); // output: why345

So now we have a "Box" that can call its own methods and parameters, and also call them from its parent "Container".
So the big picture is that an object will look at its own prototype for a method or something, and if it doesn't find it there it will look in the prototype of the thing it inherited from, and so on. The other big point is that setting something in the prototype makes it immediately available in all future AND current instances of that object.

A: An object does not contain a reference to its constructor which it uses to get at the prototype.  If it did, then the code would work as you expected.
Instead, an object contains a reference to its prototype that is set when it is created.
From the language spec section 4.2.1:

Every object created by a constructor has an implicit reference (called the object's prototype) to the value of its constructor's "prototype" property. Furthermore, a prototype may have a non-null implicit reference to its prototype, and so on; this is called the prototype chain. When a reference is made to a property in an object, that reference is to the property of that name in the first object in the prototype chain that contains a property of that name. In other words, first the object mentioned directly is examined for such a property; if that object contains the named property, that is the property to which the reference refers; if that object does not contain the named property, the prototype for that object is examined next; and so on.


text:
Q: How to properly persist login state using FireBase in React Native EXPO? I used email and password to sign in through Firebase. However, once I reload the app, I need to sign in again. Is there a way to automatically log user in once the app is reloaded?
I am using EXPO managed project with functional structure btw, not with class structure.

A: if you're still facing this problem.
Here's how I've done it.
Here's my App.js
  const [loggedIn, setLoggedIn] = useState(false);

  useEffect(() => {
    return firebase.auth().onAuthStateChanged(setLoggedIn);
  }, []);

  if (loggedIn) {
    return <HomeScreen />
  } else {
     <Login />
  }

Here's the login code.
I have a simple form with email and password and a button, when pressed, this functions is called.
  const handleLogin = async () => {
      await firebase
        .auth()
        .signInWithEmailAndPassword(email, password)
        .catch((err) => {
          setVisible(true);
          setModalMessage(err.message);
        });

  };

Let me know if this worked.


text:
Q: Visual Studio 2010 Dev Server Stopped Serving Style Sheets When Debugging ASP.NET MVC app? About an hour ago my VS2010 stopped serving style sheets for both web projects in a solution. A hard refresh (Ctrl F5) brings the sheets back, but when I navigate to the next page, I have no style sheet again.
I've restarted my machine, cleaned and rebuilt the solution, stopped and started the dev server(s) several times, and hit the F5 key extra specially hard several times, none of which seem to have helped. I have not changed any settings, so presume this is some sort of bug.
Is this common, anyone else had to fix this or have any ideas?
Thanks!

A: Solved. This was caused a gzip http module in the application. Simple fix, I'll leave the question here for myself or anyone else that runs into the same issue.
Found the problem using Fiddler http debugger.


text:
Q: Why showing empty data? I am developing cv app but it is showing white screen I have checked json response in Postman but it is showing.
below my LogCat
D/Surface: Surface::connect(this=0xa232a700,api=1)
W/libEGL: [ANDROID_RECORDABLE] format: 1
D/mali_winsys: EGLint new_window_surface(egl_winsys_display*, void*, EGLSurface, EGLConfig, egl_winsys_surface**, egl_color_buffer_format*, EGLBoolean) returns 0x3000
I/System.out: [socket][0] connection www.mocky.io/52.210.139.55:80;LocalPort=-1(10000)
D/: [Posix_connect Debug]Process activity.drawer.navigation.com.kitabsawticlone :80
E/RecyclerView: No adapter attached; skipping layout

below my JSON link

http://www.mocky.io/v2/5bd2bce93400000f00cfde57

below my IntroductionItem.java where I am making retrofit call
public class IntroductionItem extends AppCompatActivity {

  public List<Introduction> introductionList;
  public IntroductionAdapter adapter;

    protected void onCreate(Bundle savedInstanceState) {
        super.onCreate(savedInstanceState);
        setContentView(R.layout.introduction);
        KitabInterface kitabInterface = ApiClient.getApiService();
        Call<KitabSawti> call = kitabInterface.getIntroduction();

        call.enqueue(new Callback<KitabSawti>() {
            @Override
            public void onResponse(Call<KitabSawti> call, Response<KitabSawti> response) {
            introductionList =  response.body().getIntroduction();
            RecyclerView recyclerView  =  findViewById(R.id.recyclerView);
            adapter = new IntroductionAdapter(introductionList);
                recyclerView.setHasFixedSize(true);
                recyclerView.setLayoutManager(new LinearLayoutManager(getApplicationContext()));
                recyclerView.setAdapter(adapter);

            }

            @Override
            public void onFailure(Call<KitabSawti> call, Throwable t) {

            }
        });

    }
}

below my api client class
public class ApiClient

{

        public static final String BASE_URL = "http://www.mocky.io/";

        /**
         * Get Retrofit Instance
         */

        public static Retrofit getRetrofitInstance() {
            return new Retrofit.Builder()

                    .baseUrl(BASE_URL)
                    .addConverterFactory(GsonConverterFactory.create())
                    .build();

        }

        /**
         * Get API Service
         *
         * @return API Service
         */
        public static KitabInterface getApiService() {
            return getRetrofitInstance().create(KitabInterface.class);
        }
    }

below interface class where I have put ending point
public interface KitabInterface {

    @GET("/v2/5bd2bce93400000f00cfde57")
    Call<KitabSawti> getIntroduction();

}

below my adapter
public class IntroductionAdapter extends RecyclerView.Adapter<IntroductionAdapter.MyViewHolder> {

    private List<Introduction> moviesList;

    public IntroductionAdapter(List<Introduction> moviesList) {
        this.moviesList = moviesList;
    }

    @Override
    public MyViewHolder onCreateViewHolder(ViewGroup parent, int viewType) {
        View itemView = LayoutInflater.from(parent.getContext())
                .inflate(R.layout.introduction_list, parent, false);

        return new MyViewHolder(itemView);
    }

    @Override
    public void onBindViewHolder(@NonNull final MyViewHolder holder, int position) {
        final Introduction introduction = moviesList.get(position);

        if (introduction.getImage() != null) {

            Picasso.get().load(introduction.getImage()).
                    networkPolicy(NetworkPolicy.OFFLINE).transform(new RoundedCornersTransformation()).into(holder.imageView, new Callback() {
                @Override
                public void onSuccess() {

                }

                @Override
                public void onError(Exception e) {
                    Picasso.get().load(R.drawable.ic_contact).
                            into(holder.imageView);
                }
            });

        }
        holder.introduction.setText(introduction.getIntroduction());

    }

    @Override
    public int getItemCount() {
        return moviesList.size();
    }

    public class MyViewHolder extends RecyclerView.ViewHolder {
        public TextView introduction, about;
        public ImageView imageView;

        public MyViewHolder(View view) {
            super(view);

            imageView = (ImageView) view.findViewById(R.id.imageView);
            introduction = (TextView) view.findViewById(R.id.introduction);
            about = (TextView) view.findViewById(R.id.about);

        }
    }
}


text:
Q: Hide Android Context Menu Item Another newbie question.  I have a context menu that I apply for a ListView that simply allows the user to move items up or down, or delete the item.
I have code in onContextItemSelected() to prevent things from moving up past top or bottom of the list, etc., but I'd rather hide the context menu items in the first place if (for instance) the top item in the list is selected.
I assume that I need to do this in onCreateContextMenu, but I'm not sure how.
Here is my onCreateContextMenu code:
@Override
public void onCreateContextMenu(ContextMenu menu, View v,
        ContextMenuInfo menuInfo) {
    super.onCreateContextMenu(menu, v, menuInfo);
    MenuInflater inflater = getMenuInflater();
    inflater.inflate(R.menu.mycontextmenu, menu);
}

Thanks,
wTs

A: This is a solution for a PopupMenu just in case somebody is seeking for it as I did. Here I have 3 buttons in menu layout file for PopupMenu and I remove some of them in some cases:
    PopupMenu popup = new PopupMenu(this, this.actionButton);
    popup.setOnMenuItemClickListener(this);
    MenuInflater inflater = popup.getMenuInflater();
    inflater.inflate(R.menu.menu_resume_view, popup.getMenu());

    Menu menu = popup.getMenu();
    if (this.resume.isPublished()) {
        menu.removeItem(R.id.menu_button_publish);
    }
    else {
        menu.removeItem(R.id.menu_button_unpublish);
        menu.removeItem(R.id.menu_button_update_publish_date);
    }

    popup.show();

When you use PopupMenu onPrepareOptionsPanel is not called. So you have to get menu items by id while creating PopupMenu and remove those, that should not be available in a particular case.

A: If a context menu is opened for a ListView, menuInfo will contain an object of type AdapterContextMenuInfo, which gives you information about which item in the list was clicked. If it is the first or the last item, you can simply remove the corresponding entries from the context menu, though I'm not quite sure what happens if no entries are left.

A: In your onCreateContextMenu method, you need to get the menu items that you potentially want to hide and set them as not visible based on the list positions.
Something like this:
AdapterView.AdapterContextMenuInfo info = (AdapterView.AdapterContextMenuInfo) menuInfo;

if(info.position < 1) {
   myLocationMenuItem = menu.findItem(R.id.myLocation);
   myLocationMenuItem.setVisible(enable);
}

A: You can Disable a particular item if you want to.
@Override
        public void onCreateContextMenu(ContextMenu menu, View v,
                ContextMenuInfo menuInfo)
     {
                AdapterView.AdapterContextMenuInfo info = (AdapterView.AdapterContextMenuInfo) menuInfo;

                int position = info.position;

                // use this position to decide your item clicked

                menu.clear();
                menu.setHeaderTitle("Context Menu Title");
                String[] menuItems = getResources().getStringArray(
                        R.array.menu_context);

                for (int i = 0; i < menuItems.length; i++)
                {
                    menu.add(Menu.NONE, i , i, menuItems[i]);
                }
               menu.getItem(0).setEnabled(**Conditional check**);
               menu.getItem(1).setEnabled(**Conditional check**);
               menu.getItem(2).setEnabled(**Conditional check**);
     }


text:
Q: Combining several Spirograph codes into a one unified code From the answers to these questions 1, 2, and 3:
Is it possible to combine the 3 versions of the Spirograph codes:
the simple one including controlling nRotations, colours, and scales;
the one controlling segmenting the drawing (with the added \pv{dx});
and the one controlling the filling of the drawing;
into a one unified code that could be used to control all these variables, when needed, in all these different situations.
\documentclass{beamer}
\beamertemplatenavigationsymbolsempty
\usepackage{tikz}
\usepackage{verbatim}
\begin{document}
% ====================== begin spiro setting ======================
\tikzset{pics/spiro/.style={code={
\tikzset{spiro/.cd,#1}
\def\pv##1{\pgfkeysvalueof{/tikz/spiro/##1}}
\draw[trig format=rad,pic actions]
plot[variable=\t,domain=0:2*pi*\pv{nRotations}, samples=90*\pv{nRotations}+1, smooth cycle]
(
{(\pv{R}+\pv{r})*cos(\t)+\pv{p}*cos((\pv{R}+\pv{r})*\t/\pv{r})},
{(\pv{R}+\pv{r})*sin(\t)+\pv{p}*sin((\pv{R}+\pv{r})*\t/\pv{r})}
);
}},
spiro/.cd,R/.initial=6,r/.initial=-1.5,p/.initial=1,nRotations/.initial=1}
% ====================== end spiro setting ======================
% ============== begin spirofill setting ===================
\tikzset{pics/spirofill/.style={code={
\tikzset{spirofill/.cd,#1}
\def\pv##1{\pgfkeysvalueof{/tikz/spirofill/##1}}
\draw[trig format=rad,pic actions]
 plot[variable=\t,domain=pi/2:3*pi/2, samples=31, smooth]
(
{(\pv{R}+\pv{r})*cos(\t)+\pv{p}*cos((\pv{R}+\pv{r})*\t/\pv{r})},
{(\pv{R}+\pv{r})*sin(\t)+\pv{p}*sin((\pv{R}+\pv{r})*\t/\pv{r})}
);
}},
spirofill path/.code={\def\pv##1{\pgfkeysvalueof{/tikz/spirofill/##1}}
\tikzset{insert path={
plot[trig format=rad,variable=\t,domain=pi/2:3*pi/2, samples=31, smooth, domain=pi:pi/2]
(
{(\pv{R}+\pv{r})*cos(\t)+\pv{p}*cos((\pv{R}+\pv{r})*\t/\pv{r})},
{(\pv{R}+\pv{r})*sin(\t)+\pv{p}*sin((\pv{R}+\pv{r})*\t/\pv{r})}
)
|- (\pv{R}+\pv{r}+\pv{p},-\pv{R}-\pv{r}-\pv{p})
--
(\pv{R}+\pv{r}+\pv{p},\pv{R}+\pv{r}+\pv{p})  --
(-\pv{R}-\pv{r}-\pv{p},\pv{R}+\pv{r}+\pv{p})
--  cycle
}}},
spirofill/.cd,R/.initial=6,r/.initial=-1.5,p/.initial=1}
% ============== end spirofill setting ===================
% ====================== begin spirosegment setting ======================
\tikzset{pics/spirosegment/.style={code={
\tikzset{spirosegment/.cd,#1}
\def\pv##1{\pgfkeysvalueof{/tikz/spirosegment/##1}}
\pgfmathparse{(int(1/\pv{dx}+1)}
\tikzset{spirosegment/samples=\pgfmathresult}
\draw[trig format=rad,pic actions]
plot[variable=\t,domain=\pv{xmin}-0.002:\pv{xmax}+0.002, samples=\pv{samples}, smooth]
(
{(\pv{R}+\pv{r})*cos(\t)+\pv{p}*cos((\pv{R}+\pv{r})*\t/\pv{r})},
 {(\pv{R}+\pv{r})*sin(\t)+\pv{p}*sin((\pv{R}+\pv{r})*\t/\pv{r})}
);
}},
spirosegment/.cd,R/.initial=6,r/.initial=-1.5,p/.initial=1, dx/.initial=0.05,samples/.initial=21,domain/.code args={#1:#2}{%
\pgfmathparse{#1}\tikzset{spirosegment/xmin/.expanded=\pgfmathresult}
\pgfmathparse{#2}\tikzset{spirosegment/xmax/.expanded=\pgfmathresult}},
xmin/.initial=0,xmax/.initial=2*pi}
% ====================== end spirosegment setting ======================
\begin{frame}[t]
\frametitle{Spiro,nRot5}
\begin{center}
\vskip -.6cm
\begin{tikzpicture}[line width=.2mm]
\foreach \scl/\clr/\p in
{.8/blue/3.0,.4/purple/7.0}
{
(0,0) \pic[draw=\clr,rotate=360/4/2*1,scale=\scl]{spiro={R=9.6,r=-12,p=\p,nRotations=5}};
}
\end{tikzpicture}
\end{center}
\end{frame}
\begin{frame}[fragile,t]%this frame needs fragile
\frametitle{spirosegment}
\begin{tikzpicture}[line width=.8mm]
\path (0,0)
foreach \X [count=\Y starting from 0] in {blue,red,green,orange}
{pic[scale=0.5,draw=\X]{spirosegment={domain={-pi/4+\Y*pi/2}:{pi/4+\Y*pi/2}}}};%,dx=0.005
\end{tikzpicture}
\end{frame}
\begin{frame}[t]
\frametitle{spirofill with color interpolation}
\begin{center}
\begin{tikzpicture}[line width=.2mm,spirofill/.cd,R=10.5,r=-5.25,p=3]
\foreach\Z in {0,1}
{\foreach \clr [count=\X starting from 0, remember=\clr as \lastclr (initially purple)] in {blue,green,orange,purple}
{\foreach \Y [evaluate=\Y as \mycf using {int(100*\Y/9)}] in {1,...,9}
{\ifnum\Z\X\Y=102
 \clip[scale=.4,rotate=5,spirofill path];
\fi
\pic[draw=\clr!\mycf!\lastclr,rotate=45*\X+5*\Y+\Z*180,scale=.4,fill=\clr!\mycf!\lastclr!40]{spirofill};
}}}
\end{tikzpicture}
\end{center}
\end{frame}
\end{document}


text:
Q: Access non-https-image-links in fully https secured magento store I have a webshop which is fully secured over https.
Since this shop uses the M2E extension and the eBay part of this extension only accepts non-https-links for images, I need to be able to access images with both url variations, http and https.
Anybody has a solution for this?
Any help will be much appreciated

A: I found a solution now.
Introduced a subdomain like ebay.mydomain.de.
Copied following file to locale and changed it:
M2ePro / Model / Magento / Product.php

about line 1228 change code to:
Warning: use your-normal-domain with http even if it is https since m2e always want to use http
return str_replace(array('http://your-normal-domain', ' '), array('http://your-ebay-subdomain', '%20'), $url);


text:
Q: What language is this Salesforce code that I need to wrap? I'm working on a Salesforce coding issue. Let me preface this by saying I'm not a developer or Salesforce expert.

*

*What language is this?
 Data Type   FormulaThis formula references multiple objects
 IF (Fulfillment_Submission_Form_URL__c <> "" && CONTAINS(Fulfillment_Submission_Form_URL__c, "qualtrics"),

 Fulfillment_Submission_Form_URL__c &

 (IF (CONTAINS(Fulfillment_Submission_Form_URL__c,"?SID="), "&", "?")) &

 (IF (CONTAINS(TEXT(Type__c), "Site Visit"),
 "ContactId="&Statement_of_Work__r.Contractor_Contact__c&
 "&CoachType="&SUBSTITUTE(Statement_of_Work__r.Work_Type__r.Name," ","%20")&
 "&CoachName="&SUBSTITUTE(Statement_of_Work__r.Contractor_Name__c," ","%20")&
 "&InitPartId="&Initiative_Participation__r.Id&
 "&InstitutionName="&substitute(substitute(SUBSTITUTE(Institution_Name__c," ","%20"),")",""),"(","")&
 "&AccountId="&Initiative_Participation__r.Participating_Institution__r.Id&
 "&TodaysDate="&TEXT(TODAY())&
 "&SOWLineItemId="&Id&
 "&LeaderCollege="&Initiative_Participation__r.ATD_Leader_College_Status__c&
 "&SVRCompleted="&TEXT(Count_of_Site_Visit_Fulfillments__c)&
 "&SVRRequired="&TEXT(Number_of_Work_Units_Allocated__c),

 IF (CONTAINS(TEXT(Type__c), "Feedback"),
 "InitPartId="&Initiative_Participation__r.Id&
 "&SOWLineItemId="&Id&
 "&ReportYear="&Statement_of_Work__r.SOW_Year__c&
 "&UserId="&Contractor_User_Id__c&
 "&InstitutionName="&substitute(substitute(SUBSTITUTE(Institution_Name__c," ","%20"),")",""),"(",""),
 "")
 ))

 ,"")

*Essentially it's pulling a link from another product we've integrated it with. We then take the basic link and reformat it to add parameters.
The problem is when it pulls in some parameters (ex: CoachName) the Coach entered their name in strange formats like: John (Coach) Doe.
So when the script outputs a URL that includes parameters it breaks at the &CoachName=John%20(Coach)% portion of the URL. Any easy way to work around this by modifying the script? Unfortunately we DO need that (Coach) identifier because the system we push to grabs that as well.

A: It's formula syntax, I'd compare it to Excel-like formulas. There's self-paced training if you don't want to read documentation. And as it's not exactly code-related you may have more luck on dedicated site, https://salesforce.stackexchange.com/. More admins lurk there.
So you do want that "(Coach)" to go through but it breaks the link? Looks like ( is a special character. It's not technically wrong to have unescaped parentheses, if it breaks that other site you might want to contact them and get their act together. RFC doesn't force us to encode them but looks like you'll have to to solve it at least in the short term: https://webmasters.stackexchange.com/questions/78110/is-it-bad-to-use-parentheses-in-a-url
Instead of poor man's encoding (SUBSTITUTE(Statement_of_Work__r.Contractor_Name__c," ","%20") try using proper URLENCODE(Statement_of_Work__r.Contractor_Name__c).
Or there's bit more "pro" function called URLFOR but the documentation doesn't make it very clear how powerful the 3rd parameter is with the braces [key1 = value1, key2 = value2] syntax. Basically just pass the parameters and let SF worry about encoding special characters etc.
Read my answer https://salesforce.stackexchange.com/a/46445/799 and there are some examples on the net like https://support.docusign.com/s/articles/DFS-URL-buttons-for-Lightning-basic-setup-limitations?language=en_US&rsc_301


text:
Q: Optimize query on single table with group by, where, and 'flag' I am struggling with the performance of type of query that I am using repeatedly. Any help would be greatly appreciated.
I have the following table:
    item week type  flag   value
    1    1    5     0      0.93
    1    1    12    1      0.58
    1    1    12    0      0.92
    1    2    6     0      0.47
    1    2    5     0      0.71
    1    2    5     1      0.22
    ...  ...  ...   ...    ...

(the complete table has about 10k different items, 200 weeks, 1k types. flag is 0 or 1. Around 20M rows in total)
I would like to optimize the following query:
    select item, week,
    sum(value) as total_value,
    sum(value * (1-least(flag, 1))) as unflagged_value
    from test_table
    where type in (5,10,14,22,114,116,121,123,124,2358,2363,2381)
    group by item, week;

Currently, the fastest I could get was with an index on (type, item, week) and engine = MyIsam.
(I am using mysql on a standard desktop).
Do you have any suggestions (indices, reformulation, etc.) ?

A: as per my knowledge GROUP BY query can be fully optimized only with covering index.
add following covering index on your table and check with EXPLAIN:
ALTER TABLE test_table  ADD KEY ix1 (type, item, week, value, flag);

after adding index check following query with EXPLAIN:
SELECT type, item, week,
    SUM(value) AS total_value,
    SUM(IF(flag = 1, value, 0)) AS unflagged_value
FROM test_table
WHERE type IN(5,10,14,22,114,116,121,123,124,2358,2363,2381)
GROUP BY type, item, week;

you may need to modify your query like this:
SELECT item, week,
       SUM(total_value) AS total_value,
       SUM(unflagged_value) AS unflagged_value
FROM(
    SELECT type, item, week,
        SUM(value) AS total_value,
        SUM(IF(flag = 1, value, 0)) AS unflagged_value
    FROM test_table
    GROUP BY type, item, week
)a
WHERE type IN(5,10,14,22,114,116,121,123,124,2358,2363,2381)
GROUP BY item, week;

see query execution plan. SQLFIDDLE DEMO HERE

A: I think You should have only two indices in the table
1. An index on type (non clustered)
2. A composite index on (item, week) in the same order (non clustered)


text:
Q: Pass argument starting with minus sign to shell command I want to run the following (KDE specific) command with an argument (-0.1) that starts with '-'
kdialog --textinputbox 'Output:' '-0.1'

It is suposed to show a textbox with '-0.1' but the command gives
unknown option "-0.1"

while
kdialog --textinputbox 'Output:' '0.1'

works.
Obviously the command tries to interpret 0.1 as an option.
Is there a way to pass the argument "-0.1" to such commands? I tried passing it as variable which didn't work either!

A: Try with:
kdialog --textinputbox 'Output:' -- '-0.1'

-- means "end of options" and should work for all Qt (thus KDE) apps that use the standard argument functions for that framework.


text:
Q: Accessing Global Variables within Routes in Express I'm still new to Express, so please bear with me.
What I'm trying to do is store some of my environmental variables in a global variable such that they can be accessed in any route without having to redeclare the variables within each route.
Note that I used the Express Generator to set up the project scaffolding.
Here's a stripped-down example of what I'm trying to do:
App.js
const express = require('express');

// Load Routes
const inventoryRouter = require('./src/routes/inventory');

// Instantiate Express/Assign App Var
const app = express();

// Set Global Env Vars
app.set('DevUrl', process.env.Dev_URL || null);

// Use Routes
app.use('/inventory', inventoryRouter);

module.exports = app;

Inventory.js
const express = require('express');
const router = express.Router();

// Require Inventory Controller
const inventoryController = require('../controllers/inventoryController');

// Inventory Routes
router.get('/', inventoryController.get_inventory);
router.post('/', inventoryController.update_inventory);

module.exports = router;

InventoryController.js
const router = express.Router();

// Store Vars
const LocalRouteVariable = app.get('DevUrl') + 'Some String';

// Rest of Controller Code ...

Question
"app" is not defined in the controller. So, my question is, how can I get the value of "DevUrl"?

A: You can use req.app to access the app instance from inside a controller.
In your case:
InventoryController.js
export get_inventory = async (req, res, next) =>{
   const devUrl = req.app.get('DevUrl');
   //Controller Logic
}


text:
Q: Using Markdown as a Grails View We're writing a grails (Grails 2.1.1) project where, for some of our views, we want to use markdown instead of gsp files.
At the moment we can do this using the markdown plugin in a special layout. This allows us to render markdown views like so:
render(layout: 'docs', view: 'markdown')
However, this requires the markdown page to have a .gsp extension, when, for practical reasons, we need it to have a .md extension.
Does anyone know a better way to use markdown as a grails view? It would be great if we can avoid using the .gsp extension.

A: The Short Answer
You're not going to be able to without some heavy modifications. The distributed GrailsViewResolver is hard-tied to .gsp and .jsp extensions.
See grails-core on github for verification.
The Long Answer
You might be able to fashion your own Ant task to hook it into the Compile cycle of your Grails application so that, at a minimum, you can compile your *.md files through the GroovyPageCompiler.
That process might look something like this (though not exactly, since I am relying on the plugin's taglib to do the rendering in this case, for simplicity).
But this doesn't solve all of your problems. You would also need to register a new view resolver, and to do that you would inevitably go down the road of rewriting the GrailsDispatcherServlet.
It sounds like your solution of storing the files in the conf directory might be your best (although dirty) bet for now. Maybe somebody will take the time to allow for configurable GSP file extensions in the future, and that might solve your problem down the road.
I hope you find some of this information useful.

A: I did pretty much the same thing but with another approach today. I wanted to serve the readme file of the project so I couldn't really move it anywhere. I ended up soft linking it from readme.md to grails-app/views/readme/readme.gsp. I posted about the whole thing.
And yes - soft linking works if you and all your coworkers are on *-nix - so it is not a platformsafe way to do it.


text:
Q: Why won't the java String "contains" method return found? Here is the input to my function
"
TESTINGUse a new box

***-1111

"

When I do the below it never returns anything but -1
input.indexOf("cardnumber")

Any reason this isn't working? when I do an indexOf("div") it returns fine ... (help)
thanks guys (sorry for not posting the unit test earlier)
public Cart viewCart() {
        ResponseAndCookies result = service.makeHttpRequestWithUrl("https://www.xbox.com/account/fakebox/");
        String response = result.getResponse();

        String availableCreditCard = "
***";
        if (response.contains(availableCreditCard)) {
            return parseJson.parseCartAndReturnObject(response);
        }

        return null;
    }

    public class XboxViewCartServiceTest {
    @Test
    public void verify_cart_works_with_valid_login() {
        FakeXboxCartParseJson jsonParser = new FakeXboxCartParseJson();
        XboxViewCartService sut = new XboxViewCartService(new FakeXboxViewCartHttpBase(), jsonParser);
        Cart cart = sut.viewCart(null);

        Assert.assertTrue(jsonParser.calledMethod);
    }

    class FakeXboxViewCartHttpBase extends XboxHttpService {
        @Override
        public ResponseAndCookies doHttpPostWithUrl(String url, ResponseAndCookies responseAndCookies, String json) {
            ResponseAndCookies result = new ResponseAndCookies();
            result.setResponse("
TESTINGUse a new box

***-1111

");

            return result;
        }
    }

    class FakeXboxCartParseJson extends XboxCartParseJson {
        public boolean calledMethod = false;
        @Override
        public Cart parseCartAndReturnObject(String html) {
            calledMethod = true;
            return null;
        }
    }
}

A: This obviously works as you provide it, so there are only 3 options:

*

*There are some non-printable characters in the string;

*There is an encoding issue when you read the input and compare;

*There's something wrong somewhere else that we cannot see because you don't give enough code.

For the moment, the best best is item 3.
Please provide more code.
EDIT (2011-05-23 02:20):
Thanks for the update to your question. So, now we still cannot be sure as we're missing the data returned by your endpoint, but there's a good chance if just doesn't exactly contain
***.
Do make sure as well that you specify the right headers for your request and that you use valid content type and character encoding. Please make also sure that you are not using a strange encoding on your source files, as you might be inputting non-standard * characters without knowing it.


text:
Q: How to implement SRAM sense amplifier? I am designing a simple programmable LED screen system as an exercise, and I need a non-standard type of SRAM (16x5) so I am designing the memory circuits. I have looked everywhere (Digikey, TI, National Semiconductor, etc.) for a chip that is just a sense amplifier for SRAM and I haven't found anything. I called TI and they said they didn't make anything like that, but I may be able to use a comparator for that. My question is, is it possible to wire up, say, a LM339 as a sense amplifer? And if so, how?
Thanks

A: To answer your question, yes you can use a LM339 as a sense amp, and all you need to do is wire the + input to the non-inverting bit-line, and the - input to the inverting bit-line. BUT...
Since we're talking about reading a SRAM, the basic sequence of events during a READ is:

*

*Pre-charge both bit-lines to VDD.

*Assert the desired word-line

*The selected bits will now pull one of each complimentary bit-line pair towards VSS

*The sense amplifier will sense a difference between the bit-line voltages (one will stay at VDD, the other will be falling towards VSS)

If you look at the schematic for a 4T or 6T bit-cell, then you can see that the falling bit-line will eventually reach VSS. In typical IC designs, where density is very important, the bit-cells have very small transistors. Additionally, they are typically built into large arrays, which have very large bit-line capacitances. This results in a very slow (relatively) discharge of the bit-line by the bit-cell. This is the motivation for the speed aspect of a sense amplifier. It probably doesn't apply to you because you can use large transistors (since they're discrete, or in an array), and your array is small.
The isolation aspect of the sense amp is also very important. If you don't use a sense amp, your bit-line will have an unknown load based on whatever you hook up. Also, any noise on the signal will be broadcast to all your bit-cells. Some isolation is always a good idea here. Something as simple as a CMOS buffer/inverter will work just fine.
I don't think you're going to see a major benefit from using a comparator to sense the bit-lines. Instead, I would recommend that you use a CMOS inverter or buffer. It will be simpler, just as fast, and denser.

A: Unless you're trying to use the smallest transistors you can get away with to hold data, I'm not clear why you would need sense amplifiers.  Wouldn't the data latches and passgates themselves provide enough strength to drive a normal logic input?
Actually, I would expect that the simplest way to get a 16x5 RAM would be to simply use a 32Kx8 SRAM and ignore the upper part.  Otherwise depending upon your you might be able to use something like a dual 64-bit shift register chip which has taps every 16 bits.  Combining that with a 74LS374 or equivalent along with suitable clocking logic you should be able to store 80 bits fairly nicely and access them five at a time.

A: If you are not shooting for top speed(>1Mhz), you don't need any sense amplifiers.
Standard 2T trigger  (plus some Ts for accessing the data) would give you close to 0 and VCC voltages.

A: (a) Are you using an off-the-shelf SRAM IC chip? If so, it already includes the sense amplifier -- the bitlines cannot be accessed from the outside, even if you wanted to.
(b) Are you not using an SRAM IC chip? I.e., are you storing a few bits in a D latch or a shift register IC chip or are you building something out of 3 000 discrete transistors? If so, then you don't need a sense amplifier. As supercat mentioned, the output transistors of those devices is much larger than the tiny transistors inside a chip, and so that output can directly feed a digital input -- at worst you might need some digital inverter/tristate/line-driver/buffer to give you better fanout.
Do you actually have something -- such as, say, magnetic core memory -- that needs a sense amplifier? While I doubt that is actually the case, if so, the LM339 may work fine for you -- please tell use what you are actually building.


text:
Q: Is numpy reusing memory from unused arrays? While implementing some Gauss-Seidel solver with Python and Numpy I discovered an interesting side effect.
I tried to extract some minimal example:

    number = 1000
    startup = 'import numpy as np;N = 2048;X = np.arange(N * N).reshape((N, N));'
    startup2 = startup + 'np.empty_like(X)'

    example = ('X[1:: 2, : -1: 2] = ('
               'X[: -1: 2, 1:: 2] +'
               'X[1:: 2, : -1: 2] +'
               'X[1:: 2, : -1: 2] +'
               'X[: -1: 2, : -1: 2])/4')

running print(timeit.timeit(example, setup=startup, number=number)) takes at my machine ~5s
while print(timeit.timeit(example, setup=startup2, number=number)) takes ~4s.
So around ~1s faster, although there is this unnecessary array allocation withnp.emtpy_like(X). I observed this effect on various machines and with various array sizes or iterations.
I assume that calculation of the right hand side in the assignment leads to an temporally array allocation.
It seems that Numpy somehow reuses the unused array that was created with thenp.emtpy_like(X) to speed up the temporally array allocation.
Am I right with this assumption or is something totally different the reason for the differences in the time?
If I remove the /4 to
 example = ('X[1:: 2, : -1: 2] = ('
               'X[: -1: 2, 1:: 2] +'
               'X[1:: 2, : -1: 2] +'
               'X[1:: 2, : -1: 2] +'
               'X[: -1: 2, : -1: 2])')

Then, I can not observe differences in the execution time between the different versions. So I assume that in this case the calculation can be done in-place and then there is no temporally allocation.
Is there a more explicit way to exploit this effect? Just writing np.emtpy_like(X)` looks somehow "hacky" to me.
Thanks in advance!
Updates:
Thank you for your answers and comments so far.
Finally I found some more time to mess around with my observations and I am not sure if I my explanations above are clear enough.
So my initial observation was, that this
    number = 1000
    N = 1024
    X = np.arange(N * N).reshape((N, N))
    np.empty_like(X)
    for _ in range(number):
        X[1:: 2, : -1: 2] = (X[: -1: 2, 1:: 2] + X[1:: 2, : -1: 2] +
                             X[1:: 2, : -1: 2] + X[: -1: 2, : -1: 2]) / 4

was faster then this
    number = 1000
    N = 1024
    X = np.arange(N * N).reshape((N, N))
    for _ in range(number):
        X[1:: 2, : -1: 2] = (X[: -1: 2, 1:: 2] + X[1:: 2, : -1: 2] +
                             X[1:: 2, : -1: 2] + X[: -1: 2, : -1: 2]) / 4

Which I found quiet surprising, because this totally unused and unnecessary array allocation with the np.empty_like(X) seems to accelerate the loop below.
Thereby, it does not matter if I use np.empty_like , zeros_like, ones_like, ones(X.shape) or X.copy() as long there is a unused array  allocated.
And it also occurs for different N's, number of iterations and on different machines.
Furthermore I tried to investigate the issue with the tracemalloc package:
   number = 1000
   N = 1024
   X = np.arange(N * N).reshape((N, N))
   tracemalloc.start()
   np.empty_like(X)
   for _ in range(number):
       X[1:: 2, : -1: 2] = (X[: -1: 2, 1:: 2] + X[1:: 2, : -1: 2] +
                            X[1:: 2, : -1: 2] + X[: -1: 2, : -1: 2]) / 4
   s2 = tracemalloc.take_snapshot()

   display_top(s2)

Where display_top is the method from the Documentation, except that I print out in Bytes not in KB.
When I run it without the extra array allocation from np.empty_like(X) I get some output like this:
Top 10 lines
#1: ./minexample.py:40: 160.0 B
    X[1:: 2, : -1: 2] = (X[: -1: 2, 1:: 2] + X[1:: 2, : -1: 2] + X[1:: 2, : -1: 2] + X[: -1: 2, : -1: 2]) / 4
#2: ./minexample.py:39: 28.0 B
    for _ in range(1000):
Total allocated size: 188.0 B

With the extra allocation I get this:
Top 10 lines
#1: ./minexample.py:40: 128.0 B
    X[1:: 2, : -1: 2] = (X[: -1: 2, 1:: 2] + X[1:: 2, : -1: 2] + X[1:: 2, : -1: 2] + X[: -1: 2, : -1: 2]) / 4
#2: ./minexample.py:38: 32.0 B
    np.empty_like(X)
#3: ./minexample.py:39: 28.0 B
    for _ in range(1000):
Total allocated size: 188.0 B

So the size that is allocated of the line in the loop is smaller then when there is no unused array preallocated. So it seems to me that this unused array is reused.
Maybe this explains this effect?

A: empty_like(X) initializes an array (or matrix) with the same dimensions as X and fills it with random values, which is an incredibly fast process. But keep in mind that + empty_like(X) does not give you the desired result ( you would need zeros_like(X) )!
Why it's fast to add two arrays in numpy has to do with densely packed arrays and is described here: https://stackoverflow.com/a/8385658/14344821, this can potentially be faster than creating the matrix X with explicitly mentioned entries.
Tips on how to create numpy arrays efficiently can be found here.