Q: Detecting Gameobjects under Linerenderer I have made a LineRenderer and I added an EdgeCollider2D to it.
Now I am trying to detect all GameObjects below my LineRenderer.
The objects below have Colliders as well.

*

*LineRenderer starts with first mouse position and ends with last mouse position

*LineRenderer has an EdgeCollider2D

*I need to get value from all objects which are under LineRenderer

*Project is in 2D

What I tried:

*

*Use Raycast,but using raycast I am getting values from object around too.
And i want only to get values of Gameobjects under Linerenderer not values from All gameobjects touched by mouse

*Or if it is Possible to get gameobjects between 2 positions
*So basicaly i need to get values from 10 of 100 objects,which are all together.F.E i have 100 mushrooms placed together,and every mushroom have its int value which is different.
So moving my mouse around i need to select only this 10 mushrooms and take its value.
Here is my code so far
RaycastHit2D[] rays = Physics2D.RaycastAll(mousePos, lr.transform.forward);
Debug.DrawRay(new Vector3(startMousePosition.x, startMousePosition.y, 0), Vector3.up, Color.red, 5);
for (int i = 0; i < rays.Length; i++)
{
    RaycastHit2D ray = rays[i];

    if (isTOuched)
    {
        if (ray.collider.gameObject.tag == "Player")
        {
            if (objektiOdRaycast.Contains(ray.collider.gameObject) == false)
            {
                objektiOdRaycast.Add(ray.collider.gameObject);
                for (int t = 0; t < objektiOdRaycast.Count; t++)
                {
                    tekst = objektiOdRaycast[t].GetComponent < GridSquare().tekst;
                }

                words.tekstSlova.text += tekst;
            }
        }
    }
}

A: The problem with a Raycast is: It only checks one single ray direction. That makes no sense in your use case.
You probably want to use Physics2D.OverlapCollider

Gets a list of all Colliders that overlap the given Collider.

and do e.g.
// Reference via the Inspector
public LineRenderer theLine;
// configure via the Inspector
public ContactFilter2D filter;

private Collider2D lineCollider;

private readonly List<Collider2D> overlaps = new List<Collider2D>();
private readonly HashSet<Collider2D> alreadySeen = new HashSet<Collider2D>();

private void Awake()
{
    // as fallback assume same GameObject
    if(!theLine) theLine = GetComponent<LineRenderer>();

    lineCollider = theLine.GetComponent<Collider2D>();
}

public void GetOverlappingObjects()
{
    var amount = Physics2D.OverlapCollider(lineCollider, filter, overlaps);

    for(var i = 0; i < amount; i++)
    {
        var overlap = overlaps[i];

        if(alreadySeen.Contains(overlap)) continue;

        alreadySeen.Add(overlap);

        var overlapObject = overlap.gameObject;

        // These checks are actually kind of redundant
        // the second heck for the component should already be enough
        // instead of the tag you could rather use a Layer and configure the filter accordingly
        if (!overlapObject.CompareTag("Player")) continue;
        if (!overlapObject.TryGetComponent<GridSquare>(out var gridSquare)) continue;

        words.tekstSlova.text += gridSquare.tekst;
    }
}


Q: Can session be maintained if we turn off javascript in the browser? So recently i was asked this question in an interview that "Can you manage session in MVC .NET if javascript is turned off in the browser"?
I replied "Yes we can" but I am not very sure and I need some assistance on this topic.

A: Sessions, SessionIDs and Session state are managed by the .NET server (by default), not by the client. Turning off JavaScript at the client won't affect the server.
Quote from MS Docs:

The in-memory [default session state] provider stores session data in the memory of the server where the app resides.

A: Session is stored on server side and session id is stored on client side, and javascript don't impact the session. So session will work if you turn off the javascript


Q: reliable way to get line / column number from javascript Error? I have a little embedded JS editor on my site and when the code inside it throws an error I'd like to underline where the error is happening. The error stack trace looks like this:
err ReferenceError: a is not defined
    at isNumber (eval at handle_message (about:srcdoc:11:7), <anonymous>:5:5)
    at Array.filter (<anonymous>)
    at removeNumbers (eval at handle_message (about:srcdoc:11:7), <anonymous>:13:15)
    at eval (eval at handle_message (about:srcdoc:11:7), <anonymous>:16:28)
    at handle_message (about:srcdoc:14:7)

In this case my desired solution would return { line: 5, column: 5 } (the first entry of the stack trace)
My first instinct is just to do some text parsing + regex to get the last 2 numbers from the second line. This seems like a super unreliable solution though, and I'm not sure if stack traces will follow this format for all types of errors and on all browsers.
Is there a more reliable way to extract the error location from a javascript Error object?

A: There is a built-in way to get the line and column number in JavaScript, but unfortunately, it isn't supported in (literally) all browsers. The only browser that supports it is Firefox.
Right now, the best thing you can do is just get it from the browser console.

However, to get it from the Error object, you can first wrap your code in a try/catch statement.
try {
  a();
} catch (err) {
  console.log(err); // ReferenceError: a is...
}

Then, you can get the line and column numbers from it. Beware; it's only supported in Mozilla!
console.log(err.lineNumber, err.columnNumber); // 5 5

The only properties that aren't non-standard in the Error object is the name and message.

In conclusion, even though there is a built-in way to get the line and column number in JavaScript, it is non-standard and only supported in Firefox.
The best way to get it is to get it from the browser console (or to get it from third-party libraries, if possible).


Q: ggplot - add title based on the variable in the dataframe used for plotting This is a follow-up to my previous question where I asked how to use ggplot inside of purr::map.
I have a dataframe that looks like this:
I have a dataframe named data which looks like this:
Country Year Incidence
USA     1995 20000
USA     2000 23000
UK      1995 16000
UK      2000 22000

I am using this code to make a year/incidence plot split by country (each country has a separate plot, not one single, but faceted plot for all countries).
list_plot <- data %>%
               group_split(Country) %>%
               map(~ggplot(., aes(x = Year, y = Incidence) ) +
                       geom_line()+ geom_point())

Now I would like to put the name of the country in the title of each of the graphs. I tried the following:
list_plot <- data %>%
               group_split(Country) %>%
               map(~ggplot(., aes(x = Year, y = Incidence) ) +
                       geom_line()+ geom_point() + labs(title = Country))

But it's not working (it's telling me the object 'Country' is not found). How can I achieve this?

A: Using .$Country instead of Country should fix it
data = data.frame(Country = c('USA','USA','UK','UK'),
                  Year = c(1995,2000,1995,2000),
                  Incidence = c(20000,23000,16000,22000))

list_plot <- data %>%
  group_split(Country) %>%
  map(~ggplot(., aes(x = Year, y = Incidence) ) +
        geom_line()+ geom_point() + labs(title = .$Country))


Q: masstransit handle/consume messages in batches I have a clear understanding of consuming messages: http://docs.masstransit-project.com/en/latest/usage/consumer.html
these implementations only handle ONE message at a time.
I need to handle multiple messages at a time, in bulk, in batches.

A: Mass Transit now has an experimental feature to process individual message's in a batch.
Configure your bus:
_massTransitBus = Bus.Factory.CreateUsingRabbitMq(
                cfg =>
                    {
                        var host = cfg.Host(new Uri("amqp://@localhost"),
                            cfg =>
                                {
                                    cfg.Username("");
                                    cfg.Password("");
                                });

                        cfg.ReceiveEndpoint(
                            host,
                            "queuename",
                            e =>
                                {
                                    e.PrefetchCount = 30;
                                    e.Batch<MySingularEvent>(
                                        ss =>
                                            {
                                                ss.MessageLimit = 30;
                                                ss.TimeLimit = TimeSpan.FromMilliseconds(1000);
                                                ss.Consumer(() => new BatchSingularEventConsumer());
                                            });
                                });
                    });

And Create your Consumer:
public class BatchSingularEventConsumer: IConsumer<Batch<MySingularEvent>>
{
    public Task Consume(ConsumeContext<Batch<MySingularEvent>> context)
    {
         Console.WriteLine($"Number of messages consumed {context.Message.Length}");
         return Task.CompletedTask;
    }
}

You can configure your Batch with a Message Limit and a Time Limit.
I suggest reading Chris Patterson's issue on the matter Batch Message Consumption especially the part regarding prefetch

The batch size must be less than or equal to any prefetch counts or concurrent message delivery limits in order reach the size limit. If other limits prevent the batch size from being reached, the consumer will never be called.

Batch consumption is also documented on the MassTransit website.

A: As it turns out, today you can do this:
public class MyConsumer : IConsumer<Batch<MyMessage>>
{
    public async Task Consume(ConsumeContext<Batch<MyMessage>> context)
    {
        ...
    }
}


Q: Hacked, Extension Stolen - How To Recover Quickly? My Google account was hacked, and my popular (~200k users) extension was stolen and transferred to a malicious account. The extension was updated with new code and my users are being automatically updated.
I've tried to contact Google 3 different ways, but no response so far. What's the best way to quickly shut down the stolen extension, and get ownership back to me?
I don't want the extension listing and id to be just deleted, because I want to retain all my existing users and thousands of positive reviews.
Has anyone had success with a particular method of contacting Google? Any advice would be appreciated. Thanks.
Matt Kruse
Social Fixer


Q: How to stop one specific user to delete his account in Ruby on Rails? I have this code in /views/devise/registrations/edit.html.erb
Cancel my account
<%= link_to "Cancel my account", registration_path(resource_name), :data => { :confirm => "Are you sure?" }, :method => :delete %>.

which allows the logged in user to delete his account. Now I do NOT want one user with id=223 to have this permission/link. How can I do this ? I am not not sure the below cod in edit.html.erb file will work (or is there any better way to do it?)
EDIT - Ok this below code is working but how to do it through controller ?
<% if current_user.id != 223 %>
Cancel my account
    <%= link_to "Cancel my account", registration_path(resource_name), :data => { :confirm => "Are you sure?" }, :method => :delete %>.
<% end %>

A: Controller has nothing to do with a link being displayed or not. However you can disable the deletion in the controller by checking the same condition.
Anyways, you should create at least a model property for this. This id hardcode thingy is not nice, so hide it at least and make it not being repeated.
model User
  ...

  def can_delete_account?
    id != 223  # ugly hack
  end

end


Q: Calling a fun with reified type parameter if you just have a KClass object? One can only use reified type parameters with inline functions. So if I want such a parameter for a class I need a trick like this:
class Foo<T : Any>(private val clazz: KClass<T>) {
    companion object {
        inline fun <reified T: Any> create() = Foo(T::class)
    }
}

I can then create instances of Foo like this:
val foo = Foo.create<Bar>()

Within Foo I have access clazz but my question is can I then use clazz when I need to call methods that require a reified type parameter`?
E.g. within Foo I'd like to add a method like this:
fun print(list: List<Alpha>) {
    list.filterIsInstance<T>().forEach { print(it) }
}

But as far as I can see there's no way to get from clazz to something I can use as a type parameter here.
And yes, I know there's a form of filterIsInstance that takes a Class so I can do:
list.filterIsInstance(clazz.java).forEach { print(it) }

However many libraries contain methods where both forms (explicit class parameter and reified type parameter) are not provided.
E.g. the Jackson Kotlin Extensions.kt. Actually this isn't a great example as the non-reified equivalents are all one-liners but this isn't always the case - then you end up unpacking the implementation of the reified-type-parameter method into your code.

A: no, because those functions are inline, they are inlined at compiletime
and a Class or KClass is using reflection at runtime
there are some tricks that you can do.. like with the companion class, but that does nto need the KClass<T> at all.. anything else that provides a generic argument of T would work just as well for the reified type info
PS: reflection also cannot help you reliably because inline functions do not really exist at runtime, as explained by their modifier inline

A: Unless I am missing something, everything you can do with T in a function with reified T can be translated to a use of KClass: e.g. x is T becomes clazz.isInstance(x), x as T becomes clazz.cast(x), calls of other functions with reified type parameters are translated recursively, etc. Since the function has to be inline, all APIs it uses are visible at the call site so the translation can be made there.
But there's no automatic way to do this translation, as far as I know.


Q: SUM without duplicated row with GROUP BY SELECT SUM(man+woman) AS over65,
       a.cod,
       a.city,
       b.cod2
  FROM a LEFT JOIN
         b ON b.cod2 = a.cod
 GROUP BY cod

--
table  a
cod    city
28001  rome
28001  rome
28002  milan
28002  milan

table b
cod2  age man woman
28001  65 156   220
28001  66 250   280
28001  67 350   483
28002  65 556   524
28002  66 650   683
28002  67 450   342

result Is:
cod    city  over65
28001  rome    3478
28002  milan   6410

instead Of :
cod     city   over65
28001   rome     1739
28802   milan    3205

What should i do for this?
thanks

A: Use a subquery to get rid of the duplicates in table a.
SELECT SUM(man+woman) AS over65,
       a.cod,
       a.city,
       b.cod2
  FROM (SELECT DISTINCT cod, city
        FROM a) AS a
  LEFT JOIN
         b ON b.cod2 = a.cod
 GROUP BY a.cod

I also wonder why table a has those duplicates in the first place. If city is always the same for a given cod, the data is not properly normalized.


Q: Why is readxl so much faster than xlsx package? We used the two packages xlsx and readxl and now it seems, readxl is much faster. Why? As long-term stability is important to us, I would then always use the readxl package.
Reproducible example:
path <- "C:/Temp/"
name <- "myexcel.xlsx"
filename <- paste0(path, name)
dim <- c(14000, 30)
rands <- matrix(data = runif(n = dim[1]*dim[2], min = 0, max = 1), nrow = dim[1], ncol = dim[2])
df <- as.data.frame(rands)
writexl::write_xlsx(x = df, path = filename, col_names = TRUE)
# xlsx::write.xlsx(x = df, file = filename, sheetName = "Sheet1")
# Does not give a result

mytable <- readxl::read_excel(path = filename, sheet = "Sheet1")
# mytable2 <- xlsx::read.xlsx(file = filename, sheetName = "Sheet1")
# Does not give a result


Q: Quick Launch menu spacing the Spacing between the links on the Quick Launch menu is too much, need to condense the spacing, of course, I see no option, the search turns up modify CSS, I have never done the CSS modification before, and need a step by step, I scared of messing it up completely and that would be bad!!!!
Please help and talk very much down to me and explain what i need to do

A: As you said, if you want to modify the spacing between the links on the "Quick Launch" menu, you need to modify the CSS. However, modifying CSS is only effective in classic mode, not in modern mode.
More information, please refer to this article.
Note:
In SharePoint Designer 2013, please copy seattle.master.

A: I assume we are talking about the quick launch navigation in the classic experience?
Instead of modifying the master page which is usually not recommended you could add alternate CSS to your page.
Here are the steps required:

*

*Upload the CSS file to the Site Assets or to another location on your
SharePoint site.

*Click on the settings gear and select Site settings.

*In the Look and Feel group, click on the link 'Master page'.

*Expand 'Alternate CSS URL'.

*Select the 'Specify a CSS file' option and browse to the location
where you uploaded your CSS file.

*Check the box for subsite inheritance if you want all subsites to use
the CSS file.

*Click OK.
Reference: https://www.kalmstrom.com/Tips/SharePoint-Online-Course/Publishing-Infrastructure-Alternate-CSS-URL.htm#:~:text=Add%20a%20custom%20CSS%20to%20a%20site&text=Click%20on%20the%20settings%20gear,you%20uploaded%20your%20CSS%20file.
I understand you need a step-by-step guide to implement the CSS as well, but unfortunately I cannot provide this until I have a laptop at my disposal.


Q: How do we calculate the Right and Left Hand Limit of 1/x? I am confused regarding one sided limits and how to calculate it.
For Example:
$$\lim_{x\to 0}\frac{1}{x}\quad\text{does not exist}$$
How can I validate that $\lim\limits_{x\to 0^+}\frac{1}{x}$ or $\lim\limits_{x\to 0^-}\frac{1}{x}$ exists?
I am pretty certain that the limits do exist because if we take a positive value which is small $0.0000000\dots1$ we will get a very big positive limit value.  And the same for the negative value.  I know that in this case RHL$\ne$LHL.
I hope somebody can help me figure this one out. Thank you.
Sorry could not write down the equations, hope my explanation is clear enough.

A: $\mathbf{Definition} $:
$$ \boxed{ \lim_{x \to a^+ } f(x) = \infty } $$
means that for all $\alpha > 0$, there exists $\delta > 0$ such that if $ 0<x -a < \delta$, then $f(x) > \alpha$
$\mathbf{Example} $:
$$ \lim_{x \to 0^+} \frac{1}{x} = \infty $$
We use the definition to establish this fact. In other words, for a given $\alpha > 0$, we need to find a $\delta > 0$  such that if $0< x < \delta $, then $\frac{1}{x} > \alpha $
Notice $$ \frac{1}{x} > \alpha \iff \frac{1}{\alpha} > x$$
Hence, if we select $\delta = \frac{1}{\alpha } $, we will achieve our desired result.

A: To say that $\frac1x \to \infty$ as $x \to 0^+$ (the plus means goes to $0$ from the positive direction) is to say that for any large $N > 0$ I can choose a small $\epsilon > 0$ (whose choice depends on $N$) such that $0 < x < \epsilon$ implies $\frac1x > N$.  This, of course, is achieved by choosing $\epsilon = \frac1N$.
I'll leave the negative side to you, it's almost identical.

A: From a bit of intuition, you can see:
$$\lim_{x \to 0^+}(1/x) = \infty$$
$$\lim_{x \to 0^-}(1/x) = -\infty$$
Of course, this is because as the value for $x$ gets infinitesimally small, the fraction blows up.  To actually prove these limits in a rigorous fashion, however, you'd need to do the following:
For the first limit: Given any $n \in \mathbb{R}$, show that there exists an $\epsilon > 0$ such that, for all $0<x<\epsilon$, we'll have $1/x > n$.
And you'd proceed likewise for the second.


Q: Azure Automation Credentials using Azure Key Vault secrets Is there a way to create an Azure Automation Credential asset which links to an Azure Key Vault secret? Similar question for a Certificate in Azure Automation.
I want to be able to store my passwords and such all in one place, the Key Vault, so that when I change it I don't have to change it in a bunch of places.  I cannot find any documentation that indicates this is possible though.  Am I missing it?
Thank you for any suggestions....

A: You can't link a Credential asset directly to Key Vault, however it should be possible to write a script that connects to Key Vault and updates the appropriate Automation Credentials from there.
This could either be fired on a schedule, a webhook, or by picking up Key Vault events from the new Event Grid (presuming they are currently wired up)


Q: How to add label words in Microsoft Word? I need to add some words that look like labels as seen in the picture label example, so basically an enumeration of key-words. Is there a way to do this in Word?

A: Yes, you do it by inserting a rounded corner rectangle shape.
The setting is on the Insert tab. Then pull down the Shapes menu button, and in the group of rectangles, it is the second one.

A: You could try Smart Art if in the Windows version. It is on the Insert tab.


Q: Camera access in WebView in Java 8 I have a WebView in my JavaFX application that loads an HTML5 file that accesses the webcam of the local computer. It runs perfectly in Chrome and Mozilla but not in JavaFX's WebView. Is there a configuration that I need to set in order to run it in WebView? Im using Java 8u60.

A: Seems that the WebKit in WebEngine does not support it:
With the following javascript:
navigator.getUserMedia = navigator.getUserMedia || navigator.webkitGetUserMedia
        || navigator.mozGetUserMedia || navigator.msGetUserMedia || navigator.oGetUserMedia;
if (navigator.getUserMedia) {
    alert("getUserMedia supported");
    navigator.getUserMedia({video: true}, handleVideo, videoError);
} else {
    alert("getUserMedia not supported");
}

and this Java code:
    WebEngine webEngine = webView.getEngine();
    webEngine.setOnAlert(event -> System.err.println(event.toString()));

the output shows:
WebEvent [source = javafx.scene.web.WebEngine@3dd89471, eventType = WEB_ALERT, data = getUserMedia not supported]

I tried setting a confirm handler in case that the WebEngine tries to ask for permission, but that is never called.
Tried it with Java 1.8.0_66 on OSX 10.11.


Q: PHP Array combining 2 or more values together I am curious know if and how it is possible to combine 2 values of an array together instead of overriding the other. I will show you an example:
I have a form that is mapping fields to a database from a CSV file. The problem I am running into is say for example there are 2 address fields that need to be merged into 1 address field in my database. (IE: photo below)

So my problem comes when I look at the $_POST[] array. It will show that there are 2 HOME ADDRESSES Selected and import into my database with the LAST selected home-address.
How can I merge the information into 1. I hope this gives you enough information on my problem, please let me know if you need something specific.
I am dealing with all arrays, and when I post into my database it requires an Array to loop through, as I use a reflection class. I hope this makes sense...
Any light would be appreciated on this matter.
Cheers,
I appreciate the quite comments back, the problem that I have with your responses is that I can't create my inputs to be address[] as that will be dynamic and I won't know which one will be set to address and which would perhaps be set to 'phone'... I hope this new picture helps a bit in understanding.
Some of the code (Shortened):
<select name="Home_Address_1"> // name is dynamically generated from the CSV headings
  <option>...</option>
</select>
<select name="Home_Address_2"> // name is dynamically generated from the CSV headings
  <option>...</option>
</select>

A: Example of using two posted values in a single array:
<!-- HTML -->
<input name="address[]" type="text" value="111" />
<input name="address[]" type="text" value="222" />

Notice the name attributes.
// PHP
$address = $_POST['address'][0] . ' ' . $_POST['address'][1];

echo $address; // prints "111 222"

UPDATE
Before your script loops through the $_POST array, merge the fields, like so:
$preformat  = $_POST['Home_Address_1'];
$preformat .= ' ' . $_POST['Home_Address_2'];
$preformat .= ' ' . $_POST['Home_Address_3'];
$_POST['Home_Address_3'] = trim($preformat);

Then the last Home Address field contains all three.

A: Try array_merge()...http://php.net/manual/en/function.array-merge.php

A: Try array_merge with shuffle
$merged = array_merge($arr1,$arr2);
shuffle($merged);

with regards
Wazzy


Q: NHibernate : QueryOver in generic method I have this test method, I have a problem on the "List" method. I'd like use several class (all inplement IAdminDecimal). On the QueryOver, I have this error :
The type 'T' must be a reference type in order to use it as parameter 'T' in the generic type or method 'NHibernate.ISession.QueryOver()'
using (var session = sessions.OpenSession())
{
    using (var tx = session.BeginTransaction())
    {
        CurrentSessionContext.Bind(session);

        AdministrationService service = new AdministrationService(session);
        service.List<AdminDelay>();

        tx.Commit();
    }
}

The class :
public class AdministrationService
{
    private readonly ISession _session;

    public AdministrationService(ISession session)
    {
        _session = session;
    }

    public IList<T> List<T>() where T : IAdminDecimal
    {
        var res = _session.QueryOver<T>().List<T>();
        return res;
    }
}

public interface IAdminDecimal
{
    int Id { get; set; }
    int Code { get; set; }
    decimal Value { get; set; }
    bool IsDeleted { get; set; }
}

public class AdminVAT : IAdminDecimal
{
    public virtual int Id { get; set; }
    public virtual int Code { get; set; }
    public virtual decimal Value { get; set; }
    public virtual bool IsDeleted { get; set; }
}

A: Try:
public IList<T> List<T>() where T : class, IAdminDecimal


Q: Airfoil plottin by data file without court line in Spyder by python I use the AeroPython codes by Barba Group's;
#import libraries and modules needed
import os
import numpy
from scipy import integrate, linalg
from matplotlib import pyplot

# load geometry from data file
naca_filepath = os.path.join('resources', 'naca0012.dat')
with open(naca_filepath, 'r') as infile:
    x, y = numpy.loadtxt(infile, dtype=float, unpack=True)

# plot geometry
width = 10
pyplot.figure(figsize=(width, width))
pyplot.grid()
pyplot.xlabel('x', fontsize=16)
pyplot.ylabel('y', fontsize=16)
pyplot.plot(x, y, color='k', linestyle='-', linewidth=2)
pyplot.axis('scaled', adjustable='box')
pyplot.xlim(-0.1, 1.1)
pyplot.ylim(-0.1, 0.1);

and use from airfoil.com naca0012 data file  (change the name "n0012.dat" to "naca0012.dat" and delete Tittle inside the file because the program don't use the strings in data file)
in the lesson look like figure like this

but I use the code plot this includes the courtline

Something wrong but what is it?

A: The link to the airfoil database contains the coordinates of a NACA0012 in the Lednicer format, while the code in AeroPython Lesson was written for an airfoil in Selig's format.
(The Notebook compute the flow around an airfoil using a source-panel method.)
Selig's format starts from the trailing edge of the airfoil, goes over the upper surface, then over the lower surface, to go back to the trailing edge.
Lednicer's format lists points on the upper surface (from leading edge to trailing edge), then points on the lower surface (from leading edge to trailing edge).
You can load the Selig's format (skipping the header "NACA 0012 AIRFOILS" with skiprows=1 in numpy.loadtxt) as follow:
import urllib

# Retrieve and save geometry to file.
selig_url = 'http://airfoiltools.com/airfoil/seligdatfile?airfoil=n0012-il'
selig_path = 'naca0012-selig.dat'
urllib.request.urlretrieve(selig_url, selig_path)
# Load coordinates from file.
with open(selig_path, 'r') as infile:
    x1, y1 = numpy.loadtxt(infile, unpack=True, skiprows=1)

The NACA0012 airfoil here contains 131 points and you will see that the trailing edge has a finite thickness:
print('Number of points:', x1.size)  # -> 131
print(f'First point: ({x1[0]}, {y1[0]})')  # -> (1.0, 0.00126)
print(f'Last point: ({x1[-1]}, {y1[-1]})')  # -> (1.0, -0.00126)

If you do the same with the Lednicer's format (with skiprows=2 for the header), you will load 132 points (leading-edge point is duplicated) with points on the upper surface being flipped (from leading edge to trailing edge).
(That's why you observe this line in the middle with pyplot.plot; the line connects the trailing edge from the upper surface to the leading edge from the lower surface.)
One way to re-orient the points to follow Selig's format is to skip the leading edge on the upper surface (i.e., skip the duplicated point) and flip the points on the upper surface.
Here is a possible solution:
import numpy

# Retrieve and save geometry to file.
lednicer_url = 'http://airfoiltools.com/airfoil/lednicerdatfile?airfoil=n0012-il'
lednicer_path = 'naca0012-lednicer.dat'
urllib.request.urlretrieve(lednicer_url, lednicer_path)

# Load coordinates from file (re-orienting points in Selig format).
with open(lednicer_path, 'r') as infile:
    # Second line of the file contains the number of points on each surface.
    _, info = (next(infile) for _ in range(2))
    # Get number of points on upper surface (without the leading edge).
    num = int(info.split('.')[0]) - 1
    # Load coordinates, skipping the first point (leading edge on upper surface).
    x2, y2 = numpy.loadtxt(infile, unpack=True, skiprows=2)
    # Flip points on the upper surface.
    x2[:num], y2[:num] = numpy.flip(x2[:num]), numpy.flip(y2[:num])

You will end up with 131 points, oriented the same way as the Selig's format.
print('Number of points:', x2.size)  # -> 131
print(f'First point: ({x2[0]}, {y2[0]})')  # -> (1.0, 0.00126)
print(f'Last point: ({x2[-1]}, {y2[-1]})')  # -> (1.0, -0.00126)

Finally, we can also checks that coordinates are the same with numpy.allclose:
assert numpy.allclose(x1, x2, rtol=0.0, atol=1e-6)  # -> True
assert numpy.allclose(y1, y2, rtol=0.0, atol=1e-6)  # -> True


Q: How to show the pages where references were used in the bibliography? Is it somehow possible to show the numbers ob those pages in the bibliography, where a certain reference was used? This could be comparable to the glossary.
For example I used \cite{me2012} on pages 1 , 3 and 12, then the reference should show:

me (2012). unimportant paper, no name journal, 1(1):1-15; cited on: 1, 3, 12

or:

me (2012). unimportant paper, no name journal, 1(1):1-15; 1, 3, 12

instead of

me (2012). unimportant paper, no name journal, 1(1):1-15

A: You are using hyperref. This package provides the option backref with is explained as:

In addition, the hyperindex option (see below) attempts to make items
  in the index by hyperlinked back to the text, and the option backref
  inserts extra ‘back’ links into the bibliography for each entry.

So you can use:
\hypersetup{backref=true}


Q: Using Facebook Async Display Kit in Swift I want to use facebook async display kit in my project for smooth loading in tableview. I read them GitHub page but it's not clear for me. Can anyone help me to understand it?

(ASDK can also be used as a regular static library: Copy the project to your codebase manually, adding AsyncDisplayKit.xcodeproj to your workspace. Add libAsyncDisplayKit.a, AssetsLibrary, and Photos to the "Link Binary With Libraries" build phase. Include -lc++ -ObjC in your project linker flags.)

I did copy xcodeproj file into my own project and add -ObjC. But I do not know what they means by Add libAsyncDisplayKit.a, AssetsLibrary, and Photos to the "Link Binary With Libraries" build phase.. I did not find such files.
Please, do not minus my question, I'm new in Swift. Just show me the road. Thank you!

A: What it means is that you have to add the libraries you mention in the "link binary with libraries" row of the Build Phases section.
You can arrive to that section by:
- clicking in the project file in the project navigator view
- clicking in the target of the project where you want to use the library in the targets column
- clicking in the Build Phases section you will see the Link Binary With Libraries row.
Just click on the + button and add libAsyncDisplayKit.a, Photos.framework and the AssetsLibrary.framework.

A: A convenient way of adding external libs is to use cocoa pods as employeed here. (A collectionsview implementation a tableView should be somewhat similar)
(I am not the writer of that article)


Q: How can i get my container to go from starting -> healthy Background: My Docker container has a very long startup time, and it is hard to predict when it is done. And when the health check kicks in, it first may show 'unhealthy' since the startup is sometimes not finished. This may cause a restart or container removal from our automation tools.
My specific question is if I can control my Docker container so that it shows 'starting' until the setup is ready and that the health check can somehow be started immediately after that? Or is there any other recommendation on how to handle states in a good way using health checks?
Side question: I would love to get a reference to how transitions are made and determined during container startup and health check initiating. I have tried googling how to determine Docker (container) states but I can't find any good reference.

A:
My specific question is if I can control my container so that it shows
'starting' until the setup is ready and that the health check can
somehow be started immediately after that?

I don't think that it is possible with just K8s or Docker.
Containers are not designed to communicate with Docker Daemon or Kubernetes to tell that its internal setup is done.
If the application takes a time to setup you could play with readiness and liveness probe options of Kubernetes.
You may indeed configure readynessProbe to perform the initial check after a specific delay.
For example to specify 120 seconds as initial delay :
readinessProbe:
      tcpSocket:
        port: 8080
      initialDelaySeconds: 5
      periodSeconds: 120

Same thing for livenessProbe:
livenessProbe:
  httpGet:
    path: /healthz
    port: 8080
    httpHeaders:
    - name: Custom-Header
      value: Awesome
  initialDelaySeconds: 120
  periodSeconds: 3

For Docker "alone" while not so much configurable you could make it to work with the --health-start-period parameter of the docker run sub command :

--health-start-period :   Start period for the container to initialize
before starting health-retries countdown

For example you could specify an important value such as :
docker run --health-start-period=120s ...

A: Here is my work around. First in docker-compose set long timeout, start_period+timeout should be grater than max expected starting time, eg.
    healthcheck:
      test: ["CMD", "python3", "appstatus.py", '500']
      interval: 60s
      timeout: 900s
      retries: 2
      start_period: 30s

and then run script which can wait (if needed) before return results. In example above it is appstatus.py. In the script is something like:
timeout = int(sys.argv[1])
t0 = time.time()
while True:
    time.sleep(2)
    if isReady():
        sys.exit(os.EX_OK)
    t = time.time() - t0
    if t > timeout:
        sys.exit(os.EX_SOFTWARE)


Q: Scriptable way to create flat .pkg files with custom resources and scripts I have created a flat .pkg file with following options on 10.7 using PackageMaker 3.0.6:
/Applications/PackageMaker.app/Contents/MacOS/Package --root ./myroot \
 --id com.myroot.pkg --title "My Root" --scripts ./scripts --target 10.5 \
 --verbose --resources ./resources --root-volume-only --domain system \
 --no-relocate --versio 1.0 --certificate "My Cert Name"

In the resources folder I have background.png, Welcome.rtf and License.rtf and in the scripts folder I have preflight, postflight and various support files for those scripts. The resulting .pkg appears to be fully functional except that the installer does not display my background, welcome or license.
How can I add a custom background, welcome and license to a flat package?
As far as I can tell, the Distribution file in the .pkg is missing references to the background, welcome and license files.
As a workaround I tried using xar. If I unpack the package with xar like so:
xar -xf ./myroot.pkg -C work

and add the 3 tags for those files, then pack it again with xar:
cd work && xar -cf ../myroot2.pkg *

I get a package that starts installation ok with my background etc., but when it comes time to install my .app I get these errors (from /var/log/install.log):
 run preupgrade script for myroot
Could not create task for action: run preupgrade script for myroot2
Install failed: The Installer could not extract files from the package for myroot2. Contact the software manufacturer for assistance.
IFDInstallController 863170 state = 7

I have also tried Flat Package Editor: open myroot.pkg, drag out Distribution, edit it, drag it back, delete old Distribution, save. Same problem as with xar.
I would prefer to have a fully scriptable solution as opposed to using GUIs.
Edit: I have also tried to use pkgutil to expand, edit Distribution, and reflatten a flat package. This gets the icons and readme in the installer, but the installer is then unable to unpack the payload. Same if I reflatten with Flat Package Editor. I have also tried to create an expanded package without PackageMaker (which works, except on 10.8), but when I try to flatten that with pkgutil the result is a corrupted package again.

A: PackageMaker always was buggy has hell, and got deprecated with Mac OS X 10.6 Snow Leopard.
You should use pkgbuild together with productbuild.

A: This Mac Installers Blog has some useful posts about Packagemaker including details about the usage and solutions to common problems. Hope it will help.

A: Check out the Luggage - it's a Makefile helper file that lets you create OS X packages with sane Makefiles. Disclaimer: I am the original author for it, though there are a lot of other people's contributions in it now.


Q: MapReduce/Aggregate operations in SpringBatch Is it possible to do MapReduce style operations in SpringBatch?
I have two steps in my batch job. The first step calculates average. The second step compares each value with average to determine another value.
For example, Lets say i have a huge database of Student scores. The first step calculates average score in each course/exam. The second step compares individual scores with average to determine grade based on some simple rule:

*

*A if student scores above average

*B if student score is Average

*C if student scores below average

Currently my first step is a Sql which selects average and writes it to a table. Second step is a Sql which joins average scores with individual scores and uses a Processor to implement the rule.
There are similar aggregation functions like avg, min used a lot in Steps and I'd really prefer if this can be done in Processors keeping the Sqls as simple as possible. Is there any way to write a Processor which aggregates results across multiple rows based on a grouping criteria and then Writes Average/Min to the Output table once?
This pattern repeats a lot and i'm not looking for a Single processor implementation using a Sql which fetches both average and individual scores.

A: It is possible. You do not even need more than one step. Map-Reduce can be implemented in a single step. You can create a step with ItemReader and ItemWriter associated with it. Think of ItemReader -ItemWriter pair as of Map- Reduce. You can achieve the neccessary effect by using custom reader and writer with propper line aggregation. It might be a good idea for your reader/writer to implement Stream interface to guarantee intermediate StepContext save operation by Spring batch.
I tried it just for fun, but i think that it is pointless since your working capacity is limited by single JVM, in other words: you could not reach Hadoop cluster (or other real map reduce implementationns) production environment performance. Also it will be really hard to be scallable as your data size grows.
Nice observation but IMO currently useless for real world tasks.

A: I feel that a batch processing framework should separate programming/configuration and run-time concerns.It would be nice if spring batch provides a generic solution over a all major batch processing run times like JVM, Hadoop Cluster(also uses JVM) etc.
-> Write batch programs using Spring batch programming/Configuration model that integrates other programming models like map-reduce ,traditional java etc.
-> Select the run-times based on your need (single JVM or Hadoop Cluster or NoSQL).
Spring Data attempts solve a part of it, providing a unified configuration model and API usage for various type of data sources.).


Q: React view not updating even if the state is changing I'm trying to create a HackerNews with reddit.json
I'm fetching the data that's returining an array and i'm storing it in a variable
For the moment in my view i can only acess a fake json data:
    results= [
{'author' : Mister1,'url':'http://url1.com','score':400},
{'author' : Mister2,'url':'http://url2.com','score':350},
{'author' : Mister3,'url':'http://url3.com','score':500},
{'author' : Mister4,'url':'http://url1.com','score':456},
]

so when i change the topic i want to search in the bar, the state is changing and i'm getting what i want, my problem is the view it's not updating and stying with the old result
The problem i think is comming from my render code :
const list = (
      results
      &&
      results[searchKey]
      &&
      results[searchKey].hits
    )    ||  [
{'author' : Mister1,'url':'http://url1.com','score':400},
{'author' : Mister2,'url':'http://url2.com','score':350},
{'author' : Mister3,'url':'http://url3.com','score':500},
{'author' : Mister4,'url':'http://url1.com','score':456},
]

even if the result is changing it's stying with the fake json data.
My code : https://codesandbox.io/embed/mqpjrk3loy
Sorry if my question is dumb.

A: I could be wrong, but I think it could be the || operator. Have you tried a ternary operator?
{results ? results[searchKey].hits : ' // your hardcoded data '}

A: If I understand correctly, you are trying too set list variable as results[searchKey].hits, which have the wrong shape with your this.state.results
What you really want is this:
(results && results.results) || HARDCODED_FALLBACK_DATA


Q: correct method to Use sub string in where clause mysql query I have a table in mysql with column called type. contents are below
Type
Test 12
Test abc
start 1
start abcd
end 123

Now I want to select records where type starts with Test
Expected result:
Test 12
Test abc

But I am getting either
Test 12
   or empty results
I have tried like below:
select * from table where type = 'Test 12'
select * from table where type = '%Test%'
select * from table where type = '%Test'

What should be the correct sql statement.

A: If you want to do partial matches you need the LIKE operator:
SELECT * FROM table WHERE type LIKE 'Test%'

A: Use the Like keyword
select * from table where type LIKE 'Test%'

A: The equality (=) operator doesn't accept wild cards. You should use the like operator instead:
SELECT * FROM table WHERE type LIKE 'Test%'

A: Sooo close! You want to start with the string, then don't use % in the start, and use LIKE instead of =
select * from table where type LIKE 'Test%'


Q: Conservation Laws that apply to a hyperbolic trajectory
I don't understand why the answer choice is D, I thought for unbound orbits, none of these principles applied?
Could someone clear this up for me?

A: The question

Which conservation laws relate to the motion of the asteroid?

implies that it is the asteroid which is the system under consideration.
The gravitational force is an attractive central force which acts along the line joining the centre of masses of the star and the asteroid.
The asteroid has an external force acting on it, the gravitational attraction due to the star, so linear momentum of the asteroid is not conserved.
The torque, about the star, acting on the asteroid due to the star is zero because the direction of the gravitational attractive force due the star is along the line joining the star and the asteroid, so the angular momentum, about the star, of the asteroid is constant.
In classical mechanics energy is always conserved and in this example, with no frictional force etc acting, so is mechanical (gravitational potential and kinetic) energy of the asteroid and star system.
The type of orbit depends on the initial conditions and it could have been circular, elliptical, parabolic or hyperbolic.

A: The conservation laws have nothing to do with actual trajectory, but with the nature of forces acting on the object.
Take for example conservation of energy of some object in gravitational field. The only force acting on the object is (for simplicity, let us assume radial motion):
$$F=-G\frac{mM}{r^2}$$
In very short time, this will produce the change in velocity:
$$\frac{\Delta v}{\Delta t}=-G\frac{M}{r^2},$$ so the kinetic energy changed by:
$$\Delta E_k=\frac{m(v+\Delta v)^2}{2}-\frac{mv^2}{2}\approx mv\Delta v,$$
where we neglected $\Delta v^2$, because we are assuming small time interval and thus this change is also small. Plugging in from the force law:
$$\Delta E_k=-G\frac{mvM}{r^2}\Delta t,$$
Now, can we see the right hand side as negative change in potential energy? That is can we write the right hand side as simple a function of position (r)? In that case the gained/lost kinetic energy would be fully transformed into potential energy.
If you know calculus, you can calculate what kind of potential function you will get. If you don't just use the known result $E_p=-G\frac{mM}{r}$ and see  wheter it works:
$$\Delta E_p=-G\frac{mM}{r+\Delta r}+G\frac{mM}{r}= G\frac{mM\Delta r}{r(r+\Delta r)}\approx G\frac{mM\Delta r}{r^2},$$
But $\Delta r$ is just $v\Delta t$ and plugging it in, you will see it works $\Delta E_k=-\Delta E_p$!
Notice, the only thing we used is the form of the force acting on the object. We did not assume any initial velocity or position, so our formulas work for any scenario in which gravitational (and only gravitational) force acts on the object.

A: every thing is already wrote by @Umaxo, but i prefer to write it like this:
according to NEWTON second law  and your case the force is a function of r:
$$m\,\ddot{r}=F(r)\tag 1$$
multiply (1) with $\dot{r}$
$$m\,\dot{r}\,\ddot{r}=\dot{r}\,F(r)\tag 2$$
with
$$\dot{r}\,\ddot{r}=\frac{1}{2}\frac{d}{dt}\,\dot{r}^2$$
and
$$\dot{r}=\frac{d\,r}{dt}=v$$
you get:
$$\frac{m}{2}\frac{d}{dt}\,(v^2)=\frac{dr}{dt}\,F(r)$$
$\Rightarrow$
$$\int \frac{m}{2}\,d(v^2)=\int F(r)\,dr+E=-U(r)$$
or
$$\boxed{\frac{m}{2}\,v^2+U(r)=\text{E}}$$
this is the conservation of energy
the angular momentum is always conserved if the force $F$ is only function of r, for example gravitation force


Q: Sort the list by the field of another table There are two tables:
Table1
Id
Name
Table2
Id
Table1ID(foreign key Table1 ID)
Date
With EntityFramework I use:
var list = db.Table1.Where(some selection).ToList();

How can I sort "list" by "Date" field in Table2?

A: Using OrderBy on Table2.Date
    var list = db.Table1.Where(some selection)
                         .Where(x => x.Table2.Count() > 0)
                         .OrderBy(x => x.Table2.FirstOrDefault().Date)ToList();


Q: how to resolve java result 1 errors How to resolve 1 particular flavor of 'java result 1' in the context of using JVMTI agents?

A: Here's how I resolved an issue in my context:
The server is run through an ANT script with jvm configured with an agent (the property name 'agentfile' below is associated with a value pointing to the agent library)

Now, I would get the error 'java result 1' whenever the server was run, without any indication of the actual error.
Here's how this issue was debugged.
1) The agent was turned off (i.e.) the above 2 lines were commented out.
2) Then when ANT was run, the actual error message was clearly shown - the problem was: a class file was missing. This error was being eaten by the agent, since it is low level C code and just looks to load a class that it cannot find and throws the Java error.
Lesson learnt: if you have an agent, turn it off and then run your ANT - it may throw up the reasons for error seen. This is of course one of many scenarios noticed for the java result 1 error.


Q: How to filter arrays in json based on specific value using jq I am trying to make a filter using jq to filter the arrays in this json to get only the arrays that have "policy_id": 199383 and exclude the arrays that contain different policy_id value.
{
  "links": {
    "policy_id": 199383,
    "violations": [
      69892478
    ]
  },
  "incident_preference": "PER_CONDITION_AND_TARGET",
  "closed_at": 1519408001909,
  "opened_at": 1519407125437,
  "id": 17821334
}
{
  "links": {
    "policy_id": 199383,
    "violations": [
      69889831
    ]
  },
  "incident_preference": "PER_CONDITION_AND_TARGET",
  "closed_at": 1519408011851,
  "opened_at": 1519406230858,
  "id": 17820349
}
{
  "links": {
    "policy_id": 194774,
    "violations": [
      68446755
    ]
  },
  "incident_preference": "PER_POLICY",
  "closed_at": 1518835775531,
  "opened_at": 1518835745303,
  "id": 17422347
}
{
  "links": {
    "policy_id": 199383,
    "violations": [
      69892488
    ]
  },
  "incident_preference": "PER_CONDITION_AND_TARGET",
  "closed_at": 1519402345676,
  "opened_at": 1519401235467,
  "id": 17821334
}

I tried this :
jq '.incidents[] | select (.links.policy_id == "199383")' file.json. But not having anything in return ? Can anyone help.
Thank you

A: jq '.incidents[]| select(.links.policy_id==199383)' file.json

should do it.
Output
{
  "links": {
    "policy_id": 199383,
    "violations": [
      69892478
    ]
  },
  "incident_preference": "PER_CONDITION_AND_TARGET",
  "closed_at": 1519408001909,
  "opened_at": 1519407125437,
  "id": 17821334
}
{
  "links": {
    "policy_id": 199383,
    "violations": [
      69889831
    ]
  },
  "incident_preference": "PER_CONDITION_AND_TARGET",
  "closed_at": 1519408011851,
  "opened_at": 1519406230858,
  "id": 17820349
}
{
  "links": {
    "policy_id": 199383,
    "violations": [
      69892488
    ]
  },
  "incident_preference": "PER_CONDITION_AND_TARGET",
  "closed_at": 1519402345676,
  "opened_at": 1519401235467,
  "id": 17821334
}

From json.org

A string is a sequence of zero or more Unicode characters, wrapped in
  double quotes, using backslash escapes. A character is represented as
  a single character string. A string is very much like a C or Java
  string.)

and

A number is very much like a C or Java number, except that the octal
  and hexadecimal formats are not used.

So 199383 is clearly different from "199383". They are number and string respectively.
Note : Emphasis in quoted text are mine.


Q: Change php variable depending on what selected in dropdown I want to create a page on my website which will be used to view users profiles. When the user first visits the page I want it show their own profile. But I want to put in a drop-down menu or something which will give them the ability to view other users profiles. I haven't started creating this yet however I just want to know if what I want to achieve is possible with what I have planned.
What I am thinking of doing is have a php variable which would be $UserID or something.
To start with $UserID would be equal to the current user viewing the page's id e.g. 1 for Admin.
Then I would get all the data from the database through that variable $UserID.
But in order to view other user's profiles I want to change that $UserID variable depending on which user's name is selected in the dropdown.
e.g. If dropdownuser = Test3 then $UserID = 5.
Then it would display Test3's user profile.
Have I got this correct??

A: Usually this is done on two separate pages: profile of the current user (my profile) and general profile page.
On my profile page you use the logged in user's ID, something like $_SESSION['user-id'] and on general profile pages you use the ID from a drop down or whatever coming through the URL so something like $_GET['user-id'].

A: Correct. When you query the database, pass in an ID so it get's the info for that specific ID
$select = $db->query('SELECT id, name, info FROM table WHERE id = :id');
$select->execute(array(':id' => $_POST['id']));

and your html would be
<form method="post">
<select name="id">
<option value="1">Person 1</option>
<option value="2">Person 2</option>
</select>

<input type="submit" value="Select user" />
</form>

A: Basically, you can achieve what you want, just note that PHP script is not active while user watches a page. It works just when the page loads (or reloads). So, you will need to reload the page when user changes the selected item in the dropdown. That is easily achievable, simply make it in onchange event handler.
There is another way of doing it: AJAX. You can invoke the server-side not on page load, but on some internal page event (like dropdown selected index change). Then the page would not reload, but you will need to properly handle AJAX response. For the server it would be like a new page is being loaded. Read more about ajax.


Q: Ubuntu/Windows 10 Dualboot - Grub missing I previously installed a standalone copy of Windows 10 on my Microsoft Surfacebook. I intend to set up Ubuntu dual-boot alongside it. Unfortunately, after installation following these instructions, it seems that Windows still boots over Ubuntu -- the GRUB loader is ignored?
I have tried the following:

*

*Running boot repair from Live Ubuntu USB. This apparently runs and does some things, which prevents both Windows and Ubuntu from booting altogether -- gets stuck with the Surfacebook loading animation, screen flashes, goes into UEFI.

*Going into windows and trying to change the boot according to this post (Running bcdedit /set {bootmgr} path \EFI\ubuntu\shimx64.efi).

*Installing Ubuntu by itself -- for some reason, the GRUB refuses to show up, and no boot-repair operations are of any help.

*Disabling fast boot and hibernation

Here is the info output of my boot-repair program: https://pastebin.com/N1J4H9eF
Tried running this command to rename the boot entry:
sudo efibootmgr -c -L "UEFI hard drive" -l "\EFI\Boot\bootx64.efi" -d /dev/nvme0n1 -p 2

Which gave this error
Could not prepare Boot variable: No space left on device

Here is sudo efibootmgr -c (Which I think may be pertinent):
GUID Partition Table Header signature is wrong: 0 != 5452415020494645
GUID Partition Table Header signature is wrong: 0 != 5452415020494645
GUID Partition Table Header signature is wrong: 0 != 5452415020494645
GUID Partition Table Header signature is wrong: 0 != 5452415020494645
GUID Partition Table Header signature is wrong: 0 != 5452415020494645
GUID Partition Table Header signature is wrong: 0 != 5452415020494645
Could not prepare Boot variable: No space left on device

Here is a screenshot of GParted

Any help would be greatly appreciated. Been wrestling with this problem for more than a few days now, and just can't figure it out... would prefer not to do backend development on Windows!

A: Insert the bootable linux usb and boot from the usb. Then run
sudo apt-get install grub2
Sometimes, if loader is UEFI it causes problems. At first switch to BIOS and then try this.

A: I had same issue when installed Windows 8 and LinuxMint because Windows 8 was installed as UEFI and LinuxMint as Legacy BIOS mode.
Solved the issue chrooting into the installation and installing Grub on it.
Assuming that nvme0n1p5 is your Ubuntu partition, from the LiveCD, run this:
sudo mount /dev/nvme0n1p5 /mnt
sudo mount --bind /dev /mnt/dev
sudo mount --bind /dev/pts /mnt/dev/pts
sudo mount --bind /proc /mnt/proc
sudo mount --bind /sys /mnt/sys

Then chroot into it:
chroot /mnt

Install the Grub-EFI binaries and install grub to the disk:
sudo apt-get install grub-efi
sudo grub-install /dev/nvme0n1
sudo update-grub

Now exit the chrooted system and umount it:
exit
sudo umount /mnt/dev/pts
sudo umount /mnt/dev
sudo umount /mnt/sys
sudo umount /mnt/proc
sudo umount /mnt

Reboot.

A: This message :
Could not prepare Boot variable: No space left on device

suggests that the EFI partition is full, although your GParted screen shows only 35/100 MB used. 100 MB is pretty small compared to what I've seen recommended for dual boots, so you could try resizing this partition to 300 or 400 MB.
I'm not sure if this could be done in place though ; you probably will have to wipe the existing partitions and reinstall both systems.

A: Oddly enough, none of the responses posted worked for me. However, for whatever reason, after installing a bunch of updates on Windows 10 (to the latest build, 1607) everything fixed itself...
The one key thing I noticed was that 'Windows Boot Manager' was once again shown in the boot order (previously missing, for reasons unknown). I am not sure why updating Windows would have had such an effect -- running windows boot repair via the USB did nothing to help (it would exit with an error indicating boot repair is not possible).
Afterward, I was able to install Ubuntu without any issues whatsoever. Wish I knew exactly what happened and why, but it seems this will have to be one of those happy accident situations.


Q: Memory Leak: Issues with releasing NSArray in iPhone app I have a code which shows leaks in Instruments. It shows leaks where I initialize the arrayDetPerformance with the contents of arrayDetail
If I release my arrayDetail then my app crashes.
What could be wrong?
Here is the code:
    NSDictionary *finalResult = [extractUsers JSONValue];
    //      NSLog(@" Stamp-16 : %@",[NSDate date]);
    NSLog(@"Array2  : %d",[arrayDetail retainCount]);        //RETAIN COUNT IS 0
    arrayDetail = [[finalResult objectForKey:@"Detail"]
    NSLog(@"Array2  : %d",[arrayDetail retainCount]);       //RETAIN COUNT IS 2

    //  NSLog(@"Data is : %@",array1);
    //      NSLog(@" Stamp-17 : %@",[NSDate date]);

    //NSLog(@"Final Value is : %@",[[allUsers objectAtIndex:0] valueForKey:@"password"]);

    //[self setUserData:allUsers];
    //[tblView reloadData];

    [responseString release];
    [request release];

}

//sleep(0.3);
//[inProgressIndicator stopAnimating];
[fileContents release];

//Release all the allocated data
[json release];
//label.text = @"Finish";
//  NSLog(@" Stamp-19 : %@",[NSDate date]);
NSUserDefaults *def = [NSUserDefaults standardUserDefaults];
//NSLog(@"Array2  : %d",[array2 retainCount]);

arrayDetPerformance = [[NSMutableArray alloc] initWithArray:arrayDetail];
chartPoints= [arrayDetPerformance valueForKey:@"Points"];
NSLog(@"Chart Points: %@",chartPoints);
[def setObject:chartPoints forKey:@"yarray"];
[def setObject:@"YES" forKey:@"flagThumb"];

//array1 = [[NSMutableArray  alloc] initWithObjects:@"New",@"Table",@"View",nil];
//[self.Dettable reloadData];
//sNSFileManager *fileManager = [NSFileManager defaultManager];
//[array2 release];
NSLog(@"ArrayDEtPerfomance : %d",[arrayDetPerformance retainCount]);
NSLog(@"array2 : %d",[arrayDetail retainCount]);
if([chartPoints count]>0)
{
    PlotItem *plotItem = [[PlotGallery sharedPlotGallery] objectAtIndex:0];
    [plotItem imageHive:Fund];
}

//[arrayDetail release];

}

Memory leak is shown on the line
arrayDetPerformance = [[NSMutableArray alloc] initWithArray:arrayDetail];

Also I am confused on why the retain count directly goes from 0 to 2 in the below code:
NSLog(@"Array2  : %d",[arrayDetail retainCount]);        //RETAIN COUNT IS 0
    arrayDetail = [[finalResult objectForKey:@"Detail"]
NSLog(@"Array2  : %d",[arrayDetail retainCount]);       //RETAIN COUNT IS 2

What could be wrong?

A: It shows a leak because you allocate arrayDetPerformance and then not release it. Simple as that. At least that's what we can tell from the code you are showing us.
As for the rest, don't use retainCount to debug memory problems, ever! You have to understand the simple memory management rules and follow them, nothing else. Since you don't know what Apple's underlying code does, you cannot rely on the retain count of an object.
As to your question relating to this code:
NSLog(@"Array2  : %d",[arrayDetail retainCount]);        //RETAIN COUNT IS 0
arrayDetail = [[finalResult objectForKey:@"Detail"]
NSLog(@"Array2  : %d",[arrayDetail retainCount]);       //RETAIN COUNT IS 2

You are assigning a whole other object to arrayDetail so it's completely meaningless to compare any properties of arrayDetail before and after the assignment. The retain count could be all over the place and it would not tell you anything.
I get the impression that you don't really know what you are doing here. You should read the memory management rules again and again until you understand them thoroughly.

A: retainCount won't help you debug your problem (in fact it will almost never be relevant to debugging, so best forget it's even there).
Don't release arrayDetail, as you don't own it. The problem is with arrayDetPerformance. You're allocing an object on that line, and it's not being released anywhere. Now, you may be doing that elsewhere in your code, but if you aren't, send it a release when you've finished using it.
Edit
If you're deallocating arrayDetPerformance in your dealloc method, I'm assuming it's an instance variable? In this case, you can't assume that it doesn't already point at an object, so you should send it a release before assigning it to the new object.
Alternatively, if it is configured as a property, just use self.arrayDetPerformance = ... which will take care of the memory management for you.

A: Do not call retainCount
retainCount is useless.  The absolute retain count of an object is an implementation detail.   The rule is simple;   if you cause something to be retained, you must cause it to be released when you are done with it.  End of story.
The memory management documentation discusses this fully.

First, retainCount can never return zero.   The only time you'll get a zero is if you happened to message nil.   This:
NSLog(@"Array2  : %d",[arrayDetail retainCount]);        //RETAIN COUNT IS 0
arrayDetail = [[finalResult objectForKey:@"Detail"]
NSLog(@"Array2  : %d",[arrayDetail retainCount]);       //RETAIN COUNT IS 2

You are causing arrayDetail to point to a different object on that second line.   Thus, no relation between the retain count before/after that line.
When leaks tells you a leak is on a particular line like this one...
arrayDetPerformance = [[NSMutableArray alloc] initWithArray:arrayDetail];

... it is telling you that said object allocated on that line was leaked.  It is not telling you that particular line was the cause of the leak.   The leak is likely because you either over-retained it somewhere else or forgot to leak it.
You've said in several comments that you are "deallocating [something] in your dealloc".  Show your dealloc method's implementation.

A: [arrayDetPerformance release]; is not written in your code;
So, its show memory leak.


Q: Не удаётся создать в БД MSSQL пользовательский тип, заданный в зарегистрированной CLR- Сборке. Почему? Сборка зарегистрирована. Регистрировалась и WITH PERMISSION_SET = SAFE; и WITH PERMISSION_SET = EXTERNAL_ACCESS; - Не помогает.
Исходники:
namespace SqlFiteredType
{
   /* [Serializable]
    [Microsoft.SqlServer.Server.SqlUserDefinedType(Format.Native)]
    public struct FilteredType : INullable
    {
        public double a, b, c;
        public FilteredType(double _a, double _b,double _c) {
            a = _a; b = _b;c = _c;

        }
        public bool IsNull => false;
    }*/
    [Serializable]
    [Microsoft.SqlServer.Server.SqlUserDefinedType(Format.Native,IsFixedLength =true,MaxByteSize =40,Name = "FilteredType")]
    public class FilteredType : INullable
    {
        public double a=0, b=0, c=0;
        public FilteredType() {
            a = 0;b = 0; c = 0;
        }
        public bool IsNull => false;
    }
}

Код только для теста, пробовал и класс и структуру(нужна в дальнейшем структура)
Есть предположения, куда копать?
SqlServer 2016. В других созданных сборках с функциями функции видит и работает с ними нормально, а тип видеть не хочет.


Q: Check if current user is owner of GitHub remote in zsh I'm trying to write a git pre-push hook that performs some actions prior to pushing to origin if the person pushing is the repo's owner. Is there a way to check this in bash/zsh?

A: You can do this if the user is using HTTPS.  You'd need to use the authenticated user endpoint to find the user ID of the current user, say, using curl, and then see if that user is the same as the owner of the repository by checking the URL.
To get the appropriate credentials, you can take the remote URL (e.g., https://github.com/git/git.git) and pipe it to git credential fill to find the username and password, like so:
echo url=https://github.com/git/git.git | git credential fill

The output format is defined in the git-credential man page.  These credentials should also be able to be used for the API to make your request, although note that since curl requires the password to be passed on the command line, you will expose those credentials to anyone else on the machine.  A non-shell option may be a more security-conscious choice.
Technically, there are also ways to determine this via SSH, but those rely on parsing fixed output that is subject to change, and as such, you should assume that you cannot get that information for SSH remotes.
Note that this tells you the current user, which you can check against the URL, but it doesn't tell you whether the user has administrative privileges on a repo that they don't own themselves (such as one owned by an organization).  Since you haven't told us what you want to do with this information, we can't help you out there, although if you're trying to use the API, you can just do it and see if it succeeds or not.
Since you are using the user's credential store in this case, you need to be explicit and up front with the user about what you're doing so that the user isn't surprised by your use of the credentials.  It would be unethical and probably illegal to use the user's credentials in the way I've described without their knowledge and consent.


Q: JSF Datatable link to another page I've got this table:
<p:dataTable value="#{requestBean.requestsList}" var="requestClass" style="width:50px;" id="requestList">
    <p:column>
        <f:facet name="header">
            <h:outputText value="ID" />
        </f:facet>
        <h:outputText value="#{requestClass.requestID}" />
    </p:column>

    <p:column>
        <f:facet name="header">
            <h:outputText value="Status" />
        </f:facet>
        <h:outputText value="#{requestClass.requestStatus}" />
    </p:column>

    <p:column>
        <f:facet name="header">
            <h:outputText value="Details" />
        </f:facet>
        <h:outputText value="#{requestClass.requestTitle}" />
    </p:column>
</p:dataTable>

Now the rows display the data properly but I want to be able to click on a record ID. When I do I go to another page e.g. review.xhtml where the url parameter would be that ID. So something like this: review.xhtml?id="clicked request". How is that done?
Update: I tried this and it did kinda work, but is it correct in practice?
<p:column>
    <f:facet name="header">
        <h:outputText value="ID" />
    </f:facet>
    <a href="review.xhtml?id=#{requestClass.requestID}">
        <h:outputText value="#{requestClass.requestID}" />
    </a>
</p:column>

A: Try this one:
<p:column>
   <f:facet name="header">
      <h:outputText value="ID" />
   </f:facet>
   <h:link outcome="review" value="#{requestClass.requestID}" >
      <f:param name="id" value="#{requestClass.requestID}" />
   </h:link>
</p:column>

A: try this code
<h:outputLink value="#{bean.url}">
    <h:outputText value="Go to another page."/>
    <f:param name="paramid" value="#{bean.id}" />
</h:outputLink>


Q: Change stream update and array of sub document update need help on writing some proper aggregation for change stream
I am getting data some thing like
{
  "_id": {
    "$oid": "6285ee2b91c6e50012a76e0b"
  },
  "status": "new",
  "lastUpdatedData": {
    "timestamp": {
      "$date": {
        "$numberLong": "1670602175000"
      }
    },
    "priority": 0,
    "gps": {
      "longitude": 0,
      "latitude": 0,
      "altitude": 0,
      "angle": 0,
      "satellites": 0,
      "speed": 0
    },
    "event_id": 0,
    "properties_count": 8,
    "ioElements": [
      {
        "id": 239,
        "label": "Ignition",
        "value": 0,
        "valueHuman": "Ignition Off",
        "valueDB": 0,
        "_id": {
          "$oid": "63935e17ac1fa5b006927e26"
        }
      },
      {
        "id": 240,
        "label": "Movement",
        "value": 0,
        "valueHuman": "Movement Off",
        "valueDB": 0,
        "_id": {
          "$oid": "63935e17ac1fa5b006927e27"
        }
      },
      {
        "id": 200,
        "label": "Sleep Mode",
        "value": 2,
        "valueHuman": "Deep Sleep",
        "valueDB": 2,
        "_id": {
          "$oid": "63935e17ac1fa5b006927e28"
        }
      },
      {
        "id": 67,
        "label": "Battery Voltage",
        "value": 3791,
        "valueHuman": "3.791 V",
        "valueDB": 3.791,
        "_id": {
          "$oid": "63935e17ac1fa5b006927e2b"
        }
      },
      {
        "id": 68,
        "label": "Battery Current",
        "value": 0,
        "valueHuman": "0 A",
        "valueDB": 0,
        "_id": {
          "$oid": "63935e17ac1fa5b006927e2c"
        }
      }
    ]
  },
  "category": "companyCar"
}

*

*My first question is regarding updating the ‘ioElements’ array and I want to update

{
        "id": 239,
        "label": "Ignition",
        "value": 0,
        "valueHuman": "Ignition Off",
        "valueDB": 0,
      }

to
{
        "id": 239,
        "label": "Ignition",
        "value": 1,
        "valueHuman": "Ignition On",
        "valueDB": 1,
      }

I want to perform a kind of upsert on ioElements array i.e update the existing fields with new fields if any new object is present inside ioElements I receive I need to push to ioElements array how to achieve this in an effective way. My current implementation
ioElements.forEach(async (singleIoEle) => {
          const ioElementExist = await Vehicle.findOne({
            _id: mongoose.Types.ObjectId(vehicleId),
            "lastUpdatedData.ioElements.id": singleIoEle.id,
          });
          if (ioElementExist) {
            await Vehicle.updateMany(
              {
                _id: mongoose.Types.ObjectId(vehicleId),
                "lastUpdatedData.ioElements.id": singleIoEle.id,
              },
              {
                $set: {
                  "lastUpdatedData.ioElements.$": {
                    ...singleIoEle,
                  },
                },
              }
            );
          } else {
            await Vehicle.findByIdAndUpdate(
              mongoose.Types.ObjectId(vehicleId),
              {
                $addToSet: { "lastUpdatedData.ioElements": { ...singleIoEle } },
              }
            );
          }
        }),

Can the above code be improved and perform update in effective way?
We also have a change stream opened to show updates on latest values on frontend my change stream aggregation pipeline
const ids = Array.of(ObjectId(...vehicleIds));
    const pipeline = [
      {
        $match: {
          operationType: 'update',
          'documentKey._id': { $in: ids }
        },
      },
    ];

Now issue is this pipeline is triggered on each of ioElement is updated which is creating load on servers. I want to get update only once when my updating code has finished(get update not everytime a single ioElement is update rather get update only one after all the single ioElements are written)


Q: Javascript package or plugin to create network diagrams with IPs Is there a plugin or a package where I can create visual network diagrams like in cisco packet tracer, so that our technicians can request their network schedule per customer.
I have already seen protovis and infovis go by, but it can not do what I really want.
What I actually want is something like the picture.
If you need more information, let me know and if the question is wrong, do not hesitate to correct me.
thank you in advance

A: Please look up https://gojs.net/latest/samples/index.html
- these are javascript based
- Individual classes are also available (which you can customize for a new visualization)
- It can be installed via npm, and, if you don't like it, can be easily removed from the system.
I hope this helps.
regards
SS


Q: Counter example to not surjective I have to provide a counter example to show that the function $f\colon \mathbb{N} \to \mathbb{N}$ where  $f(x) = x^2+4 $ is not surjective
Would making the function natural number into integer ie
$f:\mathbb{Z} \to \mathbb{Z}$ be an acceptable counter-example?

A: Let $c\in\mathbb{N}$. Then for $x\in\mathbb{N}$, we have $f(x) = c$ if and only if $x^2 + 4 = c$ which is true if and only if $x^2 + 4 - c = 0$. This is a quadratic polynomial and you can find its roots explicitly. Can you find a value of $c\in\mathbb{N}$ for which there are no integer roots? Such a $c$ will be a counterexample, since you would have no element in your domain that maps to it, despite it being in your codomain.

A: You can't modify the domain of your function as you please. What you want to show is that there's some natural number $n$ which is not in the image of $f$ with inputs from the natural numbers, i.e. that there is some $n \in \mathbb{N}$ such that $f(k) \neq n$ for any $k \in \mathbb{N}$.
Here is a hint to help you find such a natural number: $x^{2} \geqslant 0$ for all $x \in \mathbb{N}$, so...


Q: No way to restore a Post.aspx blog view? A bug in SharePoint 2013 which breaks the Posts.aspx page.
Reproduce:
1) Click on the title of any blog post to open up the Post.aspx?ID=N view.
2) Place the page in edit mode and then place the Post web part in edit mode.
3) Click on the "Edit the current view". Do Not make any changes but just click [OK]
..Result = contents of Web Part disappears and now whenever you click on any Blog Post title, the page will not display the actual post.
Proposed Fixes that do not work..
a) Edit the broken web part and change the view from <Current View> to the <Summary View> ... Does not work because although View Comes back, it shows ALL post and in my test the "Edit Current view" option disappears so there is no way to add a filter (which also doesn't work anyway).
b) Delete the Broken web part and re-add from new. It will show as a list instead of what we had but continues to show ALL posts. Edit it's current view and add the filter "ID is equal to [ID]"... Does not work because once you go back and click on a Post Title, the new view displays "There are no items in this view" so you go from showing all, back to showing none.
c) Site Settings --> Site Actions --> Reset to site definition --> ALL... doesn't seem to do anything.
d) Add Post.aspx?contents=1 to view all web parts. Select the Post web part and "Reset'... again nothing seems to happen.
What am I missing here?

A: Here's the solution to fix the post web part on the Post.aspx site.

*

*Delete the faulty "Post" web part.

*Add a new post web part (this will display a list of all posts)

*Edit the web part by changing the view property to "<Summary View>".

*Under Appearance setting, set the Chrome Type to None

*Click on apply, then OK.

*Open SharePoint Designer, navigate to the Post.aspx page via the Site Objects > All Files folder

*Edit the file in Advanced mode.

*Locate a webpartzone which has “Description="Use the Posts list for posts in this blog."” property. (Please know that there are 2 query tags in the file).

*Replace the Query tag contained in this webpartzone with the Query code below. Problem solved!!!!

<Query>
    <OrderBy>
      <FieldRef Name="PublishedDate" Ascending="FALSE"/>
      <FieldRef Name="ID" Ascending="FALSE"/>
    </OrderBy>
    <Where>
      <Eq>
        <FieldRef Name="ID"/>
          <Value Type="">
             <GetVar Scope="Request" Name="ID"/>
          </Value>
      </Eq>
    </Where>
</Query>

A: The hint of Stefan, to replace the post.aspx is a good approach, but for me not the whole solution.
After the post.aspx was replaced and the webparts have been added, all posts are displayed, not just this one I wanted to see. Only with the additional adaptation of the code in the SPD I found the correct result.
Here are the steps:
1) Open the post.aspx of the two Blogs
2) Search for the "Left"-section and find the lines with "<View Name="{...}" Type=" .... " at the beginning.
3) Replace the lines from the new post.aspx with those from the old.
4) Now even customize the URL according to the blog and it works.

A: I previously had the same problem and I was able restore the page with help of a newly created blog site. I created a new Blog and then mapped the blogs as a network share and copied the new post.aspx over the ruined post.aspx.
This brought back the web part that showed the blog posts after that I added the missing web parts back to the posts.aspx.
Overall the blog template can be tricky sometimes.

A: I tried the approaches from Stefan and from Phil, but I was not able to get them to work for me.
My solution was to create a new blog site in my stage environment, then use Sharegate to copy the custom site columns (adding them to the posts library, of course) and then the content from the photos library and posts list.  This gave me essentially a mirror of the site that was impacted, but this had a working post.aspx page.
Next, I used Sharegate again to copy the mirrored site from stage and replace the original site.  Afterwards the original site in production was working as it was before the post.aspx page was broken. Whew!

A: You can also try to use webpart connections (Filter by URL). To do it,

*

*Add the Context filter WebPart to Posts.aspx (URL)

*Edit it.

*In "Parameter Name" type ID

*Click Ok

*Click Edit webpart -> Connections - > Send Values to -> Posts

*On the popup, select Filter by (second option)

*Select ID. Click Finish.

It should solve your problem even if you change the view again.


Q: recursion of objects and methods in python I wanna create a class  which consist of parents and children and a recursion method to call the last child :
class MyClass:
    def __init__(self,val,child =None):
        self.val = val
        self.child = child
    def findLastChildVal(self):
        if self.child ==None:
            return self.val
        return (...)

c = MyClass("I'm child")
p = MyClass("I'm parent",c)
p.findLastChildVal()

I have no Idea what to write instead of (...). It's confusing.

A: This is a classic recursion problem, in my opinion it will be much easier to use a static function instead of a member function:
class MyClass:
    def __init__(self, val, child =None):
        self.val = val
        self.child = child

    @staticmethod
    def find_last_child_val(current_node: MyClass):
        if current_node.child == None:
            return current_node.val
        else:
            return MyClass.find_last_child_val(current_node.child)

c = MyClass("I'm child")
p = MyClass("I'm parent", c)
MyClass.find_last_child_val(p)

Update:
Pay attention that searching for a child using a recursion like this, is not efficient. find_last_child_val() runs in O(n) complexity. It is much more efficient to perform n iterations in a for loop instead of a recursion. If you can't think of a way to reduce the tree traversal complexity, I suggest using a different data structure.


Q: Constructing objects from data in multiple arrays: copy or reference the data? I have a data source that constructs multiple arrays of data. Each array are associated to each other by their offsets (all arrays are the same length). I am using a library that works on singular objects of this data through a public interface.
An example with two pieces of data a and b that make up single objects.
// three 'objects'
static int a[] = { 5, 6, 7};
static double b[] = {402, 24014, 52.3};

And I have this interface of the object that the library uses:
class ISomeInterface {
   public:
    virtual ~ISomeInterface{}
    virtual int GetA() const = 0;
    virtual double GetB() const = 0;
}

How would I best to get an interface 'view' this data if the ISomeInterface can be added to a vector, get sorted and filtered in the library.
std::vector<shared_ptr<ISomeInterface> > data;

Would I just construct a class that points to the index in the data arrays? Assuming the references to the array are accessible:
class MyClass : ISomeInterface {
    public:
     MyClass(int index) : _index(index) {};

     virtual int GetA() const { return a[_index];}
     virtual double GetB() const { return b[_index];}
    private:
     int _index;
}

Or I could just copy the data from the arrays to an object:
class MyClass2 : ISomeInterface {
    public:
     MyClass2(int a, double b) : _a(a), _b(b) {};

     virtual int GetA() const { return _a;}
     virtual double GetB() const { return _b;}
    private:
     int _a;
     double _b;
}

I could potentially have a lot of data in these arrays, so I thought the first approach would avoid duplicating all the data.


Q: How to use linearGradient in react-native-svg I have some SVG graphics that I would like to apply conditional styling on (e.g. linearGradient when it's active). How would I go about achieving this? I'd rather not (if there's another way) have to go in a manually add a defs tag with linearGradients in there, and I've seen stuff about using an externals defs file to access the fill I want (so I can specify either a solid color or gradient depending on state). I'm not sure how to ask, or where to look.
An example:
An SVG file:
<svg xmlns="http://www.w3.org/2000/svg" viewBox="0 0 26 26">
  <path d="M20.94 9.56c.74 0 1.35.62 1.35 1.38v1.84c0 3.79-2.48 7.85-6.44 8.81v1.36A3.02 3.02 0 0 1 12.88 26a3.02 3.02 0 0 1-2.97-3.05v-1.34c-3.36-.83-6.2-5.05-6.2-8.83v-1.84c0-.76.6-1.38 1.35-1.38.74 0 1.34.62 1.34 1.38v1.84a6.7 6.7 0 0 0 6.6 6.79 6.7 6.7 0 0 0 6.6-6.79v-1.84c0-.76.6-1.38 1.34-1.38ZM13.08 0c2.77 0 5 2.28 5 5.09v7.44c0 2.8-2.23 5.08-5 5.08-2.76 0-5-2.28-5-5.08V5.09a5.05 5.05 0 0 1 5-5.09Z" fill-rule="evenodd"/>
</svg>

Now - I have a LOT of these, so I was hoping I could link the gradient from an external source, or use some other way to just slap a linear gradient on top of them. Is there such a way? What would be the best way to add gradients to 100+ icons without having to go in and edit each one of them? Is there a bulk editor somewhere that I don't know about?


Q: How to click outside button and keep active style? - AlpineJS & TailwindCSS I'm using TailwindCSS and AlpineJS on this project. There are two buttons that switch tabs and the first one have autofocus. When a tab is switched, the other button becomes active:

I want the button to become inactive only when the other button is clicked. Is there a way to do this using AlpineJS and TailwindCSS? Something like bind the active class with @click.away.
Thanks in advance.
Here is my code:

Saldos

$0.00

                     <button class="p-1 mr-1 text-gray-500 rounded-lg outline-none active:text-gray-200 hover:text-gray-200 focus:text-gray-200 focus:outline-none hover:bg-gray-700 focus:bg-gray-700" type="button" @click="openTab = 1" autofocus>
                        <svg class="w-6 h-6" fill="currentColor" viewBox="0 0 20 20" xmlns="http://www.w3.org/2000/svg"><path d="M9 2a1 1 0 000 2h2a1 1 0 100-2H9z"></path><path fill-rule="evenodd" d="M4 5a2 2 0 012-2 3 3 0 003 3h2a3 3 0 003-3 2 2 0 012 2v11a2 2 0 01-2 2H6a2 2 0 01-2-2V5zm3 4a1 1 0 000 2h.01a1 1 0 100-2H7zm3 0a1 1 0 000 2h3a1 1 0 100-2h-3zm-3 4a1 1 0 100 2h.01a1 1 0 100-2H7zm3 0a1 1 0 100 2h3a1 1 0 100-2h-3z" clip-rule="evenodd"></path></svg>
                     </button>

                     <button class="p-1 mr-1 text-gray-500 rounded-lg outline-none hover:text-gray-200 focus:text-gray-200 active:text-gray-200 focus:outline-none hover:bg-gray-700 focus:bg-gray-700" type="button" @click="openTab = 2">
                        <svg class="w-6 h-6" fill="currentColor" viewBox="0 0 20 20" xmlns="http://www.w3.org/2000/svg"><path d="M2 10a8 8 0 018-8v8h8a8 8 0 11-16 0z"></path><path d="M12 2.252A8.014 8.014 0 0117.748 8H12V2.252z"></path></svg>
                     </button>

               etc

               etc

A: You can toggle classes using the Alpine.js x-bind:class object syntax, eg. :class="{ 'active classes': openTab === 1 }" for your first tab, see the following snippet. You could also bind :disabled="openTab !== 1" to disable the button (for the first button).

  <button :class="{ 'active classes': openTab === 1 }" class="p-1 mr-1 text-gray-500 rounded-lg outline-none active:text-gray-200 hover:text-gray-200 focus:text-gray-200 focus:outline-none hover:bg-gray-700 focus:bg-gray-700" type="button" @click="openTab = 1" autofocus>
    <svg class="w-6 h-6" fill="currentColor" viewBox="0 0 20 20" xmlns="http://www.w3.org/2000/svg"><path d="M9 2a1 1 0 000 2h2a1 1 0 100-2H9z"></path><path fill-rule="evenodd" d="M4 5a2 2 0 012-2 3 3 0 003 3h2a3 3 0 003-3 2 2 0 012 2v11a2 2 0 01-2 2H6a2 2 0 01-2-2V5zm3 4a1 1 0 000 2h.01a1 1 0 100-2H7zm3 0a1 1 0 000 2h3a1 1 0 100-2h-3zm-3 4a1 1 0 100 2h.01a1 1 0 100-2H7zm3 0a1 1 0 100 2h3a1 1 0 100-2h-3z" clip-rule="evenodd"></path></svg>
  </button>

  <button :class="{ 'active classes': openTab === 2 }" class="p-1 mr-1 text-gray-500 rounded-lg outline-none hover:text-gray-200 focus:text-gray-200 active:text-gray-200 focus:outline-none hover:bg-gray-700 focus:bg-gray-700" type="button" @click="openTab = 2">
  <svg class="w-6 h-6" fill="currentColor" viewBox="0 0 20 20" xmlns="http://www.w3.org/2000/svg"><path d="M2 10a8 8 0 018-8v8h8a8 8 0 11-16 0z"></path><path d="M12 2.252A8.014 8.014 0 0117.748 8H12V2.252z"></path></svg>
  </button>


Q: Why doesn't os.system ignore SIGINT? I am reading Linux System Programming.
When introducing the system(command) function, the book states that during execution of the command, SIGINT is ignored.
So, assuming that os.system is just a wrapper of the underlying system function, I try the following:
loop.py
while True:
      print 'You should not be able to CTRL+C me ;p'

test_loop.py
   import os
   os.system("python loop.py")

Now that I'm executing loop.py with system, I'm expecting SIGINT to be ignored, but when I use CTRL+C on the running program it still get killed.
Any idea why os.system differ from the system() function?

A: SIGINT is ignored by the application that calls system (for as long as system is executing). It's not ignored by the application that's spawned by system. So if you hit CTRL+c, that will abort the execution of loop.py, but not of test_loop.py. So if you add some code after the call to system, you'll see that that code will execute after you press CTRL+c.


Q: Should we leave our Xerox Phaser on, or turn them on only when we need them? Looking for where the cutoff is for keeping the Phaser on, or turning it off.
We have a Xerox Phaser 8550 - and we print to it about once a week.  However, we feel like it is burning through a ton of ink being left on (in powersave).  We would like to turn it off but are worried about it either clogging up if it is left off, or breaking with the on/off cycles.
So how long do you need to go between print jobs to before it makes sense to turn on and off the printer between jobs.

A: Thanks everyone, you actually gave me some ideas to go off of in terms of additional research, and it looks to be an issue with Ink Purging, combined with other factors:
Ink Purge - When the printer is idle for 2 days or more, it cools down completely. When the printer exits the cool-down mode after being idle for 2 days, it purges ink as part of the warm-up cycle. The printer is ready to print in about 20 minutes. This also seems to be referred to as a "Full Warmup"
http://www.fixya.com/support/t1394230-turn_off_cleaning_page_feature_in_xerox
http://www.office.xerox.com/userdoc/P300X/users/06chapt7.html (different printer but seems like it explains the problem).
1) Learning Usage Patterns (thanks Eric) - I suspect the system was seeing usage once a week on different days, and is sometimes coming out of powersave - doing an Ink Purge.  We have turned this feature off.
2) Power Outages - we occasionally have power outages - once every other month.  This will cause an ink purge.
3) Since we only print ~1 time a week. The printer needs to do a ink purge when it prints too.
Looking at how much ink ends up in the tray after an ink purge, we are probably using a decent chunk of a stick a week. I cannot find numbers on the amount of ink, but it definitely looks like quite a bit judging by the pictures in the Repair Manual.
Looking through the 8550 manual , I see nothing about leaving the printer off for a long period of time.
And after doing some more searches I came up with this:

Note:You should leave the printer on
  if you use it frequently (such as
  during a normal work week with daily
  use). The printer has an automatic
  standby mode that keeps the printer
  ready to use and reduces energy
  consumption. If the printer will be
  idle for two days or more (such as
  over a weekend), turn it off.

http://www.office.xerox.com/userdoc/P300X/users/02chapt4.html
So, I think to save some power, and avoid any accidental ink purges, I will keep the printer off when not in use.

A: Leaving a printer on shouldn't burn any ink at all (unless it's printing, obviously). If you're only printing once a week it's probably worth the power savings to turn it off completely. Most printers burn 20 to 50 cents per day in electricity while in standby (sometimes much more).

A: we had a xerox phaser (dry ink) printer and left it on for years.  The neat thing about the Xerox Phasers is that they would learn usage patterns.  For example, if I came into the office early, I would notice the printer coming out of sleep mode around the time we would normally begin using the unit.  If I came in at my normal time, I would notice the printer already warmed up and ready.
We left ours on for 3-4 years we had it.  We no longer use the printer as the hardware failed after it's warranty.

A: Is there a possiblity that someone is doing a large amount of after-hours printing on it? There's almost certainly a page counter on it so it wouldn't be hard to detect any unathorized usage that is using up all that ink.


Q: Do replaced quests reappear in Duelyst? In Duelyst, if I replace a quest, does it ever re-appear?
I've only ever skipped one quest ("play four games as [some faction]"), and I don't complete quests often enough to know for sure if it's going to come back or not.


Q: Perfect minimal hash for mathematical combinations First, define two integers N and K, where N >= K, both known at compile time. For example: N = 8 and K = 3.
Next, define a set of integers [0, N) (or [1, N] if that makes the answer simpler) and call it S. For example: {0, 1, 2, 3, 4, 5, 6, 7}
The number of subsets of S with K elements is given by the formula C(N, K). Example
My problem is this: Create a perfect minimal hash for those subsets. The size of the example hash table will be C(8, 3) or 56.
I don't care about ordering, only that there be 56 entries in the hash table, and that I can determine the hash quickly from a set of K integers. I also don't care about reversibility.
Example hash: hash({5, 2, 3}) = 42. (The number 42 isn't important, at least not here)
Is there a generic algorithm for this that will work with any values of N and K? I wasn't able to find one by searching Google, or my own naive efforts.

A: There is an algorithm to code and decode a combination into its number in the lexicographical order of all combinations with a given fixed K. The algorithm is linear to N for both code and decode of the combination. What language are you interested in?
EDIT: here is example code in c++(it founds the lexicographical number of a combination in the sequence of all combinations of n elements as opposed to the ones with k elements but is really good starting point):
typedef long long ll;

// Returns the number in the lexicographical order of all combinations of n numbers
// of the provided combination.
ll code(vector<int> a,int n)
{
    sort(a.begin(),a.end());
    int cur = 0;
    int m = a.size();

    ll res =0;
    for(int i=0;i<a.size();i++)
    {
        if(a[i] == cur+1)
        {
            res++;
            cur = a[i];
            continue;
        }
        else
        {
            res++;
            int number_of_greater_nums = n - a[i];
            for(int j = a[i]-1,increment=1;j>cur;j--,increment++)
                res += 1LL << (number_of_greater_nums+increment);
            cur = a[i];
        }
    }
    return res;
}
// Takes the lexicographical code of a combination of n numbers and returns the
// combination
vector<int> decode(ll kod, int n)
{
    vector<int> res;
    int cur = 0;

    int left = n; // Out of how many numbers are we left to choose.
    while(kod)
    {
        ll all = 1LL << left;// how many are the total combinations
        for(int i=n;i>=0;i--)
        {
            if(all - (1LL << (n-i+1)) +1 <= kod)
            {
                res.push_back(i);
                left = n-i;
                kod -= all - (1LL << (n-i+1)) +1;
                break;
            }
        }
    }
    return res;
}

I am sorry I have an algorithm for the problem you are asking for right now, but I believe it will be a good exercise to try to understand what I do above. Truth is this is one of the algorithms I teach in the course "Design and analysis of algorithms" and that is why I had it pre-written.

A: This is what you (and I) need:
hash() maps k-tuples from [1..n] onto the set 1..C(n,k)\subset N.
The effort is k subtractions (and O(k) is a lower bound anyway, see Strandjev's remark above):
// bino[n][k] is (n "over" k) = C(n,k) = {n \choose k}
// these are assumed to be precomputed globals

int hash(V a,int n, int k) {// V is assumed to be ordered, a_k<...<a_1
  // hash(a_k,..,a_2,a_1) = (n k) - sum_(i=1)^k (n-a_i   i)
  // ii is "inverse i", runs from left to right

  int res = bino[n][k];
  int i;

  for(unsigned int ii = 0; ii < a.size(); ++ii) {
    i = a.size() - ii;
    res = res - bino[n-a[ii]][i];
  }
  return res;
}


Q: What is the equivalent SOAP API call to the command *S? We have an agent desktop application that runs against the current PNR/session in Sabre Red.  We're using Native API to interact with Sabre Red and we have a Sabre Red App.
If an agent begins to build a reservation/PNR and has NOT ended the current PNR, the data in GetReservation.ReservationPNRB.POS.Source.PseudoCityCode is empty.  We need to know what PCC (Pseudo City Code) the agent is working it.  Is there a way to 'get current context' (agent session) via SOAP API?  The equivalent Sabre command would be *S.  If not, I assume this value would be available within the Red App SDK and plug-in environment?

A: could be the SabreCommandLLSRQ which can be used to use host commands but using soap.


Q: Need assistance with below query I'm getting this error:

Error tokenizing data. C error: Expected 2 fields in line 11, saw 3

Code: import webbrowser
website = 'https://en.wikipedia.org/wiki/Winning_percentage'
webbrowser.open(website)
league_frame = pd.read_clipboard()

And the above mentioned comes next.

A: I believe you need use read_html - returned all parsed tables and select Dataframe by position:
website = 'https://en.wikipedia.org/wiki/Winning_percentage'
#select first parsed table
df1 = pd.read_html(website)[0]
print (df1.head())
  Win %  Wins  Losses  Year                     Team                  Comment
0  0.798    67      17  1882  Chicago White Stockings   best pre-modern season
1  0.763   116      36  1906             Chicago Cubs  best 154-game NL season
2  0.721   111      43  1954        Cleveland Indians  best 154-game AL season
3  0.716   116      46  2001         Seattle Mariners  best 162-game AL season
4  0.667   108      54  1975          Cincinnati Reds  best 162-game NL season

#select second parsed table
df2 = pd.read_html(website)[1]
print (df2)
   Win %  Wins  Losses   Season                   Team  \
0  0.890    73       9  2015–16  Golden State Warriors
1  0.110     9      73  1972–73     Philadelphia 76ers
2  0.106     7      59  2011–12      Charlotte Bobcats

                      Comment
0         best 82 game season
1        worst 82-game season
2  worst season statistically