text:
Q: Monte Carlo integration of the Gaussian function f(x) = exp(-x^2/2) in C incorrect output I'm writing a short program to approximate the definite integral of the gaussian function f(x) = exp(-x^2/2), and my codes are as follows:
#include <stdio.h>
#include <stdlib.h>
#include <math.h>

double gaussian(double x) {
    return exp((-pow(x,2))/2);
}

int main(void) {
    srand(0);
    double valIntegral, yReal = 0, xRand, yRand, yBound;
    int xMin, xMax, numTrials, countY = 0;

    do {
        printf("Please enter the number of trials (n): ");
        scanf("%d", &numTrials);
        if (numTrials < 1) {
            printf("Exiting.\n");
            return 0;
        }
        printf("Enter the interval of integration (a b): ");
        scanf("%d %d", &xMin, &xMax);
        while (xMin > xMax) { //keeps looping until a valid interval is entered
            printf("Invalid interval!\n");
            printf("Enter the interval of integration (a b): ");
            scanf("%d %d", &xMin, &xMax);
        }
        //check real y upper bound
        if (gaussian((double)xMax) > gaussian((double)xMin))
            yBound = gaussian((double)xMax);
        else
            yBound = gaussian((double)xMin);
        for (int i = 0; i < numTrials; i++) {
            xRand = (rand()% ((xMax-xMin)*1000 + 1))/1000.00 + xMin; //generate random x value between xMin and xMax to 3 decimal places
            yRand = (rand()% (int)(yBound*1000 + 1))/1000.00; //generate random y value between 0 and yBound to 3 decimal places
            yReal = gaussian(xRand);
            if (yRand < yReal)
                countY++;
        }
        valIntegral = (xMax-xMin)*((double)countY/numTrials);
        printf("Integral of exp(-x^2/2) on [%.3lf, %.3lf] with n = %d trials is: %.3lf\n\n", (double)xMin, (double)xMax, numTrials, valIntegral);

        countY = 0; //reset countY to 0 for the next run
    } while (numTrials >= 1);

    return 0;
}

However, the outputs from my code doesn't match the solutions. I tried to debug and print out all xRand, yRand and yReal values for 100 trials (and checked yReal value with particular xRand values with Matlab, in case I had any typos), and those values didn't seem to be out of range in any way... I don't know where my mistake is.
The correct output for # of trials = 100 on [0, 1] is 0.810, and mine is 0.880; correct output for # of trials = 50 on [-1, 0] is 0.900, and mine was 0.940. Can anyone find where I did wrong? Thanks a lot.
Another question is, I can't find a reference to the use of following code:
double randomNumber = rand() / (double) RAND MAX;

but it was provided by the instructor and he said it would generate a random number from 0 to 1. Why did he use '/' instead of '%' after "rand()"?

A: There's a few logical errors / discussion points in your code, both mathematics and programming-wise.
First of all, just to get it out of the way, we're talking about the standard gaussian here, i.e.

except, the definition of the gaussian on line 6, omits the

normalising term. Given the outputs you seem to expect, this seems to have been done on purpose. Fair enough. But if you wanted to calculate the actual integral, such that a practically infinite range (e.g. [-1000, 1000]) would sum up to 1, then you would need that term.

Is my code logically correct?
No. Your code has two logical errors: one on line 29 (i.e. your if statement), and one on line 40 (i.e. the calculation of valIntegral), which is a direct consequence of the first logical error.
For the first error, consider the following plot to see why:

Your Monte Carlo process effectively considers a bounded box over a certain range, and then says "I will randomly place points inside this box, and then count the proportion of the total number of points that randomly fell under the curve; the integral estimate is then the area of the bounded box itself, times this proportion".
Now, if both

and

are to the left of the mean (i.e. 0), then your if statement correctly sets the box's upper bound (i.e. yBound) to

such that the topmost bound of the box contains the highest part of that curve. So, e.g., to estimate the integral for the range [-2,-1], you set the upper bound to

.
Similarly, if both

and

are to the right of the mean, then you correctly set yBound to

However, if

, you should be setting yBound to neither

nor

, since the 0 point is higher than both!. So in this case, your yBound should simply be at the peak of the Gaussian, i.e.

(which in your case of an unnormalised Gaussian, this takes a value of '1').
Therefore, the correct if statement is as follows:
if (xMax < 0.0)
  { yBound = gaussian((double)xMax); }
else if (xMin > 0.0)
  { yBound = gaussian((double)xMin); }
else
  { yBound = gaussian(0.0); }

As for the second logical error, we already mentioned that the value of the integral is the "area of the bounding box" times the "proportion of successes". However, you seem to ignore the height of the box in your calculation. It is true that in the special case where

, the height of your unnormalised Gaussian function defaults to '1', therefore this term can be omitted. I suspect that this is why it may have been missed. However, in the other two cases, the height of the bounding box is necessarily less than 1, and therefore needs to be included in the calculation. So the correct code for line 40 should be:
valIntegral = yBound * (xMax-xMin) * (((double)countY)/numTrials);

Why am I not getting the correct output?
Even despite the above logical errors, as we've discussed above, your output should have been correct for the specific intervals [0,1] and [-1,0] (since they include the mean and therefore the correct yBound of 1). So why are you still getting a 'wrong' output?
The answer is, you are not. Your output is "correct". Except, a Monte Carlo process involves randomness, and 100 trials is not a big enough number to lead to consistent results. If you run the same range for 100 trials again and again, you'll see you'll get very different results each time (though, overall, they'll be distributed around the right value). Run with 1000000 trials, and you'll see that the result becomes a lot more precise.

What's up with that randomNumber code?
The rand() function returns an integer in the range [0, RAND_MAX], where   RAND_MAX is system-specific (have a look at man 3 rand).
The modulo approach (i.e. %) works as follows: consider the range [-0.1, 0.3]. This range spans 0.4 units. 0.4 * 1000 + 1 = 401. For a random number from 0 to RAND_MAX, doing rand() modulo 401 will always result in a random number in the range [0,400]. If you then divide this back by 1000, you get a random number in the range [0, 0.4]. Add this to your xmin offset (here: -0.1) and you get a random number in the range [-0.1, 0.3].
In theory, this makes sense. However, unfortunately, as already pointed out in the other answer here, as a method it is susceptible to modulo bias, because RAND_MAX isn't necessarily exactly divisible by 401, therefore the top part of that range leading up to RAND_MAX overrepresents some numbers compared to others.
By contrast, the approach given to you by your teacher is simply saying: divide the result of the rand() function with RAND_MAX. This effectively normalises the returned random number into the range [0,1]. This is a much more straightforward thing to do, and it avoids modulo bias.
Therefore, the way I would implement this would be to make it into a function:
double randomNumber(void) {
  return rand() / (double) RAND_MAX;
}

which then simplifies your computations as follows too:
xRand = randomNumber() * (xMax-xMin) + xMin;
yRand = randomNumber() * yBound;

You can see that this is a much more accurate thing to do, if you use a normalised gaussian, i.e.
double gaussian(double x) {
  return exp((-pow(x,2.0))/2.0) / sqrt(2.0 * M_PI);
}

and then compare the two methods. You will see that the randomNumber() method for an "effectively infinite" range (e.g. [-1000,1000]) gives the correct result of 1, whereas the modulo approach tends to give numbers that are larger than 1.

A: Your code has no obvious bug (though there is a bug in the upper bound calculation, as @TasosPapastylianou points out, though it isn't the issue in your test cases). On 100 trials, your answer of 0.880 is closer to the actual value of the integral (0.855624...) than 0.810, and neither of those numbers are so far from the true value to suggest an outright bug in the code. Seems to be within sampling error (though see below). Here is a histogram of 1000 runs of a Monte Carlo integration (done in R, but with the same algorithm) of e^(-x^2/2) on [0,1] with 100 trials:

Unless your instructor specified the algorithm and the seed in precise detail, you shouldn't expect the exact same answer.
As far as your second question about rand() / (double) RAND MAX: it is an attempt to avoid modulo bias. It is possible that such a bias is effecting your code (especially given the way you round to 3 decimal places), since it does seem to overestimate the integral (based on running it a dozen times or so). Perhaps you could use that in your code and see if you get better results.


text:
Q: All possible paths in an undirected graph with some restrictions I should find all paths with a graph (24 nodes and 42 vertices). My starting nodes are 1, 2 or 3, and the final nodes are 10, 12, 13, 16, 17, 18, 20, 21, 22 and the rest are intermediate nodes. The sparse adjacency matrix of my graphs A is as follow.
I found the following Matlab code to find the all paths from a starting point to a target point, but the problem is that for example if the starting point is 1, we should not have node 2 in path. In the other words, only one starting point should appear in a path. Can anyone help me with this?
function paths = findpaths(Adj, nodes, currentPath, start, target)
     paths = {};
     nodes(start) = 0;
     currentPath = [currentPath start];
     childAdj = Adj(start,:) & nodes;
     childList = find(childAdj);
     childCount = numel(childList);
    if childCount == 0 || start == target
      if start == target
        paths = [paths; currentPath];
     end
    return;
   end
   for idx = 1:childCount
       currentNode = childList(idx);
       newNodes = nodes;
       newNodes(currentNode) = 0;
       newPaths = findpaths(Adj, newNodes, currentPath, currentNode, target);
       paths = [paths; newPaths];
   end
  end

Example graph:
  A =

  (4,1)         1
  (5,1)         1
  (9,1)         1
  (10,1)        1
  (12,1)        1
  (5,2)         1
  (7,2)         1
  (8,2)         1
  (8,3)         1
  (1,4)         1
  (5,4)         1
  (6,4)         1
  (9,4)         1
  (15,4)        1
  (1,5)         1
  (2,5)         1
  (4,5)         1
 (14,5)         1
 (17,5)         1
  (4,6)         1
 (16,6)         1
 (19,6)         1
 (20,6)         1
 (22,6)         1
  (2,7)         1
 (20,7)         1
 (23,7)         1
  (2,8)         1
  (3,8)         1
 (23,8)         1
  (1,9)         1
  (4,9)         1
 (13,9)         1
 (1,10)         1
(12,10)         1
(13,10)         1
(14,11)         1
(17,11)         1
 (1,12)         1
(10,12)         1
(16,12)         1
(18,12)         1
 (9,13)         1
(10,13)         1
(16,13)         1
(18,13)         1
 (5,14)         1
(11,14)         1
(17,14)         1
 (4,15)         1
 (6,16)         1
(12,16)         1
(13,16)         1
(18,16)         1
 (5,17)         1
(11,17)         1
(14,17)         1
(12,18)         1
(13,18)         1
(16,18)         1
(19,18)         1
(21,18)         1
(22,18)         1
 (6,19)         1
(18,19)         1
(21,19)         1
 (6,20)         1
 (7,20)         1
(18,21)         1
(19,21)         1
(24,21)         1
 (6,22)         1
 (19,22)        1
 (24,22)        1
  (7,23)        1
  (8,23)        1
 (19,24)        1
 (21,24)        1
 (22,24)        1

redpajama_set_name: RedPajamaStackExchange


text:
Q: Random SSH Agent Generates on Boot in tmp Directory Even with Networking Disabled On a recently installed Debian system I noticed that every boot, even with no networking, a folder and empty socket file are generated in /tmp/ssh-(random_letters)/agent.xxx.
On every boot the random letters assigned to the folder name and random numbers assigned to the socket file change.
On this system there is no VPN or tunneling setup, but netstat shows a process for /var/run/charon.ctl listening on a unix 2 STREAM.
It also shows ipsec-nat-t and isakmp listening over UDP for local address 0.0.0.0 and foreign address 0.0.0.0:*.
If I run netstat -ap | grep (number assigned to empty socket file) it produces a bunch of matches running on unix 2 and 3.
Examples:
@/tmp/.ICE-unix/(number assigned to socket) x8

/tmp/.ICE-unix/(number assigned to socket) x1

All of them are preceded by reference to:
(number assigned to socket)/x-session-manager.

And then there are another 5 listings same format but no path referenced. All connected, stream. And one more connected for dgram.
Is this normal?

A: All of those things look completely normal.
The SSH agent is started on login as part of your graphical desktop. Yes it doesn't care whether you have an Ethernet cable or not (nor should it). Yes it gets a random socket address every time.
The Charon socket will be listening whenever Charon (the strongSwan daemon) is running. Whether it has any connections set up or not is irrelevant – if the overall service was configured to start on boot, it'll start on boot, just like Apache will start even if you don't really have a website yet.
(If you're running Debian it indeed configures any newly installed service to start on boot, whether the admin wants it or not...)
The two UDP listeners are IKE (the IPsec handshake protocol), which is literally Charon's job. If it's running, it'll listen for IKE packets.
ICE-unix sockets are used by the X11 session manager (e.g. gnome-session), as the traditional X11 session management protocol is built on top of "Inter-Client Exchange" IPC system (not to be confused with the ICE from STUN/WebRTC which is a different thing).
The one with a @ prefix is an abstract socket, which doesn't correspond to anything in the filesystem; abstract socket names don't necessarily look like paths at all. X11 uses both regular and abstract sockets for... legacy reasons.
The nameless sockets are client sockets. The listener socket has a path – client sockets don't. But they'll show up in netstat because showing all sockets is what netstat does.


text:
Q: Unable to execute activity in android for weatherlib I have following code to use weatherlib to get weather condition in android using android studio.
My activity:
 import android.app.Activity;
  import android.content.Context;
  import android.os.Bundle;
  import android.view.Menu;
 import android.view.MenuItem;
 import android.widget.Toast;

import com.survivingwithandroid.weather.lib.WeatherClient;
import com.survivingwithandroid.weather.lib.WeatherClientDefault;
import com.survivingwithandroid.weather.lib.WeatherConfig;
import com.survivingwithandroid.weather.lib.exception.LocationProviderNotFoundException;
import com.survivingwithandroid.weather.lib.exception.WeatherLibException;
import com.survivingwithandroid.weather.lib.model.CurrentWeather;
import com.survivingwithandroid.weather.lib.provider.IWeatherProvider;
import com.survivingwithandroid.weather.lib.provider.WeatherProviderFactory;
import com.survivingwithandroid.weather.lib.provider.openweathermap.OpenweathermapProviderType;

import java.util.List;

 public class MainActivity extends Activity {

     private Context ctx;

      @Override
      protected void onCreate(Bundle savedInstanceState) {
       super.onCreate(savedInstanceState);
        setContentView(R.layout.activity_main);

       WeatherClient client = WeatherClientDefault.getInstance();
       client.init(ctx);

         WeatherConfig config = new WeatherConfig();
         config.unitSystem = WeatherConfig.UNIT_SYSTEM.M;
         config.lang = "en"; // If you want to use english
         config.maxResult = 5; // Max number of cities retrieved
         config.numDays = 6; // Max num of days in the forecast

        client.updateWeatherConfig(config);

        IWeatherProvider provider = null;
       try {
        //provider = WeatherProviderFactory.createProvider(new YahooProviderType(), config);
           provider = WeatherProviderFactory.createProvider(new OpenweathermapProviderType(), config);
        //provider = WeatherProviderFactory.createProvider(new WeatherUndergroundProviderType(), config);
           client.setProvider(provider);
    }
    catch (Throwable t) {
        // There's a problem
    }

       try {
            client.searchCityByLocation(WeatherClient.createDefaultCriteria(), new WeatherClient.CityEventListener() {

               @Override
               public void onCityListRetrieved(List<City> cityList) {
                // Here your logic when the data is available

            }

               @Override
                 public void onWeatherError(WeatherLibException wle) {

            }

                @Override
                   public void onConnectionError(Throwable t) {

            }
        });
       } catch (LocationProviderNotFoundException e) {
        e.printStackTrace();
       }

        client.getCurrentCondition("29222451", new WeatherClient.WeatherEventListener() {
          @Override
            public void onWeatherRetrieved(CurrentWeather weather) {
               // Here we can use the weather information to upadte the view
               String text = weather.currentCondition.getCondition();
               String text2 = weather.currentCondition.getDescr();
                float temp =  weather.temperature.getTemp();

                 Toast.makeText(getApplicationContext(), "Condition :" + text + " Description " + text2 + " Temperature " + temp,
                    Toast.LENGTH_LONG).show();
          }

           @Override
           public void onWeatherError(WeatherLibException t) {

           }

           @Override
           public void onConnectionError(Throwable t) {

          }
       });

   }

I get the following error for this:
   java.lang.RuntimeException: Unable to start activity       ComponentInfo{MainActivity}: java.lang.NullPointerException: Attempt to invoke interface method 'void com.survivingwithandroid.weather.lib.provider.IWeatherProvider.setConfig(com.survivingwithandroid.weather.lib.WeatherConfig)' on a null object reference
        at android.app.ActivityThread.performLaunchActivity(ActivityThread.java:2298)
        at android.app.ActivityThread.handleLaunchActivity(ActivityThread.java:2360)
        at android.app.ActivityThread.access$800(ActivityThread.java:144)
        at android.app.ActivityThread$H.handleMessage(ActivityThread.java:1278)
        at android.os.Handler.dispatchMessage(Handler.java:102)
        at android.os.Looper.loop(Looper.java:135)
        at android.app.ActivityThread.main(ActivityThread.java:5221)
        at java.lang.reflect.Method.invoke(Native Method)
        at java.lang.reflect.Method.invoke(Method.java:372)
        at com.android.internal.os.ZygoteInit$MethodAndArgsCaller.run(ZygoteInit.java:899)
        at com.android.internal.os.ZygoteInit.main(ZygoteInit.java:694)
 Caused by: java.lang.NullPointerException: Attempt to invoke interface method 'void com.survivingwithandroid.weather.lib.provider.IWeatherProvider.setConfig(com.survivingwithandroid.weather.lib.WeatherConfig)' on a null object reference
        at com.survivingwithandroid.weather.lib.WeatherClientDefault.updateWeatherConfig(WeatherClientDefault.java:104)
        i.MainActivity.onCreate(MainActivity.java:41)
        at android.app.Activity.performCreate(Activity.java:5933)
        at android.app.Instrumentation.callActivityOnCreate(Instrumentation.java:1105)
        at android.app.ActivityThread.performLaunchActivity(ActivityThread.java:2251)
        at android.app.ActivityThread.handleLaunchActivity(ActivityThread.java:2360)
        at android.app.ActivityThread.access$800(ActivityThread.java:144)
        at android.app.ActivityThread$H.handleMessage(ActivityThread.java:1278)
        at android.os.Handler.dispatchMessage(Handler.java:102)
        at android.os.Looper.loop(Looper.java:135)
        at android.app.ActivityThread.main(ActivityThread.java:5221)

A: client.updateWeatherConfig(config); must be called after initializing provider as:
    WeatherClient client = WeatherClientDefault.getInstance();
    client.init(ctx);

    WeatherConfig config = new WeatherConfig();
    config.unitSystem = WeatherConfig.UNIT_SYSTEM.M;
    config.lang = "en"; // If you want to use english
    config.maxResult = 5; // Max number of cities retrieved
    config.numDays = 6; // Max num of days in the forecast

    IWeatherProvider provider = null;
    try {
        //provider = WeatherProviderFactory.createProvider(new YahooProviderType(), config);
        provider = WeatherProviderFactory.createProvider(new OpenweathermapProviderType(), config);
        //provider = WeatherProviderFactory.createProvider(new WeatherUndergroundProviderType(), config);
        client.setProvider(provider);

    }
    catch (Throwable t) {
        // There's a problem
    }

    client.updateWeatherConfig(config);

A: I guess you didn't import the project correctly or you didnt the right permission to the project.


text:
Q: Expected identifier error when calling a singleton method iOS I'm trying to call a method from a class that uses a singleton pattern on a different class. I'm using a tutorial that doesn't use a singleton that works great, but I can't seem to implement what I need. I keep getting an error that says Expected identifier. I'm assuming this is probably due to syntax, but I can't seem to resolve it. The POI is an NSManagedObject subclass from core data.
This is my version using a singleton. The error points at the bracket before DataSource.
NSArray *itemGroups = [POI [DataSource sharedInstance] fetchDistinctItemGroupsInManagedObjectContext:managedObjectContext];

Here is the equivalent (from the tutorial) without a singleton
NSArray *itemGroups = [POI fetchDistinctItemGroupsInManagedObjectContext:managedObjectContext];

A: You should have somethig like: [[POI sharedInstance] fetchDistinctItemGroupsInManagedObjectContext:managedObjectContext];

A: If you want be able to use POI class in this way:
NSArray *itemGroups = [POI fetchDistinctItemGroupsInManagedObjectContext:managedObjectContext];

then I will suggest to add such code:
// POI.h
+ (NSArray *)fetchDistinctItemGroupsInManagedObjectContext:(NSManagedObjectContext *)context;

// POI.m
+ (NSArray *)fetchDistinctItemGroupsInManagedObjectContext:(NSManagedObjectContext *)context {
    return [[DataSource sharedInstance] fetchDistinctItemGroupsInManagedObjectContext: context];
}


text:
Q: Monte Carlo Code does wait till calculated I want to run the following monte carlo simulation:
  Sub MonteCarlo()
  Application.ScreenUpdating = False
  Dim x As Integer

        For x = 1 To 25

            Application.Calculate
            Do
            DoEvents
            Loop While Not Application.CalculationState = xlDone

        Worksheets("Monte Carlo").Range("A" & x).Value = Worksheets("Ex-Ante Te").Range("B2").Value
        Worksheets("Monte Carlo").Range("B" & x).Value = Worksheets("Ex-Ante Te").Range("B3").Value
        Worksheets("Monte Carlo").Range("C" & x).Value = Worksheets("Ex-Ante Te").Range("B4").Value

        Next
Application.ScreenUpdating = True
End Sub

The Values in B2, B3, and B4 are dependent on random numbers, which are supposed to recalculate themselves after every loop. However, the code does not break and wait until the new random numbers are created and the sheet has recalculated, as this part does not seem to work:
 Application.Calculate
           Do
       DoEvents
     Loop While Not Application.CalculationState = xlDone

I also tried this one, which doesn't work either:
Application.Calculate
If Not Application.CalculationState = xlDone Then
DoEvents
End If

For instance: If I run the monte carlo I get values, which cannot be (values for B2 and B3 that are impossible to fit together). Moreover, when I run the monte carlo manually (recalc, write the numbers down) the sheet works fine. So it must have something to do with the fact, that the code does not seem to wait.
Any help is greatly appreciated.


text:
Q: Website hosted on IIS is not accessbile I have two sites set up in IIS on a remote machine RM; one on regular port 80, and the other on port 5773.
From my local machine LM, I can access the site on 80, but I cannot access the one on 5773; I get a status code of 502 and an error code of 10060 (A connection attempt failed because the connected party did not properly respond after a period of time, or established connection failed because connected host has failed to respond) when I try to do this.
I can access the 5773 site via IIS when I am logged into RM (i.e. by right clicking on a page on the site and going 'Browse'). I can also access pages on the 5773 site via a browser, again when I am logged into RM. I just can't do the same via a browser when I am logged into LM.
I have ensured that port 5773 is open for outgoing traffic on LM.
Could the problem be that I also need to ensure that port 5773 is open for inbound traffic on RM?

A:

Could the problem be that I also need to ensure that port 5773 is open for inbound traffic on RM?

Not quite.
You are connecting from LM  --> RM:5773
If there is a path from LM: --> RM:5773, all should be well (presuming normal firewall setups).
Steps:
From LM, can you telnet to RM 5773  ?
On RM can you telnet to RM 5773  ?
Something is in the way... firewalls.... etc
The most likely causes:

*

*You cannot get out to inet at all on 5773 from LM

*Firewall in front of RM's IIS (network layer, or windows firewall) is blocking     inbound 5773


text:
Q: Add loading indicator when select node in jstree I have many categories in my jstree and I want to add some info to user like  loading indicator while selecting node and thier children. I tried this way
how to show loading image when a child node is loading data dynamically using JSTREE?
but It didn't work for me.
thisInstance.treeInstance.jstree({
            core: {
                data: values,
                themes: {
                    name: 'proton',
                    responsive: true
                }
            },
            plugins: plugins
        });

Any ideas?
When I select or unselect I want to get user loading indicator to know that some work is in progress

A: I have same issue.
I would like to show loader when selecting node with many children.
"activate_node" function trigger event when finish but not when start.
I try to use click event :
    // that.jsTree = $('#tree-view');
that.jsTree.on("click.jstree", ".jstree-anchor", function (e) {
    console.log("on click jstree"); // display
    that.jsTree.hide(); // test not work
});

that.jsTree.on('activate_node.jstree', function (e, data) {
     console.log("after activate_node"); // display
     that.jsTree.show(); // test not work
});


text:
Q: Project referring to an older version of the dll file - System.buffers.dll version 4.0.2.0 I'm wondering what the issue could be.
When i run the application it shows the error below in the error log file.

Could not load file or assembly 'System.Buffers, Version=4.0.2.0, Culture=neutral, PublicKeyToken=cc7b13ffcd2ddd51' or one of its dependencies. The located assembly's manifest definition does not match the assembly reference. (Exception from HRESULT: 0x80131040)

The version of the system.buffer.dll file that the project references is 4.0.3.0 but when the application is run it looks for version 4.0.2.0 and i'm wondering how i can fix that error.
Solution i have tried so far
i have opened the .csproj  and the app.config files to check which version is referenced and it's version 4.0.3.0.
<Reference Include="System.Buffers, Version=4.0.3.0, Culture=neutral, PublicKeyToken=cc7b13ffcd2ddd51, processorArchitecture=MSIL">
      <SpecificVersion>False</SpecificVersion>
      <HintPath>References\System.Buffers.dll</HintPath>
    </Reference>


text:
Q: Favicon in Shiny Working with URL but not Local Filepath I'm trying to add a favicon to my R Shiny app and I want to use a local image file so it can run without Internet connectivity. Using the example Emms gave here I've got a program that will display the favicon when it's using the NOAA logo's url. However, when I saved that exact image to my computer, I've not been able to get it to display. I've tried:

*

*feeding the href parameter a complete file path "C:/Users/...favicon.ico"

*feeding the href parameter only a file path that begins where the current working directory (viewed with getwd()) leaves off

*putting the downloaded NOAA logo .ico into a folder called "www" and placing it with my project/where my current directory is viewing (I don't know if guidance on folders named 'www' applied to local readings, but I figured I'd try it anyway)

*According to Giancarlo Tamburello's answer on the same page, I tried using this site to encode that same NOAA logo as a Base 64 character string--this required changing the whole function a bit, so that I assigned rel="icon", href="data:image/x-icon;base64,[my base 64 string]", and type="image/x-icon"
Nothing I've done with filepaths (or with the base 64 string) has resulted in anything other than Google Chrome's favicon placeholder. Any solution that works with filepaths or with base 64 would satisfy my requirement of being able to run without Internet connectivity.
I'm running R 4.0.2 with Windows 10 Pro OS on a 64-bit OS and launching into Google Chrome.

A: I noticed that when rendering a shiny R markdown into html, knitr copies all static assets into a <notebook_name>_files folder. This however doesn't work when an asset is referenced inside an include, as below. In such cases you can use this workaround (e.g. if your notebook is called index.Rmd):

*

*in index.Rmd:

---
title: "Favicon"
output:
  html_document:
    includes:
      in_header: "favicon.html"
---

then also place the favicon as an image somewhere in your document:
![](favicon-32x32.png)

*

*then in your favicon.html:

<link rel="shortcut icon" href="index_files/favicon-32x32.png">

knitr will copy the favicon image into it's static folder because it's present as an image in your document, which can then can also be referenced to display the favicon ;)

A: You could just paste a base-64 encoded favicon HTML snippet into your R Markdown file, for instance copied from https://www.codegrepper.com/code-examples/html/html+favicon+base64:
<link rel="icon" type="image/png" sizes="16x16" href="data:image/png;base64,
iVBORw0KGgoAAAANSUhEUgAAABAAAAAQBAMAAADt3eJSAAAAMFBMVEU0OkArMjhobHEoPUPFEBIu
O0L+AAC2FBZ2JyuNICOfGx7xAwTjCAlCNTvVDA1aLzQ3COjMAAAAVUlEQVQI12NgwAaCDSA0888G
CItjn0szWGBJTVoGSCjWs8TleQCQYV95evdxkFT8Kpe0PLDi5WfKd4LUsN5zS1sKFolt8bwAZrCa
GqNYJAgFDEpQAAAzmxafI4vZWwAAAABJRU5ErkJggg==" />


text:
Q: No puedo hacer andar los plugins sociales de facebook en mi sitio Estoy teniendo problemas con los servicios de facebook para desarrollador.
Cuando trabajo en localhost anda bien, el tema es cuando lo testeo en el hosting (hostinger). El mas visible es la caja de comentarios que directamente no aparece. Pero el boton compartir y me gusta tampoco funcionan
La url en cuestion es emap.96.lt
En el body

Y en articulo:

{{$articulo->titulo}}

                @include('front.template.partials.face-me-gusta')

{{$articulo->copete}}

                imagen->nombre) }}" alt="..." class="img-responsive">

                {!!$articulo->contenido!!}

Si te gusto, Compartilo:

                @include('front.template.partials.face-compartir')

Comentarios:

slug}}" data-numposts="5">

Utilizo laravel 5.3, blade. Un slug para rutas amigables.
Desde localhost si intento imprimir la ruta. puedo hacerlo, pero cuando quiero imprimir en algun lugar la url para ver que me devuelve. No sale nada
{{ 'https://emap.96.lt/articulos/'.$articulo->slug }}

Por decantacion el problema esta en la url pienso. Pero es raro que ni siguiera pueda imprimir la url.

A: Encontre la solucion a este problema. Aun que aun sigo sin poder hacer andar correctamente la caja de comentarios. Pero los otros componentes. como el "me gusta" o el "compartir" si.
Es un poco insolito. Pero resulta que estaba testeando en un Hosting compartido (hostinger) mi sitio y haciendo estas pruebas.
Cuando comprobé en el generador de codigo q proporciona Facebook comments, note que colocando la url del hosting (.96.lt). En la vista previa no aparecia el chat visualizado (lo mismo que pasaba en mi sitio).
Asi que se me ocurrió cambiar el dominio, aun en hostinger, pero .hol.es, y fue asi q apareció la caja de comentarios y todos los componentes andan perfectamente
Aunque los comentarios cuando quiero colocar uno, ahora me sale "Error en el mensaje"


text:
Q: Source maps not working in unit tests in Angular2 I'm developing an Angular2 project generated by angular-cli 1.0.0-beta.18.
Generally the template has worked out very well. However, when I try to debug unit tests (in Chrome), the code is unintelligible.
What I do is:

*

*I start the tests by running ng test

*A Google Chrome browser opens

*I can confirm in the console that the tests have run: Executed 36 of 36...

*I now want to debug the tests, so I click the DEBUG button in Chrome, which opens a new tab.

*In that tab I open the Developer tools.

*I can now use Ctrl-P to find and view files. The code is readable for for the specs.

*However, when I open the implementation code, I get the following

It looks like the file has been minified, or transformed by the code coverage tool. The latter seems more probable considering the __coverage__ part. Sourcemaps are obviously not in effect.
How do I make source maps work?
I have tried modififying the karma.conf.js file to remove all references to code coverage reporting (i.e. Istanbul), see below. But this makes no difference in the behaviour:
module.exports = function (config) {
  config.set({
    basePath: '',
    frameworks: ['jasmine', 'angular-cli'],
    plugins: [
      require('karma-jasmine'),
      require('karma-chrome-launcher'),
      require('angular-cli/plugins/karma')
    ],
    files: [
      { pattern: './src/test.ts', watched: false }
    ],
    preprocessors: {
      './src/test.ts': ['angular-cli']
    },
    angularCli: {
      config: './angular-cli.json',
      environment: 'dev'
    },
    reporters: ['progress'],
    port: 9876,
    colors: true,
    logLevel: config.LOG_INFO,
    autoWatch: true,
    browsers: ['Chrome'],
    singleRun: false
  });
};

A: This was actually a known issue. It was fixed in angular-cli 1.0.0-beta.19-3. Specifically it was this fix.


text:
Q: Gremlin-python - how to automate graph creation I'm trying to create on EC2 with Amazon Linux 2 a python script to create a graph on neptune AWS.
from __future__  import print_function

from gremlin_python import statics
from gremlin_python.structure.graph import Graph
from gremlin_python.process.graph_traversal import __
from gremlin_python.process.strategies import *
from gremlin_python.driver.driver_remote_connection import DriverRemoteConnection

import matplotlib.pyplot as plt; plt.rcdefaults()
import numpy as np
import matplotlib.pyplot as plt
import pandas as pd
import networkx as nx

graph = Graph()

remoteConn = DriverRemoteConnection('wss://myendpoint:8182/gremlin','g')
g = graph.traversal().withRemote(remoteConn)

def list_all(self, limit=500):
    g.V().limit(limit).elementMap().toList()

def find_vertex(self, vid):
    g.V(vid).elementMap().next()

def list_by_label_name(self, vlabel, name):
    g.V().has(vlabel, 'name', name).elementMap().toList()

vertices = g.V().groupCount().toList()
edges  = g.E().groupCount().toList()

print(vertices)
print(edges)

# Find up to 15 routes from LHR to SJC that make one stop.
paths = g.V() \
             .out().out().has('table').limit(15) \
             .path().by('table').toList()

# Create a new empty DiGraph
G=nx.DiGraph()

# Add the routes we found to DiGraph we just created
for p in paths:
    G.add_edge(p[0],p[1])
    G.add_edge(p[1],p[2])

# Give the starting and ending airports a different color
colors = []

for label in G:
    if label in['table']:
        colors.append('yellow')
    else:
        colors.append('#11cc77')

# Now draw the graph
plt.figure(figsize=(5,5))
nx.draw(G, node_color=colors, node_size=1200, with_labels=True)
plt.show()

remoteConn.close()

no issue to connect to neptune but with import matplotlib.pyplot as plt I have an issue when I run the script
Traceback (most recent call last):
  File "gremlinexample.py", line 13, in <module>
    import matplotlib.pyplot as plt
  File "/home/ec2-user/.local/lib/python2.7/site-packages/matplotlib/pyplot.py", line 115, in <module>
    _backend_mod, new_figure_manager, draw_if_interactive, _show = pylab_setup()
  File "/home/ec2-user/.local/lib/python2.7/site-packages/matplotlib/backends/__init__.py", line 63, in pylab_setup
    [backend_name], 0)
  File "/home/ec2-user/.local/lib/python2.7/site-packages/matplotlib/backends/backend_tkagg.py", line 4, in <module>
    from . import tkagg  # Paint image to Tk photo blitter extension.
  File "/home/ec2-user/.local/lib/python2.7/site-packages/matplotlib/backends/tkagg.py", line 5, in <module>
    from six.moves import tkinter as Tk
  File "/usr/lib/python2.7/site-packages/six.py", line 203, in load_module
    mod = mod._resolve()
  File "/usr/lib/python2.7/site-packages/six.py", line 115, in _resolve
    return _import_module(self.mod)
  File "/usr/lib/python2.7/site-packages/six.py", line 82, in _import_module
    __import__(name)
ImportError: No module named Tkinter

I tried to install Tkinter with
$ pip install tk
DEPRECATION: Python 2.7 reached the end of its life on January 1st, 2020. Please upgrade your Python as Python 2.7 is no longer maintained. pip 21.0 will drop support for Python 2.7 in January 2021. More details about Python 2 support in pip can be found at https://pip.pypa.io/en/latest/development/release-process/#python-2-support
Defaulting to user installation because normal site-packages is not writeable
Requirement already satisfied: tk in ./.local/lib/python2.7/site-packages (0.1.0)

and with
$ pip3 install tk
Defaulting to user installation because normal site-packages is not writeable
Requirement already satisfied: tk in ./.local/lib/python3.7/site-packages (0.1.0)

but I have always the same problem
My goals is to draw a neptune graph with a python script. I don't want to use a neptune notebook because I want to build my graph for a web app that calls a python script


text:
Q: Circle "with radius" vs. "of radius" Are both of there correct?

*

*Circle with radius r = 1 cm.

*Circle of radius r = 1 cm.

I do not want to use other sentences such as "Radius of a circle is r = 1 cm."

A: You can say both but "circle of radius r=" is much preferred, as this ngram shows.
This  preference persists when the head of the prepositional complement is followed by the mathematical symbol "=": ngram "=".


text:
Q: jQuery Plugin - access method of instantiated object I know, this has been asked multiple times, but somehow, I can't find an answer that fits my needs, so here it goes.
I made a plugin which looks like this (stripped down):
(function(window, $){

    var MyPlugin = function(elem, options){
        this.elem = elem;
        this.$elem = $(elem);
        this.options = options;
        this.metadata = this.$elem.data('popup-options');
        this.markup = '
some markup here
';
        this.popup = null;
    };

    MyPlugin.prototype = {
        defaults:{
            type: 'outer',
            color: 'orange'
        },

        init: function(){

            this.config = $.extend({}, this.defaults, this.options, this.metadata);

            this.show();

            return this;
        },

        show: function(){

            // some stuff to show the element

        },

        hide: function(){

            // some stuff to hide the element
        },

        someMethod: function(){

            // some other stuff the plugin does
        }

    };

    MyPlugin.defaults = MyPlugin.prototype.defaults;

    $.fn.myPlugin = function(options){
        return this.each(function(){
            var thePlugin = new MyPlugin(this, options).init();
        });
    };

    window.MyPlugin = MyPlugin;

}(window, jQuery));

Now in the code I apply the plugin like this:
var thePlugin = $(this).myPlugin();

So far, this works.
But now, I wanna access one of the functions within the plugin from outside (e.g. «someMethod»).
I tried to call it like:
thePlugin.someMethod();
or
thePlugin.myPlugin.someMethod();
or even
thePlugin.myPlugin[0].someMethod();
none of this works.
How do I have to make the Plugin, so I can access it after it's been initialized?
Is this possible at all?

A: Found the solution.
I had to change the return-statement of the plugin like this:
$.fn.updPopup = function(options){
        return new UpdPopup(this, options).init();
};

This returns only a single instance of the plugin.
Then I can access it like this:
thePlugin.someMethod();

Question remains: how would I access it with the original return statement (that apparently returns an array of objects, I guess)?


text:
Q: Mysql DATE_ADD INTERVAL with mysql table fields I have one table called datas in there I have id,start_date,end_date,day_count,day_type.
Where id is primary key,start and end_date is datetime, day_count is int and day_type is varchar.
Now day_type store DAY,WEEK,MONTH as value when user made request and day field hold number of days like 1 to 60.
Now I want to user this count and type in date_add mysql built-in function.
I have tried to pass it as below but its show error.
SELECT
datas.day_count,
datas.day_type,
MIN( datas.start_date ) AS MinDate,
MAX( datas.end_date ) AS MaxDate,
DATE_ADD(MaxDate,INTERVAL datas.day_count datas.day_type) AS ExactDate,
datas.trade_service_id
FROM datas

Erro is

You have an error in your SQL syntax; check the manual that corresponds to your MySQL server version for the right syntax to use near 'datas.day_type)) AS ExactDate, datas' at line 13

Please little hint would be great.

A: This query works in MySQL but what do you exactly want to output without Group and so on?
SELECT
datas.day_count,
datas.day_type,
MIN( datas.start_date ) AS MinDate,
MAX( datas.end_date ) AS MaxDate,

start_date, min(start_date) as min_date,
case day_type
  when 'MONTH' then DATE_ADD(MAX( datas.end_date ),INTERVAL datas.day_count MONTH)
  when 'DAY' then DATE_ADD(MAX( datas.end_date ),INTERVAL datas.day_count DAY)
end as ExactDate,

datas.trade_service_id
FROM datas


text:
Q: Why is the output of "canget(state(atdoor, onfloor, inmiddle, atwindow, hasnot), Plan)." in this program repeatedly returning as false? For this assignment, I have to produce a program that determines the steps a fictional monkey needs to take in order to get a banana suspended from the ceiling. In order to grab the banana, it must push a box underneath it, climbing on top of the box for extra reach.
However, every time, when I input "?- canget(state(atdoor, onfloor, inmiddle, atwindow, hasnot), Plan).", it reads out as false, indicating that there's no way for the monkey to reach the banana.
This is blatantly untrue, as in any situation where the monkey starts on the floor, it should be able to  follow these steps.

*

*Walk to the box's location.

*Push the box to the banana's location.

*Climb on top of the box.

*Grab the banana.

There must be something wrong with the program, but I haven't been able to catch it, not even after an hour of poring over the code.
I've tried eliminating the comments, in case those are somehow connected to it.
cls :- write('\e[H\e[2J').

%state(Monkey location in the room, Monkey onbox/onfloor, boxlocation, banana location, has/hasnot banana)

%This causes the monkey to walk to the box.

do( state(_, onfloor, M, _, hasnot),
    the, monkey, walks, to, the, M, [], [],
    state(M, onfloor, M, _, hasnot)).

%This causes the monkey to push the box to where the banana is.

do( state(L, onfloor, L, M, hasnot),
    the, monkey, pushes, the, box, to, the, M,
    state(M, onfloor, M, M, hasnot)).

%This causes the monkey to climb the box.

do( state(L, onfloor, L, L, has),
    the, monkey, climbs, the, box, [], [], [],
    state(L, onbox, L, L, has)).

do( state(SharedLocation, onBox, SharedLocation, SharedLocation, hasnot)
    the, monkey, grabs, the, banana, [], [], [],
    state(SharedLocation, onBox, SharedLocation, SharedLocation, has)). %This causes the monkey to grab the banana.

%canget(state) represents if the monkey can retrieve the banana from its current state.
canget(state(_, _, _, _, has), []).

%This states what the monkey should do in a non-ideal state. Namely, performing an action, and concatenating the appropriate sentence.
canget(State1, Plan):-
    do(State1, A, B, C, D, E, F, G, H, State2),
    canget(State2, PartialPlan9),
    add(A, PartialPlan1, PartialPlan2),
    add(B, PartialPlan2, PartialPlan3),
    add(C, PartialPlan3, PartialPlan4),
    add(D, PartialPlan4, PartialPlan5),
    add(E, PartialPlan5, PartialPlan6),
    add(F, PartialPlan6, PartialPlan7),
    add(G, PartialPlan7, PartialPlan8),
    add(H, PartialPlan8, PartialPlan9),
    add(".", PartialPlan9, Plan)).

When prolog runs, there are two errors that I haven't been able to eliminate. I'm not sure if  they're related, but here they are.

ERROR: c:/users/(my account name)/documents/prolog files/monkey text problem.pl:26:3: Syntax error: Operator expected
ERROR: c:/users/(my account name)/documents/prolog files/monkey text problem.pl:47:28: Syntax error: Illegal start of term

Instead of outputting false, the program should output what the list 'Plan', should be.

A: I've cleared errors and the warning issued about the singleton you'll see in last clause once the syntax has been amended:
Warning:    Singleton variables: [PartialPlan1]

but since the add/3 predicate is missing you need more effort to get it working. Anyway, the code is here
cls :- write('\e[H\e[2J').

%state(Monkey location in the room, Monkey onbox/onfloor, boxlocation, banana location, has/hasnot banana)

%This causes the monkey to walk to the box.

do( state(_, onfloor, M, _, hasnot),
    the, monkey, walks, to, the, M, [], [],
    state(M, onfloor, M, _, hasnot)).

%This causes the monkey to push the box to where the banana is.

do( state(L, onfloor, L, M, hasnot),
    the, monkey, pushes, the, box, to, the, M,
    state(M, onfloor, M, M, hasnot)).

%This causes the monkey to climb the box.

do( state(L, onfloor, L, L, has),
    the, monkey, climbs, the, box, [], [], [],
    state(L, onbox, L, L, has)).

do( state(SharedLocation, onBox, SharedLocation, SharedLocation, hasnot),
    the, monkey, grabs, the, banana, [], [], [],
    state(SharedLocation, onBox, SharedLocation, SharedLocation, has)). %This causes the monkey to grab the banana.

%canget(state) represents if the monkey can retrieve the banana from its current state.
canget(state(_, _, _, _, has), []).

%This states what the monkey should do in a non-ideal state. Namely, performing an action, and concatenating the appropriate sentence.
canget(State1, Plan):-
    do(State1, A, B, C, D, E, F, G, H, State2),
    canget(State2, PartialPlan1),
    add(A, PartialPlan1, PartialPlan2),
    add(B, PartialPlan2, PartialPlan3),
    add(C, PartialPlan3, PartialPlan4),
    add(D, PartialPlan4, PartialPlan5),
    add(E, PartialPlan5, PartialPlan6),
    add(F, PartialPlan6, PartialPlan7),
    add(G, PartialPlan7, PartialPlan8),
    add(H, PartialPlan8, PartialPlan9),
    add(".", PartialPlan9, Plan).

A: I did not have your add predicate, so I modified the definitions of actions in each one of the do clauses.
Explanations of the changes that I made are identified by ==> in the code.
%state(Monkey location in the room, Monkey onbox/onfloor, boxlocation, banana location, has/hasnot banana)

%This causes the monkey to walk to the box.
% ==> You have to capture fact that the banana does not change location
% ==> when the monkey walks, hence the variable B. Also to make progress
% ==> L and M must not be the same location.
do(state(L, onfloor, M, B, hasnot),
   the_monkey_walks_to(M),
   state(M, onfloor, M, B, hasnot)) :-
    L \= M.

%This causes the monkey to push the box to where the banana is.
% ==> To make progress L and M must not be the same location.
do(state(L, onfloor, L, M, hasnot),
   the_monkey_pushes_the_box_to_the(M),
   state(M, onfloor, M, M, hasnot)) :-
    L \= M.

%This causes the monkey to climb on the box.
do(state(L, onfloor, L, L, hasnot),
   the_monkey_climbs_on_the_box,
   state(L, onbox, L, L, hasnot)).

%This causes the monkey to climb down the box.
% ==> This action was missing, causing the monkey to get stuck on the box.
do(state(L, onbox, L, L, hasnot),
   the_monkey_climbs_down_the_box,
   state(L, onfloor, L, L, hasnot)).

%This causes the monkey to grab the banana.
% ==> You had a typo here, you have to use the atom `onbox` instead of `onBox`.
do(state(SharedLocation, onbox, SharedLocation, SharedLocation, hasnot),
   the_monkey_grabs_the_banana,
   state(SharedLocation, onbox, SharedLocation, SharedLocation, has)).

%canget(state) represents if the monkey can retrieve the banana from its current state.
canget(state(_, _, _, _, has), [], _).

%This states what the monkey should do in a non-ideal state. Namely, performing an action, and concatenating the appropriate sentence.
% ==> You have to keep track of the previous states, for otherwise the plan could get
% ==> into an infinite loop.
canget(State1, [Action | PartialPlan1], PreviousStates):-
    not(memberchk(State1, PreviousStates)),
    do(State1, Action, State2),
    canget(State2, PartialPlan1, [State1 | PreviousStates]).
    %add(A, PartialPlan1, PartialPlan2),
    %add(B, PartialPlan2, PartialPlan3),
    %add(C, PartialPlan3, PartialPlan4),
    %add(D, PartialPlan4, PartialPlan5),
    %add(E, PartialPlan5, PartialPlan6),
    %add(F, PartialPlan6, PartialPlan7),
    %add(G, PartialPlan7, PartialPlan8),
    %add(H, PartialPlan8, PartialPlan9),
    %add(".", PartialPlan9, Plan).

Queryting for canget(state(atdoor, onfloor, inmiddle, atwindow, hasnot), Plan, []). yields:
Plan = [the_monkey_walks_to(inmiddle), the_monkey_pushes_the_box_to_the(atwindow), the_monkey_climbs_on_the_box, the_monkey_grabs_the_banana]

A: I am not sure whether this has been explicitly pointed out by somebody already, but Prolog's error messages, though they may seem somewhat cryptic to Prolog newcomers, actually tell you what is wrong with the program (syntax-wise). At the very least, it helps to look at the (immediate area around the) precise position in the code that they refer to.
The error

ERROR: c:/users/(my account name)/documents/prolog files/monkey text problem.pl:26:3: Syntax error: Operator expected

points you to the clause (line 26, column 3)
do( state(SharedLocation, onBox, SharedLocation, SharedLocation, hasnot)
    the, monkey, grabs, the, banana, [], [], [],
    state(SharedLocation, onBox, SharedLocation, SharedLocation, has)). %This causes the monkey to grab the banana.

or more precisely, the first occurrence of "the" in the second line of that clause. The message "operator expected" tells you that Prolog was expecting an operator (such as a comma) at this point, not an atom (such as "the"). If you look closely, you see that in the previous line (immediately before) indeed there is a comma missing after "state(..., hasnot)".
Similarly, the message

ERROR: c:/users/(my account name)/documents/prolog files/monkey text problem.pl:47:28: Syntax error: Illegal start of term

points you to the last line
    add(".", PartialPlan9, Plan)).

of the very last clause, which has one closing parenthesis too many. Here, Prolog tried to read the "Plan)" part as one term, which has an "illegal start" because a closing ")" should always be preceded by some functor and an opening "("; something like "foo(Plan)" for example would have been a legal term.


text:
Q: Tabbar Nav app, allowing one view to rotate while others do not I have a tab bar application in which i have 3 diffrent views each with there own view controller.
In the tab bar code i have this, to handle rotation.
#import "RotatingTabBarController.h"

@implementation RotatingTabBarController

    // Override to allow orientations other than the default portrait orientation.
    - (BOOL)shouldAutorotateToInterfaceOrientation:(UIInterfaceOrientation)interfaceOrientation {

      return [self.selectedViewController shouldAutorotateToInterfaceOrientation:interfaceOrientation];
 }
@end

Then in the 2nd view controller that i want to rotate depending on device orientation i have:
// Override to allow orientations other than the default portrait orientation.
 - (BOOL)shouldAutorotateToInterfaceOrientation:(UIInterfaceOrientation)interfaceOrientation {

   return YES;
 }

And For the other two views that i do not want to rotate i have this method set.
// Override to allow orientations other than the default portrait orientation.
- (BOOL)shouldAutorotateToInterfaceOrientation:(UIInterfaceOrientation)interfaceOrientation {
 // Return YES for supported orientations
 return (interfaceOrientation == UIInterfaceOrientationPortrait);
}

The PROBLEM: so this works fine in view 1 and view 3 when u rotate the device they stay in portrait mode which is desired.  When in view 2 i rotate to landscape, the view does as expected and rotates to landscape.  BUT when click view 1 or view 3 tab while in lanscape mode in view 2,  View 1 and View 3 are in landscape mode.
I can't figure out how to force them in portrait even if view 2 rotates to lanscape.
Any one know how to do this?

A: There's a big discussion[1] on this dating back from 2008 until now (look at comments down a few pages) -- summarily it seems like
application.statusBarOrientation = UIInterfaceOrientationLandscapeRight;

or
[[UIDevice currentDevice] setOrientation:UIInterfaceOrientationLandscapeRight];

or
[application setStatusBarOrientation: UIInterfaceOrientationLandscapeRight animated:NO];

will let you force it to landscape -- you would want to do this when the user goes back to your landscapey view(s) programmatically.
[1] iPhone app in landscape mode, 2008 systems


text:
Q: Comparing a vector and a vector of struct for matching values - c++ I have a vector of 6 numbers, and another vector which is a vector of my struct that contains numeric data from a file.
my vectors are as so (vec1 = 6 random nums, vec2 = file numeric data)

vec1
1, 2, 3, 4, 5, 6
vec2
4, 5, 2, 7, 34, 76
5, 7, 3, 7, 1, 23
98, 76, 5, 9, 12, 64

I need to compare vec1 to vec2 to see how many matching numbers are contained in vec2, and return the count of each value found from vec1 in vec2.
The issue im having is that my vec2 is a vector of a structure, and vec1 is just a regular vector. How do you compare a vec with a vec of a structure? I've tried the below but the '==' operator doesnt like the comparison between a vec and a struct.
   //struct to store data from file
   struct past_results {
      std::string date;
      std::string winningnums;
    };

    //vectors to store file content, and 6 random numbers
    std::vector<past_results> resultvec;
    std::vector<std::string> random_nums

    for(int i = 0; i < resultvec.size(); i++)
    if(randomnums.at(i) == resultvec.at(i))
    {
     //output result
    }

error message: operand types are: std::string == past_results
How do I explicitly get the values from my struct vector and compare to my normal vector?
For clarity, I have cut out a lot of my code as I didn't believe it to be relevant as i just need to know how I would compare both vectors.

A: In your if statement you are trying to compare an element of randomnums which is of type std::string to an element of resultvec which is of type past_result. In order to compare the actual winningnums value of the struct, change your if-statement to:
if(randomnums.at(i) == resultvec.at(i).winningnums)
{
    //output result
}


text:
Q: RoboBrowser TypeError: 'NoneType' object is not callable So I'm using robobrowser which uses bs4. When I try and strip the tags from the strings, I get the error described below. If I comment out i.strip("") then I can easily print the list of strings with the tags on the ends. Possible dupe: TypeError: 'NoneType' object is not callable, BeautifulSoup
from robobrowser import RoboBrowser as r

browser = r(history=False)
browser.open('http://mp3skull.com/')
usrsearch = "a-ha" #input('Search for music: ')

searchform = browser.get_form(action="/search_db.php")
searchform['q'].value = usrsearch
browser.submit_form(searchform)

songs = browser.select('b')
for i in songs:
    print(i.strip(""))

Error:
line 13, in <module>
i.strip("")
TypeError: 'NoneType' object is not callable

A: You can use encode_contents() to get the tag contents as a bytestring, without the tag itself.
from robobrowser import RoboBrowser as r

browser = r(history=False)
browser.open('http://mp3skull.com/')
usrsearch = "a-ha" #input('Search for music: ')

searchform = browser.get_form(action="/search_db.php")
searchform['q'].value = usrsearch
browser.submit_form(searchform)

songs = browser.select('b')
for i in songs:
    print(i.encode_contents())

I couldn't find information on all the BeautifulSoup4 tag properties and methods in the official documentation. However, I did find this page which lists more information on the properties and methods.


text:
Q: Separating a string in Python How would I separate characters once I have a string of unseparated words?
For example to translate "take the last character of the suffix and add a space to it every time ("aSuffixbSuffixcSuffix" --> "aSuffix bSuffix cSuffix").`
Or, more generally, to replace the x-nth character, where x is any integer (e.g., to replace the 3rd, 6th, 9th, etc. character some something I choose).

A: Assuming you're getting your string from this question, the easiest way is to not cram all the strings together in the first place. Your original create_word could be changed to this:
def create_word(suffix):
    letters="abcdefghijklmnopqrstuvwxyz"
    return [i + suffix for i in letters]

Then you'd be able to take e and ''.join(e) or ' '.join(e) to get the strings you want.

A:    str = "SuffixbSuffixcSuffix"

   def chunk_str(str, chunk_size):
        return [str[i:i+chunk_size] for i in range(0, len(str), chunk_size)]

   " ".join(chunk_str(str,3))

returns:
'Suf fix bSu ffi xcS uff ix'

A: You could use the replace method of strings. Check the documentation
initial = "aSuffixbSuffixcSuffix"

final = initial.replace("Suffix", "Suffix ")
print(final)


text:
Q: Adding additional textboxes to aspx based on xml Is there a way to add additional textboxes to an aspx based on entries from an xml file?
Ie. An xml file reads
<Number>
  <Num>1</Num>
  <Num>2</Num>
  <Num>3</Num>
</Number>

And I want to insert a new textbox every time Num = 2. Also, I'm working in C# in Visual Studio if that helps.

A: It's actually fairly straightforward. First, add something like the following to your aspx:

This doesn't strictly have to be a div - just whatever you want to add controls to.
In your code-behind, do something like this:
const string xml = @"<Number>
                       <Num>1</Num>
                       <Num>2</Num>
                       <Num>3</Num>
                     </Number>";

XDocument doc = XDocument.Parse(xml);
int i = 0;

foreach (XElement num in doc.Root.Elements())
{
    TextBox box = new TextBox
    {
        ID = "dynamicTextBox" + i,
        Text = num.Value,
        ReadOnly = true
    };
    divToAddTo.Controls.Add(box);

    divToAddTo.Controls.Add(new LiteralControl("
"));

    i++;
}


text:
Q: Windows 8 metro apps convert existing image to byte[] I am trying to save an existing image (inside a button in my app) to byte[] then save it to SQLite database. I know how to use FileOpenPicker to load and convert to IRandomAccessStream, and I know how to save to database but I can't figure our how to convert an existing image to byte array in metro apps/windows UI.
I have searched a lot but found mainly examples with FileOpenPicker or using memory stream which doesn't seem to work with metro apps.
thank you.

A: You can use a Datareader as
    var file = await new FileOpenPicker().PickSingleFileAsync();
    var fStream = await file.OpenAsync(FileAccessMode.Read);

    var reader = new DataReader(fStream.GetInputStreamAt(0));
    var bytes = new byte[fStream.Size];
    await reader.LoadAsync((uint)fStream.Size);
    reader.ReadBytes(bytes);

Finally you can save bytes to database.
One more example here Reading a StorageFile to a byte array in C#
Added Edit
WinRT you will need to use http://writeablebitmapex.codeplex.com/
WinRT Loading an Image into a Byte array
Quoting..

Basically you need to load the image into a WriteableBitmap, then
  access its pixel buffer by calling PixelBuffer.AsStream().


text:
Q: ng-show not working in angularjs    {{showSubHeader}}

            <button class="button-icon ion-bag"></button>

The expressions {{showSubHeader}} changes from true to false and false to true just fine.
showSubHeader has a boolean value .
i.e showSubHeader=true or  showSubHeader=false
The value changes are being picked up by angular . As I change the value, I see in console that ng-show expression changes but it does not hide the element even if it is ng-show="false".
How do I fix this? What seems wrong?>
Edit: draggable is a directive that looks like this:
.directive('draggable', function ($animate) {
  return function(scope, element) {
       var startX = 0, startY = 0, x = 0, y = 0;

        var el = element[0];
        console.log(el)
        el.draggable = true;
        element.css({
       position: 'relative',
       cursor: 'pointer'
      });
        el.addEventListener(
            'dragstart',
            function(e) {

          element.addClass("animated slideInDown")
                return false;
            },
            false
        );

        el.addEventListener(
            'dragend',
            function(e) {

          element.addClass("animated slideInUp")
             scope.checkBill();
                return false;
            },
            false
        );
    }
})

checkBill
$scope.checkBill= function(){
    $scope.$apply(function(){
       $scope.showSubHeader=false;

    })
     $state.go('menu.TotalBill', {}, {inherit: true, notify:true})
  }

A: Try :

      <button class="button-icon ion-bag"></button>

A: You can try to isolate ng-show:

        <button class="button-icon ion-bag"></button>


text:
Q: which way would be faster? error suppressing @$_REQUEST['x'] or going thru isset($_REQUEST['x']) Using the isset is an additional function call, but nevertheless is the recommended practice.
In the following particular example, what would be faster?
I sense that the first would be faster. Otherwise, could somebody shed some light as to why the second would be faster -if so?
if (@$_REQUEST['x']=='1'):
    define ('X','1');
else:
    define ('X','0');
endif;

//or

if (isset($_REQUEST['x'])):
    if ($_REQUEST['x']=='1'):
        define ('X','1');
    else:
        define ('X','0');
    endif;
else:
    define ('X','0');
endif;

A: Best practice dictates avoiding the suppression operator, so go with isset(). If you're concerned enough with micro-optimization to consider the difference, you should know that PHP still handles suppressed errors even though they're not displayed. Any optimization theoretically gained by @ would likely be lost by the error processing.
Best practice also dictates specificity in getting input from external sources. I'd also recommend choosing $_POST or $_GET as alternatives.


text:
Q: OctoberCMS Rainlab.Builder- Error on "hasOne" relation to same model I'm developing an October CMS Plugin for managing animals (with rainlab.builder).
Animals have a couple of fields and relations. Every animal have a father and a mother animal. But when I try to safe my animal the following error appears:
Event Log:
PDOException: SQLSTATE[23000]: Integrity constraint violation: 1048
Column 'id' cannot be null in dir/website/vendor/laravel/framework/src/
Illuminate/Database/Connection.php:413

Plugin animal form:
SQLSTATE[23000]: Integrity constraint violation: 1048 Column 'id'
cannot be null (SQL: update `prefix_animals_animal` set `id` =  where
`prefix_animals_animal`.`id` = 1 and `prefix_animals_animal`.`id` is
not null)" on line 666 of dir/website/vendor/laravel/framework/
src/Illuminate/Database/Connection.php

The error only appers when I use the relations (child -> father, child -> mother).

Code
I have implemented the following hasOne - relations to my animal model:
/* Relation */

public $hasOne = [
    'father' => [
        'Namespace\Animals\Models\Animal',
        'key' => 'id',
        'otherKey' => 'id'
    ],
    'mother' => [
        'Namespace\Animals\Models\Animal',
        'key' => 'id',
        'otherKey' => 'id'
    ]
];

This are my fields from field.yaml:
father:
    label: Father
    oc.commentPosition: ''
    nameFrom: name
    descriptionFrom: description
    emptyOption: 'No father'
    span: left
    type: relation
mother:
    label: Mother
    span: right
    oc.commentPosition: ''
    nameFrom: name
    descriptionFrom: description
    emptyOption: 'No mother'
    type: relation

I would be very happy if someone have a solution for these kind of relations.
Cheerio!

A: Don't use id as the primary key for the relation as this is not good practice.
Actually this creates the problem you are seeing also. Currently your model is using the id for primary Id, mother Id and father Id. You can't do that.
Add mother_id and father_id to the Animal model and change the relation definition to this:
public $hasOne = [
    'father' => [
        'Namespace\Animals\Models\Animal',
        'key' => 'father_id',
        'otherKey' => 'id'
    ],
    'mother' => [
        'Namespace\Animals\Models\Animal',
        'key' => 'mother_id',
        'otherKey' => 'id'
    ]
];

PS. In your case you dont have to define key and otherKey as the default value for otherKey is "id" and the otherKey value is created from the relation name with the "_id" suffix.


text:
Q: Laravel form submit showing MethodNotAllowedHttpException in RouteCollection.php line 218: This is my route
Route::resource('admin/reports', 'ReportController');

This is controller function
public function store(Request $request)
{
    return "Thank you";
}

This is my html code
{!! Form::open([ 'url' => 'admin/reports/store', 'files' => true, 'enctype' => 'multipart/form-data', 'class' => 'dropzone', 'id' => 'reportfile' ]) !!}
    {!! csrf_field() !!}

Select File

        <button type="submit" class="btn btn-primary">Upload Report</button>

    {!! Form::close() !!}

When I submit the form, it show me MethodNotAllowedHttpException in RouteCollection.php line 218:
Any help is much appreciated. Thanks

A: Your form action should just be admin/reports.
Currently it will assume you are trying to post to the route admin/reports/{id}. That endpoint is used with GET, PUT and DELETE.
Check the docs including a table giving you routes https://laravel.com/docs/5.1/controllers#restful-resource-controllers if I were you I'd use the route helper to generate your urls for you


text:
Q: Add a user profile field inside a document in another collection I have two collections, one for registering properties and one registered users.
The collection for registering properties is called listings:

And the collection for registered users is called users

I can inject into the documents that are in the "listings" collection the id of the user who is logged in at that moment.

let auth = getAuth()
    onAuthStateChanged(auth, (user) => {
        if (user) {
            // set user on formData
            formData = {
                ...formData,
                user: user.uid
            }
        } else {
            // goto('/profile');
        }
    })

What I want is to insert a field that is inside a document in the users collection into a document in the listings collection when I register a new property.
In this case the document inside the listings collection would get a new field: slug

A: I made a function to get the data I wanted

// get reference to users collection
    const usersRef = collection(db, 'users')
    // get collection data
    getDocs(usersRef).then((snapshot) => {
        let userData = []
        snapshot.docs.forEach((doc) => {
            // get user data of current user
            if (doc.id === getAuth().currentUser.uid) {
                userData = doc.data()
            }
        })
        console.log(userData)
    })


text:
Q: How can I return a class from a TypeScript function? I'm using TypeScript with a dependency injection library which works very similar to Angular 1 - basically: register a factory with your dependencies as arguments.
This is how I would register a class in ES6
export let factory = () => {
    return class Foo {}
};

If I write the same in TypeScript:
export let factory = () => {
    return class Foo {}
};

It fails to compile with the error

error TS4025: Exported variable 'factory' has or is using private name 'Foo'.

Is there any way to allow TypeScript to return a class from a factory function?

A: Late answer on old question:
You need to have the class defined outside the factory method and define return value using 'typeof'.
class Foo {}

export const factory = (): typeof Foo => {
    return Foo;
};

A: I think this is a proper way to do it:
export let factory = () => {
     class Foo {/* ... */}
     return Foo as (new () => { [key in keyof Foo]: Foo[key] })
};

Check it out on playground

A: Quick answer
change this:
export let factory = () => {
    return class Foo {}
};

to that:
export let factory = () : any => {
    return class Foo {}
};

Longer answer
This error could be triggered/forced by  to a tsconfig.json setting:
{
    "compilerOptions": {
        ...
        "declaration": true // this should be false or omitted

But that is not the reason, it is just a trigger. The real reason (as discussed here Error when exporting function that returns class: Exported variable has or is using private name) comes from the Typescript compiler
when TS compiler founds statement like this
let factory = () => { ...

it must start to guess what is the return type, because that information is missing (check the : <returnType> placeholder):
let factory = () : <returnType> => { ...

in our case, TS will quickly find out, that the returned type is easy to guess:
return class Foo {} // this is returned value,
                    // that could be treated as a return type of the factory method

so, in case we would have that similar statement (this is not the same, as original statement at all, but let's just try to use it as an example to clarify what happens) we can properly declare return type:
export class Foo {} // Foo is exported
export let factory = () : Foo => { // it could be return type of export function
    return Foo
};

that approach would be working, because the Foo class is exported, i.e. visible to external world.
Back to our case. We want to return type which is not exported. And then, we MUST help TS compiler to decide, what is the return type.
It could be explicit any:
export let factory = () : any => {
    return class Foo {}
};

But even better would be to have some public interface
export interface IFoo {}

And then use such interface as return type:
export let factory = () : IFoo => {
    return class Foo implements IFoo {}
};

A: You need to export the class as well so that the consumer of the method can access the type.
Typically a factory will return an instance rather than a class or constructor.
UPDATED EXAMPLE
export class Foo {};

export let factory = () => {
    return Foo;
};

With ES6 you don't need to export the class type, but with TypeScript you absolutely should exporting the type signatures.

A: I've found separately provided solution satisfying:
export class MyClass {
   ...
}

export type MyClassRef = new (...args: any) => MyClass;

Given that signature I can use MyClassRef as a type of return value:
exposeMyClass(): MyClassRef {
    return MyClass;
}

A: I was struggling with the same error. The solution for me was to remove the
"declaration": true

from tsconfig.json or to set it to false.

A: Are you looking for returning Type of class from the function? Below is one code snippet how we can implement factory in TypeScript similar to in other languages.
    class Greeter {
    greeting: string;
    constructor(message: string) {
        this.greeting = message;
    }
    greet() {
        return "Hello, " + this.greeting;
    }
}
class Factory{
    getObject(msg:string): Greeter {
        return new Greeter(msg);
    }
}
var greeter = new Factory().getObject("Hi");
console.log(greeter.greet());


text:
Q: Getting percent of total from subtotals in pandas pivot table I have the following dataframe
from io import StringIO
incsv = StringIO("""Date,State,City,Tools,Size,y
20130320,AZ,Phoenix,A,4,1000
20130320,AZ,Tempe,B,4,1100
20130320,NY,NYC,C,1,900
20130320,NY,NYC,C,2,1300
20130320,NY,Albany,D,1,800
20130320,AZ,Phoenix,E,1,800
20130320,AZ,Phoenix,F,4,800
""")

df = pd.read_csv(incsv, index_col=['Date'], parse_dates=True)

df
          State City  Tools Size y
Date
2013-03-20  AZ  Phoenix A   4   1000
2013-03-20  AZ  Tempe   B   4   1100
2013-03-20  NY  NYC     C   1   900
2013-03-20  NY  NYC     C   2   1300
2013-03-20  NY  Albany  D   1   800
2013-03-20  AZ  Phoenix E   1   800
2013-03-20  AZ  Phoenix F   4   800

I'm attempting to calculate what % of the State/City subtotal each size of tool makes up. My next step is:
dftest=pd.pivot_table(df,index=['State'],columns=['City','Size'],values="y",aggfunc='count',margins=True)
test=dftest.stack('City').stack('Size')
test

State  City     Size
AZ     All              4.0
       Phoenix  1       1.0
                4       2.0
       Tempe    4       1.0
NY     Albany   1       1.0
       All              3.0
       NYC      1       1.0
                2       1.0
All    Albany   1       1.0
       All              7.0
       NYC      1       1.0
                2       1.0
       Phoenix  1       1.0
                4       2.0
       Tempe    4       1.0
dtype: float64

I want my output to be
State  City     Size    Count PCT
AZ     All              4.0   1
       Phoenix  1       1.0   .25
                4       2.0   .5
       Tempe    4       1.0   .25
NY     All              3.0   1
       Albany   1       1.0   .333
       NYC      1       1.0   .333
                2       1.0   .333

I was thinking about trying to iterate over the rows, find the "All"s and iterate again to create a series with the results but there has got to be a much less hacky/more performant way to accomplish this. Thanks!

A: test = test.to_frame()
test['PCT'] = test.groupby(level=0).transform(lambda x: x/x.max())

output:
                      0       PCT
State City    Size
AZ    Phoenix 1     1.0  0.250000
              4     2.0  0.500000
      Tempe   4     1.0  0.250000
      All           4.0  1.000000
NY    Albany  1     1.0  0.333333
      NYC     1     1.0  0.333333
              2     1.0  0.333333
      All           3.0  1.000000
All   Albany  1     1.0  0.142857
      NYC     1     1.0  0.142857
      Phoenix 1     1.0  0.142857
      NYC     2     1.0  0.142857
      Phoenix 4     2.0  0.285714
      Tempe   4     1.0  0.142857
      All           7.0  1.000000


text:
Q: Can't set envs for postgres image using docker-compose i set environment from .env file.
When i login in the container and try exec psql -U admin -d art.
It returns:
psql: error: connection to server on socket "/var/run/postgresql/.s.PGSQL.5432" failed: FATAL:  database "art" does not exist

Although echo $POSTGRES_DB prints art
 db:
    build:
      context: ./
      dockerfile: Dockerfile.db
    volumes:
      - ./data/db:/var/lib/postgresql/data
    ports:
      - 5432:5432
    environment:
      POSTGRES_DB: ${POSTGRES_DB} // art
      POSTGRES_USER: ${POSTGRES_USER} // admin
      POSTGRES_PASSWORD: ${POSTGRES_PASSWORD}

My Dockerfile just copy sql scripts
FROM postgres:14.1-alpine3.15

WORKDIR /sql

COPY ./migrations/* ./


text:
Q: How to search / print specific ((files, folders or files with extension)) import os

for r,d,f in os.walk("c:\"):
    for files in f:
        if files == "abc.txt":
            print os.path.join(r,files)

I saw someone post the code up top and it worked very well for me, is there a way to create a list of words and append it to the " for " loop so that the loop goes through all the words to try and find matching results? and once one of the words in the list has been found, what is the proper syntax to print the full location path of the file found
Thanks

A: You can't add list to existing for-loop - you have to add another for-loop
import os

list_of_words = ['abc.txt', 'script.py']

for root, dirs, files in os.walk("c:"):
    for filename in files:
        for word in list_of_words:
            if word == filename:
                print( os.path.join(root, filename) )

And if you want to see partial words then you may need in instead of ==
            if word in filename:

If filename may have upper case or lower case name then you can also use .lower() or .upper() to compare it
            if word.lower() in filename.lower():

And if you want check word at the end of filename (ie. to check only extensions)
            if filename.lower().endswith( word.lower() ):

endswith() may get even list or tuple
            if filename.lower().endswith( [".jpg", ".png", ".gif"] ):

Similar method .startswith()
            if filename.lower().startswith( ["image_", "dimg_"] ):


text:
Q: How secure is IPsec w/RSA but without XAuth username/passwords? I'm using pfSense 2.0 and have an IPsec VPN configured (which uses the Raccoon IPsec daemon).
I'm connecting to the VPN using my iPhone (iOS 5).
However, the iPhone doesn't allowing saving of XAuth username and passwords.
How secure is it to remove XAuth authentication (ie. blank password) and only use RSA certificate authentication?

A: Sorry, this isn't answering your question of "how secure ...", but this might side-step your problem.
Have you tried xauth_psk_server and putting "save_passwd on;" into your mode_cfg section of racoon.conf?
This let my old iPod (Version 4.2.1) cache an XAuth username & password.  Here is my racoon.conf:
path pre_shared_key "/etc/racoon/psk.txt";

listen {
    adminsock disabled;
}

remote anonymous {
    exchange_mode aggressive;
    my_identifier address;
    proposal_check strict;
    generate_policy on;
    nat_traversal on;
    dpd_delay 20;
    ike_frag on;
    proposal {
        encryption_algorithm aes;
        hash_algorithm sha1;
        authentication_method xauth_psk_server;
        # pre_shared_key
        # rsasig (for plain RSA authentication)
        # gssapi_krb
        # hybrid_rsa_server hybrid_rsa_client
        # xauth_rsa_server xauth_rsa_client
        # xauth_psk_server xauth_psk_client
        dh_group modp1024;
    }
}

mode_cfg {
    network4 10.99.99.2;
    pool_size 253;
    netmask4 255.255.255.0;
    auth_source pam;
    # dns4 10.99.99.1;
    # wins4 10.0.12.1;
    banner "/etc/racoon/motd";
    pfs_group 2;
    # Allow client to cache password:
    save_passwd on;
    split_dns "ad5ey.net";
    split_network include 10.99.99.0/24;
}

sainfo anonymous {
    pfs_group 2;
    lifetime time 1 hour;
    encryption_algorithm aes;
    authentication_algorithm hmac_sha1;
    compression_algorithm deflate;
}

With my iPod (and my MacBook), I select "Cisco IPSec" for the VPN type, and then invent a group name and shared secret for your psk.txt.
# Example psk.txt
coolgroup   bigsecret

Now the question is, How secure is xauth_psk with a shared group secret?  (This might not be secure for a corporate environment, because other employees might recycle the group shared secret to spoof being the vpn server to other employees and then sniff usernames and passwords... (runonsentencefun) but it's fine enough for my iPod when I don't share my group with anyone.)

A: XAuth is an additional (i.e. a second) authentication round. It is usually username/password given by one side only. If both side authenticate beforehand via certificates (both means: server certificate and client certificate), no additional XAuth is needed at all.
XAuth is usually used like HTTPS websites often are: the client usually authenticates the webserver via certificates, and the server recognizes you via username/password. I.e. the first round is certificate (from one side) and the second round username/password from the other side.
Have you ever used client certificates with your browser?? If you have, why would you still need to enter a password on websites? – Maybe because the framework of that specific website is not adapted to client certificates yet. – Same is true with IPsec clients: can they actually do without XAuth??
But anyway: is it secure? Yes. – Unless you believe 2 condoms is better than 1.


text:
Q: Get value of textbox with java sciprt c#, When the text is in runat="server" i am building a website for my clients, in my site they need to request an help form.
in this form i will like to check the textboxes in java sciprt code.
but, when i am trying to do this code:
var nameeee = document.getElementById("name");
on this textbox:
<asp:TextBox ID="name" runat="server" CssClass="name"></asp:TextBox>

its just not working... i am trying to get the value of it but its seemds to not work. i am gussing its because the ruant="server", i need it so i can call it from my C# code.
Any help?
Thanks,
(Sorry for bad english)
Alon.

A: To get value:
var nameeee = document.getElementById("<%=name.ClientID%>").value;

A: Have this instead:
var nameeee = document.getElementById("<%=name.ClientID%>");

This will give you the actual ID of the textbox.


text:
Q: Program fails in Python 2.7.8 but runs in Python 3.4.1 I've ran this code using Python 3.4.1 and it works, but if I use Python 2.7.8 it fails, why?
i=1
while i<10:
    for x in(1,2,3,4,5,6,7,8,9):
        print (i*x,'\t',end='')
        if x==9:
            print('\n')
            i=i+1

A: In fact, print is a function in Python 3 but not Python 2. In Python 2, you need to remove () and end.  As an alternative, you can add from __future__ import print_function into your code in Python 2 to use print as in Python 3.

A: Amongst the breaking changes between Python versions 2.x and 3.x is that print is a function - in 2.x it was a statement. You have two options, either use:
from __future__ import print_function

at the top of your script to use the new function in 2.x, or have a separate 2.x version with the old syntax:
print '{0}\t'.format(i * x), # note trailing comma to suppress newline

The former is much easier, in my opinion.
Note that the default sep equivalent for the 2.x print statement is a single space, so the naïve version
print i * x, '\t',

would include an extra space before the tab. Also, note that your 3.x version can be slightly simpler:
print(i * x, end='\t')


text:
Q: How to take virtual machines state/back-up automatically? My problem is,

I want to take state/back-up of those 4 virtual machines(VMs)
  automatically after every 2 days.

I am using Oracle virtual box(VB). I just want to know
Is there any way or facility to achieve above thing?

A: Like pretty much everything else you can do with the VirtualBox GUI you can also do with the commandline tool VBoxManage.
It is part of your installation. The command you're most likely looking for is
VBoxManage snapshot 'MyVM' take "Snapshot of MyVM on $(date)"
snapshot                  <uuid|vmname>
                          take <name> [--description <desc>] [--live] |
                          delete <uuid|snapname> |
                          restore <uuid|snapname> |
                          restorecurrent |
                          edit <uuid|snapname>|--current
                               [--name <name>]
                               [--description <desc>] |
                          list [--details|--machinereadable]
                          showvminfo <uuid|snapname>

I tested it and it worked like a charm.
If you want to run it every 2 days, then cron would probably be your best option.
An entry like
0 0 */2 * * VBoxManage snapshot 'MyVM' take "Snapshot of MyVM on $(date)".

Inserted into your crontab will likely do the job (I did not test this). Taken from here.


text:
Q: I am trying to write VBA code that will remove all rows after the last row of data but only within a certain range of rows I cannot find a good solution that will only delete rows after the last row of data but stops at a certain row.  After row 3000 I have some legal language that needs to stay.  So, I only want to delete all rows from the last line to row 3000.  I have tried this:
On Error Resume Next
Range("A5:A3000").Select
Selection.SpecialCells(x1CellTypeBlanks).EntireRow.Delete

But it is not deleting the rows, probably because it is not identifying blank cells correctly.


text:
Q: What is an example of an embedding which is not proper? An embedded submanifold is an immersed submanifold for which the inclusion map is a topological embedding. A properly embedded submaniold is one which is embedded and the inclusion map is proper. There are many classical examples of one-to-one immersions which are not emeddings e.g. a line of irrational slope on the 2-torus. The assiciated inclusion map in this case is obviously not proper, but I am having trouble thinking of an embedded submanifold which is not properly embedded. There are examples when the ambient manifold is not Hausdorff, for instance, but can someone think of an example when both manifolds are well behaved?

A: Think of the embedding $\mathbb R^n\to\mathbb S^n$, which image is $\mathbb S^n\setminus \{N\}$. Then, for any compact neighborhood $C$ of $N$ in $\mathbb S^n$, the inverse image of $C$ is not a compact space.


text:
Q: REJECT vs DROP when using iptables Is there any reason why I would want to have
iptables -A INPUT -j REJECT

instead of
iptables -A INPUT -j DROP

A: If you're trying to hide your machine's existence entirely, -j DROP is appropriate.  For example, you might use this to implement a blacklist.
If you're trying to hide the fact that a port is open, you should mimic the behavior that would occur if the port was not open:

*

*TCP: -p tcp -j REJECT --reject-with tcp-reset

*UDP: -p udp -j REJECT --reject-with icmp-port-unreachable
If a port scanner sees that a few ports are dropping packets while most are rejecting them, it can assume the dropped packets are on ports that are open but hidden.

A: The difference is that the REJECT target sends a reject response to the source, while the DROP target sends nothing.
This can be useful e.g. for the ident service. If you use REJECT then the clients doesn't need to wait for timeout.
More about this: http://www.linuxtopia.org/Linux_Firewall_iptables/x4550.html

A: Despite of lots of correct answers, just my two cents:
Here is a short PoC FW.IDS-DROP-vs-REJECT of me to the subject as regards the rules for ban-system (firewall, IDS, etc).
Shortly:

*

*DROP can be used for recidive intruders, if banning all ports (so looks like the server is down on the intruder side)

*REJECT --reject-with tcp-reset is the best choice for multi-port banning, because it seems to behave as a real closed port

*if some ports are answering (intruder knows that the host is alive), DROP and REJECT (without tcp-reset) will give the intruder a "signal" that something blocking is there (so that could stimulate him to continue the "attack" in hope to provide required data at some point)

A: I see lots of conflicting answers here and given this is the first article in Google with the right keywords; here is the correct explanation.
It's simple: DROP does nothing at all with the packet. It does not get forwarded to a host, it does not get answered. The manpage of IPtables says it drops the packet on the floor, i.e. it does nothing with the packet.

REJECT differs to DROP that it does send a packet back, but the answer is as if a server is located on the IP, but does not have the port in a listening state. IPtables will sent a RST/ACK in case of TCP or with UDP an ICMP destination port unreachable.

A: As a general rule, use REJECT when you want the other end to know the port is unreachable' use DROP for connections to hosts you don't want people to see.
Usually, all rules for connections inside your LAN should use REJECT. For the Internet,  With the exception of ident on certain servers, connections from the Internet are usually DROPPED.
Using DROP makes the connection appear to be to an unoccupied IP address.  Scanners may choose not to continue scanning addresses which appear unoccupied.  Given that NAT can be used to redirect a connection on the firewall, the existence of a well known service does not necessarily indicate the existence of a server on an address.
Ident should be passed or rejected on any address providing SMTP service.  However, use of Ident look-ups by SMTP serves has fallen out of use.  There are chat protocols which also rely on a working ident service.
EDIT:  When using DROP rules:
 -  UDP packets will be dropped and the behavior will be the same as connecting to an unfirewalled port with no service.
 - TCP packets will return an ACK/RST which is the same response that an open port with no service on it will respond with.   Some routers will respond with and ACK/RST on behalf of servers which are down.
When using REJECT rules an ICMP packet is sent indicating the port is unavailable.

A: Usually, you want to ignore probes from attackers to certain ports, by which I mean you do not want to send back 'connection refused'. 'Connection refused' means: 'there is a server here', and possibly gives away more information, whereas dropping a packet doesn't give away clues about software versions, possible vulnerabilities or even the fact that a server is listening at you IP.
The above is one of the main reasons to use DROP instead of REJECT.

A: Yes, using DROP is pointless. Use REJECT.
Even when the rule says "DROP" the system still replies to an incoming SYN with a TCP RST/ACK - which is the default behavior for ports with no services running. (tcpdump et al doesn't log this.)
If a service is running, the SYN is met with TCP SYN/ACK.
Because the DROP does not respond as per normal with a TCP SYN/ACK, but with a RST/ACK instead, your DROP rule will advertise your firewall and port-scanners will know that you are firewalling something and might keep hammering you in the hopes of catching your firewall down.
This is now nmap can report "filtered" instead of "closed" for example:
$ nmap localhost

Starting Nmap 6.40 ( http://nmap.org ) at 2018-03-14 00:21 SAST
Nmap scan report for localhost (127.0.0.1)
Host is up (0.0000060s latency).
Not shown: 986 closed ports
PORT     STATE SERVICE
21/tcp   open  ftp
53/tcp   open  domain
80/tcp   open  http

Nmap done: 1 IP address (1 host up) scanned in 1.60 seconds

$ iptables -I INPUT -p tcp --dport 1111 -j DROP
$ nmap localhost

Starting Nmap 6.40 ( http://nmap.org ) at 2018-03-14 00:21 SAST
Nmap scan report for localhost (127.0.0.1)
Host is up (0.0000060s latency).
Not shown: 986 closed ports
PORT     STATE SERVICE
21/tcp   open  ftp
53/tcp   open  domain
80/tcp   open  http
1111/tcp filtered lmsocialserver

Nmap done: 1 IP address (1 host up) scanned in 1.60 seconds

$ iptables -D INPUT 1

As such, the only "invisible" firewalling setup is one where a dedicated device sits between your devices and only selectively forwards ports.
If you really want to mess with the basic scanners, you can TARPIT tcp connections, which sets the TCP Window to 0 so that no data can get transferred after the connection is opened, ignoring requests to close the connection, meaning the scanner has to wait for the connection timeout to occur, if it wants to be sure. But it's trivial for an attacker to detect this and make his timeout very short.
All things considered, you're probably best off just using REJECT - or putting a dedicated port forwarding device between your server and the internet.
Or just running services on your internet-facing machines that do not require firewalling.
Generally REJECT is best for web servers, as whatever service is trying to access it (probably more often than not, you) will quickly get a response and users or other services won't be kept waiting wondering if there's a network outage.


text:
Q: Recover deleted entries I am using SugarCRM SOAP Web Service.
I can delete an entry from SOAP by setting

    'id'=BeanID
    'deleted'=1

But I can't set back as

'deleted'=0

I can do from MySQL(phpMyAdmin) but not from SOAP Web Service.
What is going wrong here?

A: You are doing anything; this is a bug with the call.
Please vote on the below bug to get it fixed faster inside of Sugar
http://www.sugarcrm.com/support/bugs.html#issue_58986

A: I had the same issue, found solution just few moments ago. I didn't test it properly but it seems to work for now..
'sugar_root'/include/database/DBManager.php
Change 1
    $where .= " AND deleted=0";

to
    //$where .= " AND deleted=0";

Change 2
    return "SELECT * FROM ".$bean->getTableName()." $where AND deleted=0";

to
   //return "SELECT * FROM ".$bean->getTableName()." $where AND deleted=0";
    return "SELECT * FROM ".$bean->getTableName()." $where";

Change 3
    if($fieldDef['name'] == 'deleted' && empty($bean->deleted)) continue;

to
    //if($fieldDef['name'] == 'deleted' && empty($bean->deleted)) continue;

If anybody find any issues after following changes, pls post it here.
Cheers


text:
Q: powershell code that first checks the service on server and displays server name service name and boot type how can i write a powershell code that first checks the service on server and displays server name service name and boot type! then if it is on automatic, it switches manually and efer it shows the status again
$servicename = 'spooler'
$server = 'server2'
$G$GetStatus= Get-Service -DisplayName $servicename -ComputerName $server | Select-Object -ExpandProperty StartType
Write-host "$GetStatus" -ForegroundColor red
Write-host "$servicename på $server" -ForegroundColor Green

if ($GetStatus.StartType -eq 'Automatic') {
$GetStatus | Set-Service -StartupType Manual
}
}
}
Write-output "$GetStatus" -ForegroundColor red
Write-output "$servicename på $server" -ForegroundColor Green

A: here's an example of what i mean by NOT throwing out the object in favor of one value from one property of the object.
$servicename = 'spooler'
$server = 'LocalHost'

$ServiceInfo = Get-Service -Name $servicename -ComputerName $server

Write-host $ServiceInfo.StartType -ForegroundColor red
Write-host "$servicename på $server" -ForegroundColor Green
''

if ($ServiceInfo.StartType -eq 'Automatic')
    {
    $ServiceInfo |
        Set-Service -StartupType Manual -WhatIf
    }

''
Write-output $ServiceInfo.StartType
Write-output "$servicename på $server"

output ...
Automatic
spooler på LocalHost

What if: Performing the operation "Set-Service" on target "Print Spooler (spooler)".

Automatic
spooler på LocalHost

i have not tested it on my system, but the -WhatIf seems to indicate it will work. i have only the one system to use ... and am unwilling to muck around with it. [grin]
notes ...

*

*kept the entire object instead of only the value of the StartType property

*addressed the desired property by its name $ServiceInfo.StartType

*used the entire object to tell Set-Service what to work on

A: This should do what you want:
$serviceName = "spooler"
$server = "server2"

Get-Service -Name $serviceName -ComputerName $server |
        ForEach-Object {}{
            $_ | Format-Table Name, Status, StartType -AutoSize

            if ($_.StartType -eq "Automatic")
            {
                Set-Service -InputObject $_ -StartupType Manual
            }
        }{Get-Service -Name $serviceName -ComputerName $server | Format-Table Name, Status, StartType -AutoSize}

A: I would probably do something like this:
$server = 'server2'
$servicename = 'spooler'
$services = Get-Service -ComputerName $server -Name $servicename
# show what was found
Write-Host "`r`nService(s) named '$servicename' on '$server'" -ForegroundColor Yellow
$services | Format-Table DisplayName, Name, ServiceName, Status, StartType, MachineName -AutoSize

# next change the StartupType for any service found that is set to 'Automatic'
$services | Where-Object { $_.StartType -eq 'Automatic' } | ForEach-Object {
    Write-Host "Setting StartupType for service '$($_.Name)' on computer '$($_.MachineName)' to 'Manual'" -ForegroundColor Green
    $_ | Set-Service -StartupType Manual }

# show what has changed
Get-Service -ComputerName $server -Name $servicename |
Format-Table DisplayName, Name, ServiceName, Status, StartType, MachineName -AutoSize

If you do not know the exact name of the service, you may better use Get-Service with a partial name.
You can do this with the like operator. In that case, add asterikses around the servicename and
change the lines $services = Get-Service -ComputerName $server -Name $servicename so it becomes:
$servicename = '*spooler*'
$services = Get-Service -ComputerName $server | Where-Object { $_.Name -like $servicename }