text:
Q: ServiceStack SSE gives ERR_INVALID_CHUNKED_ENCODING in Chrome if CORS Using ServiceStack's Server Events feature I can sync two browsers if there are no cross-origin HTTP requests involved. It works as simple as documented:
(1) Plugins.Add(new ServerEventsFeature());
(2) A SyncRequest endpoint:
    [Route("/channels/{Channel}/sync", "POST")]
    public class SyncRequest : IReturnVoid
    {
        public string From { get; set; }
        public string ToUserId { get; set; }
        public string Channel { get; set; }
        public string Message { get; set; }
        public string Selector { get; set; }
    }
    public class SyncService : Service
    {
        public IServerEvents ServerEvents { get; set; }

        public void Any(SyncRequest request)
        {
            ServerEvents.NotifyChannel(request.Channel, "sync", request.From);
        }
    }

(3) In browser:
    var mychannel = 'example';
    var source= new EventSource(`${serviceUrl}/event-stream?channel={mychannel}`);
    source.onmessage = (m) => {}; // etc.

With this I can sync the browsers by calling the SyncRequest endpoint (in one browser) and processing the message that comes out of the EventSource in the other browser.
However, if the sync server is on another domain and cross-origin HTTP requests are needed, it fails.
Plugins.Add(new CorsFeature(...)) appears to work after a while, but in Chrome (on Linux) I first see ERR_INVALID_CHUNKED_ENCODING errors in the console.
On the internet I see claims that Chrome is strict w.r.t. chunked encoding and that this may cause these ERR_INVALID_CHUNKED_ENCODING errors. I also see that the response to the /event-stream call has a Transfer-Encoding:chunked header but I don't know if this is indeed the cause and if so how to get rid of it.
In another question on ServiceStack's SSE plus CORS mythz suggests that response headers can be changed like so:
    Plugins.Add(new ServerEventsFeature {
        OnInit = request => {
            request.Response.AddHeader("Transfer-Encoding", "identity");
        },
        OnHeartbeatInit = request => {
            request.Response.AddHeader("Transfer-Encoding", "identity");
        }
    });

but this has no effect on the /event-stream?channel=example call - its Response Headers include Transfer-Encoding:chunked (and the heartbeat has Transfer-Encoding:identity by default).
Now the browser keeps trying to re-establish the connection using /event-stream?channel=example and the first time it succeeds we are good - the EventSource objects work, the heartbeats happen, and syncing is possible.
I am using ServiceStack/4.512 NET45 Unix/Mono.
So the question is: Is there a way to immediately establish an SSE connection without the ERR_INVALID_CHUNKED_ENCODING errors? Maybe ServiceStack has the common error referred to in another question?

A: Chunked Transfer-Encoding is normal for Server Sent Events's long-running HTTP Response where the length is not known. The issue is likely due in Mono's HTTP implementation, if you're running on Linux/OSX it's recommended to run ServiceStack on .NET Core instead which is the supported option.


text:
Q: Visual Studio: how to control specific configuration parameters on student PCs? Can anyone tell me how to control default configuration parameters in VS 2017 C++?  The scenario is that we generate one sample PC with the software we want (Win10, VS2017, et cetera), and this image is cloned onto about 100 PCs in student CS labs.
The two specific things I would like to control are (1) use of precompiled headers and (2) message C4706 (= versus == in an if condition).  There are some others, but these are at top of the list.
I know students could fix this themselves, but so many are confused in the first few weeks of an introductory programming class that I don't want to try that.
A search of MSDN has not been productive, but I probably am using the wrong search terms.
Thank you in advance!

A: You could also edit the default platform property pages found at \\AppData\Local\Microsoft\MSBuild\v4.0, Microsoft.Cpp.Win32.user.props and Microsoft.Cpp.x64.user.props
I'm not sure how you would automatically distribute those files but so long as you are using MSBuild as the build system anything in those files is picked up prior to project-specific settings.

A: There are two ways I can think of:

*

*Change the default settings in property pages for each configuration

*Create a custom project template with all the project settings necessary. This will only affect new projects created with this template. Also it will keep the default template intact and will probably allow students to experiment a bit more.

A: For enabling Precompiled header.
Right click your project->Properties->( a property pages window appears)Configuration Properties-> C/C++ -> Precompiled Headers -> (on the right side) Select Use(/Yu) by clicking Precompiled Header.
And for suppressing C4706, set compiler warning to level less than 4
Right click your project->Properties->( a property pages window appears)Configuration Properties-> C/C++ -> General ->Warning Level to less than 4
To retain the settings and share with others....
I do not have proper VS2017.... Can you try as said below.....
First export the existing project settings using
project(visual studio menu)->Export template.... continue and and save the template and make a note of the path....
usually by default the templates is saved in below path as a zip file.
C:\Users\<>\Documents\Visual Studio 2017\My Exported Templates
Now copy the zip file and and put it in
C:\Users\<>\Documents\Visual Studio 2017\Templates\ProjectTemplates\Visual C++ Project
Check if your template is automatically picked up.
If not open visual studio command prompt tool and run
devenv /installvstemplates.

redpajama_set_name: RedPajamaStackExchange


text:
Q: Finding tools/emulator.exe in Eclipse for Android I'm beginning to develop in Android, but I'm having some problems using Eclipse.
I just reinstalled the current SDK, but when attempting to show Eclipse the path, I get the following error:

Could not find C:\Program Files (x86)...droid\android-sdk\tools\emulator.exe!

I'm pretty sure that I located the correct folder..what exactly happened here? I was told that the new SDK wouldn't pose this problem.

A: Unzip your sdk zip somewhere, copy entire contents of tools directory, replace it with your actual sdk tools folder contents.
Restart eclipse if required.


text:
Q: Months range filter react Codesandbox I have tried to setup a months filter in the chart below-

I want to filter by month, like so

However, currently, I am not able to implement this in my code.
  export default class App extends Component {
  constructor(props) {
    super(props);
    const title = "chart-filter";
    const lessThanOrGreaterThan = "lessThan";
    const filterLimit = 100;
    const from = "0";
    const toMonth = "7";
    const months = [
      { month: "Jan", value: "0" },
      { month: "Feb", value: "1" },
      { month: "Mar", value: "2" },
      { month: "Apr", value: "3" },
      { month: "May", value: "4" },
      { month: "Jun", value: "5" },
      { month: "Jul", value: "6" },
      { month: "Aug", value: "7" }
    ];
    this.levelsArr = [
      "Jan",
      "Feb",
      "Mar",
      "April",
      "May",
      "June",
      "July",
      "Aug"
    ];
    this.chartData = {
      dataSet1: Array.from(
        { length: 8 },
        () => Math.floor(Math.random() * 590) + 10
      ),
      dataSet2: Array.from(
        { length: 8 },
        () => Math.floor(Math.random() * 590) + 10
      )
    };
    this.state = {
      months: [
        { month: "Jan", value: "0" },
        { month: "Feb", value: "1" },
        { month: "Mar", value: "2" },
        { month: "Apr", value: "3" },
        { month: "May", value: "4" },
        { month: "Jun", value: "5" },
        { month: "Jul", value: "6" },
        { month: "Aug", value: "7" }
      ],
      from: "0",
      toMonth: "7"
    };
  }
  componentDidMount() {
    this.barChart = new Chart("bar", {
      type: "bar",
      options: {
        responsive: true,
        title: {
          display: true,
          text: "Student Admission Data"
        }
      },
      data: {
        labels: ["Jan", "Feb", "Mar", "April", "May", "June", "July", "Aug"],
        datasets: [
          {
            type: "bar",
            label: "School 1",
            data: this.chartData.dataSet1,
            backgroundColor: "rgba(20,200,10,0.4)",
            borderColor: "rgba(20,200,10,0.4)",
            fill: false
          },
          {
            type: "bar",
            label: "School 2",
            data: this.chartData.dataSet2,
            backgroundColor: "rgba(100,189,200,0.4)",
            borderColor: "rgba(100,189,200,0.4)",
            fill: false
          }
        ]
      }
    });
  }

  applyDateFilter() {
    this.barChart.data.labels = this.levelsArr.slice(
      parseInt(this.from),
      parseInt(this.toMonth) + 1
    );
    this.barChart.update();
  }
  render() {
    return (

          <canvas id="bar"></canvas>

            <select
              id="from"
              value={this.state.from}
              onChange={(e) => this.setState({ from: e.target.value })}
            >
              {this.state.months.map((el) => (
                <option value={el.value} key={el}>
                  {" "}
                  {el.month}{" "}
                </option>
              ))}
            </select>

            <select
              id="toMonth"
              value={this.state.toMonth}
              onChange={(e) => this.setState({ toMonth: e.target.value })}
            >
              {this.state.months.map((el) => (
                <option value={el.value} key={el}>
                  {" "}
                  {el.month}{" "}
                </option>
              ))}
            </select>

          <button class="button" onClick={() => this.applyDateFilter()}>
            Apply Date Filter
          </button>

    );
  }
}

Following is what this function is returning

It's only rendering Jan to Jan, no matter what month range I select. I think the issue is with how select is defined. Variables 'from' and 'toMonth' are not getting updated for some reason.

A: your problem is with applyDateFilter function, you need to extract the "from" and "toMonth" from state
change this:
  applyDateFilter() {
    this.barChart.data.labels = this.levelsArr.slice(
      parseInt(this.from),
      parseInt(this.toMonth) + 1
    );
    this.barChart.update();
  }

to this:
  applyDateFilter() {
    this.barChart.data.labels = this.levelsArr.slice(
      parseInt(this.state.from),
      parseInt(this.state.toMonth) + 1
    );
    this.barChart.update();
  }

forked sandbox


text:
Q: error cannot simplicity convert string to system.collection.generic.ienumerable on view Problem

Error: Cannot simplicity convert string to
  System.Collection.Generic.IEnumerable on view
  of index

Details
I need to display every department and his employees following to it in tree view using jtree I downloaded from nuget in MVC 5 Visual Studio 2015 as department parent and children employee:
Sales (parent)
michel (children)
divid (children)
My database data as following:
SELECT dbo.Departments.DepartmentName, dbo.Employee.EmployeeName, dbo.Employee.DepartmentID
FROM dbo.Employee
INNER JOIN dbo.Departments
ON dbo.Employee.DepartmentID = dbo.Departments.DepartmentID

And treeviewhelper class has following function for children:
 public TreeView<T> Children(Func<T, IEnumerable<T>> selector)
 {
            //  if (selector == null) //throw new ArgumentNullException("selector");
            _childrenProperty = selector;
            return this;
 }

My employee controller as following:
public class EmployeeController : Controller
{
        // GET: Employee
        HRSystem hr = new HRSystem();
        public ActionResult Index()
        {
            IEnumerable<Employee> catgory1 = hr.Employees.Where(x => !x.DepartmentID.HasValue).ToList();
            return View(catgory1);
        }
}

My error show on view of index as following:
@model IEnumerable<EmployeeSystem.Employee>
@using System.Web.UI.WebControls
@using EmployeeSystem.Models;

TreeView

<link href="~/Content/jsTree/themes/default/style.min.css" rel="stylesheet" />

        @(Html.TreeView(Model)
                              .EmptyContent("root")
                              .Children(m=>m.EmployeeName)
                              .HtmlAttributes(new { id = "tree" })
                          .ChildrenHtmlAttributes(new { @class = "subItem" })
                              .ItemText(m => m.EmployeeName)
                              .ItemTemplate(
        @<text>
            @item.EmployeeName
        </text>)
        )

Employee model
public partial class Employee
{

        [Key]
        public int EmployeeNo { get; set; }
        [StringLength(100)]
        public string EmployeeName { get; set; }
        public int? DepartmentID { get; set; }
        public virtual Department Department { get; set; }

}

Department model
 public partial class Department
 {

        public Department()
        {
            Employees = new HashSet<Employee>();
        }

        public int DepartmentID { get; set; }

        [StringLength(50)]
        public string DepartmentName { get; set; }
        public virtual ICollection<Employee> Employees { get; set; }
}

Error displayed on line Children(m=>m.EmployeeName) on view of index.
How to solve it?

A: The reason behind exception is obvious: you're assigning EmployeeName string property to Children method of TreeView helper which expects ICollection<T> property.
Consider adding ICollection<T> property as noted in this article inside Employee class like this:
public partial class Employee
{
    [Key]
    public int EmployeeNo { get; set; }
    [StringLength(100)]
    public string EmployeeName { get; set; }
    public int? DepartmentID { get; set; }
    public virtual Department Department { get; set; }

    // add this property
    public virtual ICollection<Employee> EmployeeChilds { get; set; }
}

Then, use that virtual property to Children method of TreeView:
@(Html.TreeView(Model)
      .EmptyContent("root")
      .Children(m => m.EmployeeChilds) // insert ICollection property here
      .HtmlAttributes(new { id = "tree" })
      .ChildrenHtmlAttributes(new { @class = "subItem" })
      .ItemText(m => m.EmployeeName)
      .ItemTemplate(
        @<text>
            @item.EmployeeName
        </text>)
)

You can see example implementation of MVC TreeView in this reference:
Creating TreeView For MVC 5


text:
Q: Does $\mathbb{P}(X\leq5)$ mean $\mathbb{P}(X=0)+..+\mathbb{P}(X=5)$ Does $\mathbb{P}(X\leq5)$ mean $\mathbb{P}(X=0)+..+\mathbb{P}(X=5)$?
Edit:X ist hypergeometric distributed.
If so, is the following equation correct?
$1-(\mathbb{P}(X\leq5)-\mathbb{P}(X\leq2))=\\= 1-(\mathbb{P}(X=0)+..+\mathbb{P}(X=5)) - (\mathbb{P}(X=0)+..+\mathbb{P}(X=2))\\=1-(\mathbb{P}(X=3)+..+\mathbb{P}(X=5))\\$

A: as $X$  folloes the hypergeometric distribution $X$ is a non-negative integer.
Then $\{ \omega: $X$(\omega) \le 5 \} = \bigcup_{i=0}^5 \{ \omega: $X$(\omega) = i \}$. As all the six sets in the R.H.S. are disjoint, the P-measure of their union equals the sum of their P-meausers.


text:
Q: Entries iterator in Google's logadmin never returns iterator.Done I'm using Google's logadmin package which comes in the logging package and trying to retrieve some logs by using a filter. Pretty simple... or so I thought. But the iterator never returns iterator.Done.
By looking at the opened issues in the package on GitHub and searching I couldn't find anything about it.
My code:
iter := client.Entries(ctx, logadmin.NewestFirst(),
    logadmin.Filter(
        fmt.Sprintf(`resource.type="cloud_function" resource.labels.function_name="%s"`, logger)))
var entries []string
for {
    select {
    case <-ctx.Done():
        return nil
    default:
        entry, err := iter.Next()
        log.Print(fmt.Sprintf("[%s] [LEVEL]: %s\n [PAYLOAD]: %s\n [TIMESTAMP]: %s\n\n", logger,
            entry.Severity, entry.Payload, entry.Timestamp.String()))
        if err == iterator.Done {
            return nil
        }
        if err != nil {
            return err
        }
    }
}

A: I manage to solve the problem by adding a timestamp to my filter as follows:
now := time.Now().Add(-24 * time.Hour).Format(time.RFC3339)
filter := fmt.Sprintf(`resource.type="cloud_function" resource.labels.function_name="%s" timestamp > %s`, logger, now)


text:
Q: How to generate vertex-transitive tilings? It is trivial to construct vertex-transitive polytopes: choose any finite matrix group $\Gamma\subseteq\mathrm O(\Bbb R^d)$ and some point $v\in\Bbb R^d$. Take the convex hull of the orbit $\Gamma v$, then this defined the orbit polytope
$$\mathrm{Orb}(\Gamma,v):=\mathrm{conv}(\Gamma v),$$
which is vertex-transitive (i.e. for any two vertices there is a symmetry of the polytope mapping the first vertex to the second).

Question: Is there a simiar way to generate an abundance of vertex-transitive tilings of $\Bbb R^d$?

By tiling I mean a face-to-face tiling of $\Bbb R^d$ by convex polytopes.

Update
I just had the following idea: take any lattice $\Lambda\subseteq\Bbb R^d$ and consider the Vornoi decomposition of $\Bbb R^d$ w.r.t this lattice. It is cell-transitive. So we compute its dual, which should then be vertex-transitive. Do we get the dual as the Vornoi decomposition of $\Bbb R^d$ w.r.t the vertices of the first Vornoi decomposition? I am not sure.

A: As you noted in the comments, the problem with $\mathbb R^d$ is that it's flat, and the convex hull of a set of points "forgets about" the interior points.
Consider the mapping from $\mathbb R^d$ to a paraboloid in $\mathbb R^{d+1}$ defined by
$$x=x_1e_1+\cdots+x_de_d\mapsto$$
$$x^\smile=x+\tfrac12x^2e_{d+1}$$
$$=x_1e_1+\cdots+x_de_d+\tfrac12(x_1^2+\cdots+x_d^2)e_{d+1}$$
where $e_i$ are basis vectors. This gives us a curved model of Euclidean space. It's not intrinsic curvature, though; if we use a degenerate dot product on $\mathbb R^{d+1}$, with $e_i\cdot e_j=(1-\delta_{i,d+1})\delta_{i,j}$, then the resulting geometry on the paraboloid is ordinary Euclidean geometry.
Furthermore, translations, rotations, reflections, etc. can be induced by affine transformations on $\mathbb R^{d+1}$. We need only consider reflections, since other Euclidean transformations are compositions of these. Let $y\in\mathbb R^d$ be any point, and $u\in\mathbb R^d$ any unit vector, normal to a hyperplane passing through $y$. Then the reflection of $x\in\mathbb R^d$ across this hyperplane is
$$x\mapsto$$
$$x-2\big((x-y)\cdot u\big)u.$$
Now consider this affine transformation on $\mathbb R^{d+1}$:
$$x+x_{d+1}e_{d+1}\mapsto$$
$$x+x_{d+1}e_{d+1}-2\big((x-y)\cdot u\big)\big(u+(y\cdot u)e_{d+1}\big).$$
(Notice that $u+(y\cdot u)e_{d+1}=u_y^\smile$ is a tangent vector to the paraboloid at the point $y^\smile$, and that factor in the middle is $(x-y)\cdot u=(x+x_{d+1}e_{d+1}-y^\smile)\cdot u_y^\smile$ using the degenerate dot product.)
Its restriction to the paraboloid is
$$x^\smile\mapsto$$
$$x+\tfrac12x^2e_{d+1}-2\big((x-y)\cdot u\big)\big(u+(y\cdot u)e_{d+1}\big)$$
$$=\Big(x-2\big((x-y)\cdot u\big)u\Big)+\tfrac12\Big(x-2\big((x-y)\cdot u\big)u\Big)^2e_{d+1}$$
$$=\Big(x-2\big((x-y)\cdot u\big)u\Big)^\smile$$
which has the same effect as the reflection on $\mathbb R^d$.
Using this, you should be able to express any Euclidean isometry group in terms of these non-Euclidean reflections on $\mathbb R^{d+1}$. Then you can take the convex hull of the orbit of any point $x^\smile$, find the hull's faces, and project these back onto $\mathbb R^d$.
Note that the convex hull of a set $S$ has $F(\text{conv}(S))=\text{conv}(F(S))$ for any affine transformation $F$, so it doesn't matter where the origin is in $\mathbb R^d$, or where the vertex of the paraboloid is.
Since the paraboloid is strictly convex, no points are "forgotten" (absorbed into the convex hulls of other points).
Any face of the convex hull which is unbounded must be vertical (its covector must have no $e^{d+1}$ component). Equivalently, any non-vertical face is bounded. For, if a face is defined by $\alpha_1x_1+\cdots+\alpha_dx_d+x_{d+1}=b$, since the convex hull is above the paraboloid, we have $x_{d+1}\geq\tfrac12x^2$ and thus $\alpha_1x_1+\cdots+\alpha_dx_d+\tfrac12x^2\leq b$, which describes a ball in $\mathbb R^d$. So $x_1,\cdots,x_d$ are bounded, and it follows that $x_{d+1}=b-\alpha_1x_1-\cdots-\alpha_dx_d$ is also bounded.
With a vertical face, all of the points in $\mathbb R^d$ are on one side of a hyperplane. So if your chosen group is cocompact, then any point's orbit crosses any hyperplane, and each face must be bounded.
If your chosen group is discrete, then each bounded face must be the convex hull of a finite set of points. (Otherwise the points would accumulate and not be discrete.)


text:
Q: CAML Query to Get Single List Item Failing So this is about the third script I've copied (this time from C# Corner) in an attempt to get a CAML query working but as with the others, I can't get it to work. Starting to get pretty upset about it tbh.
I need it to pick a single item from 'DSHaveYouMet' based on the number field 'scriptIndex' (this will be passed in as a variable but doing it with manual values atm). I've set up a page with the list in an App Part and a Script Editor WP with the code below in it. Every time I hit the button to trigger the async function, it returns the onFailedCallBack error; no errors in the F12 console either before or after clicking the button, not even a warning.
Code I'm using below:

<button onclick=" queryListItems ()">Click here to Create a List</button>

Any ideas?

A: You have missed <Eq></Eq>
try following query
<View><Query><Where><Eq><FieldRef Name='ID' /><Value Type='Number'>234</Value></Where></Eq></Query></View>

Or If you want to get Item using ID Instated of caml Query getItemById() method.
Try following code.
function queryListItems() {
         //Get the current context
         var context = new SP.ClientContext();
         //Get the Announcements list. Alter this code to match the name of your list
         var list = context.get_web().get_lists().getByTitle('DSHaveYouMet');
         var item=  list.getItemById(234);
         context.load(item);
         //Run the query asynchronously, passing the functions to call when a response arrives
         context.executeQueryAsync(onSucceededCallback, onFailedCallback);
      }


text:
Q: Issues with using a logitech streamcam, system unstable I connected my Logitech Streamcam to my Ubuntu 20.04.1 installation. After minutes of uptime I get extreme slowdowns and the system gets very laggy. After a reboot everything is fine.
Furthermore I use a Focusrite USB Audio Interface, connected via USB as well, which might be related to this issue.
When disconnecting the Streamcam before booting, the system runs fine.
These are the logs related to the failure:
kernel: usb 2-1: device descriptor read/8, error -110
kernel: usb 2-1: reset SuperSpeed Gen 1 USB device number 2 using xhci_hcd
kernel: usb 2-1: device descriptor read/8, error -110
kernel: usb 2-1: USB disconnect, device number 2
/usr/lib/gdm3/gdm-x-session[1668]: (II) config/udev: removing device Logitech StreamCam
/usr/lib/gdm3/gdm-x-session[1668]: (**) Option "fd" "58"
/usr/lib/gdm3/gdm-x-session[1668]: (II) event21 - Logitech StreamCam: device removed
/usr/lib/gdm3/gdm-x-session[1113]: (II) config/udev: removing device Logitech StreamCam
/usr/lib/gdm3/gdm-x-session[1113]: (II) UnloadModule: "libinput"
/usr/lib/gdm3/gdm-x-session[1113]: (II) systemd-logind: releasing fd for 13:85
/usr/lib/gdm3/gdm-x-session[1668]: (II) UnloadModule: "libinput"
/usr/lib/gdm3/gdm-x-session[1668]: (II) systemd-logind: releasing fd for 13:85
gsd-media-keys[1428]: Unable to get default source
gsd-media-keys[1977]: Unable to get default source
kernel: usb 2-1: new SuperSpeed Gen 1 USB device number 3 using xhci_hcd
systemd[1]: NetworkManager-dispatcher.service: Succeeded.
kernel: usb 2-1: device descriptor read/8, error -110
kernel: usb 2-1: new SuperSpeed Gen 1 USB device number 3 using xhci_hcd
kernel: usb 2-1: device descriptor read/8, error -110
kernel: usb 2-1: new SuperSpeed Gen 1 USB device number 4 using xhci_hcd
kernel: usb 2-1: device descriptor read/8, error -110
kernel: usb 2-1: new SuperSpeed Gen 1 USB device number 4 using xhci_hcd
kernel: usb 1-2.4: 2:1: usb_set_interface failed (-110)
...

This might be related to this. But I am not sure on how to fix it, if it is even fixable or if it is a bug in the kernel.
kernel: usb 1-2.4: 2:1: usb_set_interface failed (-110)
pulseaudio[1577]: Failed to set hardware parameters: Input/output error

keeps repeating forever, and the streamcam is no longer detectable. (And the system unusable).
I don't need the audio to be working on the streamcam, just the camera itself has to work.


text:
Q: ManagedIdentityCredential for Azure RelayManagementClient For Azure Key Vault I use DefaultAzureCredential. This works great when developing locally and when published to Azure using the app identity. I do not need to store any id's or secrets in the application.
I also need to utilize the RelayManagementClient to manage (CRUD) hybrid connections from the application. I'm unable to find a similar approach to authorization using the Microsoft.Azure.Management.Relay package. The constructor for this client accepts a ServiceClientCredentials instance of which there are three derived classes; BasicAuthenticationCredentials, CertificateCredentials and TokenCredentials - none of which are suitable.
I create an instance of ServiceClientCredentials by calling
SdkContext.AzureCredentialsFactory
   .FromServicePrincipal(config.ClientId,
                        config.ClientSecret,
                        config.TenantId,
                        AzureEnvironment.AzureGlobalCloud);

But this way I expose the the azure tenant details in the configuration. This isn't such a big problem initially as the config is secured, but I wonder if it's possible to use ManagedIdentityCredentials for this client?
I could store these values in a KeyVault which used the managed identity credentials, but perhaps someone has done this previously.
EDIT:
This is code for adding AzureCredentials to DI container.
services.AddSingleton(SdkContext.AzureCredentialsFactory.FromSystemAssignedManagedServiceIdentity(MSIResourceType.AppService, AzureEnvironment.AzureGlobalCloud));

A: Yes, you could use managed identity to auth, just use  FromSystemAssignedManagedServiceIdentity or FromUserAssigedManagedServiceIdentity instead of FromServicePrincipal when creating the instance of ServiceClientCredentials. The first one is for system-assigned managed identity, the second one is for user-assigned managed identity.


text:
Q: How to pass multiple classNames as props with css modules I can't seem to understand how to pass a string with multiple classNames as a prop using css modules? I have different classes i use everywhere for the button, and so i have on class for when it's active, and another when it's inactive. I also have different color schemes i pass.
Button:
import styles from "./Button.module.css";

const Button = (props) => {

  return (
    <button className={`${styles.standardButton} ${styles[props.className]}`}>

{props.text}

    </button>
  );
};

export default Button;

And here is the page which uses the button. The button function is at the bottom, and some input fields needs to be filled out in order for it to be "active".
import React, { useState } from "react";

import Input from "../input/Input";
import Select from "../input/Select";
import Button from "../input/Button";

const CreateJobPage1 = (props) => {
  const [enteredName, setEnteredName] = useState("");
  const [enteredCompany, setEnteredCompany] = useState("");
  const [enteredLocation, setEnteredLocation] = useState("");
  const [enteredText, setEnteredText] = useState("");
  const [projectType, setProjectType] = useState('DEFAULT');

  const projectTypes = ["shortfilm", "fiction", "commercial", "arthouse", "animation"];

  const nameChangeHandler = (props) => {
    setEnteredName(props);
  };
  const companyChangeHandler = (props) => {
    setEnteredCompany(props);
  };
  const locationChangeHandler = (props) => {
    setEnteredLocation(props);
  };
  const textChangeHandler = (props) => {
    setEnteredText(props);
  };
  const projectTypeHandler = (props) => {
    setProjectType(props);
  };

  return (

        <Input
          placeholder="What's the project name?"
          enteredValue={enteredName}
          onChange={nameChangeHandler}
        />
        <Input
          placeholder="What's the production company?"
          enteredValue={enteredCompany}
          onChange={companyChangeHandler}
        />
        <Input
          placeholder="Where's the project located?"
          enteredValue={enteredLocation}
          onChange={locationChangeHandler}
        />
        <Select
          placeholder="Choose project type"
          options={projectTypes}
          value={projectType}
          onChangeOption={projectTypeHandler}
        />
        <Input
          placeholder="What's the project about?"
          enteredValue={enteredText}
          onChange={textChangeHandler}
          formulaType="textarea"
        />
        <Button
          className={enteredName === "" || enteredCompany === "" || enteredLocation === "" || projectType === "DEFAULT" ? ["isRed", "formButton", "inActive"] : ["isRed", "formButton"]}
          text={"Add Functions"}
        />

  );
};

export default CreateJobPage1;

A: const classNameTest = ['isRed', 'fontColor']

 {
          return styles[item] + ' '
        })}`}
      >

As I mentioned above in the comment,  all the styles in xxx.module.scss is mean to prevent different style files have duplicate className and they will effect each other globally. when you do styles.isRed the REAL class name will likely to be src-pages-YourFileName-module__isRed--SOMEUNIQUECODE

*

*when you try to pass them as props, u still need to access them by import styles

*when you do a map return u need to have space between each return so at the end html will know they are different class

*I still think is better to pass the status like isActive to control the component style. otherwise this component is not really fit the idea of a component


text:
Q: Alignment issue of the SlidingDrawer I have created a SlidingDrawer which content the list view i want to align the handle of the SlidingDrawer at the right corner of the screen but it always align at the center ...please suggest me how to solve this problem...
     <SlidingDrawer
    android:gravity="right"
    android:id="@+id/slidingDrawer"
    android:handle="@+id/drawerHandle"
    android:content="@+id/contentLayout"
    android:layout_width="wrap_content"
    android:layout_height="wrap_content">

    <Button
        android:id="@+id/drawerHandle"
        android:text="list"
        android:layout_height="wrap_content"

        android:layout_alignParentBottom="true"
    android:layout_alignParentRight="true"
    android:layout_width="wrap_content">
    </Button>

    <LinearLayout
        xmlns:android="http://schemas.android.com/apk/res/android"
        android:id="@+id/contentLayout"
        android:gravity="center"
        android:layout_width="fill_parent"
        android:layout_height="wrap_content"
        android:background="@android:color/black">
        <ListView
        android:id="@+id/list"
        android:layout_width="fill_parent" android:layout_height="wrap_content"/>

    </LinearLayout>
</SlidingDrawer>

A: something like this might work
    <LinearLayout  android:id="@+id/drawerHandle"
        android:layout_height="wrap_content"
        android:layout_width="fill_parent"
        android:background="@android:color/transparent
        android:gravity="right"
    >
      <Button
         android:text="list"
         android:layout_height="wrap_content"
         android:layout_width="wrap_content">
      </Button>
    </LinearLayout>


text:
Q: PHP code to modify a URL My current code is:
$scripturl.'main.php?i='.$app_id.'&s='.$app_secret."&n=".$n, 'response_type' => 'code'));

I want to add &display=touch to the end of the result URL, like so:
status_update%2Cuser_birthday%2Cpublish_stream&response_type=code&display=touch

If I add it in the above code like this: 'response_type' => 'code&display=touch'
The result URL shows up like this:
status_update%2Cuser_birthday%2Cpublish_stream&response_type=code%26display%3Dtouch

It converted & to %26 and = to %3D. How do i add &display=touch without triggering that effect?

A: Add 'display' => 'touch' as another element in the array:
$scripturl.'main.php?i='.$app_id.'&s='.$app_secret."&n=".$n, 'response_type' => 'code', 'display' => 'touch'));


text:
Q: HTML JS append random image in DIV Im trying to make a booster pack opening simulator
With this code it displays a random image
<!DOCTYPE html>

    <input class="randombutton" type="button" value="Open Pack" onclick="randomImg1()"/>

Would it be possible so when the image (The card) is generated its displayed and then when the button is pushed again it is put into a inventory of all the "Cards" you have opened so you can show other all the cards you have opened and then another card is generated and so on.
Thanks

A: You can append image to container instead of rewriting innerHTML with the new one. For example using appendChild method:
function randomImg1() {
    var myImages1 = new Array();
    myImages1[0] = "images/Myimage.png";
    myImages1[1] = "images/Myimage1.png";

    var rnd = Math.floor(Math.random() * myImages1.length);

    var img = new Image();
    img.src = myImages1[rnd];
    document.getElementById("image").appendChild(img);
}

or it can be simpler with insertAdjacentHTML method:
document.getElementById("image").insertAdjacentHTML("beforeend", "");

Also note, that you don't need  closing tag in case of img, but you do need var keyword in myImages1 variable declaration.


text:
Q: Finding The First Non-repeating Character algorithm Swift 4 (Looping over string only once) I am trying to solve code fights interview practice questions, but I am stuck on how to solve this particular problem in swift. My first thought was to use a dictionary with the counts of each character, but then I would have to iterate over the string again to compare, so that doesn't work per the restrictions. Any help would be good. Thank you. Here is the problem and requirements:
Note: Write a solution that only iterates over the string once and uses O(1) additional memory, since this is what you would be asked to do during a real interview.
Given a string s, find and return the first instance of a non-repeating character in it. If there is no such character, return '_'
Here is the code I started with (borrowed from another post)
func firstNotRepeatingCharacter(s: String) -> Character {

var countHash:[Character:Int] = [:]

    for character in s {
        countHash[character] = (countHash[character] ?? 0) + 1
    }

let nonRepeatingCharacters = s.filter({countHash[$0] == 1})

    let firstNonRepeatingCharacter = nonRepeatingCharacters.first!

return firstNonRepeatingCharacter

}

firstNotRepeatingCharacter(s:"abacabad")

A: You can create a dictionary to store the occurrences and use first(where:) method to return the first occurrence that happens only once:
Swift 4
func firstNotRepeatingCharacter(s: String) -> Character {
    var occurrences: [Character: Int] = [:]
    s.forEach{ occurrences[$0, default: 0] += 1 }
    return s.first{ occurrences[$0] == 1 } ?? "_"
}

Swift 3
func firstNotRepeatingCharacter(s: String) -> Character {
    var occurrences: [Character:Int] = [:]
    s.characters.forEach{ occurrences[$0] = (occurrences[$0] ?? 0) + 1}
    return s.characters.first{ occurrences[$0] == 1 } ?? "_"
}

Another option iterating the string in reversed order and using an array of 26 elements to store the characters occurrences
func firstNotRepeatingCharacter(s: String) -> Character {
    var chars = Array(repeating: 0, count: 26)
    var characters: [Character] = []
    var charIndex = 0
    var strIndex = 0
    s.characters.reversed().forEach {
        let index = Int(String($0).unicodeScalars.first!.value) - 97
        chars[index] += 1
        if chars[index] == 1 && strIndex >= charIndex {
            characters.append($0)
            charIndex = strIndex
        }
        strIndex += 1
    }
    return characters.reversed().first { chars[Int(String($0).unicodeScalars.first!.value) - 97] == 1 } ?? "_"
}

A: Use a dictionary to store the character counts as well as where they were first encountered. Then, loop over the dictionary (which is constant in size since there are only so many unique characters in the input string, thus also takes constant time to iterate) and find the earliest occurring character with a count of 1.
func firstUniqueCharacter(in s: String) -> Character
{
    var characters = [Character: (count: Int, firstIndex: Int)]()

    for (i, c) in s.characters.enumerated()
    {
        if let t = characters[c]
        {
            characters[c] = (t.count + 1, t.firstIndex)
        }
        else
        {
            characters[c] = (1, i)
        }
    }

    var firstUnique = (character: Character("_"), index: Int.max)
    for (k, v) in characters
    {
        if v.count == 1 && v.firstIndex <= firstUnique.index
        {
            firstUnique = (k, v.firstIndex)
        }
    }

    return firstUnique.character
}

A: Swift
Use dictionary, uniqueCharacter optional variable with unique characters array to store all uniquely present characters in the string , every time duplication of characters found should delete that character from unique characters array and same time it is the most first character then should update the dictionary with its count incremented , refer following snippet , how end of the iteration through all characters gives a FIRST NON REPEATED CHARACTER  in given String. Refer following code to understand it properly
func findFirstNonRepeatingCharacter(string:String) -> Character?{
    var uniqueChars:[Character] = []
    var uniqueChar:Character?
    var chars = string.lowercased().characters
    var charWithCount:[Character:Int] = [:]
    for char in chars{
        if let count = charWithCount[char] {   //amazon
            charWithCount[char] = count+1
            if char == uniqueChar{
                uniqueChars.removeFirst()
                uniqueChar = uniqueChars.first
            }
        }else{
            charWithCount[char] = 1
            uniqueChars.append(char)
            if uniqueChar == nil{
                uniqueChar = char
            }
        }
    }
    return uniqueChar
}
// Use
findFirstNonRepeatingCharacter(string: "eabcdee")


text:
Q: Removing first few entries in dynamo db list conditional on field values or on number of elements I have a dataset in dynamoDB which looks like this:
{
    "userID" : 2323423,    // Primary Key
    "lt" :  [
            {
                  "timestamp"   : epoch1,
                  "coordinates" : "coordinate1"
            },
            {
                  "timestamp"   : epoch2,
                  "coordinates" : "coordinate2"
            },
            ...
        ]
}

The "lt" is location-tracking list, which is intended to store the coordinate values for a userID at different times.
Q1 The requirement is:

*

*Store a maximum of 1 days worth of location tracking data per user, with the auto deletion happening only when the new LT coordinate data entry is received

*What this means is at a time, there could be stale LT data, all of which is of 24 hour duration. However, as soon as a new LT coordinate data comes, deletion of stale entries should happen such that entries older than 24 hours are removed.

I'm clear on how to append entries to a list, or even remove entries at a particular index from a list in dynamoDB.

UpdateExpression : "REMOVE lt[0]" - Remove one element
UpdateExpression : "REMOVE lt[0] lt[1]" - Remove elements 0 and 1

However, now the requirement is to remove entries from the beginning of the list, such that the entries older than 24 hours are removed from it. I've banged my head over this for very long, and there does not seem to be any conditional expression which helps us do that. Am I missing something?
Q2 As a workaround, I changed requirements to:

*

*Store last 100 entries into this "lt" list.

*This is going to keep potentially stale LT data for users in case their LT data is not received

If I receive N new LT points for a user, I want to remove the first "n" entries, if the total entries have become 100 + "n". If total entries are less than or equal to 100, no need to delete the entries.
I can obviously append new N entries into the User item's "lt" list, get that User Item back, find out total number of entries, and then remove the first "n" entries, but that would be inefficient, since I'll have to make two queries, one where I'll have to return the entire "lt" list.
It would help if the size of the "lt" list could be retrieved be via some sort of Count construct, is there one.
I want to understand how it should actually be done?

A: You do not need to model locations as a list. You could model them as a map, with HH:MM as the key of the map. In your update expression, just SET lt.#hhmm = :coord with ExpressionAttributeNames={#hhmm:"16:05"} and ExpressionAttributeValues={:coord:"0,0"}. If you record location once per minute, that means 24 * 60 = 1440 entries in the lt map. If each coordinate pair is 19 characters long, you have approximately 30 bytes per entry or around 43 KB per person if you record once per minute.
Using the scheme above, it would cost around 43 WCU per minute, or less than 1 WCU per second per user to maintain current location with minute granularity. This is kind of high for one customer. Instead, you could split up the user location item into 30 minute buckets, using 48 such items to cover a 24 hour span per person. Thus, the UpdateItem write cost would be 1 WCU per minute or 60 WCU per hour. The hash key would be of a form like <user_id>_HH:<00 or 30>.


text:
Q: Retrofit 2.0 Multipart Request, send boolean type in form data including file I am trying to upload a file using retrofit 2.0. Apart from file, I have few other params to be send with form data which include a boolean type also. My request declaration is -
@Multipart
    @POST("/upload/abc")
    Call<UploadResponse> uploadToServer(@Part("img_file\";filename=\"image") RequestBody file,
                                             @Part("access_token") RequestBody sessionKey,
                                             @Part("is_final") Boolean isFinal,
                                             @Part("sequence_id") Integer sequenceId,
                                             @Part("entity_id") RequestBody entityId,
                                             @Part("image_type") RequestBody imageType);

I am using GsonConverterFactory. I tried 2 approaches -
(1) Instead of @Part("is_final") Boolean isFinal I used @Part("is_final") RequestBody isFinal and sending it with RequestBody.create(MediaType.parse("text/plain"), String.valueOf(true))
(2) Using @Part("is_final") Boolean isFinal and sending with Boolean.true.
In both the cases, "is_final" received on server side is Unicode or as a String instead of boolean value.
What is the best way to achieve this

A: I made it work by -
Add compile 'com.squareup.retrofit2:converter-scalars:2.1.0' to the gradle file.
While creating retrofit instance, add
Retrofit retrofit = new Retrofit.Builder()
                .baseUrl("url")
                .client(builder.build())
                .addConverterFactory(ScalarsConverterFactory.create())
                .addConverterFactory(GsonConverterFactory.create())
                .build();

Now you can safely send primitive types with the request.
Example Request
Call<UploadResponse> uploadFile(@Part("img\"; filename=\"image") RequestBody file,
                                @Part("session_key") String sessionKey,
                                @Part("is_final") Boolean isFinal);

Call this method using -
RequestBody fBody = RequestBody.create(null, someFile);
service.uploadFile(fBody, "some_string_session", true);


text:
Q: Autogenerated codes of Database in Visual Studio I created a database in Visual Studio 2010 from Server Explorer. I want to see the auto generated codes created by Visual Studio. Where to find them?

A: There is no auto generated code. It creates a database on the server you specified in the Create New SQL Server Database dialog box.


text:
Q: VisualStudio InheritancePicker with Solution Folders Has anyone of you ever had the problem that when you try to create a new "User Control" with Visual Studio, that the grid with the possible classes to choose from is just empty?
I'm having this problem now. Everything worked just fine until i created some "Solution Folder" in my VS-Solution. I made this folders to structure my solution, because it has grown big over the time. I can still compile the solution, everything works just fine. The only problem I'm facing is that I can't create any "User Control" anymore. The "Inheritance Picker Window" is just empty... I could choose the assembly that contains the needed UserControls manually via "Browse..." but that is not a good solution, because it will have to statically reference the dll. I could also make the inheritance myself, without the "wizard" but then I'd have to edit the designer file to match the parent class...and that is nothing I want to do...
This problem only occurs when I have these "Solution Folder" in my solution. When I have all the projects on the same level without folders, then the "Inheritance Picker" works fine...
Is this a bug in VS (happens in 10 and 12), or am I doing something wrong?


text:
Q: I am unable to successfully import pywinauto into python 3.6.4 I began with a pip install of "pywinauto" and attempted to import it, and I initially I got a message saying that the module win32api was missing.  I attempted a pip install of that module but received a message saying that no satisfactory version could be found.
I then downloaded a copy of it from the web which when I tried to install it informed me that I don't have Python 3.6 installed on my system(!)
I had a number of installations of earlier versions and worried that they might be causing a problem so I deleted them and tried again, no success.  The path to my executable is C:\Python36\python.exe.
I went to the site-packages folder and deleted the pywinauto and pywinauto-0.6.4-py3.6.egg-info folders and did a fresh pip install which concluded with the message: "Successfully installed pywinauto-0.6.4" and attempted to import it again.
This time I got the following:
import pywinauto

File "C:\Python36\lib\site-packages\pywinauto\__init__.py", line 72, in <module>
from . import findwindows
File "C:\Python36\lib\site-packages\pywinauto\findwindows.py", line 42, in <module>
from . import controls
File "C:\Python36\lib\site-packages\pywinauto\controls\__init__.py", line 36, in <module>
from . import uiawrapper # register "uia" back-end (at the end of uiawrapper module)
File "C:\Python36\lib\site-packages\pywinauto\controls\uiawrapper.py", line 46, in <module>
from ..uia_defines import IUIA
File "C:\Python36\lib\site-packages\pywinauto\uia_defines.py", line 181, in <module>
pattern_ids = _build_pattern_ids_dic()
File "C:\Python36\lib\site-packages\pywinauto\uia_defines.py", line 169, in _build_pattern_ids_dic
if hasattr(IUIA().ui_automation_client, cls_name):
File "C:\Python36\lib\site-packages\pywinauto\uia_defines.py", line 50, in __call__
cls._instances[cls] = super(_Singleton, cls).__call__(*args, **kwargs)
File "C:\Python36\lib\site-packages\pywinauto\uia_defines.py", line 63, in __init__
self.ui_automation_client.CUIAutomation().IPersist_GetClassID(),
AttributeError: module 'comtypes.gen.UIAutomationClient' has no attribute 'CUIAutomation'

At this point I really don't know what to do.  It appears that one of the imported files is lacking something that another one needs.  I would be grateful for any ideas......

A: The correct dependency can be installed so:
pip install pywin32

Previously it was pypiwin32 but something is changed in these packages maintenance and pywin32 became official again. pywinauto 0.6.5 will reflect these changes soon.
The second issue looks like known comtypes issue with generating cache files for UI Automation type library. The workaround assumes running the script as Administrator at least first time to have an access to comtypes cache folder. Unfortunately comtypes maintainers are not so active and there are a number of pull requests with very similar fixes and they all still hang unaccepted.


text:
Q: How to display news in facebook mobile app How to display news / articles and display card type as some news sites do in facebook mobile app?

I am developing a WordPress site .

A: That's called Instant Articles.
A "light-weight" article format, specifically designed for mobile - a bit similar to Google's Accelerated Mobile Pages.
More information on how to prepare your content, how to publish it etc. can be found in the official documentation: https://developers.facebook.com/docs/instant-articles


text:
Q: How to find out the Hybris version of a server? Is there any specific way of finding out the Hybris version of a server.
I know that the hybris version appears in logs during server startup but I was wondering if it can be found somewhere in hac or backoffice. That way I will be able lookup the version deployed on a specific test machine.
I also know about the hac foot note which opens the popup mentioning the OS, the number of CPUs, and the version. But for older versions of Hybris the version is not included.

A: You can check the hybris version by navigating to hybris\bin\platform and opening the file named build.number. It should have content similar to the below content :
#Ant properties
#Tue Dec 12 15:56:57 CET 2017
builddate=20171212 1548
releasedate=20171212 1548
vendor=hybris
version=6.5.0.4
version.api=6.5.0

A: You can see the platform version from hac -> Platform -> Configuration and look for the build.version property. The value should be the hybris version, and I think that still work for 5.x versions.
Or you can download some console logs to check for the startup version (using the uptime as a guide for what to download) also via hac -> Platform -> Support

A: Also, when the Hybris server starts, you can check the version. It would look something like this-
Starting up hybris server
Configuration:

Cluster:     disabled
Tenant:      master
Mode:        development
OS:          Mac OS X 10.13.6, x86_64
Database:    Pool: hybris - hsqldb, table prefix:
             SA - jdbc:hsqldb:file:/Users/abcd/Hybris/hybris/data/hsqldb/mydb;shutdown=true;hsqldb.tx=MVCC
Platform:    6.6.0.4
Java:        Oracle Corporation
             Java(TM) SE Runtime Environment, 1.8.0_191-b12
             /Library/Java/JavaVirtualMachines/jdk1.8.0_191.jdk/Contents/Home/jre
VM Locale:   language=en,country=US,region=null
Cache:       RegionCache is not yet initialized. [de.hybris.platform.cache.impl.RegionCacheAdapter]
Server type: tomcat

A: You can go to hac > Platform > Configuration and search for version.

A: There are two more options that can be used:

*

*"ant -p" should render also the Hybris Version

*Open  hybris/data/build.number


text:
Q: UML papyrus tool Here what i have done so far to create UML Diagrams from java code.

*

*Project -> right click-> Discovery -> Discoverer -> Discover KDM code from java project model –> You'll get a property dialog box at the serialization line make set it to TRUE that would generate a file project_KDM.xmi

*Right click that file -> Discovery -> Discoverer -> Discover UML model from KDM code again you'll get a property dialog set the serialization prop to TRUE to generate a file named project.UML

*create a folder in your project and copy that UML file to it, this is because sometimes when you delete the papyrus files along with UML files it messes up with the .project file and makes your project loses the Library runtime settings so just put them in that folder instead of main project folder "/" .

*now go to that folder you created, and pasted the UML file there, then right click on the project.uml file –> new –> papyrus model -> and finish

*This will create empty project.di file but it in someway references the uml (I wish I knew at the moment how to import the UML file and create so many *.di files but for now I don't so just do it the way i did)

*ALT+W -> show view -> papyrus model explorer

I am able to generate .uml from above steps.
When i right click on .uml i can not see any option "Initialize class diagram".
Do i need to intall any plugin/tool for this?
and how can i generate UML Diagrams from this .uml using papyrus tool?

A: When you have your .uml file open, you have to create diagrams in the model itself. To do that you have to open the "model explorer" view, trough usual window -> show view -> others -> Papyrus -> model explorer. Right click on a node in the explorer and select new diagram -> class diagram.


text:
Q: Send a value from an action link in an ASP.NET MVC app I have two tables, reports and comments.
In the Report_Index.HTML, I have something like this:
@foreach (var item in Model)
{

        @Html.DisplayFor(modelItem => item.TITLE)

        @Html.DisplayFor(modelItem => item.DETAILS)

        @Html.ActionLink("Edit", "Edit", new { id = item.REPORT_ID }) |
        @Html.ActionLink("Details", "Details", new { id = item.REPORT_ID }) |
        @Html.ActionLink("Delete", "Delete", new { id = item.REPORT_ID })
        @Html.ActionLink("Add comment", "Create","COMMENTs")

}

On the other hand, Create_Comments.HTML looks like this:

    @Html.LabelFor(model => model.ID_REPORTE, "ID_REPORTE", htmlAttributes: new { @class = "control-label col-md-2" })//

        @Html.DropDownList("ID_REPORTE", null, htmlAttributes: new { @class = "form-control" })
        @Html.ValidationMessageFor(model => model.ID_REPORTE, "", new { @class = "text-danger" })

My question is how can I send the value of TITLE from Report_Index.HTML to Create_Comments.HTML, so when I click on the action link it transfers, the value TITLE of the corresponding report, to the page where I create a comment.
Thanks in advance

A: on action link - @Html.ActionLink("Add comment", "Create","COMMENTs", new {title = "something"})
create action Create on COMMENTs controller with a string parameter call title
take the title from parameter and then pass it to view using viewmodel or viewbag


text:
Q: Should I minify javascript in userscripts for Greasemonkey or Chrome extensions? Is it worthwhile to minify a script that goes into an extension or userscript for Greasemonkey?  I ask because the user will just be downloading it once and running it many times (it's not part of the webpage).  Assume that it's about 50k uncompressed.
Will it save time for the user?  Is it significant or is most of the gain in the download speed?

A: Minifying javascript is only interesting for increasing the download speed. The execution of the javascript will not be faster.

A: Do not minify your code.  This helps others to understand it -- which is important because many people will not use a script unless they can be reasonably sure that it's not doing bad things.
Also, decent code makes it easier for users to help you debug problems and for other users to modify it to taste (We've all started on the backs of programmers that came before).
As the others stated, any speed/performance gains will be too small to measure.

A: It will reduce the download time, but most likely only slightly, and the user won't notice it. A webpage usually minifies js to save bandwidth and loading times, but in your case none of these are relevant.


text:
Q: How to apply WSS to mocked response in SoapUI? I have a SoapUI Mock Service. I would like it to use WS-Security.
I configured the project WS-Security Configurations, both Outgoing and Incoming.
I use a Test Suite to send a request and it is properly processed with Timestamp, Signature and Encrypt WSS Entries. But the response from the Mock Service is a plain text fault:
Missing operation for soapAction [] and body element
[{http://www.w3.org/2001/04/xmlenc#}EncryptedData] with SOAP Version [SOAP 1.1]

From this message I guess that the mock service did not recognize encryption HTML elements. Am I right?
Is there a way to encrypt SoapUI mock service responses using WS-Security?

A: It is possible. The options can be found after clicking on the mock service in the bottom left part of the screen (unlike all other configuration options that are available in popups). There you can choose outgoing and incoming security configuration set from a dropdown.
It is hidden so well that I ran into the problem twice within three months, performed a research and found my own unanswered question in StackOverflow before a friend showed me the solution.
So I post the answer should anyone need that.


text:
Q: Grails field pattern for different time formats I'm trying to use patterns for my gsp file in Grails. I want to check if the time entered is in the correct format.
For example: 12.15 == 12:15 == 12,15 == 12-15 and so on.
<g:field type="text" name="startTime" class="date" pattern="\\$##:##"/>
<g:field type="text" name="endTime" class="date" pattern="[0-9]{2}:[0-9]{2}" />

That's my code. The patterns are just some trys.
Maybe someone knows a solution.
Greetings
Nik

A: the pattern in your g:field tag will be pass into date template (for example: /_fields/date/_field.gsp) like you pass parameters into other templates. You can access it by ${pattern}.
You can use any validator such as bootstrap_validator or jquery_inputmask to do the task

A: I found a solution:
<g:textField name="startTime" class="date"
        value="${formatDate(format:'HH:mm',date:record.start)}" pattern="\\d{1,2}(:\\d{0,2})?" />
<g:textField name="endTime" class="date"
        value="${formatDate(format:'HH:mm',date:record.end)}" pattern="\\d{1,2}(:\\d{0,2})?"/>

I just skiped the part with different dots. Now it shows a warning if you use the wrong pattern.


text:
Q: Javascript/Jquery: issue with append in cycle I get Flickr gallery via API/Json. My issue with my code is that the gallery that I fetch has ~ 30 picture, but this snippet:
$.each(data.album.content,function (index,content)
        {
            album_container.append(column);
         [...]
}

Appends only one
 to the container, and not 30, but appends in right way 30 a/img to this unique column. I cannot figure why and how solve it.
Thank you for your help!
var album_container = $('div#album');

function callGetAjax(url)
{
    return $.get(url,{});
}

function getAlbum(feed_url)
{
    callGetAjax(absolute_path+'/feed/'+feed_url)
    .success(function(data)
    {
    })
    .error(function(xhr, statusText)
    {//console.log(statusText);
    })
    .done(function(data)
    {
        var loaded = 0;
        album_title = data.album.album_title;
        $('h1#gallery-title').html(album_title);
        var column  = $('

');
        $.each(data.album.content,function (index,content)
        {
            album_container.append(column);
            $('')
                .append($('').prop('src', content.photo))
                .prop('href', content.target)
                .prop('title', content.title)
                .attr('data-gallery', '')
                .appendTo(column)
                .colorbox({rel:'gallery', speed:0, maxWidth:'95%', maxHeight:'95%'});
        });

    });
}

Current HTML result:

 [...]

HTML that I need:

[...]

A: Remember that .append() will move the HTML node around the DOM tree when the node already exists in your document. In your case, you have declared:
var column  = $('

')

…outside of your $.each() loop, therefore causing it to be repeatedly moved around inside album_container, instead of being cloned as you have expected. Therefore, what you would do is to declare it within your loop, such that the instance is not outside the scope of your loop:
var album_container = $('div#album');

function callGetAjax(url)
{
    return $.get(url,{});
}

function getAlbum(feed_url)
{
    callGetAjax(absolute_path+'/feed/'+feed_url)
    .success(function(data)
    {
    })
    .error(function(xhr, statusText)
    {//console.log(statusText);
    })
    .done(function(data)
    {
        var loaded = 0;
        album_title = data.album.album_title;
        $('h1#gallery-title').html(album_title);

        $.each(data.album.content,function (index,content)
        {
            // Creates a new column for every image element
            var column  = $('

'),
                item = $('')
                    .append($('').attr('src', content.photo))
                    .attr('href', content.target)
                    .attr('title', content.title)
                    .attr('data-gallery', '')
                    .appendTo(column)
                    .colorbox({rel:'gallery', speed:0, maxWidth:'95%', maxHeight:'95%'});

            // Append column instance to the album container
            album_container.append(column);

        });

    });
}

If you're also looking for a review of your code, may I suggest you transition away from the jqXHR.success() and jqXHR.error() methods? They have been deprecated in favour of the jqXHR.done() and jqXHR.fail() methods. Using promises, we have a backbone that looks like this:
var album_container = $('div#album');

function callGetAjax(url)
{
    return $.get(url,{});
}

function getAlbum(feed_url)
{
    // Store returned promise from $.get() in a variable
    var ajaxCall = callGetAjax(absolute_path+'/feed/'+feed_url);

    // Now we listen to the promise
    ajaxCall
    .done(function(data) {

        var loaded = 0;
        album_title = data.album.album_title;
        $('h1#gallery-title').html(album_title);

        $.each(data.album.content,function (index,content)
        {

            var column  = $('

'),
                item = $('')
                    .append($('').attr('src', content.photo))
                    .attr({
                        'href': content.target,
                        'title': content.title,
                        'data-gallery': ''
                    })
                    .appendTo(column)
                    .colorbox({rel:'gallery', speed:0, maxWidth:'95%', maxHeight:'95%'});

            album_container.append(column);

        });

    })
     .fail(function(xhr, statusText) {
        // Log error
        // console.log(statusText);
    });
}


text:
Q: Runnable JAR not working with referenced libraries I want to create a runnable JAR that include referenced libraries, namely jackson,  in eclipse via the export. There used to be fat jar that seemed to be the goto solution before Eclipse offered to export to runnable JAR.
From this question, the first option would be what I'm looking for. Since it is for the moment a small project, it wouldn't be a problem to always have everything together (plus it's easier for me since I'm just starting with JARs, runnables and jnlp)
When I try to launch it, there's an alert window saying there was a problem and to try to find it in the console (which I can't get to open).
If I remove any use of this referenced library everything runs perfectly (except the part that it's not doing what I want at all). The window looks the way I designed it, but no functionality without the library.
I don't even have a stack trace to help with the problem. I've created other projects without any referenced libraries and everything is fine. So I've pretty much narrowed it down.
Since I let Eclipse handle the exporting and everything, I don't suppose you need the manifest to see if it is alright. Any questions you might have, I'll provide the informations you need. It goes without saying that the project runs directly from Eclipse.
Eclipse
Version: Indigo Service Release 2
Build id: 20120216-1857

Edit following Baqueta's answer
What happens when I do that is that I get a custom RuntimeException. I'm a bit baffled here. Here's a simple explanation of my code.
I have a utility class (UtilityJSON) that uses the referenced library (jackson). The constructor of that utility class instantiate an object defined in the referenced library, let's call it mapper.
A method of UtilityJSON uses a method of 'mapper'. At this point the exception is raised. Why I'm baffled is that 'mapper' is succesfully instantiated but using its method raises an exception. If the jar couldn't find the referenced library, it probably couldn't create the object 'mapper'. But running the project from Eclipse is all fine.
Is there any way to debug when running an executable jar? Maybe echo something in the console.

Edit 2
I may have found the error. My program reads a *.txt file in a folder inside the project. When exploring the content of the jar I see that this folder was not included, thus the exception. So the question now becomes: how do I include this folder? It's in the root folder of the project.

A: You could try the following:

*

*In Eclipse, go to Project->Properties.

*Select 'Java Build Path' from the column on the left.

*Select the 'Order and Export' tab.

*Find 'jackson' in the list and make sure it's checked.

EDIT
To answer your updated question:
In Eclipse, find the *.txt file in the Package Explorer. Right-click it and select Build Path->Add to Build Path. Then follow the instructions above to make sure the file gets included in the Jar. Finally, do a clean and rebuild.
If you're ever going to add more resources, it is common practice (and makes sense!) to have a resources folder (often called 'res'). You can then add the entire folder to the build path, so that all the resources in there get included in the Jar.

A: Enable the java console by writing
javaws -viewer

in a terminal. Close the Cache Viewer and click the advanced tab. There open Java-Console and click "enable console".


text:
Q: Idiomatic ways of expressing disagreement Are there any idiomatic ways in english writting to express disagreement as regards someone's opinion?
These are what i normally read:
"i respectfully disagree"
"With due respect, i disagree"
"Reluctantly, i differ".

A: As a "rule of thumb"  when someone says "with respect..." that means that they don't have much respect for the speaker!
(Examples of this are in the Comedy program "Yes Minister".  The civil servant who thinks he is much cleverer than the Minister often starts with "With respect, minister, ...." It is clear to anyone watching that the civil servant is very clever, and doesn't respect the minister at all!)
If you have to tell someone that you are speaking with respect, it suggests that the respect is not actually there.
But these kinds of expressions do exist in English, for that reason: because the thing you are about to say implies disrespect, so you want to soften by saying "respectfully"...
The simplest way to say that you disagree is

I disagree...

And then explain why you disagree.
Or just explain what your opinion is... You don't have tell people that it doesn't agree with another person.
If you want to, you can say "I have to disagree because..." or "Reluctantly, I'm going to disagree..." or "I respectfully disagree" and so on. There are many many things to say and none is particularly better than another.  You can use any of the examples in your question.

A: "I'm afraid I don't agree".
"I'm sorry, but I beg to differ."
"I'm really not sure I can agree."
All the above are polite and respectful enough, without descending into the trap of obsequity.
As has been pointed out elsewhere, "With all respect", and perhaps more pointedly, "With all due respect" tends to sound less polite, because it has evolved into the usage whereby it is tacitly implied that the speaker does not have a great deal of respect for the hearer. Such usage leads one into a minefield of manners.


text:
Q: Essential simple closed curves in a torus Definition: By a closed curve in a surface $S$ we will mean a continuous map $S^1 \to S$.
We will usually identify a closed curve with its image in $S$. A closed curve
is called essential if it is not homotopic to a point, a puncture, or a boundary
component.
I want to prove the following lemma:

Lemma. Let $\alpha$ and $\beta$ be two essential simple closed curves in a torus $T$. Then $\alpha$ is isotopic to $\beta$ if and only if $\alpha$ is homotopic to $\beta$.

Proof. One direction is vacuous since an isotopy is a homotopy. So suppose that $\alpha$ is homotopic to $\beta$. We immediately have that $i(\alpha, \beta)=0$.
Also we have:

Theorem: The nontrivial homotopy classes of oriented simple closed
curves in a torus $T$ are in bijective correspondence with the set of primitive elements of $\pi_1(T) ≈ \mathbb{Z}^2$.
An element (p, q) of $\mathbb{Z}^2$ is primitive if and only if $(p, q) = (0, \pm1)$,
$(p, q)=(\pm1, 0)$, or $\gcd(p, q)=1$.

A: A detailed sketch (again requiring exercises) is given in Chapter Two, Section C (titled "Knots in the torus") of Rolfsen's book Knots and links.


text:
Q: Printing a one dimensional array as a two dimensinoal array I'm trying to create a method that takes a one dimensional array and prints it out as a two dimensional array, but as square as possible so it looks nice. I've tried creating for loops to  do this, but how would you figure out how many rows and columns there are? Could someone give me the logic in how to make one, so I can use that to create my own? An explanation would be lovely.

A: This will make a new array that is square and big enough to house all the elements of the old array. It takes the square root of the original array's length and rounds up.
int size = (int)Math.ceil(Math.sqrt(oldArray.length));
int[][]newArray = new int[size][size];

A: Example:
array =    |1 2 3|
           |4 5 6|
           |7 8 9| (3*3)

Make a 1D array
int array1 = new int[3*3];

Or you can get length of the array
For row length: int row = array.length;
For column length: int column = array[0].length;
and then int array1 = new int[row*column];
Now iterate over array and copy all elements of array into array1.
         _________________
array1 = |1|2|3|4|5|6|7|8|9|

Now don't ask me for code.

A: This method will print the elements in your one-dimensional array as close as possible to a square pattern on the console output. It places tabs in between elements to line them up on each row.
private void printMyArray(String[]  onDimensionalArray) {
    int cols = (int) Math.floor(Math.sqrt(onDimensionalArray.length));
    int currentCol = 0;
    for(String element : onDimensionalArray) {
        System.out.print(element + "\t");
        if(currentCol >= cols) {
            System.out.println("");
            currentCol = 0;
        }
        else {
            currentCol++;
        }
    }
}

A: check this out
int array2d[][] = new int[10][3];

for(int i=0; i<10;i++)
for(int j=0;j<3;j++)
   array2d[i][j] = array1d[(j*10) + i];


text:
Q: How to rearrange select result using condition in LINQ I am new to linq I am looking for solution for following table.
Here is my table structure

By using TransType as condition I want to create two new columns Credit and Debit and want to show data according TransType condition.
like following screenshot.

Can you please suggest me LINQ select query to get result according to 2 screenshot.
Thank You.

A: To get two extra columns, you could create your own custom class or generate anonymous class on the fly (you can always pass it anywhere through dynamic data type). The code shows the principle. In this case, I use anonymous class, so I have to repeat all fields in original object plus add two extra columns:
static void Main(string[] args)
{
    var list = new List<MyObj>
    {
        new MyObj { TransType = "Credit", PaymentMethod = 1, Amount = 1000 },
        new MyObj { TransType = "Debit", PaymentMethod = 2, Amount = 2000 },
        new MyObj { TransType = "Debit", PaymentMethod = 1, Amount = 4000 },
        new MyObj { TransType = "Credit", PaymentMethod = 3, Amount = 3000 }
    };

    var filtered = from o in list
                   where o.TransType == "Credit"
                   select new
                   {
                      o.TransType,
                      o.PaymentMethod,
                      o.Amount,
                      Credit = "<VALUE>",
                      Debit = "<VALUE>"
                   };
}
class MyObj
{
    public string TransType { get; set; }
    public int PaymentMethod { get; set; }
    public int Amount { get; set; }
}

A: Thanks for suggestions.
from o in erp.CompAccTransactions
                                  where o.CompanyId == cid
                                  select new
                                     {
                                         o.TransId,
                                         o.TransDate,
                                         o.TransType,
                                         o.TransDesc,
                                         o.PaymentRef,
                                         Credit = o.TransType == "Credit" ? o.Amount : (o.TransType == "Debit" ? (decimal?)null : (decimal?)null),
                                         Debit = o.TransType == "Debit" ? o.Amount : (o.TransType == "Credit" ? (decimal?)null : (decimal?)null),
                                         o.ClearBalance

                                     });


text:
Q: Return type in If expression I am learning scala and can't understand why:
def signum(arg: Int) = {
    if(arg > 0 ) 1
    else if(arg < 0) -1
    else 0
}

Has Int as return type signum (arg: Int): Int
But
def signum(arg: Int) = {
    if(arg > 0 ) 1
    else if(arg < 0) -1
    else if(arg == 0) 0
}

Has AnyVal signum (arg: Int): AnyVal

A: It happens because in the second case you have not specified final else part. In this case the return type of this missing branch would be Unit. So Scala compiler infers AnyVal as a common parent of Int and Unit.
you can try to add explicit return type to the function signature:
def signum(arg: Int): Int = ...

It will not compile with following error:
 found   : Unit
 required: Int
    else if(arg == 0) 0
         ^
one error found

So the compiler tells you that result type of the last if is actually Unit and not Int.

A: In the absence of an explicit else, Scala assumes this:
else ()

Where () is the value of Unit. It's the value returned by println or assignment to var, for example.
This can be easily verified:
scala> val x = if (false) 1
x: AnyVal = ()

scala> x.isInstanceOf[Unit]
res3: Boolean = true


text:
Q: Matching strings for multiple data set in Python I am working on python and I need to match the strings of several data files. First I used pickle to unpack my files and then I place them into a list. I only want to match strings that have the same conditions. This conditions are indicated at the end of the string.
My working script looks approximately like this:
import pickle

f = open("data_a.dat")
list_a = pickle.load( f )
f.close()

f = open("data_b.dat")
list_b = pickle.load( f )
f.close()

f = open("data_c.dat")
list_c = pickle.load( f )
f.close()

f = open("data_d.dat")
list_d = pickle.load( f )
f.close()

for a in list_a:
    for b in list_b:
        for c in list_c
            for d in list_d:
                 if a.GetName()[12:] in b.GetName():
                      if a.GetName[12:] in c.GetName():
                         if a.GetName[12:] in d.GetName():
                              "do whatever"

This seems to work fine for these 2 lists. The problems begin when I try to add more 8 or 9 more data files for which I also need to match the same conditions. The script simple won't process and it gets stuck. I appreciate your help.
Edit: Each of the lists contains histograms named after the parameters that were used to create them. The name of the histograms contains these parameters and their values at the end of the string. In the example I did it for 2 data sets, now I would like to do it for 9 data sets without using multiple loops.
Edit 2. I just expanded the code to reflect more accurately what I want to do. Now if I try to do that for 9 lists, it does not only look horrible, but it also doesn't work.

A: out of my head:
files = ["file_a", "file_b", "file_c"]
sets = []

for f in files:
    f = open("data_a.dat")
    sets.append(set(pickle.load(f)))
    f.close()

intersection = sets[0].intersection(*sets[1:])

EDIT: Well I overlooked your mapping to x.GetName()[12:], but you should be able to reduce your problem to set logic.

A: Here a small piece of code you can inspire on. The main idea is the use of a recursive function.
For simplicity sake, I admit that I already have data loaded in lists but you can get them from file before :
data_files = [
    'data_a.dat',
    'data_b.dat',
    'data_c.dat',
    'data_d.dat',
    'data_e.dat',
]

lists = [pickle.load(open(f)) for f in data_files]

And because and don't really get the details of what you really need to do, my goal here is to found the matches on the four firsts characters :
def do_wathever(string):
    print "I have match the string '%s'" % string

lists = [
    ["hello", "world", "how", "grown", "you", "today", "?"],
    ["growl", "is", "a", "now", "on", "appstore", "too bad"],
    ["I", "wish", "I", "grow", "Magnum", "mustache", "don't you?"],
]

positions = [0 for i in range(len(lists))]

def recursive_match(positions, lists):
    strings = map(lambda p, l: l[p], positions, lists)
    match = True
    searched_string = strings.pop(0)[:4]
    for string in strings:
        if searched_string not in string:
            match = False
            break
    if match:
        do_wathever(searched_string)

    # increment positions:
    new_positions = positions[:]
    lists_len = len(lists)
    for i, l in enumerate(reversed(lists)):
        max_position = len(l)-1
        list_index = lists_len - i - 1
        current_position = positions[list_index]
        if max_position > current_position:
            new_positions[list_index] += 1
            break
        else:
            new_positions[list_index] = 0
            continue

    return new_positions, not any(new_positions)

search_is_finished = False

while not search_is_finished:
    positions, search_is_finished = recursive_match(positions, lists)

Of course you can optimize a lot of things here, this is draft code, but take a look at the recursive function, this is a major concept.

A: In the end I ended up using the map built in function. I realize now I should have been even more explicit than I was (which I will do in the future).
My data files are histograms with 5 parameters, some with 3 or 4. Something like this,
par1=["list with some values"]
par2=["list with some values"]
par3=["list with some values"]
par4=["list with some values"]
par5=["list with some values"]

I need to examine the behavior of the quantity plotted for each possible combination of the values of the parameters. In the end, I get a data file with ~300 histograms each identified in their name with the corresponding values of the parameters and the sample name. It looks something like,
datasample1-par1=val1-par2=val2-par3=val3-par4=val4-par5=val5
datasample1-"permutation of the above values"
...
datasample9-par1=val1-par2=val2-par3=val3-par4=val4-par5=val5
datasample9-"permutation of the above values"

So I get 300 histograms for each of the 9 data files, but luckily all of this histograms are created in the same order. Hence I can pair all of them just using the map built in function. I unpack the data files, put each on lists and the use the map function to pair each histogram with its corresponding configuration in the other data samples.
for lst in map(None, data1_histosli, data2_histosli, ...data9_histosli):
  do_something(lst)

This solves my problem. Thank you to all for your help!


text:
Q: An example of an expectation operator that is uniformly bounded Define the expectation operator $P_j : L^2(\mathbb{R}) \rightarrow L^2(\mathbb{R})$ as
$$
P_j f(x) := m_I := {1 \over |I|} \int_I f(t) \, dt
$$
where $I$ is of form $[2^{-j}k, 2^{-j}(k+1))$ (i.e., a dyadic interval) s.t. $x \in I$ (for each $x \in \mathbb{R}$, there is a unique $I$ for which $x \in I$).
According to an unproven lemma in a textbook on Harmonic Analysis, we have

Question: What's an example of a function $f \in L^2(\mathbb{R})$ (preferably one that only takes real values) where this inequality is strict? That is, where
$$
\|P_jf\|_2 < \|f\|_2 ?
$$

A: Let $I_{j, k} := [2^{-j}k, 2^{-j}(k+1)) $. Observe we have
\begin{align}
P_j f(x) = \sum^\infty_{k=-\infty} \left(\frac{1}{|I_{j, k}|}\int_{I_{j, k}}f(t)\ dt\right)\chi_{I_{j, k}(x)}
\end{align}
then it follows
\begin{align}
\|P_jf\|^2_2=&\ \int^\infty_{-\infty}\left| \sum^\infty_{k=-\infty} \left(\frac{1}{|I_{j, k}|}\int_{I_{j, k}}f(t)\ dt\right)\chi_{I_{j, k}(x)} \right|^2\ dx\\
=&\ \int^\infty_{-\infty} \sum^\infty_{k=-\infty} \frac{1}{|I_{j, k}|^2}\left(\int_{I_{j, k}} f(t)\ dt\right)^2 \chi_{I_{j, k}}(x)\ dx\\
=&\ \sum^\infty_{k=-\infty} \frac{1}{|I_{j, k}|} \left(\int_{I_{j, k}} f(t)\ dt\right)^2 \leq \sum^\infty_{k=-\infty} \int_{I_{j, k}}|f(t)|^2\ dt =\|f\|_2^2.
\end{align}
Since the inequality is purely a consequence of Cauchy-Schwarz inequality, then it's not hard to concoct up an example where the inequality is strict.
Edit:  Consider
\begin{align}
f(x) = 2x\cdot \chi_{I_{j, 0}}(x),
\end{align}
then we see that
\begin{align}
P_jf(x) = 2^{-j}\chi_{I_{j, 0}}(x).
\end{align}
Then it follows
\begin{align}
\|P_j f\|_2=2^{-3j/2}  \ \ \ \text{ and } \ \ \ \|f\|_2 = \sqrt{\frac{4}{3}}2^{-3j/2}.
\end{align}


text:
Q: Performance of ImageApply I would like to optimize this code
fadeAndShine[old_, new_] := If[old == new, {1, 0.8, 0.2}, new];
ImageApply[fadeAndShine, {imageA, imageB}]

Is it possible, and if yes, on what should I focus?

Applying fadeAndShine to following image takes 0.53 sec on my pc, while applying Max takes 0.31 sec.
imageA =
  Rasterize[Graphics[Table[Circle[{x, 0}, x], {x, 1, 25}]], "Image",
   ImageSize -> 500];
imageB =
  Rasterize[Graphics[Table[Circle[{0.8 x, 0}, x], {x, 1, 25}]],
   "Image", ImageSize -> 500];

I'm willing to use another functionality as long as I get same result for any pair of images.

A: Your If codition is pretty simple and can be precomputed on all pixels more efficiently to generate a composition mask
mask = Binarize[ImageDifference[imageA, imageB], 0]

You can then use simple arithmetic to combine it
ImageAdd[
 ImageMultiply[ColorNegate[mask], RGBColor @@ {1, 0.8, 0.2}],
 ImageMultiply[mask, imageB]
]

Putting all together
fadeAndShine2[old_, new_, color: _?ColorQ : RGBColor[1, 0.8, 0.2]] :=
With[
    {mask = Binarize[ImageDifference[old, new], 0]},
    ImageAdd[
        ImageMultiply[ColorNegate[mask], color],
        ImageMultiply[mask, new]
    ]
]
fadeAndShine2[imageA,imageB]//AbsoluteTiming//First

(* => 0.012 *)

And
MinMax[
 fadeAndShine2[imageA, imageB] -
  ImageApply[fadeAndShine, {imageA, imageB}]]

(* => {0., 0.} *)

A: You can try to use compiled code and apply it to the ImageData of your images:
fadeAndShine[old_, new_] := If[old == new, {1, 0.8, 0.2}, new];

cFadeAndShine = Compile[{{old, _Real, 1}, {new, _Real, 1}},
   If[old == new, {1., 0.8, 0.2}, new],
   CompilationTarget -> "C",
   RuntimeAttributes -> {Listable},
   Parallelization -> True
   ];

And here the usage example with timings:
imageA = Rasterize[Graphics[Table[Circle[{x, 0}, x], {x, 1, 25}]],
   "Image", ImageSize -> 500];
imageB = Rasterize[Graphics[Table[Circle[{0.8 x, 0}, x], {x, 1, 25}]],
    "Image", ImageSize -> 500];

imageC = ImageApply[fadeAndShine, {imageA, imageB}]; //
  AbsoluteTiming // First
imageD = Image[cFadeAndShine[ImageData[imageA], ImageData[imageB]]]; //
   AbsoluteTiming // First
ImageData[imageC] - ImageData[imageD] // Abs // Max

0.355039
0.035754
0.

A: imageA=Rasterize[Graphics[Table[Circle[{x,0},x],{x,1,25}]],"Image",ImageSize->500];
imageB=Rasterize[Graphics[Table[Circle[{0.8 x,0},x],{x,1,25}]],"Image",ImageSize->500];

data1=ImageApply[Function[{old,new},If[old==new,{1.,0.8,0.2},new]],{imageA,imageB}]//
  ImageData;//AbsoluteTiming

data2=Map[With[{old=#[[{1,2,3}]],new=#[[{4,5,6}]]},If[old==new,{1.,0.8,0.2},new]]&,
  Join[ImageData[imageA],ImageData[imageB],3],{2}];//AbsoluteTiming

data3=With[{old=ImageData[imageA],new=ImageData[imageB]},
  With[{k=Unitize[new-old]},Map[{1.,0.8,0.2}#&, 1-k,{2}]+new k]];//AbsoluteTiming

data1==data2==data3

{0.637831, Null}
{0.249619, Null}
{0.0957136, Null}
True


text:
Q: facebook login using phantom js i was learning about phantomjs
and i was trying to login into facebook using phantom js
i was successfully able to change the values of the input fields
looks like this
and i could submit the form
the problem is with multiple redirects that facebook do to reach the home page
here is how my code looks like:
var webpage = require('webpage');
var page = webpage.create();

page.settings.javascriptEnabled = true;
page.settings.loadImages = false;
phantom.cookiesEnabled = true;
phantom.javascriptEnabled = true;

var loaded = false;
page.onLoadStarted = function() {
  loaded = false;
  console.log("load started");
};
page.onLoadFinished = function() {
  loaded = true;
  console.log("load finished");
};

page.open('http://www.facebook.com',function () {
  page.render('1.jpg')

  page.evaluate(function () {
    document.getElementById('m_login_email').value = "me@email.com";
    document.getElementById('m_login_password').value = "*********";
    document.getElementById('login_form').submit();
  });

  page.render('2.jpg');

  setInterval(function () {
    if (loaded) {
      page.render('3.jpg');
      console.log("loaded : "+page.url);
      phantom.exit();
    }
  },1000);

});

//EDIT
//the output
load started
load finished
load started
load finished
load started
load finished
loaded : https://m.facebook.com/login/async/?refsrc=https%3A%2F%2Fwww.facebook.com%2F&lwv=100

//
that totally work for me but the 3.jpg image it's black image
and the url of this page >>https://m.facebook.com/login/async/?refsrc=https%3A%2F%2Fwww.facebook.com%2F&lwv=100<<
i was lucky only once, this code worked and i could login .. but it's back to fail again :(
thanks for help BTW


text:
Q: Circular dependency, fine or bad? I'm making some sort of personal framework, for educational and practical purposes, and encountered a design problem i'd like to share.
I have a Component namespace, that contains various classes for, um, components (i. e. bits of reusable ViewModels). One of them is Component\Form, a generator class for building form templates from models. After some time i realized a need for some Validation service classes, that will perform non-model specific validations, like checking captcha.
The problem is, my default form validation accumulates error messages and displays them in one place. So, to accomplish this, my Validator classes need to have access to the Form, and Form class adds Validator classes via setter injection.
So, this creates circular dependency. From one side, there's an (although optional) dependency of Form on Validator classes, and from other side, i have to inject a Form class into every Validator i add. I wonder, if this approach is fine from the point of OOP design, and if not, what problems could possibly arise from that, and how could i possibly resolve it.
I'm sorry i don't provide any relevant code, i think it would take too much space to be readable, but if necessary, i'll gladly post anything to clarify specific moments of the problem.

A: I think the validator should not have a dependency on the form, because it should not display an error. The form can ask the validator to check some raw input against some rule. If the validation fails, the validator might return an error code or message, based on which the form can display an error. Displaying that error is not the job of the validator.

A: i would say that you miss some kind of mvc. i would keep that the validator depends on form as it have to access all data and passing raw values will be tedious and complex (comparing two passwords, captcha, checking if one field is longer that 5 only if another is shorter than 3). but i would not make that a form depends on a validator. because form doesn't know if it requires a validation. sometimes you need to trigger validators A and B and sometimes B and C. and form doesn't have the knowledge to make that decision. that's the controller's job. i would add some kind of ValidationGroup / ValidatorHandler etc. which references a form and (a group of) validators. then a controller would trigger the correct group of validators


text:
Q: Saving a buffer in Google Cloud Bucket I'm trying to find a solution that will let me stream in-memory created zip to Google Cloud Bucket (I'm using Firebase, but seems like it's beyond it so I need to handle it through GCB).
I have nailed down file creation part (code below) and when it's working locally on my machine it saves it in the main folder where server files reside. So far so good.
Now I found this link that lets stream transfers, but not sure how to connect them. Should it be after zip is created? Instead? Any suggestions are welcome!
const express = require('express')
var router = express.Router()
var archiver = require('archiver')
var admin = require("firebase-admin");
var serviceAccount = require("../servicekey.json")
admin.initializeApp({
  credential: admin.credential.cert(serviceAccount),
  databaseURL: "https://myName.firebaseio.com",
  storageBucket: "myName.appspot.com"
})
var bucket = admin.storage().bucket()

const {
  convertCSVtoJSON,
  generateDocuments,
  generateDocx,
  isCorrectTemplateFileType
} = require('./generateServices')

router.post('/', async (req, res) => {
  try {
    if(!isCorrectTemplateFileType(req.files.template))
      return res.status(403).send({
        message: 'Wrong file type. Please provide .docx file.'
      })

    const template = req.files.template.data
    const data = await convertCSVtoJSON(req.files.data1)

    let zip = archiver('zip')

    zip.on('warning', function(err) {
      console.log(err)
    });

    zip.on('error', function(err) {
      res.status(500).send({error: err.message})
    });

    zip.on('entry', function(ars) {
      // console.log(ars)
    });

    zip.on('end', function() {
      console.log('Archive wrote %d bytes', zip.pointer())
    });

    // res.attachment('archive-name.zip')

    // zip.pipe(output)
    // zip.pipe(res)

    data.forEach((docData, index) => {
      let buff = generateDocx(template, docData, 'title')
      zip.append(buff, { name: `${index}.docx` })
    })

    zip.finalize()

    console.log(zip)
    const file = bucket.file("pliki.zip") // nazwa do zmiany
    file.save(zip, (err) => {
      if (!err) {
        console.log("cool");
      } else {
        console.log("error " + err);
      }
    });

    res.sendStatus(201)
  } catch (error) {
    console.log(error)
    res.send(error)
  }
})

module.exports = router


text:
Q: How to build a Corpus of hashtags (Text Mining) I am trying to analyze a twitter data by mining all the hashtags. I want to put all hashtags in a corpus and mapping this corpus to a list of words. Do you have any idea how I can to manage this problem ?
Here is a snap of my data

Here is the code that I used but I have a problem in my DTM with a 100% of sparsity
step1 <- strsplit(newFile$Hashtag, "#")
step2 <- lapply(step1, tail, -1)
result <- lapply(step2, function(x){
sapply(strsplit(x, " "), head, 1)
})
result2<-do.call(c, unlist(result, recursive=FALSE))
myCorpus <- tm::Corpus(VectorSource(result2)) # create a corpus

Here is information about my Corpus
myCorpus
  <<SimpleCorpus>>
 Metadata:  corpus specific: 1, document level (indexed): 0
 Content:  documents: 12635

And my DTM
<<DocumentTermMatrix (documents: 12635, terms: 6280)>>
Non-/sparse entries: 12285/79335515
Sparsity           : 100%
Maximal term length: 36
Weighting          : term frequency (tf)

A: Your problem is you are using str_split. You should try:
str_extract_all("This all are hashtag #hello #I #am #a #buch #of #hashtags", "#\\S+")
As results this list:
[[1]]
[1] "#hello"    "#I"        "#am"       "#a"        "#buch"     "#of"
[7] "#hashtags"

If your desired result is a data frame use simplify = T:
str_extract_all("This all are hashtag #hello #I #am #a #buch #of #hashtags", "#\\S+", simplify = T)

As result:
     [,1]     [,2] [,3]  [,4] [,5]    [,6]  [,7]
[1,] "#hello" "#I" "#am" "#a" "#buch" "#of" "#hashtags"


text:
Q: Adding arrows on 3D curves in Asymptote I am trying to plot (1D) trajectories in 3D with Asymptote (because I am also plotting surfaces with opacity and do not want to use hacks for hidden surfaces).
Each curve is defined by points in an external csv file. The following minimal example for one curve works properly (given a data.csv file of course):
\documentclass[margin=1cm]{standalone}
\usepackage{asymptote}

\begin{document}
\begin{asy}
settings.outformat="pdf";
settings.prc=false;
settings.render=0;

import graph3;
currentprojection=orthographic(1,-2,4);
currentlight=(1,-1,1);
size3(200,200,80,IgnoreAspect);

file in=input("data.csv").line().csv();
real[][] a=in.dimension(0,0);
a=transpose(a);

real[] x=a[0];
real[] y=a[1];
real[] z=a[2];

draw(graph(x,y,z),blue,currentlight);

xaxis3(XY()*"$x_1$",Arrow3);
yaxis3(XY()*"$x_2$",Arrow3);
zaxis3("$y$",Arrow3);
\end{asy}
\end{document}

Now, I would like to add arrows on the curve to show the direction of the trajectory.
It seems if the trajectory was a path, I could do it quite easily using something such as draw(pathname,Arrow(Relative(0.7)));. But I can't manage to "convert" my graph as a curve to do so.
Any ideas how I could add arrows?
I cannot manage to plot arrows on the curves.

A: In this case you need to use Arrow3 instead of just Arrow.
With a simple data file it gives

\begin{filecontents*}{data.csv}
0.81,0.59,0.1
0.31,0.95,0.2
-0.31,0.95,0.3
-0.81,0.59,0.4
-1,0,0.5
-0.81,-0.59,0.6
-0.31,-0.95,0.7
0.31,-0.95,0.8
0.81,-0.59,0.9
1,0,1
\end{filecontents*}
\documentclass[margin=1cm]{standalone}
\usepackage{asymptote}

\begin{document}
\begin{asy}
settings.outformat="pdf";
settings.prc=false;
settings.render=0;

import graph3;
currentprojection=orthographic(1,-2,4);
currentlight=(1,-1,1);
size3(200,200,80,IgnoreAspect);

file in=input("data.csv").line().csv();
real[][] a=in.dimension(0,0);
a=transpose(a);

real[] x=a[0];
real[] y=a[1];
real[] z=a[2];

draw(graph(x,y,z,operator..),blue,Arrow3(Relative(0.7)),currentlight);

xaxis3(XY()*"$x_1$",Arrow3);
yaxis3(XY()*"$x_2$",Arrow3);
zaxis3("$y$",Arrow3);
\end{asy}
\end{document}


text:
Q: External hard disk can be detected but cannot be accessed I've plugged an external hard disk on my computers. The device has been detected, but isn't shown on explorer. It is the same situation on both windows 7 and windows 10.
Detected / installed because it was shown in control panel > Devices and Printers. Also because I've found it using the list disk command line and it should be the Disk 1 :
Microsoft DiskPart version 10.0.10586

Copyright (C) 1999-2013 Microsoft Corporation.
On computer: TOSHIBA-MINCONG

DISKPART> list disk

  Disk ###  Status         Size     Free     Dyn  Gpt
  --------  -------------  -------  -------  ---  ---
  Disk 0    Online          238 GB      0 B        *
  Disk 1    Online          465 GB   127 MB        *

Unrecognized because it seems that the Partition 2 has unknown file system type. So it cannot be recognized by windows.
DISKPART> select disk 1

Disk 1 is now the selected disk.

DISKPART> list partition

  Partition ###  Type              Size     Offset
  -------------  ----------------  -------  -------
  Partition 1    System             200 MB    20 KB
  Partition 2    Unknown            465 GB   200 MB

Can somebody help me to resolve this problem without clean the data in the hard disk ?

Update
I tested the hard disk format type on OSX. And its type Apple_HFS as you can see at /dev/disk2.
Air-de-xx:~ xx$ diskutil list
/dev/disk0 (internal, physical):
   #:                       TYPE NAME                    SIZE       IDENTIFIER
   0:      GUID_partition_scheme                        *121.3 GB   disk0
   1:                        EFI EFI                     209.7 MB   disk0s1
   2:          Apple_CoreStorage Macintosh HD            120.5 GB   disk0s2
   3:                 Apple_Boot Recovery HD             650.0 MB   disk0s3
/dev/disk1 (internal, virtual):
   #:                       TYPE NAME                    SIZE       IDENTIFIER
   0:                  Apple_HFS Macintosh HD           +120.1 GB   disk1
                                 Logical Volume on disk0s2
                                 440DB97F-xxxx-xxxx-xxxx-19AEAC28E415
                                 Unencrypted
/dev/disk2 (external, physical):
   #:                       TYPE NAME                    SIZE       IDENTIFIER
   0:      GUID_partition_scheme                        *500.1 GB   disk2
   1:                        EFI EFI                     209.7 MB   disk2s1
   2:                  Apple_HFS MEMUP                   499.8 GB   disk2s2

A: What was the hard drive used for previously? Make sure the hard drive is formatted in NTFS, Fat32, or eXFat so that it is readable by Windows. Windows can't read file systems that are formatted for Mac or Linux. It may also not be mounted.
Guide to mount drives: http://windows.microsoft.com/en-us/windows/mount-dismount-drive#1TC=windows-7

A: Try changing the external hard-disk case or plug it in through another external USB hard-disk connector (and not through its own case circuit), to make sure if the hard-disk case circuit is still working and not gone out of order.

A: Please check the disk manager. There are multiple ways to access it, and depending on the version of Windows that you have, the steps might be slightly different
On most windows
 1. Open Windows Explorer > Right-click My Computer/or This PC > Manage
Or WindowsKey + R > Type diskmgmt.msc
 2. Locate the disk partition in question > Right-click "Change Drive Letter and Paths"
 3. Make sure there is a drive letter associated to the disk, or click Add to create one
 4. See if you can access the disk after a disk letter had been established
Here is a quick example to Win7 steps
enter link description here