text:
Q: How to simulate the RISCV Rocket chip According to the riscv-gcc compiler we are generated the binary file. This binary file data are feeding to rocket chip through this signals.
    io_host_in_valid,    input [15:0] io_host_in_bits
Here io_host_in_bits is 16-bit, so we are driving the 2-times for each instruction data in little-Endian mode.
We are not getting any response from Rocket core (HTIF).
How to simulate the Rocket core and if it is possible to simulate in Xilinx Vivado 2014 as well as debug the design.
Can any one help me about this
Regards,
Santhosh Kumar.

A: For more information on the Rocket Chip infrastructure, I recommend checking out the slides and videos from the first RISC-V Bootcamp.
The Rocket Chip can be simulated/debugged in two different ways: C simulator and Verilog. For information on using these modes, please consult the Rocket Chip README.

A: Yunsup's response on the riscv-hw mailing list:

I would take a look at http://riscv.org/tutorial-hpca2015/riscv-rocket-chip-generator-tutorial-hpca2015.pdf for an overview of interfaces and the FPGA setup.
Here's a link to our test bench we use to test the rocket chip: https://github.com/ucb-bar/rocket-chip/blob/master/vsrc/rocketTestHarness.v.  I would take a look at the htif_tick function, where the implementation can be found here at https://github.com/ucb-bar/rocket-chip/blob/master/csrc/vcs_main.cc, which calls a method on htif_emulator_t (https://github.com/ucb-bar/rocket-chip/blob/master/csrc/htif_emulator.h), which is inherited from htif_pthread_t (https://github.com/riscv/riscv-fesvr/blob/master/fesvr/htif_pthread.cc).  You should also take a look at https://github.com/riscv/riscv-fesvr/blob/master/fesvr/htif.cc.
The host interface (HostIO) doesn't take instructions directly, it's a port for the front-end server (https://github.com/riscv/riscv-fesvr/tree/master/fesvr) to access target memory and the core's control and status registers (CSR).


text:
Q: Connection between LocalServer and Flutter Application I have one question related flutter app development.
The Question is, " Is it possible to implement OAuth2 in flutter without firebase?
Basically I want to link my Android Application with own localserver to authenticate users. Every person first register there application with firebase then move further.
If there is any solution please share with me.

A: You can use oauth2 client package https://pub.dev/packages/oauth2
Github https://github.com/dart-lang/oauth2
Client Credentials Grant code snippet
// This URL is an endpoint that's provided by the authorization server. It's
// usually included in the server's documentation of its OAuth2 API.
final authorizationEndpoint =
    Uri.parse("http://example.com/oauth2/authorization");

// The OAuth2 specification expects a client's identifier and secret
// to be sent when using the client credentials grant.
//
// Because the client credentials grant is not inherently associated with a user,
// it is up to the server in question whether the returned token allows limited
// API access.
//
// Either way, you must provide both a client identifier and a client secret:
final identifier = "my client identifier";
final secret = "my client secret";

// Calling the top-level `clientCredentialsGrant` function will return a
// [Client] instead.
var client = await oauth2.clientCredentialsGrant(
    authorizationEndpoint, identifier, secret);

// With an authenticated client, you can make requests, and the `Bearer` token
// returned by the server during the client credentials grant will be attached
// to any request you make.
var response = await client.read("https://example.com/api/some_resource.json");

// You can save the client's credentials, which consists of an access token, and
// potentially a refresh token and expiry date, to a file. This way, subsequent runs
// do not need to reauthenticate, and you can avoid saving the client identifier and
// secret.
await credentialsFile.writeAsString(client.credentials.toJson());

redpajama_set_name: RedPajamaStackExchange


text:
Q: Swiftui decodable, Printing multiple searches So in Swiftui, I'm trying to output multiple multiple of post.hints. It's a part of a large hierarchy. "results" itself is a list and I'm trying to make result = every single option rather than just one. What's the most efficient way to do that?
URLSession.shared.dataTask(with: url) { (data, _, _) in
        if let posts = try? JSONDecoder().decode(Welcome.self, from: data!) {
            results = [posts.hints[10].food]
            }

A: I didn't realize I could just make a for loop and append each one.
if let posts = try? JSONDecoder().decode(Welcome.self, from: data!) {
//            results = [posts.hints[10].food]
            for i in posts.hints {
                results.append(i.food)
            }
            }


text:
Q: Absolutely continuous measures We have two measures with
$\mu_F(]-\infty,x])=F(x)$
$\mu_G(]-\infty,x])=G(x)$
$G(x)=F(x)^2$
Prove that $\mu_G$ is absolutely continuous with respect to $\mu_F$.

So we have to prove that $\mu_F(A)=0\Rightarrow\mu_G(A)=0$. I was able to prove this when A is an interval. But how can I argue that it is true for A that are not intervals as well?

A: Let $\mu_F(E)=0$. By the Approximation Theorem of Measure Theory (See Theorem D, p. 56 of Measure Theory by Halmos) we can find a finite disjoint union on half-closed intervals, say $H=\bigcup_{k=1}^{n} (a_k,b_k]$ such that $\mu (E\Delta H) <\epsilon$ where $\mu =\mu_F+\mu_G$. Now $$\mu_G(E)$$ $$ \leq \mu_G(H)+\mu_G(E \setminus H)$$ $$ < \sum\limits_{k=1}^{n} (G(b_k)-G(a_k))+\epsilon.$$ But $G(b)-G(a) \leq 2(F(b)-F(a))$ so we get $\mu_G(E) \leq 2\mu_F(H)+\epsilon <\mu_F(E)+2\epsilon=2\epsilon$ Since $\epsilon$ is arbitary we are done.


text:
Q: mail validation suggestions I am using some thing like signup page, after the user finishes his registeration form an email is send to him including a link which when pressed redirect him to page which confirm his registration , so any suggestions how to do that with google app engine (even the concept)

A: *

*create GUID - java.util.UUID.

*put this GUID into database table along with timestamp

*generate the confirmation link with GUID as a parameter and email it to the user

*once link is hit by the user, check that passed GUID exist in DB (and valid, not expired), complete registration and delete GUID record from database


text:
Q: What is the best way to call fragments method from ViewModel in MVVM architecture using live data For eg, As ViewModel should be loosely coupled we cant pass interface reference to ViewModel to get a callback from Viewmodel and call the method implemented in the fragment.
Also please provide an example or reference to call with methods with two or more params using livedata.

A: Make a live data variable in ViewModel and attach an observer in Fragment to that variable and whenever there will be a change in data then the function will be automatically invoked.
For Example:
   viewModel.loading.observe(viewLifecycleOwner, { loading ->
        loading?.let {
          // Here, I'm calling a new function named setLoaderVisibility

            setLoaderVisibility(loader = binding.shimmerProductDetail, binding.containerBody, isLoaderVisible = loading)
        }
    })

Feel free to ask if something is unclear.


text:
Q: Why is my cache raising after each day? I have an android app and its cache is raising from time to time.
I think that the reason for this could be probably that I have an endles running background service which always request my position.
I also have a database which is always open but I don´t think that this could be a problem.
The next thing I was thinking about was this code:
ViewPager.setOffscreenPageLimit(2);


text:
Q: Want to Retain the calling app's url in addressbar after redirecting My project is in Java(Spring/JSF) and from our project we are calling .Net application.When we reached to .Net application, there we do some valid search and after that they just redirect(sendRedirect) the response to my application(Java application).
One more thing we need some parameter from .Net application's response in our application.
My Application Local url:http://localhost:8080/US
DOT NET application url:http://20.12.223.12/excess/
But problem is that when it come back to our application, our application url is changed to
.NET application url "http://20.12.223.12/excess/".We just want to retain our application localhost url(requestUrl).
Is there any way to retain it?
Please give your suggestion!!!
Thanks in advance!!!


text:
Q: How to prevent those PHP variables from being cached on WordPress? I'm using this code in functions.php on WordPress to generate an affiliate link based on the visitor location, It's working perfectly but the problem is that if page caching is turned on (W3 Total Cache), The variables get cached so if someone from the UK was the first one to open the page then the second one from Germany opened the page he will get the same link that the first visitor got.
One more thing please, I'm still very new to PHP and javascript so I would appreciate if the answer was simplified enough
add_action( 'woocommerce_before_add_to_cart_button', 'affiliate_link', 10);

function affiliate_link() {
    $not_avilable_country = '
This product is not avilable in your country yet
';

    // IP Geolocation
    $country_code = $_SERVER ["HTTP_CF_IPCOUNTRY"];
    // Get Custom Fields
    $de_asin = get_post_meta(get_post()->ID, "wccaf_de_asin", true );
    $uk_asin = get_post_meta(get_post()->ID, "wccaf_uk_asin", true );

    //////////////////////////////////////////////

    if ($country_code=="DE" or $country_code=="DE") {
        $amazon_domain = 'https://www.amazon.de';
     // $associate_id = 'bonstato-21';
        $asin = $de_asin;
    }

    else if ($country_code=="GB" && $uk_asin!=="") {
        $amazon_domain = 'https://www.amazon.co.uk';
     // $associate_id = 'bonmedico-21';
        $asin = $uk_asin;
    }

    ///////////////////////////////////////////////

    if( wp_is_mobile() ) {

    // Amazon Link For Mobile
    ?>

    <?php

    } else {

    // Amazon Link For PC
    ?>

    <?php
    }

    ?>

        <button type="button" id="buy_amz_btn" class="buy_amz_btn" onclick="amzGo();"><?php echo $amz_btn_title ?></button>

    <?php
}

A: Not sure if it will work, but you could try to set some initial values for the variables and a timestamp and after to use an if statement to check if current timestamp is greater than initial one and inside the {} to set the variables.


text:
Q: Is there a way to view Assembly File? In Xcode 4 I could see the assembly file by clicking on Product\Generate Output\Assembly File.
But in Xcode 6 and 7 I do not see that option for a Swift file.
Is this feature removed or where do I find it?

A: This only works for pure Swift, but a nice swift assembler is online here: https://swift.godbolt.org. It even color-codes different sections so you can see which lines the assembly comes from.

A: Partial Assembly View
You can profile your application using Instruments (Cmd+I from Xcode) with Time Profiler template. When you find the part that interests you (eg. your critical loop), double click the Symbol Name and in the upper right corner select View Disassembly or Show side-by-side source/disassembly views to see the assembly.
From the gear icon in the same corner, you can Show ISA Reference Guide.

A: Xcode 6 and Xcode 7 (up to the current Xcode 7.3) do not offer the option to view the generated assembly file
for Swift input. (Perhaps that feature will be added in a later
release.)
Currently the only way that I know of is to call the compiler on the command line
with the "-emit-assembly" option, e.g.

xcrun -sdk macosx swiftc -emit-assembly main.swift


text:
Q: Should I create a maintenance plan for my database or use jobs? I tried creating a Maintenance Plan on my SQL Server 2008 database and was impressed by some of the things that are available out of the box.  However, after it was created, it seemed difficult to customize.  This left me wondering if I should have just created SQL jobs with the activities I wanted done.  Are there any benefits to using the maintenance plan over manually creating SQL jobs?

A: I can't think of any benefits, but I am also biased towards using my own jobs for maintenance.
I think that MPs are very good for new or accidental DBAs, as they allow for some maintenance activities to be done (which is better than having none at all). But as most DBAs progress in their experience they tend to start developing their own custom scripts instead.
HTH

A: I don't think the maintenance plans are hard to change.. There's just a simple designer for all action items.
But I'm also more in favor of SQL Jobs then maintenance plans. Actually I'm using plans only on servers I don't really touch and just want to use a wizard to do simple tasks (backups, validation, cleaning of old files). On all other servers I prefer jobs.
I think I'm using the plans only for the cleaning of old files. Don't remember anything else, the SQL Agent jobs are just too customizable to be ignored :-).

A: If you are looking at alternatives to using Maintenance Plans or are looking for  something that is easy to customize, you should really look into the Ola Hallengren maintenance solution.
https://ola.hallengren.com/


text:
Q: Newline characters not recognized in XML attribute value? Java, DOM, JTextArea I have an XML file, which I extract the Material.comment attribute from and populate a JTextArea with. (example XML below)
Problem is that it displays the text in one line, ignoring newlines.
This is strange because in all of my text editors, and XML viewers, it shows the comment attribute value having multiple lines.
Even stranger, is that when I analyze the string char by char (in java) it shows the end of each line to be only 2 space chars, no newline (ascii value 32).
How could notepad, notepad++, internet explorer, altova XML spy, etc. all interpret these invisible newlines? Is it possible java is ignoring characters? Perhaps it is a problem with java DOM parser?
<material
    version="1.4" units="kg"
    comment="12AUG2012 -- An Extended Summary plot was added which includes the Monitor value.  J. Doe
15AUG2012 -- - Added  summary plot definition as requested.  J. Doe
27JAN2013 -- Fixed spacing issues between title and headings   J. Doe
03MAR2013 -- Added longName property to material file.  Updated summary plot legends with new heading convention, i.e. Mean Area and Area of Concern.  J. Doe

A: There is nothing wrong with Java DOM parser, it is the intended way to process white space characters inside attributes.
Quoting W3C Recommendation for XML 1.0

Before the value of an attribute is passed to the application or
  checked for validity, the XML processor must normalize the attribute
  value by applying the algorithm below, or by using some other method
  such that the value passed to the application is the same as that
  produced by the algorithm.

The algorithm is described in the previous link, but basically it converts all "white space" characters into spaces, so is normal to lost new line characters after parsing the xml.
The reason Notepad++ and others show the new line, is because they are not parsing the xml but showing directly the string, which has not been processed and mantains the original new line characters.


text:
Q: Is there an English (British or American) expression or idiom that refers to a recluse finally socializing In Icelandic, there is an expression "að viðra sig", using the analogy of clothes that smell of closet and the act of taking them outside to get some of that old smell out of them, that is used to describe a recluse who finally spends some time with other people.
While I don´t expect the same analogy to be used in English, is there any other idiom/expression that refers in any way to the same act/effort?
Updated
I was not as clear as I could be with the original question... The act I am trying to pinpoint is a one-off effort to socialize, rather than a permanent change from recluse to non-recluse. Using the Icelandic expression as an example, it would be used by a parent about having forced a kid who is a World of Warldcraft addict to participate in a family dinner. Again, I am not looking for an exact corresponding expression, but hoping to get as close as possible.
Note
In the comments to this question, a few expressions were mentioned but it was pointed out that they are not intended for people:
"De-mothball" - used for military equipment
"given an airing" - used for papers and ideas that are brought back into discussion after neglect
While difficult to use for my purposes, they might be useful in a different situation as long as you take into account the weirdness of referring to people in this way... so i thought I'd mention them here. Thanks to mplungjan and 'Colin Fine'

A: I'm a fan of "emerged from his/her cave." It seems to fit the concept described in the updated version of your question, of someone who is making a rare foray into society, rather than entering society on a permanent and ongoing basis.

A: EDIT: Changing my original answer in view of the OP's updated and revised question.
He's emerging from his den/shell/cave/burrow
Seem to be the most appropriate, I asked a few native speakers and nearly all came up with "emerging from his + (noun)" as first suggested by user867.
Google Ngram seems to suggest that emerging from his den is the least commonly used expression, but if you click on the actual results you'll find that the "emerging from his den" is commonly used for bears and people, whereas emerging from his shell can also refer to tortoises, turtles and snails, so depending on the person's physical traits you could opt for either.

A: There's a few actually.
The simplest one would be a person "opening up", which goes equally for any individual trying to become more sociable. You would say "that person has really opened up!" But mind that it can also mean opening up to new ideas, rather than being exclusively social.
Another good one is "coming out", which is usually paired with "coming out of his/her shell" or "coming out if his/her cocoon".  But be careful with this, because it can also mean "coming out" as a homosexual (usually paired with "Coming out of the closet").  If you pair it with the shell/cocoon metaphor though, it should be clear what you are trying to say.
To clarify, these are more permanent concepts.  You may be looking for a more temporary or one-off event than I have described here.

A: There is a word for it too - reclaim
reclaim v.3 To save (a person) from an undesirable state, course of action, etc.; (also) to bring back or restore (a person) to a better or more acceptable way of life or condition. OED has many example sentences:

A young man, who was reclaimed from a very dissolute course of life.
Here is Calvin, reclaimed—from substance abuse, from financial uncertainty—so strong now.

The Pink Floyd song comes to mind coming back to life. The closest English parallel to your phrase is breath of fresh air. Although this is not what you are looking for, a closely related phrase breathe new life into might be relevant.

A: "Let your hair down" captures the spirit of your request.
From wisegeek: The phrase "let your hair down" is an idiom that means to relax or let go of inhibitions. Most language experts agree that the idiom is from the time period when it was only proper for women to wear their hair pinned up on the head in public. They were only allowed to let their hair down to hang naturally when alone, either when bathing or at bedtime. Letting one's hair down, at that time, was reserved for moments when relaxing and behaving less properly were acceptable.
Most of the time, the idiom is not intended to mean "relaxing" as in calming, soothing, or otherwise stress-relieving situations such as quietly sitting to read a book or getting a massage. Instead, it more accurately refers to relaxing social rules and letting go of inhibitions that would normally hold a person's behavior in check. For example, it would be a correct use of the idiom to say that, halfway through a party, you let your hair down and danced for a few songs, when you had been previously too embarrassed to try.

A: If one were of a poetic bent, it might be described as "emerging from the chrysalis", depending upon the precise context.

A: I feel comfortable saying, "popped [or poked] his head up",
although I can't find much evidence for its widespread usage.
This can refer to a ground-dwelling animal
(e.g., a gopher, groundhog, or mole) sticking its head out of its hole
(i.e., tunnel system).
It can also refer to a person with her head "buried"
or "down" in some reading material (or an electronic device) lifting her head to interact with the environment (including other people).  I also found "put/stick your head above the parapet"
on The Free Dictionary,
but (1) I don't consider that common usage, and (2) it's not the same thing; it's more like "sticking one's neck out".
Wiktionary claims that
"prairie dog" can be used as a verb
with this meaning, but I've never heard that, either.
This is not to be confused with
"holding one's head up",
"raise/rear its (ugly) head",
or "poke my head in".

A: Consider "tear loose" and "break away," used figuratively, as in:

I see you finally got to tear loose/break away from your room (World of Warcraft, etc.). Welcome back to society/Planet Earth!


text:
Q: Avoid involuntary data pushing to iCloud during updates I run iCloud on iOS/macOS with only "Contacts" (and iMessage) enabled, because I don't want other data copied out of my device.
However, it seems that every time I upgrade iOS/macOS (and possibly when logging out/in of iCloud), that all other iCloud settings are forcibly enabled without my consent.
And you don't notice this until the device is up and running again, and then probably a lot of data has already been copied to iCloud before you manage to turn it off.
How can I make sure no data is copied to iCloud except what I have expressly chosen myself? Will it suffice to disable Wi-Fi before updates, since (I think) iCloud doesn't sync over Cellular Data.
Please provide step-by-step instructions for both iOS and macOS that are watertight.

A: This is a bug that affected the update to iOS 10.3. Apple has resolved this issue with iOS 10.3.1.
See also Apple Warns iCloud Users Some Disabled Services Were Accidentally Re-enabled in iOS 10.3
iCloud sync settings are not supposed to change after an iOS update. In the case of iOS 10.3 this was due to a bug.
To answer your question: You don't need to change any settings to prevent iOS to enable any iCloud sync settings with 10.3.1 and higher. Older iOS releases (10.2.1 and 10.3) can not be updated to any more.


text:
Q: Stop iwctl from automatically connecting to network I have recently installed arch linux along with gnome DE. During installation I used iwctl command to connect to wifi. But after installing the DE, I no longer need it.
But on every boot, it automatically connects to wifi network, and hence I am not able to use the gnome settings to connect to wifi. I have to open terminal and open iwctl and then use the disconnect command station wlan0 disconnect. After this only I am able to switch networks from the gnome settings.
How do I stop iwctl from connecting to the network everytime on a boot? Should I disable iwd service, since iwctl comes under that? Or would that cause more trouble.
Link to iwd page on archwiki.

A: I was able to forget the network from iwctl.
Just run run iwctl
and then run known-networks list, to list the known networks to iwctl. And then use known-networks SSID forget where SSID is the SSID is the SSID of a network you are trying to forget

A: You might want to use the command known-networks <Network-Name> set-property AutoConnect no from within iwctl.


text:
Q: What's the best way to count results in GQL? I figure one way to do a count is like this:
foo = db.GqlQuery("SELECT * FROM bar WHERE baz = 'baz')
my_count = foo.count()

What I don't like is my count will be limited to 1000 max and my query will probably be slow.  Anyone out there with a workaround?  I have one in mind, but it doesn't feel clean.  If only GQL had a real COUNT Function...

A: Count functions in all databases are slow (eg, O(n)) - the GAE datastore just makes that more obvious. As Jehiah suggests, you need to store the computed count in an entity and refer to that if you want scalability.
This isn't unique to App Engine - other databases just hide it better, up until the point where you're trying to count tens of thousands of records with each request, and your page render time starts to increase exponentially...

A: You have to flip your thinking when working with a scalable datastore like GAE to do your calculations up front. In this case that means you need to keep counters for each baz and increment them whenever you add a new bar, instead of counting at the time of display.
class CategoryCounter(db.Model):
    category = db.StringProperty()
    count = db.IntegerProperty(default=0)

then when creating a Bar object, increment the counter
def createNewBar(category_name):
  bar = Bar(...,baz=category_name)

  counter = CategoryCounter.filter('category =',category_name).get()
  if not counter:
    counter = CategoryCounter(category=category_name)
  else:
    counter.count += 1
  bar.put()
  counter.put()

db.run_in_transaction(createNewBar,'asdf')

now you have an easy way to get the count for any specific category
CategoryCounter.filter('category =',category_name).get().count

A: According to the GqlQuery.count() documentation, you can set the limit to be some number greater than 1000:
from models import Troll
troll_count = Troll.all(keys_only=True).count(limit=31337)

Sharded counters are the right way to keep track of numbers like this, as folks have said, but if you figure this out late in the game (like me) then you'll need to initialize the counters from an actual count of objects.  But this is a great way to burn through your free quota of Datastore Small Operations (50,000 I think).  Every time you run the code, it will use up as many ops as there are model objects.

A: +1 to Jehiah's response.
Official and blessed method on getting object counters on GAE is to build sharded counter. Despite heavily sounding name, this is pretty straightforward.

A: I haven't tried it, and this is an utter resource hog, but perhaps iterating with .fetch() and specifying the offset would work?
LIMIT=1000
def count(query):
   result = offset = 0
   gql_query = db.GqlQuery(query)
   while True:
     count = gql_query.fetch(LIMIT, offset)
     if count < LIMIT:
       return result
     result += count
     offset += LIMIT

A: orip's solution works with a little tweaking:
LIMIT=1000
def count(query):
    result = offset = 0
    gql_query = db.GqlQuery(query)
    while True:
        count = len(gql_query.fetch(LIMIT, offset))
        result += count
        offset += LIMIT
        if count < LIMIT:
            return result

A: We now have Datastore Statistics that can be used to query entity counts and other data. These values do not always reflect the most recent changes as they are updated once every 24-48 hours. Check out the documentation (see link below) for more details:
Datastore Statistics

A: As pointed out by @Dimu, the stats computed by Google on a periodic basis are a decent go-to resource when precise counts are not needed and the % of records are NOT changing drastically during any given day.
To query the statistics for a given Kind, you can use the following GQL structure:
select * from __Stat_Kind__ where kind_name = 'Person'

There are a number of properties returned by this which are helpful:

*

*count -- the number of Entities of this Kind

*bytes -- total size of all Entities stored of this Kind

*timestamp -- an as of date/time for when the stats were last computed

Example Code
To answer a follow-up question posted as a comment to my answer, I am now providing some sample C# code that I am using, which admittedly may not be as robust as it should be, but seems to work OK for me:
/// <summary>Returns an *estimated* number of entities of a given kind</summary>
public static long GetEstimatedEntityCount(this DatastoreDb database, string kind)
{
    var query = new GqlQuery
    {
        QueryString = $"select * from __Stat_Kind__ where kind_name = '{kind}'",
        AllowLiterals = true
    };
    var result = database.RunQuery(query);
    return (long) (result?.Entities?[0]?["count"] ?? 0L);
}

A: The best workaround might seem a little counter-intuitive, but it works great in all my appengine apps.  Rather than relying on the integer KEY and count() methods, you add an integer field of your own to the datatype.  It might seem wasteful until you actually have more than 1000 records, and you suddenly discover that fetch() and limit() DO NOT WORK PAST THE 1000 RECORD BOUNDARY.
def MyObj(db.Model):
  num = db.IntegerProperty()

When you create a new object, you must manually retrieve the highest key:
max = MyObj.all().order('-num').get()
if max : max = max.num+1
else : max = 0
newObj = MyObj(num = max)
newObj.put()

This may seem like a waste of a query, but get() returns a single record off the top of the index.  It is very fast.
Then, when you want to fetch past the 1000th object limit, you simply do:
MyObj.all().filter('num > ' , 2345).fetch(67)

I had already done this when I read Aral Balkan's scathing review: http://aralbalkan.com/1504 .  It's frustrating, but when you get used to it and you realize how much faster this is than count() on a relational db, you won't mind...


text:
Q: How to get average of specific teams and exclude negatives? I am given a text file and have to print out the average of the rows, the columns, and specific teams in the columns. I also have to exclude any negative values from the average.
Here is the text file
Tom, Red, 5, 17,22
Joe , Green , 3 , 14 ,22
Maria, Blue , 6 , 18 , 21
Fred , Blue , 2 ,15 ,23
Carlos , Red , -1 , 15, 24

Here is my row column average program
{s=$3+$4+$5; print $1 "\t" s/3} #Use awk program teamlist | sort -r -n to get the row average

Here is my column average program
{t+=$3}
{u+=$4}
{v+=$5}
 {print "Average for test 1: " t/NR}
 {print "Average for test 2: " u/NR}
 {print "Average for test 3: " v/NR} #Use awk column teamlist | tail -3 to the column average

Here are the results
Average for test 1: 4
Average for test 2: 13
Average for test 3: 20

Tom, 14.6668
Joe, 13
Maria, 15

I am not sure however how to modify the program to have awk only get the team colors and to skip the negative score.


text:
Q: Do USB Composite devices show up as one, or multiple devices I'm working on a Composite USB device with HID + CDC device classes in one device. Things are not working 100% as yet, but irrespective op the details of my project, I just have a simple question.
Does a Composite USB devices show up as a single device os as multiple devices when plugged into a PC?
In other words, how many devices should my CDC + HID device show up as, in for example the Windows Device Manager, or my Mac's System Information?

A: Here's what my device manager looks like when set to "View -> Devices by connection":

As you can see, the generic "USB Composite Device" and "Sierra Wireless HSPA Device" each get broken down into distinct endpoints. The Sierra Wireless device has multiple CDC endpoints and a network adapter.
In the normal view of device manager, it just shows the endpoints and not the intermediate composite devices or hubs.
However, if you have a composite device but have not installed its driver, it shows as one device of type "unknown".


text:
Q: How to install Docker compose in Azure pipelines? I would like to use Docker Compose task in Azure pipelines, but I am getting following error:
##[error]Unhandled: Docker Compose was not found. You can provide the path to docker-compose via 'dockerComposePath'
How should I install docker compose? Is there a "nice way", something like Docker Installer task?

A: Unfortunately, there does not seem to be a "clean" step like Docker Installer task for Azure pipelines to install Docker Compose.
However, I have been able to get Docker Compose installed via shell script task which utilizes the local package manager to get/install Docker Compose (e.g. sudo apt-get install -y docker-compose)
- task: ShellScript@2
  displayName: Install Docker-Compose
  inputs:
    scriptPath: 'docker-compose-install.sh'


text:
Q: Stripping down SVG Code I have created SVG code from coreldraw and want to place it inline in my HTML5 document and have a couple of queries.

*

*How universal is SVG now-a-days?  Any suggestions on backwards compatibility?

*I have taken out the style data from the svg and put that into my css, I guess that's not a problem - or is it?  I also added a hover rule...

    .Borderline {stroke:#0099FF;stroke-width:7.45541;stroke-linejoin:round}
    .BorderFill1 {fill:#71C6FF}
    .BorderFill2 {fill:#CBEAFF}
    .BorderFill1:hover {fill: green; }

*

*Can I remove any of the following data that is not needed. (but I want it to work and look the same)

    <svg xmlns="http://www.w3.org/2000/svg" class="myimgleft" xml:space="preserve" width="100px" height="105px" version="1.1" style="shape-rendering:geometricPrecision; text-rendering:geometricPrecision; image-rendering:optimizeQuality; fill-rule:evenodd; clip-rule:evenodd" viewBox="0 0 92 97" xmlns:xlink="http://www.w3.org/1999/xlink">
    <g id="Layer_x0020_1">
    <metadata id="CorelCorpID_0Corel-Layer"/>
    <path class="BorderFill1 Borderline" d="M55 51c10,0 18,0 24,0 4,-5 9,-10 9,-15 0,-6 0,-22 0,-32l-16 14c-5,-4 -8,-6 -17,-14l0 47z"/>
    <path class="BorderFill2 Borderline" d="M79 51c-5,-1 -41,0 -47,0l0 -14c-8,8 -25,25 -28,28l28 28 0 -13c7,0 11,1 17,-2 6,-2 23,-21 30,-27z"/>
    </g>
    </svg>

*

*Any other hints / tips that might be useful are very welcome.

A: 1 MDN keeps an accurate list of compatibility per-element. Here's the list for SVG: https://developer.mozilla.org/en-US/docs/Web/SVG/Element/svg
Feature    Chrome  Firefox (Gecko)     IE  Opera   Safari
Basic support   1.0     1.5 (1.8)      9.0  8.0     3.0.4
2 Keep the style in your SVG - it'll make it easier to swap out for other SVG images later. You want to be able to quickly update your svg. This one is more a matter of preference.
3 I wouldn't get in the habit of tweaking vector-art exported from CorelDraw by hand. You may think to run it through a minifier, but hand-tuning is almost certainly more work than it's worth.
Here's the first minifier Google gives me:
http://petercollingridge.appspot.com/svg-optimiser
For cases where you're not inlining, you can give .svgz (compressed svg) a shot, which will make it significantly smaller: https://graphicdesign.stackexchange.com/questions/24797/when-should-i-use-svg-or-svgz-for-my-web-graphics
4 Hmm, other tips - well good on you for using vector art on your site. Too many web devs/designers take the shortcut of doing everything in raster. While that gets you a nice looking image for a demo, in the long run it's really hurting your site. With ubiquitous tablets + phones, pinch + zoom is everywhere and your images need to scale nicely.
Personally, I've never loved the idea of inlining svg - I've always preferred saving as .svg and src-ing it like an image. I see why you are inlining it, though, as you're using some hovers.


text:
Q: Is there any way to shift stories part above, I don't know what's wrong going on with CSS I'm not able to shift story part above, there's something wrong with CSS
I want to shift story part above just below Instagram header


text:
Q: Dropdown menu with XML data source gives web part error I am using SharePoint designer to build a page with a data view web part that displays the contents of a 6,000 record XML file that is structured like the example below with each "Details" element being a record.
<?xml version="1.0" encoding="UTF-8"?>
<Details_Collection>
   <Details>
      <Display_Name>Weather, Wendy</Display_Name>
      <Age>27</Age>
      <Gender>Female</Gender>
      <Marital_Status>Married</Marital_Status>
      <Email>person@test.edu</Email>
      <Site_Location>Denver, CO</Site_Location>
   </Details>
   <Details>
       ...
   </Details>
</Details_Collection>

I want to filter that DVWP by the Site_Location element using an ASP dropdown control. Rather than have to maintain a list of about a hundred Site Locations as choices in the dropdown control's code, I want to simply use that XML file as the data source for my dropdown's choices.
I can insert the XML data source onto the page just fine. But, when I select it as the data source for my dropdown and then preview the page, it gives me a web part error and the page won't load.
I assume that what I am doing is possible. Is it not working because my XML file doesn't have any schema information? It seems to be well-formed enough to load in the DVWP. After-all, the entire page works great UNTIL I associate the ASP dropdown with the data source. That's when it breaks.

A: I think you need sth. like this in your code:
...
<asp:DropDownList runat="server" id="siteLocationList{$Pos}" OnSelectedIndexChanged="javascript:openViewForSite();">
    <xsl:variable name="siteLocation" select="@answer"/>
    <xsl:for-each select="/Details_Collection/Details">
        <xsl:sort select="Site_Location"/>
        <asp:ListItem>
            <xsl:value-of select="Site_Location"/>
        </asp:ListItem>
    </xsl:for-each>
</asp:DropDownList>
...


text:
Q: Explain the usage of CloudBlob.BeginStartCopy With the new asynchronous programming models that are being accepted into most C# libraries, I am starting to see many uses of the words Begin and Start, but these new wordings confuse me.
Take for example the method CloudBlob.BeginStartCopy
The docs say that it Begins an asynchronous operation to start a blob copy. Okay, so that makes sense in English, but I don't see where there are callbacks or something similar for when these operations End or Stop respectively...
Can someone send light on the meanings of these methods and how I monitor them for completion?


text:
Q: Prove that $4^{(p-1)/2}\equiv 1\pmod p$ If $p$ is a prime of the form $4k+3$, prove that $4^{\frac{p-1}{2}}\equiv 1\pmod p$.
I was solving a problem and it came down to this. I have no idea how to prove it, I have tried. Any help would be appreciated.
Thanks

A: Hint: $4^{\frac{p-1}2}=(2^{2})^{\frac{p-1}2}=2^{p-1}$

A: There surely is another way to prove it, and they might be getting at quadratic reciprocity here, but Fermat's little theorem provides the simplest way to prove this particular question. If $p$ is a prime number, of whatever form, and $a$ is a number coprime to $p$, then $a^{p - 1} \equiv 1 \pmod p$. (I won't give a proof of Fermat's little theorem here, but it's easy enough to find from multiple sources).
All that we need to do now is rewrite $4^{\frac{p - 1}{2}}$ in such a way that allows us to apply Fermat's little theorem. Note that $4^x = 2^{2x}$. And voila! $4^{\frac{p - 1}{2}} = 2^{p - 1}$, and since 2 is clearly coprime to $p = 4k + 3$, it follows that $2^{p - 1} \equiv 1 \pmod p$ as asserted.


text:
Q: Lambda capturing - what is the difference between & and this? Could you please tell me the difference between capturing of [this] and [&]? (In case of a lambda is defined inside a member function of the class)
As I understood, there is no difference between both of them.

*

*[this] - [this] means capturing all the member data of the class. Capturing [this] means capturing the address of the object.
#include <iostream>
class Foo {
    int x;
public:
    Foo() : x(10) {}

    void bar() {
        // Increment x every time we are called
        auto lam = [this](){ return ++x; };
        std::cout << lam() << std::endl;
    }
};

int main() {
    Foo foo;
    foo.bar(); // Outputs 11
    foo.bar(); // Outputs 12
}

*[&] - [&] means capture all variables by reference all variables mean local variable, global variable and member data of the class.
class Foo {
    int x;
public:
    Foo() : x(10) {}

    void bar() {
        // Increment x every time we are called
        auto lam = [&](){ return ++x; };
        std::cout << lam() << std::endl;
    }
};

int main() {
    Foo foo;
    foo.bar(); // Outputs 11
    foo.bar(); // Outputs 12
}

I believe that there is no difference between [this] and [&]. Because by both capturing data is captured by reference. so the data can be changed.

*

*[this] captures address of the data (reference value)

*[&] captures all data by reference

Is my understanding is wrong? Please give me some advice.


text:
Q: Display Mat-Table without duplicate values There are three columns in my mat-table such as part, type and name.
I am getting same data from service for all these columns when I bind them it is showing duplicate data in multiple rows. Now I want to club them all and want to show only one row in table.

  loadPartsUsageData(reqObj) {
this.partUsageService.getdata(reqObj)
  .subscribe(
    success => {
      this.loaddataSource(success);
      this.updata = success;
      console.log('data', this.updata);
    },
    error => {
      this.updata = {};
      this.partusageDataSource = [];
      this.totalRecords = 0;
    },
    () => {
    }
  );

}
  loaddataSource(response: any) {
const dataWithIndex: any[] = [];
for (let i = 0; i < Object.keys(response.partDetails).length; i++) {
  dataWithIndex.push({
    // id: i,
    partType: response.partDetails[i].partType === null ? '' : response.partDetails[i].partType,
    basepartNumber: response.partDetails[i].basepartNumber === null ? '' : response.partDetails[i].basepartNumber,
    partD1d: response.partDetails[i].partD1d === null ? '' : response.partDetails[i].partD1d,
    partDescription: response.partDetails[i].partDescription === null ? '' : response.partDetails[i].partDescription,
    partNumber: response.partDetails[i].partNumber === null ? '' : response.partDetails[i].partNumber
  });
}
console.log('Valid data......', response, response.partDetails);
this.partusageDataSource = new MatTableDataSource(dataWithIndex);
this.totalRecords = Object.keys(response.partDetails).length;
console.log('Total records', this.totalRecords);
console.log('partdetails List Details', response.partDetails);
this.partusageDataSource.filterPredicate = this.customECUTableFilterPredicate();

}
response from service
enter image description here
enter image description here

A: In your component, you can create a new array and add any items from the array you are currently using to this if they aren't already added (based on matching properties ) E.g, if current array is called items:
this.items.forEach(i =>
 {
!this.itemsGroup.some(ig =>
ig.name == i.name &&
ig.part == i.part &&
ig.type == i.type) ?
this.itemsGroup.push(i) : null;
 });

Then use the itemsGrouped array to populate your table.
Alternatively, 'for' loop is generally reported as being faster so could use it instead and move the comparison logic into a function, e.g. group(item: Item):
for (var i = 0, len = this.items.length; i < len; i++) {
this.group(this.items[i]);
}

Amended your code sample to show how it could work:
loaddataSource(response: any) {
const dataWithIndex: any[] = [];
const groupedData: any[] = [];

for (let i = 0; i < Object.keys(response.partDetails).length; i++) {
  dataWithIndex.push({
    // id: i,
    partType: response.partDetails[i].partType === null ? '' : response.partDetails[i].partType,
    basepartNumber: response.partDetails[i].basepartNumber === null ? '' : response.partDetails[i].basepartNumber,
    partD1d: response.partDetails[i].partD1d === null ? '' : response.partDetails[i].partD1d,
    partDescription: response.partDetails[i].partDescription === null ? '' : response.partDetails[i].partDescription,
    partNumber: response.partDetails[i].partNumber === null ? '' : response.partDetails[i].partNumber
  });
}

dataWithIndex.forEach(i =>
 {
!groupedData.some(ig =>
ig.basepartNumber== i.basepartNumber &&
ig.partD1d== i.partD1d &&
ig.partNumber == i.partNumber) ?
groupedData.push(i) : null;
 });

console.log('Valid data......', response, response.partDetails);
this.partusageDataSource = new MatTableDataSource(groupedData);
//etc


text:
Q: Error when trying to render component in react-testing-library - got an object I'm trying to setup some integration tests of some react components that are connected to our redux store.
Our general pattern is a const (instead of a component) which is "connect"ed with redux to the store (I think this is just background to the issue, as I have the same problem with a normal component).
I am following https://testing-library.com/docs/example-react-redux
I get this error
   console.error node_modules/react/cjs/react.development.js:172
      Warning: React.createElement: type is invalid -- expected a string (for built-in components) or a class/function (for composite components) but got: object.

  Check your code at feedback.test.js:32.
console.error node_modules/react-dom/cjs/react-dom.development.js:19814
  The above error occurred in the <Provider> component:
      in Provider (at feedback.test.js:26)

This is my test
import React from 'react';
import {createStore} from 'redux'
import {Provider} from 'react-redux'
import {render, getByTitle, fireEvent} from '@testing-library/react'
//import '@testing-library/cleanup-after-each'
import '@testing-library/jest-dom/extend-expect'

import {FeedbackContainer} from '../feedbackContainer'
import {defaultState, reducer} from '../../../../redux/modules/feedback'

function renderWithRedux(
  component,
  {
    initalState, store = createStore(reducer, defaultState)
  } = {}
) {
  return {
    ...render(<Provider store={store}>{component}</Provider>)
  }
}

it('increments the counter', () => {
  console.log(<FeedbackContainer/>)
  const {container} = renderWithRedux(<FeedbackContainer />) <-- line 32
})

My container component looks like this:
import { connect } from 'react-redux';
import { Feedback } from './feedback';
import { compose, lifecycle, withHandlers } from 'recompose';
import { actions } from '../../../redux/modules/feedback';

export const mapStateToProps = (state, ownProps) => ({
// snipped state maps
});

export const mapDispatchToProps = {
// snipped functions
};

const enhance = compose(
  connect(mapStateToProps, mapDispatchToProps),
  withHandlers({
    sendFeedbackHandler: props => () => props.sendFeedback(props),
    handleResize: props => () => props.setWindowSize(),
  }),
  lifecycle({
    componentDidMount() {
      const {handleResize} = this.props
      window.addEventListener('resize',handleResize);
    },
    componentWillUnmount() {
      this.props.clearFeedback();
      const {handleResize} = this.props
      window.removeEventListener('resize', handleResize);
    },
  }),
);

export const FeedbackContainer = enhance(Feedback);

The feedback.js looks like this:
import React from 'react';
import ReactStars from 'react-stars';

export const Feedback = (props) => {

    const ratingChanged = (rating) => {
      props.setRating(rating);
    }

    const {sendFeedbackHandler} = props

    var title = null;
    switch (props.type) {
      case "REF":
        title = "Rate this FAQ"
        break;
      default:
        title = "Rate my experience"
        break
    }

    var feebackLayout;
    var buttonClassNames = "btn btn-success btn-cons pull-right";
    if (props.apertureWidth > 768) {
      buttonClassNames += " margin-right-0px ";
      feebackLayout = (

            {title}

              <ReactStars
                value={props.rating}
                count={5}
                onChange={ratingChanged}
                size={24}
                color2={'#ffd700'}
                half={false}
              />

      )
    } else {
      buttonClassNames += " margin-right-14px ";
      title = "Rate this:"
      feebackLayout = (

            {title}

            <ReactStars
              value={props.rating}
              count={5}
              onChange={ratingChanged}
              size={24}
              color2={'#ffd700'}
              half={false}
            />

      )
    }

    return (

            {feebackLayout}

 768 ? "0px" : "10px"}}>

                <textarea
                  data-test-id='feedback-text'
                  className="form-control"
                  style={{"height":"unset"}}
                  placeholder="Add any comments"
                  rows={2}
                  onChange={event => props.setFeedback(event.target.value)}
                />

                <button
                  data-test-id='feedback-submit'
                  className={buttonClassNames}
                  onClick={sendFeedbackHandler}
                >
                  {props.buttonText}
                </button>

              {props.feedbackSubmittedMessage}

    )
};

If I change my test to use the underlying Feedback component rather than the container it doesn't crash (but then I don't think the store will be correctly connected as mapstatetoprops isn't going to be called.
If I console.log the components in my test they both return objects from what I can see so I don't quite understand the error.
FeedbackContainer:
{ '$$typeof': Symbol(react.element),
        type:
         { mapStateToProps: [Function],
           mapDispatchToProps: [Function: mapDispatchToProps],
           reactComponent: { [Function: WithHandlers] displayName: 'withHandlers(lifecycle(Component))' },
           mockDispatch:
            { [Function: mockConstructor]
              _isMockFunction: true,
              getMockImplementation: [Function],
              mock: [Getter/Setter],
              mockClear: [Function],
              mockReset: [Function],
              mockReturnValueOnce: [Function],
              mockReturnValue: [Function],
              mockImplementationOnce: [Function],
              mockImplementation: [Function],
              mockReturnThis: [Function],
              mockRestore: [Function] } },
        key: null,
        ref: null,
        props: {},
        _owner: null,
        _store: {} }

Feedback:
{ '$$typeof': Symbol(react.element),
        type: [Function],
        key: null,
        ref: null,
        props: {},
        _owner: null,
        _store: {} }

From some reading I think this could be down to some version compatabilites, this is what I have in my package.json:
"jest": "^21.2.1",
"@testing-library/jest-dom": "^4.1.0",
"@testing-library/react": "^9.1.4",
"react": "^16.8.6",
"react-dom": "^16.0.0",
"react-redux": "^5.0.5",
"redux": "^3.7.2",
"redux-saga": "^0.15.6",

Where am I going wrong?!

A: Please see my answer here: What is wrong with react-testing-library render function? It returns an error on certain objects
expect(() =>
        render(
            <AddAssessmentFormModal
                recordDetailView={<RaDeathDecisionEditView />}
                addRecord={(record: any) => addAssessment(record)}
            />,
            {
                wrapper: () => <AppWrapper store={store} />,
            }
        )
    ).not.toThrow();


text:
Q: N3 notation to RDF/XML I have to sample N3 and I need to convert it to the corresponds RDF/XML format please , any help ?
 crop:AttributeValue a rdfs:Class .
 crop:SomeValue a rdfs:Class; rdfs:subClassOf crops:AttributeValue .

 crop:SomeValue/7 a crops:SomeValue .

 crop:SomeValue a rdf:Property ; rdfs:range crops:SomeValue .

A: You need to specifiy a bit more info, e.g. like this
@prefix crop: <http://example.org/foo#> .
@prefix crops: <http://example.org/foo#> .
@prefix rdf: <http://www.w3.org/1999/02/22-rdf-syntax-ns#> .
@prefix rdfs: <http://www.w3.org/TR/rdf-schema/> .

crop:AttributeValue a rdfs:Class . crop:SomeValue a rdfs:Class; rdfs:subClassOf crops:AttributeValue .

<http://example.org/foo#SomeValue/7> a crops:SomeValue .

crop:SomeValue a rdf:Property ; rdfs:range crops:SomeValue .

Replace the namespaces for crop and crops with the correct ones.
This would be the following in RDF/XML
<?xml version="1.0"?>
<rdf:RDF xmlns:rdfs="http://www.w3.org/TR/rdf-schema/" xmlns:rdf="http://www.w3.org/1999/02/22-rdf-syntax-ns#" xmlns:crops="http://example.org/foo#">
    <rdfs:Class rdf:about="http://example.org/foo#SomeValue">
        <rdfs:subClassOf>
            <rdfs:Class rdf:about="http://example.org/foo#AttributeValue" />
        </rdfs:subClassOf>
        <rdf:type rdf:resource="http://www.w3.org/1999/02/22-rdf-syntax-ns#Property" />
        <rdfs:range rdf:resource="http://example.org/foo#SomeValue" />
    </rdfs:Class>
    <crops:SomeValue rdf:about="http://example.org/foo#SomeValue/7" />
</rdf:RDF>

Here is an online tool for the conversion : http://www.rdfabout.com/demo/validator/

A: You should check first if you have a valid n3 representation of your data. For example you use a prefix named crop and a prefix named crops. Assuming that these are correct, you also need to define your prefixes (crop, crops, rdf, rdfs). A valid example would be:
@prefix crop: <http://crop.org> .
@prefix crops: <http://crops.org> .
@prefix rdfs: <http://www.w3.org/2000/01/rdf-schema#> .
@prefix rdf: <http://www.w3.org/1999/02/22-rdf-syntax-ns#> .

crop:AttributeValue a rdfs:Class . crop:SomeValue a rdfs:Class; rdfs:subClassOf crops:AttributeValue .
crop:SomeValue a crops:SomeValue .
crop:SomeValue a rdf:Property ; rdfs:range crops:SomeValue .

For a validation and conversion you might than check out RDF About Validator. Alternatively you can use this tool as well.

A: If you're using Jena, there is a command-line tool rdfcat which can convert files between RDF/XML, N-triples and Turtle formats.


text:
Q: SQL Linestring with multiple coordinates - can I use each location for distance calculations? I am trying to figure out if I can use a LineString with multiple coordinates, and calculate distances between each of the items in linestring, and another table with coordinates:
I have a few locations that I need to visit for e.g.
   A1 40.7120879 -73.9113197
   A2 40.7828647 -73.9653551
   A3 40.740777  -73.841136

I want to find out distance between these linestring locations and the other locations I will stop at
B1 40.7029334,-73.6208314
B2 40.7037142,-73.6086649
B3 40.7088981,-73.6137852
B4 40.7133267,-73.6056991
B5 40.7185586,-73.6007205

e.g.
A1 B1 - xxa meters
A1 B2 - xxb meters
A1 B3 - xxc meters
A1 B4 - xxd meters
A1 B5 - xxe meters

A2 B1 - xya meters
A2 B2 - xyb meters
A3 B3 - xyc meters
A4 B4 - xyd meters
A5 B5 - xye meters

etc
CREATE TABLE SpatialTable
    ( id int IDENTITY (1,1),
    GeogCol1 geography
);
GO

INSERT INTO SpatialTable (GeogCol1)
VALUES (geography::STGeomFromText('LINESTRING(40.7120879 -73.9113197, 40.7828647 -73.9653551, 40.740777, -73.841136)', 4326))

CREATE TABLE Route
    ( id int IDENTITY (1,1),
    Latitude float,
    Longitude float
);
GO

Insert into Route(Latitude,Longitude)
values
(40.7029334,-73.6208314),
(40.7037142,-73.6086649),
(40.7088981,-73.6137852),
(40.7133267,-73.6056991),
(40.7185586,-73.6007205)

A: There is no inbuilt function for this (that I am aware of at least), but something like this should give you the results you are looking for.
--Index of point on linestring
DECLARE  @i INT = 1

--Output
DECLARE @ResultTable TABLE (LinePointNumber INT, PointID INT, Distance FLOAT)

--Identifier for the individual points
DECLARE @id INT
DECLARE @g GEOGRAPHY

--Linestring
DECLARE @geogcol GEOGRAPHY = (SELECT TOP 1 GeogCol1 FROM SpatialTable)

--loop through each point on the linestring
WHILE @i <= @geogcol.STNumPoints()
BEGIN
  --turn points into geography and loop through the collection
  --if you just cast a float to a varchar it will truncate, so cast to a decimal first to prevent that
  DECLARE pointcursor CURSOR FOR SELECT id, GEOGRAPHY::STPointFromText('POINT(' + CAST(CAST(Longitude AS DECIMAL(15,10)) AS VARCHAR(15)) + ' ' + CAST(CAST(Latitude AS DECIMAL(15,10)) AS VARCHAR(15)) + ')', 4326)
  OPEN pointcursor
  FETCH NEXT FROM pointcursor INTO @id, @g
  WHILE @@FETCH_STATUS = 0
  BEGIN
    --STPointN returns that point, the the distance is STDistance
    INSERT INTO @ResultTable (LinePointNumber, PointID, Distance) VALUES (@i, @id, @g.STDistance(@geogcol.STPointN(@i)))

    FETCH NEXT FROM pointcursor INTO @id, @g
  END
  CLOSE pointcursor
  DEALLOCATE pointcursor
  SET @i = @i + 1
END

SELECT * FROM @ResultTable

A: Hcaelxxam has just beat me to a solution - and in native SQL.  Never-the-less, I've worked it up for you so here it is.
Given a helper class of
public class MyPoint
{
    public MyPoint(string title, SqlGeography location)
    {
        this.Title = title;
        this.Location = location;
    }

    public string Title { get; set; }

    public SqlGeography Location { get; set; }
}

Use the following code:
// The line, or route consisting of "waypoints"
        SqlGeography lineString = SqlGeography.STLineFromText(new System.Data.SqlTypes.SqlChars("LINESTRING(40.7120879 -73.9113197, 40.7828647 -73.9653551, 40.740777 -73.841136)"), 4326);

        // A container for all lookups
        List<MyPoint> stopLocations = new List<MyPoint>();

        // A container for all waypoints in the route
        List<MyPoint> wayPoints = new List<MyPoint>();

        // Add the stop locations
        stopLocations.Add(new MyPoint("B1", SqlGeography.Point(-73.6208314, 40.7029334, 4326)));
        stopLocations.Add(new MyPoint("B2", SqlGeography.Point(-73.6086649, 40.7037142, 4326)));
        stopLocations.Add(new MyPoint("B3", SqlGeography.Point(-73.6137852, 40.7088981, 4326)));
        stopLocations.Add(new MyPoint("B4", SqlGeography.Point(-73.6056991, 40.7133267, 4326)));
        stopLocations.Add(new MyPoint("B5", SqlGeography.Point(-73.6007205, 40.7185586, 4326)));

        // Add the waypoints
        for (int i = 1; i < (lineString.STNumPoints() + 1); i++)
        {
            wayPoints.Add(new MyPoint("A" + i, SqlGeography.Point(lineString.STPointN(i).Lat.Value, lineString.STPointN(i).Long.Value, lineString.STSrid.Value)));
        }

        // Join the data (essentially a cross-join) and calculate distances
        var joinAndCalculate = (
            from wp in wayPoints
            from sl in stopLocations
            select new
            {
                WayPointTitle = wp.Title,
                StopLocationTitle = sl.Title,
                DistanceInMetres = wp.Location.STDistance(sl.Location)
            }
            ).OrderBy(x => x.WayPointTitle).ThenBy(x => x.StopLocationTitle)
            .ToList()
                               ;
        // Print to the console, for testing
        foreach (var data in joinAndCalculate)
        {
            Console.WriteLine(data.WayPointTitle + "\t" + data.StopLocationTitle + "\t" + data.DistanceInMetres);
        }

If not you, it may help someone else.


text:
Q: Batch file not moving files for some reason if I run the batch file from different location other the sDir it will not move the files
@ECHO OFF &CLS
::// The Input Folder
SET $sDir="C:\Temp"

:: The Output Folders
SET $Out305="C:\Documents\completed"

::// Set Files extensions
SET "$Format=*.pdf,*.doc,*.jpg"

SETLOCAL enabledelayedexpansion

:Loop
cls&echo Waiting for file !!!
for /f %%a in ('dir /b/a-d %$sDir%\%$Format% 2^>nul') do (
 SET "$Fichier=%%a"
 ECHO Treating _^> %%a
 if "!$Fichier:~0,3!"=="305" move "%%~nxa" %$Out305%
)

::// Waiting ~5 seconds
ping localhost -n 6 >nul

::// Return to the loop
goto:Loop

A: Sorry, but to me your code is a mess. I'll try to clean it up and to solve the problem.
@ECHO OFF
CLS

:: The Input Folder
SET sDir="C:\Temp"

:: The Output Folders
SET Out305="C:\Documents\completed"

:: Set Files extensions
SET "Format=*.pdf,*.doc,*.jpg"

SETLOCAL EnableDelayedExpansion

:Loop
CLS
ECHO Waiting for file!!!
FOR /F %%a IN ('DIR /b/a-d %sDir%\%Format% 2^>nul') DO (
    SET "Fichier=%%a"
    ECHO Treating _^> %%a
    IF "!Fichier:~0,3!"=="305" MOVE "%%a" %Out305%
)

:: Waiting ~5 seconds
PING localhost -n 6 >nul

:: Return to the loop
GOTO Loop

I guess the problem is this line:
IF "!Fichier:~0,3!"=="305" move "%%~nxa" %Out305%

Your source is %%~nxa, means the name and the extention of %%a. But this way you just ignore the path to the file and the script will only look for it in it's own directory. The fix schould be just to replace %%~nxa with %%a or %%~dpnxa. Please tell me if it helps.
PS: I'd like to offer you some tips about clean code in batch. Just skip the rest of the post if you're not interested.
Don't use special characters like $ in variable names. This is uncommon in batch coding and might cause trouble in very unexpected situations.
Some people like to type commands in capital letters (PING, ECHO, CLS), others don't (dir, for, if). To keep your code clean you should try to skick to one convention. Line like theese make your code ugly to read:

ECHO Treating _^> %%a
if "!$Fichier:~0,3!"==...

A: Why your code fails? You are using a for /f command to process the output of a dir /b command. This output does not include folder information unless /s switch is used to do a recursive search. So, as the string (not a reference to a file found by a for) being processed does not include a folder, none of the following commands
MOVE "%%~nxa" .... ( only name and extension, no path )
MOVE "%%a" ....    ( only name and extension, the string does not include path )
MOVE "%%~fa" ....  ( path generated using the active directory, not file folder )

will found the file as it is not located in the current folder (the first two) or has a wrong path (the third one).
You will need something like
MOVE "%$sDir%\%%a" ....

But as your variables also include quotes, you will have to change the set commands to
SET "$sDir=c:\temp"

That is, the quotes should not be included in the value if later we need to concatenate the value.
Anyway, as the only thing that the code is doing to move the files starting with 305 to a target folder and repeat the process, this can be simplified as
@echo off
    setlocal enableextensions disabledelayedexpansion

    set "inputFolder=c:\temp"
    set "output305=c:\documents\completed"
    set "extensions=.pdf .doc .jpg"

    for /l %%a in (0) do (
        for %%b in (%extensions%) do 2>nul move /y "%inputFolder%\305*%%~b" "%output305%"
        >nul ping localhost -n 6
    )

An infinite loop (for /l %%a in (0)) that will iterate over the indicated list of extensions and move any file in the input folder, starting with 305 and with a matching extension into the target folder.


text:
Q: TraceFlag 1118 for TempDB There are many advantages of enabling trace flag 1118 ( as a service startup paramter) for TempDB to reduce contention related to mixed extent allocation even it case of SQL 2008/R2 or SQL 2012. Why in the world it is disabled out of the box in a default SQL server configuration?

A: Misconceptions around TF 1118. Read the paragraph about Why is the trace flag not required so much in 2005 and 2008?. Also consider that there are plenty of workloads that make little or no use of temp tables (eg. most well designed OLTP workloads) and some of those workloads could potentially suffer from extend allocations in tempdb.

A:
Use TF-1118. Under this trace flag SQL Server allocates full extents
  to each tempdb object, thereby eliminating the contention on SGAM
  page. This is done at the expense of some waste of disk space in
  tempdb. This trace flag has been available since SQL Server 2000. With
  improvements in tempdb object caching in SQL Server 2005, there should
  be significantly less contention in allocation structures. If you see
  contention in SGAM pages, you may want to use this trace flag. Cached
  tempdb objects may not always be available. For example, cached tempdb
  objects are destroyed when the query plan with which they are
  associated is recompiled or removed from the procedure cache.

So it takes more space which can hurt certain workloads.


text:
Q: Find min date for each stage of a process I have a process stages I need to find when did they happen. Unfortunately I can only do it though text extraction.
I have extracted dates that match the stages found in the associated text column. Unfortunately some text values are similar and were inputed to the table incorrectly, and so extracted dates are duplicated.
I cannot edit the existing table, however, I am trying to create a new one based on the manipulations I am doing (text extract, date ordering, etc).
I need to make sure that the dates are not mixed up and are consecutive. For example stage 1 date is earlier than stage 2 etc...
Data sample

Person_ID
Stage
Stage_Num
Stage_Date

1
Stage-1
1
2020-01-01

1
Stage-1
1
2021-02-02

1
Stage-2
2
2020-05-01

1
Stage-2
2
2020-05-06

1
Stage-1-R
3
2021-02-02

1
Stage-1-R
3
2020-01-01

Final result I am expecting is

Person_ID
Stage
Stage Num
Stage_Date

1
Stage-1
1
2020-01-01

1
Stage-2
2
2020-05-01

1
Stage-1-R
3
2021-02-02

I've tried the following:
select a.person_id,a.stage, a.stage_num, min(a.stage_date)
from
all_activity_dates a   join all_activity_dates b
where
a.stage_num<=b.stage_num
and a.stage_date<b.stage_date
group by
a.person_id, a.stage, a.stage_num
order by stage_num

However, the result date for stage 1 and 3 turn out to be the same.
How do I perform it correctly?
UPD1 To whoever closed my question: I cannot simply select the min and group by STAGE (I definitely know how to do that)
In my original question I state I need consecutive order, but with simple MIN DATE STAGE 1 and STAGE 3 would have the SAME DATE , BUT STAGE 3 HAS to be AFTER STAGE 2.
UPD2 Plus for stages I am missing to extract date I'd need to add a random date between previous and next stage
If it is a duplicate, I. am glad to check a working solution, I just could not find a similarly worded question

A: Here's a solution that  will at least filter out the dates that would mess up the order of Stage_num.

select Person_ID, Stage, Stage_Num
, max(Stage_Date) as Stage_Date
from your_table t
where not exists (
        select 1
        from your_table t2
        where t2.person_id = t.person_id
          and t2.stage_num = t.stage_num + 1
        group by t2.person_id, t2.stage_num
        having max(t2.stage_date) < t.stage_date
   )
group by Person_ID, Stage, Stage_Num
order by Person_ID, Stage_Num;

Person_ID
Stage
Stage_Num
Stage_Date

1
Stage-1
1
2020-01-01

1
Stage-2
2
2020-05-06

1
Stage-1-R
3
2021-02-02

Demo on db<>fiddle here
But the thing about adding the missing Stage_nums with a random stage name & date is too unclear.
You could left join to a tally table.  Or just add them manually.


text:
Q: How to dynamically build a Hash dataset in Rails? I'm working to build a chartjs data object that contains a dynamic number of datasets. In my Ruby on Rails 5 controller, I'm trying the following:
chartJsObject = []

chartJsObject << {
  label: "Label Stuff",
  datasets: []
}

i = 0
num = 5

while i < num  do
  chartJsObject.datasets << [rand(10), rand(10)]
   i+=1
end

This is resulting in the following error:
undefined method `datasets' for [{:label=>"Label Stuff", :datasets=>[]}]:Array

Any ideas what I'm doing wrong here to be able to loop through and populate chartJsObject.datasets?

A: In the first line you define chartJsObject as an array:
chartJsObject = []

then in the second, you push a hash object in it:
chartJsObject << {
  label: "Label Stuff",
  datasets: []
} #=> [{:label=>"Label Stuff", :datasets=>[]}]

Now, what you have is an array of hash objects. In order to insert the data in datasets you just need access to the hash object, probably like so:
i = 0
num = 5

while i < num  do
  chartJsObject[i][:datasets] << [rand(10), rand(10)] if chartJsObject[i]
  i+=1
end


text:
Q: ServletOutputStream write in jsp when using struts I am working with a struts2 web application. Am facing a situation in which I want to display a file (it may be an excel , pdf file or html) in the users browser when he/she clicks on a link.
And the response must be in the form of an open/save dialogue box in the browser.
For that what I had done so far is
1)create an action mapping in struts.xml file.
2)Action  class method will have the content like
ServletOutputStream outputStream = null;
outputStream = response.getOutputStream();
                byte[] output = (byte[])content;
                response.setContentType(getContentType(format));
                response.setContentLength(output.length);
                outputStream.write(output, 0, output.length);
                outputStream.flush();
                outputStream.close();

This code portion will set whatever is the content type, content length and atlast will write the content.
My question is what I need to write in the jsp page for displaying this content.?
Anyone please help.

A: You either display a JSP page as a result from an action or you have the browser download a file. You can't do both. They're sent on the same channel, so to speak.
For a typical example for how to implement downloading files, see StreamResult.
But in this case you probably just want to return ActionSupport.NONE or null from your action since you're setting up the headers and writing the output yourself, see http://struts.apache.org/2.x/docs/result-configuration.html
If you call
response.setHeader("Content-Disposition","attachment; filename=\"rfc2616-quoted-string\"");`

the user will be presented with a download dialog, but if you call
response.setHeader("Content-Disposition","inline");`

the content will be shown in the browser if possible.

A: I would recommend using a StreamResult
Here is an example
Additionally, you can set the StreamResult params in your action class instead of the struts.xml file.

A: Nothing, you need also to set Response header context-disposition as "attachment"

A: Add this to your servlet code
 response.setHeader("Content-Disposition","attachment;filename=myfilename.pdf");


text:
Q: Ajax page load in div halts browser even if it is async? I am trying to do async page open inside div with $.ajax but i am still having about 3sec delay after clicking link and that time page is jammed. Happens at least chrome and sasfari. Where am i going wrong way..?
$.ajaxSetup({
    async: true
});
$(document).ready(function() {
    $("#Button").click(function(evt) {
        $('#change').html('

');
        $.ajax({
            url: "reg.php",
            cache: false
        }).done(function( html ) {
            $("#change").html(html);
        });
    });
});

A: No, asynchronous ajax requests like that don't hold up the browser. The problem is elsewhere, in code you haven't shown. The code you've shown will correctly do an async request.
Speculating on possible issues with what we can't see:

*

*If the link has an href, you're not cancelling the default action, so it could be loading the page. You can prevent the default by calling evt.preventDefault() within your click handler, or by doing return false; at the end of it (which does that and also stops propagation).

*If you have other code elsewhere setting async: false as the default, perhaps your ajaxSetup changing it back isn't getting called.

A: If you are using PHP sessions then the script will halt the browser until reg.php is completely finished.
In reg.php you will need to add this somewhere:
session_write_close();

This will allow you to read the session data but not write to it.
This is the case because you would probably never want two ASYNC scripts trying to write to the session at the same exact time.


text:
Q: How to prove that a function is bijective? I just began learning about mathematical proofs (the questions I have in homework are mainly about proving bijections between sets) and I found this subject extremely puzzling and confusing and it seems like I can't understand this damn subject...
I understand that if you show that if $f(a)=f(b)$, then $a=b$ and the function is injective. So if I have a function from set $A$ (which is the set of odd natural numbers (without zero)) to set $B$ (even natural numbers (without zero)) $f(a)=a+1$ then you show that it is injective by saying that $a=b$ if $f(a)=f(b)$ because we can take $f(a)=f(b) = a+1=b+1$ and remove $1$ from both sides and turn it to $a=b$. This is a "proof" that the function is injective? Why? Because I could use some operations to turn $a+1=b+1$ to $a=b$?. And how do you prove that a function is surjective?

A: Yes that a correct proof for injectivity.
For sujectivity we need to prove that for every $n$ even exists $a$ odd such that $f(a)=a+1=n$ which is true.
Therefore $f$ is injective and surjective and thus invertible.


text:
Q: Flex: make responsive two column page Let's assume I have a two column page: an article + image. And using flex I want it to be responsive in all screens, i.e. I want it always to keep its proportions.

How do I do it?
Here is the code:
HTML

Lorem ipsum

            Lorem ipsum dolor sit amet, consectetur adipiscing elit. Pellentesque non rhoncus quam, ut varius risus.
            Donec eu ullamcorper sem, eget sodales lacus. Sed iaculis eros lectus, fringilla sollicitudin nibh viverra
            volutpat. Integer dolor est, maximus non nibh eget, cursus commodo lectus. In finibus sagittis lectus. Donec
            nec mi dui. Praesent sit amet ullamcorper neque. Nulla id libero vitae dui fringilla volutpat. Suspendisse
            lacinia rutrum sem eget fringilla.

            Fusce porta orci dui, ac egestas nibh cursus vitae. Sed vel odio venenatis, elementum enim in, malesuada
            eros. In dapibus ex vitae leo vestibulum, non lacinia massa varius. Nullam faucibus eros ut maximus dapibus.
            Praesent vitae ante vulputate, sagittis lectus eu, egestas massa. Curabitur eget pulvinar nunc. Donec
            faucibus libero sed nisi efficitur, sit amet efficitur diam aliquet. Fusce a ultricies neque. Maecenas
            fringilla iaculis metus, efficitur faucibus lorem. Etiam nisi orci, hendrerit eu felis ac, interdum laoreet
            nisi. Etiam sit amet fermentum odio. Nulla et vehicula purus. Sed lacinia pharetra augue.

                Lorem Ipsum

CSS
.image {
  width: 300px;
  height: 200px;
}
.example {
  max-width: 800px;
  margin: 0 auto;
  font-size: 14px;
  padding: 54px 0 0 0;
  width: 100%;
  position: relative;
}
.example-sides {
  display: -webkit-flex;
  display: flex;
  display: -ms-flexbox;
  -webkit-flex-direction: row;
  flex-direction: row;
  -webkit-align-items: flex-start;
  align-items: flex-start;
  line-height: 20px;
  padding: 45px 0 55px 0;
}
.example-text {
  box-sizing: border-box;
  float: left;
  padding-left: 0 !important;
}
.example-img {
  box-sizing: border-box;
  margin-left: 20px;
}

A: Please try this one

/*  SECTIONS  */
.section {
  clear: both;
  padding: 0px;
  margin: 0px;
}

/*  COLUMN SETUP  */
.col {
  display: block;
  float:left;
  margin: 1% 0 1% 1.6%;
}
.col:first-child { margin-left: 0; }

/*  GROUPING  */
.group:before,
.group:after { content:""; display:table; }
.group:after { clear:both;}
.group { zoom:1; /* For IE 6/7 */ }

/*  GRID OF TWO  */
.span_2_of_2 {
  width: 100%;
}
.span_1_of_2 {
  width: 49.2%;
}

/*  GO FULL WIDTH AT LESS THAN 480 PIXELS */

@media only screen and (max-width: 480px) {
  .col {
    margin: 1% 0 1% 0%;
  }
}

@media only screen and (max-width: 480px) {
  .span_2_of_2, .span_1_of_2 { width: 100%; }
}

    This is column 1

    This is column 2

A: you need a nested flex div to approach this.

div#mainContent{
display:flex;
flex-direction:row;
flex-wrap:wrap;
height:500px;
position:relative;}

#mainContent .forImage{
  position:relative;
  background:red;
  width:30%;
  height:100%;
  display:flex;
  align-items:flex-start;
  justify-content:center;
}
.forImage .theImage{
  width:90%;
  margin-top:50px;
}
.theImage img{
width:100%;}

#mainContent .forText{
  background:yellow;
  width:70%;
  height:100%;
  display:flex;
  align-items:flex-start;
  justify-content:center;
  position:relative;
}
.forText .theText{
 width:90%;
  margin-top:50px;
}

    <image src="http://imagecolony.com/wp-content/uploads/2016/09/Wallpaper-Wide-803.jpg">

  Lorem Ipsum is simply dummy text of the printing and typesetting industry. Lorem Ipsum has been the industry's standard dummy text ever since the 1500s, when an unknown printer took a galley of type and scrambled it to make a type specimen book. It has survived not only five centuries, but also the leap into electronic typesetting, remaining essentially unchanged. It was popularised in the 1960s with the release of Letraset sheets containing Lorem Ipsum passages, and more recently with desktop publishing software like Aldus PageMaker including versions of Lorem Ipsum.

A: Here's a starting point:

body {
  max-width: 95%;
  background: #111;
}
.columnleft {
  float: left;
  max-width: 50%;
}
.columnright {
  float: right;
  max-width: 50%;
}
.article {
  border: 1px solid #999;
  display: inline-block;
  margin: 4%;
}
.title {
  color: #aff;
  font-size: 22px;
  text-align: center;
  margin: 20px 0 5px 0;
}
.content {
  color: #888;
  font-size: 18px;
  text-align: justify;
  padding: 20px;
  margin: 15px 15px 30px 15px
}
img {
  margin: 0 auto;
  max-width: 100%
}

Headline 1

Lorem ipsum dolor sit amet, legere menandri mei te, praesent democritum no pro. Aliquid tractatos facilisis in eam. Odio nisl scriptorem mea ad, id alii vidisse sit. Animal voluptaria mel te. An eum harum labore. Lorem ipsum dolor sit amet, legere
        menandri mei te, praesent democritum no pro. Aliquid tractatos in eam. Odio nisl scriptorem mea ad, id alii vidisse sit. Animal voluptaria mel te. An eum harum labore.

Headline 2

Headline 3

Lorem ipsum dolor sit amet, legere menandri mei te, praesent democritum no pro.Aliquid tractatos facilisis in eam. Odio nisl scriptorem mea ad, id alii vidisse sit. Animal voluptaria mel te. An eum harum labore. Lorem ipsum dolor sit amet, legere

Headline 4

Lorem ipsum dolor sit amet, legere menandri mei te, praesent democritum no pro. Aliquid tractatos facilisis in eam. Odio nisl scriptorem mea ad, id alii vidisse sit.

Headline 5

Lorem ipsum dolor sit amet, legere menandri mei te, praesent democritum no pro. Aliquid tractatos facilisis in eam. Odio nisl scriptorem mea ad, id alii vidisse sit. Animal voluptaria mel te. An eum harum labore. Lorem ipsum dolor sit amet, legere
        menandri mei te, praesent democritum no pro. Aliquid tractatos facilisis in eam. Odio nisl scriptorem mea ad, id alii vidisse sit. Animal voluptaria mel te. An eum harum labore. Lorem ipsum dolor sit amet, legere menandri mei te, praesent democritum

Headline 6

A: Flexbox is a good choice for this layout
If you want to keep your HTML structure and the image has to be on the left side you additionally have to set flex-direction: row-reverse or give an order otherwise you could simply put the figure before the article tag.
To achieve your desired layout just change your CSS to the following
CSS
.example {
  max-width: 800px;
  margin: 0 auto;
  font-size: 14px;
  padding: 54px 0 0 0;
  width: 100%;
  position: relative;
}

.example-sides {
  display: flex;
  line-height: 20px;
  padding: 0 20px;
}

.example-text {
  flex: 1;
  min-width: 200px;
  order: 2;
  margin-left: 20px;
}

.example-img {
  flex: 0 1 300px;
  order: 1;
  margin: 0;
}

.image {
  width: 100%;
  max-height: 200px;
}

.example {
  max-width: 800px;
  margin: 0 auto;
  font-size: 14px;
  padding: 54px 0 0 0;
  width: 100%;
  position: relative;
}
.example-sides {
  display: flex;
  line-height: 20px;
  padding: 0 20px;
}
.example-text {
  flex: 1;
  min-width: 200px;
  order: 2;
  margin-left: 20px;
}
.example-img {
  flex: 0 1 300px;
  order: 1;
  margin: 0;
}
.image {
  width: 100%;
  max-height: 200px;
}

Lorem ipsum

      Lorem ipsum dolor sit amet, consectetur adipiscing elit. Pellentesque non rhoncus quam, ut varius risus. Donec eu ullamcorper sem, eget sodales lacus. Sed iaculis eros lectus, fringilla sollicitudin nibh viverra volutpat. Integer dolor est, maximus non
      nibh eget, cursus commodo lectus. In finibus sagittis lectus. Donec nec mi dui. Praesent sit amet ullamcorper neque. Nulla id libero vitae dui fringilla volutpat. Suspendisse lacinia rutrum sem eget fringilla. Fusce porta orci dui, ac egestas nibh
      cursus vitae. Sed vel odio venenatis, elementum enim in, malesuada eros. In dapibus ex vitae leo vestibulum, non lacinia massa varius. Nullam faucibus eros ut maximus dapibus. Praesent vitae ante vulputate, sagittis lectus eu, egestas massa. Curabitur
      eget pulvinar nunc. Donec faucibus libero sed nisi efficitur, sit amet efficitur diam aliquet. Fusce a ultricies neque. Maecenas fringilla iaculis metus, efficitur faucibus lorem. Etiam nisi orci, hendrerit eu felis ac, interdum laoreet nisi. Etiam
      sit amet fermentum odio. Nulla et vehicula purus. Sed lacinia pharetra augue.

        Lorem Ipsum


text:
Q: How to remove first pin image after calling refresh button in iOS? I have map view and I am showing car on my map view using map view annotation. But after
click on refresh button. first image is remain and update pin image showing with.
         I want to remove first pin image after refresh button pressed.
Thank You.


text:
Q: Some functions/methods not exported into static library - Visual Studio 2019 C++ Apologies if this is an ill formed question. But it is something I don't even know where to start debugging.
I have a library, in which I keep general purpose code. i build this as a static library to include in my projects. The library and the projects are written in C++ and built in Visual Studio 2019.
I have just made some modifications to some code (which happens to be for dealing with times and dates) and suddenly most of my functions and methods within the .cpp file in question are no longer exported into my static library.
I am now getting unresolved symbols linker errors when I try to use these functions/methods. I have run
dumpbin /symbols /exports mylibrary.lib > exports.txt
and searching this output, shows that only a handful of symbols associated with my function/method definitions are listed. Symbols are missing for most of my methods, including those for which I have linker errors.
My questions are - have I done enough to show that my functions are not being exported - i.e. is dumpbin /symbols /exports the correct command to use? And secondly, if I have performed that check correctly, how is it possible that I have only exported some of my methods/functions and are there any steps I can take to fix it or debug further? I did not even realise this was possible when building a static lib.
Please note I am building a static lib, not an import lib or a dll.
Edit:
One example of a method not being exported is
constexpr int sci::UtcTime::getYear() const
{
    return m_cTime.tm_year+1900;
}

where sci is a namespace, UtcTime is my time related class and m_cTime is a std::tm member variable of UtcTime.
I have tried cleaning and rebuilding everything and even rebooting my computer in desperation.
Edit 2:
Removing constexpr seems to result in the symbol being exported and resolves the linker problems. Why would that be the case?

A: As mentioned in my comment, constexpr is implying inline which causes compiler to not emit the symbol at all.

A constexpr specifier used in a function or static member variable (since C++17) declaration implies inline.

Your edit is also empirical proof that that's the case. I would say it is working as expected. The choice is now yours about whether you want the function to be exported or be constexpr qualified.
As for why you have started seeing this now, VC++ has been undergoing compliance related changes for the past 5 years or so, and generally each release is more compliant with the latest language standard at the time of release than previous releases.


text:
Q: JDialog keeps reopening So I have a JDialog box that opens whenever you want to make something new in the program I'm making. The first time you open it, it works fine when you close it. But the second time, when you close it, it reopens and you have to close it for a second time. If you were to open it for a third time, you would have to close it three times, and you can see where I'm getting at. I'm assuming it's how I am showing it, and where I am setting it visible and not visible so those are the segments of code I will present, but if you need anything else just ask. The JDialog box itself is a separate class by the way. Thanks in advance.
First Creating the Dialog
private NewPlatformDialog npd = new NewPlatformDialog(frame, "New Platform", this);
Opening it
else if(source == mouseNewPlatform || source == newPlatform) {
    npd.setVisible(true);
}

Places where I close it (first one in constructor)
setDefaultCloseOperation(WindowConstants.HIDE_ON_CLOSE);
pack();
setVisible(false);

Button to close it
if(source == cancel) setVisible(false);
Apply Button
`
else if(source == add) {
    if(platformSelector.getSelectedIndex() == 0) {
        int x = 0, y = 0, w = 0, h = 0;
        if(xField != null) x = Integer.parseInt(xField.getText());
        if(yField != null) y = Integer.parseInt(yField.getText());
        if(widthField != null) w = Integer.parseInt(widthField.getText());
        if(heightField != null) h = Integer.parseInt(heightField.getText());

        le.platforms.add(new DragablePlatform(x, y, w, h, Platform.NORMAL));
        le.repaint();

        resetFields();
        setVisible(false);
    }
}

While I don't think I'm doing anything wrong, I could be mistaken, so again thanks in advance for any help.
DragablePlatform Class
package resources;

public class DragablePlatform extends Platform {
public DragablePlatform(int x, int y, int w, int h, int type) {
    super(x, y, w, h, type);
}
public DragablePlatform(int x, int y, int w, int h, int type, int horizVerti, int max) {
    super(x, y, w, h, type, horizVerti, max);
}
}


text:
Q: Why do arrow keys mess up stdout? I am writing a simple client - server programs in C for practicing network programming. The server can handle multiple clients by using multi threading. Each client is serviced in a separate thread. The client uses two threads : one to take user input from stdin and one to print to stdout.
I tested the program with regular text and it works perfectly. However, it behaves very weirdly when I input arrow keys (left key = ^[[D, right key = ^[[C, up key = ^[[A, down key = ^[[B).
For example see this output:
This is the input I sent in sequentially (in client):
>> test
I got your message
>> test1
I got your message
>> test2
I got your message
>> test3
I got your message

This is the (correct) output in server:
Here is the message: test
Here is the message: test1
Here is the message: test2
Here is the message: test3

Now I input random arrow keys (after inputting test3):
>>^[[D^[[A^[[C^[[A^[[D^[[C^[[A^[[D^[[B^[[C^[[D^[[B^[[D^[[C^[[A^[[D^[[C^[[A^[[D^[[A^[[D^[[C^[[A
I got your message

However, server prints nothing (I assumed the characters were escaped):
Here is the message: test
Here is the message: test1
Here is the message: test2
Here is the message: test3
Here is the message:

Now, I start inputting normal text:

>> test4
I got your message
>> test5
I got your message
>> test6
I got your message
>> test7
I got your message
>> test8
I got your message
>> test9
I got your message
>> test10
I got your message

When I check the server's stdout, all the previous printout is overwritten:
Here is the message: test4
Here is the message: test5
Here is the message: test6
Here is the message: test7
Here is the message: test8
Here is the message: test9
Here is the message: test10

Most importantly, the behavior changes with the random keystrokes of arrows I enter. Sometimes, the input won't override the server's stdout but it inserts the input within stdout.
I am not sure why this is happening but, if anyone wants to see my source, I can post it. The source is not long - the client and server are about 100 lines long.

Ok I tested each key seperately.
The down key and up key seem to move the file pointer in stdout by lines. And left and right keys seem to do nothing.

A: You are confusing stdout (which is a stream of bytes) with the result of feeding those bytes into a terminal emulator. If you capture your server's
stdout into a file, you'll be able to look at it using a hex editor (or the hd command, and you'll see the actual bytes sent.
The terminal emulator takes these bytes and converts them into actions which result in your display showing you something. Bytes or sequences of bytes may be displayed as single graphemes (visible symbols) or interpreted as control codes (move the cursor, change output or background colour, etc.), or even just ignored.
To understand how these bytes are interpreted, you could consult the documentation for your terminal emulator (if you can find it) or try the useful summaries in the XTerm documentation (which is specific to xterm but most modern terminal emulators are similar) or man 4 console_codes (which is specific to the Linux console, but again similar to most terminal emulators).

A: The arrow keys are sending multi-character ANSI escape sequences.  BASH (and other programs) use a library like readline (or maybe curses) to convert the escape sequences into cursor movement/editing.  If you do not want to use such libraries, you would have place the terminal into raw mode and read and process each escape sequence and move the cursor by sending cursor movement sequences, a difficult process.


text:
Q: how can I change a string from ANSI to UTF8 in Javascript? the binary code needs to change I have a  tag where the user can input text, but it happened that when copying text that's not encoded in utf8 I get a different output when sending the data in a Json file. look at this=>
I made this code to test the problem=>
<!DOCTYPE html>

<form>
<input id="q1">
<input id="q2">
</form>
<button onclick="as()">calcular</button>

I have two inputs, in the first input (w) I pasted a string from a ANSI file, on the second input (z) I just wrote the same text on the input, so it'd be in UTF-8. what I need is the first input (w) to end up with the same binaries as the second input (z) and by comparing the binary we can see that it's almost identical except for the 11th position of the array, in binaryC1 (z) we have 32 but on the other binaries (w) we have 194 and 160 (so two positions) is there a way that I can do this for all strings? I don't want to hard code a correction.
memory=>
binaryA1: Uint8Array(17) [83, 111, 109, 101, 116, 104, 105, 110, 103, 111, 114, 194, 160, 73, 107, 111, 114]

binaryA2: "Somethingor Ikor"

binaryA3: Uint8Array(17) [83, 111, 109, 101, 116, 104, 105, 110, 103, 111, 114, 194, 160, 73, 107, 111, 114]

binaryB1: "Somethingor Ikor"

binaryB2: "Somethingor Ikor"

binaryB3: Uint8Array(17) [83, 111, 109, 101, 116, 104, 105, 110, 103, 111, 114, 194, 160, 73, 107, 111, 114]

binaryC1: Uint8Array(16) [83, 111, 109, 101, 116, 104, 105, 110, 103, 111, 114, 32, 73, 107, 111, 114]


text:
Q: Calling session from jQuery Mobile client with Spring Security authentication and JAX-RS resource My JAX-RS resource for authentication looks like this (by the way I want to improve it for security matters because it's not safe to call the username and password by a GET Method):
@Path("/UserService")

public class UserServiceRS {

UserService user ;
AuthenticationManager authManager;
public UserServiceRS(){

user=(UserService)SpringApplicationContext.getBean("userDetailsService");
authManager(AuthenticationManager)SpringApplicationContext
.getBean("authenticationManager");

 }

@GET
@Produces(MediaType.APPLICATION_JSON)
@Path("/authentification/{username}/{password}")
public String login(@PathParam( value="username" ) String username,
        @PathParam( value="password" ) String password )
{
     Logger LOG = LoggerFactory.getLogger(LoginBean.class);
    LOG.info("Starting to login");
    try{
        UsernamePasswordAuthenticationToken usernamePasswordAuthenticationToken = new UsernamePasswordAuthenticationToken(username,password);
    Authentication authenticate = authManager.authenticate(usernamePasswordAuthenticationToken);
    SecurityContextHolder.getContext().setAuthentication(authenticate);

     return "1";
    }catch (final Exception e){
        LOG.error("Error log in" + e);

    }

    return "0";
}

And in my jQuery Mobile client the method I call in the "connect" button looks like this:
function login(){
 var uri="myuri";
 var login=$("#login").val();
 var password=$("#pass").val();
 uri=uri+"/"+login+"/"+password;
 $.getJSON(uri,function(data){
     if(JSON.stringify(data)==1){

$.mobile.changePage("#page-signup-succeeded",{transition:"slide" });
      }
     else {
        $.mobile.changePage("#page-signup-failed");

     }
 });
 };

I would like to manage the session in my jQuery Mobile client and I don't know how to get the session from the authenticated user. How can I achieve this?


text:
Q: ggplot2 stat_densty_2 -- how to fill different parts of the chart wth different colors? If I am making a stat_density_2d plot, with raster geometry, how can I color one part of the chart one color, another part of the chart another?
So for this chart:
d <- ggplot(data, aes(xVal, yVal))
d + stat_density_2d(geom = "raster", aes(fill = ..density..), contour = FALSE) +
  scale_fill_gradient2(low = "white",
  high = "#1A6AFF", space = "Lab", limits=c(0.00000, 0.00008), guide = "colourbar") +
 geom_point() + xlim(-100,100)

How might I fill between -100 and 0 from a white to red gradient, and the 0 to 100 part of the plot with a white to blue gradient? Note that the fill is based on density, so it would just be splitting the chart into two parts, not creating a continuous scale along -100 to 100.

A: I believe what you are trying to accomplish is covered in the documentation.  Here is the excerpt that uses the diamonds data set:
set.seed(4393)
dsmall <- diamonds[sample(nrow(diamonds), 1000), ]
d <- ggplot(dsmall, aes(x, y))
# If you map an aesthetic to a categorical variable, you will get a
# set of contours for each value of that variable
d + geom_density_2d(aes(colour = cut))

This produces the plot:

If you want to turn off the contours for a tile image, you can do so:
# If we turn contouring off, we can use use geoms like tiles:
d + stat_density_2d(geom = "raster", aes(fill = ..density..), contour = FALSE)

Which produces the following plot:


text:
Q: On super-logarithmic Collatz numbers The Collatz conjecture (or 3n + 1 conjecture) is a conjecture in mathematics that concerns a sequence defined as follows: start with any positive integer n. Then each term is obtained from the previous term as follows: if the previous term is even, the next term is one half the previous term. Otherwise, the next term is three times the previous term plus 1. The conjecture is that no matter what value of n, the sequence will always reach 1.
We denote by $collatz(n)$ the number of steps it takes to reach $1$ from $n$ (its delay).
Clearly, $collatz(n)\ge \log_2 n$ -- but by how much?
While the conjecture is still open, do we know any integer sequences with a super-logarithmic delay? Namely:

Is there a sequence $\{a_n\}$ such that $\mathit{Collatz}(a_n)=\omega(\log a_n)$?

What about the weakest bound, which is probably true:

Is there a sequence $\{a_n\}$ such that $\mathit{Collatz}(a_n)=\log_2 a_n + \omega(1)$?

From simulating many ($> 10^{12}$) random numbers (not in a uniform manner) between $1$ and $2^{9999}$, it seems that $\mathit{Collatz}(n)$ may be bounded by $50\log_2 n$.

Is there an $n$ for which $\mathit{Collatz}(n) \ge 50\log_2 n$?


text:
Q: Return the value checked for in a ternary condition in Javascript Is it possible for the following to happen. So basically I want to check if a exists or is defined or is not 0 and return that value if it is so else return 0. Is it even possible as a single statement - I am not looking to use a spare variable.
console.log(a ? a : 0)

Hi! as people in the comments have been kind enough to point out. My question is that - is there any way to simplify the above expression. I do not want to use the variable a twice. For this reason you can assume a to be a long executing function that returns a number. So, I want to use a only once

A: Yes it's possible:
console.log(a || 0);

The || operator coerces the left operand (a) to boolean type and returns it if it's true. Otherwise returns the right operand (0).
Note that if a is an empty string it will also return 0.
Alternatively:
console.log(a ?? 0);

The Nullish coalescing operator ?? is a recent feature that testing the left operand (a in this case) for being neither undefined nor null and returns it. Otherwise returns the right operand (0 in this case)