Spark buttons with embeded images

Question: I'm a Flex 4 noob so be patient...
I want to do something like:
Main.mxml
<s:HGroup id="animals">

    <s:Button name="dog">Dog Name</s:Button>
    <s:Button name="bird">Bird Name</s:Button>
    <s:Button name="cat">Cat Name</s:Button>

</s:HGroup>

Skin for #animals s|Button
<?xml version="1.0" encoding="utf-8"?>
<s:Skin xmlns:fx="http://ns.adobe.com/mxml/2009" xmlns:s="library://ns.adobe.com/flex/spark" minWidth="40" minHeight="22">

    <fx:Metadata>
       [HostComponent("spark.components.Button")]
    </fx:Metadata>

    <s:states>
        <s:State name="up" />
        <s:State name="over" />
        <s:State name="down" />
        <s:State name="disabled" />
    </s:states>

    <s:BitmapImage width="104" height="54" source="@Embed('../../assets/img/animals/__PUT_HERE_BUTTON_NAME__.png')"/>

    <s:Label
    id="labelDisplay"
    textAlign="center"
    color="0xffffff"
    fontFamily="CuteFont"
    fontWeight="bold"
    fontSize="15"
    width="100%"
    top="64"
    />
</s:Skin>

Do I have to extend the Button component or how should I proceed?
Answer: The location of the Add.png must in the src directory of your flex project. If it was somewhere else then you need to specify Add.png along with its location.
Answer: Create a custom Button with an icon property (Object) and a required iconBitmapImage (BitmapImage) skin part.
It the icon setter, apply this property to the source property of iconBitmapImage.
Then you should be able to do something like :
<s:CustomButton name="dog" icon="@Embed('../../assets/img/animals/dog.png')" />

Comment: Well, I finally did this so thanks!. Could you answer this one http://stackoverflow.com/questions/5510561/embending-images-on-css-for-an-extended-spark-button-iconbutton please?

Spark buttons with embeded images


Is possible to block the execution until all previous JavaScript listeners completes?

Question: I'm quite new to JavaScript, I've searched a lot in SO but I have not find any suitable solution yet, not involving chaining. I have two event listeners, registered in this order.
First listener (module_a.js) changes a form value:
// First listener: handle submit and change recaptcha value
form.addEventListener('submit', async refreshRecaptcha() {
  const { target: form } = e;
  const recaptchaField = form.querySelector('[name="catpcha"]');

  // Simulate long running task
  await new Promise(resolve => setTimeout(resolve, 5000));

  recaptchaField.value = token;
});

Second listener (module_b.js) actually submit the form:
// Second listener: POST data to server, with the recaptchaField changed
form.addEventListener('submit', async postData(e) {
  e.preventDefault();

  // Post data
  await fetch(url, { method: 'POST', body: formData })
});

Second listener should "wait" until the first completes. Or any other async listeners complete.
I cannot "chain" together the two because they are in different modules.
Possible or impossible?
Comment: X/Y problem. Why all those async and await? Move the fetch inside the resolve
Comment: The two handlers are run in registration order, but I would not count on the order if they are in different modules. In addition, the whole point of having events is that they are indipendently run. I think you will need to have one attached to one event and the other to something else, probably to the result of the first call. So, as the question is stated, the answer is "impossible".
Comment: I cannot "chain" together the two because they are in different modules. Every module do just one thing
Comment: "*I cannot "chain" together the two because they are in different modules.*" - so make one module call functions from the other module? Tell us more about those modules and why you think they need to be so independent (and how you still guarantee order of event registrations if they're really independent).
Answer: You can achieve this using Promises.
const myPromise = new Promise((resolve, reject) => {
  setTimeout(() => {
    resolve('foo');
  }, 300);
});

myPromise
  .then(handleResolvedA, handleRejectedA)
  .then(handleResolvedB, handleRejectedB)
  .then(handleResolvedC, handleRejectedC);

Comment: Cannot chain, different files/modules


How would I make something spawn when and where a snowball hits something?

Question: I know how to make things spawn as they follow an object, but is there any way to make them spawn once lets say a snowball hits its target?
I am working on a way to make snowballs that spawn tnt upon hitting their target.
Comment: While this question is bumped, can minecraft command-savvy people go and downvote the answers that are straight-up *wrong*?
Answer: I have found a solution that works relatively well. The main issue is that when a snowball lands, the entity disappears immediately. To counteract this, we can use an armor stand marker to track the last known location of the snowball. This is not exactly where the snowball hits, but close enough for practical purposes.
First, you need to set up a scoreboard objective to track the snowball's lifetime, and another to detect a lonely armorstand.
/scoreboard objectives add snowballTime dummy
/scoreboard objectives add hasSnowball dummy

Now, create a fill clock (or use 1.9's repeat/chain command blocks), and run the following commands:
/scoreboard players add @e[type=Snowball] snowballTime 1

/execute @e[type=Snowball,score_snowballTime=1] ~ ~ ~ summon ArmorStand ~ ~ ~ {NoGravity:1b,CustomName:"SnowballMarker",Marker:1b,Invisible:1b}
/execute @e[type=Snowball,score_snowballTime_min=2] ~ ~ ~ tp @e[type=ArmorStand,name=SnowballMarker,c=1] @e[type=Snowball,r=1]

/scoreboard players set @e[type=ArmorStand,name=SnowballMarker] hasSnowball 0
/execute @e[type=Snowball] ~ ~ ~ scoreboard players set @e[type=ArmorStand,name=SnowballMarker,r=1] hasSnowball 1

/execute @e[type=ArmorStand,name=SnowballMarker,score_hasSnowball=0] ~ ~ ~ summon PrimedTnt ~ ~ ~ {Fuse:0}
/kill @e[type=ArmorStand,name=SnowballMarker,score_hasSnowball=0]

The first command will assign an ever-increasing score to every snowball entity in the world. The second and third commands will either create a new (invisible, hitboxless) armor stand (called "SnowballMarker") at the location of the snowball, or teleport an existing one to the snowball.
The fourth and fifth commands will set the hasSnowball score on the armor stand to 0 or 1, depending on whether or not there is a snowball within a radius of 1 block.
Command 6 summons TNT at every armor stand that does not have a snowball, and the last command removes these armor stands afterwards. Set the Fuse to whatever you like.
(I you are curious about the way this works, I suggest removing Invisible:1b from the summon command of the armor stand, so you can see them in action)
Comment: `hasSnowball` can be a tag.
Answer: I would take a different approach: When the snowball is thrown, summon an ArmorStand at its location. (using execute on the snowball). And use it to track the snowball. When the snowball hits something, it disappears and the ArmorStands SBB score starts to increase. You can use this to summon a TNT at the Spot where the snowball "died":
execute @e[type=Snowball,score_SBB_min=1,score_SBB=1] ~ ~ ~ summon ArmorStand ~ ~ ~ {CustomName:"SBTracker",Marker:1b,NoGravity:1b,Invisible:1b}
(SBB=Snowballbomb, you have to create this objective first)
Teleport every ArmorStand to "its" Snowball:
execute @e[type=ArmorStand,name=SBTracker] ~ ~ ~ /tp @e[c=1] @e[type=Snowball,r=2]
At every gametick, increase every snowballs SBB score by one:
scoreboard players add @e[type=Snowball] SBB 1
Do the same to the ArmorStands:
scoreboard players add @e[type=ArmorStand] SBB 1
Reset every ArmorStands SBB to 0 when there is a snowball nearby:
execute @e[type=Snowball] ~ ~ ~ /scoreboard players set @e[type=ArmorStand,r=2] SBB 0
Summon a TNT at every ArmorStand with a SBB score of more than one:
execute @e[type=ArmorStand,score_SBB_min=2,score_SBB=2] ~ ~ ~ /summon PrimedTNT ~ ~ ~
Kill every ArmorStand with a SBB score of at least 3:
kill @e[type=ArmorStand,score_SBB_min=3]
Comment: You talk about "(taking) a different approach", but this answer is functionally identical to [mine](http://gaming.stackexchange.com/a/234018/74333), with the only difference being that you use the same scoreboard objective for the armor stands and the snowballs.
Comment: Strange, I somehow didnt see your answer... But why do you use 2 objectives?
Comment: Keeping things a bit more sorted and clear, I guess. I just didn't think about using the same objective for both.
Answer: Fixed! Fully functional 1.8/1.8.x
Enter in a command block
/testfor @e[type=Snowball]

Then, power this with a clock.
To make a clock, type
/gamerule dotiledrops false

and then set a Redstone Block on top of a command block that has this command:
/setblock ~0 ~1 ~0 minecraft:redstone_block 0 destroy

Then set two comparators on two sides of the original /testfor command block. Then, place a command block on the ends of both of the comparators pointing away from the /testfor command block. In one, place the command
/summon PrimedTnt ~20 ~-20 ~ {Fuse:whateveryouwant30reccomended} ~ ~ ~

In the other, place the command
/tp @e[type=PrimedTnt,c=-1] @e[type=Snowball,c=-1]

Comment: This is outright horrible. 1) There is no need to turn off tile drops to make a clock. 2) The summon command has syntax errors, and could be summoning to the snowballs directly using execute. 3) the tp command teleports *every* Tnt to *every* snowball (Which I don't even know how the game will handle it).
Comment: the answer has not answered his question, and he raises very valid points. Why do you say "we are making a clock" and then call the line to disable tiles dropping? I do not play minecraft **and even I can tell this is very incorrect**. There is no reason to vandalise the question, just because your answer was not accepted. We expect a certain level of quality, here, and accuracy is one of the biggest factors that trumps all.
Answer: /scoreboard objectives add lifetime dummy
/scoreboard players add @e[type=Snowball] lifetime 0

the screboard is so the tnt doesnt explode in ur face
then do
/execute @e[type=Snowball] ~ ~ ~ /testfor @a[r=2]

so it tests for a player in a range of 2 blocks
/execute @e[type=Snowball,score_lifetime_min=4] ~ ~ ~ /summon PrimedTnt

also do /gamerule commandblockoutput false or it'll spam the chat
Comment: Apart from the missing formatting and largely missing explanation, this doesn't even make sense (potentially because of the latter): 1) Your lifetime score will always be at 0, since you are adding 0. 2) Your execute/testfor *doesn't do anything*. Is is supposed to be hooked up to a comparator running into the third command?
Answer: I may have an idea (Either bad or good) Score Command:`

/scoreboard objectives add snowballtime dummy

So this is how I think that this can work.
Hook this command to a clock:

/execute @e[type=Snowball] ~ ~ ~ detect ~1 ~ ~ [block] scoreboard players add @e[type=Snowball] snowballtime 1

You will need to copy this command a lot of times and change the
"detect ~ ~1 ~", "detect ~ ~-1 ~",etc. so it will detect a block in any direction in a 1 block radius.
Then add a redstone comparator pointing to this command:

/execute @e[type=Snowball,score_snowballtime=1] ~ ~ ~ summon PrimedTnt ~ ~ ~ {Fuse:0}

and a command behind that:

/execute @e[type=Snowball] ~ ~ ~ detect [~? ~? ~?] [block] scoreboard players set @e[type=Snowball] snowballtime 0

I hope that can help, plus I am just getting some ideas for commands for maps and minigames.
Comment: I see multiple issues here. The detect syntax of the execute command requires you to specify a specific block. Meaning you'd need about 6 times the number of blocks in the game command blocks for this. Also, the snowball would blow up in your face if you throw it while adjacent to a wall (or ceiling)


How do I get rid of the old Minecraft launcher?

Question: I have a problem where my launcher isn't the newest one on my PC... I have the old one and it wasn't really an issue for me until I tried to download a shader pack and couldn't do it. Does anyone know how to get the new launcher? I've been trying to solve this problem for around a year now and I can't find anyone who has the same issue as me. I can still play 1.16.4, but on the launcher there's an article about 1.11.2 being the newest update.
Answer: You can get the newest Minecraft launcher from the official Minecraft website here: https://www.minecraft.net/en-us/download
Comment: I've uninstalled minecraft and reinstalled the link you provided but it's still the same old one.
Comment: It sounds like you might not have completely uninstalled the old launcher or you are using the wrong shortcut. On Windows by default, the launcher is installed in `C:\Program Files (x86)\Minecraft Launcher`. Try finding this install folder and opening MinecraftLauncher.exe directly.
Comment: I uninstalled again and made sure that it was completely gone, then reinstalled with your link but it's still the old one. I also made sure my shortcut was right and it was.


Sending data over NetworkStream using multiple threads

Question: I'm trying to build a command line chat room where the server is handling the connections and repeating input from one client back to all the other clients.
Currently the server is able to take in input from multiple clients, but can only send information back to those clients individually. I think my problem is that each connection is being handled on an individual thread. How would I allow for the threads to communicate with each other or be able to send data to each thread?
Server code:
namespace ConsoleApplication
{

    class TcpHelper
    {

        private static object _lock = new object();
        private static List<Task> _connections = new List<Task>();

        private static TcpListener listener { get; set; }
        private static bool accept { get; set; } = false;

        private static Task StartListener()
        {
            return Task.Run(async () =>
            {
                IPAddress address = IPAddress.Parse("127.0.0.1");
                int port = 5678;
                listener = new TcpListener(address, port);

                listener.Start();

                Console.WriteLine($"Server started. Listening to TCP clients at 127.0.0.1:{port}");

                while (true)
                {
                    var tcpClient = await listener.AcceptTcpClientAsync();
                    Console.WriteLine("Client has connected");
                    var task = StartHandleConnectionAsync(tcpClient);
                    if (task.IsFaulted)
                        task.Wait();
                }
            });
        }

        // Register and handle the connection
        private static async Task StartHandleConnectionAsync(TcpClient tcpClient)
        {
            // start the new connection task
            var connectionTask = HandleConnectionAsync(tcpClient);

            // add it to the list of pending task
            lock (_lock)
                _connections.Add(connectionTask);

            // catch all errors of HandleConnectionAsync
            try
            {
                await connectionTask;

            }
            catch (Exception ex)
            {
                // log the error
                Console.WriteLine(ex.ToString());
            }
            finally
            {
                // remove pending task
                lock (_lock)
                    _connections.Remove(connectionTask);
            }
        }

        private static async Task HandleConnectionAsync(TcpClient client)
        {

            await Task.Yield();

            {
                using (var networkStream = client.GetStream())
                {

                    if (client != null)
                    {
                        Console.WriteLine("Client connected. Waiting for data.");

                        StreamReader streamreader = new StreamReader(networkStream);
                        StreamWriter streamwriter = new StreamWriter(networkStream);

                        string clientmessage = "";
                        string servermessage = "";

                        while (clientmessage != null && clientmessage != "quit")
                        {
                            clientmessage = await streamreader.ReadLineAsync();
                            Console.WriteLine(clientmessage);
                            servermessage = clientmessage;
                            streamwriter.WriteLine(servermessage);
                            streamwriter.Flush();

                        }
                        Console.WriteLine("Closing connection.");
                        networkStream.Dispose();
                    }
                }

            }

        }
        public static void Main(string[] args)
        {
            // Start the server

            Console.WriteLine("Hit Ctrl-C to close the chat server");
            TcpHelper.StartListener().Wait();

        }

    }

}

Client Code:
namespace Client2
{
    public class Program
    {

        private static void clientConnect()
        {
            TcpClient socketForServer = new TcpClient();
            bool status = true;
            string userName;
            Console.Write("Input Username: ");
            userName = Console.ReadLine();

            try
            {
                IPAddress address = IPAddress.Parse("127.0.0.1");
                socketForServer.ConnectAsync(address, 5678);
                Console.WriteLine("Connected to Server");
            }
            catch
            {
                Console.WriteLine("Failed to Connect to server{0}:999", "localhost");
                return;
            }
            NetworkStream networkStream = socketForServer.GetStream();
            StreamReader streamreader = new StreamReader(networkStream);
            StreamWriter streamwriter = new StreamWriter(networkStream);
            try
            {
                string clientmessage = "";
                string servermessage = "";
                while (status)
                {
                    Console.Write(userName + ": ");
                    clientmessage = Console.ReadLine();
                    if ((clientmessage == "quit") || (clientmessage == "QUIT"))
                    {
                        status = false;
                        streamwriter.WriteLine("quit");
                        streamwriter.WriteLine(userName + " has left the conversation");
                        streamwriter.Flush();

                    }
                    if ((clientmessage != "quit") && (clientmessage != "quit"))
                    {
                        streamwriter.WriteLine(userName + ": " + clientmessage);
                        streamwriter.Flush();
                        servermessage = streamreader.ReadLine();
                        Console.WriteLine("Server:" + servermessage);
                    }
                }
            }
            catch
            {
                Console.WriteLine("Exception reading from the server");
            }
            streamreader.Dispose();
            networkStream.Dispose();
            streamwriter.Dispose();
        }
        public static void Main(string[] args)
        {
            clientConnect();
        }
    }
}

Answer: The main thing wrong in your code is that you make no attempt to send data received from one client to the other connected clients. You have the _connections list in your server, but the only thing stored in the list are the Task objects for the connections, and you don't even do anything with those.
Instead, you should maintain a list of the connections themselves, so that when you received a message from one client, you can then retransmit that message to the other clients.
At a minimum, this should be a List<TcpClient>, but because you are using StreamReader and StreamWriter, you'll want to initialize and store those objects in the list as well. In addition, you should include a client identifier. One obvious choice for this would be the name of the client (i.e. what the user enters as their name), but your example doesn't provide any mechanism in the chat protocol to transmit that identification as part of the connection initialization, so in my example (below) I just use a simple integer value.
There are some other irregularities in the code you posted, such as:

Starting a task in a brand new thread, just to execute a few statements that get you to the point of initiating an asynchronous operation. In my example, I simply omit the Task.Run() part of the code, as it's not needed.
Checking the connection-specific task when it's returned for IsFaulted. Since it's unlikely any I/O will actually have occurred by the time this Task object is returned, this logic has very little use. The call to Wait() will throw an exception, which will propagate to the main thread's Wait() call, terminating the server. But you don't terminate the server in the event of any other error, so it's not clear why you'd want to do that here.
There's a spurious call to Task.Yield(). I have no idea what you're trying to accomplish there, but whatever it is, that statement isn't useful. I simply removed it.
In your client code, you only attempt to receive data from the server when you've sent data. This is very wrong; you want clients to be responsive and receive data as soon as it's sent to them. In my version, I included a simple little anonymous method that is called immediately to start a separate message-receiving loop that will execute asynchronously and concurrently with the main user input loop.
Also in the client code, you were sending the "…has left…" message after the "quit" message that would cause the server to close the connection. This means that the server would never actually receive the "…has left…" message. I reversed the order of the messages so that "quit" is always the last thing the client ever sends.

My version looks like this:
Server:
class TcpHelper
{
    class ClientData : IDisposable
    {
        private static int _nextId;

        public int ID { get; private set; }
        public TcpClient Client { get; private set; }
        public TextReader Reader { get; private set; }
        public TextWriter Writer { get; private set; }

        public ClientData(TcpClient client)
        {
            ID = _nextId++;
            Client = client;

            NetworkStream stream = client.GetStream();

            Reader = new StreamReader(stream);
            Writer = new StreamWriter(stream);
        }

        public void Dispose()
        {
            Writer.Close();
            Reader.Close();
            Client.Close();
        }
    }

    private static readonly object _lock = new object();
    private static readonly List<ClientData> _connections = new List<ClientData>();

    private static TcpListener listener { get; set; }
    private static bool accept { get; set; }

    public static async Task StartListener()
    {
        IPAddress address = IPAddress.Any;
        int port = 5678;
        listener = new TcpListener(address, port);

        listener.Start();

        Console.WriteLine("Server started. Listening to TCP clients on port {0}", port);

        while (true)
        {
            var tcpClient = await listener.AcceptTcpClientAsync();
            Console.WriteLine("Client has connected");
            var task = StartHandleConnectionAsync(tcpClient);
            if (task.IsFaulted)
                task.Wait();
        }
    }

    // Register and handle the connection
    private static async Task StartHandleConnectionAsync(TcpClient tcpClient)
    {
        ClientData clientData = new ClientData(tcpClient);

        lock (_lock) _connections.Add(clientData);

        // catch all errors of HandleConnectionAsync
        try
        {
            await HandleConnectionAsync(clientData);
        }
        catch (Exception ex)
        {
            // log the error
            Console.WriteLine(ex.ToString());
        }
        finally
        {
            lock (_lock) _connections.Remove(clientData);
            clientData.Dispose();
        }
    }

    private static async Task HandleConnectionAsync(ClientData clientData)
    {
        Console.WriteLine("Client connected. Waiting for data.");

        string clientmessage;

        while ((clientmessage = await clientData.Reader.ReadLineAsync()) != null && clientmessage != "quit")
        {
            string message = "From " + clientData.ID + ": " + clientmessage;

            Console.WriteLine(message);

            lock (_lock)
            {
                // Locking the entire operation ensures that a) none of the client objects
                // are disposed before we can write to them, and b) all of the chat messages
                // are received in the same order by all clients.
                foreach (ClientData recipient in _connections.Where(r => r.ID != clientData.ID))
                {
                    recipient.Writer.WriteLine(message);
                    recipient.Writer.Flush();
                }
            }
        }
        Console.WriteLine("Closing connection.");
    }
}

Client:
class Program
{
    private const int _kport = 5678;

    private static async Task clientConnect()
    {
        IPAddress address = IPAddress.Loopback;
        TcpClient socketForServer = new TcpClient();
        string userName;
        Console.Write("Input Username: ");
        userName = Console.ReadLine();

        try
        {
            await socketForServer.ConnectAsync(address, _kport);
            Console.WriteLine("Connected to Server");
        }
        catch (Exception e)
        {
            Console.WriteLine("Failed to Connect to server {0}:{1}", address, _kport);
            return;
        }

        using (NetworkStream networkStream = socketForServer.GetStream())
        {
            var readTask = ((Func<Task>)(async () =>
            {
                using (StreamReader reader = new StreamReader(networkStream))
                {
                    string receivedText;

                    while ((receivedText = await reader.ReadLineAsync()) != null)
                    {
                        Console.WriteLine("Server:" + receivedText);
                    }
                }
            }))();

            using (StreamWriter streamwriter = new StreamWriter(networkStream))
            {
                try
                {
                    while (true)
                    {
                        Console.Write(userName + ": ");
                        string clientmessage = Console.ReadLine();
                        if ((clientmessage == "quit") || (clientmessage == "QUIT"))
                        {
                            streamwriter.WriteLine(userName + " has left the conversation");
                            streamwriter.WriteLine("quit");
                            streamwriter.Flush();
                            break;
                        }
                        else
                        {
                            streamwriter.WriteLine(userName + ": " + clientmessage);
                            streamwriter.Flush();
                        }
                    }

                    await readTask;
                }
                catch (Exception e)
                {
                    Console.WriteLine("Exception writing to server: " + e);
                    throw;
                }
            }
        }
    }

    public static void Main(string[] args)
    {
        clientConnect().Wait();
    }
}

There is still a lot you'll need to work on. You'll probably want to implement proper initialization of chat user names on the server side. At the very least, for real-world code you'd want to do more error checking, and make sure the client ID is generated reliably (if you only want positive ID values, you can't have more than 2^31-1 connections before it rolls back over to 0).
I also made some other minor changes that weren't strictly necessary, such as using the IPAddress.Any and IPAddress.Loopback values instead of parsing strings, and just generally simplifying and cleaning up the code here and there. Also, I'm not using a C# 6 compiler at the moment, so I changed the code where you were using C# 6 features so that it would compile using C# 5 instead.
To do a full-blown chat server, you still have your work cut out for you. But I hope that the above gets you back on the right track.
Comment: WOW. Very helpful. Yes, I was mostly just kind of googling and piecing together what I had found and ironing out any errors. You really went above and beyond for me and I appreciate it immensely.  I kind of had thought I needed to store the clients, but I wasn't sure if that was redundant or not. Thank you so much for clearing that up!
Comment: @hereswilson: happy to help. Note that the above is just an example of how you might do things. It's not the last word on how you _must_ do it. For example, you could choose to even send the message back to the client who sent it (simplifying the client enumeration a bit). Also note that I've changed the synchronization for the relaying part, synchronizing the entire operation instead of just the part that gets the clients to send to. I decided I like this better (for reasons described in the comment in the code).


Which level should I play to get the Nom Nom Nom achievement?

Question: The Nom Nom Nom achievement requires stopping the zombies using only the Sunflower, Wallnut, and Chomper.
I've tried playing the first level a few times with just those plants, but the zombies get through.
Answer: The first couple levels should be work. There is a couple things you want to focus on

Focus on sunflowers early on the level, plant them horizontally instead of vertically at first. It is ok for the first one or two zombies to get to the lawnmowers, focus on sunflowers first.
Plant sunflowers where the zombies got the lawn mowers and start building up chompers
Don't be afraid to use sunflowers as barriers on the first vertical row if you don't have wall nuts available
If a chomper is currently eating a zombie and is being attacked himself, remove the current chomper and plant a new one
Comment: and don't forget to buy a rake, every little bit helps
Comment: I found that if a chomper is eating a zombie and being attacked, that I can plant a new chomper behind the first.  The new chomper will grab the attacking zombie in the next square.


Missing packages

Question: I'm getting the following errors. The software repositories are setup properly so I'm not sure what's going on as it is 12.04 LTS shouldn't these be valid?
sudo apt-get install postgresql-common=129
Reading package lists... Done
Building dependency tree
Reading state information... Done
The following extra packages will be installed:
postgresql-client-common

The following NEW packages will be installed:
postgresql-client-common postgresql-common

0 to upgrade, 2 to newly install, 0 to remove and 0 not to upgrade.

Need to get 25.1 kB/121 kB of archives.

After this operation, 596 kB of additional disk space will be used.
Do you want to continue [Y/n]?

WARNING: The following packages cannot be authenticated!
postgresql-common
Install these packages without verification [y/N]? y

Err http://lips.csiro.au/ubuntu/ precise-updates/main postgresql-client-common all 129ubuntu1 404  Not Found

Failed to fetch http://lips.csiro.au/ubuntu/pool/main/p/postgresql-common/postgresql-client-common_129ubuntu1_all.deb 404  Not Found

Answer: As your error message says
Failed to fetch http://lips.csiro.au/ubuntu/pool/main/p/postgresql-common/postgresql-client-common_129ubuntu1_all.deb 404  Not Found

The host isn't reachable, not ping-able and not trace-able.
Therefore use another PPA, e.g.
deb http://apt.postgresql.org/pub/repos/apt/ precise-pgdg main

Comment: Well this is crazy, its all working now! Yesterday that domain resolved fine and I could see the contents of the directory but it did not have the exact above package file so my question was why is apt-get looking for a version that (I thought) was no longer available? Anyway all good now, thanks
Comment: @FarhanRizwi  Since you're a new user, if this answer helped you, don't forget to mark it as solved by clicking on the grey check mark to the left of the answer.
Answer: This is all working now, not sure why that particular package was missing yesterday but is there now. I understand things can go out-of-date and sometimes you have to add different repositories but I was just confused that an LTS was having trouble with default versions. Anyway all working now

Missing packages


How to protect user access form without login

Question: I have this script which direct user to Login form if he/she is not loged,But the problem is, when I login and refresh the page it take me back to Login page and also when I login and try to copy the link and paste also it take me back to Login page, instead it suppose to be after logout.
Here the Login script
 <?php

   session_start();

   // Connect to server and select databse.
   $link=mysql_connect("localhost","root", "mcl")or die("cannot connect");
   mysql_select_db("mcl",$link)or die("cannot select DB");
   // username and password sent from form
   $fname=$_POST['fname'];
   $password=$_POST['password'];
   $sql="SELECT * FROM admin WHERE fname=('$_POST[fname]') and
   password=('$_POST[password]')";
   $result=mysql_query($sql);
   // Mysql_num_row is counting table row
   $count=mysql_num_rows($result);
   // If result matched $myusername and $mypassword, table row must be 1 row
   if($count>0){
       $_SESSION['username'] = $_POST['fname'];
       switch($_POST['fname']) {
            case 'root': header("Location: dashboard.php"); break;
            case 'accountant': header("Location: dash_accou.php"); break;
            case 'secretary': header("Location: dash_secretary.php"); break;
            }
              exit;
          }
      else {
        echo "Invald username or password <input name=Click here to reload
         type=button disabled value= <<<Reload>";
   }
    ?>

Here the script which direct user to login form
        <?php
        session_start();
        if(!isset($_SESSION['username']) ||  $_SESSION['username'] != 'root') {
        header('Location: index.php');
       exit;

        }
              ?>

   <?php
   unset($_SESSION['username']);
  ?>

Any help, thank u
Comment: You have `session_start();` at the top of ALL pages don't you?
Comment: why r u checking user != root??
Answer: if(!isset($_SESSION['username']) ||  $_SESSION['username'] != 'root') {

Notice your second clause.. this basically means that if the username is NOT root it will redirect him to the login page anyway, so say if user "Jack" logged in.. he will still be redirected to the login page since his username is not "root"
Also, please do note that that mysql_* functions are deprecated and instead, you should use Mysqli or PDO. You should also make sure that you validate and sanitize your inputs from attacks by using prepared statements. This is all very important in keeping your website secure.
Comment: I this the reason after refreshing the page to direct user to Login form?


loaded keras model doesn't have predict method

Question: In the DQN algorithm, the agent is trained successfully and the model is saved as a .h5 file.
The agent class has a method called load as follows:
def load(self):
    new_model = load_model('dqn_model.h5')
    if self.epsilon == 0.0:
       self.update_network_parameters()
    return new_model

def update_network_parameters(self):
    self.model.set_weights(self.new_model.get_weights())

I try to run the evaluation step by creating the new_model as follows:
new_model = agent.load()

but the new_model doesn't have any method like predict.
Comment: So you can't run `new_model.predict()`. Apologies as I am unfamiliar with keras, but is load_model something from keras?
Comment: @user1558604 Yes. It's already imported from `keras.models`
Comment: How were you trying to run predict? You wouldn't run it on the `load` object, but instead the model that you loaded (`new_model`)
Comment: @user1558604 sorry for the typo. I edited that.
Comment: That seems unlikely to me given that the documentation says that `load_model` returns a `Model` instance and that `Model` instances have a predict method. Can you print the results of `dir(new_model)` and include that in the question?
Answer: Ensure you have Model imported within the class your calling agent.load from.
from keras.models import Model

Also, for me personally, model.predict doesn't show up within Intellisense so make sure that code actually doesn't compile when you run it. If so tell us what the exception error is.


should react services have static methods

Question: Should a react class that makes api call (a service) use static methods?
Eg:
class ProductService{
    static getAllProducts(){ return fetch(...)}
    static saveProduct(){ return fetch(...)}
    ...
}

Or should I create an instance eg. (new ProductService()).getAllProducts
Or Should I use a singleton pattern
I would rather use static methods because they are simpler and potentially faster. Also, it does not make sense to instantiate a class if there is no state specific to the instance.
Comment: Is that Java code?
Comment: It's typescript code
Comment: I removed the public modifier - so it's no longer typescript code. It's just JavaScript now
Comment: @Héctor Java code should have the return type on the method
Answer: Short answer:
Just put your functions for one service in a file my-service.js or my-service.ts and use:

import {myFunction} from "../services/my-service.js.

Long answer :
Static functions are not a good solution because they will be hard to mock if testing.
Without static, classes with only methods, like you are trying to do, raise ESLint error: class-methods-use-this on most methods for a service without state. The solution would be a singleton pattern for your classes. But it would be more work.
Just don't use a class.
So 2 solutions. First if your functions dosen't need states. Just add your functions in a JS file and import them.
In real use cases, most of them will need to update the state. So you will need to create custom hooks and contexts.
That's how services are done in React.
For example, to create a service with all your API calls to modify the list "products". You put the list in a context. And functions like fetchProduct in the hook. You will then have useProduct.js and ProductContect.js.
This allows to organize your code in multiple services.


document.getElementById giving Null by JS not by HTML

Question: When I am defining my input tag in html and accessing in JS by id then I am getting my tag.
HTML Code:
<input class="easyui-combobox" name="language" style="width:30%;" id= "XX">

JS Code:
var cc = document.getElementById("XX");

Here things are fine.
But When I am creating from javascript and trying to access I am getting. I want dynamic So I need to create from JS.
JS Code:
var input = document.createElement("input");
input.className = 'easyui-combobox';
input.style = 'width:30%';
input.id = "XX";

Here I am getting null after applying this:
var cc = document.getElementById("XX");

Answer: You have to append your created element into the document using document.body.appendChild(input);

var input = document.createElement("input");
input.className = 'easyui-combobox';
input.style = 'width:30%';
input.id = "XX";
document.body.appendChild(input);
console.log(document.getElementById("XX"));
Answer: You have not appended your element
var input = document.createElement("input");
input.className = 'easyui-combobox';
input.style = 'width:30%';
input.id = "XX";
document.body.appendChild(input);

var cc = document.getElementById("XX");
console.log(cc);

Answer: You need to append input element to document
var input = document.createElement("input");
input.className = 'easyui-combobox';
input.style = 'width:30%';
input.id = "XX";
document.body.appendChild(input);

Answer: You have created your element using -
var input = document.createElement("input");

Now you need to append it to HTML so that you can find it on DOM.

var input = document.createElement("input");
input.className = 'easyui-combobox';
input.style = 'width:30%';
input.id = "XX";
document.body.appendChild(input);

var fetchedElement = document.getElementById("XX");
console.log(fetchedElement);

createElement() creates an Element Node.
appendChild() adds your element node to DOM.
Answer: The element has been created, but needs to be appended to the DOM.  Use the
appendChild() or insertBefore() method.
var input = document.createElement("input");
input.className = 'easyui-combobox';
input.style = 'width:30%';
input.id = "XX";
document.body.appendChild(input);


human_time from posts within a post

Question: I am using a plugin which calls some posts grouped from a tag into another post. I want to add human_time to these posts, but the method I've used below just calls the time for the parent post.
if ($date) {
    $output .=  __('on ', 'posts-by-tag');
    $output .=  mysql2date(get_option('date_format'), $post->post_date) . ' at ' ;
    $output .=  mysql2date(get_option('time_format'), $post->post_date) . '' ;
    $output .=  human_time_diff(get_the_time('U'), current_time('timestamp')) . ' ago

' ;

The two middle outputs work properly, just the last one doesn't. What would be the required changes on that last output to get it to work? I'm guessing it's something to do with $post-> but I'm not sure of the right structure.
Answer: If this isn't in "The Loop" you'll have to target the post id in your get_the_time function like:
    $output .=  human_time_diff(get_the_time('U',$post->id), current_time('timestamp')) . ' ago

' ;

human_time from posts within a post


Python: Move dictionary within a class - with class methods as values - to another file

Question: I have a class that handles a TCP connection, and when receiving a message with a given "ID", I need to call a specific function to handle it. These IDs are just numbers, so I've created an IntEnum to hold the IDs:
class ID(IntEnum):
    # ...
    message_x = 20
    message_y = 21
    # ...

These IDs are not necessary contiguous (i.e. some IDs are reserved), and I expect to end up having hundreds or even thousands of IDs.
Because I don't want to create a thousand if - elses for each and every single ID, I was thinking of using the IDs as keys in a dictionary containing references to the functions that handle each message:
class ComManager:

    def __init__(self):
        # Init socket, message queues, threads for sending/receiving etc...
        self.rcv_functions = {#...
                              ID.message_x: ComManager._rcv_message_x,
                              ID.message_y: ComManager._rcv_message_y,
                              #...
                              }
        # Launch _rcv_thread here

    def _rcv_thread(self):
        message_id = self.rcv_message_id() # receive message ID from socket
        message_id = ID(message_id) # Change from type "int" to type "ID"
        self._rcv_functions[message_id](self) # Call appropriate method according to the dictionary, thus avoiding a massive if/else here or "switch case"-like workarounds

    def _rcv_message_x(self):
        # Handle reception and processing of message x here

    def _rcv_message_y(self):
        # Handle reception and processing of message y here

I've been trying to place "_rcv_functions" into its own file as it's already annoying enough to have a function per message:
# import ID and ComManager classes from their respetive files

_rcv_functions = {
    # ...
    ID.message_x:  ComManager._rcv_message_x,
    ID.message_y:  ComManager._rcv_message_y,
    # ...
}

Then, in ComManager:
class ComManager:
    def __init__(self):
        # Init socket, message queues, threads for sending/receiving etc...
        from x import _rcv_functions

This obviously results in a circular dependency.
I've been searching for a solution to this problem and some people have suggested type hinting, but I haven't been able to get it working in this case.
I've also seen some answers suggesting the use of something like __import__('module_name').ComManager.class_method for each dictionary value but I've read that this would heavily impact performance as the whole file would be processed each time I called __import__, which is far from ideal since the dictionary will contain hundreds of entries.
Comment: Currently `ComManager` worries both about what `_rcv_functions` contains as well as starting a thread for a particular RCV function. Try to separate these responsibilities. For example, you can make an `RCVFactory` that holds the `_rcv_functions` `dict`. This factory, given an ID, will return an RCV function. You should then pass this RCV function to `ComManager` directly. This also avoids the circular dependency. Type hinting won't be able to change anything here to avoid this circular dependency, it would be added for maintainability reasons instead.
Answer: Have you even tried it?
If you place the import statement inside the __init__ method as you show above, there will be no "circular dependency": at the point the other module is imported by the first time, the caller module, where ComManager is defined had already run, and the class is defined and ready to be imported in the second module.
Other than that, you can just put the handling methods in a mixin class, instead of in the body of the handler ComManager itself.
So, in the other module, you'd have:

...
class ID(IntEnum):
    ...

class HandlersMixin:
    def _rcv_message_x(self, msg):
        ...
    ...

mapping = {
  ID.message_x = HandlerMixn._rcv_message_x,
}

Note that in this way, the mapping maps the unbound methods: they are plain functions that expect an instance of "HandlerMixin" as their first parameter
And on your first module:
from other_module import ID, mapping, HandlerMixin

class ComManager(HandlerMixin):
    def _rcv_thread(self):
        message_id = self.rcv_message_id() # receive message ID from socket
        message_id = ID(message_id) # Change from type "int" to type "ID"
        mapping[message_id](self)
        # Passing "self" explictly will make the methods work the same
        # as f they were called from this instance as `self.method_name`,
        # and since they are methods on this class through inheritance
        # they can use any other methods or attributes on this instance

Comment: I did try it but it didn't work.. weirdly enough, after stepping a few hours away from this and trying it again it now worked and I feel dumb. I guess I was doing something else wrong. Anyways, I've never heard about mixins and passing the base class' self to mixin's method is such an elegant solution, I never would have thought about that coming from a C/C++ background! Thank you.


input[type="submit"] in jQuery

Question: how to do this:
input[type="submit"] {
   color:green;
}

in jQuery?
$('input[type="submit"]').css("color","green");

is not working :|
Comment: **instead of downvoting , just suggest to close this question as too localized. Is it that hard to remember ? he is new here**
Comment: Works for me: http://jsfiddle.net/Blender/JRMhM/
Comment: This should work, however you can try [`:submit`](http://api.jquery.com/submit-selector/) selector
Comment: I recommend to read the [jQuery tutorial](http://docs.jquery.com/Tutorials:Getting_Started_with_jQuery) to get you started: *"As almost everything we do when using jQuery reads or manipulates the document object model (DOM), we need to make sure that we start adding events etc. as soon as the DOM is ready. To do this, we register a ready event for the document."*. Then familiarise yourself with the API by reading http://api.jquery.com/.
Answer: Probably because it is triggering before jQuery is "ready". Try this:
$(function() {
    $('input[type="submit"]').css("color","green");
});

Comment: If you want to have access to the event, use `$(document).ready(function(event) {});` instead of `$(function() {});` I found my version more clear.
Answer: Use a simple css instead of javascript
input[type="submit"]{
        color: green;
        cursor: pointer;
        font: bold 12px Helvetica,Arial,sans-serif;
    }

Answer: But the jquery must load it before this
You can also do this by adding the id or class in submit
 $('#submit_id/.submit_class').css("color","green");

Answer: Try adding this:
$("form").submit(function(event) {
   event.preventDefault();
});

It may be that your original code is working, but since the page re-loads normally when you click on a submit button in a form, that action is preventing you from seeing your change.
Comment: This is a good example of why you want to use `.someThing(function(event) {})` to have access on the event itself.

input[type="submit"] in jQuery


Adding class object with multiple Arrylists

Question: hi i am trying to add the class object with arrylists and need to display it in json format i used gson library for json format and iam tring to bind the java object into jsonformat has below
" {"type": "record","name": "Doc","doc": "adoc","fields": [{"name": "id","type": "string"}, {"name": "user_friends_count","type": ["int", "null"]}]"

and these the following classes and main method
public class RootFields {
public String type;
public String name;
public String doc;

}
public class Fields {
public String name;
public String type;

}
and this is my main method
public class JavaToJson{

    public static void main(String[] args) {
        // TODO Auto-generated method stub
RootFields root = new RootFields();
List<Fields> F2 = new ArrayList<Fields>();
Fields F1 = new Fields();
Fields Fields1 = new Fields();
Fields Fields2 = new Fields();
root.type = "record";
root.name = "Doc";
root.doc = "adoc";
F1.name = "id";
F1.type = "string";
Fields1.name = "user_friends_count";
Fields1.type = "int";
Fields2.name = "user_location";
Fields2.type = "int";
GsonBuilder builder = new GsonBuilder();
Gson gson = builder.create();

root.F2.add(F1);
System.out.println(gson.toJson(root));

    }

}

it shows me compile error F2 cannot be resolved or is not a field at F2 in "root.F2.add(F1)" where am i going wrong please help out thanks in advance.
Comment: Yeah `root` is a `RootFields` it does not have a `F2` field
Answer: You have not declared F2 as a field in RootFields. Though from what I understand, you should use either a List or an array, not several fields for each instance of Fields.
Answer: class RootFields {
    public String type;
    public String name;
    public String doc;
    List <Fields> filelds = new ArrayList<>();
}


Standard and Polar Coordinate Conversions on $S^1$

Question: I'm having a little trouble formalizing the idea of using "ambient standard coordinates" on level sets of $\mathbb{R}^n$. For example, we typically write $S^1=\{(x,y)\in\mathbb{R}^2:x^2+y^2=1\}$, which can be seen as the (regular) level set $f^{-1}(1)$ associated to the smooth function $f(x,y)=x^2+y^2$. From what I understand, we can view these $x,y$ as the coordinate functions that come from the standard coordinate chart $\varphi$ on $\mathbb{R}^2$.
Suppose I wanted to define a vector field $X$ on a (connected) open subset of $S^1$. In this case, I'd be working with the usual angle coordinate $\theta:U\longrightarrow \mathbb{R}$, and so this vector field can be written on $U$ as $X_p=h(p)\frac{d}{d\theta}$. Essentially, what formally/rigorously allows us to also express this vector field as (say) $$X_p=y\frac{\partial}{\partial x}-x\frac{\partial}{\partial y}$$
using the standard coordinates on $\mathbb{R}^2$? The angle coordinate $\theta:U\longrightarrow \mathbb{R}^1$ has one coordinate function, so I'm not sure how we can apply the change of coordinates formula in Lee's Introduction to Smooth Manifolds (see pg. 63), since $\varphi=(x,y):\mathbb{R}^2\longrightarrow\mathbb{R}^2$ has two coordinate functions. I suppose I'm intuitively comfortable working with these standard coordinates (say, in the sense of multivariable calculus), but I think it would be especially helpful for my understanding how this intuition is formalized.
A small footnote: when I expressed $X_p$ in terms of standard coordinates, I was using the fact that $T_pS^1$ consists of vectors which are orthogonal to the point $p=(x,y)$. I'm able to see why I can do this by examining $\ker df_p$.
Comment: The main idea is that for any point $p \in \mathbb{S}^1$ we can view $T_p \mathbb{S}^1$ as a subspace of $T_p \mathbb{R}^2$ (see the section "The Tangent Space to a Submanifold" in the book of Lee that you have cited) and of course since $\mathbb{S}^1 \subset \mathbb{R}^2$ we can describe $p$ by its Cartesian coordinates as well. This is more of a "change of frame" then it is a "change of coordinates".
Comment: @jd27 thank you for the reference. I'm taking a look at Proposition 5.37, in which he shows that $T_pS^1=d\iota_p(T_pS^1)$ is spanned by $\left.\frac{\partial}{\partial x}\right|_p$. Is this "change of frame" procedure just the identification of $\left.\frac{d}{d\theta}\right|_p$ with $\left.\frac{\partial}{\partial x}\right|_p$ via $d\iota_p$? Also, while we can certainly describe $S^1$ using standard coordinates, technically $x,y$ do NOT form a coordinate chart for $S^1$, right? I'm interpreting them as convenient functions which encode points on $S^1$, yet do not form charts for $S^1$.
Comment: What is the definition of $\left.\frac{\partial}{\partial x}\right|_p$ as an element of $T_pS^1$ here? Using the standard embedding of $S^1$ in $\Bbb R^2$ to consider $T_pS^1$ to be a subspace of $T_p\Bbb R^2, \left.\frac{\partial}{\partial x}\right|_p$ is only going be in that subspace when $p = (0, \pm 1)$. Is this proposition only applicable to those two points, or in claiming that $\left.\frac{\partial}{\partial x}\right|_p$ spans $T_pS^1$, are you referring to the span of its projection into that subspace?
Comment: @PaulSinclair my apologies, I believe I conflated the slice coordinates being used in the proof of Proposition 5.37 with the standard coordinates used on $\mathbb{R}^n$. I think I'm just looking to understand how one should rigorously view this "change of frame" procedure. For example, I'll oftentimes see vector fields $X$ (on $S^1$, say) written with component functions in $\theta$ (at a point $p=(\cos\theta,\sin\theta)$), but with $\partial/\partial x$ and $\partial/\partial y$ as the chosen basis vectors for the coordinate representations of $X$, so that 2 coordinate systems are being used.
Comment: As I noted in my previous comment, $T_pS^1$ can be indentified with a subspace of $T_p\Bbb R^2$, so yes, it is possible to express the elements of $T_pS^1$ in terms of the basis $\left.\frac{\partial}{\partial x}\right|_p, \left.\frac{\partial}{\partial y}\right|_p$ of $T_p\Bbb R^2$. Because $T_pS^1$ is one-dimensional, the span of any non-zero vector in it is the entire space, so it is not necessary for two vectors to be the same to both span the space.
Answer: With respect to a local chart $(U,\theta)$ of $S^1$ and the global chart $\mathrm{id}=(x,y)$ of $\mathbb R^2$, the standard inclusion $i:S^1\to \mathbb R^2$ looks like
$$(x,y)(i(p))=(\cos(\theta(p)),\sin(\theta(p))).$$
This embedding induces a tangent map $Ti:TS^1\to T\mathbb R^2$, whose restriction to $TU\subseteq TS^1$ looks like
$$Ti\left(a\frac{\partial}{\partial \theta}\bigg|_{p}\right)=
a\left(
-\sin\theta(p)\frac{\partial}{\partial x}\bigg|_{i(p)}
+
\cos\theta(p)\frac{\partial}{\partial
y}\bigg|_{i(p)}
\right).$$
This map is injective at every point $p$ of $u$, and it is the identification of $T_pS^1$ with a subspace of $T_{i(p)}\mathbb R^2$ that jd27 was talking about.
Comment: This is super helpful; thank you!
Comment: I have one small question (my apologies, I completely missed this when I first accepted your answer): shouldn't the coordinate rep. of $Ti$ evaluated at $a\frac{\partial}{\partial\theta}|_p$ have coordinates $-\sin\theta(p)$ and $\cos\theta(p)$ (rather than $\cos\theta(p)$ and $\sin\theta(p)$)? At least according to Lee, Eq. 3.10, it seems like $di_p\left(\frac{\partial}{\partial \theta}\right)=\frac{\partial \hat{i}^1}{\partial\theta}\frac{\partial}{\partial x}+\frac{\partial \hat{i}^2}{\partial\theta}\frac{\partial}{\partial y},$ where $\hat{i}^j$ is the $j$-th component of $(x,y)(i(p))$.
Comment: @LiminalSpace glad to be helpful. About your second comment, of course you are right. I edited the post already. Thanks for noticing.


Help with uninstalling GRUB

Question: I have once installed Ubuntu on my Desktop. I dual booted it with Windows 10. My brother was messing with my disk manager and deleted my ubuntu drive. (un-installed it).The thing is GRUB remains and i want to get rid of.
BTW:I can boot into Windows 10.
Comment: If you still can boot Windows, then it must be UEFI. http://askubuntu.com/questions/63610/how-do-i-remove-ubuntu-in-the-bios-boot-menu-uefi
Comment: Please [edit] your question and help us help you! Where did you install grub when you installed it?
Comment: Uninstalling grub won't solve the problem at hand. What you need is to reinstall the Windows bootloader, which will overwrite grub.
Answer: Grub is a Boot Manager.  You can install a different Boot Manager to replace Grub.  In your case, you can install the Windows Boot manager by running the Windows Install Boot.  When you run the Windows Install program it should detect Windows and give you the option to repair it.
If there is problems with the integrity of your Windows installation you'd have to get help from a group that support Windows.  Consider creating a new issue in a forum that supports Windows... http://superuser.com
Answer: You'll need Windows 10 Installation or Recovery Media for that.
Creating Recovery Media
This is entirely optional if you have Windows Installation Media

Boot into your Windows 10 install.
Open the start screen, type recoverydrive.exe and hit enter.
Plug in your USB Drive and click on next.
Choose the USB Drive from Available drives and click next.
Click on create.

Installing Windows Bootloader

Restart your PC with the Windows installation media or Recovery media selected as the first boot device.
When Windows setup loads up, choose Repair your computer.
Click on Troubleshoot on the Choose an option page.
Choose Advanced Options and finally Command Prompt. Type the following command in the command prompt window:

bootrec.exe /fixmbr`

After it is successfully done, restart your system and it should be good to go with Windows booting up normally

Reference
https://www.techmesto.com/uninstall-linux-grub-dual-boot-windows8/

Help with uninstalling GRUB


Error when display a version of react-native

Question: When I check a version of react-native the error outputs like this:
<code>   react-native -v
fs.js:114
    throw err;
    ^

Error: EPERM: operation not permitted, chmod '/usr/local/lib/node_modules/react-native/node_modules/@react-native-community/cli/build/commands/server/external/xsel'
    at Object.chmodSync (fs.js:1027:3)
    at Object.<anonymous> (/usr/local/lib/node_modules/react-native/node_modules/@react-native-community/cli/build/commands/server/copyToClipBoard.js:50:15)
    at Module._compile (internal/modules/cjs/loader.js:778:30)
    at Object.Module._extensions..js (internal/modules/cjs/loader.js:789:10)
    at Module.load (internal/modules/cjs/loader.js:653:32)
    at tryModuleLoad (internal/modules/cjs/loader.js:593:12)
    at Function.Module._load (internal/modules/cjs/loader.js:585:3)
    at Module.require (internal/modules/cjs/loader.js:692:17)
    at require (internal/modules/cjs/helpers.js:25:18)
    at Object.<anonymous> (/usr/local/lib/node_modules/react-native/node_modules/@react-native-community/cli/build/commands/server/middleware/copyToClipBoardMiddleware.js:8:47)

</code>
Comment: Which OS are you using?
Comment: @Neeeko Linux, ubuntu
Comment: have you tried reinstalling `npm install -g react-native-cli` to fix the permissions?
Answer: <code>You have a permission error it seems ¯_(ツ)_/¯

or

Now clean the project...

cd android
gradlew clean
</code>
Comment: Why I need clean the project? This is not working, even I wrote in none project folder
Comment: npm install    or    npm install  -g react-native-cli   or react-native upgrade or npm install react-native@letest_version


How To Update a UILabel as text is being typed in a UITextField

Question: This is my first post to StackOverflow and I am also new to Xcode and Objective-C.
I have read about delegates and I have also experimented with other peoples code.  However, I wanted to see if I could create something myself that uses delegates without the aid of copying someone else's code.
What I am trying to do, to understand delegates, is to get a UITextField delegate to update a label every time a user types a key on the keyboard.
I created a xib file and connected a TextField to a UITextField *myTextField and a Label UILabel *myLabel in my .h file.
I also added  to the .h file of my ViewController Class.
However, I'm not sure what delegate method to use because the optional ones I can use as listed in the UITextFieldDelegate.h only seem to be able to update after Editing is finished.  Also I'm not sure if I should put the AppDelegate method in the .h file associated with my xib or the AppDelegate.h file.
I would appreciate any help with some direction on this.
Answer: You can add your UIViewController as a notification observer on the UITextField like so:
<code>[textField addTarget:self action:@selector(textFieldDidChange:) forControlEvents:UIControlEventEditingChanged];

- (void)textFieldDidChange:(UITextField *)textField {
}
</code>
Answer: So if you have a UITextField myTextField linked to your nib IB TextField object, and a UILabel myLabel linked to your nib IB Label object and you've made your Textfield point to your files owner then try this to see if it helps.
I just typed this up quickly, and I didn't test it, so check it for errors first.
<code>// ViewController.h
@interface ViewController : UIViewController <UITextFieldDelegate> {
    IBOutlet UILabel *myLabel;
    IBOutlet UITextField *myTextField;
}
@property (nonatomic, retain) UILabel *myLabel;
@property (nonatomic, retain) UITextField *myTextField;
@end

//  ViewController.m
- (BOOL)textField:(UITextField *)textField shouldChangeCharactersInRange:(NSRange)range replacementString:(NSString *)string
{
    myLabel.text = myTextField.text;
    return YES;
}
</code>
Comment: This is a workaround, whereas you should use the `UITextInput` protocol
Comment: is there an applescript objc version for this? thank you
Answer: <code>import UIKit

class ViewController: UIViewController , UITextFieldDelegate {
    // Create a label Outlet
    @IBOutlet weak var label: UILabel!
    // TextField Outlet
    @IBOutlet weak var textField: UITextField!
   // Select the textfield and in connection inspector drag a action from editing changed to the source code
    @IBAction func changed(_ sender: Any) {
       // Set text to label
        label.text = textField.text
        }
    override func viewDidLoad() {
        super.viewDidLoad()
        //Delegate to self
        textField.delegate = self
        textField.autocorrectionType = .no
    }
    // Implement the protocols
    func textField(_ textField: UITextField, shouldChangeCharactersIn range: NSRange, replacementString string: String) -> Bool {
        return true
    }
    func textFieldShouldReturn(_ textField: UITextField) -> Bool {
       textField.resignFirstResponder()
        return true
    }}
</code>
Comment: Basically you need an action and the protocol that correspond to it
if you wanna set the value to a instance variable you can do it in a action of didEndEditing but you must implement `code` textFieldDidEndEditing `


change the margin on each slideToggle() call by x%

Question: I want to reduce my containers magin step by step when using slideToggle()

$(document).ready(function() {
  $("#btn").click(function() {
    doIt();
  });
});

function doIt() {
  var container = $("#c2");
  var maxMarginTop = container.css("marginTop").replace('px', '');
  var maxMarginBottom = container.css("marginBottom").replace('px', '');

  container.slideToggle({
    duration: 2000,
    progress: function(animation, progress, remainingMilliseconds) {
      var newMarginTop = maxMarginTop - (maxMarginTop * progress);
      var newMarginBottom = maxMarginBottom - (maxMarginBottom * progress);

      container.css("margin-top", newMarginTop);
      container.css("margin-bottom", newMarginBottom);
    },
    complete: function() {
      container.remove();
    }
  });
}
.container {
  margin-top: 20px;
  margin-bottom: 20px;
  height: 20px;
  width: 100px;
  background: red;
}

<button id="btn">Do it</button>

I have to execute code on each step within the slide function. I calculate the new margin based on the current progress.
So the margin should go from 100% to 0% represented by the progress.
Within the progress function I calculate the new margin and when logging the new values this works fine.
But as you can see nothing happens. When logging the margin value in the complete function nothing changed.
Is it a wrong scope? What is happening there?
Answer: The problem with your code is that you have added both top and bottom margin which causes a collapsing margin - ie you only get 20px of margin.  Therefore, you may as well start off with one margin and then it will animate properly
Why not do this with css animation:

$(document).ready(function() {
  $("#btn").click(function() {
    $("#c2").addClass('closed');
  });
});
.container {
  margin-top: 20px;
  /* do not need the bottom margin due to collapsing margins */
  height: 20px;
  width: 100px;
  background: red;
  transition: all 2s ease;
}

.container.closed {
  height:0;
  margin:0;
}

<button id="btn">Do it</button>

If you want to carry on using js animations, just remove one of your margins:

$(document).ready(function() {
  $("#btn").click(function() {
    doIt();
  });
});

function doIt() {
  var container = $("#c2");
  var maxMarginTop = container.css("marginTop").replace('px', '');
  var maxMarginBottom = container.css("marginBottom").replace('px', '');

  container.slideToggle({
    duration: 2000,
    progress: function(animation, progress, remainingMilliseconds) {
      var newMarginTop = maxMarginTop - (maxMarginTop * progress);
      var newMarginBottom = maxMarginBottom - (maxMarginBottom * progress);

      container.css("margin-top", newMarginTop);
    },
    complete: function() {
      container.remove();
    }
  });
}
.container {
  margin-top: 20px;
  height: 20px;
  width: 100px;
  background: red;
}

<button id="btn">Do it</button>


Function that receives 2 possibles parameters

Question: I have a function that serves to create users, but I have defined two models "users" and "demo users" so I have two different models.
The models have similar and different properties, but for example they have properties such as "email" that are common.
The function has this structure, I receive as a parameter an object "User" but I would like you to receive an object "User" or an object "DemoUser"
public function createLogin(User $user)
{
...
}

I do not know if this would be the subject of injecting dependencies ...
Thank you and I await your comments
Comment: why are you not using the built-in authentication in laravel? `php artisan make:auth` will generate the auth system for you.
Comment: Does one of your models extend the other? eg "Demo Users" extend "Users" ?
Answer: Solely on the question of allowing the method to accept both User and DemoUser types, you can setup an Interface class that both User and DemoUser may implement.
Hope that helps.
Answer: What you're trying to do can be achieved using interfaces or abstract classes. Create an interface and implement it in the two models or create an abstract class and extend it from your two users class. Then when passing the argument, use the interface or the abstract class as the type hint e.g
public function createLogin(UserInterface $user) {

}

Answer: You can do something like this,
public function createLogin($user)
{
    if (is_a($user, 'App\User'))
    {
       // Create your user here
    }
    elseif(is_a($user, 'App\DemoUser'))
    {
     // create demo user here
    }
}

Comment: That does not sound good. What if there are many more subinstances?
Comment: @NicoHaase Thank you. But the asker said "I would like you to receive an object "User" or an object "DemoUser"."
Answer: One of the ways is to extend the class that has the createLogin method, and rewrite that method with:
public function createLogin($user)
{
    if ($user instanceOf User) {
        parent::createLogin($user)
    }
    if ($user instanceOf DemoUser) {
        // Login logic for DemoUser
    }
}

*Let me know if you have any questions
Comment: Why not use inheritance? Why should a `createLogin` method know about single instances of a user?
Comment: @NicoHaase I suppose that's another way of doing it. Add that answer for the asker please.
Comment: There is no need to duplicate the answer of LC Yoong while the OP does not share more information


How to query Cosmos DB with dashes in container name

Question: In my database I have a container named "freedom-fighters".
Doing  SELECT * FROM [freedom-fighters] does not work. Neither does SELECT * FROM "freedom-fighters", nor SELECT * FROM ["freedom-fighters"], nor anything else I have tried.
I am working in the web gui.
Comment: My solution was that a query runs in the context of a container and I, hence, don't have to (cannot?) specify container.
Answer: When you query via Core/SQL API, you don't need to specify the exact collection name.  In the Portal you can  use a simple alias to query. For example,
SELECT * FROM c

Cosmos DB will know which one you are targeting already and c will be something like an alias.
Comment: FYI the question is an exact duplicate of [this one](https://stackoverflow.com/questions/46719930/how-to-use-sql-query-with-hyphen-in-collection-name/46721189#46721189) - please vote accordingly.
Comment: Agree. I have read that question but didn't thinkt it applied to me. After finding the answer I understand it does. My bad.


MYSQL SELECT returns nothing on FK field with NULL values

Question: I am trying to make some sort of tree with database using foreign keys. So, there is an example:
CREATE TABLE tree (
   id INT(11) UNSIGNED NOT NULL AUTO_INCREMENT,
   pid INT(11) UNSIGNED NULL DEFAULT NULL,
   title VARCHAR(255) NOT NULL,
   PRIMARY KEY (id),
   CONSTRAINT TheTree FOREIGN KEY (pid) REFERENCES tree (id) ON UPDATE NO ACTION ON DELETE CASCADE
) ENGINE=InnoDB;

#insert sample data with 2 root nodes and 2 subnodes
insert into tree (id, pid, title) values
     (null, null, 'test title 1'),
     (null, null, 'test title 2'),
     (null, 1,    'test title 1-1'),
     (null, 2,    'test title 2-1');

select * from tree where pid = null
# it returns nothing.

Here goes sqlFiddle example.
I just didn't get it. Why i can't get my root nodes with NULL values? How can i deal it?
Comment: `pid = null` does nothing you need to use `pid is null`
Answer: You have to use is nullinstead of = null:
select * from tree where pid is null

Comment: You would need to add a `OR` to your `WHERE` clause: `SELECT * FROM tree WHERE pid IS NULL OR pid = @val;` or use the `COALESCE` function to convert it to a unused value: `SELECT * FROM tree WHERE COALESCE(pid, 'NULL') = @val;`
Comment: That's fine! But, what is i have to use NULL value as a variable? `$someVar = 'NULL' `; query('select * from tree where pid = $someVar')...`


How do I share my Glue Catalog with another account via Lake Formation?

Question: I have created the Glue table in my source account. I then went to Lake Formation and shared the table with the target account.
When I go to Lake Formation in my target account, I do not see the shared table. Based on the documentation here (https://docs.aws.amazon.com/lake-formation/latest/dg/viewing-available-shared-resources.html), it should automatically appear.
Am I missing something?
Answer:
Go to Lake Formation in the source account and grant the External Account (target account) access to your database/table

In the target account, go to Resource Access Manager and approve the resource share request

At this point the database/table will show up in the Lake Formation console. If you want to query it from Athena/Spectrum, you need to:

Go to Lake Formation and Create Table via a Resource Link. The source should be the shared table.

Documentation: https://docs.aws.amazon.com/lake-formation/latest/dg/cross-account-read-data.html
Comment: I had been strugggling to figure out step 3 thank you very much. My org has already setup Step 2 so I did not have to do that. Much appreciated!
Answer: Just to add to @Melissa answer. If you are using a tag based access control, you don't need the Resource Access Manager(RAM) part. Basically assigning tags to the database and tables you want to share, and grant the external account permission access to the tags should work.
Please refer to AWS detailed documentation as this will give you a more comprehensive guide on how to set it up.


When using MobX is it better to have more small stores, or fewer large stores?

Question: I prefer splitting logic and having more stores that each manage specific sets of data, but are there any performance considerations I should keep in mind when architecting my MobX state?
Is it generally considered better practice to use more small stores, or fewer large stores? Is there any performance difference between the two?
Comment: This is a non-answer, but don't optimize prematurely. Do what makes the most logical sense for the application. Mobx is generally going to have a negligible performance impact in any case.
Answer: yes you should use more small stores,sometime you should combination of them
<code>class LargeStore{
  aStore= new AStore()
  bStore= new BStore()
  ...
}
</code>


Convert List into another List that contains another List

Question: I have a list of Foo:
class Foo {
    public int Id { get; set; }
    public String Name { get; set; }
}

And I want to convert it to a list Bar:
class Bar {
    public int Id { get; set }
    public List<String> NameList { get; set; }
}

The data in Foo looks like this:
Id     Name
-----------
1      Foo1
1      Foo2
1      Foo3
2      Foo3
2      Foo2
2      Foo1

And I want it to look like this:
Id      NameList
----------------
1      Foo1
       Foo2
       Foo3
2      Foo3
       Foo2
       Foo1

I'm doing this so it will be easier to display in a Razor rendered Html unordered list.
Also, if there is an easy way to do this without conversion, please let me know.
Ultimately, I will display the Html like this:

1

Foo1

Foo2

Foo3

2

Foo3

Foo2

Foo1

So far I've tried the following Linq code, but it didn't work
BarList = FooList.Select(x => new Bar() {
    Id = x.Id,
    NameList = x.Select(y => y.)
}).ToList();

Comment: Check out LINQ's `GroupBy` statement, it does exactly this. https://msdn.microsoft.com/en-us/library/bb545971.aspx
Comment: You need `GroupBy`, absoutely.  But you may want to clarify your expected output, it doesn't really make sense.
Comment: Whoops! I misunderstood the question at first. Have a "GroupsOf" implementation anyway: http://ideone.com/Z4mNWp
Answer: Use GroupBy.
List<Bar> BarList = FooList.GroupBy(f => f.Id, f => f.Name, (id, names) => new Bar
{
    Id = id,
    NameList = names.ToList()
}).ToList();


Text not showing up in flex-row

Question: My outer div has d-flex flex-row and I have three sub divs total. Two of them are btn-group and the other one is a div with text. I have all this in another div that I have class center-block. To get these sub divs to show, I have made them z-index: 1. The buttons are showing up but not the text.

Hello

Comment: I can't really add my code here because I'm not allowed to. If you could give me a simple example that would be fine. I think I'm just missing the logic here. I just need three things on the flex-row. The three buttons in the left side of the row and the text centered with in that row.
Answer: Since Bootstrap 4 beta3, .center-block has been dropped, in favor of .mx-auto: https://getbootstrap.com/docs/4.1/migration/#utilities. But since you haven't mentioned what you expect with putting .center-block on everything, I didn't include that in my fiddle.
The text is showing up without the help of z-index.
Fiddle: http://jsfiddle.net/aq9Laaew/104420/
Comment: Thanks for putting this together. However, this is not really what I'm looking for. I will look into mx-auto which I have not researched yet.
Comment: Then tell us what you are looking for and expectation with the help of '.center-block'

Text not showing up in flex-row


SQL match comma separated strings

Question: I'm wondering how to perform the following select query in PHP/MySQL.
The MySQL field is called 'types' and contains values like this: Provincie\,Gebied\,Water\ or Water\,Plaats\
Then in PHP, I receive a string that's formatted like this: $types = 'Plaats, Provincie, Gebied, Water'
What I would like to do is select every row that contains at least one of the values that's in the PHP array.
Any Thoughts about the best way to do this?
Edit
I can't add another table to the DB, although it would be a nice option.
Which doesn't return any columns is this:
$types = explode(',', $types);
    $typesSQL = '';
    foreach($types as $type){
        $type = str_replace(' ', '', $type);
        $typesSQL .= "FIND_IN_SET('$type', types) OR ";
    }
    $typesSQL = substr($typesSQL, 0, -3);
SELECT * FROM ".$wpdb->prefix."ttr_results WHERE user_id = $user_id AND area = '$area' AND content = '$content' AND ($typesSQL) ORDER BY datetime DESC

Comment: Normalise and restructure your database to provide a 1-many relation between your existing table and a new types table
Comment: Well, that's the problem. I would prefer that too, but it isn't a real option for this project, can't add a new table.
Answer: You could have a look at the find_in_set() MySQL function
Comment: Thanks, I did. But FIND_IN_SET takes only a single string as argument, in fact I have would like to find any of the substrings in the string $types = 'Plaats, Provincie'
Comment: Ah yep, didn't see at first read that you had multiple values to check.
Doing the filtering in PHP is out of the question as you'll have too much processing to do for big resultset.
IMO Better option is what @mark-baker suggested : if you can do it, extract your types in a dedicated table
Comment: I did saw that comment. But onfortunalty I didn't have the option to create anothe table. Editing the existing table would be a option though I don't see how that could help, since the number of types to store varies.

SQL match comma separated strings


onclickListeners not working for two different ImageView

Question: I have two Images in my main activity where i want to display new activities for each image click. When I click on the first Image it starts the second activity(Image2.class) rather than starting the first activity(Image1.class). Why is this happening? I want to display Image1.class Activity when I click on image1. likewise Image2.class Activity when I click on image2.
public class MainActivity extends Activity   {

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

        ImageView image1 = (ImageView) findViewById(R.id.imageView1);

        ImageView image2 = (ImageView) findViewById(R.id.imageView2);

        image1.setOnClickListener(new View.OnClickListener() {

            @Override
            public void onClick(View v1) {
                // TODO Auto-generated method stub

                Intent intent1 = new Intent(MainActivity.this,Image1.class);
                intent1.putExtra("image1Desc", "Text Description for IMAGE1!!!!!!!!!");
                startActivity(intent1);
                finish();
            }
        });

        image2.setOnClickListener(new View.OnClickListener() {

            @Override
            public void onClick(View v2) {
                // TODO Auto-generated method stub
                Intent intent2 = new Intent(MainActivity.this, Image2.class);
                intent2.putExtra("image2Desc", "Text Description for IMAGE2!!!!!!!");
                startActivity(intent2);
                finish();
            }
        });
    }

    @Override
    public boolean onCreateOptionsMenu(Menu menu) {
        // Inflate the menu; this adds items to the action bar if it is present.
        getMenuInflater().inflate(R.menu.main, menu);
        return true;
    }

}

Main Activity XML
<RelativeLayout xmlns:android="http://schemas.android.com/apk/res/android"
    xmlns:tools="http://schemas.android.com/tools"
    android:layout_width="match_parent"
    android:layout_height="match_parent"
    android:paddingBottom="@dimen/activity_vertical_margin"
    android:paddingLeft="@dimen/activity_horizontal_margin"
    android:paddingRight="@dimen/activity_horizontal_margin"
    android:paddingTop="@dimen/activity_vertical_margin"
    tools:context=".MainActivity" >

     <ImageView
        android:id="@+id/imageView1"
        android:layout_width="wrap_content"
        android:layout_height="wrap_content"
        android:src="@drawable/a" />

      <ImageView
        android:id="@+id/imageView2"
        android:layout_width="wrap_content"
        android:layout_height="wrap_content"
        android:src="@drawable/b" />

</RelativeLayout>

Image1.class Activity XML
<RelativeLayout xmlns:android="http://schemas.android.com/apk/res/android"
    xmlns:tools="http://schemas.android.com/tools"
    android:layout_width="match_parent"
    android:layout_height="match_parent"
    android:paddingBottom="@dimen/activity_vertical_margin"
    android:paddingLeft="@dimen/activity_horizontal_margin"
    android:paddingRight="@dimen/activity_horizontal_margin"
    android:paddingTop="@dimen/activity_vertical_margin"
    tools:context=".Image1" >

    <TextView
        android:id="@+id/textView1"
        android:layout_width="wrap_content"
        android:layout_height="wrap_content"
        android:text="@string/image1text" />

    <ImageView
        android:id="@+id/imageViewZoom1"
        android:layout_width="wrap_content"
        android:layout_height="wrap_content"
        android:layout_marginTop="28dp"
        android:src="@drawable/a" />

</RelativeLayout>

Image2.class Activity XML
<RelativeLayout xmlns:android="http://schemas.android.com/apk/res/android"
    xmlns:tools="http://schemas.android.com/tools"
    android:layout_width="match_parent"
    android:layout_height="match_parent"
    android:paddingBottom="@dimen/activity_vertical_margin"
    android:paddingLeft="@dimen/activity_horizontal_margin"
    android:paddingRight="@dimen/activity_horizontal_margin"
    android:paddingTop="@dimen/activity_vertical_margin"
    tools:context=".Image2" >

    <TextView
        android:id="@+id/textView2"
        android:layout_width="wrap_content"
        android:layout_height="wrap_content"
        android:text="@string/image2text" />

    <ImageView
        android:id="@+id/imageViewZoom2"
        android:layout_width="wrap_content"
        android:layout_height="wrap_content"
        android:layout_marginTop="28dp"
        android:src="@drawable/b" />

</RelativeLayout>

AndroidManifest XML
<?xml version="1.0" encoding="utf-8"?>
<manifest xmlns:android="http://schemas.android.com/apk/res/android"
    package="com.example.imageanimation"
    android:versionCode="1"
    android:versionName="1.0" >

    <uses-sdk
        android:minSdkVersion="8"
        android:targetSdkVersion="17" />

    <application
        android:allowBackup="true"
        android:icon="@drawable/ic_launcher"
        android:label="@string/app_name"
        android:theme="@style/AppTheme" >
        <activity
            android:name="com.example.imageanimation.MainActivity"
            android:label="@string/app_name" >
            <intent-filter>
                <action android:name="android.intent.action.MAIN" />

                <category android:name="android.intent.category.LAUNCHER" />
            </intent-filter>
        </activity>
        <activity
            android:name="com.example.imageanimation.Image1"
            android:label="@string/title_activity_image1" >
        </activity>

        <activity
            android:name="com.example.imageanimation.Image2"
            android:label="@string/title_activity_image2" >
        </activity>
    </application>

</manifest>

Comment: the code seems ok .. check if you put correct image in xml
Comment: Post your xml also, you may have confused with the ids of Imageview's
Comment: will you show your xml ?
Comment: i've uploaded the xml
Comment: I've found the issue which is a simple matter.

imageView2 of MainActivity XML was overlapping on top of ImageView1 which is not visible. After I re-sized it the problem was solved. Thanks for trying to help
Answer: I've found the issue which is a simple matter.
imageView2 of MainActivity XML was overlapping on top of ImageView1 which is not visible. After I re-sized it the problem was solved.
In Main Activity XML
<ImageView
         android:id="@+id/imageView2"
         android:layout_width="200dp"
         android:layout_height="100dp"
         android:layout_alignLeft="@+id/imageView1"
         android:layout_below="@+id/imageView1"
         android:layout_marginTop="19dp"
         android:src="@drawable/b" />


How to enable death notices in console of CS 1.6?

Question: Recently I noticed that the death notices are not shown in my console. Normally, you see which bot/player killed which bot. But here it is only showing radio messages, and not death notices.
I guess something has changed but I don't know what.
Is there any command which can disable it and can be enabled again?
Comment: @Vikas try mp_logdetail 3, which should then catch everything. If that doesn't help I'll try to look for a solution when I'm back home.
Comment: I've just tried with a clean installation + bots mod and it did it right away. All kills were shown properly. Could you please attach the config file you used?
Comment: Please only tag the game you're asking about. If this is about CS:CZ, then you don't need both tags.
Comment: @Wrigglenite there's *literally* no difference between these two. If someone has played CS 1.6 and has encountered this problem, he would definitely be able to solve this issue too. But if a person has played only CS:CZ, chances are he's a *noob* and less chances of solving the issue.
Comment: I can't look it up right now, because I'm only on my phone... what are mp_logecho and mp_logdetail set to? That'd be my first guess.
Comment: @dly mp_logecho  was 1, mp_logdetail was empty. So I set it to 1 and it made no difference. Still not getting death notices.
Comment: @dly nothing changed. But one thing that you may want to know. After making it 1 or 3, I noticed these messages:
No masters loaded
Using default master
Vikas attacked a teammate
Teammate kills: 1 of 3
Vikas attacked a teammate. I guess I didn't notice them before.
Comment: Ok, so the log levels are fine. I guess it's something related to the console itself. the log details determine what's being logged and output. One more thing: what's happening in your server log file (if there is one)?
Comment: @dly how to check that?
Comment: It should be in your cstrike directory under /logs/ or directly in it. I can be opened with a simple text editor.
Comment: mp_logfile is 1. But there are no logs folder in cstrike. And not even a file named log.
Comment: @dly solved :D Please see my answer.
Answer: Okay, this is 3rd time I posted a question and myself found the solution by mistake. Actually I pressed I while playing by mistake and it turned on the death notices in console. By default, GUI interactive tutor was enabled.
But I don't know why when this is enabled console doesn't show death notices.
Comment: Wow, that's a weird behavior of the game.
Comment: You may want to try it if you have czero game?


Set selected text in SelectionArea

Question: I understand how to read the selected text in a SelectionArea, but I would also like to make selections as well. Given access to a SelectionArea, how do I programmatically set what it is selecting?
Thanks!
Comment: Same questions here
Answer: as far as I know SelectionArea does not have an easy way to do that or at least I have not seen documentation about it, , where I have seen what can be done in the TextFields, here I leave you an example.
import 'package:flutter/material.dart';

void main() => runApp(const MyApp());

class MyApp extends StatefulWidget {
  const MyApp({super.key});

  @override
  State<MyApp> createState() => _MyAppState();
}

class _MyAppState extends State<MyApp> {
  final TextEditingController controller = TextEditingController()
    ..text = 'Hello World example';
  final FocusNode focusNode = FocusNode();

  @override
  Widget build(BuildContext context) {
    return MaterialApp(
      title: 'Material App',
      home: Scaffold(
        appBar: AppBar(
          title: const Text('Material App Bar'),
        ),
        body: Center(
          child: Column(
            children: [
              TextField(
                focusNode: focusNode,
                controller: controller,
              ),
              TextButton(
                  onPressed: () {
                    //focus
                    focusNode.requestFocus();

                    //select all
                    controller.selection = TextSelection(
                        baseOffset: 0,
                        extentOffset: controller.text.length,
                        isDirectional: true);
                  },
                  child: const Text('Select All'))
            ],
          ),
        ),
      ),
    );
  }
}

Set selected text in SelectionArea


Will relocating my Central AC intake improve performance?

Question: Over this weekend, I have made a breakthrough scientific discovery that will likely change the world - hot air rises compared to cooler air! :)
My Central AC system has its intake at the ground level, and the ceilings are 8' - it's an older but remodeled house.
I have the space to reroute intake from the floor to the ceiling.  My idea: why have the AC unit pulling in the coolest air when it could be working on the warmest air instead?  And, additionally, that would be the logical flow direction, so this must be more efficient.  With its location it would be easy to construct, too.
My question is, just how much more efficient is this?  And do you have any tips on the routing?  I will be able to keep a wide radius on the new ducting and it will have at least 20x20 cross-section (equal to the intake).  Thanks!
Comment: Not only that -- *humid air rises compared to dry air* too
Comment: Yes, it does make sense, conceptually -- getting more work out of the system by offering it more work to do.  However, much about refrigeration is counter-intuitive when the physics aren't taken into account. The formula is linear: BTU of *sensible* heat = airflow-cfm × temperature-drop-°F × (constant) 1.08, so over normal operating temp ranges, this relationship should also be pretty linear.  The system is *already* removing as much heat as it is able to.  Offering it more heat to remove (within normal operating range) shouldn't increase the amount of heat it is able to remove.
Comment: *"why have the AC unit pulling in the coolest air when it could be working on the warmest air instead?"*   You seem to be assuming that, given the same humidity level and the same outdoor conditions, the intake temperature somehow impacts "efficiency" in an counterintuitive relationship.  A system that is appropriately sized and currently cools 72°F intake air down to 56°F... would reasonably be expected to only cool 76°F intake air down to ~60°F.
Comment: Good point.  I was thinking more abstractly that perhaps a) the relationship is not linear for all ranges (not an engineer though) and b) I'm assuming that there is overall greater _relative_ efficiency working a greater load.  There must be an analog to a power curve there.  So that yes you're not cooling as much but you're cooling "more" - does that make sense?
Answer: Most forced-air HVAC systems in Residential are both heating and cooling.
What might be efficient in the summer will not be efficient in the winter.
So, where do you live and which do you use more?
If you live in Arizona you optimize for cooling but if you live in Minnesota you optimize for heating. Then you just deal with a less efficient system in the opposite season.
Re-routing your ductwork may be much less cost efficient than simply buying a newer AC unit with a higher SEER rating.
Make sure you think this all the way through before pulling the trigger on anything.
Good luck!
Comment: You can also install a second intake but keep the original one there. Then, during the summer you cover up the lower one and during the winter you cover the upper one. I know some people who do this with intakes on multiple levels of their houses.
Comment: +1 for the comparison between heating and cooling.  Definitely cooling in Texas!
Answer: I am not quite sure what you are trying to accomplish but let me add my "2 cents". Many years ago heating and cooling systems were installed properly with both high and low supply registers and return grills in every room.   Today it is too expensive to do a "good job", so everyone is now doing a cheaper, "less expensive" job. If almost every room has only low return grills and you want to add high return grills which will add to your homes comfort, you or an HVAC company could replace the "low only" grills with high and low returns. "GOOGLE" The Hart& Cooley register company for an idea of the registers you will need. You will need ones similar to the #651 wall registers and #672 grills, size 6" X 14". These 2 registers used together will allow for a high open summer and low open winter room return system. As I said this combination was  used years ago, I have them in my house. You use the same stud space to mount the register/grill combination. The single flap design allows the register to be open, blocking the stud space. When the flap is open, only that register is used and when the flap is closed only the other register/grill is working. You would now have a cheap way to have high summer / low winter returns by only having to buy the single flap registers, no expensive duct changes would be needed. HVAC companies used to do this all the time. If this is not what you have in mind, rewrite your question with more detail. Hope this helps.


C# Working with a LinkedList DataStructure from base

Question: I'm currently learning Cambridge Book of dataStructures and each time I think about a problem, before I see the solution, I'm trying to solve it.
I'm Having a problem with  RemoveLast()
public void RemoveLast()
        {
            if (end != null)
            {
                Node runner = start; //if end != null then start is initialized.
                while (runner != end)
                {
                    runner = runner.Next;
                }
                runner.Next = null;
                end = runner;
             }
        }

What is the problem in my code? Thx guys!
Answer: Consider the loop condition:
while (runner != end)

At the end of the loop, runner is equal to end. So you are basically setting end.Next to null and setting end to itself.
You need to get to the node right before the end node.
Change the loop condition to this:
while (runner.Next != end)

This will make sure that at the end of the loop, runner will be the node exactly before the end node.
Please note also that this code does not handle the case where start is equal to end (when the linked list contains exactly one node).


Python doesn't write all entries from list

Question: I'm exploring python and tried to sort all files from a directory by last modified and then write the list into a txt file.
    import time
    import os
    i=1
    a="path"
    def getfiles(dirpat):
        b = [s for s in os.listdir(dirpat)
             if os.path.isfile(os.path.join(dirpat, s))]
        b.sort(key=lambda s: os.path.getmtime(os.path.join(dirpat, s)))
        return b
    lyst=[]
    testfile='c://test.txt'
    lyst=getfiles(a)
    for x in range (0,len(lyst)):
        print lyst[x]
        fileHandle = open (testfile, 'w' )
        fileHandle.write ("\n".join(str(lyst[x])))
        fileHandle.close()

It printed perfectly and sorted by date also
    example1.pdf
    example3.docx
    example4.docx
    exmaple2.docx
    example 5.doc

But when I opened the file, it just had the last entry and displayed it like this
    e
    x
    a
    ... and so on

Just can't figure out where the problem lies. If I remove "\n".join it just prints me the last entry.
Thanks in advance,
Nils
Comment: Please do not **ever** have lines like `list = []` and `file = 'c://test.txt'` (the `list` one in particular). These are builtins which you shouldn't shadow. What happens after that if you want to call `list(some_iterable)`?
Answer: Correct the join(), e.g:
'\n'.join(str(path) for path in list)

And please rename the "list" variable, because list is a built-in data type in Python.
Answer: import os, os.path

a="path"

def getfiles(dirpat):
    b = [s for s in os.listdir(dirpat)
         if os.path.isfile(os.path.join(dirpat, s))]
    b.sort(key=lambda s: os.path.getmtime(os.path.join(dirpat, s)))
    return b

outfile='c://test.txt'

with open(outfile, 'w') as fileHandle:
    lines = getfiles(a)
    for line in lines:
        print line
        fileHandle.write(line)

Avoid using meaningless one character variable names. I also did not touch your getfiles() function. I did, however, rename file and list as those are both the names of built in functions, which you're hiding when you use those names.
You also only need to open the file once, not once per line. You were truncating the file on every write. Using with makes sure the file handle gets closed even if you have an error.
Edit: If you don't need to print out each line before writing it, you can just have one line inside the with block: fileHandle.writelines(getfiles(a)).
Comment: Best answer yet, in that it removed the `range(len())` confusion, improved naming, and fixed both errors.
Comment: It wrote the entries into the file without nextline. So they we're stacked together. But all-in-all the remake was quite better than mine
Answer: Do this when writing the file:
fileHandle = open (file, 'w' )
for listItem in list:
    print listItem
    fileHandle.write (str(listItem) + "\n")
fileHandle.close()

Answer: You are opening and overwriting the file contents in each iteration of the loop.
Pass 'a' to the open(path) call to append to the file, or simply open it once outside the loop and close it outside the loop.
Answer: Because you convert each entry in the list to str the join operates on each
str because they also count as iterables and therefore a \n is put between
each character, not every item in the list. Changing the line to fileHandle.write ('\n'.join(str(path) for path in list))) will fix this just like BasicWolf wrote.