text:
Q: Streaming with fetch API I have created .NET Core API and in it I expose a POST endpoint that streams the response over multiple chunks where each chunk contains a JSON object, and I have created Angular client app that queries that endpoint through the fetch API:
const response = await fetch(environment.apiUrl + `/Vehicle/ParseVehiclesData`,
{
  method: 'post',
  body: file,
});

const reader = response.body.getReader();
while (true) {
  const { value, done } = await reader.read();
  if (done) break;
  let res = JSON.parse(new TextDecoder("utf-8").decode(value));
  console.log(res);
}

My goal here is to feed a progress bar with pieces of information about the progress which they already returned from the server in each chunk, now the problem I have is that a behavior occurs when users with weak connection speed tries it, their speed of consumption of the each chunk is less than speed of the server feed, which causes the browser to merge chunks together when there is a backpressure so my attempt to parse the decoded string fails because i will be trying to parse something like
{"name":"abc","progress":50}{"name":"ab1","progress":100"}

multiple json object will be attached together with no delimiters not even break lines,
so what I'm looking for is solution that make prevents the merge of the chunks when there is a backpressure or in the worst case a way to parse JSON objects with no delimiters and feed them to a custom stream or an observable, any help about the subject would be appreciated.
these are some articles i have stumpled upon while searching,
InternetSpeed

A: You could define a pre-parser to split the msgs by }{ separator (and handle first/last entries):

let preParser = (a)=>a.split('}{').map((item,index) => {
       if(a.split('}{').length>1){
          if (index== 0){return item+'}'} // first msg
          else if (index<a.split('}{').length-1){return '{'+item+'}'} // middle msgs
          else {return '{'+item}} // last msg
       else {return a} // no need to do anything if single msg
})

a='{"name":"abc","progress":50}'

b='{"name":"abc","progress":50}{"name":"ab1","progress":100}{"name":"ab2","progress":150}'

console.log('example 1')
preParser(a).forEach(v => console.log(JSON.parse(v)))

console.log('example 2')
preParser(b).forEach(v => console.log(JSON.parse(v)))


text:
Q: `DateTime.Parse` parses the timestamp in which timezone? I am parsing string time in date using DateTime.Parse method. It parses properly and returns me today's date with the entered time. But I am not able to determine the timezone when it takes the date part. Is it considering local date or UTC date?
public class Program
{
    public static void Main(string[] args)
    {
        //Your code goes here
        Console.WriteLine(DateTime.Parse("4:00"));
        //prints 09.05.2019 04:00:00 - here did it take 09.05.2019 from local timezone or is it UTC?
    }
}

On referring official documentation of DateTime.Parse, it is mentioned vaguely as follows:

A string with a time but no date component. The method assumes the current date unless you call the Parse(String, IFormatProvider, DateTimeStyles) overload and include DateTimeStyles.NoCurrentDateDefault in the styles argument, in which case the method assumes a date of January 1, 0001.

I am confused what culture's exactly the date is being picked?

A: Neither, it is Unspecified.
First of all, in .NET Framework, DateTime structure does not keep timezone information. It has Kind property which reflects some information as Utc, Local or Unspecified but they are not perfectly refers a timezone.
In your case, since you don't supply any other parameters, your result DateTime will be Unspecified.
It is stated on the documentation as;

If s contains time zone information, this method returns a DateTime
  value whose Kind property is DateTimeKind.Local and converts the date
  and time in s to local time. Otherwise, it performs no time zone
  conversion and returns a DateTime value whose Kind property is
  DateTimeKind.Unspecified.

For representation part, when you use DateTime in Console.WriteLine method, it calls WriteLine(object) overload and this calls the current FormatProvider which is came from Thread.CurrentThread.CurrentCulture.

A: By Default, it picks the system's currently active culture (on which the C# Code is being executed) local date and its format and then appends your time to that date. As your time has only single numeric value i.e 4 so it'll list it as 4 AM.
So output can be like 09.05.2019 04:00:00 or 5/9/2019 4:00:00 AM depending upon the server's system current format on which the code is executed. You can see the system's current culture by right-clicking on time in Windows Taskbar and see the format.

redpajama_set_name: RedPajamaStackExchange


text:
Q: Managing git repositories with another repository Linux has lots of git repositories for different modules as listed here. There are also repositories for developers. But how does Linus merge all of these repositories and make a single kernel repository like this? For instance, does he mark as submodule all of the related repositories or what?

A: git thinks the opposite way: instead of generating a "master" repository, one generates "children" repositories called submodules.
Say that you have two git repositories that are located at:
foo.bar/baz
quix.qu/foobar

Then you can initialize a parent git repository (for instance in parent):
git init .

and add submodules:
git submodule add foo.bar/baz
git submodule add quix.qu/foobar

It will create the baz and foobar directory and initialize the appropriate git repositories there. The resulting tree is thus something like:
parent
├── baz
│   ├── content of baz
│   └── other content of baz
└── foobar

Submodules are thus what are links (shortcuts) in a non-versioning file system. They are useful if a part of a project tend "to go its own way" and commits are no longer global but you want commits to only capture for instance the plugins directory.


text:
Q: "Too many arguments" error while running C program on VS Code So here's the program that I want to run:
#include <stdio.h>

int main(){
    printf("Helloworld!");
    return 0;
}

And here is the error I get:

I seriously don't know why this is happening. A month ago it was working just fine. Whenever I go to Run on VSCode and click "Start Debugging" this is what I get:

Please help.

A: The issue is in the console command line, not the c-code.  As suggested by @molbdnilo, the backslash is an escape character in bash.  In particular, the final backslash in the file path is escaping the quote character, which means the cd command is not terminated.  You can either use double-backslashes (to escape the backslash) and/or drop the last backslash in the path.  In bash you can also use forward slash to separate elements in a path to avoid this issue.

A: As mentioned by Ezward, the issue is with your bash command. Suppose you have a file named "a.cpp" at you desktop. Open the terminal in same directory, i.e. desktop and try this command:
g++ -o objectFileName sourceFileName

For example in this case use:
g++ -o a a.cpp

This command would produce an object/executable file named "a" for your a.cpp file. Now to run the file enter this command:
./objectFileName

In this case that will be:
./a

This will run your code and you would see its output.
Note: I am assuming you're using g++ based compiler in linux/ubuntu. If not, google it on how to install g++ compiler. I hope this link helps:
https://askubuntu.com/questions/481807/how-to-install-g-in-ubuntu-14-04

A: As has been mentioned, the problem is in the command line, not in your code.
However, the problem is not with g++ or with && (which is good, not bad, since it stops when there is an error), but with your backslash at the end of the directory.
Unlike cmd in Windows, bash interprets \" as a literal ", not as backslash followed by string delimiter.
This means that cd gets the two arguments
C:\Users\...\Desktop" && gcc hello.c -o hello &&

and
C:\Users\...\Desktop"hello

A: Setting the Default Profile ( Shell ) to CMD fixes the problem for me. >_<

A: There Just change your terminal to Windows PowerShell

*

*press CTRL+SHIFT+P

*Search for "Terminal: Select Default Profile" (previously "Terminal: Select Default Shell")

*Select your preferred shell. In my case I selected "Windows PowerShell"


text:
Q: Using IBM i 7.4 and the latest PTF, how te enable the New Navigator after having disabled it (needed to temporarilu use the Heritage Navigator)? Running under IBM i V7.4 and the latest ptf, I enabled the Old Navigator (using the instructions found in this document : https://www.ibm.com/support/pages/heritage-navigator-enable-and-disable-instructions), to continue using it for a while.
After disabling the Heritage Navigator to use the New One (using the instructions in the previous document, and this document : https://www.ibm.com/support/pages/node/6570961) I can't start a session with the New Navigator.
Every time I try it, I get this error message : ERR_CONNECTION_REFUSED
What am I missing ?
Thank you for your help.


text:
Q: Remove substring matching pattern both in the beginning and the end of the variable As the title says, I'm looking for a way to remove a defined pattern both at the beginning of a variable and at the end. I know I have to use # and % but I don't know the correct syntax.
In this case, I want to remove http:// at the beginning, and /score/ at the end of the variable $line which is read from file.txt.

A: You have to do it in 2 steps :
$ string="fooSTUFFfoo"
$ string="${string%foo}"
$ string="${string#foo}"
$ echo "$string"
STUFF

A: Well, you can't nest ${var%}/${var#} operations, so you'll have to use temporary variable.
Like here:
var="http://whatever/score/"
temp_var="${var#http://}"
echo "${temp_var%/score/}"

Alternatively, you can use regular expressions with (for example) sed:
some_variable="$( echo "$var" | sed -e 's#^http://##; s#/score/$##' )"

A: There IS a way to do it one step using only built-in bash functionality (no running external programs such as sed) -- with BASH_REMATCH:
url=http://whatever/score/
re='https?://(.*)/score/'
[[ $url =~ $re ]] && printf '%s\n' "${BASH_REMATCH[1]}"

This matches against the regular expression on the right-hand side of the =~ test, and puts the groups into the BASH_REMATCH array.

That said, it's more conventional to use two PE expressions and a temporary variable:
shopt -s extglob
url=http://whatever/score/
val=${url#http?(s)://}; val=${val%/score/}
printf '%s\n' "$val"

...in the above example, the extglob option is used to allow the shell to recognized "extglobs" -- bash's extensions to glob syntax (making glob-style patterns similar in power to regular expressions), among which ?(foo) means that foo is optional.

By the way, I'm using printf rather than echo in these examples because many of echo's behaviors are implementation-defined -- for instance, consider the case where the variable's contents are -e or -n.

A: $ var='https://www.google.com/keep/score'
$ var=${var#*//} #removes stuff upto // from begining
$ var=${var%/*} #removes stuff from / all the way to end
$ echo $var
www.google.com/keep

A: how about
export x='https://www.google.com/keep/score';
var=$(perl -e 'if ( $ENV{x} =~ /(https:\/\/)(.+)(\/score)/ ) { print qq($2);}')


text:
Q: In FullCalendar in react Error Uncaught TypeError: view.computeEventDraggable is not a function I am working with fullcalendar (https://fullcalendar.io) in react, my problem is when I create an event in the week view and try to go to the monthly view the console shows this error:
Uncaught TypeError: view.computeEventDraggable is not a function
    at TimeGridEventRenderer.renderSegHtml (main.esm.js: 155)
    at TimeGridEventRenderer.FgEventRenderer.renderSegEls (main.js: 9531)
    at TimeGridEventRenderer.FgEventRenderer.renderSegs (main.js: 9486)
    at TimeGrid.res [as renderFgEvents] (main.js: 3911)
    at TimeGrid.render (main.esm.js: 628)
    at TimeGrid.Component.receiveProps (main.js: 4802)
    at SimpleTimeGrid.render (main.esm.js: 1427)
    at SimpleTimeGrid.Component.receiveProps (main.js: 4802)
    at TimeGridView.render (main.esm.js: 1563)
    at TimeGridView.Component.receiveProps (main.js: 4802)
    at CalendarComponent.renderView (main.js: 7639)
    at CalendarComponent.render (main.js: 7549)
    at CalendarComponent.Component.receiveProps (main.js: 4802)
    at Calendar.renderComponent (main.js: 8298)
    at Calendar.executeRender (main.js: 8250)
    at Calendar.tryRerender (main.js: 8227)
    at Calendar.requestRerender (main.js: 8218)
    at Calendar.dispatch (main.js: 8201)
    at Calendar.changeView (main.js: 8538)
    at HTMLButtonElement.buttonClick (main.js: 7389)

my declaration of fullcalendar looks like this
<FullCalendar
    defaultView="dayGridMonth"
    header={{
        left: "prev,next today",
        center: "title",
        right: "dayGridMonth,timeGridWeek,timeGridDay,listWeek"
    }}
    rerenderDelay={10}
    eventDurationEditable={false}
    editable={true}
    droppable={true}
    plugins={[dayGridPlugin, timeGridPlugin, interactionPlugin]}
    ref={this.calendarComponentRef}
    weekends={this.state.calendarWeekends}
    events={this.state.calendarEvents}
    eventDrop={this.drop}
    drop={this.drop}
    eventReceive={this.eventReceive}
    eventClick={this.eventClick}
    dateClick={ this.handleDateClick }
/>

I would very much appreciate some help, thanks

A: My problem was solved by downloading the bookstore version:
Initial version "@ fullcalendar / interaction": "^ 4.3.0". Version that worked "@ fullcalendar / interaction": "4.2.0".


text:
Q: How can draw strokes over each other with opacity using a inkPresenter? I want to use an inkpresenter so that each new stroke is laid above the previous ones creating a darken effect.
I have tried creating a new inkpresenter each time and adding it to a canvas, but the opacity effect only appears after I release the mouse. I want it to immediatly show as you are drawing. If I set the inkpresenter diretly to the content of the target element (no blending), the strokes have opacity as you draw.

A: You haven't posted any code showing how you are currently handling InkPresenter in your application. I've made a quick test program in WPf and it seems to work correctly with opacity.
I placed InkPresenter control in xaml and added PreviewMouseDown, PreviewMouseMove and PreviewMouseUp methods' handler to the code behind. The code I used  to handle those events looks like this:
System.Windows.Ink.Stroke newStroke = null;

    private void inkPresenterSample_PreviewMouseDown(object sender, MouseButtonEventArgs e)
    {
        inkPresenterSample.CaptureMouse();

        //get mouse position and add first point to a new line to be drawn
        var mousePosition = e.GetPosition(inkPresenterSample);
        var stylusStartPoint = new StylusPointCollection();
        stylusStartPoint.Add(new StylusPoint(mousePosition.X, mousePosition.Y));

        //set line's attributes, it real application this should be probably done outside this method
        var drawingAttributes = new System.Windows.Ink.DrawingAttributes();
        //IMPORTANT: semi-transparent color is used, so the opacity effect is visible
        drawingAttributes.Color = System.Windows.Media.Color.FromArgb(110, 0, 0, 0);
        drawingAttributes.Width = 10;

        //create a new stroke to be drawn
        newStroke = new System.Windows.Ink.Stroke(stylusStartPoint, drawingAttributes);
        newStroke.StylusPoints.Add(new StylusPoint(mousePosition.X, mousePosition.Y));

        //add reference to a new stroke to the InkPresenter control
        inkPresenterSample.Strokes.Add(newStroke);
    }

    private void inkPresenterSample_PreviewMouseUp(object sender, MouseButtonEventArgs e)
    {
        inkPresenterSample.ReleaseMouseCapture();

        if (newStroke != null)
        {
            newStroke = null;
        }
    }

    private void inkPresenterSample_PreviewMouseMove(object sender, MouseEventArgs e)
    {
        //if a stroke is currently drawn in the InkPresenter
        if (newStroke != null)
        {
            //add a new point to the stroke
            var mousePosition = e.GetPosition(inkPresenterSample);
            newStroke.StylusPoints.Add(new StylusPoint(mousePosition.X, mousePosition.Y));
        }
    }

It seems to work as you described and I can see the darker parts of lines where few of them are overlapping.
Update
The overlapping effect in the suggested solution works for several overlapping lines, but does not work if a single line overlapps itself. If you want to make it work in this case as well, you can try to:

*

*use Canvas and add Polyline elements on it (update: this seems to work like the first solution suggested, so one line overlapping does not give the opacity effect)

*take a look at drawing on Image element using DrawingContext described here, it may help: Drawing with mouse causes gaps between pixels


text:
Q: For all $n$, $\partial_n \partial_{n+1} = 0$ From Rotman's Algebraic Topology:

Let $S_{n}(X) = \{\sigma | \sigma : \Delta^n \rightarrow X\}$ be the free abelian group with basis all singular $n$-simplices $\sigma: \Delta^n \rightarrow X$.
For all $n$, $\partial_n \partial_{n+1} = 0$.
Proof:
$\partial \partial \sigma = \partial(\sum_j (-1)^j\sigma \epsilon_j^{n+1}) = \sum _{j,k}(-1)^{j+k}\sigma\epsilon_j^{n+1}\epsilon_k^{n} =$
$ \sum _{j \le k}(-1)^{j+k}\sigma \epsilon_j^{n+1}\epsilon_k^n + \sum _{k \lt j}(-1)^{j+k}\sigma \epsilon_k^{n+1}\epsilon_{j-1}^n$ .
In the second sum, change the variables to $p = k$ and $q = j-1$ and now each term appears twice:
$ \sum _{j \le k}(-1)^{j+k}\sigma \epsilon_j^{n+1}\epsilon_k^n + \sum _{p \le q}(-1)^{p+q+1}\sigma \epsilon_p^{n+1}\epsilon_{q}^n$,
once in the first sum with positive sign and once in the second sum with opposite sign.

How does each term appear twice?  Let $p - 2$ and $q = 4$ which implies $k = 2$ and $j = 5$, but $5$ is not less than $2$ and therefore cannot be in the first sum.
What am I missing here?

A: Notice in the second line, the sum ranges over all pairs of $j,k$ as those indices range over all the subscripts of the edges.  Think of this as a big square of summands.
The sums in the third and fourth lines might appear to be sums only along one row or one column of that square (i.e., for fixed $j$ or for fixed $k$), but they are not.  They are sums of the upper and lower triangular regions of that square.  What is being observed is that for each term in either of these triangles of summands, there is a cancelling summand in the other triangle.
The reason for changing variables is that it is not the case that the $j,k$ term cancels the $k,j$ term.


text:
Q: Lua issue - Loading a library file before running I'm loading a Lua script to be run multiple times and another Lua script that acts as a library that is supposed to be used by the first script.
Let HelloWorldAPI.lua :
function HelloWorld()
    return "Hello world"
end

And SomeScript.lua :
HelloWorld()

I'm doing things in the following order :
L = luaL_newstate();
luaL_openlibs( L );
luaL_loadfile( L, "HelloWorldAPI.lua" );
luaL_loadfile( L, "SomeScript.lua" );
...
lua_pcall( L, 0, 0, 0 )
...
lua_pcall( L, 0, 0, 0 )
...

(some pieces of code were removed to keep it simple)
But I'm geting an error saying that I'm trying to call a nil value when calling the HelloWorld function.
Why ?
The function that I declared when the lib script was executed should be global and thus available in SomeScript.lua, right ?
Thank you.

A: luaL_loadfile(); loads and compiles a chunk, puts it on top of the stack, but does not execute it yet (so, after the first call to luaL_loadfile the function HelloWorld is not yet defined in the global lua state.
Then, you load the file SomeScript.lua, which is now on top of the stack. The call to lua_pcall now executes this chunk at the top, which tries to call the (not yet) defined function HelloWorld, resulting in the error you observe.
With this in mind, that would be the correct order:
luaL_loadfile( L, "HelloWorldAPI.lua" );
lua_pcall( L, 0, 0, 0 );
luaL_loadfile( L, "SomeScript.lua" );
lua_pcall( L, 0, 0, 0 );

However, to load and immediately execute a file you should use luaL_dofile:
luaL_dofile( L, "HelloWorldAPI.lua" );
luaL_dofile( L, "SomeScript.lua" );

A: luaL_loadfile leaves the compiled script as a function on the stack.
So, the function for SomeScript.lua is at the top, the function for HelloWorldAPI.lua is below it.


text:
Q: Actions SDK: Invoking action using "speak to" or "ask" According to Google, it is possible to invoke your own Google Action using the "speak to" and "ask" invocation commands. For example, "speak to [action name] to order a pizza". This is outlined here https://developers.google.com/actions/localization/languages-locales#trigger_phrases.
However, when using the Actions SDK, this does not seem quite so straight forward. After providing sample utterances as query patterns within the Action Package, it is not possible to make use of those sample utterances.
For example, say my query pattern looks like the following:
to order (a)? pizza
Then it would be expected that a user could say "Speak to [skill name] to order a pizza". However, this is not the case with some query patterns, and yet seemingly possible with others.
Is there anyone that could shed a light on whether this is a platform issue, or perhaps an incorrect definition of a query pattern?


text:
Q: Sax parsing a large file from S3 I have a very large xml file on s3 (50gb). I would like to stream this file to a sax xml parser for further processing using ruby. How would I do that in an environment where I cannon download the whole file locally, but only stream it over tcp from s3?
I'm thinking about using https://github.com/ohler55/ox for the parsing it self, and https://github.com/aws/aws-sdk-ruby for accessing the file on S3. I'm just unsure how connect the pieces using a streaming approach?

A: The most easiest way is to use mc. mc implements are cat command which can used in a simpler way.
For example as shown below. Here cat streams your object and pipe the output of cat to your XML parser which reads from stdinput.
$ mc cat s3.amazonaws.com/<yourbucket>/<yourobject> | <your_xml_parser>

This way you can avoid downloading the file locally.
Additionally mc provides more tools to work with Amazon S3 compatible cloud storage and filesystems. It has features like resumable uploads, progress bar, parallel copy. mc is written in Golang and released under Apache license v2. mc is supported on OS X, Linux and Windows.


text:
Q: Handle No Internet Connection Error Before Try to Parse the Result in Alamofire How should I handle if there is an error occurs when there is no internet connection in Alamofire. I tried checking if data is nil or not but it does not work.
Below is how I use Alamofire
Alamofire.request(.POST, REGISTER_URL, parameters: parameters, encoding: .JSON, headers: getAuthenticationHeader()).response { (request, response, data, errorType) -> Void in

    let resultObject: APIResults = APIResults(JSONDecoder(data!));
    let responseCode: Int = Int(resultObject.code!)!;// THIS CRASHES WHEN THERE IS NO INTERNET CONNECTION

    if (responseCode == 200) {
        available = true;
    }

    finished = true;

}

A: I agree with @Shripada. First you should use Reachability to check for connectivity.
There is a Swift library here: https://github.com/ashleymills/Reachability.swift
additionally you can use one of the Alamofire validation methods:
Alamofire.request(.POST, REGISTER_URL, parameters: parameters, encoding: .JSON, headers: getAuthenticationHeader()).validate(statusCode: 200 ..< 300).response { (request, response, data, error) -> Void in
    if error != nil {
        println("Server responded with: \(response.statusCode)")
        return
    }

    // Handle your response data here
}

A: Other way to check for internet connection existing
import SystemConfiguration

func connectedToNetwork() -> Bool {

        var zeroAddress = sockaddr_in()

       zeroAddress.sin_len = UInt8(sizeofValue(zeroAddress))

        zeroAddress.sin_family = sa_family_t(AF_INET)

      guard let defaultRouteReachability = withUnsafePointer(&zeroAddress, {
            SCNetworkReachabilityCreateWithAddress(nil, UnsafePointer($0))
        }) else {
            return false
        }
        var flags : SCNetworkReachabilityFlags = []

        if SCNetworkReachabilityGetFlags(defaultRouteReachability, &flags) == false {

            return false

        }

        let isReachable = flags.contains(.Reachable)

        let needsConnection = flags.contains(.ConnectionRequired)

        return (isReachable && !needsConnection)

    }

let hasInternet = connectedToNetwork()

A: Swift 3 Solution
Assuming you have an Error instance you can do the following:
if let err = error as? URLError, err.code  == URLError.Code.notConnectedToInternet
{
    // No internet
}
else
{
    // Other errors
}

You simply cast error into a URLError. This works since URLError implements the Error protocol. Here is a quote from the apple documentation for reference:

URLError: Describes errors in the URL error domain.

Once you have a URLError instance you can simply compare its code property, which is a URLError.Code enum, against the any relevant enum cases (in our example URLError.Code.notConnectedToInternet).

A: Details

*

*Xcode 10.2.1 (10E1001), Swift 5

Prepare
Edit NSAppTransportSecurity in Info.plist:
Code:
<key>NSAppTransportSecurity</key>
    <dict>
    <key>NSAllowsArbitraryLoads</key><true/>
</dict>

Sample 1 (need Alamofire pod)
Use Network Reachability
import UIKit
import Alamofire

class ViewController: UIViewController {

    override func viewDidLoad() {
        super.viewDidLoad()
        let button = UIButton(frame: .init(x: 80, y: 80, width: 100, height: 40))
        button.setTitle("Check", for: .normal)
        button.addTarget(self, action: #selector(checkInternetConnection), for: .touchUpInside)
        button.setTitleColor(.blue, for: .normal)
        view.addSubview(button)
    }

    @objc func checkInternetConnection() {
        guard let networkReachabilityManager = NetworkReachabilityManager(host: "http://google.com") else { return }
        networkReachabilityManager.listener = { [weak self] status in
            let alert = UIAlertController(title: "Network Status ", message: "\(status)", preferredStyle: .alert)
            alert.addAction(UIAlertAction(title: "OK", style: .default, handler: { [weak alert] _ in
                alert?.dismiss(animated: true, completion: nil)
            }))
            self?.present(alert, animated: true, completion: nil)
        }
        networkReachabilityManager.startListening()
    }
}

Sample 2 (need Alamofire pod)
import UIKit
import Alamofire

class ViewController: UIViewController {

    private lazy var networkManager = NetworkManager()

    override func viewDidLoad() {
        super.viewDidLoad()
        let button = UIButton(frame: .init(x: 80, y: 80, width: 100, height: 40))
        button.setTitle("Check", for: .normal)
        button.addTarget(self, action: #selector(checkInternetConnection), for: .touchUpInside)
        button.setTitleColor(.blue, for: .normal)
        view.addSubview(button)
    }

    @objc func checkInternetConnection() {
        let urlString = "http://dummy.restapiexample.com/api/v1/employees"
        networkManager.sessionManager.request(urlString).validate().response { response in
            print("\(response.data as Any)")
        }
    }
}

class NetworkManager {
    lazy var sessionManager: SessionManager = {
        let configuration = URLSessionConfiguration.default
        configuration.httpCookieStorage = nil
        configuration.httpCookieAcceptPolicy = HTTPCookie.AcceptPolicy.never
        let manager = SessionManager(configuration: configuration)
        manager.retrier = self
        return manager
    }()
}

extension NetworkManager: RequestRetrier {
    func should(_ manager: SessionManager, retry request: Request, with error: Error, completion: @escaping RequestRetryCompletion) {
        let error = error as NSError
        switch error.code {
            case -1009:
                DispatchQueue.main.async {
                    let alert = UIAlertController(title: "Error", message: error.localizedDescription, preferredStyle: .alert)
                    alert.addAction(UIAlertAction(title: "OK", style: .default, handler: { [weak alert] _ in
                        alert?.dismiss(animated: true, completion: nil)
                    }))
                    UIApplication.topMostViewController?.present(alert, animated: true, completion: nil)
                }
            default: break
        }
        print("-- Error code: \(error.code)")
        print("-- Error descriptiom: \(error.localizedDescription)")
    }
}

// https://stackoverflow.com/a/52932487
extension UIViewController {
    var topMostViewController: UIViewController {

        if let presented = self.presentedViewController {
            return presented.topMostViewController
        }

        if let navigation = self as? UINavigationController {
            return navigation.visibleViewController?.topMostViewController ?? navigation
        }

        if let tab = self as? UITabBarController {
            return tab.selectedViewController?.topMostViewController ?? tab
        }
        return self
    }
}

extension UIApplication {
    class var topMostViewController : UIViewController? {
        return UIApplication.shared.keyWindow?.rootViewController?.topMostViewController
    }
}

Sample 3 (without third party library)
More info: How to use SCNetworkReachability in Swift
import UIKit
import SystemConfiguration

class ViewController: UIViewController {
    override func viewDidLoad() {
        super.viewDidLoad()
        let button = UIButton(frame: .init(x: 80, y: 80, width: 100, height: 40))
        button.setTitle("Check", for: .normal)
        button.addTarget(self, action: #selector(checkInternetConnection), for: .touchUpInside)
        button.setTitleColor(.blue, for: .normal)
        view.addSubview(button)
    }

    @objc func checkInternetConnection() {
        print("-- \(URLSession.connectedToNetwork())")
    }
}

extension URLSession {
    class func connectedToNetwork() -> Bool {
        var zeroAddress = sockaddr()
        zeroAddress.sa_len = UInt8(MemoryLayout<sockaddr>.size)
        zeroAddress.sa_family = sa_family_t(AF_INET)
        guard let networkReachability = SCNetworkReachabilityCreateWithAddress(nil, &zeroAddress) else { return false }
        var flags = SCNetworkReachabilityFlags()
        SCNetworkReachabilitySetDispatchQueue(networkReachability, DispatchQueue.global(qos: .default))
        if SCNetworkReachabilityGetFlags(networkReachability, &flags) == false { return false }
        let isReachable = flags.contains(.reachable)
        let needsConnection = flags.contains(.connectionRequired)
        return isReachable && !needsConnection
    }
}

Sample 4 (need Reachability.swift pod)
import UIKit
import Reachability

class ViewController: UIViewController {

    override func viewDidLoad() {
        super.viewDidLoad()
        let button = UIButton(frame: .init(x: 80, y: 80, width: 100, height: 40))
        button.setTitle("Check", for: .normal)
        button.addTarget(self, action: #selector(checkInternetConnection), for: .touchUpInside)
        button.setTitleColor(.blue, for: .normal)
        view.addSubview(button)
    }

    @objc func checkInternetConnection() {
        guard let reachability = Reachability(hostname: "google.com", queueQoS: .utility) else { return }
        try? reachability.startNotifier()
        print("-- \(reachability.connection as Any)")
    }
}

A: Swift 5.0
You can check with NSURL-related Error Code
if error._code == NSURLErrorNotConnectedToInternet {

}

Or you can check with the code
if error._code == -1009 {

}

You can check other code on the developer site.
https://developer.apple.com/documentation/foundation/1508628-url_loading_system_error_codes

A: This works for me in Swift2.x
Alamofire.request(.POST, url).responseJSON { response in
    switch response.result {
        case .Success(let json):
            // internet works.
        case .Failure(let error):

            if let err = error as? NSURLError where err == .NotConnectedToInternet {
                // no internet connection
            } else {
                // other failures
            }
    }
}

A: It works in swift 5
.catchError { (error: Error) in
    if let err = error as? URLError, err.code  == URLError.Code.notConnectedToInternet {
        // No internet
    } else {
        // Other errors
    }
}


text:
Q: Label the internal memory file At Run Time I have an application that

*

*takes data from the user and

*creates a file in the internal memory based on the name entered by the user

*and saves the user data.

But when the file is saved by that name, the fileInputStream does not respond to that name.
what should I do ?
@Override
protected void onCreate(Bundle savedInstanceState) {
    super.onCreate(savedInstanceState);
    setContentView(R.layout.activity_load_food);
    bundle = getIntent().getExtras();
    Toolbar toolbar=(Toolbar)findViewById(R.id.food_lood_toolbar);
    setSupportActionBar(toolbar);
    file=bundle.getString("diname");

    getSupportActionBar().setTitle(file);
    String q="123";

    if (bundle.getString("activity").equals(q)) {

        String e1=editText1.getText().toString() +"/";

            fileOutputStream=openFileOutput(file,Context.MODE_PRIVATE);
            fileOutputStream.write(e1.getBytes());

    }
    String t="321";
    if (bundle.getString("activity").equals(t)){
            try {
                fileInputStream= openFileInput(file);
                int x;
                StringBuffer y = new StringBuffer();
                while((x=fileInputStream.read())!=-1){
                y.append((char)x);
                }
                String c=y.toString();
                txt=c.split("/");

            editText1.setText(txt[0]);

        } catch (FileNotFoundException e) {
            Toast.makeText(getBaseContext(),"file not found",Toast.LENGTH_LONG).show();

            e.printStackTrace();
        } catch (IOException e) {
            Toast.makeText(getBaseContext(),"io",Toast.LENGTH_LONG).show();

            e.printStackTrace();
        }
        finally {
                try {
                    fileInputStream.close();
                } catch (IOException e) {
                    e.printStackTrace();
                }
            }

}


text:
Q: is it possible sending data via NIC directly instead of via routing table lookup (linux command or python) Suppose I have 3 NIC in one host PC, name them eth0, eth1 and eth2
All interface have it's own ip address in different subnet, however, all the gateway router of those NIC have route to one server I want to access, I want to establish 3 connetions to that server and get response via different NIC.
I setting static route with different metric in that host PC, which means all ethX have route to server.
Is it possible establish tcp sessions via different NIC directly in python or via shell command sorts of:
s1 = socket.socket(socket.AF_INET, socket.SOCK_STREAM)
s1.connect((HOST, PORT, eth1))         # eth1 is my fiction
# and in same program
s0 = socket.socket(socket.AF_INET, socket.SOCK_STREAM)
s0.connect((HOST, PORT, eth0))         # ethO is my fiction

then the traffic can be send to that eth directly intead of via routing table lookup?
Thank!

A: The problem is that routing is determined by the destination and just because you have multiple routes available, doesn't mean that the OS will in fact use those multiple routes.  What you want is the OS to take into account the source address when determining which outbound route to use.  Once you get the routing correct, you can bind the source IP address on your socket and it will don the right thing.
In linux, you do this by creating multiple routing tables and setting up rules for picking those routing tables based on source IP address.  In general, the documentation for this is pretty bad, but searching for "multiple default routes" and iproute2 can help narrow it down.  Here are a couple of reasonable pages:
http://www.debian-administration.org/articles/377
http://lartc.org/howto/lartc.rpdb.multiple-links.html
OpenBSD also has support for multiple routing tables and I find it a bit easier to configure without hacking stuff into init scripts.  (You can even just do it in pf.conf)


text:
Q: Error scanning entry org/apache/logging/log4j/util/Base64Util.class from jar file:///C:.../log4j-api/2.13.3/log4j-api-2.13.3.jar I am migrating to java 11 from java 8 in project. Before migrating, Project uses the sun.misc.BASE64Encoder for encoding the byte string to string in java 8 version. Where java 8 provides BASE64Encoder. After migrating to java 11, BASE64Encoder is not provided. So, I am using alternative approach for doing Base64 Encoding. I uses the BASE64 from java.util package. I follow the link https://stackoverflow.com/questions/62193303/java-11-patch-sun-misc-base64encoder. I have written the String pubKeyStr = Base64.getEncoder().encodeToString(publicKey.getEncoded()); code for encoding. After running the program on jetty server, I am getting below error.
`MultiException[java.lang.RuntimeException: Error scanning entry org/apache/logging/log4j/util/Base64Util.class from jar file:///C:/Users/anmol/.m2/repository/org/apache/logging/log4j/log4j-api/2.13.3/log4j-api-2.13.3.jar, java.lang.RuntimeException: Error scanning entry org/apache/logging/log4j/util/ProcessIdUtil.class from jar file:///C:/Users/anmol/.m2/repository/org/apache/logging/log4j/log4j-api/2.13.3/log4j-api-2.13.3.jar, java.lang.RuntimeException: Error scanning entry org/apache/logging/log4j/util/StackLocator$FqcnCallerLocator.class from jar file:///C:/Users/anmol/.m2/repository/org/apache/logging/log4j/log4j-api/2.13.3/log4j-api-2.13.3.jar, java.lang.RuntimeException: Error scanning entry org/apache/logging/log4j/util/StackLocator.class from jar file:///C:/Users/anmol/.m2/repository/org/apache/logging/log4j/log4j-api/2.13.3/log4j-api-2.13.3.jar, java.lang.RuntimeException: Error scanning entry org/apache/logging/log4j/util/internal/DefaultObjectInputFilter.class from jar file:///C:/Users/anmol/.m2/repository/org/apache/logging/log4j/log4j-api/2.13.3/log4j-api-2.13.3.jar]
at org.eclipse.jetty.annotations.AnnotationConfiguration.scanForAnnotations(AnnotationConfiguration.java:540)
at org.eclipse.jetty.annotations.AnnotationConfiguration.configure(AnnotationConfiguration.java:449)
at org.eclipse.jetty.webapp.WebAppContext.configure(WebAppContext.java:496)
at org.eclipse.jetty.webapp.WebAppContext.startContext(WebAppContext.java:1363)
at org.eclipse.jetty.server.handler.ContextHandler.doStart(ContextHandler.java:778)
at org.eclipse.jetty.servlet.ServletContextHandler.doStart(ServletContextHandler.java:262)
at org.eclipse.jetty.webapp.WebAppContext.doStart(WebAppContext.java:522)
at org.eclipse.jetty.util.component.AbstractLifeCycle.start(AbstractLifeCycle.java:68)
at org.eclipse.jetty.util.component.ContainerLifeCycle.start(ContainerLifeCycle.java:131)
at org.eclipse.jetty.server.Server.start(Server.java:427)
at org.eclipse.jetty.util.component.ContainerLifeCycle.doStart(ContainerLifeCycle.java:105)
at org.eclipse.jetty.server.handler.AbstractHandler.doStart(AbstractHandler.java:61)
at org.eclipse.jetty.server.Server.doStart(Server.java:394)
at org.eclipse.jetty.util.component.AbstractLifeCycle.start(AbstractLifeCycle.java:68)
at net.sourceforge.eclipsejetty.starter.jetty9.Jetty9Adapter.start(Jetty9Adapter.java:68)
at net.sourceforge.eclipsejetty.starter.common.AbstractJettyLauncherMain.launch(AbstractJettyLauncherMain.java:84)
at net.sourceforge.eclipsejetty.starter.jetty9.Jetty9LauncherMain.main(Jetty9LauncherMain.java:42)
Caused by:
MultiException[java.lang.RuntimeException: Error scanning entry org/apache/logging/log4j/util/Base64Util.class from jar file:///C:/Users/anmol/.m2/repository/org/apache/logging/log4j/log4j-api/2.13.3/log4j-api-2.13.3.jar, java.lang.RuntimeException: Error scanning entry org/apache/logging/log4j/util/ProcessIdUtil.class from jar file:///C:/Users/anmol/.m2/repository/org/apache/logging/log4j/log4j-api/2.13.3/log4j-api-2.13.3.jar, java.lang.RuntimeException: Error scanning entry org/apache/logging/log4j/util/StackLocator$FqcnCallerLocator.class from jar file:///C:/Users/anmol/.m2/repository/org/apache/logging/log4j/log4j-api/2.13.3/log4j-api-2.13.3.jar, java.lang.RuntimeException: Error scanning entry org/apache/logging/log4j/util/StackLocator.class from jar file:///C:/Users/anmol/.m2/repository/org/apache/logging/log4j/log4j-api/2.13.3/log4j-api-2.13.3.jar, java.lang.RuntimeException: Error scanning entry org/apache/logging/log4j/util/internal/DefaultObjectInputFilter.class from jar file:///C:/Users/anmol/.m2/repository/org/apache/logging/log4j/log4j-api/2.13.3/log4j-api-2.13.3.jar]
at org.eclipse.jetty.annotations.AnnotationParser.parseJar(AnnotationParser.java:918)
at org.eclipse.jetty.annotations.AnnotationParser.parse(AnnotationParser.java:883)
at org.eclipse.jetty.annotations.AnnotationConfiguration$ParserTask.call(AnnotationConfiguration.java:165)
at org.eclipse.jetty.annotations.AnnotationConfiguration$1.run(AnnotationConfiguration.java:552)
at org.eclipse.jetty.util.thread.QueuedThreadPool.runJob(QueuedThreadPool.java:671)
at org.eclipse.jetty.util.thread.QueuedThreadPool$2.run(QueuedThreadPool.java:589)
at java.base/java.lang.Thread.run(Thread.java:834)
Suppressed:
|java.lang.RuntimeException: Error scanning entry org/apache/logging/log4j/util/ProcessIdUtil.class from jar file:///C:/Users/anmol/.m2/repository/org/apache/logging/log4j/log4j-api/2.13.3/log4j-api-2.13.3.jar
|   at org.eclipse.jetty.annotations.AnnotationParser.lambda$parseJar$0(AnnotationParser.java:929)
|   at java.base/java.util.TreeMap$ValueSpliterator.forEachRemaining(TreeMap.java:2890)
|   at java.base/java.util.stream.ReferencePipeline$Head.forEach(ReferencePipeline.java:658)
|   at org.eclipse.jetty.annotations.AnnotationParser.parseJar(AnnotationParser.java:921)
|   at org.eclipse.jetty.annotations.AnnotationParser.parse(AnnotationParser.java:883)
|   at org.eclipse.jetty.annotations.AnnotationConfiguration$ParserTask.call(AnnotationConfiguration.java:165)
|   at org.eclipse.jetty.annotations.AnnotationConfiguration$1.run(AnnotationConfiguration.java:552)
|   at org.eclipse.jetty.util.thread.QueuedThreadPool.runJob(QueuedThreadPool.java:671)
|   at org.eclipse.jetty.util.thread.QueuedThreadPool$2.run(QueuedThreadPool.java:589)
|   at java.base/java.lang.Thread.run(Thread.java:834)
|Caused by:
|java.lang.IllegalArgumentException
|   at org.objectweb.asm.ClassReader.<init>(Unknown Source)
|   at org.objectweb.asm.ClassReader.<init>(Unknown Source)
|   at org.objectweb.asm.ClassReader.<init>(Unknown Source)
|   at org.eclipse.jetty.annotations.AnnotationParser.scanClass(AnnotationParser.java:986)
|   at org.eclipse.jetty.annotations.AnnotationParser.parseJarEntry(AnnotationParser.java:970)
|   at org.eclipse.jetty.annotations.AnnotationParser.lambda$parseJar$0(AnnotationParser.java:925)
|   at java.base/java.util.TreeMap$ValueSpliterator.forEachRemaining(TreeMap.java:2890)
|   at java.base/java.util.stream.ReferencePipeline$Head.forEach(ReferencePipeline.java:658)
|   at org.eclipse.jetty.annotations.AnnotationParser.parseJar(AnnotationParser.java:921)
|   at org.eclipse.jetty.annotations.AnnotationParser.parse(AnnotationParser.java:883)
|   at org.eclipse.jetty.annotations.AnnotationConfiguration$ParserTask.call(AnnotationConfiguration.java:165)
|   at org.eclipse.jetty.annotations.AnnotationConfiguration$1.run(AnnotationConfiguration.java:552)
|   at org.eclipse.jetty.util.thread.QueuedThreadPool.runJob(QueuedThreadPool.java:671)
|   at org.eclipse.jetty.util.thread.QueuedThreadPool$2.run(QueuedThreadPool.java:589)
|   at java.base/java.lang.Thread.run(Thread.java:834)
Suppressed:
|java.lang.RuntimeException: Error scanning entry org/apache/logging/log4j/util/StackLocator$FqcnCallerLocator.class from jar file:///C:/Users/anmol/.m2/repository/org/apache/logging/log4j/log4j-api/2.13.3/log4j-api-2.13.3.jar
|   at org.eclipse.jetty.annotations.AnnotationParser.lambda$parseJar$0(AnnotationParser.java:929)
|   at java.base/java.util.TreeMap$ValueSpliterator.forEachRemaining(TreeMap.java:2890)
|   at java.base/java.util.stream.ReferencePipeline$Head.forEach(ReferencePipeline.java:658)
|   at org.eclipse.jetty.annotations.AnnotationParser.parseJar(AnnotationParser.java:921)
|   at org.eclipse.jetty.annotations.AnnotationParser.parse(AnnotationParser.java:883)
|   at org.eclipse.jetty.annotations.AnnotationConfiguration$ParserTask.call(AnnotationConfiguration.java:165)
|   at org.eclipse.jetty.annotations.AnnotationConfiguration$1.run(AnnotationConfiguration.java:552)
|   at org.eclipse.jetty.util.thread.QueuedThreadPool.runJob(QueuedThreadPool.java:671)
|   at org.eclipse.jetty.util.thread.QueuedThreadPool$2.run(QueuedThreadPool.java:589)
|   at java.base/java.lang.Thread.run(Thread.java:834)
|Caused by:
|java.lang.IllegalArgumentException
|   at org.objectweb.asm.ClassReader.<init>(Unknown Source)
|   at org.objectweb.asm.ClassReader.<init>(Unknown Source)
|   at org.objectweb.asm.ClassReader.<init>(Unknown Source)
|   at org.eclipse.jetty.annotations.AnnotationParser.scanClass(AnnotationParser.java:986)
|   at org.eclipse.jetty.annotations.AnnotationParser.parseJarEntry(AnnotationParser.java:970)
|   at org.eclipse.jetty.annotations.AnnotationParser.lambda$parseJar$0(AnnotationParser.java:925)
|   at java.base/java.util.TreeMap$ValueSpliterator.forEachRemaining(TreeMap.java:2890)
|   at java.base/java.util.stream.ReferencePipeline$Head.forEach(ReferencePipeline.java:658)
|   at org.eclipse.jetty.annotations.AnnotationParser.parseJar(AnnotationParser.java:921)
|   at org.eclipse.jetty.annotations.AnnotationParser.parse(AnnotationParser.java:883)
|   at org.eclipse.jetty.annotations.AnnotationConfiguration$ParserTask.call(AnnotationConfiguration.java:165)
|   at org.eclipse.jetty.annotations.AnnotationConfiguration$1.run(AnnotationConfiguration.java:552)
|   at org.eclipse.jetty.util.thread.QueuedThreadPool.runJob(QueuedThreadPool.java:671)
|   at org.eclipse.jetty.util.thread.QueuedThreadPool$2.run(QueuedThreadPool.java:589)
|   at java.base/java.lang.Thread.run(Thread.java:834)
Suppressed:
|java.lang.RuntimeException: Error scanning entry org/apache/logging/log4j/util/StackLocator.class from jar file:///C:/Users/anmol/.m2/repository/org/apache/logging/log4j/log4j-api/2.13.3/log4j-api-2.13.3.jar
|   at org.eclipse.jetty.annotations.AnnotationParser.lambda$parseJar$0(AnnotationParser.java:929)
|   at java.base/java.util.TreeMap$ValueSpliterator.forEachRemaining(TreeMap.java:2890)
|   at java.base/java.util.stream.ReferencePipeline$Head.forEach(ReferencePipeline.java:658)
|   at org.eclipse.jetty.annotations.AnnotationParser.parseJar(AnnotationParser.java:921)
|   at org.eclipse.jetty.annotations.AnnotationParser.parse(AnnotationParser.java:883)
|   at org.eclipse.jetty.annotations.AnnotationConfiguration$ParserTask.call(AnnotationConfiguration.java:165)
|   at org.eclipse.jetty.annotations.AnnotationConfiguration$1.run(AnnotationConfiguration.java:552)
|   at org.eclipse.jetty.util.thread.QueuedThreadPool.runJob(QueuedThreadPool.java:671)
|   at org.eclipse.jetty.util.thread.QueuedThreadPool$2.run(QueuedThreadPool.java:589)
|   at java.base/java.lang.Thread.run(Thread.java:834)
|Caused by:
|java.lang.IllegalArgumentException
|   at org.objectweb.asm.ClassReader.<init>(Unknown Source)
|   at org.objectweb.asm.ClassReader.<init>(Unknown Source)
|   at org.objectweb.asm.ClassReader.<init>(Unknown Source)
|   at org.eclipse.jetty.annotations.AnnotationParser.scanClass(AnnotationParser.java:986)
|   at org.eclipse.jetty.annotations.AnnotationParser.parseJarEntry(AnnotationParser.java:970)
|   at org.eclipse.jetty.annotations.AnnotationParser.lambda$parseJar$0(AnnotationParser.java:925)
|   at java.base/java.util.TreeMap$ValueSpliterator.forEachRemaining(TreeMap.java:2890)
|   at java.base/java.util.stream.ReferencePipeline$Head.forEach(ReferencePipeline.java:658)
|   at org.eclipse.jetty.annotations.AnnotationParser.parseJar(AnnotationParser.java:921)
|   at org.eclipse.jetty.annotations.AnnotationParser.parse(AnnotationParser.java:883)
|   at org.eclipse.jetty.annotations.AnnotationConfiguration$ParserTask.call(AnnotationConfiguration.java:165)
|   at org.eclipse.jetty.annotations.AnnotationConfiguration$1.run(AnnotationConfiguration.java:552)
|   at org.eclipse.jetty.util.thread.QueuedThreadPool.runJob(QueuedThreadPool.java:671)
|   at org.eclipse.jetty.util.thread.QueuedThreadPool$2.run(QueuedThreadPool.java:589)
|   at java.base/java.lang.Thread.run(Thread.java:834)
Suppressed:
|java.lang.RuntimeException: Error scanning entry org/apache/logging/log4j/util/internal/DefaultObjectInputFilter.class from jar file:///C:/Users/anmol/.m2/repository/org/apache/logging/log4j/log4j-api/2.13.3/log4j-api-2.13.3.jar
|   at org.eclipse.jetty.annotations.AnnotationParser.lambda$parseJar$0(AnnotationParser.java:929)
|   at java.base/java.util.TreeMap$ValueSpliterator.forEachRemaining(TreeMap.java:2890)
|   at java.base/java.util.stream.ReferencePipeline$Head.forEach(ReferencePipeline.java:658)
|   at org.eclipse.jetty.annotations.AnnotationParser.parseJar(AnnotationParser.java:921)
|   at org.eclipse.jetty.annotations.AnnotationParser.parse(AnnotationParser.java:883)
|   at org.eclipse.jetty.annotations.AnnotationConfiguration$ParserTask.call(AnnotationConfiguration.java:165)
|   at org.eclipse.jetty.annotations.AnnotationConfiguration$1.run(AnnotationConfiguration.java:552)
|   at org.eclipse.jetty.util.thread.QueuedThreadPool.runJob(QueuedThreadPool.java:671)
|   at org.eclipse.jetty.util.thread.QueuedThreadPool$2.run(QueuedThreadPool.java:589)
|   at java.base/java.lang.Thread.run(Thread.java:834)
|Caused by:
|java.lang.IllegalArgumentException
|   at org.objectweb.asm.ClassReader.<init>(Unknown Source)
|   at org.objectweb.asm.ClassReader.<init>(Unknown Source)
|   at org.objectweb.asm.ClassReader.<init>(Unknown Source)
|   at org.eclipse.jetty.annotations.AnnotationParser.scanClass(AnnotationParser.java:986)
|   at org.eclipse.jetty.annotations.AnnotationParser.parseJarEntry(AnnotationParser.java:970)
|   at org.eclipse.jetty.annotations.AnnotationParser.lambda$parseJar$0(AnnotationParser.java:925)
|   at java.base/java.util.TreeMap$ValueSpliterator.forEachRemaining(TreeMap.java:2890)
|   at java.base/java.util.stream.ReferencePipeline$Head.forEach(ReferencePipeline.java:658)
|   at org.eclipse.jetty.annotations.AnnotationParser.parseJar(AnnotationParser.java:921)
|   at org.eclipse.jetty.annotations.AnnotationParser.parse(AnnotationParser.java:883)
|   at org.eclipse.jetty.annotations.AnnotationConfiguration$ParserTask.call(AnnotationConfiguration.java:165)
|   at org.eclipse.jetty.annotations.AnnotationConfiguration$1.run(AnnotationConfiguration.java:552)
|   at org.eclipse.jetty.util.thread.QueuedThreadPool.runJob(QueuedThreadPool.java:671)
|   at org.eclipse.jetty.util.thread.QueuedThreadPool$2.run(QueuedThreadPool.java:589)
|   at java.base/java.lang.Thread.run(Thread.java:834)
Caused by:
java.lang.RuntimeException: Error scanning entry org/apache/logging/log4j/util/Base64Util.class from jar file:///C:/Users/anmol/.m2/repository/org/apache/logging/log4j/log4j-api/2.13.3/log4j-api-2.13.3.jar
at org.eclipse.jetty.annotations.AnnotationParser.lambda$parseJar$0(AnnotationParser.java:929)
at java.base/java.util.TreeMap$ValueSpliterator.forEachRemaining(TreeMap.java:2890)
at java.base/java.util.stream.ReferencePipeline$Head.forEach(ReferencePipeline.java:658)
at org.eclipse.jetty.annotations.AnnotationParser.parseJar(AnnotationParser.java:921)
at org.eclipse.jetty.annotations.AnnotationParser.parse(AnnotationParser.java:883)
at org.eclipse.jetty.annotations.AnnotationConfiguration$ParserTask.call(AnnotationConfiguration.java:165)
at org.eclipse.jetty.annotations.AnnotationConfiguration$1.run(AnnotationConfiguration.java:552)
at org.eclipse.jetty.util.thread.QueuedThreadPool.runJob(QueuedThreadPool.java:671)
at org.eclipse.jetty.util.thread.QueuedThreadPool$2.run(QueuedThreadPool.java:589)
at java.base/java.lang.Thread.run(Thread.java:834)
Caused by:
java.lang.IllegalArgumentException
at org.objectweb.asm.ClassReader.<init>(Unknown Source)
at org.objectweb.asm.ClassReader.<init>(Unknown Source)
at org.objectweb.asm.ClassReader.<init>(Unknown Source)
at org.eclipse.jetty.annotations.AnnotationParser.scanClass(AnnotationParser.java:986)
at org.eclipse.jetty.annotations.AnnotationParser.parseJarEntry(AnnotationParser.java:970)
at org.eclipse.jetty.annotations.AnnotationParser.lambda$parseJar$0(AnnotationParser.java:925)
at java.base/java.util.TreeMap$ValueSpliterator.forEachRemaining(TreeMap.java:2890)
at java.base/java.util.stream.ReferencePipeline$Head.forEach(ReferencePipeline.java:658)
at org.eclipse.jetty.annotations.AnnotationParser.parseJar(AnnotationParser.java:921)
at org.eclipse.jetty.annotations.AnnotationParser.parse(AnnotationParser.java:883)
at org.eclipse.jetty.annotations.AnnotationConfiguration$ParserTask.call(AnnotationConfiguration.java:165)
at org.eclipse.jetty.annotations.AnnotationConfiguration$1.run(AnnotationConfiguration.java:552)
at org.eclipse.jetty.util.thread.QueuedThreadPool.runJob(QueuedThreadPool.java:671)
at org.eclipse.jetty.util.thread.QueuedThreadPool$2.run(QueuedThreadPool.java:589)
at java.base/java.lang.Thread.run(Thread.java:834)`

Mainly error is Error scanning entry org/apache/logging/log4j/util/Base64Util.class from jar file:///C:/Users/anmol/.m2/repository/org/apache/logging/log4j/log4j-api/2.13.3/log4j-api-2.13.3.jar
I have used various approach. I used org.apache.commons.codec.binary.Base64 for encoding. I used the providing dependency for sun.misc.BASE64Encoder. I used the jars library for sun.misc.BASE64Encoder. For all approach I am getting same error. Please let me know the alternative approach for doing Base64Ecoding in java 11. Please help me out form this issue. Your help is appreciated.


text:
Q: ¿como hago para que el hook "woocommerce_payment_complete" no salte cuando el pago no fue exitoso? que tal. He desarrollado un plugin para wp, para actualizar el stock de la tienda fisica cada vez que haya una venta en la tienda online. Para ello utilizo este hook: woocommerce_payment_complete, pero he visto por internet que no solo salta cuando el pago es exitoso sino tambien cuando el estado del pedido es "failed" o "cancelled". Entonces queria asegurarme de que solo salte cuando el pago es exitoso. Este es el codigo completo del plugin:
<?php
/**
 * Plugin Name: miPlugin
 * Plugin URI: https://pablomonteserin.com
 * Description: Actualiza el stock de la tienda fisica
 * Version: 1.0.0
 * Author: Jose Luis Guillan Suarez
 * Author URI: https://pablomonteserin.com
 * License: GPL2
 */

add_action( 'woocommerce_payment_complete', 'rudr_complete' );

function rudr_complete( $order_id ) {

        global $wpdb;

    $order = wc_get_order($order_id);

    foreach ($order->get_items() as $item_id => $item ) {

        // Get an instance of corresponding the WC_Product object
        $product        = $item->get_product();

        $active_price   = $product->get_price(); // The product active raw price

        $regular_price  = $product->get_sale_price(); // The product raw sale price

        $sale_price     = $product->get_regular_price(); // The product raw regular price

        $product_name   = $item->get_name(); // Get the item name (product name)

        $item_quantity  = $item->get_quantity(); // Get the item quantity

        $item_subtotal  = $item->get_subtotal(); // Get the item line total non discounted

        $item_subto_tax = $item->get_subtotal_tax(); // Get the item line total tax non discounted

        $item_total     = $item->get_total(); // Get the item line total discounted

        $item_total_tax = $item->get_total_tax(); // Get the item line total  tax discounted

        $item_taxes     = $item->get_taxes(); // Get the item taxes array

        $item_tax_class = $item->get_tax_class(); // Get the item tax class

        $item_tax_status= $item->get_tax_status(); // Get the item tax status

        $item_downloads = $item->get_item_downloads(); // Get the item downloads

        $item_sku = $product->get_sku();

            $cantidad = $item_quantity;
            $referencia = $item_sku;

            $results = $wpdb->get_results('SELECT * FROM productos WHERE codigo_de_barras = "'.$referencia.'"');

                foreach( $results as $result ) {
                    $unidadesRestantes=$result->unidades-$cantidad;
                    $wpdb->update( "productos", array( 'unidades' => $unidadesRestantes),array('codigo_de_barras'=>$referencia));
                    //mail("luilli.guillan@gmail.com", "dentro del bucle",$result->unidades);
                }

    }

}?>


text:
Q: Error while installing mongodb in AWS EKS cluster - "running PreBind plugin VolumeBinding: binding volumes: timed out > waiting for the condition" I tried to install mongodb in EKS cluster by following the given links.
(using mongodb-kubernetes-operator)
https://www.youtube.com/watch?v=VqeTT0NvRR4&t=1s
https://github.com/mongodb/mongodb-kubernetes-operator
kubectl apply -f config/crd/bases/mongodbcommunity.mongodb.com_mongodbcommunity.yaml
kubectl get crd/mongodbcommunity.mongodbcommunity.mongodb.com

kubectl create ns mongo

kubectl apply -k config/rbac/ --namespace mongo

kubectl get role mongodb-kubernetes-operator --namespace mongo

kubectl get rolebinding mongodb-kubernetes-operator --namespace mongo

kubectl get serviceaccount mongodb-kubernetes-operator --namespace mongo

kubectl create -f config/manager/manager.yaml --namespace mongo

kubectl get pods --namespace mongo

kubectl apply -f config/samples/mongodb.com_v1_mongodbcommunity_cr.yaml --namespace mongo
kubectl get pods -n mongo

When checked
kubectl get pods -n mongo

example-mongodb-0 pod is in pending state for very long time.
Upon describing the pod got the following error,

"running PreBind plugin "VolumeBinding": binding volumes: timed out
waiting for the condition".

A: When contacted with AWS support team, got the following response.

From your correspondence, I understand that you are facing issues
while creating the mongodb pods in your EKS cluster, and after
creating the pod, your pod is going to pending status.
Please let me know if I misunderstood your query. Thanks for sharing
the GitHub repository URL using the same. I put some effort into
replicating the same issue on my side, and thankfully I was able to
replicate the issue.
Further investigation into my pending pod problem I ran the following
describe command on my cluster,
"kubectl describe pod <pending_pod_name>"
After several minutes, I found the following line in the "event"
part of my output.
"running PreBind plugin "VolumeBinding": binding volumes: timed out
waiting for the condition".
On further investigation, I found that the mongodb pod module that you
are trying to deploy on your cluster is trying to create an EBS volume
as a persistent volume, which is why I got the aforementioned error.
We need the EBS CSI driver add-on installed in your cluster to create
an EBS volume using EKS, and the above error usually occurs if the EBS
CSI driver add-on is not present. Since this add-on is not installed
by default while creating the cluster you need to install it via EKS
console add-on tab.
Or another possibility is that, even though the add-on is present, it
won't have the required permission to create the EBS volume. So,
before we even install the EBS CSI driver add-on to the cluster, we
need to make sure that we have created the IAM role for attaching to
the add-on. The same is referred to over here[1].
In your case, you can check whether the EBS CSI driver is present by
running the following command:
"kubectl get pods -n kube-system"
And look for pods with names like "ebs-csi-controller-xxxxxxx." If
you find one, it means you've already installed the EBS CSI driver,
and the problem could be with permissions.
For that, you need to run the following command.
"kubectl describe pod ebs-csi-controller-xxxxxxx -c csi-provisioner
-n kube-system"
This will give an output of the configuration of the driver pod. In
that output, you need to check for an environment called
"AWS_ROLE_ARN:" If that wasn't present in your output, this implies
that you haven't provided the IAM OIDC provider role for the add-on.
So you need to create that role in the IAM console, then remove the
existing EBS CSI driver add-on from the EKS cluster console, and then
again add the EBS CSI driver add-on with that role as "Service
account role". More details for adding the EBS CSI driver add-on to
the cluster are referred to here[3].
If you already have the value for "AWS_ROLE_ARN" then you need to
check for the configuration of the role by using this
documentation[2].
So, keeping the above things in mind, I have created the IAM OIDC
provider role for the add-on. For that, you need to follow all the
steps regarding how to create an IAM role for the add-on as referred
to here[2].
After creating the IAM OIDC provider role, I have installed the add-on
via console by following the steps in this documentation[3] and for
the service account role, I have selected the OIDC provider role that
was created in the above step.
After installing the add-on, I tried to delete the mogodb database pod
by running the following command.
"kubectl delete -f
config/samples/mongodb.com_v1_mongodbcommunity_cr.yaml"
Then run the following apply command to redeploy the pods.
"kubectl apply -f
config/samples/mongodb.com_v1_mongodbcommunity_cr.yaml"
After I checked the pods, I could see that the mongodb database pod
had come to running status.
The above is the most common issue that might happen, if none of the
above is your problem then please share a convenient time along with
the timezone you're working in as well as contact number with country
code so that we can connect over a call and have a screen sharing
troubleshooting session.

reference links:
[1] Amazon EBS CSI driver add-on : https://docs.aws.amazon.com/eks/latest/userguide/ebs-csi.html
[2] How to create IAM OIDC provider for EBS CSI driver add-on : https://docs.aws.amazon.com/eks/latest/userguide/csi-iam-role.html
[3] Managing the EBS CSI driver add-on : https://docs.aws.amazon.com/eks/latest/userguide/managing-ebs-csi.html
Working commands/steps
(Steps mentioned by support team)

*

*Creation of EKS cluster

*Go to the newly created EKS cluster in AWS console. In the Overview tab, copy the value of OpenID Connect provider URL and save the value in some place for future reference.

*Go to IAM -> Identity providers -> Add Provider. Select OpenID Connect as the provider type.

*Paste the copied url from step 2, in the Provider URL textbox and click 'Get thumbprint'. Set Audience - sts.amazonaws.com in the corresponding text box.

*Click the 'Add Provider' button.

*Create the required iam role. IAM -> Roles -> Create Role. In the 'Select trusted entity' section, choose 'Web Identity' . In Identity provider drop down, select the OIDC option that is created in step 5. Choose Audience - sts.amazonaws.com in the drop down. Click 'Next'

*Search for AmazonEBSCSIDriverPolicy policy in the next window and click 'Next' and give name,description,tags for the role and click create role.

*In the Roles section, search for the newly created role in step 7 and go inside that role. Trust relationships -> Edit trust policy.

"oidc.eks.eu-west-1.amazonaws.com/id/385AA11111111116116:sub":
"system:serviceaccount:kube-system:ebs-csi-controller-sa"

*Update the above text with current oidc id and add it as new key-value in the Statement[0] -> Condition -> StringEquals. Refer the full json structure of this trusted relationship json data in the last.

*After updating the text, click 'Update Policy'
Go to EKS -> Clusters -> Newly created cluster in step 1. Click Add-ons tab, Add new.

*In the pop up choose Name as Amazon EBS CSI Driver. Version as latest. Choose Role as the role created in step 7. If the above role is not listed in drop down, reload the section using the reload button and click Add.

*After some time, the new Add on will become active. Then run this kubectl get pods -n kube-system command and we should see csi pods as shown.
    ebs-csi-controller-68d49f84c8-sl7w6   6/6     Running   0          109s
    ebs-csi-controller-68d49f84c8-w2k6r   6/6     Running   0         2m19s
    ebs-csi-node-ldmsm                    3/3     Running   0        2m20s

Then run the commands given in the question.
Following dictionary is the Trusted relationships json for role
{
    "Version": "2012-10-17",
    "Statement": [
        {
            "Effect": "Allow",
            "Principal": {
                "Federated": "arn:aws:iam::112345678900:oidc-provider/oidc.eks.eu-west-1.amazonaws.com/id/Axxxxxxxxxxxxx"
            },
            "Action": "sts:AssumeRoleWithWebIdentity",
            "Condition": {
                "StringEquals": {
                    "oidc.eks.eu-west-1.amazonaws.com/id/Axxxxxxxxxxxxx:sub": "system:serviceaccount:kube-system:ebs-csi-controller-sa",
                    "oidc.eks.eu-west-1.amazonaws.com/id/Axxxxxxxxxxxxx:aud": "sts.amazonaws.com"
                }
            }
        }
    ]
}


text:
Q: Proving inequality using Mathematical Induction I'm stuck in a prove by Mathematical Induction and I have no clue how to continue on.
To prove:

$2!\cdot 4! \cdot 6! \cdot ...\cdot(2n)! \geq [(n+1)!]^n$ for all $n \in \mathbb{N}$

Proof:
We proceed by induction. Since $2! = 2 \geq 2^1 =2$ is true for $n = 1$. Assume for a $k \in \mathbb{N}$, that
$2!\cdot 4! \cdot 6! \cdot ...\cdot(2k)! \geq [(k+1)!]^n$ .
We show that
$2!\cdot 4! \cdot 6! \cdot ...\cdot(2(k+1))! \geq [(k+2)!]^{k+1}$
Observe that
$2!\cdot 4! \cdot 6! \cdot ...\cdot (2k)! \cdot (2(k+1))! \geq [(k+1)!]^k (2k+2)!$
I do not, however, know how to proceed further.

A: Expand out $[(k+2)!]^{k+1}$ into individual factors: $[1 \cdot 2 \cdot \ldots \cdot k \cdot (k + 1) \cdot (k + 2)]^{k+1} = 1^{k+1} \cdot 2^{k+1} \cdot \ldots \cdot k^{k+1} \cdot (k+1)^{k+1} \cdot (k+2)^{k+1}$. Doing the same thing with $[(k+1)!]^k$, we get $1^k \cdot 2^k \cdot \cdots \cdot k^k \cdot (k+1)^k$. Notice that for the numbers $1$ through $k+1$, we have exactly one more factor in $[(k+2)!]^{k+1}$ than $[(k+1)!]^k$. Grouping together everything we can, we can write $[(k+2)!]^{k+1} = [(k+1)!]^k \cdot 1 \cdot 2 \ldots \cdot k \cdot (k+1) \cdot (k+2)^{k+1}$. Simplifying a little, $[(k+2)!]^{k+1} = [(k+1)!]^k \cdot (k+1)! \cdot (k+2)^{k+1}$.
So now the question is: how do you know that $(2k+2)! > (k+1)! \cdot (k+2)^{k+1}$? For that, try the same trick: expand out both sides, cancel out factors, and see what happens.

A: We wish to show $2!4!\cdots (2k+2)! \geq [(k+2)!]^{k+1}$. By the inductive hypothesis
$$[(k+2)!]^{k+1}=[(k+1)!]^k\cdot (k+1)!(k+2)^{k+1}\leq 2!4!\dots(2k)!\cdot(k+1)!(k+2)^{k+1}.$$
So, the result holds if we can show that
$$(k+1)!(k+2)^{k+1}\leq (2k+2)!$$
However, we can estimate $(k+2)$ by $(k+n)$ for all $n\geq 2$:
$$(k+1)!(k+2)^{k+1}\leq(k+1)!(k+2)(k+3)\cdots (k+(k+2)) = (2k+2)!$$
and the result follows.

A: Assume that $2!\cdot 4! \cdot 6! \cdot ...\cdot(2k)! \geq [(k+1)!]^n$, then
$$
\begin{align}
[(k+2)!]^{k+1} = & [(k+2)!]^{k}\cdot (k+2)!\\
= & [(k+1)!]^{k}\cdot(k+2)^{k}\cdot (k+2)! \\
\leq & [(k+1)!]^{k} \cdot \prod_{i=1}^k (k+2+i)\cdot (k+2)!\\
=& [(k+1)!]^{k} \cdot (2k+2)! \\
\leq & 2!\cdot 4! \cdot 6! \cdot ...\cdot (2k)! \cdot (2(k+1))!
\end{align}
$$


text:
Q: Django + raw SQL query - how to juggle between a null value for a field in sql query I have a sql query. It first gets all the songs from the playlists. These songs could have an entry in Block Song Table and possibly some songs may not have an entry in the block song model.
So, for those songs who have an entry they will have an unblock_flag which is a boolean field and will carry either true or false. But, the concern is that those songs which will not have an entry in the block song model table will have null values for unblock_flag. I also thought to use an update in it but that also didn't work. The field to be changed is core_blocksong.unblock_flag in the below query.
So, if anyone can suggest any other ways to make this scenario work?
select songs.id, songs.name, songs.artist, songs.album, songs.albumart,
songs."albumartThumbnail", cpr.votes, is_requested, core_blocksong.unblock_flag from (select id,
name, artist, album, albumart, "albumartThumbnail" from (select song_id from
core_plsongassociation where
playlist_id in (1477)) as sinpl left join songs on sinpl.song_id=id) as
songs left join (select` song_id, votes, bool_or(user_id=null) as is_requested from
(select * from core_priorityrequests where client_id=2876 and is_played=False) as clpr left
join core_priorityrequests_requested_by
on clpr.id=priorityrequests_id group by priorityrequests_id, song_id, votes) as cpr
on songs.id=cpr.song_id left join core_blocksong on songs.id = core_blocksong.song_id where core_blocksong.unblock_flag='f'and core_blocksong.client_id=2876;`

Adding the Block Song Model Table:
class BlockSong(models.Model):
    client = models.ForeignKey('Client')
    playlist = models.ForeignKey('Playlist', blank=True, null=True)
    song = models.ForeignKey('Song')
    unblock_flag = models.BooleanField(default=False)

Update 1:
I have found the answer but here, I am getting a small error:
ERROR:  syntax error at or near "on"
LINE 3: ...select core_blocksong.song_id from core_blocksong on (songs....

And the Query:
select songs.id, songs.name, songs.artist, songs.album, songs.albumart,
songs."albumartThumbnail", cpr.votes from (select id, name, artist, album, albumart, "albumartThumbnail" from (select song_id from core_plsongassociation where playlist_id in (1477)) as sinpl left join songs
on sinpl.song_id=id where explicit=False) as songs left join (select song_id, votes, bool_or(thirdpartyuser_id=177) as is_requested from (select *
from core_priorityrequests where client_id=2876 and is_played=False) as clpr left join core_priorityrequests_third_party_user on clpr.id=priorityrequests_id group by priorityrequests_id, song_id, votes) as cpr on songs.id=cpr.song_id where songs.id not in (select core_blocksong.song_id from core_blocksong on (songs.id = core_blocksong.song_id) where core_blocksong.unblock_flag = 'f' and core_blocksong.client_id=2876);

Can anyone suggest what is wrong in on here in the second last line?


text:
Q: PL/SQL data types conversion I am writing a PL/SQL procedure and I'm having a problem with type conversion. Here is my code:
create or replace FUNCTION fn_easy7 (att in nfl5.att%type,
    comp in nfl5.comp%type, td in nfl5.td%type,inter in nfl5.inter%type,
    yds_g in nfl5.yds_g%type, yds in nfl5.yds%type)
RETURN number IS
   a number;
   b number;
   c number;
   d number;
   e number;
BEGIN
   a :=  (((comp/att)*100)-30)/20;
   b := ((td/att)*100)/5;
   c := (9.5 - ((inter/att)*100))/4;
   d := ((TO_NUMBER(yds, '999')/att) - 3)/4 ;
   e := (a + b + c + d)/ 0.06;

   RETURN e;
END fn_easy7;

update nfl5
   set rate = fn_easy7(att , comp, td ,inter, yds_g, yds);

Description for table nfl5:
 Name      Null   Type
---------- -----  ------------
  COMP            NUMBER(4)
  YDS             VARCHAR2(8)
  TD              NUMBER(3)
  RATE            NUMBER
  YDS_G           VARCHAR2(5)

Type of rate number as well. I have error numeric or value errors.


text:
Q: STL algorithm function name resolution I'd expect in the example bellow compiler will fail to compile the code, since it
doesn't know what is "find()", which defined in std namespace in algorithm header.
However this code compiles on RHEL 5.3 with gcc 4.1.2.
What do I miss?
#include <string>
#include <algorithm>

int main()
{
    std::string s;
    find(s.begin(), s.end(), 'a');  // should not compile
}

A: This works due to Argument Dependent Lookup. The function-template is searched in the namespace of the arguments types. In this case, the arguments are std::string::iterator, so the function is searched in the namespace std.


text:
Q: how to make deb package version 2? I am trying to build deb packages using deb version 2, I downloaded apache2_2.4.18-2ubuntu3_amd64.deb when I extracted it I found 3 files inside it.
1) control.tar.gz
2) data.tar.xz
3) debian-binary
I know, how to make older version.
but didn't find a correct guide to make deb in format 2
please provide video tutorial or article link!

A: I found this solution
1) Decide on the name of your package. Standard debian notation is all lowercase in the following format:
Code: <project>_<major version>.<minor version>-<package revision>

2) For example, you could name your first package...
Code: mypackage_1.0-1
3) copy all all your program files to mypackage_1.0-1
4) create DEBIAN directory inside mypackage_1.0-1
5) create control file inside DEBIAN with below content (modify it as your package)
Package: mypackage
Version: 1.0-1
Section: base
Priority: optional
Architecture: i386
Depends: libsomethingorrather (>= 1.2.13), anotherDependency (>= 1.2.6)
Maintainer: Your Name <you@email.com>
Description: my Package
 When you need some sunshine, just run this
 small program!
 (the space before each line in the description is important)

7) Now you just need to make the package:
Code: dpkg-deb --build mypackage_1.0-1


text:
Q: Composer "Download failed" Error i use xampp in Windows and my PHP Version is 5.5.15 .
need to install composer for Start work with laravel framework. but my problem is here, when i want install composer, be faced with this error :
Download failed: file_get_contents(): SSL operation failed with code 1. OpenSSL Error messages:
error:14090086:SSL routines:SSL3_GET_SERVER_CERTIFICATE:certificate verify failed
file_get_contents(): Failed to enable crypto
file_get_contents(https://getcomposer.org/composer.phar): failed to open stream: operation failed
Download failed: file_get_contents(): SSL operation failed with code 1. OpenSSL Error messages:
error:14090086:SSL routines:SSL3_GET_SERVER_CERTIFICATE:certificate verify failed
file_get_contents(): Failed to enable crypto
file_get_contents(https://getcomposer.org/composer.phar): failed to open stream: operation failed
Download failed: file_get_contents(): SSL operation failed with code 1. OpenSSL Error messages:
error:14090086:SSL routines:SSL3_GET_SERVER_CERTIFICATE:certificate verify failed
file_get_contents(): Failed to enable crypto
file_get_contents(https://getcomposer.org/composer.phar): failed to open stream: operation failed
The download failed repeatedly, aborting.

What should I do?
and is there a way to install laravel without using composer ?

A: You basically have to set the environment variable SSL_CERT_FILE to the path of the PEM file of the ssl-certificate downloaded from the following link : http://curl.haxx.se/ca/cacert.pem.
It took me a lot of time to figure this out.
For a detailed answer, you can have a look here: https://stackoverflow.com/questions/34590842/cannot-install-composer-on-mac-os-x

A: If you are using Kaspersky, try to disable the Encrypted connection scanning (or set the Scan encrypted connections upon request from protection components option) and try again.

If you have the Always scan encrypted connections you can get errors like these:
[Composer\Downloader\TransportException]
  The "https://packagist.org/packages.json" file could not be downloaded: SSL operation failed with code 1. OpenSSL Error messages:
  error:1416F086:SSL routines:tls_process_server_certificate:certificate verify failed
  Failed to enable crypto
  failed to open stream: operation failed

[RuntimeException]
  Failed to clone https://github.com/doctrine/inflector.git via https, ssh protocols, aborting.
  - https://github.com/doctrine/inflector.git
    Cloning into 'C:\Users\User\my-project\vendor\doctrine\inflector'...
    fatal: unable to access 'https://github.com/doctrine/inflector.git/': SSL certificate problem: self signed certificate in certificate chain
  - git@github.com:doctrine/inflector.git
    Cloning into 'C:\Users\User\my-project\vendor\doctrine\inflector'...
    Host key verification failed.
    fatal: Could not read from remote repository.

    Please make sure you have the correct access rights
    and the repository exists.


text:
Q: How you can put 6 values when overloading an operator? But values also can be added after? Okay, I am aware it seems complicated.
To start with the code has to take 2 string 2 int numbers and smash them together depending on input then out put result just like:
input:
Dave
8
Jessica
7
output:
Dave & Jessica
15
I tried many times with different approaches but none  seems to work :(
I tried  putting name1 or name2 like strings to DancerPoints Class but I can't find a way to connect with input I mean it is there but can't get input.
I also tried putting values in to the parameter directly but it said operator just can take 2 values but I need 6! 4 for dancers values 2 for management.
At this point it only gets the firstdancer's string and int and use it but I don't get how to add seconddancer's values.
I am working on this for 3 nights I don't know what else to do? :(
using System;
using System.Collections.Generic;

namespace Code_Coach_Challenge
{
    class Program
    {
        // I tried putting values here with public but why that not workked I dont know :(

        static void Main(string[] args)
        {
            string name1 = Console.ReadLine();
            int points1 = Convert.ToInt32(Console.ReadLine());
            string name2 = Console.ReadLine();
            int points2 = Convert.ToInt32(Console.ReadLine());

            DancerPoints dancer1 = new DancerPoints(name1, points1);
            DancerPoints dancer2 = new DancerPoints(name2, points2);

            DancerPoints total = dancer1 + dancer2;
            Console.WriteLine(total.name);
            Console.WriteLine(total.points);
        }
    }

    class DancerPoints
    {
        public string name;
        public int points;
                            // I tried putting values here no luck.error CS7036
        public DancerPoints(string name, int points)
        {
            this.name = name;
            this.points = points;
                                  // I tried putting values here no luck.error CS7036
        }

        //overload the + operator
        public static DancerPoints operator+ (DancerPoints n, DancerPoints p)
        {
                                     // I tried putting values here no luck.error CS7036
            string name = n.name + " & " + n.name;
            int points = p.points + p.points;

            DancerPoints res = new DancerPoints(name, points);

            return res;

        }
    }
}

A: You can simplify a lot of this code down if all you want the program to do is

*

*Ask for Name1

*Ask for Points1

*Ask for Name2

*Ask for Points2

*Print {Name1} & {Name2} {Points1 + Points2}
string name1 = Console.ReadLine();
int points1 = Convert.ToInt32(Console.ReadLine());
string name2 = Console.ReadLine();
int points2 = Convert.ToInt32(Console.ReadLine());

string output = $"{name1} & {name2} {points1 + points2}"
Console.WriteLine(output);

Just simple string concatenation. No need for any fancy classes or operator overloads.

Now, if you wanted to expand your code to do more than two people at a time, then
class Dancer
{
    public string Name {get;set;}
    public int Score {get;set;}
}

var dancers = new List<Dancer>
{
    new Dancer { Name = "David", Score = 8 },
    new Dancer { Name = "Jessica", Score = 7 },
    new Dancer { Name = "Sally", Score = 6 },
}

var allNames = string.Join(" & ", dancers.Select(x => x.Name));
var totalScore = dancers.Sum(x => x.Score);
var output = $"{allNames} {totalScore}"

With this example you'd get

David & Jessica & Sally 21

Again, no need for operator overloading. It doesn't really make sense to "add" dancers together into a new "Dancer" object.

A: Your operator overload should be:
public static DancerPoints operator+ (DancerPoints n, DancerPoints p)
    {
        string name = n.name + " & " + p.name;
        int points = n.points + p.points;

        DancerPoints res = new DancerPoints(name, points);

        return res;
    }

Notice how I changed an n into a p and a p into an n.
This way both n and p's name and point values are used.


text:
Q: What is the correct punctuation in this sentence? Would someone please check and correct the following sentence for punctuation:

A 9/11 widow psychiatrist, falls for a patient, who plans a similar attack to avenge his colleagues, annihilated in the false war that followed the 9/11.

A:
A psychiatrist, widowed by the 9/11 attacks, falls for a patient who
  plans a similar action to avenge his former colleagues, all of whom
  were annihilated in the invasion of Iraq and the false war that followed.

That's how I would phrase it. I've added parenthetical commas at the beginning to make it read a bit easier, and so that there's no initial confusion about the subject of the piece. I would maybe refine your choice of the term "false war", because it was definitely a war, just a war of a highly questionable nature. Perhaps "unjustified" or something along those lines would be more appropriate? Using "false" seems a little blurry, in my opinion.


text:
Q: Get value of input text with react-bootstrap I try to get value into a input text and add it to a text area with react-bootstrap.
I know I must use ReactDOM.findDOMNode to get value with ref. I don't understand what is wrong.
Here my code :
import React from 'react';
import logo from './logo.svg';
import ReactDOM from 'react-dom';
import { InputGroup, FormGroup, FormControl, Button} from 'react-bootstrap';
import './App.css';
class InputMessages extends React.Component {
constructor(props) {
super(props);
this.handleChange =      this.handleChange.bind(this);
    this.GetMessage= this.GetMessage.bind(this);
this.state = {message: ''};
}
handleChange(event)
{
this.setState({message: this.GetMessage.value});
}
GetMessage()
{
return ReactDOM.findDOMNode(this.refs.message     );
 }
 render() {
    var message = this.state.message;
    return(
 <FormGroup >
 <FormControl
 componentClass="textarea" value={message} />
 <InputGroup>
 <FormControl type="text" ref='message' />
    <InputGroup.Button>
    <Button bsStyle="primary" onClick={this.handleChange}>Send
    </Button>
    </InputGroup.Button>
    </InputGroup>
    </FormGroup>
    );
   }
   }
   export default InputMessages;

A: Form Control has a ref prop, which allows us to use React Refs
Sample Code :
class MyComponent extends React.Component {
  constructor() {
     /* 1. Initialize Ref */
     this.textInput = React.createRef();
  }

  handleChange() {
     /* 3. Get Ref Value here (or anywhere in the code!) */
     const value = this.textInput.current.value;
  }

  render() {
    /* 2. Attach Ref to FormControl component */
    return (
      <div>
        <FormControl ref={this.textInput} type="text" onChange={() => this.handleChange()} />
      </div>
    )
  }
}

Hope this helps!

A: Add an Input ref to your form :
<FormControl inputRef={ref => { this.myInput = ref; }} />

so now you get the value like
this.myInput.value


text:
Q: Property of continuous functions and monotonic functions on disconnected sets If $S=[0,1)\cup [2,3]$ and $f:S\to \mathbb{R}$ be strictly increasing and $f(S)$ be connected. Then, is $f$ continuous? If so, why?
Am totally helpless. I think the proof/disproof has something to do with the property that image of connected set is connected and the monotonicity. Thanks beforehand.


text:
Q: Rails console ignores newlines in ActiveRecord:Relation object? I was going through the AR query interface guide and from it I got the impression that the Rails console should be interpreting the \n in the output from the .explain command as a newline, rather than printing it as raw text on the screen. Reading a query on one single line is inconvenient to say the least.
I can "fix" the formatting issue by prepending "print" to any ActiveRecord::Relation object output to the console, as in the canonical example:
print User.joins(:posts).explain

Is it supposed to work that way by default, or am I doing something wrong? Do people always stick to prepending print?
Thanks!

A: Yes, the rails console displays the \n characters (rather than rendering) them by default. I always add print exactly as you have done.

A: Seems normal.
>> hi = "hello\nworld"
=> "hello\nworld"
>> hi
=> "hello\nworld"
>> puts hi
hello
world
=> nil

If you just type a variable or method, it shows you a raw data dump of the value or return value.


text:
Q: Error opening serial port in c# So I am receiving the following exception when I attempt to open COM1 in a c# application, using the SerialPort.Open() method:
"ArgumentException: The given port name does not start with COM/com or does not resolve to a valid serial port"
However, if I disable the Com1 port in Device Manager, then enable, everything works fine. From then on, no problems. I can run the app and open the port without fail. But if I reset the PC, I experience the same issue, until I disable then enable.
Com1 does not appear to be open when I start the computer. When Com1 is open, and I try to open with my app, I do not get an ArgumentException. Rather, i get an exception that access to that port is denied.
I have only attempted this with Windows 7 machines. I am using VS2010. I tried .net 3.5 & 4.0.
So, as I've said, the app works fine ONCE I reset the port. Any thoughts?
Code (This is a simple test app):
public partial class Form1 : Form
{
    SerialPort port = new SerialPort();

    public Form1()
    {
        InitializeComponent();
    }

    private void Form1_Load(object sender, EventArgs e)
    {
        string[] ports = SerialPort.GetPortNames();

        foreach (string element in ports)
        {
            textBox1.Text = element + "\r\n";
        }
    }

    private void button1_Click(object sender, EventArgs e)
    {
        port.PortName = "COM1";
        port.BaudRate = 9600;
        port.Parity = Parity.None;
        port.DataBits = 8;
        port.StopBits = StopBits.One;
        port.Handshake = Handshake.None; // Handshake.RequestToSend;
        port.ReadTimeout = 1000;
        port.WriteTimeout = 500;
        try
        {
            port.Open();
        }
        catch (Exception ex)
        {
            MessageBox.Show(ex.ToString());
        }
        button1.Text = port.IsOpen.ToString();
    }
}

}

A: I figured it out.
Adobe PDF, for some reason, is assigned to COM1. If I move Adobe to COM2, then all is well. I suppose since Adobe is not actively using the port, that is why I don't get "access denied."
I have no idea why Adobe PDF needs a serial port at all.
THanks for the views/votes.

A: I disabled comport and then enabled again!!
And then renamed it to for example COM6! some COM6. Some of steps is  :
Control Panel=>Device Manager=>Serial Ports(COM ... =>Advanced setting =>
Change port name from combo-box,
And delete nitro-PDF in my printers device


text: Q: Why does function being linear imply it can be represented as matrix multiplication? In the video where 3blue1brown explains determinants, this point in question is brought up at 6:35  but what is the intuition/ justification for this statement?


text:
Q: How to use WaitForSingleObject() I read different topics concerning the use of WaitForSingleObject() but I still don't understand why I cannot make it work.
I have a progress bar which updates using AfxBeginThread and I would like to wait to finish its work before doing another proccess. My code is based on this example: http://www.codeproject.com/Articles/2459/Using-AfxBeginThread-with-class-member-controlling
startupEvent = ::CreateEvent(NULL, FALSE, FALSE, NULL);
THREADSTRUCT *_param = new THREADSTRUCT;
_param->_this = this;
CWinThread* thread = AfxBeginThread (StartThread, _param);
WaitForSingleObject(startupEvent , INFINITE);
AfxMessageBox(_T("This message should pop up after the thread terminates."));

I have defined the startupEvent variable in the header file like this:
protected:
   HANDLE startupEvent;

Here is the thread method.
UINT CView::StartThread (LPVOID param)
{
   THREADSTRUCT* ts = (THREADSTRUCT*)param;
   ::SetEvent(ts->_this->startupEvent);
   //Some heavy calculation from here + ProgressBar update
   return 1;
}

In the above example, I would like the MessageBox to appear after the thread terminate the proccess but it currently appears before.

A: Short answer to your question: you need to call ::SetEvent(ts->_this->startupEvent);, after the heavy calculation, otherwise WaitForSingleObject will return before the heavy calculation starts.
Side note: you can use WaitForSingleObject directly on the thread handle, so you don't need an additional event. Like: WaitForSingleObject(thread->m_hThread, INFINITE);
Bad practices
Your solution contains 2 bad practices:

*

*It's a bad idea to block your main-thread, because it runs the main message loop, which in turn is responsible for redrawing GUI elements (like updating the progressbar in your case). Letting the main-thread wait for a worker thread to finish defeats the reason for offloading the heavy calculation to a secondary thread.

*Don't touch the GUI from a worker thread. The worker thread can use SendMessage or PostMessage to send status messages to the main thread, which in turn will update the UI. I found an old but still relevant article about this matter.


text:
Q: JS - How to get the correct val of a map? On load I create a map, the key is an anker-element and the value the offset of that anker. Unfortunately I cannot read out the val correctly, it always returns the value of the last key. What is wrong?
js fiddle
HTML
AnkerAnkerAnker

JS
var ankers = {};
$('a').each(function(){

var pos = $(this).offset().left;

ankers[$(this)] = pos;
});

$('a').click( function(e) {
    e.preventDefault();
    alert(ankers[$(this)]);
});

A: JavaScript objects, which you're using for a map here only support string keys (like objects in most other languages).
If you want an actual map should use a Map object instead if you'd like to use an object key - but those only work in new browsers, you can (polyfill it though):
var ankers = new Map();
$('a').each(function(){

    var pos = $(this).offset().left;

    ankers.set($(this), pos);
});

$('a').click( function(e) {
    e.preventDefault();
    alert(ankers.get($(this));
});

Fiddle (based on dfsq's)
Alternatively, you can use the element's ID as a key and give them IDs. Or, you can avoid this altogether and save the data on the objects rather than in a map:
$('a').each(function(){
    $(this).data("anker", $(this).offset().left);
});

$('a').click( function(e) {
    e.preventDefault();
    alert($(this).data("anker");
});

Fiddle
You should only use data attributes for presentation properties and binding, but this seems to be appropriate and is the case here.

A: The property of the object in javascript is always a String. So when you try to set a map with an object as a key, this object is converted to string type. As the result you have only ankers object has only one key [object Object].
Instead consider to give an ids to anchors and use something like this:
var ankers = {};
$('a').each(function () {
    var pos = $(this).offset().left;
    ankers[this.id] = pos;
});

$('a').click(function (e) {
    e.preventDefault();
    $('.val').val(ankers[this.id]);
});

Demo: http://jsfiddle.net/1c4h17ma/1/


text:
Q: AWS SSO integration with G suite I want to make use of AWS SSO and integrate it to work with G suite.
I followed the official blog post - https://aws.amazon.com/blogs/security/how-to-use-g-suite-as-external-identity-provider-aws-sso/
However, I'm unable to perform the user synchronization from G suite into AWS SSO via the mentioned ssosync project - https://github.com/awslabs/ssosync. There's an open issue regarding the fact that ssosync is no longer available in AWS Serverless Application Repository. I've tried to clone and build the project manually but I get a 404 error and I can't find a reason why.
I am also unable to find a way to create users/groups programmatically (didn't find anything useful in AWS SSO API reference) in AWS SSO.
Has anyone encountered this problem as well?

A: I think that does not work anymore. What about using this one instead?

A: https://github.com/awslabs/ssosync was updated to V.2.0.0 few days ago (Dec 2022).
I installed it from AWS Serverless Application Repository and it seems to work.
It requires that you configure every possible variable before successful execution. For variables that you don't wish to use, put *.


text:
Q: How to monitor which processes access a particular file in Unix? I have a file and a lot of process (and process threads) are accessing it.
I want to monitor the file to get a listing of what all processes tried to access the file. Being able to record the timestamps also would be excellent for logging purposes, though I can do without it.

*

*Is there any Unix utility that does something similar?

*In case no such utility exists, how should I program this using a script (shell, Perl) or a program (C, C++)?

A: Under Linux, inotify might be what you're looking for.

A: I think the basic functionality you're looking for is in the UNIX command fuser.
This will tell you what processes are using a file (or port if you like).

A: FAM - File Alteration Monitor http://oss.sgi.com/projects/fam/
or
Gamin http://people.gnome.org/~veillard/gamin/
might help you (gamin seems maintained while I cannot say the same for FAM).
You can attach your app to FAM/Gamin and then you'll be notified if something happened with the watched files.
For details I suggest: http://techpubs.sgi.com/library/tpl/cgi-bin/getdoc.cgi?coll=0650&db=bks&fname=/SGI_Developer/books/IIDsktp_IG/sgi_html/ch08.html

A: You might want to look at lsof.


text:
Q: jQuery CuteTime Plugin and Ajax Data - False conversion in IE + Safari? I have a site with a liveticker which loads new forum events and adds them to an HTML table.
For the time field I am ajax-loading the datetime of each event (e.g. 2013-02-15 17:28:03), and converting them via jquery plugin cutetime to human readable format, e.g. 22 minutes ago.
Problem with CuteTime is that the recent version (from 2010) has some issues in dealing with dynamically loaded AJAX data.
My current solution seems to work a bit:
1.At first the ajax call loads the entire forum events as html table, then I assign the cutetime plugin:
// initial load at page startup
$('#responsecontainer').load('./liveticker', {ajax:1}, function() {
    // convert datetime to readable date format
    $('.timestamp').cuteTime();
});

2.Then I check every 30 seconds for new events, and assign cuteTime each time on the loaded data:
$('#responseEvents').load('./liveticker', {ajax:lastevent}, function() {
    // stuff...
    // convert datetime to readable date format
    $('.timestamp').cuteTime();
})

This seems to work in Firefox and Chrome. However, in Internet Explorer 9 all $(.timestamp) elements get the same text assigned: just now.
Does anyone know a solution to this bug / problem?
--
Note: On the cutetime-site I found a comment about ajax. Somebody there stated his workaround:

I had to hack my app to make additional fields so i first copy all
  the values into all my spans, then call cuteTime.

But I am not sure if this is in any way connected to the Internet Explorer Bug I am facing now...

A: It was not the AJAX call. Indeed, I used the normal datetime format (from mysql) and tried to convert that format with cutetime.
Reading the site of the developer, I stumbled over this sentence:

timestamp MUST be a valid Date().parse 'able' format

as well as:

If neither cutetime attribute nor valid object text exist, then the timestamp is assumed to be 'now'.

Bingo! Now I am formattting the datetime to ISO8601 date format server site with:
$timeCode = date("c", strtotime( $row['datetime'] ));
and I get dates in this format: 2013-02-17T15:26:21+01:00 which work for js-conversion in all browsers!


text:
Q: fail unit tests if coverage is below certain percentage I make a makefile that executes go test -cover. Is it possible to fail the make unit_tests command if coverage is below X? How would I do that?

A: You can use TestMain in your test to do that. TestMain can act as a custom entry point to tests, and then you can invoke testing.Coverage() to get access to the coverage stats.
So for example, if you want to fail at anything below 80%, you could add this to one of your package's test files:
func TestMain(m *testing.M) {
    // call flag.Parse() here if TestMain uses flags
    rc := m.Run()

    // rc 0 means we've passed,
    // and CoverMode will be non empty if run with -cover
    if rc == 0 && testing.CoverMode() != "" {
        c := testing.Coverage()
        if c < 0.8 {
            fmt.Println("Tests passed but coverage failed at", c)
            rc = -1
        }
    }
    os.Exit(rc)
}

Then go test -cover will call this entry point and you'll fail:
PASS
coverage: 63.0% of statements
Tests passed but coverage failed at 0.5862068965517241
exit status 255
FAIL    github.com/xxxx/xxx 0.026s

Notice that the number that testing.Coverage() returns is lower than what the test reports. I've looked at the code and the function calculates its coverage differently than the test's internal reporting. I'm not sure which is more "correct".


text:
Q: DeleteObject does not exist in Context i am using vs 2012 and dot net 4, i have a model folder that contains my model in my page " Default.aspx " i used
> using MyProjectName.Model;

but when i am trying to delete some data it says " DeleteObject " Method does not exist!
using (var context = new Entities())
                    {
                        (from ur in context.Module_Users_Info where ur.UserID == comarg select ur).ToList().ForEach(context.DeleteObject);

                    }

A: The issue is DbContext doesn't have a DeleteObject method, only ObjectContext does, you can get the underlying object context by casting e.g.
((IObjectContextAdapter)context).ObjectContext.DeleteObject

A: With DbContext you can use DbSet<T>.Remove instead of ObjectContext.DeleteObject which has the same purpose to delete entities from the database:
using (var context = new Entities())
{
    (from ur in context.Module_Users_Info
     where ur.UserID == comarg
     select ur)
    .ToList()
    .ForEach(ur => context.Module_Users_Info.Remove(ur));
}