text:
Q: Deleted entire Git project I tried to fix my git repo and .gitignore for not having tracked the right files and everything is gone from remote and from local. This is some history of commands in bash on my ubuntu server:
 1952  git status
 1955  git rm -r --cached .

 1957  git commit -m "git fix"
 1958  git push

 1981  git rm -rf data/
 1982  git rm -r --cached data
 1983  git clean -xdf

 1986  git ls-files
 1995  ls

The major issue is everything is gone locally or remotely.
Thanks and Regards,

A: Some Git commands are "dangerous": they wipe out actual files from the world of your visible files (the working tree). And they do not just conceal them in some tricky way; they just remove them, as if they had never been. You have chosen to use two of those commands: git clean and git rm.
So if you use those commands, you can certainly remove files in such a way that they can never ever be recovered.
However, the job of Git is to preserve earlier states of your working tree. So if you made any commits that included any state of any of these files, then those states are preserved in those commits. So all you have to do is one or both of these:

*

*return to an earlier commit that includes your files

*extract an individual file from an earlier commit that includes it
Since everything was pretty much okay in the commit before the one you just made, you can go back to that commit simply by saying
git checkout @~

If you're pretty happy with what you see, then you will also want to get out of detached head mode by resetting your branch to what you see now:
git reset HEAD

But if there are other files that were in your working tree and have never been committed, then that is no business of Git's and no fault of Git's: you are the one who used the very dangerous words clean and rm, so whatever you damage you did, you did it to yourself. Git only stores commits; that is all it knows about and all it cares about.
So what's the lesson here? Is it "don't ever give dangerous commands"? Not at all! Give any commands you like, but first you need to be safe. To preserve a file (meaning a file in a particular state), commit it — and do that before you start rattling around giving dangerous commands. To risk losing a file when you give dangerous commands, don't commit it. It's as simple as that.


text:
Q: Weird sum of roots of unity Let $ 1, \omega_2, \omega_3, \omega_4\cdots \omega_n$ be the roots of the equation$$ x^n=1,$$ then find the value of

$$\frac{1}{2-\omega_2} + \frac{1}{2-\omega_3}+ \frac{1}{2-\omega_4} + \cdots+ \frac{1}{2-\omega_n}$$
  In terms of $ n$.

I tried many ways but was not able to solve this. If you see this message, then your question was automatically blocked by the server. All new questions are subjected to a "minimum quality" filter that checks for some basic indicators of a good, complete question. Check to make sure that your question has the following:

redpajama_set_name: RedPajamaStackExchange


text:
Q: Running Multiple Processes The following code I'm about to posts works fine, however I need to be able to kick off multiple processes at the same time.
So to give some background, the listbox contains files that will be run through another process to create PDF files (essentially passing arguments to the other process which is the exe listed in the StartInfo.Filename). What's currently happening, say the listbox contains 10 files. Each file will be processed separately before the additional files are processed. I'd like to be able to kick off all 10 files at the same time instead of waiting. Some files may take longer than others, so I'm wasting time waiting for each file to finish.
Suggestions?
            Dim UPSFiles = (From i In ListBoxUPSFiles.Items).ToArray()
        For Each Item In UPSFiles
            Dim UPSFiles2 = Item.ToString
            Using psinfo As New Process
                psinfo.StartInfo.FileName = "\\dgrvdp1\ClientServices\APPS\Printtrack\HeliosPNetExecuter\HeliosPNetExecuter.exe "
                psinfo.StartInfo.Arguments = Arg2 + Arg3 + Arg4 + (Chr(34) + DATA_PATH + "\" + UPSFiles2 + Chr(34) + " ") + Arg6 + Arg7 + Arg8 + Arg9a + Arg10 + Arg11 + Arg13
                psinfo.StartInfo.WindowStyle = ProcessWindowStyle.Hidden
                psinfo.Start()
                'psinfo.WaitForExit()
            End Using
        Next

EDIT
Here's my current code, based on the Parallel.ForEach suggestion. It appears to sort of worked but submitted 10x the number of files I need to run. In my case, I have two files to process however like I mention the code produced 10x the number of processes I truly need.
            Dim SequentialFiles = (From i In ListBoxSequentialFiles.Items).ToString
        For Each Item In SequentialFiles
            Dim SequentialFiles2 = Item.ToString

            Parallel.ForEach(SequentialFiles2, Sub(processFiles)

                                                   Using psinfo As New Process
                                                       psinfo.StartInfo.FileName = "\\dgrvdp1\ClientServices\APPS\Printtrack\HeliosPNetExecuter\HeliosPNetExecuter.exe "
                                                       psinfo.StartInfo.Arguments = Arg2 + Arg3 + Arg4 + (Chr(34) + DATA_PATH + "\" + SequentialFiles2 + Chr(34) + " ") + Arg6 + Arg7 + Arg8 + Arg9c + Arg10 + Arg11 + Arg12
                                                       psinfo.StartInfo.WindowStyle = ProcessWindowStyle.Normal
                                                       psinfo.Start()
                                                       psinfo.WaitForExit()
                                                   End Using

                                               End Sub)

        Next

A: Depends how is PDF processor work. You can avoid creting threads, but simply launch 10 processes, by feeding inside one file per process. No need of multi threading, at this stage at least.


text:
Q: Changing C++ Standard Output If I understand correctly, std::cout << "Test"; should output Test to the terminal emulator, but when I run a program using it, it instead creates a file called a.out. Is there a way to change this?

A: Try running the a.out file from inside a Terminal (if Linux/Mac) or cmd (if Windows) by running the following command:
./a.out
If it throws any permission exception in Linux/Mac then you should try running the following command first,
chmod +x ./a.out
and then run,
./a.out


text:
Q: How well do compilers (with link-time optimization) cope with functions that return quickly (early-out paths)? In C, if I have a function call that looks like
// main.c
...
do_work_on_object(object, arg1, arg2);
...

// object.c
void do_work_on_object(struct object_t *object, int arg1, int arg2)
{
  if(object == NULL)
  {
    return;
  }
  // do lots of work
}

then the compiler will generate a lot of stuff in main.o to save state, pass parameters (hopefully in registers in this case), and restore state.
However, at link time it can be observed that arg1 and arg2 are not used in the quick-return path, so the clean-up and state restoration can be short-circuited. Do linkers tend to do this kind of thing automatically, or would one need to turn on link-time optimization (LTO) to get that kind of thing to work?
(Yes, I could inspect the disassembled code, but I'm interested in the behaviours of compilers and linkers in general, and on multiple architectures, so hoping to learn from others' experience.)
Assuming that profiling shows this function call is worth optimizing, should we expect the following code to be noticeably faster (e.g. without the need to use LTO)?
// main.c
...
if(object != NULL)
{
  do_work_on_object(object, arg1, arg2);
}
...

// object.c
void do_work_on_object(struct object_t *object, int arg1, int arg2)
{
  assert(object != NULL) // generates no code in release build
  // do lots of work
}

A: Some compilers (like GCC and clang) are able to do "shrink-wrap" optimization to delay saving call-preserved regs until after a possible early-out, if they're able to spot the pattern.  But some don't, e.g. apparently MSVC 16.11 still doesn't.
I don't think any do partial inlining of just the early-out check into the caller, to avoid even the overhead of arg-passing and the call / ret itself.

Since compiler/linker support for this is not universal and not always successful even for shrink-wrapping, you can write your code in a way that gets much of the benefit, at the cost of splitting the logic of your function into two places.
If you have a fast-path that takes hardly any code, but happens often enough to matter, put that part in a header so it gets inlined, with a fallback to calling the rest of the function (which you make private, so it can assume that any checks in the inlined part are already done).
e.g. par2's routine that processes a block of data has a fast-path for when the galois16 factor is zero.  (dst[i] += 0 * src[i] is a no-op, even when * is a multiply in Galois16, and += is a GF16 add (i.e. a bitwise XOR)).
Note how the commit in question renames the old function to InternalProcess, and adds a new template<class g> inline bool ReedSolomon<g>::Process that checks for the fast-path, and otherwise calls InternalProcess.  (as well as making a bunch of unrelated whitespace changes, and some ifdefs... It was originally a 2006 CVS commit.)
The comment in the commit claims an overall 8% speed gain for repairing.

A: Neither the setup or cleanup state code can be short-circuited, because the resulted compiled code is static, and it doesn't know what will happen when the program get's executed. So the compiler will always have to setup the whole parameter stack.
Think of two situations: in one object is nil, in the other is not. How will the assembly code know if to put on the stack the rest of the argument? Especially as the caller is the one responsible of placing the arguments at their proper location (stack or registry).


text:
Q: Toggle the debug Firebase Analytics prop at runtime on Android Motivation: toggle the debug Firebase Analytics property at runtime
I'm looking for a way to switch the debug on and off through the code like it's done through adb shell here:
https://firebase.google.com/docs/analytics/debugview
Already tried the methods that were advised here:
https://stackoverflow.com/a/11623309/6301831
But got this message:
Unable to set property "debug.firebase.analytics.app" to "com.pantos27.Basefook": connection failed; errno=13 (Permission denied)

running as root is not an option btw


text:
Q: What '&' stands for in "std::vector& stream;" I know that
void foo(vector<int>& v) { ... }

is passing vector by reference, but
std::vector<byte>& stream;

what is that stream variable definition? Why '&' is there?

A: It's a reference to a std::vector<byte>. Because it is a reference, it allows you to change the original vector, as shown in this example:
#include <iostream>
#include <vector>

class Incrementer {
public:
    Incrementer(std::vector<int>& v) : vec(v) {}
    void increment() {
        for (auto& i : vec)
            ++i;
    }
private:
    std::vector<int>& vec;
};

int main() {
    std::vector<int> numbers { 1, 2, 3, 4 };
    Incrementer inc(numbers);
    for (auto i : numbers)
        std::cout << i << ' ';
    std::cout << '\n';

    inc.increment();

    for (auto i : numbers)
        std::cout << i << ' ';
    std::cout << '\n';
}

inc will hold a reference to numbers, so calling inc.increment() changes numbers:
1 2 3 4
2 3 4 5

A: As others said, both of these two are the references. However, the second one is not valid as there is no referenced variable!
It should be written in some way like this:
#include <vector>
#include <iostream>

int main()
{
    std::vector<int> stream1(5);
    stream1[0] = 10;
    std::vector<int>& stream2 = stream1; // stream2 and stream1 are two names for the same variable
    stream1[0] += 55;
    cout << "stream1: " << stream1[0] << endl;
    cout << "stream2: " << stream2[0];
    return 0;
}


text:
Q: Equation of state of Lennard-Jones spheres One way of accounting for van der Waals interactions in fluids is to use the Lennard-Jones potential [*], which has a repulsive term that dominates at short distances which mimics the hard-core repulsion of particles, and a short-range attraction term (due to van der Waals). LJ is usually written as:
$$
V_{LJ} = 4\epsilon \left[(\frac{\sigma}{r})^{12}-(\frac{\sigma}{r})^{6} \right] \tag{1}
$$
where $\sigma$ denotes the sphere diameter, $r$ is the distance between the spheres, and $\epsilon$ is the depth (minimum) of the attraction potential.
[*]: This effective potential is derived from the consideration of all 3 key dipolar interactions (between permanent (p) and induced (i) ones), namely: Keesom interaction (p-p), Debye (p-i), and London dispersion interaction (i-i).

Questions:

*

*In the context simple spherical fluids, where the only interaction between them is LJ, has the corresponding phase diagram been studied by theory and simulation previously? In contrast to the hard sphere system which is well studied. [1, 2]. In other words, are there known estimates for the equation of state of such systems? Alternatively,  has the phae diagram been studied for instance using Monte Carlo simulations?

*More generally, be it for hard spheres (pure steric repulsion and no attraction) or LJ spheres, what order parameters are usually of interest for tracking the phase transitions that such systems undergo (e.g., liquid-solid)?

A: There's a considerable amount of simulation data (both molecular dynamics and Monte Carlo) for the Lennard-Jones potential.
You should be aware that there are many different versions of the potential. In simulations it is truncated at a maximum "cutoff" distance; $r_\text{cut}=2.5\sigma$ is a common choice. It may or may not be shifted up by a constant amount, so as to make its value zero at the cutoff distance. Other choices apply a distance-dependent correction, so that the potential and its derivative(s) vanish at the cutoff. For any of these choices, it is possible to apply long-range corrections to simulation results, to get an estimate of the equation of state for the true infinite-range potential. Some features of the phase diagram are very sensitive to these choices. For example, the liquid-vapour coexistence curve is noticeably different: the critical temperature is at $k_BT_c/\epsilon\approx 1.32$ for the full potential, but $k_BT_c/\epsilon\approx 1.086$ for the cutoff and shifted potential with $r_\text{cut}=2.5\sigma$.
A fitted equation of state for $r_\text{cut}=2.5\sigma$, based on a wide range of simulation data, has been presented by Thol, Rutkai, Span, et al. Int J Thermophys, 36, 25 (2015), and for the full potential by Thol, Rutkai, Köster, et al. J Phys Chem Ref Data, 45, 023101 (2016). In each case, those authors have thoughtfully provided a computer program which you can download, to generate thermodynamic values for any given density and temperature in the fluid region.
When it comes to theoretical studies of thermodynamic properties and the phase diagram, there is also a considerable body of work. One approach is to predict the structure by mapping the repulsive part of the Lennard-Jones potential onto an effective hard sphere model (referring back to the theories that you mention in your question), and then treat the attractive part of the potential as a perturbation, to predict thermodynamic properties. This is sometimes called the Weeks-Chandler-Andersen approach, after the authors of the original paper. But really, a comprehensive answer cannot be given here: you need to read a book such as Theory of Simple Liquids by J-P Hansen and I R McDonald (4th edition). This covers many different theoretical approaches.
You also asked about order parameters. For the liquid-vapour transition, the density is the important one. For the liquid-solid transition, one can define parameters based on peaks at particular wave-vectors in the solid-state structure factor (which will be large in the solid, and small in the liquid) or bond-order parameters, termed Steinhardt parameters, characterizing the distribution of nearest-neighbour directions in the crystal. Some more details may be found in this online tutorial.


text:
Q: Nested function working but returning messages in Django I have a function called inside another one.
The functions are working properly but, while using a validator to raise some error in case of wrong entries by the users, the validator works but is calling either the success and the error message.
I post some code for better explanation.
utils.py
def add_flight_function(request):
    try:
        aircraft_maintenance_type = AircraftMaintenanceType.objects.first()
    except:
        aircraft_maintenance_type = None
    aircraft = request.POST.get('aircraft')
    adep = request.POST.get('adep')
    ades = request.POST.get('ades')
    date = request.POST.get('date')
    atd = request.POST.get('atd')
    ata = request.POST.get('ata')
    function_type_obj = request.POST.get('function_type')
    function_type_obj = FunctionType.objects.get(id=function_type_obj)
    operational_condition = request.POST.get('operational_condition')
    student = request.POST.get('student')
    instructor = request.POST.get('instructor')
    night = request.POST.get('night')
    note = request.POST.get('note')
    aircraft_type = Aircraft.objects.get(
        id=aircraft).aircraft_type.abbreviation
    if aircraft_maintenance_type.is_tacho == True:
        atd_tacho = request.POST.get('atd_tacho')
        ata_tacho = request.POST.get('ata_tacho')
        if float(ata_tacho) <= float(atd_tacho):
            messages.error(
                request, "ATA Tacho cannot be lower than ATD Tacho")
            return HttpResponseRedirect(request.META.get('HTTP_REFERER'))
        is_valid_flight, error_message = flight_validator(
            request, ata, atd, function_type_obj.name, instructor)
        if not is_valid_flight:
            messages.error(request, error_message)
            return HttpResponseRedirect(request.META.get('HTTP_REFERER'))
    else:
        is_valid_flight, error_message = flight_validator(
            request, ata, atd, function_type_obj.name, instructor)
        if not is_valid_flight:
            messages.error(request, error_message)
            return HttpResponseRedirect(request.META.get('HTTP_REFERER'))
    log_entry = LogEntry.objects.create(aircraft_id=aircraft, adep_id=adep, ades_id=ades, date=date, atd=atd,
                                        ata=ata, function_type_id=function_type_obj.id, student_id=student, instructor_id=instructor, operational_condition_id=operational_condition, note=note)
    if night == 'on':
        log_entry.night_flight = True
    # if function_type_obj.name == 'Dual Command':
    #     instructor_flight_payment = InstructorFlightPayment(log_entry=log_entry, instructor_id=instructor)
    #     instructor_flight_payment.save()
    if function_type_obj.name == 'Single Pilot':
        log_entry.solo_flight = True

    if aircraft_type == 'SIM':
        log_entry.sim_flight = True

    elif aircraft_type == 'MEP':
        log_entry.mep_flight = True
    log_entry.save()
    # This Part is for maintenance without Tachometer
    if aircraft_maintenance_type is None or aircraft_maintenance_type.is_tacho == False:
        ata_obj = parse(ata)
        atd_obj = parse(atd)
        if (ata_obj - atd_obj) > 10:
            maintenance_eet = timedelta(
                minutes=(ata_obj-atd_obj)) - timedelta(minutes=10)
        else:
            maintenance_eet = timedelta(minutes=(ata_obj-atd_obj))
        aircraft_flight_time = AircraftFlightTime(
            aircraft_id=aircraft, log_entry=log_entry, maintenance_eet=maintenance_eet)
        aircraft_flight_time.save()
    # This Part is for maintenance With Tachometer
    else:
        ata_obj = float(ata_tacho)
        atd_obj = float(atd_tacho)
        maint_eet_obj = (ata_obj - atd_obj) * 60

        maintenance_eet = timedelta(minutes=maint_eet_obj)

        aircraft_flight_time = AircraftFlightTime(
            aircraft_id=aircraft, log_entry=log_entry, maintenance_eet=maintenance_eet, atd_tacho=atd_tacho, ata_tacho=ata_tacho)
        aircraft_flight_time.save()

flight_validator:
def flight_validator(request, ata, etd, function_type, instructor):
    if ata <= etd:
        return False, "ATA cannot be greater or equal to ETD!"
    elif function_type == 'Dual Command' and not instructor:
        return False, "Instructor must be on Board!"
    return True, ""
    enter code here

views.py
def add_new_flight(request):
    aircrafts = Aircraft.objects.all()
    aerodromes = Aerodrome.objects.filter(is_base=False)
    base_aerodrome = Aerodrome.objects.get(is_base=True)
    function_type = FunctionType.objects.all()
    students = Student.objects.filter(is_active=True).order_by('last_name')
    instructors = Instructor.objects.filter(
        is_active=True).order_by('last_name')
    operational_conditions = OperationalCondition.objects.all()
    today = dt.today().date()
    try:
        aircraft_maintenance_type = AircraftMaintenanceType.objects.first()
    except:
        aircraft_maintenance_type = None
    context = {
        'aircrafts': aircrafts,
        'aerodromes': aerodromes,
        'function_type': function_type,
        'students': students,
        'instructors': instructors,
        'today': today,
        'operational_conditions': operational_conditions,
        'base_aerodrome': base_aerodrome,
        'aircraft_maintenance_type': aircraft_maintenance_type,
    }
    if request.method == 'POST':
        try:
            add_flight_function(request)
            messages.success(request, "New Flight Inserted Successfully")
            return HttpResponseRedirect(reverse('flight:flight_list'))
        except:
            messages.error(request, "Failed to Add New Flight")
            return HttpResponseRedirect(reverse('flight:add_new_flight'))
    return render(request, 'flight/add_new_flight.html', context)

If I make some input error, the validators are working properly but, for example, are showing both the error and success message. But, in fact, the success message shouldn't be there and actually the function doesn't work and doesn't save anything.

A: I think that in your function add_flight_function you want to raise some kind of error so the code flow goes to the except block. Right now, you are returning a response instance which is not being used in your view and the code simply goes on to the next lines which add the success message and return a redirect (the try block).
So the fix would be to do this everywhere where you return HttpResponseRedirect in add_flight_function:
messages.error(request, error_message)
raise ValidationError(error_message)
# return HttpResponseRedirect(request.META.get('HTTP_REFERER'))

Side note: it would be better if you used Django forms for all of this.


text:
Q: how to use AJAX in JSF 2.0 to get the word the mouse is over? is there a way to get the word the mouse is over on by using AJAX on JSF 2.0 (which even works on outputText component)?
My goal is to store that word on a bean variable (let's say #{bean.selectedWord}) to use for further operations.
Up to now I'm only able to get the entire value of the  inputText element... I was wondering if I had to use jQuery too.
page.xhtml
     <h:inputText id = "myIinput" value="this is a test">
        <f:ajax event="mouseover" render="myOutput" execute="myInput"
                listener="#{bean.ajaxFunction}"/>
     </h:inputText>
     <h:outputText id ="myOutput" value="#{bean.selectedWord}" />

bean.java
String selectedWord;

  public void ajaxFunction(AjaxBehaviorEvent event) {
    UIComponent uic = event.getComponent();
    String output = (String) uic.getAttributes().get("value");
    myOutput = output ;
  }

  public String getSelectedWord(){
    return selectedWord
  }

A: Plain JSF nor any of the component suites I know of has a component for this. So effectively you need to break down your problem in two:

*

*client side in javascript (with or without the help of a js framework like jquery) find the word a client hovers over. This is adressed in e.g.

*

*How to get a word under cursor using JavaScript?

*Get hovered word from hover() in Jquery?

*send a javascript value to the server via some ajax call, which is addressed in

*

*How to invoke a JSF managed bean on a HTML DOM event using native JavaScript?
Combine the two and you have your solution. But don't forget to add a delay  in the hover so not every qucik hover isemd, just when the user pauses.


text:
Q: Got internal error 500 when sending email with Laravel 6 in production I've never configured a Laravel mail settings before. On development, you know, it works but on production, I'm getting internal error 500.
In my mail controller, this is giving the error:
[..]

Mail::to($toEmail)->send(new Support($support));

I've looked in storage/logs/ and no logs are there. I now assume I'm missing a php module? My .env: MAIL_DRIVER=smtp
Im using Ubuntu 18 with php 7.2 and nginx.
Also, why am I not seeing the log files?
Thanks


text:
Q: Kafka NodePort service is unreachable outside of cluster I have been trying to deploy Kafka using Helm charts. So I defined NodePort service for Kafka pods. I checked console Kafka producer and consumer with the same hosts and ports - they work properly. However, when I create Spark application as data consumer and Kafka as producer they are not able to connect to the Kafka service0. I used minikube ip (instead of node ip) for the host and service NodePort port.
Although, in Spark logs, I saw that NodePort service resolves endpoints and brokers are discovered as pods addressed and ports:
INFO AbstractCoordinator: [Consumer clientId=consumer-1, groupId=avro_data] Discovered group coordinator 172.17.0.20:9092 (id: 2147483645 rack: null)
INFO ConsumerCoordinator: [Consumer clientId=consumer-1, groupId=avro_data] Revoking previously assigned partitions []
INFO AbstractCoordinator: [Consumer clientId=consumer-1, groupId=avro_data] (Re-)joining group
WARN NetworkClient: [Consumer clientId=consumer-1, groupId=avro_data] Connection to node 2147483645 (/172.17.0.20:9092) could not be established. Broker may not be available.
INFO AbstractCoordinator: [Consumer clientId=consumer-1, groupId=avro_data] Group coordinator 172.17.0.20:9092 (id: 2147483645 rack: null) is unavailable or invalid, will attempt rediscovery
WARN NetworkClient: [Consumer clientId=consumer-1, groupId=avro_data] Connection to node 2 (/172.17.0.20:9092) could not be established. Broker may not be available.
WARN NetworkClient: [Consumer clientId=consumer-1, groupId=avro_data] Connection to node 0 (/172.17.0.12:9092) could not be established. Broker may not be available.

How this behavior can be changed?
NodePort service definition looks like this:
kind: Service
apiVersion: v1
metadata:
  name: kafka-service
spec:
  selector:
    app: cp-kafka
    release: my-confluent-oss
  ports:
    - protocol: TCP
      targetPort: 9092
      port: 32400
      nodePort: 32400
  type: NodePort

Spark consumer configuration:
def kafkaParams() = Map[String, Object](
  "bootstrap.servers" -> "192.168.99.100:32400",
  "schema.registry.url" -> "http://192.168.99.100:8081",
  "key.deserializer" -> classOf[StringDeserializer],
  "value.deserializer" -> classOf[KafkaAvroDeserializer],
  "group.id" -> "avro_data",
  "auto.offset.reset" -> "earliest",
  "enable.auto.commit" -> (false: java.lang.Boolean)
)

Kafka producer configuration:
  props.put("bootstrap.servers", "192.168.99.100:32400")
  props.put("client.id", "avro_data")
  props.put("key.serializer", "org.apache.kafka.common.serialization.StringSerializer")
  props.put("value.serializer", "io.confluent.kafka.serializers.KafkaAvroSerializer")
  props.put("schema.registry.url", "http://192.168.99.100:32500")

All the K8s services for Kafka:
NAME                                     TYPE           CLUSTER-IP       EXTERNAL-IP   PORT(S)             AGE
kafka-service                            NodePort       10.99.113.234    <none>        32400:32400/TCP     6m34s
kubernetes                               ClusterIP      10.96.0.1        <none>        443/TCP             27d
my-confluent-oss-cp-kafka                ClusterIP      10.100.156.108   <none>        9092/TCP            102m
my-confluent-oss-cp-kafka-connect        ClusterIP      10.99.78.89      <none>        8083/TCP            102m
my-confluent-oss-cp-kafka-headless       ClusterIP      None             <none>        9092/TCP            102m
my-confluent-oss-cp-kafka-rest           ClusterIP      10.100.152.109   <none>        8082/TCP            102m
my-confluent-oss-cp-ksql-server          ClusterIP      10.96.249.202    <none>        8088/TCP            102m
my-confluent-oss-cp-schema-registry      ClusterIP      10.109.27.45     <none>        8081/TCP            102m
my-confluent-oss-cp-zookeeper            ClusterIP      10.102.182.90    <none>        2181/TCP            102m
my-confluent-oss-cp-zookeeper-headless   ClusterIP      None             <none>        2888/TCP,3888/TCP   102m
schema-registry-service                  NodePort       10.103.100.64    <none>        32500:32500/TCP     33m
zookeeper-np                             NodePort       10.98.180.130    <none>        32181:32181/TCP     53m

A: I had a similar issue when I was trying to access kafka broker (cp-helm-chart) running on minikube from outside.
Here how I resolved it. Before you install using helm install from local repository.

*

*Edit inside this file https://github.com/confluentinc/cp-helm-charts/blob/master/charts/cp-kafka/values.yaml

*Search for nodeport: and change its enabled field to true.

nodeport:
enabled: true

*Uncomment these two lines by removing #:
"advertised.listeners": |-
EXTERNAL://${HOST_IP}:$((31090 + ${KAFKA_BROKER_ID}))

*Replace ${HOST_IP} by your minikube ip (enter minikube ip in cmd to retrieve your k8s host ip e.g : 196.169.99.100)

*Replace ${KAFKA_BROKER_ID} by the broker id (if only one broker is running than its will be by default just 0)

*Finally it would look something like this:
"advertised.listeners": |-
EXTERNAL://196.169.99.100:31090

Now you can access the kafka broker running within k8s cluster from outside by pointing the bootstrap.servers to 196.169.99.100:31090


text:
Q: RSolve returns a wrong result, why? I'm trying to solve the following recurrence relation: $ \begin{cases} u_{0} = a \\ u_{n + 1} = - \sum_{i = 0}^{n} u_{i} u_{n - i} \end{cases} $
Here is my Mathematica code:
InitialCondition = u[0] == a;
RecurenceRelation = u[n + 1] == - Sum[u[i] * u[n - i], {i, 0, n}];
RSolveValue[{InitialCondition, RecurenceRelation}, u[n], n ] /. n -> 0

I'm not quite sure why I get $-a$ as a result. I expected $+a$, since that's my initial condition.
I'm new to Mathematica, so it's probably obvious, but I would really appreciate the help.
Thank you!

A: A workaround,
Clear["Global`*"]

u[0] = a;
u[n_] := u[n] = -Sum[u[i]*u[n - i - 1], {i, 0, n - 1}];

seq = {#, u[#]} & /@ Range[0, 6]

(* {{0, a}, {1, -a^2}, {2, 2 a^3}, {3, -5 a^4}, {4, 14 a^5}, {5, -42 a^6},
  {6, 132 a^7}}

Using FindSequenceFunction to generalize,
sol = FindSequenceFunction[seq, n] // FunctionExpand // Simplify

(* (4^n (-a)^n a Gamma[1/2 + n])/(Sqrt[π] Gamma[2 + n]) *)

Checking for larger values,
Table[sol, {n, 0, 50}] === Table[u[n], {n, 0, 50}]

(* True *)


text:
Q: Translate postgis data to a coordinate system I have a PostGIS database where the data is in an unknown or incorrect coordinate system.  Is there a way given some known points in the data to translate all the data to a specific coordinate system.

A: I wrote a short blog post and some java code to solve this problem last week (and the pom to build it).

A: If it is just in an unknown co-ordinate system, but you know the EPSG code that is should be. You can run:
ST_SetSRID(geom,EPSG_code)

For example I have a table called lines, which has a geometry column called geom, which I want to set to EPSG:4326:
ALTER TABLE lines
ALTER geom TYPE geometry(LineString, 4326) USING ST_SetSRID(geom, 4326)


text:
Q: owncloud 7 set expiration feature We upgraded from owncloud 5.0.10 to owncloud 7.0.4, we found that the set expiration date for shared folder's is not supported anymore from owncloud.
Is there any other way to do this feature?


text:
Q: Can CodeIgniter route to different controllers based on port number? I would like to have CodeIgniter route to a different controller based on port number like so:
host_name/ControllerName      => foo()
host_name:3000/ControllerName => bar()

I've added port 3000 to Apache's httpd.conf, so the server listens to both, but how do you tell CodeIgniter to route to a different method based on the port number? I was thinking that something like
$route[":3000/test/index"] = "ControllerName/bar"

would work, but no.
I've searched StackOverflow as well as the official documentation, but no luck.
Anyone have an idea, or is port-based routing just not supported by the framework?

A: use $_SERVER['SERVER_PORT'] to get port number and then write conditional routing in route.php


text:
Q: Adding custom html and standard widgets to sidebar I want to add both custom html that advanced text widgets can't support and the standard sidebar widgets in the same sidebar. However, when I put a sidebar widget into the theme, it removes all the custom html and just displays the widgets in the sidebar. It shouldn't be a tough fix, but I am pretty big php noob who learned wordpress by trial and error. I have attached the code from my sidebar:

Title goes here

Content goes here

Title goes here

Content goes here

Thanks for any help

A: I suppose you are doing something like this:
<?php if ( ! dynamic_sidebar( 'widget-area' ) ) : ?>
    Your sidebar code goes here.
<?php endif; ?>

If yes, do this instead:
Your sidebar code goes here.
<?php dynamic_sidebar( 'widget-area' ); ?>

A: You could also use a plugin - like http://www.mlynn.org/graceful-sidebar-plugin that I just wrote and plublished.  The Graceful Sidebar Plugin creates a widget that enables you to use custom fields in a post or page that display in the sidebar.  You can use it to display custom html or a simple message.  The custom fields it uses are graceful_title and graceful_content.

A: That should do it:

<?php _e('Your headline for the sidebar', TEXTDOMAIN); ?>

        <?php some_function(); ?>

    <?php if ( !function_exists('dynamic_sidebar') || !dynamic_sidebar() && !is_active_sidebar( 'widgets-sidebar-right-default' ) ) :

        the_widget(
            'WP_Widget_Text'
            ,array(
                'title'     => 'Textwidget'
                ,'text'     => '

                        Lorem ipsum dolor sit amet, consectetur adipiscing elit.
                        Aenean et quam a ante sodales feugiat. Aliquam et vulputate turpis.
                        Mauris quis sodales neque. Sed vestibulum faucibus eros nec tincidunt.
                        Integer tortor magna, suscipit vitae ultricies vel, vehicula sit amet sapien.

                '
                ,'filter'   => ''
            )
            ,array(
                'before_widget' => '
'
                ,'after_widget' => '
'
                ,'before_title' => '
'
                ,'after_title'  => '
'
            )
        );

    elseif ( is_active_sidebar( 'widgets-sidebar-right-default' ) ) :
        dynamic_sidebar( 'widgets-sidebar-right-default' );
    endif;
?>


text:
Q: Latex escaping in MatPlotlib There are a number of situations where it is useful to set matplotlib.rcParams['text.usetex'] = True. In this case, special LaTeX characters such as % have to be escaped in places like axis labels. Is there a function built in to matplotlib for escaping LaTeX symbols?
There is a hint of such a thing in the docs here and here, but no clear mention.
The specific problem I am trying to tackle is using a matplotlib.ticker.PercentFormatter, where a custom symbol (symbol=r'\%') must be used if rcParams['text.usetex'] is true. I am trying to add a PR that will escape the percent symbol in PercentFormatter if rcParams['text.usetex'] is enabled, but it does not make sense to only check for the percent symbol in that case, so I would like to escape the entire symbol string.


text:
Q: How to filter data using react? I have created search filter but I am not able to type anything in search input why so ? I have created searchTermChanged method but why is it not working ? When user types in input field the projects should get filtered based on title.
Code:
    import Projects from '../../data/projects';

export default class Home extends Component {

  constructor(props) {
    super(props);
    this.state = {
      search: '',
      projects: Projects
    }
  }

  searchTermChanged = (event) => {
    this.setState({ projects: this.state.projects.filter(val =>
      val.title.toLowerCase().indexOf(this.state.search.toLowerCase()) > -1 )
    })
  }

  render() {
    return (

                <input className="form-control" type="text" placeholder="Search projects" aria-label="Search"
                value={this.state.search}
                onChange={e => this.searchTermChanged(e.target.value)}
                />

              {this.state.projects.map((val,index) => (

                  <Card title={val.title} by={val.by} blurb={val.blurb}
                  url={val.url} funded={val.funded} backers={val.backers} imgurl={index}/>

              ))}

    )
  }
}

A: You need to make sure you're making correct use of the state.
import Projects from '../../data/projects';

export default class Home extends Component {

  constructor(props) {
    super(props);
    this.state = {
      search: '',
      projects: Projects
    }
  }

  searchTermChanged = (search) => {
    this.setState({
      //Update the search state here.
       search,
       //Use the current search state to filter
       projects: this.state.projects.filter(val =>
          val.title.toLowerCase().indexOf(search.toLowerCase()) > -1 )
       }
    );
  }

  render() {
    return (

                <input className="form-control" type="text" placeholder="Search projects" aria-label="Search"
                value={this.state.search}
                onChange={e => this.searchTermChanged(e.target.value)}
                />

              {this.state.projects.map((val,index) => (

                  <Card title={val.title} by={val.by} blurb={val.blurb}
                  url={val.url} funded={val.funded} backers={val.backers} imgurl={index}/>

              ))}

    )
  }
}

A: I think if you don't need to change the projects you can also do the bellow to simplify your logic:
constructor(props) {
    super(props);
    this.state = {
      search: ''
    }
  }

render() {
    let {search} from this.state;
    let myProjects = projects.filter((p) => {
      p.title.toLowerCase().indexOf(search.toLowerCase) > -1
    });

return (

            <input className="form-control" type="text" placeholder="Search projects" aria-label="Search"
            value={this.state.search}
            onChange={e => this.setState({search: e.target.value})}
            />

          {myProjects.map((val,index) => (

              <Card title={val.title} by={val.by} blurb={val.blurb}
              url={val.url} funded={val.funded} backers={val.backers} imgurl={index}/>

          ))}

)
}

A: You need to user Projects variable directly to filter otherwise filter changes will search on existing state. You need to set search value to refect what is your input
searchTermChanged = (event) => {
    console.log(event);
    this.setState({
      projects: Projects.filter(val =>
      val.title.toLowerCase().indexOf(event.toLowerCase()) > -1 ),
      search: event <-- here
    })
  }

stackblitz: https://stackblitz.com/edit/react-fyf7fr

A: You are not changing the state of "search".
Assuming u have an input like this:
<input type="text" id="whatever" className="whatever" onChange={(event) => props.searchTermChanged(e.target.value)} />

you can change your method searchTermChanged
searchTermChanged = (value) => {
this.setState({search: value});
    this.setState({ projects: this.state.projects.filter(val =>
      val.title.toLowerCase().indexOf(value.toLowerCase()) > -1 )
    });
  }

The reason why u use "value" instead of "this.state.search" here "indexOf(value.toLowerCase())" its because setState is asynchronous and you can reach that piece of code with state outdated. And you are sure that "value" has the right value.


text:
Q: How to convert SIGFPE into a C++-exception Under Win32 it's easy to convert a SEH-exception into a C++-exception with _set_se_translator. Is there a similar way to convert certain signals into C++-exceptions on Linux? I need a mapping of SIGFPE to a C++-exception.

A: With g++, you can use -fnon-call-exceptions option and just throw an exception from the FPE signal handler. Note not every signal can be mapped like that, only signals that arise from trapping instructions. Fortunately SIGFPE is such a signal.

A: You cannot do reliably that on POSIX systems such as Linux. See also this for more details. Notice that you can't use signalfd(2) in your case. I assume you are using Linux on x86-64 or some other commonly available architecture.
Read very carefully signal(7) (in particular what is said about async-signal-safe functions in signal handlers, and they are the only way to handle signals like SIGFLE). Read also what the C++11 standard or the C99 standard say about signal. Most C++ implementations might sometimes generate some implicit call to runtime support functions which are not async-signal-safe (in particular, those for throwing an exception. So you cannot reliably throw an exception from a signal handler).
In practice, the following would be a wrong signal handler:
/// WRONG CODE, against signal(7) since calling
/// non-async-signal-safe functions from the C++ runtime
void badSIGFPEhandler(int sig) {
  if (sig == SIGFPE)
    throw std::runtime_error("got SIGFPE");
}

You can check by compiling it with g++ -Wall -O -fverbose-asm -S (then looking into the emitted .s assembler file) that it is calling some non-async-signal-safe functions (from the C++ runtime) like __cxa_allocate_exception, __cxa_throw, _Unwind_Resume which is forbidden by signal(7)....
In practice, the only safe thing to do from a signal handler which does not abort or _exit is to set some volatile sigatomic_t flag, or use the few async-signal-safe functions, e.g. write(2) something on a pipe(7). Also, throwing an exception from a signal handler is not worse than calling printf from it (lots of people are wrongly doing it); it is forbidden, but it could often work. I still don't recommend doing that, in particular in programs which are running for a long time, or for which crashing -even infrequently- is not acceptable.
Read more about undefined behavior, notably Lattner's blog about What every C programmer should know about undefined behavior.
In practice, the only reliable and portable way to handle signals is to have a signal handler which just sets some volatile sigatomic_t flag. But if you do that for SIGFPE your implementation is very likely to restart the same computation in the same state, hence looping indefinitely on SIGFPE handling. See also this regarding -fnon-call-exceptions (so I believe that n.m.'s answer might not always be right and reliable; it is in fact undefined behavior which would often seem to work).
PS. Actually, I strongly suspect that Windows way of doing that conversion is not C++11 or C++14 standard (or C99 or C11 standard) conforming, and you could have a standard conforming implementation of C++ (or C99 or C11) on Windows which disallows doing what you suggest; and probably Clang or GCC are such implementations.


text:
Q: test angular if else block and subscribe(response => {} block in jasmine I am facing an issue in writing test case on component method.
How to test a Angular component method if else block inside subscribe((res) => { ///block} and ToasterService inside it.
I have called the Angular service method in my component.ts file.
within the service call subscribe(response=>{}.
I have validated the response value in if else block, and show toaster message according to result but my karma report says: response=> function not covered and inside if else block not statement not covered.
component.ts
constructor(private userService: UserService,
    private toastr: ToastrService) { }
sortUsers(sortKey: string) {
    this.userService.getSortUserList(sortKey).subscribe((res) => {
      if(res.Success){
        this.userService.users = res.Data as User[];
      }else{
        this.toastr.error(res.Message);
      }

    });
  }

component.spec.ts
it('call sortUser when users are sorted', () => {
    const users: User[] = [{
      User_Id: 1,
      First_Name: 'Madhu Ranjan',
      Last_Name: 'Vannia Rajan',
      Employee_Id: 12345,
      Project_Id: 1,
      Task_Id:1,
      _id: 'xcv'
    }];

    component.sortUsers('First_Name');
    const res = {Success: true, Data: users}
    spyOn(service, 'getSortUserList').and.returnValue(of({Success: true, Data: users}));
  });

expecting the below block also to be tested by jasmine:
subscribe((res) => {
      if(res.Success){
        this.userService.users = res.Data as User[];
      }else{
        this.toastr.error(res.Message);
      }

    });

karma report:
Karma report

A: Try
constructor(
    public userService: UserService,
    public toastr: ToastrService) {
}

and in spec file:
it('call sortUser when users are sorted with success', () => {
    const users: User[] = [{
      User_Id: 1,
      First_Name: 'Madhu Ranjan',
      Last_Name: 'Vannia Rajan',
      Employee_Id: 12345,
      Project_Id: 1,
      Task_Id:1,
      _id: 'xcv'
    }];
    const res = {Success: true, Data: users}
    spyOn(component.userService, 'getSortUserList').and.returnValue(of(res));
    spyOn(component.toastr,'error').and.callThrough();
    component.userService.users = undefined;
    component.sortUsers('First_Name');
    expect(component.userService.users).toBeDefined()
    expect(component.toastr.error).not.toHaveBeenCalled()
  });

it('call Error Toaster in sortUser() when users are sorted', () => {
    const res = {Message: 'error_msg'}
    spyOn(component.userService, 'getSortUserList').and.returnValue(of(res));
    spyOn(component.toastr,'error').and.callThrough();
    component.userService.users = undefined;
    component.sortUsers('First_Name');
    expect(component.userService.users).not.toBeDefined()
    expect(component.toastr.error).toHaveBeenCalledWith('error_msg')
  });

Since you are new to karama I would strongly suggest you to read this article which contains a collection of articles to handle Angular Unit testing at the bottom page.


text: Q: Collapse views like FAB with CollapsingToolbarLayout inside CoordinatorLayout What attribute should be added in order for a view to behave like FAB that shrinks upon scroll up and collapsing a Toolbar that is inside CoordinatorLayout? Can you shrink the ImageView here with just XML attributes?


text:
Q: bitmapfactory fails to load images I have a android app to load multiple images from mysql database onto a ImageButton.
imageButton.setImageBitmap(fetchBitmap("http://www...~.jpg"));

I was once able to load png successfully but it also fails now (No success with jpg images ever). Here is the code I use for downloading images:-
public static Bitmap fetchBitmap(String urlstr) {
    InputStream is= null;
    Bitmap bm= null;
    try{
        HttpGet httpRequest = new HttpGet(urlstr);
        HttpClient httpclient = new DefaultHttpClient();
        HttpResponse response = (HttpResponse) httpclient.execute(httpRequest);

        HttpEntity entity = response.getEntity();
        BufferedHttpEntity bufHttpEntity = new BufferedHttpEntity(entity);
        is = bufHttpEntity.getContent();
        BitmapFactory.Options factoryOptions = new BitmapFactory.Options();
        bm = BitmapFactory.decodeStream(is);
    }catch ( MalformedURLException e ){
        Log.d( "RemoteImageHandler", "Invalid URL: " + urlstr );
    }catch ( IOException e ){
        Log.d( "RemoteImageHandler", "IO exception: " + e );
    }finally{
        if(is!=null)try{
            is.close();
        }catch(IOException e){}
    }
    return bm;
}

I get this error:-
D/skia(4965): --- SkImageDecoder::Factory returned null

I have already tried various combinations as suggested here, here and several other solutions, but it doesnt work for me. Am I missing something? Image is definitely present in the web address I enter.
Thank you.

A: Use below code for download image and store into bitmap, it may help you.
public static Bitmap loadBitmap(String url) {
    Bitmap bitmap = null;
    InputStream in = null;
    BufferedOutputStream out = null;

    try {
        in = new BufferedInputStream(new URL(url).openStream(), IO_BUFFER_SIZE);

        final ByteArrayOutputStream dataStream = new ByteArrayOutputStream();
        out = new BufferedOutputStream(dataStream, IO_BUFFER_SIZE);
        out.flush();

        final byte[] data = dataStream.toByteArray();
        BitmapFactory.Options options = new BitmapFactory.Options();

        bitmap = BitmapFactory.decodeByteArray(data, 0, data.length,options);
    } catch (IOException e) {
        Log.e(TAG, "Could not load Bitmap from: " + url);
    } finally {
        closeStream(in);
        closeStream(out);
    }

    return bitmap;
}

A: The problem was that the images could not be downloaded because the directory in which the images were kept did not have "execute" permission. As soon as the permission was added, the app works smoothly :)


text:
Q: Neo4j Recommendation Cypher Query Optimization I am using Neo4j community edition embedded in java application for recommendation purpose. I made a custom function which contains a complex logic of comparing two entities, namely product and users. Both entities are present as nodes in graph and has more than 20 properties each for comparison purpose. For eg. I am calling this function in following format:
match (e:User {user_id:"some-id"}) with e
match (f:Product {product_id:"some-id"}) with e,f
return e,f,findComparisonValue(e,f) as pref_value;

This function call on an average takes about 4-5 ms to run. Now, to recommend best product to a particular user, I wrote a cypher query which iterates over all products, calculate the pref_value and rank them. My cypher query looks like this:
MATCH (source:User) WHERE id(source)={id} with source
MATCH (reco:Product) WHERE reco.is_active='t'
with reco, source, findComparisonValue(source, reco) as score_result
RETURN distinct reco, score_result.score as score, score_result.params as params, score_result.matched_keywords as matched_keywords
order by score desc

Some insights on graph structure:
Total Number of nodes: 2 million
Total Number of relationships: 20 million
Total Number of Users: 0.2 million
Total Number of Products: 1.8 million

The above cypher query is taking more than 10 seconds as it is iterating over all the products. On top of this cypher query, I am using graphaware-reco module for my recommendation needs (Using precompute, filteing, post processing etc). I thought of parallelising this but community edition does not support clustering. Now, as number of users in system is increasing day by day, I need to think of a scalable solution.
Can anyone help me out here, on how to optimize the query.

A: As others have commented, doing a significant calculation potentially millions of times in a single query is going to be slow, and does not take advantage of neo4j's strengths. You should investigate modifying your data model and calculation so that you can leverage relationships and/or indexes.
In the meantime, there are a number of things to suggest with your second query:

*

*Make sure you have created an index for :Product(is_active), so that it is not necessary to scan all products. (By the way, if that property is actually supposed to be a boolean, then consider making it a boolean rather than a string.)

*The RETURN clause should not need the DISTINCT operator, since all the result rows should be distinct anyway. This is because every reco value is already distinct. Removing that keyword should improve performance.


text:
Q: How to access a Thermocouple signal in PC? I'm looking for the way to access a thermocouple signal to use it in my own software.
I suppose that I have to place a data acquisition system (something like this https://www.dataq.com/data-acquisition/thermocouple/) between the thermocouple and the PC. The problem is to find a DAQ that shows the software calls to use it in my own code. I'm seeing that the main part of the DAQs have their own closed software and don't allow to see those calls.
Does anyone know a DAQ that allows this? Or another method to connect the thermocouple and use the signal?
Thanks in advance

A:
I suppose that I have to place a data acquisition system (something like this https://www.dataq.com/data-acquisition/thermocouple/) between the thermocouple and the PC. The problem is to find a DAQ that shows the software calls to use it in my own code. I'm seeing that the main part of the DAQs have their own closed software and don't allow to see those calls.

I have never seen a piece of PC DAQ hardware that did not provide APIs for software integration.  That is the whole point of DAQ hardware.

Does anyone know a DAQ that allows this? Or another method to connect the thermocouple and use the signal?

The company you linked above provides APIs for a number of programming languages for its DAQ hardware.

A: Lots of companies have these. For example, Advantech (Taiwan) has 10/100 Ethernet modules that are properly isolated.
Thermocouples and RTDs are relatively easy because there are usually no worries about synchronization and timing that you would have with higher bandwidth sensors.

A: I would just go with arduino (nano to make it small) connected to thermocouple. It will show up as a COM port on the PC, which you can easily access from PC. I did that kind of communication with Python and Java, shouldn't be too hard. If you need more precision, you can connect RS232 serial converter to STM32 blue pill to thermocouple. The final result will be the same - virtual COM port. It has prettier ADC, but needs 3.3V (serial converter can provide that). And you can also program it with Arduino IDE, there's plenty of examples on youtube.


text:
Q: Shuffling Text Animation with CSS/JS? I want to display the word 'Hello' on the home page of a website. I used CSS to make the 'Hello' transition up as the page loads in the beginning. I would like to implement a shuffling animation that randomly shuffles between the word Hello in different languages. I would like to do so with an animation where as the 'Hello' slides up at the beginning, the 'Hello' slides up more, fades out and disappears. As this occurs, a 'Bonjour' for example slides up from beneath and takes place. I picture this repeating forever.
Is there any way to implement such animation using CSS, JavaScript, Jquery, or any other web tools? Below is the HTML, CSS, and JS structure I have that only achieves the initial transition as the page loads:

Hello

section {
    text-align: left;
}
section h1 {
    font-size: 100px;
    font-weight: 420;
    position: absolute;
    top: 130px;
    left: 200px;

    opacity: 0;
    transform: translateY( 43px );
    animation-name: fade-in;
    animation-duration: 0.6s;
    animation-timing-function: ease-out;
    animation-fill-mode: forwards;
}

var currentIndex = 0;
var hello = new Array( 'Hello', 'Bonjour', 'Hola' );

function randomIndex( ) {
    return Math.floor( Math.random( ) * hello.length);
};

window.setInterval( function( ) {
    var newIndex = randomIndex( );
    while( newIndex === currentIndex ) newIndex = randomIndex();
    currentIndex = newIndex;
    document.getElementById("switch").textContent = hello[ currentIndex ];
}, 2300 );

A: In CSS you need to set up @keyframes for your fade-in animation,. Then you can add a percentage of the duration that you wish to animate the animate-able properties opacity and top position. Make sure your duration matches the setInterval time => 2300 => 2.3s.
@keyframes:
In my example I set up a tween that will start at 0% with opacity 0 and top position in vh lengths, then as the tween reaches 70%, it is shown moving upwards to 5vh, where it will stay at an opacity of 1 until 90%, when its opacity will start to fade out. At 100% it will be opacity of 0, then the loop starts over as it is set to infinte in the css animation, the element will reset to 20vh and the animation repeats itself over again.
*You can play around with the percentages in the @keyframes rule to get the effect you're look for in terms of fading in and out movement, etc...

let currentIndex = 0;
const hello = ['Hello', 'Bonjour', 'Hola'];

function randomIndex() {
  return ~~(Math.random() * hello.length);
};

window.setInterval(function() {
  let newIndex = randomIndex();
  while (newIndex === currentIndex) newIndex = randomIndex();
  currentIndex = newIndex;
  document.getElementById("switch").textContent = hello[currentIndex];
}, 2300);
* {
  margin: 0;
  padding: 0;
  box-sizing: border-box;
}

section {
  text-align: center;
}

section h1 {
  font-size: 100px;
  font-weight: 420;
  position: absolute;
  top: 5vh;
  left: 50vh;
  opacity: 0;
  animation: fade-in 2.3s ease-in-out forwards infinite;
}

@keyframes fade-in {
  0% {
    opacity: 0;
    top: 20vh;
  }
  70%,
  90% {
    opacity: 1;
    top: 5vh;
  }
  100% {
    opacity: 0;
    top: 5vh;
  }
}

Hello

A: As the greeting is not really semantic (you don't for example want it read out every few seconds to a screen reader) you could put it instead on the body (or another suitable element, depending on exactly the structure you want) in a pseudo before element. That way it is basically decoration, not meaning.
Also, to avoid timing issues, where a setInterval may get out of step with the timing of the keyframes animation, you can sense the animationend event and then set a timout for the next 300ms and then reset the animation to run again.

let currentIndex = 0;
const hello = ['Hello', 'Bonjour', 'Hola'];

function randomIndex() {
  return ~~(Math.random() * hello.length);
};

function getNext() {
  let newIndex = randomIndex();
  while (newIndex === currentIndex) newIndex = randomIndex();
  currentIndex = newIndex;
  document.body.style.setProperty('--greeting', "'" + hello[currentIndex] + "'");
  document.body.style.setProperty('--animationname', 'none');
  setTimeout(function () {
    document.body.style.setProperty('--animationname', 'move');
  }, 300);
}
document.body.addEventListener('animationend',getNext);
body {
  --greeting: 'Hello';
  --animationname: move;
}
body::before {
  content: var(--greeting);
  animation-duration: 2s;
  animation-iteration-count: 1;
  animation-name: var(--animationname);
  position: absolute;
  top: 100%;
  font-size: 100px;
  font-weight: 420;
  position: absolute;
  left: 200px;
  animation-timing-function: linear;
  animation-fill-mode: forwards;
}
@keyframes move {
  0% {
    top: 100%;
    opacity: 0;
  }
  50% {
    top: 50%;
    opacity: 1;
  }
  100% {
    top: 0%;
    opacity: 0;
  }
}

Obviously you'll want to change the timings, positionings etc to be exactly what you want.


text:
Q: How to call a CPU instruction from C#? My processor (Intel i7) supports the POPCNT instruction and I would like to call it from my C# application. Is this possible?
I believe I read somewhere that it isn't, but the JIT will invoke it if it finds it available but what function would I have to call that may be substituted with such an instruction?
Popcount is being called millions of times in a loop so I'd like to be able to have this CPU optimization if possible.

A: You want to play with fire, and here we like to play with fire...
class Program
{
    const uint PAGE_EXECUTE_READWRITE = 0x40;
    const uint MEM_COMMIT = 0x1000;

    [DllImport("kernel32.dll", SetLastError = true)]
    static extern IntPtr VirtualAlloc(IntPtr lpAddress, IntPtr dwSize, uint flAllocationType, uint flProtect);

    private delegate int IntReturner();

    static void Main(string[] args)
    {
        List<byte> bodyBuilder = new List<byte>();
        bodyBuilder.Add(0xb8); // MOV EAX,
        bodyBuilder.AddRange(BitConverter.GetBytes(42)); // 42
        bodyBuilder.Add(0xc3);  // RET
        byte[] body = bodyBuilder.ToArray();
        IntPtr buf = VirtualAlloc(IntPtr.Zero, (IntPtr)body.Length, MEM_COMMIT, PAGE_EXECUTE_READWRITE);
        Marshal.Copy(body, 0, buf, body.Length);

        IntReturner ptr = (IntReturner)Marshal.GetDelegateForFunctionPointer(buf, typeof(IntReturner));
        Console.WriteLine(ptr());
    }
}

(this small example of assembly will simply return 42... I think it's the perfect number for this answer :-) )
In the end the trick is that:
A) You must know the opcodes corresponding to the asm you want to write
B) You use VirtualAlloc to make a page of memory executable
C) In some way you copy your opcodes there
(the code was taken from http://www.cnblogs.com/netact/archive/2013/01/10/2855448.html)
Ok... the other one was as written on the site (minus an error on the uint -> IntPtr dwSize), this one is how it should be written (or at least it's a +1 compared to the original... I would encapsulate everything in a IDisposable class instead of using try... finally)
class Program
{
    const uint PAGE_READWRITE = 0x04;
    const uint PAGE_EXECUTE = 0x10;
    const uint MEM_COMMIT = 0x1000;
    const uint MEM_RELEASE = 0x8000;

    [DllImport("kernel32.dll", SetLastError = true)]
    static extern IntPtr VirtualAlloc(IntPtr lpAddress, IntPtr dwSize, uint flAllocationType, uint flProtect);

    [DllImport("kernel32.dll", SetLastError = true)]
    [return: MarshalAs(UnmanagedType.Bool)]
    static extern bool VirtualProtect(IntPtr lpAddress, IntPtr dwSize, uint flAllocationType, out uint lpflOldProtect);

    [DllImport("kernel32.dll", SetLastError = true)]
    [return: MarshalAs(UnmanagedType.Bool)]
    static extern bool VirtualFree(IntPtr lpAddress, IntPtr dwSize, uint dwFreeType);

    private delegate int IntReturner();

    static void Main(string[] args)
    {
        List<byte> bodyBuilder = new List<byte>();
        bodyBuilder.Add(0xb8); // MOV EAX,
        bodyBuilder.AddRange(BitConverter.GetBytes(42)); // 42
        bodyBuilder.Add(0xc3);  // RET

        byte[] body = bodyBuilder.ToArray();

        IntPtr buf = IntPtr.Zero;

        try
        {
            // We VirtualAlloc body.Length bytes, with R/W access
            // Note that from what I've read, MEM_RESERVE is useless
            // if the first parameter is IntPtr.Zero
            buf = VirtualAlloc(IntPtr.Zero, (IntPtr)body.Length, MEM_COMMIT, PAGE_READWRITE);

            if (buf == IntPtr.Zero)
            {
                throw new Win32Exception();
            }

            // Copy our instructions in the buf
            Marshal.Copy(body, 0, buf, body.Length);

            // Change the access of the allocated memory from R/W to Execute
            uint oldProtection;
            bool result = VirtualProtect(buf, (IntPtr)body.Length, PAGE_EXECUTE, out oldProtection);

            if (!result)
            {
                throw new Win32Exception();
            }

            // Create a delegate to the "function"
            // Sadly we can't use Funct<int>
            var fun = (IntReturner)Marshal.GetDelegateForFunctionPointer(buf, typeof(IntReturner));

            Console.WriteLine(fun());
        }
        finally
        {
            if (buf != IntPtr.Zero)
            {
                // Free the allocated memory
                bool result = VirtualFree(buf, IntPtr.Zero, MEM_RELEASE);

                if (!result)
                {
                    throw new Win32Exception();
                }
            }
        }
    }
}


text:
Q: Import DB from Google Spreadsheet I'm importing a cell text from a Google Spreadsheet and inserting into a post on WordPress using the follow code. But I have more than 300 values to get. So, I was wondering if that is any easier way to import it without coping the long sheet URL over the 300 times.
It also could be in php, so I would insert in my page.php file, but I have no idea how to do it.

jQuery.ajax("https://docs.google.com/spreadsheets/d/e/2PACX-1vQhp9yFq8eXagN03gn-mCN3_KPWRc2EIpswDFpHJLflFOG-XU2OMktqj03gxvUBZMAp8gYwWO5Q3MVJ/pub?gid=942917560&single=true&range=c3&output=csv").done(function(txt1){
               jQuery("#text1").html(txt1);
});

jQuery.ajax("https://docs.google.com/spreadsheets/d/e/2PACX-1vQhp9yFq8eXagN03gn-mCN3_KPWRc2EIpswDFpHJLflFOG-XU2OMktqj03gxvUBZMAp8gYwWO5Q3MVJ/pub?gid=942917560&single=true&range=c4&output=csv").done(function(txt2){
               jQuery("#text2").html(txt2);
});

jQuery.ajax("https://docs.google.com/spreadsheets/d/e/2PACX-1vQhp9yFq8eXagN03gn-mCN3_KPWRc2EIpswDFpHJLflFOG-XU2OMktqj03gxvUBZMAp8gYwWO5Q3MVJ/pub?gid=942917560&single=true&range=c5&output=csv").done(function(txt3){
               jQuery("#text3").html(txt3);
});

A: Well, first off, why are you making 300 calls to a spreadsheet?  Just do one call and get the cells you care about.  There is a parameter in the URL single, set it to false, and then pass in the range of cells you want.
But since I don't know what cells those are, I guess you could do:
function getCell(cell, id) {
    var url = "https://docs.google.com/spreadsheets/d/e/2PACX-1vQhp9yFq8eXagN03gn-mCN3_KPWRc2EIpswDFpHJLflFOG-XU2OMktqj03gxvUBZMAp8gYwWO5Q3MVJ/pub?gid=942917560&single=true&range="
               + cell + "&output=csv";
    jQuery.ajax(url).done(function(t){
           $(id).html(t);
    });
}

for (var i = 0; i < 300; i++) {
    var cell = 'c' + (i+3);      //first iteration: "c3"
    var dest = '#text' + (i+1);  //first iteration: "#text1"
    getCell(cell, dest);
}


text:
Q: Read Json file inside Angular custom library I am trying to build a custom library in angular 8. I am trying to read data from a JSON file inside the angular library working file but when I build the library and using in the project the JSON file path is not correct.

when I am using this library inside the project I am getting error like below
ERROR in ./node_modules/chatbot-lib/fesm2015/chatbot-lib.js
Module not found: Error: Can't resolve 'projects/chatbot-lib/src/assets/Loc.json' in 'D:\demo\DemoApplication\XmppConnection\node_modules\chatbot-lib\fesm2015'
Also, can someone help me in adding global SCSS in the angular library?

A: your project looks like a monorepo. if it is, try to specify external path alias to tsconfig in compilerOptions.paths
{
  compilerOptions: {
    ...
    paths: {
      "@chatbot": ["projects/chatbot-lib/index.ts"], // <RELATIVE_PATH>
      "@chatbot/assets": ["projects/chatbot-lib/src/assets/index.ts"]
    }
  }
}


text:
Q: What "neutral culture" breaks DateTime.TryParse()? I have the following code snippet
DateTime date1;
CultureInfo neutralCulture = new CultureInfo("fr");
bool isNeutral = neutralCulture.IsNeutralCulture; // True

DateTime.TryParse("not a date", neutralCulture, DateTimeStyles.AdjustToUniversal, out date1);

Which executes without throwing an exception, however, the documentation states

NotSupportedException: provider is a neutral culture and cannot be used in a parsing operation.

"fr" is a neutral culture, as demonstrated by the property on the CultureInfo object above, so I would expect this code to break.
What "neutral culture" breaks this method - is this documented anywhere?

A: I did a quick test of all the neutral cultures, and not even one threw an exception as shown below:
CultureInfo[] cultures = CultureInfo.GetCultures(CultureTypes.NeutralCultures);
foreach (var thisCulture in cultures)
{
    DateTime date1;
    CultureInfo neutralCulture = new CultureInfo(thisCulture.Name);
    bool isNeutral = neutralCulture.IsNeutralCulture; // True

    DateTime.TryParse("not a date", neutralCulture, DateTimeStyles.AdjustToUniversal, out date1);
}

I am not sure what to conclude from that. Could the documentation be wrong? Who knows.


text:
Q: Issue in using WSDL2OBJC tool for my WebService I am using the wsdl2objc Tool to generate the soap Searvice APIs for my webservice.
I am following this tutorial to generate code and use it
http://code.google.com/p/wsdl2objc/wiki/UsageInstructions
&&
http://brismith66.blogspot.com/2010/05/iphone-development-accesing-soap.html
I can generate My WebService APIS successfully, but when i added i am getting 8 Errors and errors are
Expected Identifier or '(' before '=' token
Please tell me what can i Do with it. I am stuffed. the WEBSERVICE URL given in the tutorial work perfectly fine when i compile but mine code giving these errors.
Can anybody Help!

A: First, don't use version 0.6, use version 0.7 instead. I encountered cache problem under version 0.6. The version 0.7 fixed this problem. So, my web service could use session mechanism to store state information.
Second, not any generated codes with wsdl2objc (or gSOAP) and WSDL will be compiled successfully. In practice, our team encountered some problems about compiling, so finally we implemented a proxy web service which provides an interface with simple class types (ex, int, string, byte) in order to avoid the compiling problems.


text:
Q: Managing a linux daemon with golang I need to manage the varnish service through an application in Golang, more specifically I need to have the application change the port, ip, storage method and etc.
At first I started by following the official varnish documentation (https://varnish-cache.org/docs/trunk/tutorial/putting_varnish_on_port_80.html), so I did with that the application created the following file in the path:
/etc/systemd/system/varnish.service.d/customexec.conf

[Service]
ExecStart=
ExecStart=/usr/sbin/varnishd -a :6081 -T
localhost:6082 -f /etc/varnish/default.vcl -S /etc/varnish/secret

There was no error, however, the service does not start
In the service status it displays the following message:
● varnish.service - Varnish HTTP accelerator    Loaded: loaded
(/lib/systemd/system/varnish.service; enabled; vendor preset: enabled)
Drop-In: /etc/systemd/system/varnish.service.d
           └─customexec.conf    Active: inactive (dead) since Dom 2018-01-28 15:10:46 -03; 3h 56min ago
     Docs: https://www.varnish-cache.org/docs/4.1/
           man:varnishd   Process: 970 ExecStart=/usr/sbin/varnishd -a :6081 -T localhost:6082 -f /etc/varnish/default.vcl -S
/etc/varnish/secret (code=exited, status=0/SUCCESS)  Main PID: 970
(code=exited, status=0/SUCCESS)

Is there another way to manage a service across an application?
Thank you all


text:
Q: Load wasm in VSCode Web Extension I'm trying to load a wasm module with a VSCode web extension.
I started from the "lsp-web-extension-sample".
Within the server directory, I created a simple rust lib with wasm-bindgen, it successfully compiles with wasm-pack. When I call the init function from the rust pkg output, it basically does this:
input = new URL("my-ext.wasm", import.meta.url)
fetch(input)

I get the following error: "TypeError: failed to fetch", without more explanations.
This error happens when testing with @vscode/test-web as well as when testing with the vsce package version.
Any idea what to do? Is there any example out there of a wasm web extension for vscode?

A: I was able to get the work done by loading wasm inline.
webpack.config.js
  module: {
    rules: [
      // ...,
      {
        test: /\.wasm$/,
        type: "asset/inline",
      },
    ],
  },

A: Accepted solution didn't work for me (WASM generated by wasm-pack), but this did:
https://github.com/SonOfLilit/vscode-web-wasm-rust
It involved writing a webpack WASM Loader plugin (and patching webpack to make that possible, PR submitted) to use this loader:
/******/    /* webpack/runtime/wasm loading */
/******/    (() => {
/******/        __webpack_require__.v = (exports, wasmModuleId, wasmModuleHash, importsObj) => {
/******/            var vscode = require('vscode');
/******/            var wasmPath = __webpack_require__.p + wasmModuleHash + '.module.wasm';
/******/            var req = vscode.workspace.fs.readFile(vscode.Uri.file(wasmPath));;
/******/            return req
/******/                .then((bytes) => (WebAssembly.instantiate(bytes, importsObj)))
/******/                .then((res) => (Object.assign(exports, res.instance.exports)));
/******/        };
/******/    })();

as well as setting __webpack_public_path__ in activate before trying to import the WASM:
export function activate(context: vscode.ExtensionContext) {
  __webpack_public_path__ =
    context.extensionUri.toString().replace("file:///", "") + "/dist/web/";

  let disposable = vscode.commands.registerCommand(
    "vscode-rust-web.helloWorld",
    () => {
      require("rust-wasm").then((rust: any) => {
        vscode.window.showInformationMessage(rust.greet());
      });
    }
  );

  context.subscriptions.push(disposable);
}

A: It took me quite a while to figure this out too (as you can see in my comments below). This is the code I ended up with in my activate method.
export function activate(context: vscode.ExtensionContext) {

    // These few lines took a looooooong while to figure out.
    // fetch is patched by VS Code, but WebAssembly.instantiateStreaming isn't, so call fetch
    // directly and pass the Response to the wasm-pack init function.
    //
    // Some of this approach copied from:
    //   https://github.com/microsoft/vscode-anycode/blob/anycode.v0.0.70/anycode/client/src/common/client.ts#L114

    let wasmUri = vscode.Uri.joinPath(context.extensionUri, "./dist/bqm_wasm_bg.wasm");
    // Will be something like "file:///Users/billti/src/bqm/dist/hello_wasm_bg.wasm" running in VSCode.
    // Something like "http://localhost:3000/static/devextensions/dist/hello_wasm_bg.wasm" with npx @vscode/test-web

    let fixedUri = 'importScripts' in globalThis ? wasmUri.toString() : wasmUri.fsPath;
    let ready = fetch(fixedUri).then(
        response => init(response)
    );


text:
Q: How many ways are there to arrange 4 letters from the word PROGRAM? The question doesn't mention unique words or repetition. How to know whether it is permutation or combination ?
Is it correct to say there are 7 letters in the word PROGRAM and R occurs 2 times,
hence from 6 different letters there are 6C4 x 4C4 ways of arranging 4 letters from the word PROGRAM ?

A: I'm assuming the question is how many $4$ letter words can be formed from the letters in the word PROGRAM. All such words can be categorized as either containing no R's, containing $1$ R or containing $2$ R's.
Containing no R's : In how many ways can you select $4$ letters from P, O, G, A, M and arrange $4$ different letters?
Containing $1$ R : In how many ways can you select $3$ letters from P, O, G, A, M and arrange $4$ different letters?
Containing $2$ R's : In how many ways can you select $2$ letters from P, O, G, A, M and arrange $4$ letters out of which $2$ are the same?


text:
Q: Java equivalent to C# $"{var}" formatting So I am learning a bit of Java and I'm just curios if there is an equivalent to the string format with the $ sign like in C#.
For example
string s = $"Date: {DateTime.Now}";
// s = Date: 5/27/2020 8:02:25 AM

Is this possible in Java?
I find it more convenient than doing it with indexes.

A: Java provides a type-safe way of concatenating Strings.
Here is a demonstration using jshell:
> jshell

jshell> import java.time.*;

jshell> String s = ("Date: " + LocalDateTime.now());
s ==> "Date: 2020-05-27T09:49:10.476140"

jshell>

Here is a working example program that uses Date formatting:
// File name: Demo.java

import java.text.Format;
import java.text.SimpleDateFormat;
import java.util.Date;

public class Demo {
   public static void main(String[] args) {
      Format f = new SimpleDateFormat("dd/mm/yyyy hh:mm:ss a");
      String s = ( "Date: " + f.format(new Date()) );
      System.out.println(s);
   }
}

Output:
> javac Demo.java

> java Demo
Date: 27/03/2020 10:03:02 am


text:
Q: Trouble with If/Else Statements to move through 2d array Working on a version of the knight's tour. The program is not acting the way I think it would given my code. I am getting several different strange discrepencies. The 'knight' is going out of bounds though I set up paramters for it not to. There are also more movements being made than there should be given my while loop. Mess with the i value, j value, and the number in the while loop and you will get several strange results. I have the value set to 32 for now just to see what will happen. Here is the code and the result:
#include <iostream>
int board[8][8];
void printBoard();
bool openSpace(int i,int j);
int startingPoint=0, m , n, i , j;
using namespace std;

int main()
{
        i=4;
        j=2;
        cout<<"Move: "<<startingPoint<<" Coordinates: "<<i<<","<<j<<endl;
        std::fill_n(&board[0][0], sizeof(board) / sizeof(**board), -1);//set all points to -1
        //Set the starting point to zero
        board[i][j] = startingPoint;//plot the starting point
        while(startingPoint<32)//for the first 32 points
        {
            if (i-2>0)
            {
                if(j+1<8)
                {
                    m=i-2;
                    n=j-2;
                    if (openSpace(m,n))
                    {
                        startingPoint++;
                        i=i-2;
                        j=j+1;
                        board[i][j]=startingPoint;
                        cout<<"Move: "<<startingPoint<<" Coordinates: "<<i<<","<<j<<endl;
                    }
                }
                if(j-1>0)
                    m=i-2;
                    n=j-1;
                    if (openSpace(m,n))
                    {
                        startingPoint++;
                        i=i-2;
                        j=j-1;
                        board[i][j]=startingPoint;
                        cout<<"Move: "<<startingPoint<<" Coordinates: "<<i<<","<<j<<endl;
                    }
            }
            if (i-1>0)
            {
                if(j+2<8)
                {
                    m=i-1;
                    n=j+2;
                    if (openSpace(m,n))
                    {
                        startingPoint++;
                        i=i-1;
                        j=j+2;
                        board[i][j]=startingPoint;
                        cout<<"Move: "<<startingPoint<<" Coordinates: "<<i<<","<<j<<endl;

                    }
                }
                if(j-2>0)
                    m=i-1;
                    n=j-2;
                    if (openSpace(m,n))
                    {
                        startingPoint++;
                        i=i-1;
                        j=j-2;
                        board[i][j]=startingPoint;
                        cout<<"Move: "<<startingPoint<<" Coordinates: "<<i<<","<<j<<endl;

                    }
            }
            if (i+1<8)
            {
                if(j+2<8)
                {
                    m=i+1;
                    n=j+2;
                    if (openSpace(m,n))
                    {
                        startingPoint++;
                        i=i+1;
                        j=j+2;
                        board[i][j]=startingPoint;
                        cout<<"Move: "<<startingPoint<<" Coordinates: "<<i<<","<<j<<endl;
                    }
                }
                if(j-2>0)
                    m=i+1;
                    n=j-2;
                    if (openSpace(m,n))
                    {
                        startingPoint++;
                        i=i+1;
                        j=j-2;
                        board[i][j]=startingPoint;
                        cout<<"Move: "<<startingPoint<<" Coordinates: "<<i<<","<<j<<endl;

                    }
            }
            if (i+2<8){
                if(j+1<8)
                {
                    m=i+2;
                    n=j+1;
                    if (openSpace(m,n))
                    {
                        startingPoint++;
                        i=i+2;
                        j=j+1;
                        board[i][j]=startingPoint;
                        cout<<"Move: "<<startingPoint<<" Coordinates: "<<i<<","<<j<<endl;
                    }
                }
                if(j-1>0)
                    m=i+2;
                    n=j-1;
                    if (openSpace(m,n))
                    {
                        startingPoint++;
                        i=i+2;
                        j=j-1;
                        board[i][j]=startingPoint;
                        cout<<"Move: "<<startingPoint<<" Coordinates: "<<i<<","<<j<<endl;
                    }
            }else{
            cout<<"I don't understand"<<endl;
            }
        }//end while
        printBoard();
}

void printBoard()
{
    //We need to loop through each row one by one
    for (int row=0; row<8; row++)
    {
    //now loop through each column in the row
        for(int column=0; column<8; column++)
        {
            cout<<board[row][column]<<" ";
        }
        cout<<endl;
    }
    cout<<endl;
}

//Check for open surrounding spaces
bool openSpace(int m,int n){
    if (board[m][n] == -1)
        return true;
    else
        return false;
}

Result:
Move: 0 Coordinates: 4,2
Move: 1 Coordinates: 2,3
Move: 2 Coordinates: 0,2
Move: 3 Coordinates: 1,4
Move: 4 Coordinates: 2,2
Move: 5 Coordinates: 4,3
Move: 6 Coordinates: 6,2
Move: 7 Coordinates: 4,3
Move: 8 Coordinates: 3,5
Move: 9 Coordinates: 4,7
Move: 10 Coordinates: 5,5
Move: 11 Coordinates: 7,6
Move: 12 Coordinates: 5,7
Move: 13 Coordinates: 3,6
Move: 14 Coordinates: 2,4
Move: 15 Coordinates: 3,2
Move: 16 Coordinates: 5,3
Move: 17 Coordinates: 7,2
Move: 18 Coordinates: 5,3
Move: 19 Coordinates: 4,5
Move: 20 Coordinates: 3,3
Move: 21 Coordinates: 4,1
Move: 22 Coordinates: 6,0
Move: 23 Coordinates: 4,-1
Move: 24 Coordinates: 3,1
Move: 25 Coordinates: 2,-1
Move: 26 Coordinates: 3,-3
Move: 27 Coordinates: 5,-2
Move: 28 Coordinates: 4,0
Move: 29 Coordinates: 5,2
Move: 30 Coordinates: 6,0
I don't understand
Move: 31 Coordinates: 7,-2
I don't understand
Move: 32 Coordinates: 5,-1
Move: 33 Coordinates: 6,1
I don't understand
-1 -1 2 -1 -1 -1 -1 -1
-1 -1 -1 -1 3 -1 -1 25
-1 -1 4 1 14 26 -1 -1
-1 24 15 20 -1 8 13 23
28 21 0 7 -1 19 27 32
-1 -1 29 18 -1 10 -1 12
30 33 6 -1 -1 -1 31 -1
-1 -1 17 -1 -1 -1 11 -1

Process returned 0 (0x0)   execution time : 0.172 s
Press any key to continue.

So yeah, why are there 34 moves, why are the going off the board?

A: I think there are few problems.
First you check the allowed moves one after other
while (starting point<32){
  if (not over right board){
  }
  if (not over left board){
  }
  ....
}

This means that multiple if statements can be true until the while loop is checked, hence you go over the limit of 32. You could use continue statement after each move which goes to the beginning of the loop and  does the check or you have to do the comparison after every move and then break from the loop.
Then you are missing brackets { in several places.
Then as pointed out by felix in the first if you should have n=j+1 not n=j-2.
You might want to consider slight rewriting of the code to be easier to read. E.g., you could make a function which tries to make the move and return true it is successful.
bool tryToMove(int stepI, int stepJ){
  int n = i+stepI;
  int m = j+stepJ;
  if (n>=0 && n<8 && m>=0 && m<8 && openSpace(n,m)){
    i = n;
    j = m;
    board[i][j] = startingPoint;
    return true;
  }
  return false;
}

and you can use it like
if (tryToMove(-2,1)){
  if (startingPoint == 32) break;
}
if (tryToMove(-2,-1)){
  if (startingPoint == 32) break;
}
...

or instead use continue, but that changes the order of move.
There will be few more comparisons than in your code, but it is much easier to see what is going on.


text:
Q: Making subversion "update if already checked out, check out otherwise" I want to write this script which goes into a directory that usually contains a checked-out subversion repository, and updates it; it should also checkout the repo if it's missing for some reason. Is there some special svn command to do this, or should I resort to checking whether .svn exists?

A:
checking whether .svn exists

Isn't bullet-proof method (in case of possible future changes)
Check output of svnversion or svn info in unversioned directory seems more promising


text:
Q: Android code to find when antenna is hot due to my or any other app I am new to android. I want to detect programmatically when mobile antenna is hot, meaning, I want to find when there is lot of n/w activity going on due to my or any other app, in general, in a programatic way as part of my business logic. Can some one share code snippet to figure this out. Thanks!

A: There is no tempature sensor on antenna, unless it is a custom device. Even if there is this information probably will not going to be available at application layer, because of security, even if it's available antenna would not get that hot from transferring data, even if it heats up, you wouldn't be able to detect it because big enviromental changes, it is not the same in equator and in Nordic countries.
To sum up, it is impossible to do that


text:
Q: How do I find the vector potential in this question (4)?
How do I find the vector potential in this question? What exactly is the 'region' being referred to?
I am using equation 334 in this. I am not able to get the bounds to integrate the formula with. Is z infinite? What would the radius vector be?


text:
Q: How to add scroll bar in CSS I would like to add scroll bar in this terminal like window in CSS if the text overflow. I tried overflow-y:scroll but it didn't work.
http://cssdeck.com/labs/pure-css-osx-terminal
Could anyone help me with this?

A: The scrollbar was hidden out of view. If you add
box-sizing:border-box;
overflow-y:scroll;

to the code for #body, it will work as planned.
http://cssdeck.com/labs/pbhmi7ux


text:
Q: How does Yubo previously known as Yello remember users after reinstall? Okay, I have asked Reddit 3x and Apple once and no one could answer this so I am coming to you guys. Please be the ones to answer this validly. Okay, details. Yubo remembers my phone after reinstall and I do not know how. I have tried the following:

*

*Changed my IP Address using a VPN

*Change my IDFA through reset identifier which I now know is pointless as since I had "limit ad tracking" on the output would have been an output value of numerous 0's (though this some how got me unbanned from the "Instagram" app, idk how tho)

*Changed my IDFV by...well reinstalling the app (Yubo is there only app so don't ask about other apps from the vendor)

*Change my iPhones name multiple times

*Prevented the app from being backed up on Icloud then reinstalling

*I also logged out of the Icloud prior to using the app for the first time after reinstall

And that's about it. I am aware the app may recognize: my phone, ios version and hardware. However, none of that is exclusive to my phone. I have read people having the exact same model and phone so i doubt Yubo is remembering me through that. I have never met an app so smart before, but I know some of you have probably been screaming this entire time one thing I have missed so please tell me what i missed and a way to change it without resetting my phone.
My device: Iphone6s and IOS 11


text:
Q: Why Chrome can not(or CAN) find context in a Arrow function of ES6 [UPDATE]: It turns out there are tow reason for my question:
For CAN NOT: It is my lack of knowledge about how arrow function works, it just locks the surrounding context everywhere it defined. And the global is undefined in strict mode.
For CAN: It could be a bug of old version Chrome Dev Tool.
Please refer to comment to find out what are the CAN and CAN NOT here

All:
I am pretty new to ES6, when I try arrow function's concept of lexical context locking, I use code like:
var glb = {name: "glb" };
glb.showname = () => {
    /******* interesting thing happens here below *******/
    console.log(this);
    this.name = "hello"
    return () => {
        console.log(this.name);
    }
}
const ext = {name: "ext"};
ext.showname = glb.showname();
ext.showname();

And I transpile it with:
browserify main.js  -o bundle.js -t [ babelify --presets [ es2015 ]   ] -d

Interesting thing is:
When I run it without setting breaking point(either with Node or in Chrome), it always give me error:

Uncaught TypeError: Cannot set property 'name' of undefined

and the console just prints out undefined
But when I set a break point(I do it in Chrome), this time, the context can be printed out like:
 Object {name: "glb"}

Any idea why this happens?
Thanks

A: If the Chrome dev tools are reporting this to be glb then there is a bug in the tools, which isn't too surprising given how new arrow functions are. this should be equal to undefined, as stated in your error.
Arrow functions bind to their lexical scope and only their lexical scope. Meaning, regardless of what object the function is attached to, it will always be called with the original lexical scope. This code shows a few examples of how arrow functions work.
var globalScope = () => {
  console.log(this); // undefined
};

function MyObj() { // Assuming we use it as a constructor
  console.log(this); // MyObj
  this.myObjScope = () => {
    console.log(this); // MyObj
  };
}

MyObj.prototype.globalScope = () => {
  console.log(this); // undefined
};

For a detailed rundown on arrow functions, see this Stack Overflow answer.


text:
Q: Angular JS http GET request with basic authentication I am new to angular JS. Here is the snippet of the code I have.
I am trying a GET request against a URL with basic authentication. This works fine with CURL or even in the browser. So, there is no problem with the URL that is being accessed.
I tried the following 2 ways to connect using the basic authentication. This does not return anything in the response. Any idea what is missing here?
var app = angular.module('myApp', ['base64']);
app.controller('customersCtrl', function($scope, $http) {
   var auth = $base64.encode("Username:Password");
   var headers = {"Authorization": "Basic " + auth};
   var url="<URL>";
   $http.get(url,{headers: headers}).then(function(response) {
             $scope.myData = resonpse.somthing;
          });
});

And:
var app = angular.module('myApp', ['base64']);
app.controller('customersCtrl', function($scope, $http) {

     $http({
         method : "GET",
         url : "<URL>"
         headers: {
                    'Authorization': 'Basic <encoded string>',
                    'Accept': 'application/json',
                                         }
         }).then(function mySuccess(response) {
                 $scope.myData = response.something;
     });
});