text:
Q: List, dictionary, and tuple values a=[{"a":30},{"c":("a","=","c")}]

I need values of "c".
for x in a[1].values():
    for j in x:
        print(j, end=" ")

This is my solution but if you have any other short solution for this then tell me.

A: You could simply say
for element in a[1]['c']:
       print(element,end=" ")

A: >>> print(' '.join(*a[1].values()))
a = c

A: If you just need the values to be printed, you can unpack the tuple as arguments to print:
print(*a[1]['c'])

A: The same result can be achieved with a comprehension:
>>> a=[{"a":30},{"c":("a","=","c")}]
>>> print(*(_ for _ in a[1]['c']))
a = c
>>>


text:
Q: Can't set action in aui:form although I named the action in MVCPortlet I'm having a bit of a problem tracing where this error comes from, in my jsp I have a form set like this:
<jsp:useBean id="usuario" type="com.cide.cajaVirtual.EContinua.model.Estudiantes" scope="request">
</jsp:useBean>
<jsp:useBean id="compras" type="com.cide.cajaVirtual.EContinua.model.EstudiantesCompras" scope="request">
</jsp:useBean>

<% Calendar now = CalendarFactoryUtil.getCalendar(); %>
<portlet:actionURL name="registrarCompra" var="registrarCompraURL">
<aui:form name="fmCompra" action="<%=registrarCompraURL.toString() %>" method="post">

Then in my portlet class I have:
public class CajaVirtualPortlet extends MVCPortlet {
    /*
 * El portlet RegistroUsuariosComprasPortlet permite a los estudiantes llenar la    forma
 * de registro y hacer una compra de la oferta de Educación Continua
 *
 */

public void addCompra(ActionRequest request, ActionResponse response) throws   Exception {
    ThemeDisplay themeDisplay =
            (ThemeDisplay) request.getAttribute(WebKeys.THEME_DISPLAY);

}

public void registrarCompra(ActionRequest request, ActionResponse response) throws   Exception {
}

But I keep getting the error on Eclipse that says "registrarCompraURL cannot be resolved"
I ask this because honestly I don't have an idea of what I'm doing wrong, as I said I lost trace of what I was doing while typing in Eclipse. Please someone help!

A: I suspect portlet action url tag is not closed thats why you are facing this issue.
Try <portlet:actionURL name="registrarCompra" var="registrarCompraURL"/>
Also make sure you have taglib declared for it like.
<%@ taglib uri="http://java.sun.com/portlet_2_0" prefix="portlet" %>

redpajama_set_name: RedPajamaStackExchange


text:
Q: Is UIPageControl customization legal? I've found out that it's very easy to customize UIPageControl page images (I've checked it for iOS7/8):
[self setValue:[UIImage imageNamed:@"my_icon_for_off_state"] forKey:@"_pageImage"];
[self setValue:[UIImage imageNamed:@"my_icon_for_on_state"] forKey:@"_currentPageImage"];

But I wonder can I publish my app with this code, because these variables are declared as private in UIPageControl?

A: As per Apple, you can't use private API's in your project.
However we can. Don't worry. Just be honest and while submitting the app, inform them that you have used xyz code.
Apple DON'T approve the app where insecure private API's are used.
Many times, I used private API's and Apple approved it.
Honesty is simplicity.
One of the example

A: As you've already stated, those properties are declared private by Apple so you will be unable to use them. You can change the tint color of the page "dots" by using pageIndicatorTintColor and currentPageIndicatorTintColor.


text:
Q: How to get the "helped" class from an helper class function? I'm trying to write an helper class function without statically referencing to the helped class:
  TMyEnum = (meA, meB, meC);
  TMyEnumHelper = record helper for TMyEnum
  public
    class function InRange(AValue : integer) : Boolean; static;
  end;

...

class function TMyEnumHelper.InRange(AValue : Integer) : Boolean;
begin
  Result := (
    (AValue >= Ord(Low(TMyEnum))) and
    (AValue <= Ord(High(TMyEnum)))
  );
end;

Is there a way to dynamically get the helped class?
I mean something like the following code:
class function TMyEnumHelper.InRange(AValue : Integer) : Boolean;
begin
  Result := (
    (AValue >= Ord(Low(HelpedClass))) and
    (AValue <= Ord(High(HelpedClass)))
  );
end;

I've tried using Self but Delphi says E2003 Undeclared identifier: 'Self'

A: Static class methods have no "self" parameter. They also cannot access any instance members. (They still have access to class fields, class properties, and class methods.)
In this case (the helper is a record helper), the class method must be declared as static.
As @David points out, an ordinary class method (not static) can refer to its type with the "Self" key, but only when it is referring to a class.
Example:
type
  TMyClass = class
  end;
  TMyClassHelper = class helper for TMyClass
     class function NameOfClass : String;
  end;

class function TMyClassHelper.NameOfClass : String;
begin
  Result := Self.ClassName;
end;

If the enumeration is contiguous, you can use a generics "helper" method to get the range using RTTI.
type
  TRttiHelp = record
    class function EnumInRange<TEnum>(AValue: Integer) : Boolean; static;
  end;

class function TRttiHelp.EnumInRange<TEnum>(AValue: Integer) : Boolean;
var
  typeData: PTypeData;
begin
  if GetTypeKind(TEnum) <> tkEnumeration then
    raise EInvalidCast.CreateRes(@SInvalidCast);

  typeData := GetTypeData(TypeInfo(TEnum));
  Result := (AValue >= typeData.MinValue) and (AValue <= typeData.MaxValue);
end;

type
  TMyEnum = (a,b,c);
begin
  WriteLn(TRttiHelp.EnumInRange<TMyEnum>(2));  // Writes true
end.


text:
Q: Application of Differentiation (Doesn't understand) It's given the cubic equation $x^3-12x-5=0$.  Show graphically that the iteration $x_{n+1}=\sqrt[3]{12x_n+5}$ should be used to find the most negative root and the positive root, and the iteration $x_{n+1}=\dfrac{x^3_n-5}{12}$ should be used to find the other root.
This is the solution given by book,
$$x_{n+1}=\sqrt[3]{12x_n+5}$$
$$F'(x_n)=\frac{4}{\sqrt[3]{(12x_n+5)^2}}$$
$$F'(-3)=0.41$$
$$F'(-0.5)=4$$
$$F'(3)=0.34$$
I've a problem here. Where the -3,-0.5 and 3 come from?

A: The idea to find approximations of roots of $f(x) = 0$ starts with finding an integer $a$ such that a root lies between $a$ and $(a + 1)$. To ensure that this is so we need to guess some integers $a$ such that $f(a)f(a + 1) < 0$ i.e. $f(a)$ and $f(a + 1)$ are of opposite signs. Then by Intermediate Value Theorem there is a root of $f(x)$ between $a$ and $(a + 1)$.
Here $f(x) = x^{3} - 12x - 5$ and clearly we can see that $$f(0) = -5, f(1) = -16, f(2) = -21, f(3) = -14, f(4) = 9$$ so that there is a root in the interval $[3, 4]$. Again checking the negative integers we have $$f(0) = -5, f(-1) = 6$$ so that there is a root in interval $[-1, 0]$. Going to further negative values of $x$ we have $$f(-2) = 9, f(-3) = 4, f(-4) = -21$$ so that the third root lies between in $[-4, -3]$.
Now the method of iteration used here recasts the equation $f(x) = 0$ in the form $x = \phi(x)$ and uses the iteration $x_{n + 1} = \phi(x_{n})$ with suitable starting point $x_{0}$. The suitable starting is normally chosen to be one of the end-points of the interval in which the root lies. Sometimes a midpoint of the interval is also chosen.
Next we need to choose the $\phi(x)$ such that $|\phi'(x)| < k < 1$ (for some fixed number $k$) near the points of iteration $x_{i}$. This is needed to guarantee that the iteration converges to the desired root.
The solution has chosen $\phi(x) = \sqrt[3]{12x + 5}$ for one of the roots namely the one lying in interval $[-4, -3]$ and therefore the derivative $\phi'(-3) = 0.41$ has been calculated. (Your notation uses $F$ instead of $\phi$.) Similarly for the root in interval $[3, 4]$ the value $\phi'(3) = 0.34$ is used. In both the cases we see that the value of $|\phi'(x)|$ is less than $1$ and hence the iterations works.
However for the third root in $[-1, 0]$ it appears that the initial point of iteration is chosen as mid point $-0.5$ of the interval and then $\phi'(-0.5) = 4$ which is much greater than $1$. Choosing initial point as $0$ (or $-1$) would also give $|\phi'(x)| > 1$ so that the form of iteration needs to be changed for the iteration to converge.
For the root in $[-1, 0]$ we can write the equation as $$x = \frac{x^{3} - 5}{12}$$ so that $\phi(x) = (x^{3} - 5)/12$ and $\phi'(x) = x^{2}/4$. Clearly in this case $|\phi'(x)| < 1$ for any value of $x \in [-1, 0]$ and the iteration will converge.
I hope you now understand how we need to choose the form of iteration as well as the starting value for the iteration chosen.
Note: You should also read the textbook to understand why the condition $|\phi'(x)| < k < 1$ is needed to guarantee the convergence of iteration $x_{n + 1} = \phi(x_{n})$ to a root of equation $x = \phi(x)$. It is not very difficult to understand and you can revert back for more details.


text:
Q: Pushing input to seperate DOTenv file from function I'm in python.
How would I go about writing a function that takes in a name and then a value?
How do I push input to another file?
What I tried:
global key
key = ""
print(key)
# print("Key must be string.\n Key must have a length greater than or equal to 3.\n Key will be displayed in capital letters.")

def getKey(key:str="", value:str="") -> str:
  # Check type of key
  if(type(key) != str or type(value) != str):
    print("Type of key and value  must be a string.")
    getKey(key,value)
  # Check length of key and valuee
  if(len(key) < 3 and len(value) < 1):
    print("Length of key and value  must be 3 or more.")
    print("An error has occured.\n Fix it yourself damnit")
    getKey(key,value)

def appendKeyToDOTenn():
  # .ENV.APPEND(KEY) AS KEY,VALUE.. Help

A: Looks like the getKey function that you defined is also accepting and returning the value. So, I'm assuming that—

*

*You want to insert the key and value as parameters of the function.

*Do a bunch of validations like type checking and length checking.

*Return both the key and value if they pass the validation.

Then in the second function—

*

*You want to take the key and value from the return values of the first function.

*And send those to a second function that will append them as KEY=VALUE to a .env file.

Since the first function is taking both the key and value as parameters, let's rename the function. Also, I assumed that you'll appreciate simplicity over brevity at this point.
# In Python, it's canonical to use `snake_case` instead of `camelCase`.
def get_key_value(key: str, value: str) -> str:
    """This function gets the key for you."""

    # Check the type of the key using `isinstance` rather than `type`.
    if not isinstance(key, str):
        # Raising error as early as possible is considered idiomatic.
        raise TypeError("Type of `key` must be string.")

    # Doing the same for the value.
    if not isinstance(value, str):
        raise TypeError("Type of `value` must be string.")

    # Doing the length checking.
    if not len(key) >= 3:
        raise ValueError("Length of the `key` cannot be less than 3.")

    if not len(value) >= 1:
        raise ValueError("Lenght of `value` cannot be less than 1.")

    return key, value

Now, you can send the return values of the first function to the following function. This one will open a .env file in append-only mode and append the key, value in a newline.
def append_key_value_toenv(key, value):
    """This function appends key, value to the environment file."""

    # Open / create and open the .env file.
    with open("./.env", "a") as envfile:
        # Write your variables.
        print(f"Appending {key=}, {value=} to the environment file.")
        envfile.writelines([f"{key}={value}\n"])

You can tie together everything in the following way:
# script.py

# In Python, it's canonical to use `snake_case` instead of `camelCase`.
def get_key_value(key: str, value: str) -> str:
    """This function gets the key for you."""

    # Check the type of the key using `isinstance` rather than `type`.
    if not isinstance(key, str):
        # Raising error as early as possible is considered idiomatic.
        raise TypeError("Type of `key` must be string.")

    # Doing the same for the value.
    if not isinstance(value, str):
        raise TypeError("Type of `value` must be string.")

    # Doing the length checking.
    if not len(key) >= 3:
        raise ValueError("Length of the `key` cannot be less than 3.")

    if not len(value) >= 1:
        raise ValueError("Lenght of `value` cannot be less than 1.")

    return key, value

def append_key_value_toenv(key, value):
    """This function appends key, value to the environment file."""

    # Open / create and open the .env file.
    with open("./.env", "a") as envfile:
        # Write your variables.
        print(f"Appending {key=}, {value=} to the environment file.")
        envfile.writelines([f"{key}={value}\n"])

if __name__ == "__main__":
    key, value = get_key_value("HELLO", "WORLD")
    append_key_value_toenv(key, value)

When you run the script, you'll see a .env file created in your current directory (if it already doesn't exist) and the file will have a new line as HELLO=WORLD.


text:
Q: Add onclient click to ASP.NET button I have a button like this
<asp:Button ID="btncnclbkng" CssClass="divskyblue" runat="server" Text="CANCEL BOOKING" Enabled="false" Width="410px"  OnClientClick="return checkrecord();"/>

And javascript as below
function checkrecord()
    {
        if (confirm("Are You Sure")) {
            return true
        }
        else
            return false;
    }

If i remove Enabled="false" from button then it asks confirmation but i adding and removing eneble-disable property  of button in javascript after making enable then its not working
.Please suggest me how to onclient click property to asp.net button in javascript

A: Use disabled attribute for your input. As this is a server attribute you can't enable/disable using JavaScript.
JSFiddle


text:
Q: Three.JS UV Mapping for partial spheres In a previous question I was looking to map a stereographic projection onto a sphere for the sake of live-streaming a virtual reality event.
I ultimately learned quite a bit about UV mapping and was able to construct a very accurate mapping that looks incredible. However there's one thing I don't like about this mapping method: there's a hack where the bottom of the sphere has to map to "nothing", so I map it to a corner of the texture.
In an effort to improve upon this solution, I tried creating only a partial sphere by adjusting the theta length per the Three.JS documentation on SphereGeometry.
While I got the shape of the sphere right, I noticed something odd about the UV mapping:
var fov = 270;
var geometry = new THREE.SphereGeometry(
    1, // Radius
    50, // Horizontal segments
    50, // Vertical segments
    0, // Phi start
    2 * Math.PI, // Phi length
    Math.acos((360 - fov) * Math.PI / 180 / 2), // Theta start
    Math.PI - Math.acos((360 - fov) * Math.PI / 180 / 2) // Theta length
);
var minX, minY, minZ, maxX, maxY, maxZ;
var faceVertexUvs = geometry.faceVertexUvs[0];
for ( var i = 0; i < faceVertexUvs.length; i++ ) {
    var face = geometry.faces[i];
    for ( var j = 0; j < 3; j ++ ) {
        var x = face.vertexNormals[j].x;
        var y = face.vertexNormals[j].y;
        var z = face.vertexNormals[j].z;

        // Capture the upper and lower bounds for all points
        if (!minX || x < minX) minX = x;
        if (!maxX || x > maxX) maxX = x;
        if (!minY || y < minY) minY = y;
        if (!maxY || y > maxX) maxY = y;
        if (!minZ || z < minZ) minZ = z;
        if (!maxZ || z > maxZ) maxZ = z;
    }
}
console.log("minX: " + minX + ", maxX: " + maxX);
console.log("minY: " + minY + ", maxY: " + maxY);
console.log("minZ: " + minZ + ", maxZ: " + maxZ);

I learned previously when performing UV mapping that the x, y, and z values range from -1 to 1 - regardless of the actual size of the mesh. If the sphere had a radius of 1 or a radius of 100, an x value of 1 means "the far right of the sphere" and a y value of 1 means "the top of the sphere". However when I have an incomplete sphere like this (using thetaStart and thetaLength to cut a hole in the top of the sphere) suddenly maxY was equal to about 0.7854.
Why is it that this mesh ends at 0.7854 instead of scaling from -1 to 1? I had hoped that by changing the shape of the sphere I could simplify my UV mapping logic (removing the scaledY term from my previous question that I linked) however altering the shape of the sphere seems to have had no affect on the UV map.
Is there a way to tell Three.JS that this partial sphere is the full shape and its coordinates should range from -1 to 1?

A: I believe you're confusing Normals with UVs in your description and code snippet. You're reading the value of Normals above in these lines:
    var x = face.vertexNormals[j].x;
    var y = face.vertexNormals[j].y;
    var z = face.vertexNormals[j].z;

With your SphereGeometry attributes, the min and max y normals match the expected result:
What you want to do is look at the min and max UV values. I've updated the code to get UV values:
var fov = 270;
var geometry:THREE.SphereGeometry = new THREE.SphereGeometry(
    2, // Radius
    50, // Horizontal segments
    50, // Vertical segments
    0, // Phi start
    2 * Math.PI, // Phi length
    Math.acos((360 - fov) * Math.PI / 180 / 2), // Theta start
    Math.PI - Math.acos((360 - fov) * Math.PI / 180 / 2) // Theta length
);
var minX, minY, minZ, maxX, maxY, maxZ;
var faceVertexUvs = geometry.faceVertexUvs[0];

for ( var i = 0; i < faceVertexUvs.length; i++ ) {
    var vertUV = faceVertexUvs[i];
    for ( var j = 0; j < 3; j ++ ) {
        var x = vertUV[j].x;
        var y = vertUV[j].y;

        // Capture the upper and lower bounds for all points
        if (!minX || x < minX) minX = x;
        if (!maxX || x > maxX) maxX = x;
        if (!minY || y < minY) minY = y;
        if (!maxY || y > maxX) maxY = y;
    }
}
console.log("minX: " + minX + ", maxX: " + maxX);
console.log("minY: " + minY + ", maxY: " + maxY);

When you run this code, you'll see that the range is always [0, 1], not [-1, 1]. Additionally, keep in mind that UVs don't have a Z value; only X and Y, since they're used to map a 2-dimensional image.
Normals:

*

*x: (-1, 1)

*y: (-1, 1)

*z: (-1, 1)

UVs:

*

*x: [0, 1]

*y: [0, 1]

You can see how ThreeJS builds sphere UVs in this code, specifically in lines 90, 94, and 111.


text:
Q: Node.js: Long-polling with EventEmitter and Express 4.x | Catching request close I'm long-polling node.js route with JQuery's ajax request (xhr). This sends a GET request to my Express server and listens for message bus events. I'm setting a timeout on that GET request (as my proxy would kill long requests). So after the timeout, an abort event should be sent by the client to the server.
I want to catch that abort/close/finish event and remove the relevant message bus listener/subscriber.
But I struggle. I tried req.on("close"..) and the on-finished npm module, but that didn't work for me. I'm also not much more clever after reading the http documentation of node: https://nodejs.org/api/http.html.
Any ideas how to tackle this beast? Or better ways to remove listeners to prevent memory leaks?
Server side essentials:
// server.js
var express = require("express");
var EventEmitter = require("events").EventEmitter;
var messageBus = new EventEmitter();
messageBus.setMaxListeners(20);

var REST_PORT = (process.env.PORT || 5000);
var app = express();

app.get("/events", (req, res) => {
    var listener = function(res) {
        messageBus.once("message", function(data) {
            res.status(200).json(data);
        });
    };
    req.on("abort", function() { //I tried also "aborted", "close", "closed", "finish", "finished"..no luck
        messageBus.removeListener("message", listener);
    });

    listener(res);
    console.log("Total listeners to 'message' events:", messageBus.listeners("message").length);
});

// other messageBus.emit logic ..

app.listen(REST_PORT, () => {
    console.log("Application ready on port " + REST_PORT);
});

Client side essentials:
//client.js
$.ajax({
    method: "GET",
    async: true,
    url: "/events",
    success: function(data) {
        callback(data);
    },
    complete: function(request, status, err) {
        if (status == "timeout" || status == "success") {
            console.log("LOG: Normal long-polling timeout or successful poll, continuing.");
            longPoll();
        } else {
            console.warn("WARN: Server probably offline, retrying in 2 sec.");
            setTimeout(function() {
                longPoll();
            }, 2000);
        }
    },
    timeout: 30000
});

Thank you!

A: If this helps someone, I finally decided to implement the long-polling differently and killing the client request at the server side after certain timeout. This works for me nicely and after reflection, is probably better mechanism than trusting the client to close the requests correctly.
setTimeout(() => {
    if (!responded) {
        messageBus.removeListener("message", listener);
        res.status(204).end();
    }
}, 30000);

A: I recommend aborting your custom long-polling system altogether and using one of the existing messaging/socket-type systems.  There are many that are fully formed.  socket.io is the most popular still and works well, but some alternatives like these might be better https://www.reddit.com/r/node/comments/4ktqae/socketio_alternatives/


text:
Q: How to remove all simultaneous connections from firebase I am making a web app with firebase Realtime database with free plan having 100 simultaneous connection limit. I have logged in with only one google account. But it is showing 3 simultaneous connections every time. Yes, sometimes it drops to 2 connections but not below 2. I can recall that few days ago I had signed in with 2 custom made email-password authentication. But now I have logged out from both of them and deleted the 2 accounts and I have also disabled email-password authentication method. Still it is showing 3 simultaneous connection. Reminding you currently I am logged in with only 1 google account still it is showing 3 simultaneous connections.
How to solve this problem?
OR
Tell me some way to manually remove all simultaneous connection from firebase Realtime Database, so that I can retry by logging in with different methods and debug that what is actually causing this issue?

A: A simultaneous connection is any client currently connected to your app, this is specifically any instances of your firebase that has connected with your project credentials regardless of a user logging in or not.
Per the documentation

A simultaneous connection is equivalent to one mobile device, browser tab, or server app connected to the database.

I do believe that the counter is also delayed by an hour or two to reduce live update bandwidth and logging into your Firebase console itself also counts as a connection.


text:
Q: Proving that something cannot be a coordinate ring of an affine variety This was the problem that was given: Let $k$ be a field and define
$R = \frac{k[x, y]} {< x^2 >}$ Prove that R cannot be the coordinate ring of a variety $V \subseteq A^2_k$.
I'm confused about what the question is actually asking. I know that a coordinate ring of a variety is of the form: $\frac{k[x_1,x_2...x_n]}{I(V)}$. However, I don't really understand that $R$ cannot be a coordinate ring in this case.

A: A coordinate ring is always a reduced ring, because $I(V)$ is necessarily radical. On the other hand $k[x,y]/(x^2)$ has some obvious nonzero nilpotent elements.


text:
Q: Android Call log date convertion I have a call log backup from my Android mobile phone, and I'm trying to know the date & time of the calls.
The log says:
<HTCCALLOG>
new=1
numbertype=3
duration=28
number=PERSON'S PHONE NUMBER
type=1
_id=1853
numberlabel=null
name=PERSON'S NAME
date=1333119990954

Here's the problem. When I try to converto do Date Time (I'm using .Net's CSsharp), I got the following date 02/01/0001 01:01:51, which of course is not the valid date of the call.
Trying to convert today's date and time to a long number from UTC format, I got 130134760479804654 which is a larger number than those in the log file.
Could someone points me what I'm doing wrong? Following is the code.
    long datelong = long.Parse("1333119793100");
    DateTime date = new DateTime(datelong, DateTimeKind.Utc);

    Console.WriteLine(date.ToString("dd/MM/yyyy hh:mm:ss"));

    DateTime today = DateTime.Now;
    Console.WriteLine("\n\n{0}\n{1}", today.ToFileTimeUtc(), datelong);

    Console.ReadKey();

Thanks very much

A: Sorry, I don't know too much of Unix word. Googleing a little, I found that this is the 'epoch' time, so I found out a convertion function:
public DateTime FromUnixTime(long unixTime)
{
    var epoch = new DateTime(1970, 1, 1, 0, 0, 0, DateTimeKind.Utc);
    return epoch.AddSeconds(unixTime);
}

Thanks anyway.

A: +998999431294</phoneNumber><dateTime>1624939282459</dateTime><callDuration>15</callDuration><logType>2</logType></callLog><callLog><phoneNumber>+998937031331</phoneNumber><dateTime>1624939219493</dateTime>


text:
Q: ScriptResource.axd path is too long here is my problem.
I develop web applications, and I use IIS to host them.
I also used the module ARR (application request routing) as a proxy for my server farm. The problem is the ARR cache the pages on disk. I have ScriptResource  cached in the arr cache disk, and when I try to delete the access path is too long.
Is there a way to shorten the name of the script resources?
thank you

A: If you use ASP.NET 4.0 you can use CDN version of scripts and get additional benefits. Just set EnableCdn property of your script manager to true and your script links will look like this :
<script src="http://ajax.microsoft.com/ajax/4.0/1/WebForms.js" type="text/javascript"></script>
<script src="http://ajax.microsoft.com/ajax/4.0/1/MicrosoftAjax.js" type="text/javascript"></script>
<script src="http://ajax.microsoft.com/ajax/4.0/1/MicrosoftAjaxWebForms.js" type="text/javascript"></script>


text:
Q: appcompat-v7:27.1.1 CardView not showing in previous apis I'm compiling for SDK 27 and I used these dependency:
implementation 'com.android.support:appcompat-v7:27.1.1'
implementation 'com.android.support:design:27.1.1'

However, I can't change 27 to a previous version as it spits an error with some cache problem. The program runs and I can see the card view on my phone as it's running the latest SDK. But when I take a phone with an older SDK (say 6.0), the cardview does show. This is my output if I change targetSDK to 23 and compileSDK to 23. and:
implementation 'com.android.support:appcompat-v7:23.0.1
implementation 'com.android.support:design:23.0.1'

This is the error:

AGPBI: {"kind":"error","text":"error: resource android:attr/colorError not found.","sources":[{"file":"/root/.gradle/caches/transforms-1/files-1.1/appcompat-v7-27.0.2.aar/1642e61f47dd91a1acce6e369ec672e9/res/values-v26/values-v26.xml","position":{"startLine":8,"startColumn":4,"startOffset":431,"endLine":11,"endColumn":12,"endOffset":652}}],"original":"","tool":"AAPT"}

A: Try to add in your dependencies:
implementation 'com.android.support:cardview-v7:21.1.1'


text:
Q: Filtering DataGridView By Date Prior to Printing I am filtering the DataGridView by a TIMESTAMP column so users can determine the date of data to print. Following is how I am creating my filtered DataGridView. However, in order to get the correct dates for instance Feb 8, 2010 to Feb 10, 2010, I have to select one date prior so the date range has to be Feb 7, 2010 to Feb 10, 2010 to get Feb 8, 2010 to Feb 10, 2010. This is too confusing for users.
TIMESTAMP is declared as SqlDbType.DateTime.
Where am I screwing up?
private void CreateFilteredDataGridView(DataGridView dgv, string fromDate, string toDate)
{
    try
    {
        myDataSet = new DataSet();
        myDataSet.CaseSensitive = true;

        DataAdapter.SelectCommand.Connection = myConnection;
        DataAdapter.TableMappings.Clear();
        DataAdapter.TableMappings.Add("Table", "GARAGE");
        DataAdapter.Fill(myDataSet);

        myDataView = new DataView(myDataSet.Tables["GARAGE"], "TIMESTAMP >= '" +
        Convert.ToDateTime(fromDate) + "' AND TIMESTAMP <= '" +
        Convert.ToDateTime(toDate) + "'", "TIMESTAMP", DataViewRowState.CurrentRows);

        dgv.DataSource = myDataView;
    }
    catch (Exception ex)
    {
        MessageBox.Show(ex.Message);
    }

}

A: I can't tell what time you're passing in to that method, but it's possible that the time portion of your DateTime is causing the problem. Make sure that the from date starts at 00:00:00 (which it should already if no time is included) and that the end date contains 23:59:59.


text:
Q: How to use logdna CLI with IBM Cloud hosted LogDNA I am trying to get the logdna cli working with the IBM Cloud hosted LogDNA offering. I would like to search and tail logs from my machine without using the LogDNA UI.
The logdna CLI install is trivial to install but the instructions assume you are using the main logDNA hosted by logdna.com. Anyone have any instructions on how to get it working with IBM Cloud's instances?
https://docs.logdna.com/docs/logdna-cli
https://github.com/logdna/logdna-cli
The .logdna.conf file looks like this but I assume I need to put the public endpoints for my us-east logDNA instances. I am not sure how this would be integrated with the IAM IBM Cloud uses.
Too IBM Cloud folks, The loganalysis-logdna tag does not exist and I don't have the stackoverflow reputation to create it. :(
VERSION_CHECK_URL = https://repo.logdna.com/mac/version
UPDATE_CHECK_URL = https://repo.logdna.com/mac/logdna.gz
UPDATE_CHECK_INTERVAL = 86400000
SSO_URL = https://logdna.com/sso/
SSO_LONG_PATH = /ext/cli-sso/
SSO_POLL_INTERVAL = 5000
DEFAULT_CONF_FILE = /Users/blah/.logdna.conf
LOGDNA_APIHOST = api.logdna.com
LOGDNA_TAILHOST = tail.logdna.com
LOGDNA_APPHOST =
LOGDNA_APISSL = true
SUPPORTS_COLORS = true
updatecheck = 1587180105124
email = user@example.com
account = XXXX
key = XXXX
token = XXXX
servicekey = XXXXXX

A: The LogDNA CLI is not supported via SSO on IBM Cloud.


text:
Q: File sizes ordered by date If I had FSQL, I would write select size from directory1 order by date. But, I have a Windows and Cygwin. Windows Explorer can sort the items by date but it rounds the file sizes to much. So, I am looking for other options.

A: Since you have Cygwin, you can do this in the shell of a Cygwin terminal (mintty).
cd directory1
ls -lt

ls will list the files in the current directory, directory1. The -l option will use the long form for display, which includes file sizes, and the -t option will sort according to modification time. Use
man ls

to find more details on these and other options.


text:
Q: Python Commands For a login Page I need some help on how i would add more commands to this program to show a list of Films(or data) from a notebook or text file
def main():
command = username = password = ''
logged_in = False
while command != 'quit':
    command = input('Please type a command: ')
    if command == 'log in':
        logged_in, username, password = log_in()
    if command == 'log out':
        logged_in = False
        username = password = ''
    if command == 'new user':
        if not logged_in:
            new_user()
        else:
            print ('First logout to make a new user')

This Is the Full Code:
print("------------------Welcome------------------")
print("--Do you need to make a new user or login--")
def log_in():
username = input("Please enter your username : ")
password = input("Please enter your password : ")

with open('test_file.txt', 'r') as file:
    for line in file:
        if line == 'Username:{0}, Password:{1}'.format(username, password):
            print ("Greetings," , username, "you are now logged in")
            return True, username, password
print (" Sorry username and password incorrect please re-enter for
validation ")
return False, '', ''

def new_user():
succes = False
while not succes:
    new_user = input("Please enter your new username : ")
    new_pass = input("Please enter your new password : ")

    exists = False
    with open("test_file.txt","r") as file:
        for line in file:
            if line.split(',')[0] == 'Username:'+new_user:
                print ('Invalid username: {0} already
exsist'.format(new_user))
                exists = True

    if not exists:
        with open("test_file.txt","a") as file:
            file.write('Username:{0}, Password:{1}'.format(new_user,
new_pass))
            file.write("\n")
        succes = True
print ('You made a new user with username:{0} and password:
{1}'.format(new_user, new_pass))

def main():
command = username = password = ''
logged_in = False
while command != 'quit':
    command = input('Please type a command: ')
    if command == 'log in':
        logged_in, username, password = log_in()
    if command == 'log out':
        logged_in = False
        username = password = ''
    if command == 'new user':
        if not logged_in:
            new_user()
        else:
            print ('First logout to make a new user')

main()


text:
Q: Q: Non linear & non autonomous ode system How could be solved  (either numerically or analytically) the following dynamic system?
$$\frac{dv}{dt}=a(\frac{h+b.v^2}{h+b.v^2+c})$$
$$\frac{dh}{dt}=d-f.t-g.v$$
where: a, b,c,d,f and g are positive scalars.
Boundary conditions:
$v(0)=v_0$ and $h(0)=0$
This system is an preliminary model for my undergrade engineering thesis project which is about pulsatile flowes. Finally, i suppose that function solution will contain an exponential form.
Regards,


text:
Q: Get widget Title from widget id Is there anyway at all to get the title of a widget from the widget id? The post title can be used by using
get_the_title()

Is there a way to get the title for a widget using the same kind or function?

A: You can get the widget name from the widget id with this:
<?php
    global $wp_registered_widgets;
    $id = 'recent-comments-1';  // example
    if ( isset($wp_registered_widgets[$id]['name']) ) {
        echo $wp_registered_widgets[$id]['name'];
    }
?>

A: This worked for me in the dynamic_sidebar_params:
/**
 *  Get Widget instance title or widget name as a fallback.
 *  Returns empty widget titles too.
 *
 *  @param string $widget_id
 *  @return string Widget title or widget name
 */
function get_widget_title( $widget_id ) {

    global $wp_registered_widgets;

    // get instance
    $instance = $wp_registered_widgets[$widget_id]['callback'][0];
    // @see https://developer.wordpress.org/reference/classes/wp_widget/get_settings/
    $settings = $instance->get_settings();

    // fallback 1 – widget number can't be found
    if ( isset( $wp_registered_widgets[$widget_id]['params'][0]['number'] ) ) {
        $num = $wp_registered_widgets[$widget_id]['params'][0]['number'];
    } else {
        return $instance->name;
    }

    // nasty nesting
    if ( isset( $settings[ $num ]['title'] ) ) {
        return $settings[ $num ]['title'];
    }
    return $instance->name;

}


text:
Q: Can't load local file into mysql database So I will preface this by saying that I'm not all that skilled in MySQL (or regular SQL for that matter), but I'm trying to load data from a .txt file into my table that I keep for ticket sales. When I do that using:
LOAD DATA LOCAL INFILE '/path/presales1.txt' INTO TABLE presales

I get the '> prompter. And I have no idea what to do. I tried looking up solutions and the one I thought would work was:
--local-infile[=1]; because that is straight out the MySQL handbook. It didn't work (nor did any variation on it...such as local-infile=1;, local-infile=1 etc....)
Did I miss a simple step? My version of MySQL is 5.7

A: Watch carefully, everything is up my sleeve.
mysql> SELECT 'abc
    '>
    '>
    '> def';
+-----------+
| abc

def |
+-----------+
| abc

def |
+-----------+
1 row in set (0.00 sec)

Notice that my first line has a quote, but not the matching quote.  When I hit return; it prompted me with '> -- That's the clue that I need to balance the quotes.  Eventually, I did so, and the query terminated.
Look around, I suspect there is a stray quote on the preceding or following line.  Or the quotes around the filename aren't really the same.


text:
Q: Revit API How to make a external command run asynchrously? I have an External Command to create about 40 (or even more) Generic model
 in Revit. I want to make Revit run the command asynchronously to speed up the process according to this flow:
load command -> run command -> load families -> generate family instances asynchronously -> end command.
I 've read some ideas a bout make a modeless dialog to work around but it is not what I need. How can I do this?

A: Meiki is completely correct. The Revit API can only be used within a valid Revit API context, and such a context is provided exclusively by Revit events. You can however implement an external event and trigger that from outside to obtain access to a valid Revit API context. This is discussed in detail with many solutions provided by The Building Coder in the topic group on Idling and External Events for Modeless Access and Driving Revit from Outside.
Another approach might be to make use of the DocumentOpened Event. You could use that to trigger the execution flow you desire.
A third but unsupported approach might be to make use of a journal file, as in the IFC Import and Conversion Journal Script.
I would start out reading the numerous solutions listed in the topic group, and probably end up making use of an external event.
Good luck and have fun!

A: You can't run external command asynchronously for creating (or modifying) something because of Transactions and remember that Revit doesn't support Async methods or approaches. can you describe what you gonna do exactly maybe there is another approach.

A: According to the docs:

The Autodesk Revit API supports single threaded access only.  This means that your API application must perform all Autodesk Revit API calls in the main thread (which is called by the Autodesk Revit process at various API entry points), and your API application cannot maintain operations in other threads and expect them to be able to make calls to Autodesk Revit at any time.

However, I believe you could create an external API and consume it from your command.


text:
Q: Override Adminhtml importexport dataflow Profile Controller I'm trying to override ProfileController located in

app/code/core/Mage/Adminhtml/controllers/System/Convert/ProfileController.php

I created a new module to handle that as following :

app/etc/modules/FifoBox_ProductApproval.xml

<?xml version="1.0"?>
    <config>
        <modules>
            <FifoBox_ProductApproval>
                <active>true</active>
                <codePool>local</codePool>
            </FifoBox_ProductApproval>
        </modules>
    </config>

app/code/local/FifoBox/ProductApproval/etc/config.xml

<config>
    <modules>
        <FifoBox_ProductApproval>
            <version>1.0.0</version>
        </FifoBox_ProductApproval>
    </modules>
    <global>
         ....
    </global>
    <admin>
        <routers>
            <adminhtml>
                <args>
                    <modules>
                        <fifoBox_productapproval before="Mage_Adminhtml">FifoBox_ProductApproval_Adminhtml</fifoBox_productapproval>
                    </modules>
                </args>
            </adminhtml>
        </routers>
    </admin>
</config>

And My main class (controller) located in :

app/code/local/FifoBox/ProductApproval/controllers/Adminhtml/System/Convert/ProfileController.php

<?php require_once Mage::getModuleDir('controllers', 'Mage_Adminhtml') . DS . 'System' . DS . 'Convert' . DS . 'ProfileController.php';

class FifoBox_ProductApproval_Adminhtml_System_Convert_ProfileController extends Mage_Adminhtml_System_Convert_ProfileController {

    public function batchRunAction() {

        die('Overriden');
    }

} ?>

But Magento still call overriding (Original) method (i.e can't access my new class), even I tried to put the new controller file in
app/local/Mage/Adminhtml/controllers/System/Convert/ProfileController.php to avoid any xml config error but I got the same result, I cleared catch checked all logs even Apache ones with nothing
The only way I got my new code work is to modify the core file itself
Please help

A: Overriding controllers in app/code/local does not work, because controllers are not loaded with the Magento autoloader.
But I guess the reason that your controller is not used, is that there is a controller Mage_Adminhtml_System_Convert_GuiController that extends Mage_Adminhtml_System_Convert_ProfileController and the actual route is adminhtml/system_convert_gui/batchRun and not adminhtml/system_convert_profile/batchRun.
Try to add a class FifoBox_ProductApproval_Adminhtml_System_Convert_GuiController and see if this is used.


text:
Q: IE10 and ASP.NET 2.0 Button control I'm Still stuck cause of IE 10.
On page_load I tried to set :
Button1.Enabled = false;

and its not working only on IE10, on other browsers it works amazing.
Edit:
I have already updated ie.browser file. [Fix for most of the IE10 problems]
What can be done to fix this issue. Please somebody help me!

A: @Emma
This is the source code.
<%@ Page Language="VB" %>

<!DOCTYPE html PUBLIC "-//W3C//DTD XHTML 1.0 Transitional//EN" "http://www.w3.org/TR/xhtml1/DTD/xhtml1-transitional.dtd">

<script runat="server">

  Protected Sub Page_Load(sender As Object, e As System.EventArgs)
    Button1.Enabled = False
  End Sub

</script>

<html xmlns="http://www.w3.org/1999/xhtml">
  <head runat="server">
    <title></title>
  </head>
  <body>
    <form id="form1" runat="server">
      <div>
        <asp:Button ID="Button1" runat="server" Text="Button" />
      </div>
    </form>
  </body>
</html>

My Ie version:


text:
Q: ReactJS - New item even if the field is empty I'm practicing React and I'm making a TodoList Component. But currently, I can add a todo item that is empty. And I want a message saying that it's not allowed.
My issue is even if the field is empty, I can create a new item.
Here is my code:
import React, { Component } from "react";

class TodoList extends Component {
    constructor() {
        super();
        this.state = {
            userInput: '',
            items: []
        };
    }

    onChange(event) {
        this.setState({
            userInput: event.target.value
        }, () => console.log(this.state.userInput));
    }

    addTodo(event) {
        event.preventDefault();
        this.checkField();
        this.setState({
            userInput: '',
            items: [...this.state.items, this.state.userInput] },
            () => console.log(this.state.items));
    }

    deleteTodo(item) {
        const array = this.state.items;
        const index = array.indexOf(item);
        array.splice(index, 1);
        this.setState({
            items: array
        })
    }

    checkField() {
        if(this.state.userInput.length === 0) {

            let emptyMessageDom = document.createElement("p");
            document.body.appendChild(emptyMessageDom);
            emptyMessageDom.innerHTML ="This is empty!!"

        }
    }

    renderTodos() {
        return this.state.items.map((item, index) => {
            return (

                {item} {index} | <button onClick={this.deleteTodo.bind(this, item)}>X</button>

)
        })
    }

    render() {
        return(

                <form>
                    <input
                        value={this.state.userInput}
                        type="text"
                        placeholder="New item"
                        onChange={this.onChange.bind(this)}
                        required
                    />
                    <button onClick={this.addTodo.bind(this)}>Add</button>
                </form>

                    {this.renderTodos()}

        );
    }
}

export default TodoList;

I tried to put the code of the function checkField() into the setState of addTodo() function, but it doesn't work.
Thanks in advance!

A: You should use state to show an error message. This will help clean up the way you render and remove the message. Heres a full working example
Update addTodo to conditionally add based on your criteria.
addTodo(event) {
  event.preventDefault();
  if (!this.checkField()) {
    return
  }
  this.setState({
    userInput: '',
    items: [...this.state.items, this.state.userInput]
  })
}

and then update checkField to validate and return a boolean
checkField() {
  if(this.state.userInput.length === 0) {
    this.setState({error: 'Field is required.'})
    return false;
  }
  return true;
}

you can then update the render portion to show the error message
<form>
  <input
    value={this.state.userInput}
    type="text"
    placeholder="New item"
    onChange={this.onChange.bind(this)}
    required
  />
  {!!this.state.error && {this.state.error}}
  <button onClick={this.addTodo.bind(this)}>Add</button>
</form>

Then finally don't forget to remove the error when a change event happens on the input as the validation is now stale.
onChange(event) {
  this.setState(
    {
      userInput: event.target.value,
      error: ''
    }
  );
}

A: you can modify checkField ,addToDoas follows
 checkField() {
        if(this.state.userInput.length === 0) {

            let emptyMessageDom = document.createElement("p");
            document.body.appendChild(emptyMessageDom);
            emptyMessageDom.innerHTML ="This is empty!!"
           //invalid input to be added as to do item
           return false;

        }
        //valid input to be added as to do item
       return true
       }

     addTodo(event) {
        event.preventDefault();
        if(this.checkField())
       {
        this.setState({
            userInput: '',
            items: [...this.state.items, this.state.userInput] },
            () => console.log(this.state.items));
        }
        }


text:
Q: yo angular EACCESS error when creating package.json After having done the command line "yo angular" and following the difference steps, I got this error :
Screenshot error
I tried to run it as "sudo yo angular" but it did not fix the issue.
Any ideas of a solution ?
Thank you

A: Try some of these
npm cache clean

and
bower cache clean

Or
sudo chown username /var/root/.config/configstore/insight-yo.json

or
sudo chown /var/root/.config/configstore/insight-yo.json

I hope this helps.


text:
Q: Ampersand is not supporting in Appium driver.get method In my test, we need to call an url scheme for a diagnostics purpose but the method is not supporting &.
driver.get(abc-xx://qa-preview?adunit=banner) it is working
driver.get(abc-xx://qa-preview?adunit=banner&lat=10)
when I append & it is not working and throws the following message
org.openqa.selenium.WebDriverException: An unknown server-side error occurred while processing the command. Original error: Error attempting to start URI. Original error: Error: Error executing adbExec. Original error: 'Command '/Users/abc/Library/Android/sdk/platform-tools/adb -P 5037 -s 83f0374b42535532 shell am start -W -a android.intent.action.VIEW -d abc-xx\://qa-preview\?adunit\=banner\&ctg\=2280352\&flt\=0\&nwk\=54 com.abc.droid.qa' exited with code 127'; Stderr: '/system/bin/sh: com.abc.droid.qa: not found'; Code: '127' (WARNING: The server did not provide any stacktrace information)

I have encoded the URL and tried it is passing through but that is not supported in my app. In our app only normal URL is supported for scheme. Are there any workarounds for this problem?

A:  String url = "Your URL Containing &";
    String url1 = url.trim();
    String url2 = url1.replace(/&/g,"-");


text:
Q: angularjs how to avoid dynamic html compilation in controller? I am using google maps api to display some infowindow (google maps balloon windows).
var contentString = '

hello world

';
var infowindow = new google.maps.InfoWindow({
    content: contentString
});
//... add info window to google map object

This will display 'Hello world' in a balloon, when you click on a map marker. (A map marker is an icon on the map like the red pins you are used to.
I wanted the content of the infoWindow to be dynamic so I set the contentString to:
"

";
This gets inserted into the DOM of the page when the user clicks on a map marker.
To make this work I have to compile the above line, when it gets inserted into the DOM of the page.
I am using a directive that abstracts the use of the map like:

So, when clicking on a map marker, the directive will create the infoWindow, subscribe to the domReadyEvent of the inforWindow, show the infoWindow, and bubble up the domReadyEvent to the page controller.
infoWindow exposes a domReady event which I bubbled up through the directive, and I do something like this in my page controller:
        $scope.onInfoWindowDomReady = function () {
        $scope.$apply(function () {
            var element = document.getElementById("infoWindowContent");
            $compile(element)($scope);
        });
    };

The problem I'm having is that I don't like the dom manipulation I'm doing in the controller. Is there any other way I could do this? Should I put the compile inside the directive? Then the directive would know that the infoWindow content is dynamic and has to be compiled, which isn't true for all info windows.
An important thing to know is that infoWindow content can also be an html element (as opposed to static string), but I don't know if this can help in any way.

A: Using angular-ui it becomes a simple as this:

        <input type="text" ng-model="myText" required />

$scope.ClickOnMarker = function (marker) {
    $scope.myText = "Clicked on marker";
    $scope.myInfoWindow.open($scope.myMap, marker);
};

$scope.ClickMap = function ($event) {
    var newMarker = new google.maps.Marker({
        map: $scope.myMap,
        position: $event.latLng,
        hasChanges: true,
        isSaved: false,
    });

    $scope.myMarkers.push(newMarker);
    $scope.myText = "Clicked on map";
    $scope.ClickOnMarker($scope.currentMarker);
};

Hope it helps!


text:
Q: How Do I Properly Scope Nested #each Spacebars Iterators When Using Meteor? I have these nested iterators:

    {{#each detailsCollection}}

        <input type="checkbox" class='detailCheckbox'>
        {{detail}}

x

        <form class='form-inline'>

                <input type="text" id='{{_id}}' name='message' class="form-control" placeholder="message">

        </form>
        {{#each messagesCollection}}
            {{#if isMessageForThisDetail}}
                {{message.message}}
            {{/if}}
        {{/each}}

    {{/each}}

And I understand that I can access parent attributes from child template via handlebars path, from docs:

{{./name}} or {{this/name}} or {{this.name}}

But I need my helper isMessageForThisDetail to compare an attribute of the currently iterated messageCollection to the currently iterated parent detailsCollection.  My helper for that looks like this:
isMessageForThisDetail: function(){
    var message = messagesCollection.findOne({detailId: this._id});
    if(message != undefined){
        return this._id == message._id;
    } else {
        console.log('there is no message for this detail');
    }
}

But the context of this._id is the message, not the _id of the detail I want to compare a field of the message to.

A: You should be able to access the parent data like so:
isMessageForThisDetail: function() {
    var detailId = Template.parentData(1)._id;
    var message = messagesCollection.findOne({detailId: detailId});
    if(message)
      return this._id === message._id;
    else
      console.log('there is no message for this detail');
}

A: I was stuck in a similar way and found that the Template.parentData() approach currently doesn't work within event handlers (see https://github.com/meteor/meteor/issues/5491). User Lirbank posted this simple workaround:
Pass the data from the outer context to an html element in the inner context, in the same template:
{{#each companies}}
  {{#each employees}}
    Do something
  {{/each}}
{{/each}}

Now the company ID can be accessed from the event handler with something like
$(event.currentTarget).attr('companyId')

A: (not verified)
Option 1:
Template
{{#each companies}}
  {{#each employee this}}
    {{this}}
  {{/each}}
{{/each}}

Helper
var templateHelpers = {
    companies: function () {
    // array of companies
        return arrayOfCompanies;
    },
    employee: function (company) {
        var companyId = company.id;
         // do something with companyId
    }
}

Option 2:
Template
{{#each companies}}
  {{#each employee this.id}}
    {{this}}
  {{/each}}
{{/each}}

Helper
var templateHelpers = {
    companies: function () {
    // array of companies
        return arrayOfCompanies;
    },
    employee: function (companyId) {
         // do something with companyId
    }
}


text:
Q: Motion of an object in rotating frame Yesterday I was looking at an old sloan video that describes  motion in inertial and non-inertial frame. An experiment was actually like this. Two persons are sitting on the opposite side of a table fixed to a turning platform. The platform is rotating in uniform circular motion. Now Guy1 pushes  a ball over the frictionless surface of the table in a straight line towards Guy2. The question what will be the motion of the ball from a viewer inside the rotating frame and to someone outside in fixed frame of reference. I got little confused as to how to conceive the fictitious force. What will the motion be? In general, how to derive equation of motion in non-inertial frame. Please also add some good references on intuitive understanding of these type of problems.

A: The ball will move in a straight line according to an observer outside. But the observer is rotating, he will see ball deflecting away. This is called $\textbf{coriolis effect}$. Watch this video to understand properly.
coriolis effect

A: The motion for viewer inside rotating frame will be a straight line while for inertial frame observer or outside person it will be circular as motion is relative to the frame.


text:
Q: cordova-plugin-file-transfer plugin not working on Windows 10 sencha touch store app I have been using filetransfer plugin in our hybrid html app and it supports both widows 8.1 and ios and android but I also need it to work in Windows 10 store app. It seems like it cannot download file in windows 10 please suggest some alternative plugin to download files from server or if we got this work in windows 10
sample code below
var fileTransfer = new FileTransfer();
var uri = encodeURI("some_url.com");
var fileName = "localpathofwindows"
fileTransfer.download(uri, fileName,
function(entry) {
console.log("file download success");
},
function(error) {
console.log("file download failure");
},
false, {
headers: {
"Authorization": auth,
"action": "getFiles"
}
});

A: First of all it is not a problem with apache cordova or visual studio. It's windows 10 network settings. All I had to do is reset network settings of my windows 10 computer.
Search "Settings".
Click on "Network and Ethernet"
Click on "Status"
Click on "Network Reset" .
Restart your computer.


text:
Q: Set distance between chapter and start of text I'm using the Wiley Template, that can be found here (http://www.latextemplates.com/template/wiley-book-style).
I'm trying to change the spacing between the chapter title and the beginning of the text. To be clear, this region shown in the figure below.

Does anyone know where I can set this parameter?

A: Here's the definition of \@makechapterhead - the macro in charge of setting the chapter heading components (I've added indentation):
\def\@makechapterhead#1{%
  \vglue10pt
  \SpaceAboveChapterNumber=36pt
  {\parindent \z@
    \interlinepenalty\@M
    \Large
    \hbox to\textwidth{\hbox{\chapternumberfont CHAPTER
      \the\c@chapter}\hfill\vrule depth12pt width0pt}
    \hrule height3pt
    \vtop to22.5pc{\vfill
      \hyphenpenalty10000
      \raggedright
      \parfillskip=0pt
      \LARGE\boldmath\bfseries\chaptertitlefont
      #1\vskip1pc
      \hrule height 1pt
      \vskip7pc}}
  \dooffprintinfo}

After setting the chapter number, the chapter title is set inside a box of height 22.5pc. The top of this box has a \vfill to push everything inside to the bottom. Then, at the bottom, there's the chapter title (set \raggedright), a small skip (\vskip1pc), a horizontal rule (\hrule height 1pt) and then a large skip (\vskip7pc). Here's a visual of the last major skips (the showframe package was added to highlight the text block boundary):

You can patch \@makechapterhead to remove this using etoolbox, or edit the template to change the lengths. Below is an etoolbox patch, which reduced the large 22.5pc vertical box to 10pc and also only leaving a 2pc gap between the horizontal rule and the start of the chapter text.
\usepackage{etoolbox}
\makeatletter
% Reduce chapter title vertical box height
\patchcmd{\@makechapterhead}% <cmd>
  {\vtop to22.5pc}% <search>
  {\vtop to10pc}% <replace>
  {}{}% <success><failure>
% Reduce space between chapter title and main text
\patchcmd{\@makechapterhead}% <cmd>
  {\vskip7pc}% <search>
  {\vskip2pc}% <replace>
  {}{}% <success><failure>
\makeatother


text:
Q: unicode not printing on when imported from text file python I am reading in a text file from python and when it prints the Unicode, it does not print the symbol.
input.txt:
hello world
\u00a9

code:
from pathlib import Path
with open('input.txt','r') as file:
    txt = Path('input.txt').read_text()
    print(txt)

output:
hello world
\u00a9

expected output:
hello world
°

A: The data printed is exactly what is in the file.  To translate Unicode escapes you will need to specify that as an encoding.  The original code was also mixing file reading methods, so here's both versions:
with open('input.txt',encoding='unicode-escape') as f:
    txt = f.read()
print(txt)

from pathlib import Path
txt = Path('input.txt').read_text(encoding='unicode-escape')
print(txt)

Output (both versions):
hello world
©

Note that \u00a9 is the copyright symbol, not degree symbol.  The degree symbol is \u00b0.


text:
Q: REST endpoints limited in v1 I have been in the process of building a simple frontend for Magento, but stopped because the API only allow access to products, categories, orders and customers, and I would at least also need Brands.
Is there a plugin or other way I can get the information I need via a REST endpoint?
If I upgrade to Magento 2, would that help?

A: You can customize a native API REST of Magento with third-party module:
https://medium.com/@denniswalters84/how-to-extend-and-customize-magento-rest-api-a842d0071682
When you upgrade to Magento 2, you should rewrite your module.


text:
Q: Difference between fixed-width and proportional typewriter fonts in listings? In the MWE below, I wonder why does the pcr (Courier) font align in both escaped and unescaped versions and for whatever column setting of {listing} - while the cmtt (Computer Modern Teletype) aligns escaped and unescaped only for fullflexible columns. The MWE is basically the same code repeated for different fonts (I would have stored it in a macro, but I'd get "Text dropped after begin of listing..." then):
\documentclass{article}

\usepackage{listings}
\usepackage{xcolor} % \pagecolor
\pagecolor{yellow!15}
\setlength{\fboxsep}{0pt}

\begin{document}

\renewcommand{\ttdefault}{pcr}

Here entering a sample paragraph with \texttt{some} words entered in
\texttt{typewriter font}, which should also be \texttt{monospaced} - or rather,
\texttt{fixed width}. It can be quite useful for showing \texttt{variables}.

\noindent\begin{minipage}[t]{.325\textwidth}
\begin{lstlisting}[basicstyle=\scriptsize\ttfamily,
caption={[short] Some instructions here; the font here is \texttt{\ttdefault}.},
escapechar=!,
showlines=true,
label=lst:ex1a,
columns=fixed,
frame=tlrb]
080484c4 <list>:
 !\fbox{\hspace{-\fboxrule}\texttt{80484c4:\fbox{ }cmd one}\linebreak}!
 80484c7: cmd two
 80484ca: cmd three, four
 80484cf: cmd five
 80484d6: cmd six, seven
 80484dd: cmd more than enough
 80484e0: cmd  not_even_joking
\end{lstlisting}
\end{minipage}
\hspace{1cm}
\noindent\begin{minipage}[t]{.325\textwidth}
\begin{lstlisting}[basicstyle=\scriptsize\ttfamily,
caption={[short] Some instructions here; the font here is \texttt{\ttdefault}.},
escapechar=!,
showlines=true,
label=lst:ex1b,
columns=fullflexible,
frame=tlrb]
080484c4 <list>:
 !\fbox{\hspace{-\fboxrule}\texttt{80484c4:\fbox{ }cmd one}\linebreak}!
 80484c7: cmd two
 80484ca: cmd three, four
 80484cf: cmd five
 80484d6: cmd six, seven
 80484dd: cmd more than enough
 80484e0: cmd  not_even_joking
\end{lstlisting}
\end{minipage}

\renewcommand{\ttdefault}{cmtt}

Here entering a sample paragraph with \texttt{some} words entered in
\texttt{typewriter font}, which should also be \texttt{monospaced} - or rather,
\texttt{fixed width}. It can be quite useful for showing \texttt{variables}.

\noindent\begin{minipage}[t]{.325\textwidth}
\begin{lstlisting}[basicstyle=\scriptsize\ttfamily,
caption={[short] Some instructions here; the font here is \texttt{\ttdefault}.},
escapechar=!,
showlines=true,
label=lst:ex2a,
columns=fixed,
frame=tlrb]
080484c4 <list>:
 !\fbox{\hspace{-\fboxrule}\texttt{80484c4:\fbox{ }cmd one}\linebreak}!
 80484c7: cmd two
 80484ca: cmd three, four
 80484cf: cmd five
 80484d6: cmd six, seven
 80484dd: cmd more than enough
 80484e0: cmd  not_even_joking
\end{lstlisting}
\end{minipage}
\hspace{1cm}
\noindent\begin{minipage}[t]{.325\textwidth}
\begin{lstlisting}[basicstyle=\scriptsize\ttfamily,
caption={[short] Some instructions here; the font here is \texttt{\ttdefault}.},
escapechar=!,
showlines=true,
label=lst:ex2b,
columns=fullflexible,
frame=tlrb]
080484c4 <list>:
 !\fbox{\hspace{-\fboxrule}\texttt{80484c4:\fbox{ }cmd one}\linebreak}!
 80484c7: cmd two
 80484ca: cmd three, four
 80484cf: cmd five
 80484d6: cmd six, seven
 80484dd: cmd more than enough
 80484e0: cmd  not_even_joking
\end{lstlisting}
\end{minipage}

\end{document}

... and the output is this:

Now this is the weird thing for me: for fixed columns, the escaped and unescaped listing text has completely different spacing between characters (compare the 80484c part in Listing 3) for the font cmtt, specifically; this doesn't happen for pcr.
So the conclusion I'm making from this, is that apparently pcr is a "real" fixed width font, and cmtt is "simply" a "typewriter" font, but a proportional one? But for one, cmtt doesn't look all that proportional to me - and even if it was, it should align for columns=fixed, shouldn't it?
So my questions are:

*

*is there a (simple) way to determine in Latex if a font is really fixed-width? (e.g. I'd like to type something like \iffontfixedwidth{cmtt}\typeout{yes}\else\typeout{no}\fi)

*Could I somehow get cmtt to behave the same as pcr does in {listing} (that is, have the same alignment/spacing between letters, regardless of escaped/unescaped or columns= setting)?

A: With columns=fixed and columns=flexible, the listing is built inserting each character in a box 0.6em wide for fixed and 0.45em for flexible (the default value can be changed via basewidth).
Using these two types is meaningless when the font has fixed width glyphs, like Courier or Computer Modern Typewriter, because for these fonts the interword space is the same as the width of every character, so the columns will line up automatically.
In those cases, columns=fullflexible is the best: characters are not inserted in a box and the alignment is automatic.
How to set the basewidth to a sensible value for fixed? You can exploit the fact that when basewidth is computed, the basic font has already been selected, so
basewidth=\fontcharwd\font`W,

will set this width to the one of the (usually) widest character.
Example:
\documentclass{article}
\usepackage[T1]{fontenc}
\usepackage{listings}
\usepackage{xcolor} % \pagecolor
\pagecolor{yellow!15}
\setlength{\fboxsep}{0pt}

\begin{document}

Here entering a sample paragraph with \texttt{some} words entered in
\texttt{typewriter font}, which should also be \texttt{monospaced} - or rather,
\texttt{fixed width}. It can be quite useful for showing \texttt{variables}.

\noindent\begin{minipage}[t]{.4\textwidth}
\begin{lstlisting}[basicstyle=\scriptsize\ttfamily,
caption={[short] Some instructions here; the font here is \texttt{\ttdefault}.},
escapechar=!,
showlines=true,
label=lst:ex2a,
columns=fixed,
basewidth=\fontcharwd\font`M,
frame=tlrb]
080484c4 <list>:
 !\fbox{\hspace{-\fboxrule}\texttt{80484c4:\_cmd one}\linebreak}!
 80484c7: cmd two
 80484ca: cmd three, four
 80484cf: cmd five
 80484d6: cmd six, seven
 80484dd: cmd more than enough
 80484e0: cmd  not_even_joking
\end{lstlisting}
\end{minipage}
\hspace{1cm}
\noindent\begin{minipage}[t]{.4\textwidth}
\begin{lstlisting}[basicstyle=\scriptsize\ttfamily,
caption={[short] Some instructions here; the font here is \texttt{\ttdefault}.},
escapechar=!,
showlines=true,
label=lst:ex2b,
columns=fullflexible,
keepspaces,
frame=tlrb]
080484c4 <list>:
 !\fbox{\hspace{-\fboxrule}\texttt{80484c4:\_cmd one}}!
 80484c7: cmd two
 80484ca: cmd three, four
 80484cf: cmd five
 80484d6: cmd six, seven
 80484dd: cmd more than enough
 80484e0: cmd  not_even_joking
\end{lstlisting}
\end{minipage}

\end{document}

How to determine if a font is fixed width?
\ifdim\fontcharwd\font`i=\fontcharwd\font`W
   <code for fixed width font>
\else
   <code for proportional font>
\fi

Of course \font refers to the current font.

A: Ok, I managed to get somewhere, but not sure how correct it is. Basically, it's all about setting basewidth=, but to a correct value, which I've obtained by using \widthof from package calc. Now, the problem is that we must have an expandable macro for basewidth= - and also, I think when basewidth= is processed, the {lstlisting} environment still doesn't "know" what \lst@basicstyle has been set to. This means, that this length has to be calculated before the {lstlisting} starts, and the arguments that will be used as basicstyle= have to be retyped there. For that, below I use a newcommand.
So, not to paste the whole example, these are the most substantial changes at the start:
\documentclass{article}

\usepackage{calc}%\widthof
\usepackage{listings}
\usepackage{xcolor} % \pagecolor
\pagecolor{yellow!15}
\setlength{\fboxsep}{0pt}

\newlength{\tlen}
% \xdef\etlen{}
\makeatletter
\newcommand{\getMyLen}[1]{%
%   \setlength{\tlen}{\widthof{{\lst@basicstyle W}}}%
  \setlength{\tlen}{\widthof{#1}}%
%   \xdef\etlen{\the\tlen}%
%   \etlen% return
  \the\tlen% return
}
\makeatother
\begin{document}

\renewcommand{\ttdefault}{pcr}

Here entering a sample paragraph with \texttt{some} words entered in
\texttt{typewriter font}, which should also be \texttt{monospaced} - or rather,
\texttt{fixed width}. It can be quite useful for showing \texttt{variables};
\getMyLen{\scriptsize\ttfamily W}.

\noindent\begin{minipage}[t]{.325\textwidth}
\begin{lstlisting}[basicstyle=\scriptsize\ttfamily,
caption={[short] Some instructions here; the font here is \texttt{\ttdefault}.},
escapechar=!,
showlines=true,
label=lst:ex1a,
columns=fixed,
basewidth=\tlen,
frame=tlrb]
080484c4 <list>:
 !\fbox{\hspace{-\fboxrule}\texttt{80484c4:\fbox{ }cmd one}\linebreak}!
 80484c7: cmd two
 80484ca: cmd three, four
 80484cf: cmd five
 80484d6: cmd six, seven
 80484dd: cmd more than enough
 80484e0: cmd  not_even_joking
\end{lstlisting}
\end{minipage}
\hspace{1cm}
...
\renewcommand{\ttdefault}{cmtt}

Here entering a sample paragraph with \texttt{some} words entered in
\texttt{typewriter font}, which should also be \texttt{monospaced} - or rather,
\texttt{fixed width}. It can be quite useful for showing \texttt{variables};
\getMyLen{\scriptsize\ttfamily W}.
...

... and otherwise add basewidth=\tlen, for all {lstlisting}; the end result is this:

... and, so to speak, looks good enough to me in either font. Of course, the question on determining if a font is really fixed-width is still open...


text:
Q: How can I make a MethodCallExpression for a method? If I have a method name, and the parameters for the method, how can I create a MethodCallExpression for the method?
Here is an example method:
public void HandleEventWithArg(int arg)
{

}

Here is the code that I have:
var methodInfo = obj.GetType().GetMethod("HandleEventWithArg");
var body = Expression.Call(Expression.Constant(methodInfo), methodInfo.GetType().GetMethod("Invoke"), argExpression);

Here is the exception:

An unhandled exception of type
  'System.Reflection.AmbiguousMatchException' occurred in mscorlib.dll
Additional information: Ambiguous match found.

A: I'm not sure if this is ok with you, but your construction of the call expression looks wrong to me (you are trying to create a expression that calls your method info's Invoke method, instead of the actual method on your type.
To create a expression that calls your method on your instance, do this:
var methodInfo = obj.GetType().GetMethod("HandleEventWithArg");

// Pass the instance of the object you want to call the method
// on as the first argument (as an expression).
// Then the methodinfo of the method you want to call.
// And then the arguments.
var body = Expression.Call(Expression.Constant(obj), methodInfo, argExpression);

I've made a fiddle
PS: I'm guessing argExpression is an expression with the int that your method expects


text:
Q: Batch file to search for string in most recent file I have alot of log files which need searching for certain strings and was wondering if I could make a batch file to automate this job for me? All I need it to do is locate the most recent log in a certain directory then search for the string in that file.
I have found the below code on this website which works great to open the most recent log file but unfortunatly I dont know enough about batch programming to amend the code to search for the string and display the line.
for /f "usebackq delims=" %%i in (`dir /b /o-d`) do @call "%%i"&goto :eof

Any help would be much appreciated.

A: Add a findstr to the end:
or /f "usebackq delims=" %%i in (`dir /b /o-d`) do findstr searchforthisstring %%i

What this is doing is searching for "searchforthisstring" the files found by
dir /b/o-d

Which list files (/b = simply name not any other info and /o-d reverse date order

A: At first, set which is the file you want. If /od doesn't work, try /o-d...
for /f %%i in ('dir \path\to\files\ /b /od') do set myfile=%%i
... and pay attention because myfile will come without pathway.
Then use for /f "tokens=*" to read each line of the file fully, and findstr to search for your STRING...
for /f "tokens=*" %%i in (\path\to\files\%myfile%) do (echo %%i | findstr STRING >> OUTPUTFILE)
If you want OUTPUTFILE to be overwritten everytime you run the code, use a single >.
If you don´t want a file, but see the output on screen,  just delete the >> OUTPUTFILE code.


text:
Q: Microsoft Teams Side-Loaded App - Multiple "conversationUpdate" Events Firing This might just be me misunderstanding something, but I'm working on some welcome message logic, and it's firing twice. I'm already doing a foreach to check who is being added to the conversation, because I know I'll be notified, even in this 1-1, of both user + bot joining, something like this:
    foreach (var member in membersAdded)
    {
        if (member.Id == turnContext.Activity.Recipient.Id)
        {
           await SendWelcomeMessage(turnContext);
           break;
        }
   }

The problem, however, is that I'm getting two completely duplicated "conversationUpdate" events being fired. This is a 1-1 chat, and I'm getting the following (redacted) both times:
    "membersAdded": [
        {
            "id": "29:...",
            "aadObjectId": "[guid]"
        },
        {
            "id": "28:..."
        }
    ],
    "type": "conversationUpdate",
    "timestamp": "...",
    "id": "f:guid",
...

the only thing that changes is the message id, but aside from that, I get both entries in membersAdded both times. I know I should get notified of both members being added to this 1-1, but surely I should get either two entries in membersAdded or two "conversationUpdate" events? Right now I'm getting, basically, 2x2.
Is the only solution to track conversation state, to determine if I've "Welcomed" this user before in this same 1-1 conversation? Even if I do try that, I'm worried I'll end up with two state entries (e.g. two duplicates in the database) because of thread timing issues (one could still be creating the database entry for the conversation, and there's no way to differentiate the conversationUpdates right now).
What am I missing?
Perhaps it's relevant that this is a side-loaded custom app? Also, this only happens the very first time I install the app - if I uninstall and re-install, I just get 1 notification.


text:
Q: Unable to find any valid shell. Required for execution in an external terminal so I'm currently running my C program in NetBeans IDE 8.1, but as soon as I tried using the scanf function, I began running into issues. I have MinGW download and have added C:\MinGW\bin; to my path environment variable. I looked up and found that I should be running external terminal to use scanf but I am receiving this error. Does anyone have any idea how to fix this. I'm pretty new to C and this IDE so simpler instructions would be appreciated.
Here is the code:
#include <stdio.h>

int main()
{
    int int1, sum, int2;
      printf("Enter\n");
      scanf("%d", int1);
      printf("Enter\n");
      scanf("%d", int2);
      sum = int1 + int2;
      printf("sum is %d", sum);

      return 0;

}

A: You need to pass an int *, not an int into scanf. This is because scanf must fill in each argument in the variable argument list. Your code should be
int main()
{
    int a, b;
    printf("Enter first number\n");
    scanf("%d", &a);

    printf("Enter second number\n");
    scanf("%d", &b);

    printf("sum is %d\n", a + b);

    return 0;
}


text:
Q: Convert command line args into simulated keyboard / text output for Windows, using C++ I'm working on a little automation module for key presses and mouse-clicks, and while I've found the documentation for SendInput() and the Virtual Key Codes quite helpful for the standard keyboard and mouse input, I'm not sure how I can accomplish this task with the less ASCII-friendly potential input, like say, ®, or ê, which would be really helpful when trying to send localized strings to text fields.
I was thinking that using simulated key-presses was the way to go, but now I'm wondering if I should resort to some other sneaky devilry, like putting the string into the clipboard and doing a CTRL + V operation, or something like that and only sending virtual key-presses when appropriate.
My thought was doing something like this for all the specifically keyboard keys:
std::map<std::string,int> keys {
    {"0", 0x30},
    //...
    {"F24", 0x87}
};

Then iterating through each command line argument character-by-character to see if the whole arg only uses keys in the keys map in reference to the virtual key codes. If it does, just simulate the sequence of virtual keyboard key-codes with SendInput(). If it doesn't, I'm assuming it's not a valid direct key-press, and would do something like,
std::string to_send = argv[1];
pasteClipboard(to_send);

Is there a more straight-forward way to accomplish my goal? If not, any suggestions on how to implement a pasteClipboard style of method? I'm not using anything like Forms or MFC and would prefer to stick to the WINAPIs.


text:
Q: I dont know how to add column "RICHNESS" in the dataframe, also with its data menhinick <- function(x) {
     sum(x>0)/sqrt(sum(x))
}
ddply(df,~Newcode,function(x) {
     data.frame(RICHNESS=menhinick(x[-1]))
})

   Newcode  RICHNESS
1     BL01 1.4508215
2     BL02 1.4050583
3     BL03 1.5321132
4     BL04 1.4142136
5     BL05 0.6479552
6     BL06 1.2880334
7     BL07 0.2820650
8     BL08 1.0684120
9     BL09 0.3252526
10    BL10 0.7363117
11    BL11 1.8349137
12    BL12 1.2174252
13    BL13 1.0563106
14    BL14 1.6669913
15    BL15 1.6175783
16    BL16 1.3056432
17    BL17 1.6294405
18    BL18 0.9885727

The vector Newcode is already here. But I couldn't find RICHNESS.
Please teach me how to fix it.
Thank you so much in advance!


text:
Q: a trouble about UITableFooterView After add a footerview to the tableview, if the table has one cell only , the footer displays a little high just at the bottom of the cell. How to make it display at the foot of the tableview no matter how many cells the table has?

A: footerView is just the background, add a view that you really want, just like this:
func tableView(_ tableView: UITableView, heightForFooterInSection section: Int) -> CGFloat {
    return 100
}

func tableView(_ tableView: UITableView, viewForFooterInSection section: Int) -> UIView? {

    let footerView = UIView.init()
    footerView.backgroundColor = .red

    // footerView is just the background, add a view that you really want
    let subView = UIView.init(frame: CGRect.init(x: 20, y: 20, width: UIScreen.main.bounds.width - 40, height: 100 - 40))
    subView.backgroundColor = .yellow
    footerView.addSubview(subView)

    return footerView
}

A: Here is my code to set view on tableFooterView and its working fine.
@property (weak, nonatomic) IBOutlet UITableView *tblView;
@property (weak, nonatomic) IBOutlet UIView *viewTableFooterView;

- (void)viewDidLoad {
    [super viewDidLoad];
    _tblView.tableFooterView = _viewTableFooterView;
    _tblView.backgroundColor = [UIColor greenColor];
    [_tblView reloadData];
}

- (NSInteger)tableView:(UITableView *)tableView numberOfRowsInSection:(NSInteger)section
{
    return 10;
}

- (UITableViewCell *)tableView:(UITableView *)tableView cellForRowAtIndexPath:(NSIndexPath *)indexPath
{
    static NSString *simpleTableIdentifier = @"SimpleTableItem";

    UITableViewCell *cell = [tableView dequeueReusableCellWithIdentifier:simpleTableIdentifier];

    if (cell == nil) {
        cell = [[UITableViewCell alloc] initWithStyle:UITableViewCellStyleDefault reuseIdentifier:simpleTableIdentifier];
    }

    cell.textLabel.text = [NSString stringWithFormat:@"%ld",(long)indexPath.row];
    return cell;
}

Check code and let me know if its not working for you.

A: This occurs because the footer view that you are adding is the footer of the content you are displaying inside the UITableView. That being said there is a way to get the output you want. What you can do is drag a UIView below the UITableViewCell added in the storyboard for it to appear as a footer.
Setup constraints for the UILabel or anything you want to show inside with respect to this view, what I mean is don't add fixed height constraints otherwise you will get annoying layout breaking warnings.
Make a duplicate of this footer view and add it to the bottom your UITableView and add a fixed height for it to make it as a copy of the footer view you added inside the UITableView. Sort of like this:

Now, create an outlet for this height constraint of the footer view into your UIViewController.
Now in your viewDidLoad what you can do is check if the height of the UITableView after adding the cells is less than screen bounds and proceed accordingly, like this:
- (void)viewDidLoad {

    [super viewDidLoad];

    //dont show footer view if cells are within screen bounds
    if (numberOfCells * cellHeight < [UIScreen mainScreen].bounds.size.height){

        UIView *footerView = mainTableView.tableFooterView;

        CGRect tempFrame = footerView.frame;

        tempFrame.size.height = 0.0f;

        footerView.frame = tempFrame;

        mainTableView.tableFooterView = footerView;

    }else{

        //dont show footerview below table view if cells are outside screen bounds
        [footerHeightConstraint setConstant:0.0f];
    }

}

Note: I have missed an edge case related to height like the product of rows * height coming to be equal or just less than screen bounds, so you'll have to have a look at that.


text:
Q: running multiple collections using a script into gitlab-ci failed I'm facing an issue with newman. Actually, i'm trying to do a script to run all collections in one time.
But at some point, the script failed and the last collections are not running.
Can someone suggest me a solution ?
the script that i'm using :
for collection in postman/*.json; do newman run ${collection} --reporters cli,html --reporter-html-export `basename ${collection} | awk '{gsub(".json",".html", $1);print $1}'` --insecure;done


text:
Q: Gracefully restart a Reactive-Kafka Consumer Stream on failure Problem
When I restart/complete/STOP stream the old Consumer does not Die/Shutdown:
[INFO ] a.a.RepointableActorRef -
  Message [akka.kafka.KafkaConsumerActor$Internal$Stop$]
  from Actor[akka://ufo-sightings/deadLetters]
  to Actor[akka://ufo-sightings/system/kafka-consumer-1#1896610594]
  was not delivered. [1] dead letters encountered.

Description
I'm building a service that receives a message from Kafka topic and sends the message to an external service via HTTP request.

*

*A connection with the external service can be broken, and my service needs to retry the request.

*Additionally, if there is an error in the Stream, entire stream needs to restart.

*Finally, sometimes I don't need the stream and its corresponding Kafka-consumer and I would like to shut down the entire stream
So I have a Stream:
Consumer.committableSource(customizedSettings, subscriptions)
  .flatMapConcat(sourceFunction)
  .toMat(Sink.ignore)
  .run

Http request is sent in sourceFunction
I followed new Kafka Consumer Restart instructions in the new documentation
  RestartSource.withBackoff(
      minBackoff = 20.seconds,
      maxBackoff = 5.minutes,
      randomFactor = 0.2 ) { () =>
          Consumer.committableSource(customizedSettings, subscriptions)
            .watchTermination() {
                case (consumerControl, streamComplete) =>
                  logger.info(s" Started Watching Kafka consumer id = ${consumer.id} termination: is shutdown: ${consumerControl.isShutdown}, is f completed: ${streamComplete.isCompleted}")
                  consumerControl.isShutdown.map(_ => logger.info(s"Shutdown of consumer finally happened id = ${consumer.id} at ${DateTime.now}"))
                  streamComplete
                    .flatMap { _ =>
                      consumerControl.shutdown().map(_ -> logger.info(s"3.consumer id = ${consumer.id} SHUTDOWN at ${DateTime.now} GRACEFULLY:CLOSED FROM UPSTREAM"))
                    }
                    .recoverWith {
                      case _ =>
                        consumerControl.shutdown().map(_ -> logger.info(s"3.consumer id = ${consumer.id} SHUTDOWN at ${DateTime.now} ERROR:CLOSED FROM UPSTREAM"))
                    }
             }
            .flatMapConcat(sourceFunction)
      }
      .viaMat(KillSwitches.single)(Keep.right)
      .toMat(Sink.ignore)(Keep.left)
      .run

There is an issue opened that discusses this non-terminating Consumer in a complex Akka-stream, but there is no solution yet.
Is there a workaround that forces the Kafka Consumer termination

A: How about wrapping the consumer in an Actor and registering a KillSwitch, see: https://doc.akka.io/docs/akka/2.5/stream/stream-dynamic.html#dynamic-stream-handling
Then in the Actor postStop method you can terminate the stream.
By wrapping the Actor in a BackoffSupervisor, you get the exponential backoff.
Example actor: https://github.com/tradecloud/kafka-akka-extension/blob/master/src/main/scala/nl/tradecloud/kafka/KafkaSubscriberActor.scala#L27


text:
Q: Too much download bandwidth on nginx process I rent dedicated server from company and I noticed it is using too much download bandwidth constantly on nginx process even with low traffic on non peak hours. I checked with tcpdump and I saw those
05:59:41.415892 IP x.x.x.x.65524 > 224.1.1.14.search-agent: UDP, length 1472
05:59:41.415901 IP x.x.x.x.49842 > 224.24.1.7.search-agent: UDP, length 940
05:59:41.415938 IP x.x.x.x.53999 > 224.24.1.4.search-agent: UDP, length 1472
05:59:41.416131 IP x.x.x.x.65524 > 224.1.1.14.search-agent: UDP, length 1472
05:59:41.416257 IP x.x.x.x.53999 > 224.24.1.4.search-agent: UDP, length 1472
05:59:41.416481 IP x.x.x.x.65524 > 224.1.1.14.search-agent: UDP, length 1472
05:59:41.416498 IP x.x.x.x.53999 > 224.24.1.4.search-agent: UDP, length 1472
05:59:41.416536 IP x.x.x.x.65524 > 224.1.1.14.search-agent: UDP, length 1472
05:59:41.416651 IP x.x.x.x.53999 > 224.24.1.4.search-agent: UDP, length 1472
05:59:41.416751 IP x.x.x.x.65524 > 224.1.1.14.search-agent: UDP, length 1472
05:59:41.416770 IP x.x.x.x.53999 > 224.24.1.4.search-agent: UDP, length 1472
05:59:41.416940 IP x.x.x.x.53999 > 224.24.1.4.search-agent: UDP, length 1472
05:59:41.416957 IP x.x.x.x.65524 > 224.1.1.14.search-agent: UDP, length 1472
05:59:41.417134 IP x.x.x.x.53999 > 224.24.1.4.search-agent: UDP, length 1472
05:59:41.417183 IP x.x.x.x.65524 > 224.1.1.14.search-agent: UDP, length 1472
05:59:41.417247 IP x.x.x.x.53999 > 224.24.1.4.search-agent: UDP, length 1472
05:59:41.417349 IP x.x.x.x.65524 > 224.1.1.14.search-agent: UDP, length 1472
05:59:41.417364 IP x.x.x.x.53999 > 224.24.1.4.search-agent: UDP, length 1472
05:59:41.417493 IP x.x.x.x.53999 > 224.24.1.4.search-agent: UDP, length 1472
05:59:41.417511 IP z.z.z.z.54220 > 233.1.1.17.search-agent: UDP, length 1472
05:59:41.417553 IP z.z.z.z.63019 > 233.1.1.15.search-agent: UDP, length 1472
05:59:41.417580 IP x.x.x.x.65524 > 224.1.1.14.search-agent: UDP, length 416
05:59:41.417602 IP z.z.z.z.54220 > 233.1.1.17.search-agent: UDP, length 1472
05:59:41.417624 IP z.z.z.z.54216 > 233.1.1.18.search-agent: UDP, length 1128
05:59:41.417632 IP x.x.x.x.53999 > 224.24.1.4.search-agent: UDP, length 1472
05:59:41.417701 IP z.z.z.z.63516 > 233.1.1.20.search-agent: UDP, length 1472
05:59:41.417745 IP z.z.z.z.54220 > 233.1.1.17.search-agent: UDP, length 1472
05:59:41.417764 IP x.x.x.x.53999 > 224.24.1.4.search-agent: UDP, length 1472
05:59:41.417779 IP z.z.z.z.63516 > 233.1.1.20.search-agent: UDP, length 408
05:59:41.417806 IP z.z.z.z.54220 > 233.1.1.17.search-agent: UDP, length 472
05:59:41.417829 IP z.z.z.z.54218 > 233.1.1.14.search-agent: UDP, length 1472
05:59:41.417876 IP z.z.z.z.63019 > 233.1.1.15.search-agent: UDP, length 1472
05:59:41.417889 IP x.x.x.x.53999 > 224.24.1.4.search-agent: UDP, length 1472
05:59:41.417924 IP z.z.z.z.63516 > 233.1.1.20.search-agent: UDP, length 1472
05:59:41.417940 IP z.z.z.z.63019 > 233.1.1.15.search-agent: UDP, length 1472
05:59:41.417980 IP z.z.z.z.54218 > 233.1.1.14.search-agent: UDP, length 596
05:59:41.417985 IP z.z.z.z.63516 > 233.1.1.20.search-agent: UDP, length 1160
05:59:41.418008 IP z.z.z.z.63019 > 233.1.1.15.search-agent: UDP, length 1472
05:59:41.418099 IP z.z.z.z.63019 > 233.1.1.15.search-agent: UDP, length 692
05:59:41.418100 IP x.x.x.x.53999 > 224.24.1.4.search-agent: UDP, length 1472
05:59:41.418152 IP z.z.z.z.54218 > 233.1.1.14.search-agent: UDP, length 1472

Above x.x.x.x, z.z.z.z IP is also not my server IPV4 but it is other ip from the service provider subnet.
EDIT:
And this is my ifconfig
eth0: flags=4163<UP,BROADCAST,RUNNING,MULTICAST>  mtu 1500
        inet f.f.f.f  netmask 255.255.255.0  broadcast f.f.f.255
        ether 2c:44:fd:7f:fe:e0  txqueuelen 1000  (Ethernet)
        RX packets 6513838035  bytes 8249745134653 (7.5 TiB)
        RX errors 0  dropped 965  overruns 0  frame 0
        TX packets 860626046  bytes 934970894599 (870.7 GiB)
        TX errors 0  dropped 0 overruns 0  carrier 0  collisions 0
        device interrupt 38

eth1: flags=4099<UP,BROADCAST,MULTICAST>  mtu 1500
        ether 2c:44:fd:7f:fe:e1  txqueuelen 1000  (Ethernet)
        RX packets 0  bytes 0 (0.0 B)
        RX errors 0  dropped 0  overruns 0  frame 0
        TX packets 0  bytes 0 (0.0 B)
        TX errors 0  dropped 0 overruns 0  carrier 0  collisions 0
        device interrupt 39

eth2: flags=4099<UP,BROADCAST,MULTICAST>  mtu 1500
        ether 2c:44:fd:7f:fe:e2  txqueuelen 1000  (Ethernet)
        RX packets 0  bytes 0 (0.0 B)
        RX errors 0  dropped 0  overruns 0  frame 0
        TX packets 0  bytes 0 (0.0 B)
        TX errors 0  dropped 0 overruns 0  carrier 0  collisions 0
        device interrupt 38

eth3: flags=4099<UP,BROADCAST,MULTICAST>  mtu 1500
        ether 2c:44:fd:7f:fe:e3  txqueuelen 1000  (Ethernet)
        RX packets 0  bytes 0 (0.0 B)
        RX errors 0  dropped 0  overruns 0  frame 0
        TX packets 0  bytes 0 (0.0 B)
        TX errors 0  dropped 0 overruns 0  carrier 0  collisions 0
        device interrupt 39

lo: flags=73<UP,LOOPBACK,RUNNING>  mtu 65536
        inet 127.0.0.1  netmask 255.0.0.0
        loop  txqueuelen 1000  (Local Loopback)
        RX packets 35765450  bytes 98858211782 (92.0 GiB)
        RX errors 0  dropped 0  overruns 0  frame 0
        TX packets 35765450  bytes 98858211782 (92.0 GiB)
        TX errors 0  dropped 0 overruns 0  carrier 0  collisions 0

Is this a misconfiguration by the server provider or can I fix this by myself?

A: This is multicast traffic, that is sent by some entity in your provider's network.
This can happen when the same L2 network is shared with several servers. You cannot really prevent that.
However, if none of your services are subscribed to the multicast group, the Linux kernel automatically drops the traffic. Therefore it shouldn't have any effect on the network performance.


text:
Q: how to set win32 api c++ button background color and text color? im using simple button in win32 application and i like to change its color and text
but i can't find from all searching in google how to do it.
i have this code that represent a button:
this is in the rc file :
LANGUAGE LANG_NEUTRAL, SUBLANG_NEUTRAL
IDD_DIALOG1 DIALOG 0, 0, 273, 209
STYLE DS_3DLOOK | DS_CENTER | DS_MODALFRAME | DS_SHELLFONT | WS_CAPTION | WS_VISIBLE | WS_POPUP | WS_SYSMENU
CAPTION "Win32  demo"
FONT 8, "Ms Shell Dlg"
{
    DEFPUSHBUTTON   "My Button1 ", IDOK, 59, 176, 69, 14
    PUSHBUTTON      "Log Off", IDC_BUTTON1, 155, 175, 54, 14
 }

and in the main cpp file i only triger simple Massegebox alerts
case WM_COMMAND:
            switch(LOWORD(wParam))
            {
                case IDOK:

                    MessageBox(NULL, L"IDOK button pressed!", L"Pinky says...", MB_OK | MB_ICONEXCLAMATION);
                    break;
                case IDC_BUTTON1:
                    MessageBox(NULL, L"IDC_BUTTON1 button pressed!",L"Pinky says...", MB_OK | MB_ICONEXCLAMATION);
                    break;
                break;
            }
        break;

where and how i change the buttons background colors and text?

A: There are several approaches you could take for this:

*

*Use bitmaps as your buttons

*Ownerdraw the buttons

*Handle NM_CUSTOMDRAW

The easiest way is just to handle WM_CTLCOLORBTN.

A: You can't, or at least you can't do so simply. If you want a coloured button then you need to set the owner-draw style and draw it yourself. Plain old buttons don't have customisable colours.

A: You can do it as described by the Forger. He has a very good tutorial for other bits of Windows Programmering as well.
Check it out here


text:
Q: Form submission with Ant Design' Select I'm currently trying to submit a form from the Ant Design's select. I've managed to keep the dropdown open and I have an input inside a form but when I hit enter the form doesn't submit and that happened after I used the dropdownRender.
**The dropdown looks like this **

What I've done
const createorSelect = ()
 =>{

const handleFormSubmit = (values: { newAccount: string }): void => {
    const { newAccount } = values;
    children.push({ id: children.length + 1, value: newAccount });
    console.log('form submitted...');
  };

  const newAccBtn = (

      {showInput ? (
        <Form onFinish={handleFormSubmit}>
          <Form.Item name="newAccount">
            <Input className="new-acc-input" placeholder="Create account..." name="newAccount" />
          </Form.Item>
        </Form>
      ) : (

          Add acount

      )}

  );

  return (
    <Select
      className="selector"
      allowClear={false}
      showSearch
      placeholder="Select..."
      defaultValue={defaultValue}
      dropdownRender={(menu) => (
        <>
          {showAddAccount && newAccBtn}
          {menu}
        </>
      )}
    >
      {options}
    </Select>
  );
};
}

I want to add the new item to the options list as seen in the dropdown. But the form isn't submitted, hence the new item not being added to the list. What am I doing wrong? Thanks.


text:
Q: Using Ajax with JQuery .on() I am trying to combine these two functions but my knowledge of Ajax and JS isn't that strong yet and I don't know how i would go about doing it.
$(document).on('click', '.list_item', function() {
    var indx = $(this).index();
});

$.ajax({
    type: 'POST',
    url: 'NavBar.php',
    data: {'indx': pat_id},
});

basically I want to send the JS variable indx to the php variable pat_id.
When the user clicks on the li it would be received as something like this.
<li class= "list_item" onclick ="<?php $pat_id = $_POST ['indx']; ?>">

this would all be happening inside the same php file: NavBar.php.

A: Try this:
    $(document).on('click', '.list_item', function() {
        var indx = $(this).index();
        $.ajax({ // add ajax code here
        type: 'POST',
        url: 'NavBar.php',
        data: {pat_id: indx}, // send parameter like this
        success: function(response) {
               console.log(response);
        }
        });
    });

So in NavBar.php you can access pat_id like this:
echo $_POST['pat_id'];


text:
Q: Query list of servers for memory/cpu allocated Running RHEL 6.2, trying to write a bash script to SSH to a list of remote servers, and write the CPUs and Total Memory to a file, one line per host in the following format:
HOSTNAME1    CPUS: 12    MEMORY: 64
HOSTNAME2    CPUS: 08    MEMORY: 12

Here is what I have so far, it doesn't work fully, what I'm running in to is the part where the system SSHs to run cat /proc/cpuinfo and free.
The bash script would be called like so: ./query_host_info.sh <DEST> <USER> <FILE>
The file it reads the lists of hosts from is a one-per-line file of hostnames.
#!/bin/bash

# username to connect via ssh
USER=$2
# destination path/filename to save results to
DEST=$3
# source list of hostnames to read from
FILE=$1

# Iterate through line items in FILE and
# execute ssh, if we connected successfully
# run proc/info and free to find memory/cpu alloc
# write it to DEST path/file
# if we don't connect successfully, write the hostname
# and "unable to connect to host" error to DEST path/file
for i in `cat $FILE`; do
  echo -n ".";
  CHK=`ssh -q -o "BatchMode yes" -o "ConnectTimeout 5" \
            -l $USER $i "echo success"`;
  if [ "success" = $CHK ] >/dev/null 2>&1
  then
    `ssh -q -o "BatchMode yes" -o "ConnectTimeout 5" -l $USER $i "\
        printf "$i    ";
        echo "`cat /proc/cpuinfo | grep processor | awk '{a++} END {print a}';
        free -g | sed -n -e '/^Mem:/s/^[^0-9]*\([0-9]*\) .*/\1/p'`";" >> ${DEST}`;
  else
    printf "${i}\tUnable to connect to host\n" >> ${DEST};
  fi
done
# All line items have been gone through,
# show done, and exit out
echo ""
echo "Done!"
echo "Check the list 'checkssh_failure' for errors."
exit 0

A: Just modified your script :
#!/bin/bash
# username to connect via ssh
USER=$2
# destination path/filename to save results to
DEST=$3
# source list of hostnames to read from
FILE=$1

[[ $# -ne 3 ]] && { echo -e "\nUsage: $0  <User> <ServerList> <LogFile>\n"; exit 1; };

func_ssh() {
    local Ipaddr=$1
    local Cmd="${@:2}"
    local LogIt=${DEST}
    ssh -q -o "BatchMode yes" -o "ConnectTimeout 5" -l $USER $Ipaddr "${Cmd}"
    [[ $? -ne 0 ]] && printf "${Ipaddr}\tUnable to connect to host\n" >> ${LogIt}
}

GetTotalProcs="awk '/processor/{a++} END{print a}'  /proc/cpuinfo"
GetMemoryDetails="free -g | sed -n -e '/^Mem:/s/^[^0-9]*\([0-9]*\) .*/\1/p'"

# Iterate through line items in FILE and
# execute ssh, if we connected successfully
# run proc/info and free to find memory/cpu alloc
# write it to DEST path/file
# if we dont connect successfully, write the hostname
# and "unable to connect to host" error to DEST path/file
for srv in $(< $FILE );
do
    echo -n "."
    A="$( func_ssh $srv $GetTotalProcs )"
    B="$( func_ssh $srv $GetMemoryDetails )"
    echo "${srv} CPU: ${A} MEMORY: ${B}" >> ${DEST}
done

# All line items have been gone through,
# show done, and exit out
echo ""
echo "Done!"
echo "Check the list 'checkssh_failure' for errors."
exit 0

A: Can't you just run the script like so?:
% ./query_host_info.sh <DEST> <USER> <FILE> > output.log

-or-
% ./query_host_info.sh <DEST> <USER> <FILE> | tee output.log

Additionally you can use a command list, wrap a bunch of commands in parens, and redirect their output to a file.
% (ls; ls; ls;) > some_output.log

A: I figured it out.. two things.. SSH didnt like the concatenated proc/cpuinfo and free, and i reorganized how the commands are ran.. Probably a way better way of doing this but this seems to work..
#!/bin/bash

# username to connect via ssh
USER=$2
# destination path/filename to save results to
DEST=$3
# source list of hostnames to read from
FILE=$1

# Iterate through line items in FILE and
# execute ssh, if we connected successfully
# run proc/info and free to find memory/cpu alloc
# write it to DEST path/file
# if we dont connect successfully, write the hostname
# and "unable to connect to host" error to DEST path/file
for i in `cat $FILE`; do
  echo -n ".";
  CHK=`ssh -q -o "BatchMode yes" -o "ConnectTimeout 5" \
            -l $USER $i "echo success"`;
  if [ "success" = $CHK ] >/dev/null 2>&1
  then
    A=`ssh -q -o "BatchMode yes" -o "ConnectTimeout 5" -l $USER $i "cat /proc/cpuinfo | grep processor | awk '{a++} END {print a}'"`
    B=`ssh -q -o "BatchMode yes" -o "ConnectTimeout 5" -l $USER $i "free -g | sed -n -e '/^Mem:/s/^[^0-9]*\([0-9]*\) .*/\1/p'"`
    echo "${i} CPU: ${A} MEMORY: ${B}" >> ${DEST}
  else
    printf "${i}\tUnable to connect to host\n" >> ${DEST};
  fi
done
# All line items have been gone through,
# show done, and exit out
echo ""
echo "Done!"
echo "Check the list 'checkssh_failure' for errors."
exit 0