Node.js Kill app because of memory usage

Question: I have simple app
its a for loop going through a request rest api and then go to another for loop and request.
something like this :
var request = require('request');

for(var j=1;j<=10;j++){

            request({
              method: 'GET',
              url: 'https://api.domain.com/items/?page='+j+'&limit=1000',
              headers: {
                'Content-Type': 'application/json'
              }}, function (error, response, body) {

              var data = JSON.parse(body)

              for(var i=0;i<data.length;i++){

                    request({
                      method: 'GET',
                      url: 'https://api.domain.com/itemDetail/'+data[i].id,
                      headers: {
                        'Content-Type': 'application/json',
                      }}, function (error, response, body) {

                        var itemDetails = JSON.parse(body);

                        // save items to mongodb

                        }

              }
    });

}

i have more than 200,000 data to save , when i loop through 10 page (set first loop limit to 10) its ok but when i increase the page number in first loop node memory usage going high and kill app.
i wants know the reason this happen and how solve this.
thanks in advance
Comment: You will want to control how many requests are "in-flight" at the same time from both loops.  Both the Async library and the Bluebird promise library have functions specifically for doing this.
Comment: @jfriend00 thanks, can you give me an example?
Comment: Do you understand the concept I'm talking about?  If so, what specific question do you have about implementing it?  In the Async library, you would use the `.eachLimit()` method.  In the Bluebird library, you could use the `.map()` method with the concurrency option or you can code it yourself with a counter.
Answer: If you are going to trigger 200'000 item to save, iterating through a loop means you will ask your javascript application to keep waiting for thousands of callbacks to return and finish. This is not going to work, remember that javascript (and thus nodejs) are single-threaded.
You should implement this routine with a library like async or q, which give you control over the iteration cycle to keep it within acceptable memory limits.
Comment: could you give me an example for `async` in my situation i should use `series` ?
Comment: Can't give an example right now, I'm on the go. But the best you can do is read the async documentation itself, it's really good and will teach you tons about how to properly use this module. If I were you, I'd look at eachLimit instead of series. Series will execute the commands sequentially, which is probably not what you want. You want some parallelism without crashing the system


How to get MethodInfo of static method with generic parameters when method ambiguity occurs?

Question: The method I would like to obtain is Observable.Return from System.Reactive.
It's defined like this:
public static IObservable<TResult> Return<TResult>(TResult value)
{
    ...
}

I've tried with
Type observableType = typeof(Observable);
MethodInfo returnMethodInfo = observableType.GetMethod("Return");
var genericMethodInfo = returnMethodInfo.MakeGenericMethod(typeof(int));

The problem is that I'm getting an error message:

Ambiguous match found.

I guess it's because there is another method called "Return":
public static IObservable<TResult> Return<TResult>(TResult value, IScheduler scheduler)
{
   ...
}

How should I call GetMethod to get a MethodInfo to the method I want?
Answer: You could try it with this solution.
    var method = typeof(Observable).GetMethods().FirstOrDefault(
            x => x.Name.Equals("Return", StringComparison.OrdinalIgnoreCase) &&
                x.IsGenericMethod && x.GetParameters().Length == 1)
        ?.MakeGenericMethod(typeof(int));

Answer: You'll need to use GetMethods() and filter to the one you want; this could be as simple as:
var returnMethodInfo = observableType.GetMethods().Single(x => x.Name == "Return"
    && x.IsGenericMethodDefinition && x.GetParameters().Length == 1);


Why might my ceiling light be flickering?

Question: I have two lights in my bedroom on the same circuit with a single switch. One of them (always the same one) will sometimes flicker to the point that it's strobing. It doesn't do it all of the time, and there doesn't seem to be a correlation between it doing it and how log it's been switched on (sometimes it does it straight away, sometimes it can be on for ages and not do it). I am assuming there's no issue with the supply or fuses or I'd be seeing it on both light fittings.
I've tried a different bulb. The bedroom is in an extension that is about 5 years old so the wiring should be fairly up to code and in good condition. I can't access the wiring above it as the attic is boarded and insulated, but nothing should be disturbing it if, for example, there was a loose connection.
There is nothing obviously (to me) wrong with the wiring.
Switch wiring:

Good light wiring:

Problem light wiring:
Comment: That's not by chance a dimmer switch, is it?
Comment: I would turn off the breaker and check the connections in both lights just to be sure a loose connection is not the problem.  Changing the bulb should have checked that it was not a bad light bulb.  Type of light bulb can be useful, LEDs seem to have more flickering problems.
Comment: @Huesmann No, not a dimmer.
Comment: @crip659 The one with the problem is an LED bulb, the other one is an older sytle mercury low-energy bulb. How am I checking for loose connections? Just giving things a pull and tightening them up?
Answer: Low quality LED bulbs have an irritating tendency to flicker on occasion and sometimes constantly.
While I know of no scientific study to support this, I can tell you from experience that when faced with a the flickering bulb, I have replaced it with a bulb from one of the better reviewed companies.
(One review post is here.)
A better bulb has historically given me better service.
Comment: Other bulbs from the same batch are all working fine. When I get some time, I'll try to do a more scientific test and swap some around.
Comment: Understand that not every bulb from a batch may flicker.  It is not uncommon for a bulb to be fine then develop a flicker and even have a flicker that goes away ( If one is willing to put up with it long enough.)
Answer: The flicker is very unlikely to be related to any wiring.
LEDs don't do well in fully enclosed lamps because they trap heat and make the bulb's complex electronics run hot. Whereas incandescent bulb's simple metal and glass combo don't care about a 30C increase in operating temp caused by lack of ventilation in the lamp housing.
If you must keep that fixture, find an LED bulb line with the highest lumen-to-watt ratio you can find, and then use the lowest wattage you can stand, both of which are efforts to avoid heat, which is what causes internal driver failure (the most common fail method and synonymous with flickering/strobing) and lower-life LED chips.
Larger watt LED bulbs are usually physically larger and have more surface area to dissipate heat, so long is it's not all trapped by the fixture; like a globe for example. Putting such a lamp fixture behind a dimmer, using a larger-watt bulb, and then running it at 50-75% is a good way to run the bulb cooler, reduce flicker, increase efficiency (albeit slightly), and ensure long lifespan.
Comment: Thanks. The lamp shades are pretty open so I'm not sure it's a heat issue. Will try to post a picture.


In .NET Core EF, why Query run so much faster if .Select() is used than ToListAsync()?

Question: Why retrieving data from database is much much faster if Select() is used than ToListAsync()? I have 5000 dummy entries in a table.
my code:
private IQueryable<TEntity> GetQueryable<TEntity>(
            Expression<Func<TEntity, bool>> filter = null,
            Func<IQueryable<TEntity>, IOrderedQueryable<TEntity>> orderBy = null,
            int? skip = null, int? take = null, bool asNoTracking = false,
            Func<IQueryable<TEntity>, IIncludableQueryable<TEntity, object>> include = null)

            where TEntity : class, IEntity
        {
            IQueryable<TEntity> query = _context.Set<TEntity>();

            if (filter != null)
                query = query.Where(filter);

            if (include != null)
                query = include(query);

            if (orderBy != null)
                query = orderBy(query);

            if (skip.HasValue)
                query = query.Skip(skip.Value);

            if (take.HasValue)
                query = query.Take(take.Value);

            if (asNoTracking)
                query = query.AsNoTracking();

            return query;
        }

when the method is used like this:
public virtual async Task<IEnumerable<TEntity>> GetAllAsync<TEntity>(
            Func<IQueryable<TEntity>, IOrderedQueryable<TEntity>> orderBy = null,
            int? skip = null, int? take = null, bool asNoTracking = false,
            Func<IQueryable<TEntity>, IIncludableQueryable<TEntity, object>> include = null)
            where TEntity : class, IEntity
        {
            return await GetQueryable<TEntity>(null, orderBy, skip, take, asNoTracking, include).ToListAsync();
        }

this takes 30 seconds!
But when this code is used:
public virtual async Task<IQueryable<dynamic>> GetDynamicAsync<TEntity>(
            Func<IQueryable<TEntity>, IOrderedQueryable<TEntity>> orderBy = null,
            int? skip = null, int? take = null, bool asNoTracking = false,
            Func<IQueryable<TEntity>, IIncludableQueryable<TEntity, object>> include = null,
            Expression<Func<TEntity, dynamic>> columns = null)
            where TEntity : class, IEntity
        {
            return GetQueryable<TEntity>(null, orderBy, skip, take, asNoTracking, include).Select(columns);
        }

this takes not even a second! 1 second max I think.
Why is that? Can someone explain? Even if I add all the of my table's column in the "columns" variable still it is so fast to retrieve. So what's the difference between the 2 queries? Also is it okay if await is not being used here? I cant' use await because it says that IQueryable has no GetAwaiter. It concerns me.
Thanks!
edit: added Service code
public async Task<ManyResult<LibrariesForTableDTO>> GetLibrariesForTable(DatatableSearchDTO dto)
        {
            var response = new ManyResult<LibrariesForTableDTO>();
            try
            {
                //var libraries = await _repo.GetDynamicAsync<Library>(columns: x => new { x.Id, x.Name, x.Description });
                var libraries = await _repo.GetAllAsync<Library>();
                response.Entities = _mapper.Map<List<LibrariesForTableDTO>>(libraries);
                response.TotalFilteredEntities = libraries.Count();
                response.TotalEntities = libraries.Count();
                response.Success = true;
            }
            catch (Exception e)
            {
                response.Success = false;
                response.Message = "Error retrieviing the libraries.";
                _logger.LogError("Error calling GetLibrariesForTable: {0} - {1}", e.Message, e.StackTrace);
            }

            return response;
        }

Comment: second returns just plain IQueryable ... obviously it doesn't query database at all
Comment: You're returning different things. Your first method (the one that is slow) returns the data. The second one (the fast one) returns a function that can fetch the data.
If you print the data to the console, you'll find that they both will take approximately the same time to run because then both will need to actually fetch the data.
Comment: i don't get it. i'm retrieving the correct data tho? so is my way of retrieving the data wrong?
Comment: `Select` is returning the shopping list - the steps of what to do. `ToList`(or any enumeration of the `Select`) is **doing the shopping**. Writing a shopping list is fast. Going to the shops and buying stuff is slow.
Comment: I edited my post guys, I added my service code that calls the query methods. The commented "libraries" return list of data. and the mapping of this still just take a second. the second(not commented) "libraries" takes 30 seconds. Can you guys tell me what part here is the "fetching the data"? Because I don't really get it when does it happen. I'm confused right now. Thanks!
Comment: The reason I have selected the duplicate that I did was due to its inclusion of the sentence `Nothing is sent to the server until we try to consume the result in the foreach loop.`. That is the fundamental difference between your code samples.  Your `Select` isn't actually executing the SQL - but the `ToList` is since it consumes (enumerates) the data.
Comment: ok2 now I kinda get it. But a follow up question, is it wrong to do it the "fast" way? because the difference is like half a minute and I think it does have a con(s) maybe? should I use the fast way? i'm using this in jquery datatable btw.
Comment: If it is actually slower (end to end) then it is likely that you are enumerating the `IQueryable` more than once. This is resulting in multiple database queries. In that case, `ToList`ing can be useful to avoid multiple DB hits.
Comment: i almost forgot, thanks for enlightening me!
Answer: Running Select on the IQueryable does not execute the query, that's why it's fast.
When you run something like ToList or FirstOrDefault, it actually needs to enumerate the results, and that's when the query executes.
It essentially just adds a projection to the queryable object so that when the query executes, that projection can be translated to the SQL query etc.
So if you don't execute the query there, you are delaying the query execution for later, when the IQueryable is enumerated.
Comment: How are you looking at it? If you go through it with a loop for example, it will run the query at that time. Any tool that you use to look at the IQueryable data is going to enumerate it and thus cause the query to run.
Comment: But I don't get it sir. If it does not execute the query, why i'm getting the data from database? IQueryable with Select does return my desired data. Why is that?
Comment: I edited my post sir, I added my service code that calls the query methods. The commented "libraries" return list of data. and the mapping of this still just take a second. the second(not commented) "libraries" takes 30 seconds. Can you tell me what part here is the "enumerate" or the real "execution"? Because I don't really get it when does it happen. I'm confused right now. Thanks!
Comment: Linq - deferred execution. Here's an explanation https://medium.com/exam-70-487/deferred-execution-of-linq-query-39a925195b73
Comment: When you call Map on the mapper, that will run the query. Both calls to Count() will also run queries to get a count of results.
Comment: so it does "realized value is actually required" in the line of the mapping? or in javascript because i'm using the data in datatable? but that's not it right because it's in front end now hehe. so is it being used in the mapping? it's where the actual work does?
Comment: ok2 now I kinda get it. But a follow up question, is it wrong to do it the "fast" way? because the difference is like half a minute and I think it does have a con(s) maybe? should I use the fast way? i'm using this in jquery datatable btw.


Swapping Drayton LP722 for smart switch - the wiring

Question: I'm replacing my Drayton LP722 control unit which controls the Hot Water only (heating is UFH and controlled via the zone thermostats) with a Smart switch and I am trying to figure out the wiring.
The Drayton unit is wired in for N, L, 3, 4.
The Smart switch I have, has connectors for: N, L1, L2, C.
I think it should be N -> N, L -> L1, 3 -> C.
The bit that is confusing me in the wiring into 4 on the Drayton unit, according to the documentation that is for central heating, but that's not controlled through this unit...
Not sure where this should be wired into.
Smart switch wiring can be found here: https://shop.meross.com/products/meross-two-way-smart-light-switch-eu-uk
Answer: I chased #4 wire back, turns out it's not connected to anything. It's terminated in #12 in the following picture


Is there any other format battle in Battle Tree?

Question: Unlike the Battle Maison in X/Y that has Triple Battle and Rotation Battle, the Battle Tree only has Single, Double, and Multi Battle in it.
So, where's the other two? Can they be unlocked by some event or something or do they simply not have it?
Comment: Considering the abysmal frame rate even double battles have sometimes, it's likely they were removed so the game wouldn't drop to 5FPS during them
Answer: According to this thread, this source, and personal experience, these are in fact the only modes in the Battle Tree. The only thing that is new to this one is the addition of "nostalgic characters". Basically allowing you to battle against old characters from previous Pokemon games. E.g. Blue and Red, Cynthia, Wally, and more.
Like the other games, battling will earn you points that you can spend to unlock mostly exclusive items that are frequently used in competitive battling and ev training.
Answer: If I remember correctly, the actual game data for Rotation Battles has been removed from the S/M game code. The logic for Triple battles is still there however, but seeing as Nintendo doesn't do DLC for main series Pokemon games (yet), it's unlikely we'll see them return.


Oracle REGEXP_REPLACE help adding dashes to a number string

Question: Can someone help me write an Oracle REGEXP_REPLACE statement to add dashes to a number like this...
5310009618390
5310-00-961-8390

I'm thinking I need regexp_replace but maybe not, maybe just replace witll work. Have tried both and not gotten anywhere.
select replace(t.column, 5310009618390, '-') from table t

Comment: Have you tried SUBSTRING? SELECT SUBSTRING(t.column,0,4) + '-' + SUBSTRING(t.column,4,2) + '-' etc.
Comment: No I had not tried that Malanie. The ultimate goal is to update the database, I'm using a select right now just for testing.
Comment: The first example Oracle provides on regexp_replace is the phone number problem which is very, very close to the solution provided. http://docs.oracle.com/cd/B28359_01/server.111/b28286/functions137.htm#SQLRF06302.
Comment: Thanks Patrick, I did see that page on my search but failed to scroll down far enough to see the examples. Will take a look at it now to see if it helps me understand Gary's solution any better.
Answer: Well first you need to be able to describe what you want to do to understand how to build the expression.  For example, it appears to be: group the 1st 4 numbers, then the next 2 numbers, then the next 3 numbers then the next 4 numbers.  If this is accurate:
select regexp_replace('5310009618390', '(\d{4})(\d{2})(\d{3})(\d{4})', '\1-\2-\3-\4') from dual;

This expression "remembers" the groups as described above, then displays them with the dashes in between.
It's important to be able to describe what you want to do, as that will help you to build the expression.  i.e. If the rule is to group the 1st 4 characters (instead of numbers) then the expression would be different, etc.
Note this example is for REGEXP_REPLACE which can be expensive depending on the size of the dataset you will be operating on.  If the rules are simple, it may be faster to just chop it up using SUBSTR() and concatenate the pieces, adding the dashes as Melanie suggests (only use || for concatenation not +).
Comment: That worked perfect Gary, thank you very much. Sorry I didn't make it as clear as it should have been, but you nailed. I appreciate it.
Comment: Glad to help, just be sure you have considered all forms that the number could be in in the data as the expression depends on that.  Is it the entire string? embedded in a string? Always the same length? Could multiple numbers appear in the string? etc.
Comment: Yea, the string of numbers will always be the same length. It was really just a one time thing so fixed the problem and can now move on. Thanks again.


SwiftUI with SceneKit: How to use button action from view to manipulate underlying scene

Question: I'm trying to implement a very basic SwiftUI app with an underlying SceneKit scene/view. The buttons in the SwiftUI view should manipulate the content of the scene and vice versa the content of the scene should determine if the buttons are active or inactive.
Yes, I've read and watched the Apple developer sessions 226: Data Flow through SwiftUI and 231: Integrating SwiftUI. And I worked my way through the Apple tutorials. But I'm little lost here. Any hints and directions are appreciated.
Here is the code:
I have a MainView, which uses a SceneKit SCNView with a HUDView on top:
import SwiftUI

struct MainView: View {
    var body: some View {
        ZStack {
            SceneView()

            HUDView()
        }
    }
}

The SceneView integrates a SCNView via the UIViewRepresentable protocol. The scene has two functions to add and remove the box from the scene:
import SwiftUI
import SceneKit

struct SceneView: UIViewRepresentable {
    let scene = SCNScene()

    func makeUIView(context: Context) -> SCNView {

        // create a box
        scene.rootNode.addChildNode(createBox())

        // code for creating the camera and setting up lights is omitted for simplicity
        // …

        // retrieve the SCNView
        let scnView = SCNView()
    scnView.scene = scene
        return scnView
    }

    func updateUIView(_ scnView: SCNView, context: Context) {
        scnView.scene = scene

        // allows the user to manipulate the camera
        scnView.allowsCameraControl = true

        // configure the view
        scnView.backgroundColor = UIColor.gray

        // show statistics such as fps and timing information
        scnView.showsStatistics = true
        scnView.debugOptions = .showWireframe
    }

    func createBox() -> SCNNode {
        let boxGeometry = SCNBox(width: 20, height: 24, length: 40, chamferRadius: 0)
        let box = SCNNode(geometry: boxGeometry)
        box.name = "box"
        return box
    }

    func removeBox() {
        // check if box exists and remove it from the scene
        guard let box = scene.rootNode.childNode(withName: "box", recursively: true) else { return }
        box.removeFromParentNode()
    }

    func addBox() {
        // check if box is already present, no need to add one
        if scene.rootNode.childNode(withName: "box", recursively: true) != nil {
            return
        }
        scene.rootNode.addChildNode(createBox())
    }
}

The HUDView bundles the buttons with actions to add and remove the box from the underlying scene. If the box object is in the scene, the add button should be inactive, only the remove button should be active:
struct HUDView: View {
    var body: some View {
        VStack(alignment: .leading) {
            HStack(alignment: .center, spacing: 2) {
                Spacer()

                ButtonView(action: {}, icon: "plus.square.fill", isActive: false)
                ButtonView(action: {}, icon: "minus.square.fill")
                ButtonView(action: {}) // just a dummy button
            }
            .background(Color.white.opacity(0.2))

            Spacer()
        }
    }
}

The buttons are fairly simple as well, they take an action and optionally an icon as well as their initial active/inactive state:
struct ButtonView: View {
    let action: () -> Void
    var icon: String = "square"
    @State var isActive: Bool = true

    var body: some View {
        Button(action: action) {
            Image(systemName: icon)
                .font(.title)
                .accentColor(isActive ? Color.white : Color.white.opacity(0.5))
        }
        .frame(width: 44, height: 44)
    }
}

The resulting app is pretty simple:

The SceneKit scene is rendered correctly and I am able to manipulate the camera on screen.
But how do I connect the button actions to the corresponding scene functions? How do I let the scene inform the HUDView about it's content (box is present or not), so it can set the active/inactive state of the buttons?
What is the best approach to this task? Should I implement a Coordinator in SceneView? Should I use a separate SceneViewController implemented via the UIViewControllerRepresentable protocol?
Answer: I found a solution using @EnvironmentalObject but I am not completely sure, if this is the right approach. So comments on this are appreciated.
First, I moved the SCNScene into it's own class and made it an OberservableObject:
class Scene: ObservableObject {
    @Published var scene: SCNScene

    init(_ scene: SCNScene = SCNScene()) {
        self.scene = scene
        self.scene = setup(scene: self.scene)
    }

    // code omitted which deals with setting the scene up and adding/removing the box

    // method used to determine if the box node is present in the scene -> used later on
    func boxIsPresent() -> Bool {
        return scene.rootNode.childNode(withName: "box", recursively: true) != nil
    }
}

I inject this Scene into the app as an .environmentalObject(), so it is available to all views:
class SceneDelegate: UIResponder, UIWindowSceneDelegate {

    func scene(_ scene: UIScene, willConnectTo session: UISceneSession, options connectionOptions: UIScene.ConnectionOptions) {

        // Create the SwiftUI view that provides the window contents.
        let sceneKit = Scene()
        let mainView = MainView().environmentObject(sceneKit)

        // Use a UIHostingController as window root view controller.
        if let windowScene = scene as? UIWindowScene {
            let window = UIWindow(windowScene: windowScene)
            window.rootViewController = UIHostingController(rootView: mainView)
            self.window = window
            window.makeKeyAndVisible()
        }
    }
}

MainView is slightly altered to call SceneView (a UIViewRepresentable) with the separate Scene for the environment:
struct MainView: View {
    @EnvironmentObject var scene: Scene

    var body: some View {
        ZStack {
            SceneView(scene: self.scene.scene)
            HUDView()
        }
    }
}

Then I make the Scene available to the HUDView as an @EnvironmentalObject, so I can reference the scene and its methods and call them from the Button action. Another effect is, I can query the Scene helper method to determine, if a Button should be active or not:
struct HUDView: View {
    @EnvironmentObject var scene: Scene
    @State private var canAddBox: Bool = false
    @State private var canRemoveBox: Bool = true

    var body: some View {
        VStack {
            HStack(alignment: .center, spacing: 0) {
                Spacer ()

                ButtonView(
                    action: {
                        self.scene.addBox()
                        if self.scene.boxIsPresent() {
                            self.canAddBox = false
                            self.canRemoveBox = true
                        }
                    },
                    icon: "plus.square.fill",
                    isActive: $canAddBox
                )

                ButtonView(
                    action: {
                        self.scene.removeBox()
                        if !self.scene.boxIsPresent() {
                            self.canRemoveBox = false
                            self.canAddBox = true
                        }
                    },
                    icon: "minus.square.fill",
                    isActive: $canRemoveBox
                )

            }
            .background(Color.white.opacity(0.2))

            Spacer()
        }
    }
}

Here is the ButtonView code, which used a @Bindingto set its active state (not sure about the correct order for this with the@State property inHUDView`):
struct ButtonView: View {
    let action: () -> Void
    var icon: String = "square"
    @Binding var isActive: Bool

    var body: some View {
        Button(action: action) {
            Image(systemName: icon)
                .font(.title)
                .accentColor(self.isActive ? Color.white : Color.white.opacity(0.5))
        }
        .frame(width: 44, height: 44)
        .disabled(self.isActive ? false: true)

    }
}

Anyway, the code works now. Any thoughts on this?
Answer: I answered a very similar question here. The idea is that you create a PassthroughSubject that your parent view (the one that owns the buttons) will send events down and your UIViewRespresentable will subscribe to those events.
Comment: Thank you for this hint, but I tried `@EnvironmentalObject` to have a 2-way relation from the scene back to the HUD. See my separate answer.
Answer: There are many ways to do this stuff and you've obviously solved it - congrats!
You might check out this post 58103566 on game design layout.  I'm sure there will be experts that disagree which is fine, and I don't want to cause a debate, just thought it might save you a few steps in the future.
From multiple VC's, I manipulate game objects and buttons often, usually without muddying up the water too much.
Hope it helps.
Comment: Thanks, will consider this. For the start just a single scene app. Do you recommend any books/articles/blogs specially for SceneKit? By the way, I added the direct link to your post id.
Comment: Thanks, this guy is pretty good: https://www.raywenderlich.com  - the rest I get from StackO.


Probability of equilateral and right triangle built in a cube

Question: Having a standard cube:

Show that the triangle created by any three vertices can only be equilateral or right.
Calculate the probability that $3$ vertices forms a right triangle.
Excluding $3$ vertices and considering only the other $5$, calculate the probability $P$ that $3$ of the $5$ vertices form a right triangle. Say how many values $P$ can assume.

For the first point I don't understand how can I mathematically show it.
For the second point I've built manually the triangle on every face:
$$ \frac{6\cdot 4\cdot 2}{\binom{8}{3}} = \frac{6}{7}$$ but it's a try and I don't think it's right.
Being unsure on the second point, the third seems confusing to me.
Thanks to those who'll answer.
Answer: For the third one, label the eight corners alternately black and white.
Any three black corners, or any three white corners, form an equilateral triangle.
Given five points, there are ${5\choose3}=10$ triangles.  How many of them are equilateral?  (It depends on the five points.)
Answer: Realize the vertices of the cube by $C:=\{0,1\}\times\{0,1\}\times\{0,1\}$. Let $T$ be a set of $3$ vertices in $C$. If there are two distinct vertices $v_1, v_2$ in $T$ with that $v_1, v_2$ differ only on one coordinate, then $T$ must be a right triangle, otherwise, $T$ must be an equilateral triangle.
For the second question, each equilateral triangle can be corresponded to a vertex which differs on exactly one coordinate with each vertex of the triangle, for instance, $\{(1,0,0),(0,1,0),(0,0,1)\}\leftrightarrow(0,0,0)$. Hence, the answer is $\frac{\binom{8}{3}-8}{\binom{8}{3}}$.
The third question question is not clear to me as which three vertices are deleted, or they being deleted by random choice?
Comment: They're randomly deleted
Comment: Ok, if they are randomly deleted, how randomly? Just uniformly choose one such configuration from $\binom{8}{5}$? Or we flip a coin for each vertex, and accept those results each of which has 5 vertices chosen?
Comment: The vertex have each one the same probability of the others to be deleted,so i think $\binom{8}{5}$ is what is needed to choose the 5 vertex...


Facebook oauth dialog not calling the callback function

Question: It appears that the FB.ui method='oauth' has stopped calling our callback function on a production site. Here is our code:
<code>FB.ui(
        {
            method: 'oauth',
            client_id: '[outClienID]',
            redirect_uri: '[validRedirect_uri]',
            scope:'email, publish_stream',
            response_type: 'token',
            display: 'popup'
        },
        function(response) {
            FB.getLoginStatus(checkFBConnect, true);
        })
</code>
I have tried replacing the FB.getLoginStatus with a simple alert and it is never called. When I call FB.getLoginStatus(checkFBConnect, true); manually from a debugging console, the process all works as intended. It's like our function(response) is never called by facebook.
Answer: Leaving *redirect_uri* and *response_type* parameter out solves this in canvas/pages applications:
<code>        FB.ui({method: 'oauth',
        client_id: fb_app_id,
        state: new Date().getTime().toString(),
        /*
        redirect_uri: location.protocol + '//' + location.host + '/' + app_folder + '/oauth',
        response_type: 'token',
        */
        scope: 'email,publish_actions'
    }, callback);
</code>
On the other hand, if your application isn't meant to run in a canvas/page, then it is true that your callback function won't be called anymore, but you can handle the oauth token directly in your *redirect_uri* callback page.


pandas data frame find all rows with particular column value?

Question: I have a dataset with column
 1445544152817 SEND_MSG  123
 1445544152817 SEND_MSG  123
 1445544152829 SEND_MSG  135
 1445544152829 SEND_MSG  135
 1445544152830 SEND_MSG  135
 1445544152830 GET_QUEUE 12
 1445544152830 SEND_MSG  136
 1445544152830 SEND_MSG  136
 1445544152892 GET_LATEST_MSG_DELETE  26

I name the columns : timestamp type and response_time
 I do:
df = read_csv(output_path,names=header_row, sep=' ')

and its fine when I output the df it gives me all the values of the file.
Problem? When I do
df = df[df['type'] == 'SEND_MSG']

the df has 0 rows! How come? Its not true because the file and df have rows with type = SEND_MSG
here is my program :
warm_up = 100
cool_down = 100

def refine(df):
    start_time = np.min(df['timestamp'])
    #print start_time.columns[0]
    end_time = np.max(df['timestamp'])
    #print end_time.columns[0]
    new_start_time = start_time + (10 * 1000)
    #new_end_time = 0
    df = df[df['timestamp'] > new_start_time]
    #df = df[df['timestamp'] < new_end_time]
    return df

def ci(data):
    n, min_max, mean, var, skew, kurt = scipy.stats.describe(data)
    std = math.sqrt(var)
    error_margin = 1.96 * (std / np.sqrt(n))
    l, h = mean - error_margin, mean + error_margin
    return (l, h)

MSG_TYPE = {
    'SEND_MSG', 'GET_QUEUE', 'GET_LATEST_MSG_DELETE'
}
COLORS = ['r','g','b']

def main():
    output_path = "/Users/ramapriyasridharan/Documents/SystemsLabExperiements/merged.txt"

    xlabel = "Time in minutes"
    ylabel = "Response time in ms"
    header_row = ['timestamp','type','response_time']
    df = read_csv(output_path,names=header_row, sep=' ')
    #df = refine(df)
    min_timestamp = np.min(df['timestamp'])

    df['timestamp'] = df['timestamp'] - min_timestamp
    # convert time to minutes
    df['timestamp'] = np.round(df['timestamp'] / 60000)
    # filter all outlier above 70 seconds reponse times
    #df = df[df['response_time'] < 70 ]
    df['type'] = df['type']
    i = 0
    print df['type']
    for msg in MSG_TYPE:
        print msg
        df = df[df['type'] == msg]
        print len(df)
        response_mean = np.mean(df['response_time'])
        response_median = np.median(df['response_time'])
        response_std = np.std(df['response_time'])
        l,h = ci(df['response_time'])
        max_resp = np.max(df['response_time'])
        print "For msg_type = %s maximum response time %s"%(msg,max_resp)
        print "For msg_type = %s Response time avg = %.3f +- %.3f std = %.3f and Median = %.3f "%(msg,np.round(response_mean,3),np.round(h-response_mean,3),np.round(response_median,3),np.round(response_std,3))
        # round to nearest minute
        #find number of timestamps greater than 100
        #print df[df['response_time'] > 70]
        grp_by_timestamp_df = df.groupby('timestamp')
        mean_resp_per_min = grp_by_timestamp_df['response_time'].mean()
        #print mean_resp_per_min[0:36]
        plt.plot(mean_resp_per_min, 'x-', color=COLORS[i], label='%s requests'%msg, lw=0.5)
        i += 1

    response_mean = np.mean(df['response_time'])
    response_median = np.median(df['response_time'])
    response_std = np.std(df['response_time'])
    l,h = ci(df['response_time'])
    max_resp = np.max(df['response_time'])
    print "For msg_type = %s maximum response time %s"%('ALL',max_resp)
    print "For msg_type = %s Response time avg = %.3f +- %.3f std = %.3f and Median = %.3f "%('ALL',np.round(response_mean,3),np.round(h-response_mean,3),np.round(response_median,3),np.round(response_std,3))
    # round to nearest minute
    #find number of timestamps greater than 100
    #print df[df['response_time'] > 70]
    grp_by_timestamp_df = df.groupby('timestamp')
    mean_resp_per_min = grp_by_timestamp_df['response_time'].mean()
    #print mean_resp_per_min[0:36]

    plt.plot(mean_resp_per_min, 'x-', color='k', label='ALL requests', lw=0.5)
    plt.xlim(xmin=0.0,xmax=30)
    plt.ylim(ymin=0.0,ymax=20)
    plt.xlabel(xlabel)
    plt.ylabel(ylabel)
    plt.legend(loc="best", fancybox=True, framealpha=0.5)
    plt.grid()
    plt.show()

    #print df['response_time']

EDIT: I found the problem,but have no solution
My actual data looks like what I pasted before ,but when I put it in a dataframe it looks like this, with spaces before the type
22059    GET_LATEST_MSG_DELETE
22060    GET_LATEST_MSG_DELETE
22061    GET_LATEST_MSG_DELETE
22062    GET_LATEST_MSG_DELETE
22063                GET_QUEUE
22064                GET_QUEUE
22065                GET_QUEUE
22066                GET_QUEUE
22067                GET_QUEUE
22068                GET_QUEUE
22069                GET_QUEUE
22070                GET_QUEUE
22071                GET_QUEUE
22072    GET_LATEST_MSG_DELETE
22073    GET_LATEST_MSG_DELETE
22074    GET_LATEST_MSG_DELETE
22075    GET_LATEST_MSG_DELETE
22076    GET_LATEST_MSG_DELETE
22077    GET_LATEST_MSG_DELETE
22078    GET_LATEST_MSG_DELETE
22079    GET_LATEST_MSG_DELETE
22080    GET_LATEST_MSG_DELETE
22081    GET_LATEST_MSG_DELETE
22082    GET_LATEST_MSG_DELETE

There is a leading space in front of get_queue, how do I solve that,this space is not present in my actual data
EDIT: The problem is the fact that type has varible size elements in it, how can I fix it?
Comment: Can you check for trailing and leading spaces in 'type' column values?
Comment: Sorry in your first text block are you saying that your column has all that information: `1445544152817 SEND_MSG  123` this is not 3 columns? If so then it should be obvious why `df = df[df['type'] == 'SEND_MSG']` doesn't work, are you looking for `df = df[df['type'].str.contains('SEND_MSG')]`?
Comment: @JohnGalt how do I do that? You mean visually?
Comment: @EdChum it says TypeError: unsupported operand type(s) for -: 'str' and 'str', it doesnt work.
Comment: Sorry try `df = df.loc[df['type'].str.contains(['SEND_MSG'])]`
Comment: it says can only use .str accessor with string values, which use np.object_ dtype in pandas
Comment: @JohnGalt I think the df saves the second column with leading space
Answer: Since you are looking for just a single value (SEND_MSG) you can do this:
import pandas as pd

df = pd.read_clipboard()
df.columns = ['timestamp', 'type', 'response_time']
print df.loc[df['type'] == 'SEND_MSG']

Outputs:
       timestamp      type  response_time
0  1445544152817  SEND_MSG            123
1  1445544152829  SEND_MSG            135
2  1445544152829  SEND_MSG            135
3  1445544152830  SEND_MSG            135
5  1445544152830  SEND_MSG            136
6  1445544152830  SEND_MSG            136

The important line is:
df.loc[df['type'] == 'SEND_MSG']

Comment: it tells me that there are 5 columns and giving me an error when i assign headers the way you do, but visually i cna only see 3 columns, the space might not be uniform,is there a way to correct that?
Comment: I copied the dataframe you pasted into your original question, including the leading space before your first column. Prior to assigning the columns, do a `print df` and see what the dataframe looks like. If your `read_csv` is working, don't worry about the `read_clipboard` I have. Instead, adjust the `df = df[df['type'] == 'SEND_MSG']` line to the one I mention above


Reattaching water meter

Question: I'm trying to reinstall the water meter pictured below. It it has plastic male threads on each side, and they connect to the copper piping using a flare fitting (I think that's the right terminology).

I can't get the connections not to leak, even if I really crank down with my pipe wrench.
Possibly relevant is that there are rubber gaskets that appear to go into each fitting, as pictured below. I used the gaskets and it still leaks, but perhaps the gaskets are just shot (they appear worn).

Any ideas on why I can't get the connections to work?
Comment: That type of connection is *not* called a flare. I would call them flat sealing surfaces, or union type sealing surfaces, but I don't know the exact terminology They have to be nearly perfectly aligned and if they are not I think the connection will leak. If you get new seals and the connections still leak, then I'd say alignment is off. Are any of the surfaces scored or otherwise not smooth?
Comment: Also, fittings that have rubber seals _usually_ do not have to be super tight because the rubber does a lot of the sealing work.  In other words, making the fitting too tight will strip the threads and it just shouldn't need that much force.
Comment: One of the washers in the photo looks like it has a significant amount of debris stuck to it (sand or dust?). Have you inspected the mating surfaces of the meter and the pipe, and also both sides of the gaskets, to ensure that each is clean, smooth, and free of nicks or scratches?
Answer: I would first ask why you removed the water meter. they are usually sealed with a type of non removable link that has to be cut to remove so the customer can not move the meter and steal water. Usually, if there is a leak at the meter you should contact the water company and they will fix the problem.. That said, if this water meter is the one supplied by the local water company, you could call them and ask if they could provide you with the correct type gaskets (leather). If they ask why the meter was removed find a credible answer that you think they will accept. I rarely saw rubber type washers used on a water meter.
Comment: It's a foreclosure and the water meter was removed previously (don't know why). But I believe this is also just an internal meter for the homeowner's use, and the municipality has another meter somewhere that they read for billing. Anyway, it sounds like alignment could be the issue, so I'll work from there.
Comment: One thing you want to do is try to get each side started and not tighten either side until they are both started. Wiggle the meter if need be to get the threads started. Once started tighten each side evenly until tight. If it's that far out of alignment and if it is a customer only meter then bypassing it may be a better option than trying to align it.
Answer: I'm not the water meter police and think it is your business why the meter is being replaced. That said, I would replace the rubber washers and do not tighten too much. It's hard to describe because you want to tighten it with a wrench, but not as tight as you can get it. I also agree that alignment is key on this type on joint. If the two pieces aren't perfectly in-line with each other and you have to pull/push one of them to get it in-line, it has a good chance of leaking.

Reattaching water meter


i created a program to find the area of polygons but nothing happens?

Question: I am new to java. i created a program to find the area of polygons.
I wanted it to ask the type of polygon an then find the area. i used if, else if and else statements
but whenever i type the name of the polygon nothing happens.
Here is the script
 import java.util.Scanner ;
  public class Area

   {
      static Scanner sc = new Scanner(System. in );

      public static void main(String[] args) {

          System.out.print("Enter the type of polygon: ");
          String polygon = new String("polygon");
          polygon = sc.next();
          String square = new String("square");
          String rectangle = new String("rectangle;");
          String triangle = new String("triangel");

          polygon = sc.next();
          if (polygon == square) {

              double side;
              System.out.print("Enter the side: ");
              side = sc.nextDouble();
              double area;
              area = side * side;
              System.out.print("The Area is: " + area);
          } else if (polygon == rectangle) {
              double length;
              double breadth;
              System.out.print("Enter the length: ");
              length = sc.nextDouble();
              System.out.print("Enter the breadth: ");
              breadth = sc.nextDouble();
              double area;
              area = length * breadth;
              System.out.print("The Area is : " + area);
          } else if (polygon == triangle) {

              double base;
              double height;
              System.out.print("Enter the base: ");
              base = sc.nextDouble();
              System.out.print("Enter the height: ");
              height = sc.nextDouble();
              Double area;
              area = base * height / 2;
              System.out.print("The Area is: " + area);
          } else {
              System.out.print("ERROR it is not a polygon");
          }

      }
  }

Please help me out
thank you
Answer: Okay, I see a couple of better ways to do things in your code.
You do not need to create a String object just to compare your input to the string. You could just use:
if(polygon="square")
Or even better you could use the switch statement. I think the reason you are running into an issue is because you are using .next() instead of .nextLine(). I would use a switch statement and do the following:
Scanner sc = new Scanner(System. in );
myInput = sc.nextLine() // Get the next line from the keyboard
switch (myInput.toLowerCase()) // Make the inputted text to lower case, do switch
{
    case "square":
        // DO SQUARE LOGIC HERE
        break;

    case "rectangle":
        // DO RECT LOGIC HERE
        break;

    case "triangle":
        // DO TRIANGLE LOGIC HERE
        break;
    default:
        // Did not recognize the type of polygon entered.
}

Answer: it seems you are comparing the variable polygon(which always holds the string "polygon") to the next line.
try this:
import java.util.Scanner;

public class Area

{
static Scanner sc = new Scanner(System.in);

 public static void main (String [] args)
 {

   System.out.println("To find the area of a polygon type,");
   System.out.println("\"1\" for a Square");
   System.out.println("\"2\" for a Rectangle");
   System.out.println("\"3\" for a Triangle");
   System.out.println("Enter the number to select the type of polygon: ");
   int p = sc.nextInt();

    if (p == 1 ) {

     double side ;
     System.out.print("Enter the squaer side: ");
     side =sc.nextDouble() ;
     double area;
     area =side * side;
     System.out.print("The Area is: " + area);}

     else if (p == 2)
      {
      double length;
      double breadth;
      System.out.print("Enter the rectangle length: ");
      length =sc.nextDouble();
      System.out.print("Enter the breadth: ");
      breadth =sc.nextDouble();
      double area;
      area =length * breadth;
      System.out.print("The Area is : " + area); }

      else if (p == 3)
      {

     double base;
     double height;
     System.out.print("Enter the triangle's base: ");
     base =sc.nextDouble();
     System.out.print("Enter the height: ");
     height =sc.nextDouble();
     Double area ;
     area = base * height / 2 ;
     System.out.print("The Area is: " + area) ;   }

    else
     {
     System.out.println("ERROR it is not a polygon");
     System.out.print("Please enter a number: 1, 2 or 3.");
     }

   }
 }

I've tried it a few times and it works fine. hope this looks better for your coding as well as it is "user-friendlier" in my opinion because the programmer would ask a user for numbers instead of strings (which may cause miss-spelling). good luck.


Uninstalling VIVADO from Ubuntu 18.0

Question: I have installed vivado on my Ubuntu 18.0 but i am having difficulties in trying to uninstall it.
I tried the two following tutorials but their methods did not work for me.
https://forums.xilinx.com/t5/7-Series-FPGAs/Uninstalling-Vivado-2016-1-ubuntu-16-04-1/td-p/748481
Uninstalling program
Firstly i do no not have the directory that is mentioned at the second tutorial `
/opt/folder you have installed Xilinx/.xinstall/bin/lin`

There is no /bin file ate the up-mentioned directory. What i have are the following files:
/.xinstall/DocNav
/.xinstall/Vivado_2018.2
/.xinstall/xic

So any help on how to uninstall it?
Answer: go to [install dir]/.xinstall/Vivado_2018.2/bin and run terminal from there and put the ff command:
"sudo ./xsetup -Uninstall"
Answer: First go to your Xilinx instalation folder, then look for xsetup binaries:
<Xilinx_installation_folder>$ find . -name xsetup

Outputs would correspond to all installed Xilinx application and their xsetup binaries.
For the Xilinx application you want to Uninstall, go to the folder where xsetup is located for that application and run:
<Xilinx_program_you_want_to_delete_folder>$ sudo ./xsetup -Uninstall

Answer: I had Vivado 2020.2 installed at /opt/Xilinx/.xinstall/Vivado_2020.2. There I found the xsetup binaries.
Run the command sudo ./xsetup -Uninstall
OS - Pop OS 20.04 LTS

Uninstalling VIVADO from Ubuntu 18.0


How should I connect this meter to my power inverter?

Question: Is there anyone here knows how to install this on an inverter? I haven't been able to locate an instruction manual.

Top Picture grabbed from the internet
.

Actual picture of unit I have
Comment: The wiring diagram in the top picture is different from the wiring diagram in the bottom picture. I assume the bottom one is your actual unit, and the top is just some random web picture? Is that correct? It looks like you have a manual there with installation instructions.
Comment: Watch this video to see if it helps. Basically, the voltage connection to the meter is for voltage sensing only. The current transformer measures current on the single wire passing through the hole. Watch this video.
https://help.ekmmetering.com/support/solutions/articles/6000124129-how-to-install-an-omnimeter-video-
Comment: There's a wiring diagram on the right side.  What else do you need to know?
Comment: I can't understand the wiring diagram. All I know is I need to connect it in between of Grid and Solar Inverter
Comment: this page has a link for contacting the manufacturer .... http://www.chintmeter.com/industrial-instruments-panel-meter/din-rail-energy-meter/din-rail-kwh-meter-single-phase.html
Comment: Where are you on this planet?
Comment: There seem to be several versions of very similar products which wire up in slightly different ways. Some seem to have integrated current transformers, and some seem to use external current transformers.
Comment: @mkeith you are right. The top picture is from web and the bottom is actual unit. The manual shown on the bottom picture is the manual for my inverter not the manual for meter. I have manual for meter but it only shows the same diagram as what is printed on the actual unit. That's all, no elaboration on how to connect it between inverter and grid
Answer: You need to follow the labeling and instructions which were part of the equipment's UL, TUV, ETF etc. listing... nope, could not keep a straight face.
Seriously, the labeling and instructions that is actually on your equipment.  If that's the lower picture, then the current transformer goes on 5 and 6, line to 1 and 2, and neutral to 3 and 4.
Do not daisy chain, that is don't bring "line in" into 1, and "line out" into 2, unless your diagram tells you to (such as in your first picture). In the lower pictured unit, you need to put pigtail wires on line 1 and 2, and use an appropriate 4-wire splicing device to join those pigtails to line in and line out (4 wires in total). Likewise lines 3 and 4.  Note the instruction may be different for line vs neutral.  That's for a reason.


How to get Netextender (VPN) working in Ubuntu 12.10 x64?

Question: At work we have to use Sonicwall Netextender to connect over VPN. The NetExtender client works fine on Windows x64 for me, but when using the same settings in my Ubuntu , the connection seems to work fine at first - But after just some packages have been sent, it slows down to almost 0 or 0 ( the connection is still up and seems fine)
Some other people at work have the same NetExtender problem with their Ubuntusetups, so we belive it's some failure with the NetExtenderclient - or that some workaround is needed with it.
So the Question is: Has anyone had success in using NetExtender on Ubuntu 12.x, and what specific settings did you use?
Also - are there any Open Source alternative NetExtender clients we could use instead of the SonicWalls one?
BTW (I tried stuff like this http://www.webantix.net/2012/02/sonicwall-netextender-on-ubuntu-x64.html)
Also tried with latest NetExtenderPackage "NetExtender.Linux.7.0.741.x86_64" and it's the same symptoms - i can connect successfully, fetch about one webpage, and then everything just seem to stall. I also upgraded to Ubuntu 13.04.
Irritating that it works flawlessly on the same machine with Windows 7 in dualboot, same settings.
Answer: See Franck Routiers Post:
Note, you'll have to have the Java Development Kit installed on your System.

1) go to https://sslvpn.demo.sonicwall.com/cgi-bin/welcome
2) log in with demo/password
3) click on NetExtender icon, this will download a tar.gz with the
  client
4) sudo ln -s /lib/x86_64-linux-gnu/libssl.so.1.0.0
  /usr/lib/libssl.so.6
5) sudo ln -s /lib/x86_64-linux-gnu/libcrypto.so.1.0.0
  /usr/lib/libcrypto.so.6
6) un-tar the client, make install script executable and launch
  install
You're done.
Connect with :
sudo netExtender -u user -p password -d domain server
(and see man netExtender)
Comment: Mine works without the ln -s steps 4 & 5 in Ubuntu 14.04. Very easy.
Comment: It needs a Java JDK installed to work.
Comment: Sorry, no that won't work for me or my colleagues, it's the same solution as describe in the link in my question.
Answer: https://www.sonicwall.com/support/knowledge-base/how-can-i-download-and-install-netextender-on-linux/180105195559153/
Installing with rpm had this issue, download the .tgz version and install, that fixed my issue in ubuntu 16.04 version
Comment: Welcome to Ask Ubuntu! Whilst this may theoretically answer the question, [it would be preferable](//meta.stackoverflow.com/q/8259) to include the essential parts of the answer here, and provide the link for reference.
Comment: Great, Sadly I can no longer verify anything regarding this question as I don't have access to this environment any more.
Comment: It is good to see an old member still using AU and following their questions. Questions still receive answers and as @KevinBowen commented, we should keep maintaining high quality answers so future users with same problems will have more tools and possible solutions for it.
Answer: Not sure if you got a solution to this or not, but Dell Sonicwall just released a firmware update to the NSA series that somewhat addresses this type of issue.  I was having similar "trailing off" issues with my windows client.  The Global VPN client would work fine, but the Netexender would slow to a crawl after a couple minutes.  This firmware update has increased the throughput by a factor of at least eight and the speed stays constant!
Comment: Oh, wish I could test, however I changed work since this.. Thanks anyhow, and hope your answer helps someone.


How to remove encoded HTML tags from a string in PHP

Question: A web service that I am accessing send the following response...
result

How can I strip the string of these encoded tags?
Comment: maybe convert to HTML and then strip_tags?
Comment: http://stackoverflow.com/questions/657643/how-to-remove-html-special-chars-in-php
Comment: I tried using `htmlspecialchars` and `html_entity_decode` in conjunction. I missed the `strip_tags`
Answer: <?php
$str = 'result';
echo strip_tags(html_entity_decode($str));


Oven Igniter Going Bad Quickly

Question: I have a hotpoint RGB535GET1AD gas oven. Around three years ago the igniter died and the landlord replaced it. Nine months ago it went bad again, and I replaced it myself. Yesterday the igniter went bad again. As I understand it an igniter should last longer than that. I have two questions:

Could I have done something while installing the igniter to make it go bad quickly?
Might there an underlying problem that would make the igniter die, and if so how would I diagnose it?
Answer: I had a Viking stove with 2 ovens. The larger oven had 2 igniters and the smaller one had 1.   One igniter in the large oven had failed, but we didn't realize it. It just took a long time to heat up. Then the 2nd one failed, on Thanksgiving day, naturally!    I moved the igniter from the small oven to replace one of them in the large oven so at least we could get it partially working.
In doing research, I found that Viking igniters are notorious for failing.  I found a different brand replacement and it's been trouble free for at least 10 years.   You might see if you can find a higher quality replacement. Don't go for the cheapest, get the best.   I wish I could remember where I got the new ones to let you know, but it was 10 years ago and I forgot!

Oven Igniter Going Bad Quickly


Distance between Sprinkler head and Air condition system

Question: I'm planning to add Sprinkler system in office area which have a central air condition system.
Does code specify how close air condition can be to the sprinklers head?
What does minimum distance between sprinkler head and Air condition system should be?
Comment: Code questions are tough to answer as code tends to vary from country to country, state to state, city to city.  If you can provide location information you may get lucky and have someone that knows your specific situation.  That said if you can reword your question to get a more general suggestion/best practice answer that may be more doable.
Comment: I don't think there'd be a problem, unless the ducting obstructed the spray from the nozzle or interfered with the operation of the sprinkler head in some way.
Answer: Air conditioning units can get water on them - save any internal electronics which almost always have guard/protection/enclosure.  I can't foresee any local code that would care.
Answer: Code in my area requires you use a professional to install the sprinkler.
The pro will know the exact details.  It also depends which part of the air conditioner is involved.


Django Forms or own html forms?

Question: Is it a good practice to write own forms in django templates isntead of creating built-in django forms?
 Like this:

             <form method="post" >
            {% csrf_token %}

                UserName

                <input type="text" id="username" placeholder="username" name="{{ form.username.name }}"
                       class="form-control">

                Password

                <input type="password"  id="password1" placeholder="password"
                       name="{{ form.password1.name }}" class="form-control">

                Password

                <input type="password"  id="password2" placeholder="password" name="{{ form.password2.name }}"
                       class="form-control">

            <input type="submit"  class="btn btn-primary form-control" value="Send">
        </form>

Answer: Django's docs say the following about their role in form creation:

"preparing and restructuring data to make it ready for rendering"
"creating HTML forms for the data"
"receiving and processing submitted forms and data from the client"

source: https://docs.djangoproject.com/en/2.1/topics/forms/
If you want to let them do the heavy lifting and manage those three things listed above then why not? No need to re-invent the wheel unless you are doing something that requires it. It really depends on what you're building.
Answer: As a heavy user of django and its forms. I recommend django forms with django-crispy-forms. This is the best package you can use to customize a form by functionality and/or layout. They have ready template forms for bootstrap too which I use for most of my projects.
Hope this helps!

Django Forms or own html forms?


is there a mybatis 'pre-interceptor' to change sql programmatically before sql execution?

Question: in my current project, the update statements are assembled with those non-null bean properties , we ignore those null bean properties to prevent wrongly update fields to null.
for example (not actual code, just help to understand)
update person
set
<if test=" address != null and address != '' ">
    address = #{address},
</if>
<if test=" name != null and name != '' ">
    name = #{name},
</if>
where id = #{id}

and if we set the person.address = '--set-to-null--' and person.name = 'john' and person.id = 1
mybatis will generate a sql
update person set address = '--set-to-null--', name = 'john' where id = 1;

my question is, how I can programmatically change the sql to
update person set address = null, name = 'john' where id = 1;

before mybatis excute the sql
I hope I made the question clear, thanks a lot.
Answer: Try binding:
<bind name="newAddress" value = "address.equals(\"--set-to-null--\") ? org.me.Utils.defaultAddress() : address"/>
update person
set
<if test=" address != null and address != '' ">
  address = #{newAddress},
</if>
<if test=" name != null and name != '' ">
  name = #{name},
</if>
where id = #{id}

Comment: it will need quite a few of binds


How to pretty print JSON into a line based key structure?

Question: Say I have an arbitrary nested JSON file:
{"menu": {
  "id": "file",
  "value": "File",
  "popup": {
    "menuitem": [
      {"value": "New", "onclick": "CreateNewDoc()"},
     {"value": "Open", "onclick": "OpenDoc()"},
     {"value": "Close", "onclick": "CloseDoc()"}
   ]
 }
}}

And I want to output the structure:
foo.menu.id=file
foo.menu.value=File
foo.menu.popup.menuitem[0].value=New
foo.menu.popup.menuitem[0].onclick=CreateNewDoc()
foo.menu.popup.menuitem[1].value=Open

And so forth. My use case is that it will make easier to work with JSON APIs if I can get an overview of the keys I might want to use in my mashup.
How would I achieve that in PHP or nodejs? Or some other tool? If the text value is very long then it could be truncated to be nicely lines based.
Comment: slightly confused, how is this more useful? Just JSON.stringify an object to send it somewhere, JSON.parse that data back into an object, between those two points where is the need to see the structure? In even decently written code you shouldn't have to worry about the keys, you just make sure -as programmer- that they're there, then you use them.
Comment: `console.log(JSON.parse(jsonstring))`; use the built-in object explorer in (modern) the browser's console.
Answer: Note that in most cases, you should simply parse JSON in the desired target language. If that's not an option, you can easily iterate over all elements, like this:
<?php
function unroll_obj($o, $prefix='') {
    foreach ($o as $k => $v) {
        if (is_array($v)) {
            unroll_obj($v, $prefix . $k . '.');
        } else {
            echo $prefix . $k . '=' . $v . "\n";
        }
    }
}

$s = '{"menu": {
  "id": "file",
  "value": "File",
  "popup": {
    "menuitem": [
      {"value": "New", "onclick": "CreateNewDoc()"},
     {"value": "Open", "onclick": "OpenDoc()"},
     {"value": "Close", "onclick": "CloseDoc()"}
   ]
 }
}}';

$o = json_decode($s, true);
unroll_obj($o);

Comment: Nice! Just what I was looking for. Be nicer if the numeric keys could have the square brackets for use in JS. Nonetheless I'll accept as is.
Comment: @hendry If you want to use it in JavaScript, **you don't need this code**! All JSON is valid JavaScript, so simply write out `echo 'var data = ' . $json . ';';`
Comment: Yes, but this helps me quickly find the key I want to use. :)
Comment: @hendry Are you aware of the `JSON_PRETTY_PRINT` flag? That makes the JSON quite readable as well.
Comment: Yes I am, but the output isn't line based like I like it here.


error when installing PDFNetPython3==8.1.0 for my pyrthon virtual environment

Question: When I try to install PDFNetPython3==8.1.0 with pip on the pycharm command window I get the following error:
ERROR: Could not find a version that satisfies the requirement PDFNetPython3==8.1.0 (from versions: none)
ERROR: No matching distribution found for PDFNetPython3==8.1.0

I expected that the Python package will be installed. Please can someone help me with the possible reason for this.
Answer: You can see the release history for this Python package on the Python Package Index (PyPI) that pip uses when downloading packages: https://pypi.org/project/PDFNetPython3/#history
There is no version 8.1.0 available, either because it never was uploaded or because it was there but the author deleted it later on.
Comment: Thank you for your response .Thesame error occur with the version PDFNetPython3 9.5.0.post2 and also 9.4.2
Comment: @NkonghoNdip Which Python version do you use?
Comment: If you don't add a version requirement, the error should be a different one. Have you tried `pip install PDFNetPython3`? What does it say?


react-hook-form batch async validation

Question: Say I have 3 separate fields in my form and I want to validate them asynchronously, i.e. by sending a request to the server. Currently, I am doing this manually on the submit handler. I know you can define your custom validate() function for registered controllers, but that would cause 3 separate requests to be performed.
How to batch them together so there is only one request for all three fields?
Answer: You have to set mode in useForm to "onSubmit" to make the validation trigger on the submit event.

useForm({
    ...
    mode: "onSubmit"
})

react-hook-form batch async validation


Using single RMI Registry

Question: I've been using RMI for a project I am currently working on and I want to bind from multiple hosts to a single RMI registry.
However when I attempt to do so I get an error saying
java.rmi.AccessException: Registry.Registry.bind disallowed; origin / 192.168.0.9 is non-local host
I did so googling and it seems that RMI stops remote hosts from binding by default, what I want to know is there some way of overriding or bypassing this?
If anyone any suggestions on how to get past this issue they would be highly appreciated, i've tried using different policy files and overriding the security manger but none seem to work.
Answer: There's a way to get around the limitation but it is what it is: a work-around. Anyway, feel free to try it out. It works for us.
On the host that is running the central RMI registry run a small service which will bind a remote object with just one remote method: proxyRebind. The implementation of this method simply binds the object that is supplied to it in the central registry (this would not fail because the registry is on the same machine as this service).
All other hosts would simply lookup this remote object and invoke proxyRebind with their own remote objects.
This works because look-up on remotely hosted registries is allowed. Your original attempt failed because binding on remotely hosted registries is not allowed.
Let me know if you need any further clarity on this.
/RS
Comment: That's clever! Sounds like something that might be closed up as a potential security hole in a future release of the JRE. I wouldn't make any major design decisions depend on this technique.
Comment: If it were to be closed up, would have happened a long time ago! I have been doing this implementation for the past 10 years!
Comment: rndm.buoy I've attempted to implement this and the object does indeed bind succesfuly however when I attempt to invoke a remote method I get the exception `java.rmi.ConnectException: Connection refused to host: 127.0.1.1; nested exception is:` even though the remote object should resolve to the IP 192.168.126.137
I'm wondering if there is something i'm missing could you please expand on your suggestion it would be greately appreciated.
Answer:
2    There's a way to get around
  the limitation but it is what it is: a
  work-around. Anyway, feel free to try
  it out. It works for us.
On the host that is running the
  central RMI registry run a small
  service which will bind a remote
  object with just one remote method:
  proxyRebind. The implementation of
  this method simply binds the object
  that is supplied to it in the central
  registry (this would not fail because
  the registry is on the same machine as
  this service).
All other hosts would simply lookup
  this remote object and invoke
  proxyRebind with their own remote
  objects.
This works because look-up on remotely
  hosted registries is allowed. Your
  original attempt failed because
  binding on remotely hosted registries
  is not allowed.
Let me know if you need any further
  clarity on this.

This perfectly works. The only thing to take care is following should be always set correctly.
-Djava.rmi.server.hostname="LOCAL HOST IP"
Comment: It is only necessary to set `java.rmi.server.hostname` in a multihomed host or if there is something wrong with your DNS as described in item [A.1 of the RMI FAQ](http://docs.oracle.com/javase/7/docs/technotes/guides/rmi/faq.html#domain).
Answer: I may be misunderstanding your question, if so please let me know.
I have limited experience with Java RMI, we used it in our Design Patterns class with the Proxy Pattern. (Textbook: Headfirst Design Patterns)
We were not able to get our projects working from outside the university network, but they worked perfectly when connected directly to the network.  According to our professor, it wasn't possible to use RMI in our implementation over the internet or wan.  A solution she suggested was that a VPN would be required.  I believe Vladimir is correct in that it has to do with it being a local naming service.
Comment: No. It has to do with callbacks being infeasible over networks with client-side proxies, and the issue described in item A.1 of the RMI FAQ. 'Local naming service' is a figment of the imagination.
Answer: I may be wrong, but it looks like rmiregistry application is essentially a wrapper over local naming service. Which means there is no way to make it point to remote objects.
What you need is a Naming implementation, and clustered at this. Consider to move into J2EE AS clustering solution. JNDI tree is shared within the cluster.
Comment: You are wrong. The RMI Registry *is* a naming service. It isn't a wrapper over anything. It just won't accept bind/rebind/unbind requests other than from the localhost. That isn't the same thing as not being able to point to remote objects. It can.
Answer: Thanks for everyones answers the solution I came up with in the end was to use the Cajo Framework this gives a very flexible system for distribution and it allowed for me to handle the registry as I saw fit. It can also work behind NATs, firewalls, and HTTP proxies, which is very useful.
I believe that the method of proxying suggested by rndm.buoy will work in some cases but its may be troublesome on some system. RMI seems to have some issues with associating to the wrong Network Interface I particularly had this issue when running on Debian based Linux distributions.

Using single RMI Registry


Jquery trim not working Japanese whitespaces

Question: I just found that the jquery trim function (using 1.8.x) will not trim Japanese whitespaces.
Any better solution to this issue?
Comment: http://stackoverflow.com/questions/4300980/what-are-all-the-japanese-whitespace-characters
Comment: There are actually *Japanese* whitespaces?
Comment: @ExplosionPills, [yes](http://www.fileformat.info/info/unicode/char/3000/index.htm).
Comment: since you're on the topic of encoding, please read this article, which I found helpful when someone once gave it to me: http://www.joelonsoftware.com/articles/Unicode.html
Comment: @mplungjan Please start Japanese IME for Japanese input and press the space key. You will get the Japanese whitespace.
Answer: I wrote something after reading this:
https://github.com/jquery/jquery/pull/896
DEMO
<code>$.extend({
  jTrim: function(str){
    var re = /^[\s\xA0\uFEFF\u1680\u180E\u2000-\u200A\u202F\u205F\u3000]+|[\s\xA0\uFEFF\u1680\u180E\u2000-\u200A\u202F\u205F\u3000]+$/g
    return str.replace(re,"");
  }
});

console.log(">"+$.jTrim(' よろしくお願い申し上げます。')+"<");
</code>
Comment: Thanks you. I found the problem is actually a browser-based. Jquery trim works fine in IE9, but I had to support IE >= 6 :(
Answer: For an ES5 shim including a (supposedly) complete implementation of the ES5 String.trim() method, see https://github.com/kriskowal/es5-shim
<code>// ES5 220.127.116.11
// http://es5.github.com/#x18.104.22.168
var ws = "\x09\x0A\x0B\x0C\x0D\x20\xA0\u1680\u180E\u2000\u2001\u2002\u2003" +
    "\u2004\u2005\u2006\u2007\u2008\u2009\u200A\u202F\u205F\u3000\u2028" +
    "\u2029\uFEFF";
if (!String.prototype.trim || ws.trim()) {
    // http://blog.stevenlevithan.com/archives/faster-trim-javascript
    // http://perfectionkills.com/whitespace-deviations/
    ws = "[" + ws + "]";
    var trimBeginRegexp = new RegExp("^" + ws + ws + "*"),
        trimEndRegexp = new RegExp(ws + ws + "*$");
    String.prototype.trim = function trim() {
        if (this === undefined || this === null) {
            throw new TypeError("can't convert "+this+" to object");
        }
        return String(this)
            .replace(trimBeginRegexp, "")
            .replace(trimEndRegexp, "");
    };
}
</code>


Can't summon mossy stone bricks

Question: I'm using Minecraft 1.11 and am having trouble summoning a mossy stone brick. I am using /setblock and can summon a normal stone block, but not mossy. I have tried mossy_stoneblock, stoneblock:1, stoneblock1 and much more. It just won't happen for me.
Can anyone help?
Answer: /setblock syntax:
/setblock X Y Z <block ID> [metadata] [oldBlockHandling] {NBT}

You must separate the block ID and metadata value. The correct ID is minecraft:stonebrick with a metadata value of 1:
/setblock ~ ~1 ~ minecraft:stonebrick 1

You can find a list of all block IDs here.
Answer: In 1.13 and later versions, there is no concept of "block ID" and "Metadata value" and everything just has its own name:
/setblock <coords> mossy_stone_bricks

Comment: The question asks about Minecraft 1.11.
Comment: This answer is supposed to be addressed to future readers from 2023, not to the asker. This is what distinguishes the Stack Exchange network from a forum.

Can't summon mossy stone bricks


How to map model property to view model using AutoMapper

Question:
Is there a simple way to map a single model property into a viewModel?
I need to map some props from the "outter model" and the rest from the "inner model" (complex type)...
class Car
{
    public int Id {get;set;}
    public string Name {get;set;}
    public virtual CarDetails Details {get;set;}
}

class CarDetails
{
    public int Id {get;set;}
    public string Model {get;set;}
    public DateTime Year {get;set;}
}

class DetailsViewModel
{
    public string Name {get;set;}
    public string Model {get;set;}
    public DateTime Year {get;set;}
}

Then I want to be able to:
var viewModel = mapper.Map<Car, DetailsViewModel>(car);

I've tried to map this without success using something like this:
CreateMap<Car, DetailsViewModel>().ForAllMembers(opts => opts.MapFrom(c => c.Details ));

PS¹.: I'm aware of the naming convetion for flattening objects, but in don't want to change the names of the view model and don't want to use multiple ForMember statements too (my current model is a lot bigger than the one from the example).
PS².: I'm using asp.net-core and a AutoMapperConfig static class to do all configuration. So I don't have access to the Mapper instance before registering the configurations.
Answer: AutoMapper Config:
 var config = new MapperConfiguration(cfg =>
        {
            cfg.CreateMap<Car, DetailsViewModel>()
                      .ForMember(x =>
                          x.Model, opt => opt.MapFrom(src => src.Details.Model))
                      .ForMember(x =>
                          x.Year, opt => opt.MapFrom(src => src.Details.Year));

        });

 var mapper = config.CreateMapper();

Then you can do
var detail = mapper.Map<Car, DetailsViewModel>(car);

Comment: Please refer to the first observation of my question


How many torpedoes does it take to sink the Aircraft Carrier on Wake Island?

Question: On the Wake Island Battlefield 1942 map, there is an Aircraft carrier and a battleship. On the Wake Island airbase there are three planes, two with bombs, and one with torpedoes. How many torpedoes does it take to sink the aircraft carrier?
Also, does the damage depend on angle of attack, ie dropping it into the water low and fast/dropping it onto the deck or is it the same for a hit anywhere?
Comment: *nod* I've seen before after a long pounding (and ramming with the destroyer) it sinks. Note the tag Battlefield 1942, not Battlefield 2.
Comment: It can be sunk? Really? Or am I mixing something up here?
Answer: Looks like it takes at least 8 torpedoes (launched from the plane, like above). I know BF1942 is a much older game but there's your answer.
Answer: Hits at right angles with bombs and torpedoes will cause more damage, yes.  Another effective strategy for taking out the carrier can be to deck bomb from high altitude whilst "looping the loop".


Can only have five bots in CS GO and competitive mode

Question: I would like to play alone (or with some friends) against 10 bots.
When selecting "casual", this is working pretty fine.
(The bots are only added to the CT team, there is no kind of team balancing, there is no check, if one team has more members than the other, maxplayers is set to 20)
But as soon as I switch to competitive mode, there are only 5 bots allowed. When trying to add one more bot to the CT team on the server console, a message is shown that the team be full.
I did not find any difference between the gamemode_casual cfg file and the gamemode_competitive file.
Does anyone have a clue why this phenomenon is shown?
Best regards,
Box
Answer: I found this video:

I am unable to test it myself as I don't have access to CSGO at this moment in time, so apologies in advance if it doesn't work, but this video shows changing the gamemode files to increase the max players.
Good luck
Comment: That's it! Trank you!


SQL database in Google Cloud, insert data with curl

Question: I have created a MySQL database in google cloud. I want to insert/update/delete data with curl from the command line. Is there any google api with which you can do this without creating your own API to do this ?
Or is there any other simple and pretty much out-of-the-box solution for this. I just want to spin up a database to insert some data for my project and not spend a lot of time creating the api
-Jani
Comment: Why do you want to use cURL for that? There's a native MySQL shell client which can do all that
Comment: I am going to use it from a bash script so it would be easier to just use curl. I think I will use Firestore instead: https://firebase.google.com/docs/firestore/use-rest-api
Answer: The MySQL client protocol is not HTTP, therefore you cannot use an HTTP tool such as curl to communicate with MySQL unless you install a bridge/translation library.
The out of the box solution is to use the MySQL client library.


Minecraft spawneggs CanPlaceOn

Question: I am trying to give myself a wolf spawn egg named Bradley (or a different name) that can be placed on grass.
I have tried:
<code>/give @p minecraft:spawn_egg 1 0 {Entitytag:{id:"Wolf",CustomName:"Bradley"CanPlaceOn:["minecraft:grass"]}}</code>
Can someone please help me?
Comment: I believe the id for the wolf egg is minecraft:spawn_egg:95
Answer: The correct command for 1.12 is:
<code>/give @p spawn_egg 1 0 {EntityTag:{id:"minecraft:wolf",CustomName:"Bradley"},CanPlaceOn:["minecraft:grass"]}
</code>
Here is a command with the proper hideflag to hide the CanPlaceOn data:
<code>/give @p spawn_egg 1 0 {EntityTag:{id:"minecraft:wolf",CustomName:"Bradley"},CanPlaceOn:["minecraft:grass"],HideFlags:16}
</code>
Comment: This doesn't work, `CanPlaceOn` only works for blocks.
Comment: In my testing, command works properly.  In adventure mode, eggs spawn if used only on grass block.
Comment: can you also hide it's name?
Comment: In my original command you didn't see it's name but when you placed it it showed it's name
Comment: I just edited the answer to fix that.

Minecraft spawneggs CanPlaceOn


Returning multiple values in java (String and an array)

Question: So the method is called:
private void print()
{
    System.out.println("The list of Devices is:");
    for(int i = 0; i < numDevices; i++)
    {
        System.out.println(list[i].toString());
    }
}

When it gets to toString method it brings it here
public String toString()
{
     String temp = name + ": " + readings[0];
     return temp;
}

My issue is when I call on the method print its supposed to out put all data values inside of readings instead I can only return one data value. Any help would be appreciated and if more information is needed let me know as this is two of 3 files.
My output:
The list of Devices is:

Speedometer: 3

Alitimeter: 1

there output is
The list of Devices is:

Speedometer: 3,39.7,93.2,193.2,0.0,0.0

Altimeter: 1,422.6,98.7,340.5

Comment: You should look at this: http://stackoverflow.com/questions/2832472/how-to-return-2-values-from-a-java-function it looks similar to your question.
Comment: yes it does seem very similar the issue is I cant create another class. additionally no new objects may be created in the class where tostring is located at.
Answer:   public String toString() {
        String str = name + ": ";
        for (int i = 0; i < readings.length; i++) {
            if (i < readings.length - 1) {
                str += readings[i] + ", ";
            } else {
                str += readings[i];
            }
        }
        return str;
    }

Try replace your toString method like this.
Answer: You have the line
 String temp = name + ": " + readings[0];

The "[0]" means only do the first item in the readings array.  You need to find a way to do ALL the items in the array.  For example, if there were 3 items in the array, you could do
 String temp = name + ": " + readings[0] + "," + readings[1] + "," + readings[2];

Of course, since the number of items in the array can vary, you'll want to put it into a loop.  Which is what Drogba's example does.
Good luck!


How to remove preceding spaces before non space text begins + regex + sed +

Question: How do I remove the preceding spaces before 809 in the output of my echo??
here is my sample:
$ echo '   809 23/Dec/2008:19:20'
   809 23/Dec/2008:19:20
^^^3 spaces here preceding the 809

I can remove 3 or 4 spaces using sed:
        ...4 spaces here
$ echo '    809 23/Dec/2008:19:20' | sed 's/^.\{3\,4\}//'
809 23/Dec/2008:19:20
0 spaces here preceding the 809

But what I want is my sed command to work on anything greater than 3
        .....5 spaces here
$ echo '     809 23/Dec/2008:19:20' | sed 's/^.\{3\,4\}//'
 809 23/Dec/2008:19:20
^1 spaces here preceding the 809

Ho do I write my regex in the sed to remove 3 or more spaces preceding 809?
Comment: Use `sed 's/^[[:blank:]]\{3,\}//'` if you want to remove 3 or more spaces at the start.
Comment: Maybe `^\s{3,}`
Comment: do you have to use sed? xargs chops off white spaces automatically.
Comment: Why are you using `.` in the regexp? That matches any character, not just spaces.
Answer: If you want to remove 3 or more spaces at the start use
sed 's/^[[:blank:]]\{3,\}//'

Details

^ - start of input
[[:blank:]]\{3,\} - 3 or more consecutive occurrences of any horizontal whitespace.

If you need to remove 3+ spaces at the start before a specific value, say, 809, just add that value to the regex and replacement pattern:
sed 's/^[[:blank:]]\{3,\}809/809/'

or use a capturing group and placeholder:
sed 's/^[[:blank:]]\{3,\}\(809\)/\1/'

Answer: xargs frees you from thinking about regular expressions.
$ echo '   809 23/Dec/2008:19:20' | xargs
809 23/Dec/2008:19:20

It's a more or less unconventional trick of xargs. This tool is meant to be used to build up commands with long argument lists. From man page:

xargs reads items from the standard input, delimited by blanks (which can be protected with double or single quotes or a
         backslash) or newlines, and executes the command

However, it a part of the preprocess that white space will be trimmed, before sending to subsequent command. In this case, there isn't subsequent command, and therefore xargs just send the argument as it is, modulo with the spaces trimmed, to standard output, which does exactly what you are asking for.
Comment: @HattrickNZ I added a few more words explaining why it would work.
Comment: good to know `echo '     809 23/Dec/2008:19:20' | xargs
809 23/Dec/2008:19:20
` can you briefly explain `xargs`?
Answer: You can specify how many characters you want to for using {minimum,maximum}.
If you leave maximum blank it will match anything with at least the minimum amount of characters. So selecting three spaces would be "\{3,\}". Good luck!
Answer: Don't escape comma:
$ echo '             809 23/Dec/2008:19:20' | sed -s 's/^ \{3,\}//'
809 23/Dec/2008:19:20


Why can't we prove the consistency of ZFC by proving its axioms is satisfiable?

Question: We can prove the consistency of Peano Arithmetics by given a model of natural numbers, within this model, PA's axioms are satisfiable,thus PA is consistent. Why can't we do the same thing to ZFC
Comment: We cannot actually prove that PA is consistent. There are proofs , but either they rely on ZFC which itself cannot prove its own consistency, or on transfinite induction (as in the case of Gentzens proof) which we cannot prove to be consistent either. So, strictly speaking, the situation is not actually better in PA. Gentzen's proof at least avoids the proof in a stronger theory. If we use a stronger theory, we land again in Goedel's second incompleteness-theorem. We can extend ZFC, but the problem does not vanish. So, Gentzen's approach is most promising.
Comment: Well, even describing a model of ZFC - ignoring all proof-theoretic issues, as well as the issue of verifying that a given theory is true in a given structure - is meaningfully harder than for PA: [ZFC has no computable models](https://mathoverflow.net/questions/12426/is-there-a-computable-model-of-zfc). This is related to the fact that PA has no computable *nonstandard* models.
Answer: I think it may help to think about the Soundness Theorem as saying the following:

Let $\Sigma$ be a collection of sentences over some language $\mathcal{L}$, and let $\mathsf{S}$ be a collection of axioms of set theory.  Suppose $\mathsf{S}$ proves that there is a model for $\Sigma$.  Then $\mathsf{S}$ proves that $\Sigma$ is consistent.  In particular, if $\mathsf{S}$ itself is consistent then so is $\Sigma$.

So if you prove the "consistency" of $\mathsf{PA}$ by constructing a model for it, using the axioms of $\mathsf{ZFC}$, then what you have really proved is relative consistency: if $\mathsf{ZFC}$ is consistent then so is $\mathsf{PA}$.  Of course, you do not actually know whether $\mathsf{ZFC}$ is consistent, though it seems very likely.
You can attempt to take $\Sigma = \mathsf{ZFC}$ in the Soundness Theorem, but the question then is what do you take for $\mathsf{S}$?  Gödel's second incompleteness theorem implies that you cannot take $\mathsf{S} = \mathsf{ZFC}$.  Usually to construct a model of $\mathsf{ZFC}$, your set theory $\mathsf{S}$ is all the axioms of $\mathsf{ZFC}$ plus some extra ones, e.g. $\mathsf{I}=$ "there exists an inaccessible cardinal".  But this is not very satisfying as a way to decide whether $\mathsf{ZFC}$ itself is consistent, since it's already trivial that $\operatorname{Con}(\mathsf{ZFC}+\mathsf{I}) \to \operatorname{Con}(\mathsf{ZFC})$.
It is very rare in logic to actually prove that a collection of axioms is consistent; it's usually only possible for very trivial examples.
Comment: Regarding the first point, it's not super clear how to get from "S proves $\Sigma$ consistent" to "if $S$ is consistent then $\Sigma$ is". Just cause $S$ is consistent doesn't make it right about everything. However for effective theories, inconsistency can be proved by a computation so if an effective $\Sigma$ were inconsistent, then $S$ would certainly prove it, provided it can represent recursive functions, which is a very weak requirement. So if $S$ is consistent and proves $\Sigma$ is consistent, it does happen to be right about it.
Comment: @spaceisdarkgreen: Good point.  To detect inconsistency, $\mathsf{S}$ needs to be able to prove that a set of sentences which purports to be a valid proof from axioms of $\Sigma$, really is one.  The difficulty, I guess, is verifying that "axioms" in that proof really are axioms of $\Sigma$, which could be hard if $\Sigma$ is very complex.
Comment: (An alternative way to think about it might be "inside a model of $S$ lies a model of $\Sigma$" but that requires similar justification for why $S$ should be right about what a model of $\Sigma$ is. Again we can show it and like the case above, the converse is not true: there can be models of $\Sigma$ inside a model of $S$ that the model of $S$ believes is *not* a model of $\Sigma$. For instance, amusingly, every model of ZFC contains a model of ZFC, regardless if Con(ZFC) holds in the model.)