text:
Q: Securing credentials in Desired State Configuration deployed via ARM How to use Desired State Configuration in combinition with ARM.
Scope:
- We have an Azure virtual machine that is deployed via an ARM template.
- The VM has an extension resource in the ARM template, for the Desired State Configuration
- We need to pass sensitive parameters (in a secure way!) into the Desired State Configuration (we want to create an additional local windows account with the DSC)
- Configuration file is used to know what public key to use for encryption, and to let the VM know which certificate it has to use for decryption (by thumbprint)
- When using ARM, you need to define the configuration data file in a separate property
- I noticed that the DSC service, automically adds an certificate for document encryption to the VM.
Question:
If I want to get this working out of the box, I will need to create the configurationDataFile upfront, and store it somewhere (like blob or something).
However, the 'out-of-the-box' certificate on the VM is only known after the ARM template has been deployed.
I was wondering if there is a way to get the encryption/decryption in DSC working, using the out of the box DSC Certificate on the VM, without using different incremental DSC templates.
So how can I know the out of the box certificate thumbprint at deployment time? (In the arm template?)
Do I actually need to transform the ConfigurationData file for every deployment (and finding the correct thumbprint of the VM), or is there an out of the box way to tell DSC via ARM to use the out of the box created certificate for this?

A: Because the target VM is also the authoring machine, the passwords can be passed as plain text, as they never leave the Virtual Machine.
This has been verified by Microsoft support.


text:
Q: Get .NET to consider a specific network share to be fully trusted I have (only) Visual Studio 2010 installed. I'm trying to run my unit tests from a command-line build-system. All my development work is in my home directory on a Linux server that's shared out using Samba. When I try to run NUnit I get an error like this:
Unhandled Exception: System.TypeInitializationException: The type initializer for 'NUnit.ConsoleRunner.Runner' threw an exception. ---> System.Security.Security
Exception: That assembly does not allow partially trusted callers.
   at NUnit.ConsoleRunner.Runner..cctor()
The action that failed was:
LinkDemand
The assembly or AppDomain that failed was:
nunit-console-runner, Version=2.5.9.10305, Culture=neutral, PublicKeyToken=96d09a1eb7f44a77
The method that caused the failure was:
NUnit.Core.Logger GetLogger(System.Type)
The Zone of the assembly that failed was:
Intranet
The Url of the assembly that failed was:
file:///Z:/gitrepos/smarties/dependencies/Windows-x86/NUnit-2.5.9.10305/bin/net-2.0/lib/nunit-console-runner.DLL
   --- End of inner exception stack trace ---
   at NUnit.ConsoleRunner.Runner.Main(String[] args)
   at NUnit.ConsoleRunner.Class1.Main(String[] args)

I have tried using caspol.exe as described here: Edit and run .NET projects from network shares
>caspol -addgroup 1.2 -url file:///Z:/* FullTrust -name MyZShare
Microsoft (R) .NET Framework CasPol 4.0.30319.1
Copyright (c) Microsoft Corporation.  All rights reserved.

WARNING: The .NET Framework does not apply CAS policy by default. Any settings shown or modified by CasPol will only affect applications that opt into using
CAS policy.

Please see http://go.microsoft.com/fwlink/?LinkId=131738 for more information.

The operation you are performing will alter security policy.
Are you sure you want to perform this operation? (yes/no)
yes
Added union code group with "-url" membership condition to the Machine level.
Success

It has no obvious effect.
Other instructions tell me to find some Microsoft .NET Security Policy tool in Administrative Tools in the Control Panel, but I have no such tool available. (Is this because I only have Visual Studio 2010, not earlier versions? I'm running Windows 7 Pro 64-bit, if it makes a difference.)
I really just want .NET to believe that this directory is on my own machine and not part of the intranet. I don't want any of this code to run from a network share when deployed, only as part of development. I also don't want to blindly trust all network shares, although even that would be a more palatable workaround than copying everything onto a local drive every time I want to run a test.
I would rather not have to sign everything with strong names at this point in development. (And I'm not even sure if it would help, since NUnit is apparently failing before it has even loaded my assembly.)

EDIT - In the end it turned out I was trying to solve the wrong problem. While figuring out how to get NUnit to run .NET 4.0 tests without a subprocess, I found this:
http://frater.wordpress.com/2010/05/04/debugging-nunit-tests-under-visual-studio-2010/
It says:

According to this page you should also add this line under the runtime element [in nunit-console.exe.config]:
<loadFromRemoteSources enabled="true" />
This allows libraries downloaded from a remote site (such as a website) to be loaded with full trust.  I'm not sure why this would be necessary and indeed, my application debugged NUnit just fine without it.  However, if you have problems, you might want to give it a try.

This fixed my problem for me without having to muck about with caspol.

A: This is because in .NET 3.5 and below, all libraries located on network shares are treated as partial trust. It is possible to work around this by using a later version of the framework to run NUnit.
The NUnit runners target the v3.5 framework, presumably for legacy support. You can check this with the corflags tool that comes with Visual Studio
> corflags nunit-console.exe
Version   : v2.0.50727

This means if you run nunit-console.exe from the from command line and you have .NET 3.5 and .NET 4 installed, the v3.5 runtime will be used to run the executable. You can see this in the console output.
> nunit-console.exe
CLR Version: 2.0.50727.7905 ( Net 3.5 )

The config contains the <loadFromRemoteSources enabled="true"/> element, which causes .NET v4 to ignore the partially trusted caller error, but this setting is ignored in the older versions of the framework.
To force the application to run under .NET 4 or above, add the following line to the startup section of the application config file.
<supportedRuntime version="v4.0"/>

In my case, I had to add a step to the build server automation to make this config change before running the tests in a continuous integration environment.
desc 'run unit tests'
task :tests => :compile do
  runner_dir = FileList["packages/NUnit.Runners*/tools"].first
  runner_config = File.join(runner_dir, "nunit-console.exe.config")

  # running the tests from a network share fails due to code access policy if the
  # runner is on framework v3.5 or lower. force the runner to use v4.0 or above
  comment = %<!-- Comment out the next line to force use of .NET 4.0 -->
  runtime_version = %<supportedRuntime version="v4.0.30319"/>
  File.write(runner_config, File.read(runner_config).sub(comment, runtime_version))

  nunit! :actually_run_tests do |nunit|
    nunit.command = File.join(runner_dir, "nunit-console.exe")
    nunit.assemblies = FileList["out/**/*.Tests.dll"]
    nunit.log_level = :verbose
  end
end

A: I don't know know enough about security in .net 4.0 to give you a solution but I can provide some insight on the "missing" Microsoft .net security policy tool.
It has been removed in .net 4.0 thus any examples referring to it are prior to .net 4.0.  Even if you installed .net framework 2.0 to gain the "SPT" it would only affect .net 2.0, 3.0, and 3.5 applications.
http://msdn.microsoft.com/en-us/library/2bc0cxhc.aspx
There have been extensive changes to security model in .Net 4.0 thus any documents prior to 4.0 shouldn't be trusted.
http://msdn.microsoft.com/en-us/library/dd233103.aspx

A: Are you sure that NUnit is running under .NET 4.0 instead of an earlier .NET Framework version?  (You might have earlier framework versions installed even if you don't have earlier Visual Studio versions installed.)  Also, what is the full command line (including all switch values) that you are using to launch the NUnit console application?

redpajama_set_name: RedPajamaStackExchange


text:
Q: Node.js + Mongoose: Find data and get other data for each I have two models Users and News. On the page which is written with Express framework are published news and under the news are comments. Inside News model is subdocument with comments which contains two fields - user (subfields:) { name, objectid } and comment. Because in addition to comment there is user's name, I would like to add some additional informations about it (like number of comments, link to website, ...).
And this is my question: How to get data of user (from Users model) for each comment from subdocument (from News model)?

A: Add a populate call to your find query to pull in the user details.  I'm not quite clear on your schema, but something like:
News.find().populate('comments.userId').exec(...);

This relies on your schema defining userId as an ObjectId ref to Users.


text:
Q: Problem after Google Services Version Change Problem after change from google-services version 4.3.10 to 4.3.14
classpath 'com.google.gms:google-services:4.3.10' -> no problem
classpath 'com.google.gms:google-services:4.3.14' -> build error
build error message :
Execution failed for task ':unityLibrary:processDebugGoogleServices'.

No matching client found for package name 'com.unity3d.player'

//----------------------------
//build.gradle (project : ---)
//----------------------------

    allprojects {
        buildscript {
            repositories {
                google()
            jcenter()
        }

        dependencies {
            classpath 'com.android.tools.build:gradle:7.3.1'
            classpath 'com.google.gms:google-services:4.3.10'
            classpath 'com.google.firebase:firebase-crashlytics-gradle:2.9.2'
        }
    }

    repositories {
        google()
        jcenter()
        flatDir {
            dirs "${project(':unityLibrary').projectDir}/libs"
        }
    }
}

task clean(type: Delete) {
    delete rootProject.buildDir
}

I hope it will be fixed in the next version.thank you.


text:
Q: Connecting Pentaho to Apache Druid Can anybody let me know the steps to connect to Apache Druid using Tableau, please?
I tried the following steps:

*

*Copy the Avatica jar file to tomcat/lib

*Create a new Generic Database (JDBC connection) using the following parameters options-

MSTR_JDBC_JAR_FOLDER=/opt/mstr/MicroStrategy/install/JDBC;
DRIVER=org.apache.calcite.avatica.remote.Driver;
URL={jdbc:avatica:remote:url=http://localhost:8082/druid/v2/sql/avatica/};

Note-
1. userid/password is not enabled i.e. Druid can be accessed without login credentials

*Able to access the Druid console "http://localhost:8888/unified-console.html"

*Able to connect to Druid using Apache Superset and Tableau applications.

A: jdbc:avatica:remote:url=http://localhost:8082/druid/v2/sql/avatica/
instead of HTTP replace it with druid. like I did below , may be it works.
jdbc:avatica:remote:url=druid://localhost:8082/druid/v2/sql/avatica/
Also let me know the update that were you able to connect druid to pentaho


text:
Q: Information about Home Primes I will be doing some research on Home Primes and the lack of resources online baffled me. I would be grateful and thankful to those who contribute to this post adding their prior knowledge , links, facts and information about Home Primes.
I can then also add these information to the common sites such as wolfram and wikipedia to make others access knowledge quicker.
Also if anyone knows, why is there a huge mystery and vagueness in the research of home primes?
For anyone who does not know what a Home Prime is:
A Home Prime is the terminating prime in a sequence in concatenating the prime divisors of a number.
This may sound very abstract but an example will do
lets take 49
49 = 7x7 therefore we write it as 77
77 = 7x11 therefore we write it as 711
and we continue until we find a prime
since if we hit a prime we cannot factorise it any longer, the sequence ends and that prime is called a home prime.

A: Just my opinion, but Home Primes started out as recreational math. But you'll find there's likely no known shortcut for calculating what it will be from the start number.  Thus it relies on the toughness of factoring. You can get a few hints about factors by modular arithmetic, but it's not really that much help ... attempting to work backwards doesn't help much more ...

A: I am currently generating home primes for numbers up to 5000000. Just for fun!
I stop the loop normally when the composite reaches 84+, but I have found several larger ones. I have some statistics. About 83% of all home primes are found at this point. Currently I have reached 3000000, 4000000 will be reached witin weeks. All factoring is done using MSIEVE 1.53. If anybody is interesded, I can mail a database as a .csv file as well a statistics file.


text:
Q: Prevent drag helper from being added to sortable List using knockout Issue
When dragging an item from the toolbar to an observation group the item is correctly added, but the  drag helper is also added to the sortable list.
Desired Functionality
Drag an element from the toolbar onto an observation group. Depending on what type of observation it is, display the correct template for input.
http://jsfiddle.net/PQL9T/2/

A: In your sortableList binding, looks like you want to remove the item at the end, since you will be rendering an item based on what you push to your collection.
            //Add Item to list

            collection.splice(newIndex, 0, collectionItem);

            valueAccessor().valueHasMutated();

            ui.item.remove();  //add this line


text:
Q: Commons SCXML2 Unable to jump to provided State I am using commons SCXML2 having States and tasks to control the Workflow Engine and initially the engine starts with a initial State and execute State and task in a flow.
And our requirement is that we want to persist the State if the Workflow get exited.
We are storing the State in the Database from which we want to resume the Workflow.
Now i am unable to resume the Workflow with the given State.
what i tried...
SimpleTransition initialTransition = new SimpleTransition();
initialTransition.setNext("first");    //jumping to First State
exec.getStateMachine().setInitialTransition(initialTransition);

I am unable to find how to jump to given state and used the above code to do so but it does not help for me.


text:
Q: How to find depth of property? public class CategoryInModel
{
 public int Id { get; set; }
 public CategoryInModel Parent { get; set; }
}

I have a class like above. I want to get depth of the Parent object.
Parent object can have various depths.
Like:
Parent.Parent.Parent
or
Parent.Parent
How can I find the depth of the parent object?

A: Based on the logic that a model's depth will be 1 + the parent depth:
public class CategoryInModel
{
    public int Id { get; set; }
    public CategoryInModel Parent { get; set; }

    public int Depth => 1 + ParentDepth;
    public int ParentDepth => Parent?.Depth ?? 0;
}

A: static int GetDepth (CategoryInModel cat, int depth = -1)
{
    if (cat == null)
        return depth;
    else
        return GetDepth(cat.Parent, depth + 1);
}

And then to use:
var mod = new CategoryInModel { Parent = new CategoryInModel { Parent = new CategoryInModel { Parent = new CategoryInModel() } } };

Console.WriteLine(GetDepth(mod));


text:
Q: Can't see my mistake in these computations to prove second contracted Bianchi identity I'm trying to prove that the following equality holds, where $X$ is an arbitrary  vector field on a Riemannian manifold (since I already know the left side is also equal to $\nabla_{X} R$, if I proved it the second Bianchi identity would then follow):
$$-2 \Delta \nabla_{i} X^{i}-2 R_{i j} \nabla_{i} X^{j}+\nabla_{i} \nabla_{j} \nabla_{i} X^{j}+\nabla_{i} \nabla_{j} \nabla_{j} X^{i}
=2 X^{i} \nabla_{j} R_{i j}$$
Now, by my computations:
$$\begin{aligned} \nabla_{i} \nabla_{j} \nabla_{j} X^{i} &=  \nabla_{i} \nabla_{j} \nabla_{j} X^{i} - \nabla_{j} \nabla_{i} \nabla_{j} X^{i} + \nabla_{j} \nabla_{i} \nabla_{j} X^{i}  \\ &= R_{ijk}^{i} \nabla_{j} X^{k} +  \nabla_{j} \nabla_{i} \nabla_{j} X^{i} \\ &= R_{ij} \nabla_{i} X^{j} +  \nabla_{j} \nabla_{i} \nabla_{j} X^{i}\end{aligned}$$
$$\begin{aligned} \nabla_{j} \nabla_{i} \nabla_{j} X^{i}  &= \nabla_{j} \nabla_{i} \nabla_{j}  X^{i} - \nabla_{j} \nabla_{j} \nabla_{i} X^{i} +  \nabla_{j} \nabla_{j} \nabla_{i} X^{i} \\ &= \nabla_{j}(R_{ijk}^{i} X^{k}) + \Delta \nabla_{i} X^{i} \\ &= \nabla_{j} (R_{jk} X^k) + \Delta \nabla_{i} X^{i}  \\ &= \nabla_{i}(R_{ij} X^{j}) + \Delta \nabla_{i} X^{i}  \end{aligned}$$
So we have:
$$\begin{aligned} &-2 \Delta \nabla_{i} X^{i}-2 R_{i j} \nabla_{i} X^{j}+\nabla_{i} \nabla_{j} \nabla_{i} X^{j}+\nabla_{i} \nabla_{j} \nabla_{j} X^{i} \\ &= -2 \Delta \nabla_{i} X^{i}-2 R_{i j} \nabla_{i} X^{j} +  \nabla_{j} \nabla_{i} \nabla_{j} X^{i} +\nabla_{i} \nabla_{j} \nabla_{j} X^{i}
 \\ &= -2 \Delta \nabla_{i} X^{i}-2 R_{i j} \nabla_{i} X^{j} + \nabla_{i}(R_{ij} X^{j}) + \Delta \nabla_{i} X^{i} + R_{ij} \nabla_{i} X^{j} +  \nabla_{j} \nabla_{i} \nabla_{j} X^{i} \\ &= -2 \Delta \nabla_{i} X^{i}-2 R_{i j} \nabla_{i} X^{j}  + 2\nabla_{i}(R_{ij} X^{j}) + 2\Delta \nabla_{i} X^{i}  + R_{ij} \nabla_{i} X^{j}  \\ &= 2\nabla_{i}(R_{ij} X^{j}) - R_{i j} \nabla_{i} X^{j} \\ &= 2X^{j} \nabla_{i}R_{ij} + R_{ij} \nabla_{i} X^{j}\end{aligned}$$
What's going on here? Where did I make a mistake so that an extra $R_{ij} \nabla_{i} X^{j}$ could come in? I'd appreciate some help.

A: Your mistake is in the second equality of your first display.  In short, the curvature operator is a derivation, so it needs to be applied in both components.  Thus, if $T^{ji}$ is a $(2,0)$-tensor field, then
\begin{align*}
 \nabla_i\nabla_j T^{ji} - \nabla_j\nabla_i T^{ji} & = R_{ij}{}^j{}_k T^{ki} + R_{ij}{}^i{}_k T^{jk} \\
 & = -R_{ik} T^{ki} + R_{jk} T^{jk} \\
 & = 0 .
\end{align*}
(Note: I am using abstract index notation in this computation.)  Applying this with $T^{ji}=\nabla^j X^i$ yields your expected result; in your computation, you missed the first summand, which led to your extra factor of $R_{ij}\nabla^iX^j$.


text:
Q: Why are quarters on the Enterprise-D so spacious? Watching TNG I noticed that nearly every crew member has very spacious quarters, which is something that does not seem practical on a space vessel.
Today's aircraft carriers house 3 officers to a room and 8 or more enlisted men to a room.
Why are quarters on the Enterprise-D so spacious and is there evidence that lesser crew members had more confined/shared living quarters?

A: Why the quarters are so spacious;

*

*Ship space isn't at much of a premium. The ship can readily hold ten times the present crew when the need arises (for evacuation missions and emergencies) which means that for most of the time, the ship is 90% empty.

*The Enterprise is not a military vessel. Their primary mission is one of peaceful exploration. In addition to there being a considerable number of civilians on board, the crew are not expected to maintain military discipline in their quarters. Providing them with spacious accommodation would obviously lead to less stress and a happier and more productive crew.
The TNG Technical Manual has this to say on the subject;

Starfleet believes that providing comfortable living quarters to all
  crew and attached personnel to be of primary importance. Indeed,
  living accommodations are one of the most visible displays of
  Starfleet's commitment to caring for its single most important
  "system," its people.
...
The living areas of the starship have been designed for maximum
  comfort and safety while the crew is conducting a mission. Long-term
  studies of humanoid cultures have confirmed that as each race embarked
  upon permanent occupation of space, large personal living spaces had
  to be established, especially on early sublight expeditions. The
  Enterprise allows for some 110 square meters of living space per
  person, in addition to community space and the areas allocated to
  purely working functions.
While some engineers on the Galaxy Class Project questioned the
  relatively large size of the vessel, opting for a smaller, more
  efficient design, it was conceded that the large size provided a
  greater number of mission options, given the changing social,
  political, and economic conditions in the Milky Way.

Do lesser crew members have less space?
Yes, crew quarters aboard the Enterprise-D (at least for Starfleet personnel) are assigned and sized according to rank. In the episode TNG : Lower Decks, we learn that junior officers (and probably enlisted crewpersons) are required to share quarters until they reach the rank of Lieutenant.

LAVELLE : Promote me, please -- so I can make Lieutenant and have my own room.
TAURIK : If you aren't happy sharing quarters with me, then you should put in for a new room assignment. Just in case you're not
  promoted.

Above the junior ranks, Senior officers are provided with staterooms and at least one extra room for work/study. Picard and Riker use this extra space as separated visiting areas, Data uses his extra room as a private workspace and  Troi uses hers as an informal workroom with her famously messy desk. The ship also contains "apartments" for officers who choose to bring their families on board, comprised of two normal sets of quarters combined into a single living area.

A: So many great answers. Wanted to throw in a few. Clearly, the out-of-world explanation helps explain the reality of the situation - big sets, easier to shoot (the TNG series was filmed on some fairly large studio equipment from the 1980s, cameras with wheels and tracks and such), and generally looks more glamorous, so it fits the theme of a Utopian-like future (for humanity, at least).
In-universe the long-duration missions are used to explain all "luxury-like" accommodations included (schools, arboretum, holodecks). It is established in "Lower Decks" that not everyone enjoys large quarters but our primary characters all have a good amount of space (similar to all the Trek series, excepting maybe Enterprise).
Technologically, it also makes more sense than it would on a modern day aircraft carrier. First, modern day aircraft carriers (from the US Fleet) have a personnel complement much higher. The recently deactivated USS Enterprise CVN65, for example, housed up to 4,600. TNG's Enterprise only houses ~1000 (including civilian families) with much larger emergency capacity.
Further, the Navy has to worry about gravity, whereas the Enterprise-D has to worry about structure. The larger those naval quarters, the more deck space, the more weight, the more furniture, etc. (just think how much space replicator functionality would save, food has to be stored somewhere). All of that mass adds up, so it's not so much that space is at a premium as it is mass. They could make bigger aircraft carriers but then they'd be even bulkier and more difficult to move, maintain and protect.
The Enterprise-D, with it's technology, just needs to form a stable warp-bubble and voila the "weight" of the thing is irrelevant. So you can afford spacious accommodations, large cargo decks, large shuttle bays (even the ones we see on camera were many times larger than the most efficient bay could imagine; ENT's shuttle bays for example) because your concern is the structural integrity of the vessel, not the weight.
The same could be said of modern spacecraft, things are tight because it's expensive to rocket all that mass into orbit. However, designs have been discussed like "inflatable spacecraft" that would allow relatively spacious accommodations. Just a matter of maintaining the integrity of the space vessel.
So, in-universe it makes sense that they'd have spacious quarters to match the rest of the spacious nature of the vessel. (Fun question)

A: Galaxy Class is an Explorer, to say the least, also a century since Starfleets prior vessels quarter size grew with technical complexity. As an explorer type it's got enough space (Cargo) to store several years worth of resources (spare parts, food stuffs, fuel)
People just don't understand how big it is. You could have the ENTIRE 1000 person crew on a single deck. For comparisons sake a Galaxy class has 1000 crew aboard with room for families and children. Using Constitution style quarters you could fit everyone on Deck 8.
An aircraft carrier holds 5500 on board (albeit the enlisted crew is triple bunked), The Titanic has room for 2000 passengers and 800 crew.

We only see Officers quarters on board the Enterprise D, we seldom see Enlisted quarters on board. Blueprints depict various multi-bed quarter rooms and four room apartments (families)

A: There are some pretty good answers here giving design philosophy etc. but lets just do a little rough math on the problem.
The Enterprise D is nearly 50 times the size of the aircraft carrier USS Enterprise (4.5 million tonnes vs. 95,000 tonnes displacement) yet it has a crew of 1012 against the 4600 crew of the carrier. Now NG Enterprise D has families as well so lets double its crew and add a little more to get 2300 or half the crew of the carrier (remember many of the crew are single).
This means that if the Enterprise D gave up as much of its space percentage wise as the carrier Enterprise, then each crew member would get 50 X 2 = 100 times the room available.
So now the enlisted crew instead of getting to share 1 room with 8 gets 12.5 rooms all to themselves.
Space on a ship the size of the Enterprise D simply would not be a issue; the ship architects can give spacious quarters quite easily without compromising other design needs of a starship.
Various supplements to Star Trek have shown that lower ranks do get smaller rooms then officers which is traditional in naval vessels.

A: The typical U.S. Navy deployment for a submarine or a surface ship is 3-6 months. In Star Fleet, the exploration missions last for years. NX-01 ultimately completed a 10 year mission of exploration. The NCC-1701 Enterprise originally had a 5 year mission. That is a long time to be in a ship.
From Memory-Alpha

Crew's quarters: The majority of the enlisted crew and junior officers share quarters and bunk areas on small- to medium-sized vessels. (VOY: "Flashback") On starships of the Constitution-class, crew's quarters were structured as double suites, with private sleeping areas sharing a common, central bathroom. On starships of the Galaxy-class, crewmembers ranked Lieutenant junior grade or higher are given their own quarters while personnel up to the rank of ensign are required to share quarters. (TNG: "Lower Decks")
Officers' quarters: Many starships feature separate quarters for higher-ranked officers. Usually, these staterooms are composed of two or more areas, featuring separate bed- and bathrooms and a dedicated work- and living area. (TNG: "Schisms")

Since the show focuses on the officers, with the only NCO of note bring Chief O'Brien (who has a family) we don't see much of the lower ranked officers or NCO quarters for regular crewmen. Here is an image of a room with double bunks and a common area.

As ships become larger, so do the accomodations. Here is a similar bunk bed situation on the NX-01

A: Modern warships have crew quarters that are extremely spacious compared to 18th century warships (which gave each man a space 14" wide in which to hang his hammock). Star Trek is merely extrapolating that trend into the future.

A: Somewhere, maybe even "Making of Star Trek" back in the 60s, Star Trek creator Gene Roddenberry was quoted as wishing to treat members of his space crew with a little more respect than one gets in the real-world navy. For the pilot episodes, the captains' quarters were designed per the producers' wishes; Kirk's was nice size, Picard's even bigger. For money reasons, those same rooms were reused when filming anyone else's quarters.
If you look at the deck plans sold for the 1701 ($5 in the 1970s!) and the 1701-D, they resemble cruise ships inside, with crew quarters stashed everywhere. In the 1701 plans, most rooms had 2 beds (I think).

A: It might sound trite, but I believe the main reason is because they can. The technology of the Federation allows starships with comfortable quarters. Sure, they could have extra phasers or cargo holds in that volume, but could they power those phasers? Do they need that cargo?

A: On the debate about replicators being space-saving – The energy matrix required to form dishes as well as the food itself can be just as easily de-materialized and is reclaimed as 'free' energy back into the EPS system. They function on technology similar to that of transporters, but with lower resolution. Another thing to consider is waste processing and reclamation. All biological wastes are fed into a processing location where, basically, those materials are vaporized into the same kind of energy and fed into the system. If you think about it in a strictly linear sense, it's kind of 'gross'. However, it's very efficient, which means that there is less deuterium and anti-deuterium consumed to create the energy needed for the process.
In the Trek verse, Matter/Anti-Matter Reactor Assemblies (MARAs) – a.k.a. the Warp Core – can produce tremendous amounts of energy from very little matter. This is in addition to what supplemental fusion reactors aboard ship also produce, which have also become remarkably efficient and compact. A Next Generation fusion reactor could fit into your bedroom without much extra needed. Oh, and they're much safer.
Another thing to consider is that, on the matter of structure, all TNG era and beyond Trek vessels and stations have 'structural integrity fields', which are basically reinforcing forcefields that snap on when needed to reinforce materials and points of stress. Concerns for size and mass are somewhat mitigated by the usage of these fields, especially during combat or other emergency situations. Federation ships are meant to be tough, and are designed for survivability. It was stated in another answer that a five- to ten-year mission out in the black, often with little to no support, is not uncommon.
These elements do play into the consideration when considering the size of quarters.

A: As many other have already stated, the Enterprise D was a cruise ship attached to a military vessel.  One of the key things to remember is that on the 178 episodes of The Next Generation we saw a VERY small percentage of the interior spaces of the ship.  The saucer module was where the vast majority of the living and recreational spaces were contained.  In the show, the saucer module was about 1000 feet across from port to starboard and 16 decks high from the bridge on deck one to the Captain's Yacht on deck 16.  We only saw a small sampling of crew quarters, some cargo bays, sickbay, the transporter room, a couple of lounges and ten-forward, sickbay, and the holodeck. There were complete blueprints drawn up for the entire ship that showed schools, restaurants, and five-deck high mall/promenade, aquatic research labs, a two-deck theater, and much more.  The budget constraints of the production limited what we saw on TV, but in-universe the ship was intended to be a city-in-space for over 1000 officers, civilians, and even children and spouses.  The USS Voyager was shown to be much smaller but also quite spacious relative to the number of people onboard.  The USS Defiant was much more akin to the accommodations of a modern naval vessel with shared accommodations for all crew and very tight interior spaces.  The galaxy-class Enterprise-D was not necessarily representative of life on every Starfleet vessel.


text:
Q: How do I fix: GET http://... 404 (Not Found) I have made a JS game. However, nothing shows up on the screen on localhost. When I check the console, I get the following error:
GET http://127.0.0.1:5500/socket.io/?EIO=3&transport=polling&t=NMFSX-v 404 (Not Found)
What does this error mean? How do I fix it?
code:
<!DOCTYPE html>

    <meta charset="UTF-8">
    <meta name="viewport" content="width=device-width, initial-scale=1.0">
    <link rel="stylesheet" href="../css/game.css">
    <title>Document</title>
    <canvas id="ctx" width="500" height="500" style="border: 1px solid #000000;"></canvas>

var express = require('express');
var app = express();
var serv = require('http').Server(app);

app.get('/', function(_req, res){
    res.sendFile(__dirname + '../clients/index.html');
});
app.use('../clients', express.static(__dirname + '../clients'));

serv.listen(2000);
console.log("Server started.");

var SOCKET_LIST = {};

var io = require('socket.io') (serv,{});
io.sockets.on('connection', function(socket){

    socket.id = Math.random()
    socket.x = 0;
    socket.y = 0;
    SOCKET_LIST[socket.id] = socket;
});

setInterval(function(){
    for(var i in SOCKET_LIST){
        var socket = SOCKET_LIST[i];
        socket.x++
        socket.y++
        socket.emit('newPosition', {
            x:socket.x,
            y:socket.y
        })
    };

},1000/25);

Please can you make sure to post potential solutions in the Answers section?
Thank you SO much for your help!!!
**Edit: Here is a screenshot of the error:

A: I think the error starts under the line
var io = require('socket.io') (serv,{});

try this block for the lines under instead
io.sockets.on('connection', function(socket){
    var socketID=Math.floor(Math.random())*80
    while(SOCKET_LIST[socketID]!=undefined){
      socketID=Math.floor(Math.random())*80
    }
    //all that drama above is to(at least meant to) prevent socket overlap(just in case that solves a problem)
    socket.id = socketID
    socket.x = 0;
    socket.y = 0;
    SOCKET_LIST[socket.id] = socket;
});

setInterval(function(){
    Object.keys(SOCKET_LIST).forEach((a,i)=>{
        var socket = SOCKET_LIST[i];
        socket.x++
        socket.y++
        socket.emit('newPosition', {
            x:socket.x,
            y:socket.y
        })
    })

},1000/25);

if this doesn't work then the problem is what the frontend tries to access(reason for that 100% strange link it tried to access)

A:
404 (Not Found)

It is the http-error-code for not finding an url.
Edit:
In your given script you call the js-file from the Content Delivery Network of socket.io: "https://cdn.socket.io/socket.io-1.4.5.js".
Check your local script if you mayby made a mistake with transforming it to  "http://127.0.0.1:5500/socket.io/?EIO=3&transport=polling&t=NMFSX-v"


text:
Q: How to use DATEPART of the GETDATE as a variable for a query This might be easier than I'm making it, I'm pretty new to SQL.
I have a database with a lot of movies release dates in the format YYYY-MM-DD.
I'm trying to write a query that would return films released on the current date (MM-DD) in various years.
I've tried using:
WHERE ReleaseDate LIKE '%-(DATEPART(mm,GETDATE())-(DATEPART(dd,GETDATE())'

But it doesn't return anything.
"WHERE ReleaseDate LIKE '%-06-03'" works but I'd really like to automate this.

A: Arrg!  Don't use LIKE with dates.
How about just doing something like this:
where DATEPART(month, ReleaseDate) = DATEPART(month(GETDATE()) AND
      DATEPART(day, ReleaseDate) = DATEPART(day, GETDATE())

Or, more simply:
where month(ReleaseDate) = month(getdate()) and
      day(ReleaseDate) = day(getdate())

A: You are treating datapart etc as a string literal by putting it inside the quotes.
You could use concat to build this string dynamically:
WHERE ReleaseDate LIKE CONCAT('%-',
                              (DATEPART(mm,GETDATE()),
                              '-',
                              (DATEPART(dd,GETDATE())
                             )


text:
Q: Arctan in complex logarithm form I tried to formulate the arctan function in a complex logarithmic form by integrating its derivative by using partial fraction decomposition. And I was wondering if my attempt is valid or not:
Using $\frac{d}{dz}\arctan(z) = \frac{1}{1+z^2}$ one knows that
$\int \frac{1}{1+z^2} dz =\arctan(z)$
Using partial fraction decomposition one gets
$ \frac{1}{1+z^2} = \frac{1}{(z-i)(z+i)} = \frac{1}{2i}\frac{1}{(z-i)} - \frac{1}{2i}\frac{1}{(z-i)}$.
Then one can integrate:
$\int \frac{1}{1+z^2} dz = \frac{1}{2i} \int \frac{dz}{(z-i)} - \frac{1}{2i} \int \frac{dz}{(z+i)} = \frac{\log(z-i) -\log(z+i)}{2i}$
So my result would be $\arctan(z) = \frac{\log(z-i) -\log(z+i)}{2i}$. Is this correct?
Any comment or advice would be highly appreciated!

A: $$\text{arctanh}(iz)=\sum_{i=0}\frac{(iz)^{2k+1}}{(2k+1)!}$$
but $$i^{2k+1}=i^{2k}i=\begin{cases}-i&\text{if }k\text{ is odd}\\i&\text{if }k\text{ is even},\\\end{cases}$$
then,
$$\sum_{i=0}^\infty \frac{(iz)^{2k+1}}{(2k+1)!}=i\sum_{i=0}^\infty \frac{(-1)^kz^{2k+1}}{(2k+1)!}=i\arctan(z)$$
and thus
$$\arctan(z)=\frac{\text{arctanh}(iz)}{i}.$$
But $\text{arctanh}(z)=\frac{1}{2}\ln\left(\frac{1+z}{1-z}\right)$ and so, we conclude that,
$$\arctan(z)=\frac{1}{2i}\ln\left(\frac{1+iz}{1-iz}\right)=\frac{\ln(1+iz)-\ln(1-iz)}{2i}.$$

A: As @gammatester mentioned, you forgot an integration constant.  But what value should this integration constant be?  We do know that we want $\arctan{(0)} = 0$.  Then we would have
$$\frac{\log{(-i)} - \log{(i)}}{2 i} + C = 0$$
What is $\log{(-i)}$?  Is $-i = e^{-i \pi/2}$, or $e^{i 3 \pi/2}$, or something else?  Regardless, the question is, is the difference between the logs then $i \pi$ or $-i \pi$?
Here we note that the principal value of the arctan is defined with respect to a branch cut $-i z \in (-\infty,-1] \cup [1,\infty) $.  Thus, we would take $-i = e^{-i \pi/2}$ and the difference between the logs to be $-i \pi$; thus, $C=\pi/2$. Thus
$$\arctan{z} = \frac1{2 i} \left [\log{(z-i)} - \log{(z+i)} - i \pi \right ]  = \frac{i}{2} \log{\left ( \frac{i+z}{i-z}\right )}$$

A: @gammatester: Yes, you are right! I missed that one! So using
(1)
$e^{i\frac{\pi}{2}} = \cos(\frac{\pi}{2}) + i\sin(\frac{\pi}{2}) = i$
in my formula
$\frac{\log(z-i) - \log(z+i)}{2i} + C ~~~~~~~~~$ for $z=0$
I get $C=\frac{\pi}{2}$.
Then using (1) again I can rewrite this as
$\frac{\log(z-i) - \log(z+i)}{2i} - i \cdot \log(i) =\frac{\log(z-i) +\log(i) - (\log(z+i)-\log(i))}{2i}$
By applying logarithm laws I then get the same result as @idm !
$\frac{\log(z-i) +\log(i) - (\log(z+i)-\log(i))}{2i} = \frac{\log(1+iz) - \log(1-iz)}{2i} = \arctan(z)$
Many Thanks to both of you! :)


text:
Q: floating View displaying on hover in android I am trying to implement some hints when a user is hovering a button or another view, I see that android have support for onHoverListener but I don't understand how it really works. However I did try to find a solution how to make a floating editText on a button hover but I didn't find any ideas.
I am thinking that hover in android is the same think with long click because you can't hover with finger without clicking the view.

A: OnHoverListener is only implemented in 2 specific situations: a) when a Bluetooth or USB mouse is plugged into the device, or b) on Galaxy Note devices, when the S-Pen (stylus) is hovering over the object.
In specific setups/situations this can be a very neat feature, but unfortunately, most users will never even know it exists. For your situation, you may want to implement an OnLongClickListener for showing hints/tips as that is pretty standard in Android.
This example will show a TextView or ImageView hint for 5 seconds when a long-click is initiated:
btn.setOnLongClickListener(new View.OnLongClickListener() {
    @Override
    public boolean onLongClick(View view) {
        findViewById(R.id.hint).setVisibility(View.VISIBLE);
        Handler handler = new Handler();
        handler.postDelayed(new Runnable() {
            public void run() {
                findViewById(R.id.hint).setVisibility(View.GONE);
            }
        }, 5000);
        return true;
    }
 });

Hope this helps,

A: I want to add up on Aaron's answer.
Some devices with sensitive screens - Samsung S5 comes to mind - don't even need an s-pen.
Just need to hold your finger 1/2 inch over the screen and it would trigger it.


text:
Q: Passing generic wildcard type to a method accepting generic type I'm writing some basic storage engine abstraction logic, but because different storage system use differently formatted primary keys (like Long for mysql, ObjectId for mongo) I'm using generics for my DBA.
public interface StorageAdapter<T> {
    Optional<PlayerModel<T>> getPlayer(OfflinePlayer offlinePlayer);
}

public class MysqlStorageAdapter implements StorageAdapter<Long> {
     ...
}

My application never knows the details of what type the storage is using, and it essentially doesn't care because that data is only used by the database. So I'm using wildcards:
Optional<? extends PlayerModel<?>> optionalPlayerModel = MyApp.getInstance().getStorageAdapter()
            .getPlayer(player);

What I don't understand is what my method signatures need to look like for passing in the data later:
void logPlayerConnection(PlayerModel<T> playerModel) { ... }

The optional type is ? extends PlayerModel<?> but a method I want to pass that value to is PlayerModel<T>. PlayerModel is the highest interface I can accept. My IDE tries to suggest making PlayerModel<T> extend PlayerModel<T> which obviously can't work.
I'm not sure how best to handle this.
EDIT: Here is the exact error when trying to pass the playerModel to the logPlayerConnection method:
java:35: error: incompatible types: PlayerModel<CAP#1> cannot be converted to PlayerModel<CAP#2>
                .logPlayerConnection(playerModel);
                                   ^
  where CAP#1,CAP#2 are fresh type-variables:
    CAP#1 extends Object from capture of ?
    CAP#2 extends Object from capture of ?

EDIT2: Here's a more complete breakdown of my objects:
public interface StorageAdapter<T> {
    Optional<PlayerModel<T>> getPlayer(OfflinePlayer offlinePlayer);

    void logPlayerConnection(PlayerModel<?> playerModel);
}

public interface PlayerModel<T> extends PrimaryKeyModel<T> {

}

public interface PrimaryKeyModel<T> {
    T getId();
}

public class SqlPlayerModel extends AbstractModel<Long> implements PlayerModel<Long> {

}

public abstract class AbstractModel<T> {
    protected final T id;

    public AbstractModel(T id) {
        this.id = id;
    }

    public T getId() {
        return id;
    }
}

// Use case:

PlayerModel<?> playerModel;
Optional<? extends PlayerModel<?>> optionalPlayerModel = storageAdapter.getPlayer();

if (optionalPlayerModel.isPresent()) {
    playerModel = optionalPlayerModel.get();
} else {
    playerModel = /* create logic here */
}

storageAdapter.logPlayerConnection(playerModel);


text:
Q: iOS MKMapView custom images display on top left corner I use iOS MKMapView to show images as marker icons on the map. The problem is the images are always displayed on the top left corner of the screen. If I touch the screen or move the map a little bit, the images show correctly at the right gps locations.
If I don't use custom images, the pins/markers are displayed correcly at the right location.
here is the code:
func addAnnotationsToMap()
{
    self.mapView.removeAnnotations(self.mapView.annotations)
    for post in self.posts
    {
        let gps = CLLocationCoordinate2D(latitude: post.GPS!.latitude!, longitude: post.GPS!.longitude!)
        let postPin = PostAnnotation(gps: gps)
        self.mapView.addAnnotation(postPin)
     }
}

func mapView(mapView: MKMapView, viewForAnnotation annotation: MKAnnotation) -> MKAnnotationView?
{
    if (annotation is MKUserLocation)
    {
        return nil
    }

    let postAnnotation = annotation as! PostAnnotation
    let reuseId = "customAnnotationView"
    var anView = mapView.dequeueReusableAnnotationViewWithIdentifier(reuseId)
    if anView == nil
    {
        anView = createCustomIconView(postAnnotation)
    }
    else
    {
        anView!.annotation = annotation
    }
    return anView
}

func createCustomIconView(postAnnotation:PostAnnotation) -> CustomAnnotationView
{
    let w = (UIScreen.mainScreen().bounds.size.width) / 8
    let h = w
    let customIconView = CustomAnnotationView(frame: CGRectMake(0, 0, w, h))
    customIconView.imageView.image = UIImage(imageLiteral: postAnnotation.picName!)
    customIconView.annotation = postAnnotation
    return customIconView
}

A: Believe it or not, the problem is fixed after I delete view.translatesAutoresizingMaskIntoConstraints = false
This answer is inspired from MKViewMap custom annotation disappears on click


text:
Q: Why is -didDeselectRowAtIndexPath not being called? I created a fresh project (Xcode 4, Master-Detail application) just to see if I'm doing something wrong, but I still have the same problem. I want to call -reloadData when the user deselects a cell, so this is my code:
- (void)tableView:(UITableView *)tableView didSelectRowAtIndexPath:(NSIndexPath *)indexPath
{
    [tableView deselectRowAtIndexPath:indexPath animated:YES];
    NSLog(@"%s", __PRETTY_FUNCTION__);
}

-(void)tableView:(UITableView *)tableView didDeselectRowAtIndexPath:(NSIndexPath *)indexPath {
    NSLog(@"%s", __PRETTY_FUNCTION__);
    [tableView reloadData];
}

-(NSIndexPath *)tableView:(UITableView *)tableView willDeselectRowAtIndexPath:(NSIndexPath *)indexPath {
    NSLog(@"%s", __PRETTY_FUNCTION__);
    return indexPath;
}

The problem is that didDeselectRowAtIndexPath and willDeselectRowAtIndexPath don't seem to be called. Is this the expected behavior? The docs for tableView:didDeselectRowAtIndexPath: state

Tells the delegate that the specified row is now deselected.

so I guess that it should work as I thought.

A: A clean way of solving this problem is to do the following:
func tableView(tableView: UITableView, cellForRowAtIndexPath indexPath: NSIndexPath) -> UITableViewCell {
    let cell = tableView.dequeueReusableCellWithIdentifier("myCell", forIndexPath: indexPath)
    // Do your cell setup work here...

    //If your cell should be selected...
    if cellShouldBeSelected {
        tableView.selectRowAtIndexPath(indexPath, animated: false, scrollPosition: UITableViewScrollPosition.None)
    }

    return cell
}

This solves this entire problem of a cell not responding to being deselected after a tableView.reloadData()call happens.

A: If you call deselectRowAtIndexPath:animated:, the delegate methods tableView:willDeselectRowAtIndexPath: and tableView:didDeselectRowAtIndexPath: message are not sent.

A: When any cell is selected the first time, the -[UITableViewDelegate tableView:didDeselectRowAtIndexPath:] method is not called, but the -[UITableViewDelegate tableView:didSelectRowAtIndexPath:]. Just after selecting one more cell, the didDeselectRowAtIndexPath is called right after the didSelectRowAtIndexPath.
This is OK.
But if you have to show a cell as selected at the begining, (e.q. using UITableViewCellAccessoryCheckmark), then, after selecting another cell you probably want the didDeselectRowAtIndexPath method being called the first time, to deselect the previous cell.
The solution!
You have to call the -[UITableView selectRowAtIndexPath:animated:scrollPosition:] in the -[UITableViewDataSource tableView:cellForRowAtIndexPath:] to notify that a wanted cell is already selected.
Objective-C
#pragma mark - UITableViewDelegate

- (void)tableView:(UITableView *)tableView didSelectRowAtIndexPath:(NSIndexPath *)indexPath
{
    UITableViewCell *cell = [tableView cellForRowAtIndexPath:indexPath];
    cell.accessoryType = UITableViewCellAccessoryCheckmark;
    // saving the current selected row
    SelectedRow = indexPath.row;
}

- (void)tableView:(UITableView *)tableView didDeselectRowAtIndexPath:(NSIndexPath *)indexPath
{
    UITableViewCell *cell = [tableView cellForRowAtIndexPath:indexPath];
    cell.accessoryType = UITableViewCellAccessoryNone;
}

#pragma mark - UITableViewDataSource

- (UITableViewCell *)tableView:(UITableView *)tableView cellForRowAtIndexPath:(NSIndexPath *)indexPath
{
    UITableViewCell *cell = [tableView dequeueReusableCellWithIdentifier:@"cell"];

    if (!cell) {
        cell = [[UITableViewCell alloc] initWithStyle:UITableViewCellStyleDefault reuseIdentifier:@"cell"];
    }

    // preventing selection style
    cell.selectionStyle = UITableViewCellSelectionStyleNone;

    cell.textLabel.text = "Some text";

    if (indexPath.row == SelectedRow) {
        cell.accessoryType = UITableViewCellAccessoryCheckmark;
        // just wanted to make it selected, but it also can scroll to the selected position
        [tableView selectRowAtIndexPath:indexPath animated:NO scrollPosition:UITableViewScrollPositionNone];
    }

    return cell;
}

Swift 3.1
// MARK: - UITableViewDelegate

override func tableView(_ tableView: UITableView, didSelectRowAt indexPath: IndexPath) {
    let cell = tableView.cellForRow(at: indexPath)!
    cell.accessoryType = UITableViewCellAccessoryType.checkmark
    selectedRow = indexPath.row
}

override func tableView(_ tableView: UITableView, didDeselectRowAt indexPath: IndexPath) {
    let cell = tableView.cellForRow(at: indexPath)!
    cell.accessoryType = UITableViewCellAccessoryType.none
}

// MARK: - UITableViewDataSource

override func tableView(_ tableView: UITableView, cellForRowAt indexPath: IndexPath) -> UITableViewCell {
    let cell = UITableViewCell(style: UITableViewCellStyle.default, reuseIdentifier: "cell")

    // preventing selection style
    cell.selectionStyle = UITableViewCellSelectionStyle.none

    cell.textLabel?.text = "some text"

    if (indexPath.row == selectedRow) {
        cell.accessoryType = UITableViewCellAccessoryType.checkmark
        // just wanted to make it selected, but it also can scroll to the selected position
        tableView.selectRow(at: indexPath, animated: false, scrollPosition: UITableViewScrollPosition.none)
    }

    return cell
}

A: the documentation of tableView:willDeselectRowAtIndexPath: also says that

This method is only called if there is an existing selection when the
  user tries to select a different row. The delegate is sent this method
  for the previously selected row. You can use
  UITableViewCellSelectionStyleNone to disable the appearance of the
  cell highlight on touch-down.

It not worked for we when I used UITableViewCellSelectionStyleNone.

A: You just have to set the selection to be "Multiple Selection" as Xcode allow you to deselect the cells in this mode only.
Xcode Screenshot

A: One other quirk that I've found — in IOS 5.1, at any rate — is that if you call reloadData on the table, you won't get didDeselectRowAtIndexPath for any selected rows. In my case, I adjust the cell layout slightly depending on whether it's selected or not, so I needed to manually do that work prior to reloading the table data.

A: I know this is an old question but I just ran into the same problem.
If you use
[tableView reloadData]

Then The table data is reloaded and no rows are selected behind the scenes - meaning
only
didSelectRowAtIndexPath

is ever called. I hope this helps someone who comes across this problem.

A: Set allowsMultipleSelection for that tableview to TRUE
  self.tableView.allowsMultipleSelection = YES;

A: For me it's started working by adding ->super.setSelected(selected, animated: animated)
override func setSelected(_ selected: Bool, animated: Bool) {
   super.setSelected(selected, animated: animated)//This was missing
}

A: I think it's just simple mistake!
Why don't you use following:
[self.tableView deselectRowAtIndexPath:indexPath animated:YES];

Instead of using just "tableView" in that line?
I guess, and pretty sure that above line would give you the solution!  hope this helped you, if you looked back at your old question!!!
Kudos! :)

A: First of all, you have to set allowsMultipleSelection is true and set delegate by below code
self.tableView.allowsMultipleSelection = true
self.tableView.delegate = self

If you use tableView.reloadData() in didSelectRowAt delegate method, remove this.
in your custom cell, use selected method.
override func setSelected(_ selected: Bool, animated: Bool) {
   super.setSelected(selected, animated: animated)
   //write your code here for selection method
}

By this method, your cell state is selected. If you again click on selected cell, then didDeSelect delegate method will call automatically.

A: One source of this issue is setting isSelected directly on the table view cell, rather than telling the table view to select the cell via selectRow(at:animated:scrollPosition:) or deselect it via deselectRow(at:animated:).
The cell's isSelected property is not the source of truth that the table view uses to determine whether to call the delegate's didDeselect method (although a cell whose isSelected is set does seem to prevent the table view from calling the delegate's didSelect method—meaning that the cell can get in a state where it is impossible to select or deselect via the UI).


text:
Q: Why does a query on a local instance with local database files cause NETWORK_IO waits? I have followed this tutorial to get the wait stats of a particular query while it is 'in flight' using extended events. Whilst the tutorial refers to an index rebuild, I just did a select statement from a single table
The waits (using the query in the tutorial) were
Wait Type            Wait Count  Wait Time  Resource Wait Time  Signal Wait Time
-------------------  ----------  ---------  ------------------  ----------------
NETWORK_IO                  693        778                 776                 2
SOS_SCHEDULER_YIELD           6          0                   0                 0

I ran the query in SSMS on the same box the instance is installed on (used . as my server name when connecting)
the data files for the database are on the C:/ drive of the box so I am confused as to why NETWORK_IO is showing?
As a further test, I disabled the network adapter on the box and found the same result (obviously with slightly different numbers)
Would I be right in thinking that NETWORK_IO relates to SQL server returning the result to SSMS?

A: Usually this surfaces as ASYNC_NETWORK_IO outside of Extended Events, but yes, it is the time SQL Server spent waiting for the caller (in this case SSMS) to consume the results. If the caller is slow (like SSMS) then SQL Server has to sit there and wait before feeding more rows. If you have a wide result set or large values, you should compare results to grid and results to text. But really, you shouldn't be timing anything based on response times in SSMS, since it does unrealistic things with the data and how it renders that your application won't be doing (hopefully).
I wrote about this wait type (and 9 other common ones) here:

*

*What to do (or not do) about top wait stats


text:
Q: Beating a greedy algo For class we have a grid and a bunch of squares on the grid that we need to detect and travel to. We start at (0,0). We scan tiny regions of the grid at a time (for reasons regarding our data structure it's mandatory), and when we detect squares that we need to travel, and then we travel. There are 32 locations on the grid, but we only need to travel 16 of them, and as fast as possible (we're racing someone else to them).
Dijkstra's algo would find the shortest path from our current location to our next location. This is sub-optimal however, because our next location may be really far from the location after that. It would be more beneficial if we could somehow figure out the density of locations as we scan, and then choose to go to a very dense place and travel all the locations within that area.
Is there an algorithm best suited for a situation like this? I know the greedy heuristic isn't optimal. A* and Dijkstra's are the ones we thought about at first but we are hoping there's a completely different solution.
PS this is being done in assembly, unfortunately.

A: Finding dense clumps of points (e.g. locations you have to visit) is called cluster analysis. See the link for several classes of algorithms.
Assembly language is a really painful way to experiment with high-level algorithms. Is your prof a sadist??


text:
Q: How to add double qoutes to all values inside a vector? I have a vector
a <- c(one, two, three)

and I need it to become
a <- c("one", "two", "three")

Is there a way to do this using programming?

A: ls() will return a character vector of the names of all the variables defined in your environment. So if one, two and three are the only variables you've defined then it will give you what you want. You can ensure there is nothing else in your environment by using rm(list = ls()).
rm(list = ls()) # clear environment
one <- 1; two <- 2; three <- 3 # assign your variables
a <- ls() # capture variable names
a # inspect output
#> [1] "one"   "three" "two"

Created on 2022-11-05 with reprex v2.0.2


text:
Q: Angular material tab navigation loses active mark when route query parameters change I am using angular material navigation tab:
<nav mat-tab-nav-bar>
    <a mat-tab-link
        [routerLink]="'firstRoute'"
        [queryParams]="{param1: value1, param2: value2}"
        routerLinkActive #rla1="routerLinkActive"
        [active]="rla1.isActive">
    Import
    </a>
    <a mat-tab-link
        [routerLink]="'secondRoute'"
        [queryParams]="{param1: value1, param2: value2}"
        routerLinkActive #rla2="routerLinkActive"
        [active]="rla2.isActive">
    Database
    </a>
</nav>

Everything works fine, until I change query parameters value:
changeQueryParams() {
    const params = {
      param1: 'newValue1',
      param2: 'newValue2'
    };
    this.router.navigate([], { relativeTo: this.route, queryParams: params });
}

Every time I call this method, current tab loses activation mark (blue border below text). What I missed here ?

A: probably it is a bit late, but try adding queryParamsHandling="merge" to the mat-tab-link tag. It will also keep the parameters when you navigate between tabs.
<a mat-tab-link
    [routerLink]="'firstRoute'"
    [queryParams]="{param1: value1, param2: value2}"
    routerLinkActive #rla1="routerLinkActive"
    queryParamsHandling="merge"
    [active]="rla1.isActive">
Import
</a>

It works for me.


text:
Q: Internal Mor of schemes Let $S$ be a Noetherian scheme and $X,Y$ be $S$-schemes of finite type. Consider the functor $X^Y$ given by $T \mapsto Mor_S(Y \times_S T,X)$. When is this functor representable by an $S$-scheme of finite type?
Is it true when $Y \rightarrow S$ is finite and flat?
In http://www.math.harvard.edu/~gaitsgde/grad_2009/SeminarNotes/Sept17(Bun(G)).pdf (Thm 1.6) it is shown that $X^Y$ is representable if $X \rightarrow S$ is quasi-projective and $Y \rightarrow S$ is projective. Dennis Gaitsgory explained to us that this implies that  $X^Y$ is representable by a locally finite type scheme.


text:
Q: Directing functions with Jquery directly to single instances of a class I have a series of
's with the same class that are auto generated by a system. They have no ID values to it. I am trying to change the properties of the single instances of the class.
Here's the HTML

something

something

something

something

something

something

What I'm trying to do is make it so that all of the
s are collapsed to just show the first
something
 if you click the
 then it expands to its full size.
The problem I have is that the amount of
's can change as the content can be uploaded.
I'm trying to obtain each of the div's height before using jquery to set the css height properies to only show the first
 of each div. Then on a click event of the div's expand to their full size.
Here's my Jquery:
var height = ('.test').height());

$('.test').css('height','25');

$('.test').click(function(){
    $(this).animate('height', height);
});

I can't get the function to work directly to the single instance of the class object.
fiddle

A: You could use not(:first-child) selector to get the li elements which are not the first child.
$('li:not(:first-child)').hide();

$('.test').click(function(){
    var $this = $(this),
        list = $this.find('li:not(:first-child)');
    $this.data('collapsed', !$this.data('collapsed'));
    $this.data('collapsed') ? list.fadeIn() : list.fadeOut();
});

SEE THE WORKING DEMO.

A: You can try with this:
var h = $('.test').find('li:eq(0)').height();

$('.test').css({'height': h, 'overflow' : 'hidden'});

$(document).on('click', '.test', function(){ // delegate the event
    if($(this).css('overflow') === 'hidden'){
        $(this).removeAttr('style');
    }else{
        $(this).css({'height': h, 'overflow' : 'hidden'});
    }
});

You need to have a event delegation because as you mentioned that it is system generated, I have delegated to the $(document) but you can delegate to the element which was available when page was first loaded like parent of .test.

A: Try this:
$('.test').each(function() {
    $(this).find('li').hide().eq(0).show();
});
$('.test').click(function() {
    $(this).find('li').show();
});

jsFiddle


text:
Q: Cannot increment a simple value in redux store I am very new to react and redux and still trying to wrap my head around basics.
I need to use boilerplate for the project that is upcoming, where redux is split in different folders and files  -  actions, reduces, store. Like so:
Redux
├── actions
│   ├── actionTypes.js
│   ├── counterActions.js // created by me
│   └── usersActions.js
├── reducers
│   ├── counterReducer.js // created by me
│   ├── index.js
│   ├── initialState.js
│   └── usersReducer.js
└── store
    └── configureStore.js

So here, I am simply trying to display data from my store to my app and manipulate it with a button clicks (increment, decrement).
Here is my files content:
./actions/actionTypes:
export const GET_REQUESTER_SUCCESS = 'GET_REQUESTER_SUCCESS';
export const COUNTER_INCREMENT = 'COUNTER_INCREMENT';
export const COUNTER_DECREMENT = 'COUNTER_DECREMENT';

./actions/counterActions:
import * as types from './actionTypes'

export const counterIncrement = () => {
    return {
        type: types.COUNTER_INCREMENT,
    }
}

export const counterDecrement = () => {
    return {
        type: types.COUNTER_DECREMENT,
    }
}

./reducers/counterReducer.js:
import * as types from "../actions/actionTypes";
import initialState from "./initialState";

export default function changeCounter(state = initialState.counter, action) {
  switch (action.types) {
    case types.COUNTER_INCREMENT:
      console.log('increment')
      return state + 1
    case types.COUNTER_DECREMENT:
      console.log('decrement')
      return state - 1
    default:
      return state;
  }
};

./reducers/initialState.js:
export default {
  users: {},
  counter: 0,
};

All the reducers are then combined in the ./reducers/index.js files:
import { combineReducers } from 'redux';
import users from './usersReducer';
import changeCounter from './counterReducer'

const rootReducer = combineReducers({
  users,
  changeCounter,
});

export default rootReducer;

And last but not least, snippet of the App where I am displaying and trying to increment my counter:
import PropTypes from 'prop-types';
import './App.scss';
import { connect, useSelector, useDispatch } from 'react-redux';
import HelloWorld from './components/HelloWorld'
import { counterIncrement } from './redux/actions/counterActions';

function App(props) {
  const { users } = props;
  const { requester = {} } = users;
  const counter = useSelector(state => state.changeCounter)
  const dispatch = useDispatch();
  return (

      <HelloWorld />

Counter is {counter}

      <button onClick={() => dispatch(counterIncrement())}>+</button>
      <button>-</button>

So, as far as I understand - my reducer is created, it is combined with another one (comes with boilerplate and works well).  I am dispatching an action (which I can see in redux dev tool being dispatched), but my reducer is just not doing an increment.
What would be the reason for that.
Please let me know if I provided insufficient information.

A: I think it's typo mistake, change types to type :
In ./reducers/counterReducer.js
export default function changeCounter(state = initialState.counter, action) {
  switch (action.types) { // <----- ISSUE

change it to :
export default function changeCounter(state = initialState.counter, action) {
  switch (action.type) { //<---- CHANGE

WORKING DEMO


text:
Q: Different sleep binaries on Mac (Darwin) and in Linux. How to properly handle the differences? In my Linux box, sleep accepts seconds, minutes and hours. So:
sleep 10m

Sleeps for 10 minutes (or 600s).
sleep on Mac only accepts seconds as argument. sleep 10m doesn't work, only sleep 600s.
What can I do? Create a function named sleep that converts when 10m or 10h is passed as a parameter to seconds, and calls the builtin sleep?

A: sleep on Linux accepts seconds too (at least all the versions I've ever seen); can't you just use sleep 600 on both?

A: You could use homebrew for Mac OS X: https://github.com/mxcl/homebrew and install the coreutils package from there. That will allow you to install the GNU version of sleep that handles the same parameters as the linux version.
Note that by default it installs the binaries with a 'g' prefix, so the command will actually be named gsleep, but the package provides a script file to alias all commands.


text:
Q: About settings when outputting an axis camera to a network video recorder manufactured by another company About settings when outputting an axis camera to a network video recorder manufactured by another company
Equipment used
axis camera P3905-R Mk II
Network video recorder VIGI NVR1008H (tp-link)
Poe-compatible switching hub ETG-POE04 (IODATA)
Monitor LCD-10169VH5 (manufactured by Century)
In order to record and monitor output from the axis camera to the network video recorder, the network video recorder is connected to the axis camera with a lan cable (cat.5e) via a poe-compatible switching hub.
The network video recorder and the monitor are connected by hdmi cable.
After turning on the power, the network video recorder finds the presence of the axis camera, but the connection status displays "Insufficient bandwidth" or "Not authorized" and the image of the axis camera cannot be output to the monitor.
The ip camera (powered by poe) made by another company is recognized by the video recorder without any problem and can be output to the monitor.
Is there anything I should change in the browser settings of the axis camera?
Translated with www.DeepL.com/Translator (free version)


text:
Q: How to add stream in coverity I am new to Coverity Analysis. I need to add Stream in Coverity, how can I achieve this.
Below is my script
-solution:'nameofsolution.sln' -targets:"Rebuild" -configuration:"Release" -platform:"x64" -coverityHost:"%system.CoverityHost%" -coverityPort:%system.CoverityPort% -coverityUser:"%system.CoverityUser%" -coverityPassword:"%system.CoverityPassword%" -coverityStream:"TEST" -coverityOutputDir:"%env.CoverityWorkFolder%" -triggerType:'%teamcity.build.triggeredBy%' %ForceCoverity%.

Now, where and how can I add stream "TEST" in Coverity. Thanks for your help !!

A: cov-manage-im --host "<YOUR_HOST>" --user="<USER_NAME>" --password="<PASSWORD>" --mode streams --add --set --name:<STREAM_NAME>

For future reference, pass the "--help" flag to cov-manage-im to see if it has what you need.

A: I am not sure whether your script is right, your workflow and what kind of script it is.
To create a new stream just navigate your browser to Coverity connect and create one. Make sure you actually have permissions to add streams to your project.
In coverity connect you have one option like configuration in right most top corner.In that you can find Projects and stream which already created. You have to add(+stream) and name the stream name.Then It will be added.
You can use that stream in your script.
Example:
cov-commit-defects --dir /Users/admin/Coverity_intermediate_file_directory --host 192.178.196.125 --port 8080 --user admin --password admin123 -stream stream_name

Replace stream_name with your streams name which you have created in coverity connect.


text:
Q: Listen to Changes on 2 Dependent Fields in Angular 9 Reactive forms I have 2 form fields in angular reactive forms, where when I change the % gain, the price changes immediately, and when the price is changed, the % is computed and changes immediately.
I did the following:
const avgPrice = this.totalStockProductForm.get('AVERAGE_PRICE').value;
this.totalStockProductForm.get('PERCENTAGE_GAIN').valueChanges.subscribe(percentage => {
    this.totalStockProductForm.controls['FINAL_PRODUCT_PRICE'].patchValue(
        avgPrice + avgPrice * (percentage / 100)
    );
});
this.totalStockProductForm.get('FINAL_PRODUCT_PRICE').statusChanges.subscribe(finalPrice => {
    this.totalStockProductForm.controls['PERCENTAGE_GAIN'].patchValue(
        ((finalPrice - avgPrice) / avgPrice) * 100
    );
});

I know, and it eventually happened, this will lead to infinite loop. How can I achieve my goal of changing one entry and previewing change immediately on the other?

A: const avgPrice = this.totalStockProductForm.get('AVERAGE_PRICE').value;
this.totalStockProductForm.get('PERCENTAGE_GAIN').valueChanges.subscribe(percentage => {
    this.totalStockProductForm.controls['FINAL_PRODUCT_PRICE'].patchValue(
        avgPrice + avgPrice * (percentage / 100),
        { emitEvent: false }
    );
});
this.totalStockProductForm.get('FINAL_PRODUCT_PRICE').statusChanges.subscribe(finalPrice => {
    this.totalStockProductForm.controls['PERCENTAGE_GAIN'].patchValue(
        ((finalPrice - avgPrice) / avgPrice) * 100,
        { emitEvent: false }
    );
});

adding { emitEvent: false } will block detecton of other events on the other fields which resolves the infinite loop issue! Hope it helps someone!


text:
Q: LINQ First vs Find performance considerations We have a system that does all kinds of complex and simple select queries.
We did some simple testing and got these results:
Query 3.9 seconds :
var result = (from temp in context.model
               where temp.ID == 1302
               select temp).First();

Start Transaction time: 17:54:58.7073806
End Transaction time: 17:55:02.6246046

Query 3.7 seconds :
Model modelResult = context.Model.Find(1302);

Start Transaction time: 17:53:51.1995194
End Transaction time: 17:53:54.8737295

I have been reading trying to figure out what the best options are. There is a lot of conversation of this topic on this site, however, I have not found exactly what I need.
I know that query choices are situational (based off the complexity of the query, etc) but in the case when we need a single entity based off a key that will not be used again (meaning, in the case of Find, caching doesn't matter because that query is very unlikely to be called again) is it better to use direct LINQ or continue to use Find?
Is the cost of caching the results of Find, when it won't be used, too costly? Are the results of our simple test accurate enough to assume Find will always be faster in a single entity/key situation?
I didn't test the LINQ with turning off tracing, would this be a better approach than the two examples given?

A: The two are not exactly the same.
Find will check to see if the entity has already been loaded in the context.  If it has, it will just return it without performing a query.  In this scenario, it will likely be far more efficient.
However, if the entity is not in the context, it performs a query more like SingleOrDefault rather than first, which will require pulling the top two results back from the server.  While there is no overhead on constructing the query, the query itself will potentially be (very slightly) slower due to that, and the results will differ, as you'll receive errors if there is more than a single match.
For more details and information, including the generated queries, see this Slauma's answer here.


text:
Q: Plugin-like architecture in .NET I'm trying to implement a plug-in like application. I know there are already several solution out there but this is just going to be proof of the concept, nothing more. The idea would be to make the application main application almost featureless by default and then let the plugins know about each other, having them have implement all the needed features.
A couple of issues arise:

*

*I want the plugins at runtime to know about each other through my application. That wouldn't mean that at code-time they couldn't reference other plugin's assemblies so they could use its interfaces, only that plugin-feature initialization should be always through my main app. For example: if I have both plugins X and Y loaded and Y wants to use X's features, it should "register" its interest though my application to use its features. I'd have to have a kind of "dictionary" in my application where I store all the loaded plugins. After registering for interest in my application, plugin Y would get a reference to X so it could use it. Is this a good approach?

*When coding plugin Y that uses X, I'd need to reference X's assembly, so I can program against its interface. That has the issue of versioning. What if I code my plugin Y against an outdated version of plugin X? Should I always use a "central" place where all assemblies are, having there always the up to date versions of the assemblies?

Are there by chance any books out there that specifically deal with these kinds of designs for .NET?
Thanks
edit: I think people are drifting away from the 2 questions I made. I can take a look at both MEF and #develop, but I'd like to get specifics answers to the questions I made.

A: I recommend looking into MEF. This is a new way of doing plugins in .NET. It is the recommend way of doing new addins for VS2010, for example. I've not used it myself, but what I've looked into about it looks great. Adding this as an answer on prodding of others :)

A: Look into the System.AddIn namespace.  It's a little lower-level than MEF, and so should give you the "implement it myself" experience you're looking for.

A: There is a good book on building what you are looking for: Dissecting a C# Application: Inside SharpDevelop.  Here's a link: http://www.icsharpcode.net/OpenSource/SD/InsideSharpDevelop.aspx
The SharpDevelop application is fully plugin-based and the book talks about how they built it, the pitfalls they faced, and how they overcame it.  The book is freely available from the site, or you can buy it too.

A: Once I done it using this example. I loved it, but it was couple years ago, I think there might be better solutions now. As long as I remember the basic idea was that there is abstract class in your program, and your plug-ins inherit that class and compiled as DLLs... or something similar using Interfaces. Anyways that approach worked great for me. Later I added a filesystemwatcher so it could load those DLL plugins while it is running.
To load an Assembly
To get the types the assembly exposes

A: About the two specific issues you exposed:
1) I'm not sure what are you trying to achieve, but my guess is that you want to have lazy initialization of features, and maybe lazy loading of add-ins. If that's the goal, what you are proposing might work. So it could work like this:

*

*The Y plugin provides a list of features it needs to use (it could be done for example through a specific interface implementation or through an xml manifest).

*The X add-in implements an API which allows initializing a feature, with a method like Initialize(featureId).

*The host application gets the feature list required by Y, loads/initializes the X plugin, and calls Initialize for each feature.

*The host application also provides a GetFeature() method which Y can use to get a reference to a 'feature' object, which would be implemented in X.

However, if the plugin Y has direct access to the X API, I think it is unnecessary to have all that infrastructure for registering features. Y can just access the X features by directly using the X API, and Y would take care of lazy initializing each feature when required. For example, Y could just call SomeXFeature.DoSomething(), and the implementation of that class would initialize the feature the first time it is used.
2) If the API of an assembly changes, any assembly depending on it may break. Plugins are just assemblies which depend on other assemblies, so they will also break. Here are some things you can do to alleviate this problem.

*

*Assign a version number to each plugin. This could be just the assembly version.

*When loading a plugin, ensure that all dependencies can be properly satisfied (that is, all plugins on which it depends must be present and have the required version). Refuse to load the plugin if dependencies can't be satisfied.

*Implement a plugin management tool, to be used for all plugin install/uninstall operations. The manager can check dependencies and report errors when trying to install plugins with unsatisfied dependencies, or when trying to uninstall a plugin on which other plugins depend.

Similar solutions are used by the Mono.Addins framework. In Mono.Addins, each add-in has a version number and a list of add-ins/versions on which it depends. When loading an add-in, the add-in engine ensures that all dependent add-ins with the correct versions are also loaded. It also provides an API and a command line tool for managing the installation of add-ins.


text:
Q: Nopcommerce view not updating I updated the view CategoryTemplate.ProductsInGridOrLines in NopCommerce source code and also added custom code in CatalogController > Category action.
The breakpoints are hitting in the controller code but the View breakpoints are disabled. It says a copy for the view is found and source code is newer.
The controller is sending the updated data but the view is not rendering it the way I want. I also tried adding the random string on the view and it is still not showing that string on the page or in its source code in the browser.
I cleaned and rebuilt the solution. I cleaned the NopCommerce cache. I published it to Azure and restarted the app. But still, the new view updates are not visible. What should I do?
UPDATE
Looks like there is some problem with NopCommerce caching system. I returned the view by mentioning the View file path directly and it worked. I tried clearing NopCommerce cache from admin but it didn't work.

A: While working view pages in nopCommerce, bear in mind, there are multiple places from view pages being served; inside plugin (if you'd have override any), default view pages and theme pages.
Default nopCommerce code uses view pages from root folder(i.e. from Views folder); however, if you've enabled the theme, it will use pages from theme folder. So, make sure you're referring right pages.


text:
Q: Why am I receiving a SQL Insert procedure ERROR. Msg 60060? I have the following query and error.  Why am I receiving this error? I found nothing online via Google.
MSSQL query:
INSERT INTO [CEPrekyba].[dbo].[BK1$REFGoodUnit]
([GoodCode],[UnitCode],[UnitName],[IsCommon]
,[IsAccount],[Rate],[IsPack],[IsInteg]
,[IsSize],[Lenght],[Height],[Width]
,[Weight],[GrossWeight]
,[IsReusable],[ManualInserted])
VALUES ('530162','VNT','Gamintojas','1',
'1','1,00','0','0',
'0','0,00','0,00','0,00',
'0,00','0,00','0','1')

Error message:
Msg 60060, Level 16, State 1, Procedure sp_sRaiseError, Line 13
Msg 3609, Level 16, State 1, Line 1
The transaction ended in the trigger. The batch has been aborted.


text:
Q: get child nodes having large data from firebase realtime database I want to get child of node using addValueEventListener(). when books data is few, it works properly but when books count is more than 30000 it gives error as "java.lang.RuntimeException: Firebase Database encountered an OutOfMemoryError. You may need to reduce the amount of data you are syncing to the client (e.g. by using queries or syncing a deeper path)."
Firebase data structre is as
booksData
    123 (book id)
        bookname : ""
        writer   : ""
        price    : ""
        category : ""
        publicher : ""
        ...
    456 (book id)
        bookname : ""
        writer   : ""
        price    : ""
        category : ""
        publicher : ""
        ...
    .... and so on. having vast data

(Data structure & name is changed just for sample)
I tried in android as
userIDRef1.child("booksData").addValueEventListener(new ValueEventListener() {

        @Override
        public void onDataChange(@NonNull DataSnapshot dataSnapshot) {
            Log.e(TAG, "in get booksData");

            ArrayList<BooksWrapper> booksList = new ArrayList<>();

            for (DataSnapshot postSnapshot : dataSnapshot.getChildren()) {

                BooksWrapper vtw = postSnapshot.getValue(BooksWrapper.class);
                booksList.add(vtw);
            }

            userIDRef1.child("booksData").removeEventListener(this);
            Log.e(TAG, "daybooks data size is : "+booksList.size());
            if (booksList.size() >0){
                db.addBookData(booksList);
            }
        }

        @Override
        public void onCancelled(@NonNull DatabaseError error) {
            // Failed to read value
            Log.e(TAG, "Failed to read app title value.", error.toException());
        }
    });

is there any way to get data in chunks as first 1000 books then next 1000 & so on...? Any solution please...


text:
Q: Formula to get the right elimination of data on 2 groups I have been working for a part of my program which suppose to eliminate/delete items which has a contradicting type with the same values. Here is an example.
Group A.
Symbol     Type      Volume.
EURUSD     Buy       10.
EURUSD     Buy       2.
EURGBP     Buy       10.
Group B
Symbol     Type     Volume.
EURUSD     Sell     2
EURUSD     Sell     5
EURGBP     Sell     10
There are 2 EURUSD on Group A and also 2 EURUSD on Group B. We cannot easily eliminate the first item EURUSD since it has a volume 10 while in Group B the value of first EURUSD is at 2. We easily get the difference on it given that in the Group A item has a larger volume which leaves:
Group A
Symbol     Type      Volume
EURUSD     Buy       8
EURUSD     Buy       2
EURGBP     Buy       10
Group B
Symbol     Type     Volume
EURUSD     Sell     5
EURGBP     Sell     10
same thing here. since EURUSD on Group A is larger than the EURUSD on Group B, we subtract again and eliminate.
Group A
Symbol     Type      Volume
EURUSD     Buy       5
EURUSD     Buy       2
EURGBP     Buy       10
Group B
Symbol     Type     Volume
EURGBP     Sell     10
and since there is no EURUSD left on Group B, we can proceed with the other symbol EURGBP and since they have the same volume as the EURGBP on Group B, we can easily eliminate both which brings us:
Group A
Symbol     Type      Volume
EURUSD     Buy       8
EURUSD     Buy       2
Group B
Symbol     Type     Volume
and that leaves us with only 2 remaining items both EURUSD with 8 and 2 respectively.
I have tried this on but i cannot get the results that i want.
Do you have any formula, algorithm that you can share or examples perhaps.
Thank you very much.


text:
Q: Angularjs pagination only display 1 I cant paginate the data that return from my $http it only display only 1 page. I follow this plunker but still dont know the problem why it dont paginate.
This is my script
$scope.currentPage = 1;
$scope.numPerPage = 2;
$scope.maxSize = 5;

$scope.makeTodos = function() {
    $scope.todos = response.data; //return of $http
}
$scope.makeTodos();

$scope.$watch('currentPage + numPerPage', function() {
    var begin = (($scope.currentPage - 1) * $scope.numPerPage);
    var end = begin + $scope.numPerPage;

    $scope.names = $scope.todos.slice(begin, end);
    console.log($scope.todos.slice(begin, end));
});

This is the inside of response.data
{"id":"1","name":"name 1","description":"description 1","field3":"field3 1","field4":"field4 1","field5 ":"field5 1"},
{"id":"2","name":"name 2","description":"description 1","field3":"field3 2","field4":"field4 2","field5 ":"field5 2"},
{"id":"3","name":"name 3","description":"description 1","field3":"field3 3","field4":"field4 3","field5 ":"field5 3"},
{"id":"4","name":"name 4","description":"description 1","field3":"field3 4","field4":"field4 4","field5 ":"field5 4"},
{"id":"5","name":"name 5","description":"description 1","field3":"field3 5","field4":"field4 5","field5 ":"field5 5"},
{"id":"6","name":"name 6","description":"description 1","field3":"field3 6","field4":"field4 6","field5 ":"field5 6"},
{"id":"7","name":"name 7","description":"description 1","field3":"field3 7","field4":"field4 7","field5 ":"field5 7"},
{"id":"8","name":"name 8","description":"description 1","field3":"field3 8","field4":"field4 8","field5 ":"field5 8"},
{"id":"9","name":"name 9","description":"description 1","field3":"field3 9","field4":"field4 9","field5 ":"field5 9"},
{"id":"10","name":"name 10","description":"description 1","field3":"field3 10","field4":"field4 10","field5 ":"field5 10"}

EDITED
This is my HTML

Todos

{{todos.length}} total

{{x.id}}

{{x.name}}

{{x.description}}

{{x.field3}}

{{x.field4}}

{{x.field5}}

    <pagination
      ng-model="currentPage"
      total-items="names.length"
      max-size="maxSize"
      boundary-links="true">
    </pagination>

A: In your pagination component just add items-per-page='numPerPage' attribute then your paging will work accordingly
Your final code will be like
<pagination
      ng-model="currentPage"
      total-items="names.length"
      items-per-page='numPerPage'
      max-size="maxSize"
      boundary-links="true">
</pagination>

Here is updated example Plunker


text:
Q: Is there a way to programmatically retrieve the Http Archive (HAR) from chrome via remote debugging? From the network panel in a developer tools, a right click will allow "Copy all as HAR" or "Save as HAR with content" however I can't find a way to achieve that functionality programmatically. Does anyone know how to accomplish this?
Using the remote debugging functionality I can access information from the console, EG I can retrieve the timings for the page. Is there a command that would allow me to pull the entire HAR? Any help would be greatly appreciated.

A: This is a node module that gets closest to what you want:
https://github.com/cyrus-and/chrome-har-capturer
Note: This node module still has important unresolved timing issue. As an alternative, you can check this out:
https://github.com/parasdahal/speedprofile


text:
Q: Google Sheets, Moving from one Tab to another via input I am trying to get this script working where it will work when I put a "yes" or "no" for a choice it will move based on the "yes" to the targeted sheet "Completed Dispatch"
The original sheet is called "Tracker" and the column that I need it to check the "Yes or No" is called "Dispatched"
It doesn't work and I am not that great in GAS
The actual problem I am having is when I make the decision from no to Yes it does not move the row and does not do anything at all.
function onEdit(e) {

    var ss = e.source,
        sheet = ss.getActiveSheet(),
        range = e.range,
        targetSheet,
        columnNumberToWatch = 9; // column A = 1, B = 2, etc
    if (sheet.getName() === "Tracker" && e.value === "Dispatched" && e.range.columnStart === columnNumberToWatch) {
        targetSheet = "Completed Dispatch"
    } else if (sheet.getName() === "Completed Dispatch" && e.value === "Incomplete" && e.range.columnStart === columnNumberToWatch) {
        targetSheet = "Tracker"
    }
    ss.getSheetByName(targetSheet)
        .appendRow(sheet.getRange(e.range.rowStart, 1, 1, sheet.getLastColumn())
            .getValues()[0])
    sheet.deleteRow(e.range.rowStart);
}


text:
Q: Underscore (_) not working in headers name Apache 2.4 We've using some headers for authentication in our API
Request:
URL: http://lapi.domain.in/test

Header: {AUTH_TOKEN :NUBibTM0QHJkMzM5}

But trying to get header AUTH_TOKEN , its return nothing.
$auth_token = $request->header('AUTH_TOKEN');

Note: other headers working fine and when its name has been changed
  too AUTH-TOKEN then its working.

Apache 2.4, PHP 5.6
Thanks

A: I believe it's related to Apache and not Laravel;
There was a similar issue with Authorization headers in previous versions which was solved by allowing the Authorization headers through htaccess to fix it:
RewriteEngine On
RewriteCond %{HTTP:Authorization} .
RewriteRule .* - [E=HTTP_AUTHORIZATION:%{HTTP:Authorization}]


text:
Q: Timeout when reading users from page when calling transitive member api on a group I have an Azure Durable Function (consumption plan) with two activity functions:
Activity function 1 is to get transitive members from group from first page:
public async Task<IGroupTransitiveMembersCollectionWithReferencesPage> GetPageByIdAsync(string groupId)
{
                             await grapClient
                                .Groups[groupId]
                                .TransitiveMembers
                                .Request()
                                .Top(999)
                                .GetAsync();
}

Activity function 2 is to get transitive members from group from next page:
public async Task<IGroupTransitiveMembersCollectionWithReferencesPage> GetNextPageAsnyc(
            IGroupTransitiveMembersCollectionWithReferencesPage groupMembersRef,
            string nextPageUrl)
 {             groupMembersRef.InitializeNextPageRequest(graphClient, nextPageUrl);
                groupMembersRef
                 .NextPageRequest
                 .GetAsync();
 }

I see Activity Function 2 is exceeding 10 minutes. Is there a way to resolve that?

A: I think that you can set functionTimeout for Azure Durable Functions in host.json but according to the documentation the maximum timeout for consumption plan is 10 minutes.
You can either reduce the page size by set value for Top method < 999 or check if you can apply some retry handling for Azure Durable Functions.


text:
Q: Get the Max Length of a column in Entity Framework When I import a Database to my EDMX Model I get the following information regards to the Max Length

In the image above, I have String column with the Max Length of 250
Is there a way to check (while coding) this max length, without the need to look into the EDMX property?

Sample of how I want the information to be displayed:
If I type something like Class.ColumnName it shows in the Intellisense like a summary information.

A: One way is to declare it in a class and use this class (not the edmx), example:
[Column("Name")]
[Required(ErrorMessage = "Name is obligatory")]
[StringLength(30, MinimumLength = 3, ErrorMessage = "Name has to have at least 3 characters")]
public string Name { get; set; }

Then I use a user control to check it on the screen. (I know there are better solutions)

PS: The class is a little complex and with a lot of customization, if someone want it I can post in the future.
But, you can check more about it in these links:
StringLength vs MaxLength attributes ASP.NET MVC3 with EF 4.1 Code First
C# How to use DataAnnotations StringLength and SubString to remove text
StringLengthAttribute Class
and String Canonical Functions

A: Intellisense will show whatever text is in the Documentation -> Summary field of the designer.  That gives you a few options.
1) You can be really OCD, and upon editing your EDMX in the designer you make sure to always fill out this field.
2) You create some script to parse your .edmx (you can edit it just like any XML file), look for a <Property> element which has a MaxLength specified, and add <Documentation> and <Summary> elements inside, simply stating what the max length is.  For example, parse:
<Property Name="USER_NAME" Type="String" MaxLength="50" Unicode="true" FixedLength="false" >

into:
<Property Name="USER_NAME" Type="String" MaxLength="50" Unicode="true" FixedLength="false" >
  <Documentation>
    <Summary>Max length of 50</Summary>
  </Documentation>
</Property>

Then after your edit is complete, all you need to do is rebuild the .Designer.cs/vb by just opening the designer and saving again.
3) Somehow get Visual Studio to know that a class is from an EDMX, then go back to parse the EDMX to get the MaxLength, then update the Intellisense to display accordingly. (I have no idea if this is possible.)


text:
Q: How to make slds box fit for long text value inside lightning layout? I have created lightning layout component and made the lightning layout item size as 5. Inside the layout item I want place some dynamic text value. If the text value is larger it is crossing the box also the layout. How can I fit the text inside the box dynamically based on the length?
My dynamic text testingggggggggggggggggggggggggggggggggggggggggggggggggggggggggggggggggggggggggggggggggggggggggggggggggggggggggggggggggggggggggggggggggggggg
Markup
<lightning:layout multipleRows="true">
    <lightning:layoutItem size="12" mediumDeviceSize="5" class="border">
        <div class="slds-box">
            size=12, mediumDeviceSize=5.slds-size_1-of-2.slds-size_1-of-2.slds-size_1-of-2.slds-size_1-of-2.slds-size_1-of-2.slds-size_1-of-2.slds-size_1-of-2.slds-size_1-of-2.slds-size_1-of-2.slds-size_1-of-2.slds-size_1-of-2
            testingggggggggggggggggggggggggggggggggggggggggggggggggggggggggggggggggggggggggggggggggggggggggggggggggggggggggggggggggggggggggggggggggggggg
        </div>
    </lightning:layoutItem>
    <lightning:layoutItem size="12" mediumDeviceSize="5" class="border">size=12, mediumDeviceSize=5</lightning:layoutItem>
</lightning:layout>

Highlighted in yellow is out of the layout even though i fit the size

A: You just need to play with CSS of div element.
Check following examples:
Word Break
Word Wrap


text:
Q: CPU Frequency Scaling BASH Script I've written a script to run when my PC starts up and it's supposed to overwrite "energy_performance_preference" and "scaling_governor" with ones that have different values.
What's happening is only the first command is being run for some reason. I have a similar script for something else that uses the same process of opening konsole and running multiple commands in succession as root.
Here's my script so far CPU_Boost.
See CPU frequency scaling for more information.

A:
only the first command is being run for some reason

This is because you have the following:
konsole -e sudo cp -f /home/austin/CPU_Boost/energy_performance_preference /sys/devices/system/cpu/cpufreq/policy0/; cp -f /home/austin/CPU_Boost/scaling_governor /sys/devices/system/cpu/cpufreq/policy0/; chown root:root /sys/devices/system/cpu/cpufreq/policy0/energy_performance_preference; chmod 444 /sys/devices/system/cpu/cpufreq/policy0/energy_performance_preference; [...]

Bash will split commands by a semicolon (not newline), so what is being run is more like below (shown with one command per line):
konsole -e sudo cp -f /home/austin/CPU_Boost/energy_performance_preference /sys/devices/system/cpu/cpufreq/policy0/
cp -f /home/austin/CPU_Boost/scaling_governor /sys/devices/system/cpu/cpufreq/policy0/
chown root:root /sys/devices/system/cpu/cpufreq/policy0/energy_performance_preference
chmod 444 /sys/devices/system/cpu/cpufreq/policy0/energy_performance_preference
[...]

You're also lucky that konsole "will catch all following arguments passed to Konsole" [ref] - most commands will not do this, instead taking sudo as the parameter to the -e and trying to handle cp, -f, /home/austin/... as other command line arguments.

cp isn't really appropriate for use with writing to sysfs... even if it works. You would be more likely to have success with redirection, or tee.
For example, if your scaling_governor file contains the text performance, then you could do the following:
echo "performance" | sudo tee /sys/devices/system/cpu/cpufreq/policy0/scaling_governor

Then there would be no need for the subsequent chown or chmod. That's three commands down to one.

You're doing that once for each of policy0, policy1, policy2 and policy3. How about the following:
sudo tee /sys/devices/system/cpu/cpufreq/policy*/scaling_governor <<<"performance"

That's four repetitions down to one call to tee - and it'll even automatically adjust for different systems (my system has 8 policies, not 4).
Repeat that again for energy_performance_preference and the value you'd like to use.

As for getting it to show up in konsole... do you need it to? Can't you just run it as a bash script?
Perhaps if you really want, you could use the following as a command / shortcut to launch the script:
konsole -e "${PATH_TO_SCRIPT}"