text:
Q: How to change browser url without changing anything in history You might think this is a duplicate, but it's not. I've seen the other SO answers about changing the browser url with replaceState() but I have a problem...
On one webpage on my website, it receives a lot of parameters, so the link goes on and on and on... I did replaceState(), and it shortened the URL by a lot. That worked. If I go on another link, and I go back in history, the URL will still be the same that I defined on replaceState() and the page gives a 404 error. Is there a way to just load the link the way it is and then temporarily change the URL so the user doesn't see a huge link but the system uses the actual URL?
I'm using JSP, go ahead and give me answers in JavaScript, JQuery, or Java.

A: You could store the parameters in localstorage (ie a cookie) then have your next page un-pick them from localstorage, thus reducing the size needed of the URL in the frst place. Example code (stolen from Storing Objects in HTML5 localStorage) :
// add to storage
localStorage.setItem('myAttibute', 'acceptable');

// Retrieve the object from storage (on another page)
var sMyAttibute= localStorage.getItem('myAttibute');

alert("myAttibute=" + sMyAttibute);

Hopefully it'll tell you that my attribute is acceptable.


text:
Q: Insert into several tables at once with Entity Framework Not that new to SQL development anymore, but new to EF.
I have a few tables that are related. I was wondering if EF can insert multiple rows in the table that generates the IDENTITY key then the table(s) that hold related data.
About to start doing some learning on EF, but to know this is possible would motivate me more (keep my up longer at night while learning the subject).
If its possible it is something I could really use.

A: Yes, you may insert both parent and child data (each of which are new) at the same time when using Entity Framework. You can take a look at this blog post for a very basic example of how to do so.

redpajama_set_name: RedPajamaStackExchange


text:
Q: inject service into instance of src/groovy class I have the following problem:
Under src/groovy I have class that is created in many parts of application (not like spring beans but in the runtime using new () operator)
I want to inject some grails services into all those instances, is it possible somehow without invoking constructor or setters?

A: Invoking constructors and setters are the only two ways to do dependency injection that I know of. You can use reflection and directly set the field value, but that eliminates any opportunity of having some logic execute when a dependency is injected.
Usually src/groovy (and src/java) classes are called directly or indirectly from an artifact (controller/service/taglib/etc.) that can use dependency injection, so it's often a simple matter of doing the DI there, and passing those Spring beans to the src/groovy classes in their constructors, via setters, or as arguments of the methods that use them.
Obviously if these classes were Spring beans there wouldn't be an issue, because Spring creates them and manages dependencies. But once you are working with a non-bean that has a bean dependency, you either have to do the work yourself, or look into an AOP-style solution, since you need to be notified somehow that there's a new instance that needs to be configured. I assume that this is doable, probably with AspectJ, but it'll probably be more work than it's worth, and add an extra layer of magic to further confuse new team members beyond the regular Grails and Groovy magic.


text:
Q: Transpose from Consumer to CompletableFuture I'm currently using an API which I unfortunately cannot change easily. This API has some methods in the style of this:
public void getOffers(Consumer<List<Offer>> offersConsumer) {
        final Call<List<Offer>> offers = auctionService.getOffers();
        handleGetOffers(offersConsumer, offers);
    }

It's a web api using retrofit, and it enables me to process the response in a consumer, but I much rather want to work with CompletableFutures.
I'm using the data I receive from this endpoint to compose an interface in a game, and therefore compose an inventory, that basically acts as a frontend to the api. What I want to do, is to have my composing method to wait for the consumer to finish, and then provide the processed results. This is what I have so far, but I don't know how to do the step from the consumer to the CompletableFuture:
    @Override
    public CompletableFuture<Inventory> get(Player player) {
        return CompletableFuture.supplyAsync(() -> {
            auctionAPI.getOffers(offers -> {
                //process the offers, then return the result of the processing, in form of an "Inventory"-Object.
                }

            });

        });
    }

I now need to return the result of the processing after all the Items have been received and then processed. How can I achieve this?

A: Something along the lines should work:
@Override
public CompletableFuture<Inventory> get(Player player) {
    CompletableFuture<Inventory> result = new CompletableFuture<>();
    CompletableFuture.supplyAsync(() -> {
        auctionAPI.getOffers(offers -> {
            //process the offers, then return the result of the processing, in form of an "Inventory"-Object.
            result.complete(inventory);
            }

        });
        return null;
    });

    return result;
}


text:
Q: GIT: Manually invoke 3-way-mergetool on a file on 2 branches I'm on branch C on which I would like to inspect and (partially) integrate the differences between branch A and B of file.c.
Is there are way to manually have git invoke the (3-way)-merge-tool on one file when not being in a merge-situation?
file.c:A -> file.c:C <- file.c:B

A: I didn't found any direct ways on Git to do that, but here is an answer that makes the job :)
Use a Bash script like
#!/bin/bash

LEFTREV=$1
RIGHTREV=$2
FILENAME=$3

LEFTFNAME=$FILENAME.left
RIGHTFNAME=$FILENAME.right

git show $LEFTREV:$FILENAME > $LEFTFNAME
git show $RIGHTREV:$FILENAME > $RIGHTFNAME

meld $LEFTFNAME $FILENAME $RIGHTFNAME

Usage : git3way A B file.c
where A and B are your two branches.


text:
Q: How to stop " point " to be replaced by a " comma" in the output of a VBA code? Initially it is important to note that I use MS Excel in Brazilian Portuguese.
That's my code:
Dim C1 As Integer
Dim C2 As Integer
Dim Cod As String

C1 = Worksheets("Dictionary").Range("D1").Value
C2 = Worksheets("Dictionary").Range("D2").Value

Cod = C1 & "." & C2

Worksheets("Dictionary").Range("D3").Value = Cod

Cells:
D1 = 1
D2 = 2

I expected that the output would be "1.2", but it's "1,2"!
What am I doing wrong?
And I apologize for my rusty English
Thank you!

A: Try this before outputting the value to the range:
Worksheets("Dictionary").Range("D3").NumberFormat = "@"

This changes the format of the cell to Text which prevents Excel to interpret the value you write to it as a number.

A: You use your Excel in "Brazilian Portuguese". The change may be due to the International Settings in the Windows Control Panel.
If your International Settings define the "," as the decimal separator, then Excel will convert the dot to the comma when you make the assignment in Visual Basic. This behavior makes the VBA code independent of locale settings and so makes the code portable in the international context (I assume that is the intention of this behavior).
If Brazilian Portuguese needs the dot as separator, then set your computer to use the dot as decimal separator, however, it shouldn't matter because when you send the spreadsheet to Brazil, the Excel there will use the correct decimal separator (I assume numbers are stored as binary floating point so dot or comma is only a matter of presentation).
EDIT: strikethrough of text above that would seem a workaround, as setting the international seting/decimal separator makes no difference for the end result.

A: Sub Replace()

    Sheet1.Range("B1").Value = "=SUBSTITUTE(A1,""."","","")"

End Sub

You can change your range accordingly.
Example -  Range("B1:B3").Value = "=SUBSTITUTE(A1:A3,""."","","")"


text:
Q: I want to repair an LED Christmas light string with 3 wires per bulb. How is this string wired? My prelit tree has strings of LED lights and each bulb has three wires going to it.  Looking on the web there are a number of sites that describe how to repair strings wired in series that have two wires per bulb.  However I cannot find any reference to strings with three wires per bulb.

A: I took a string apart and traced the circuit.  It's interesting- pairs of LED's are in parallel and these pairs are wired in series.  The string uses a full-wave rectifier (improves flicker) and splits the diodes between the plug end and receptacle end (so both plug and receptacle are not too large).  So for an extra wire per bulb this design gains redundancy- one bulb of any or multiple pairs can be missing or open and the string still lights.  However if both bulbs of a pair are missing or open the string is dark.
Of course a parallel string is better for reliability but I think that would require four wires per bulb and a brick power supply of some type.
So as far as repairing it seems best to replace burned out bulbs immediately.  This is because if the other bulb paired with a burned out bulb goes then the entire string goes.  Then tracing which bulb is bad requires special effort.  Of course I've read that sometimes LED bulbs fail shorted instead of open.  So this helps.
Here is a schematic:

A: Typically one of the wires would be parts of the series string and the other two would be connected to each side of the power. That allows sets of series strings to be daisy-chained. Below diagram from here:


text:
Q: HTML  inside PHP using mysql data I am new to HTML and PHP so sorry for a trivial question. I am trying to create a select statement inside my php where i get values for my options from a mysql database. I managed to do it somehow but in my select options, there is a empty line after each entry for some reason. Here is some example code that have the empty lines. Any ideas what might cause this empty lines to appear ? Thanks.
$rs = mysql_query("SELECT title, year FROM Movie GROUP BY title;" , $db_connection)
    or die(mysql_error());

    for($i = 0; $row = mysql_fetch_row($rs); $i++)
    {

        $count = count($row);

        for($j = 0; $j < $count; $j++)
        {
            $temp_row1 = current($row);
            next($row);
            $temp_row2 = current($row);

            print " <option value=\"$temp_row1 $temp_row2\">$temp_row1 $temp_row2</option> ";
            next($row);
        }
    }

    echo  "</select>";

EDIT:
Ok so I ended up doing this, which is a much cleaner code for me but I have 1 more problem. For some reason I cant get the value after I press the submit button on select menu.
<?php

    echo "<form action=\"./addCommentsToMovies.php\" method=\"GET\">";
    echo "<select name=\"rating\">";

    $db_connection = mysql_connect("localhost", "cs143", "")
    OR die("could not connect to database !!!");

    mysql_select_db("CS143", $db_connection);

    $rs = mysql_query("SELECT * FROM Movie GROUP BY title;" , $db_connection)
    or die(mysql_error());

    while ($row = mysql_fetch_assoc($rs))
    {
        $tmp_movieName = $row[title];
        $tmp_movieYear = $row[year];

        print " <option value=\"$tmp_movieName $tmp_movieYear\">$tmp_movieName $tmp_movieYear</option> ";
    }

    echo  "</select>";
    echo "<input type=\"submit\" name=\"submit\" value=\"GO\"/>";
    echo "</form>";

    $rating = $_GET[rating];

    echo "Print This: " . $rating;

    mysql_close($db_connection);

?>

In other words echo "Print This: " . $rating;
only prints "Print This:"  and $rating variable is empty.

A: NOTE: mysql is deprecated use mysqli or PDO
First of all you don't need current or next function to show your select box,And too much of for loop also.
<?php
  $db_connection = mysql_connect("localhost", "cs143", "")
OR die("could not connect to database !!!");

mysql_select_db("CS143", $db_connection);
if(isset($_POST['submit'])){
 echo $_POST['rating'];
}
?>

<form action="" method="post">
<select name="rating"  required>
<option value="">Select</option>
<?php
/*Selects all the available shows*/
$sql="SELECT title, year FROM Movie GROUP BY title";
$result_show=mysql_query($sql_show);
while($row_show=mysql_fetch_array($result_show))
{
    $value=$row_show['title'].$row_show['year'];
    $display=$row_show['title'].$row_show['year'];
   //I can use single variable to this but you need to understand
    echo '<option value='.$value.'>'.$display.'</option>';
}
?>
</select>
<input type="submit" name="submit" value="GO"/>
</form>

A: try this

<?php
    $rs = mysql_query("SELECT title, year FROM Movie GROUP BY title;" , $db_connection)
    or die(mysql_error());

    for($i = 0; $row = mysql_fetch_row($rs); $i++)
    {

        $count = count($row);

        for($j = 0; $j < $count; $j++)
        {
            $temp_row1 = current($row);
            next($row);
            $temp_row2 = current($row);
?>
            <option value="<?php echo $temp_row1.$temp_row2 ?>"><?php echo $temp_row1.$temp_row2 ?></option>;
   <?php          next($row);
        }
    }
?>

A: create an array that contains all the data, with mysqli_fetch_array and use while loop to print data from $row data array
$rs = mysql_query("SELECT title, year FROM Movie GROUP BY title;" , $db_connection) or die(mysql_error());

    echo  '<select name="title">';
    while($row = mysqli_fetch_array($rs))
    {

        echo'<option value="'.$row['title'].'" >'.$row['title'].'</option>';
    }
    echo  "</select>";
?>


text:
Q: Getting multiple 404 and 405 errors in Teams Bot I'm doing some investigating around a Teams Bot that I currently have in development. I'm seeing a lot of 404, and in some other cases, 405 errors when I look in Application Insights - I'm trying to understand if I've missed anything.

I have the App Service set to 'Always On' so my assumption is that it's polling the service every 5 minutes to keep it from idling out. However, I'm seeing a lot of 404 failures, specifically pointing to the GET/ endpoint and in other cases a 405 error as well, which is pointing to the api/messages endpoint.
I have the App ID and App Password set in the environment variables and I've set the storage using a Cosmos DB too as shown in the index.js file below. I have also checked the Teams manifest to ensure it's pointing to the Bot ID and recently added the bot domain as well to see if that makes a difference.
const restify = require('restify');
const path = require('path');

// Import required bot services.
// See https://aka.ms/bot-services to learn more about the different parts of a bot.
const { BotFrameworkAdapter, ConversationState, UserState } = require('botbuilder');

// Import required services for bot telemetry
const { ApplicationInsightsTelemetryClient, TelemetryInitializerMiddleware } = require('botbuilder-applicationinsights');
const { TelemetryLoggerMiddleware, NullTelemetryClient } = require('botbuilder-core');

// Import our custom bot class that provides a turn handling function.
const { DialogBot } = require('./bots/dialogBot');
const { ProvisioningProfileDialog } = require('./dialogs/provisioningProfileDialog');

// Read environment variables from .env file
const ENV_FILE = path.join(__dirname, '.env');
require('dotenv').config({ path: ENV_FILE });

// Create the adapter. See https://aka.ms/about-bot-adapter to learn more about using information from
// the .bot file when configuring your adapter.
const adapter = new BotFrameworkAdapter({
    appId: process.env.MicrosoftAppId,
    appPassword: process.env.MicrosoftAppPassword
});

// Define the state store for your bot.
const { CosmosDbPartitionedStorage } = require('botbuilder-azure');

const cosmosStorage = new CosmosDbPartitionedStorage({
    cosmosDbEndpoint: process.env.CosmosDbEndpoint,
    authKey: process.env.CosmosDbAuthKey,
    databaseId: process.env.CosmosDbDatabaseId,
    containerId: process.env.CosmosDbContainerId,
    compatibilityMode: false
});

// Create conversation state with storage provider.
const conversationState = new ConversationState(cosmosStorage);
const userState = new UserState(cosmosStorage);

// Create the main dialog.
const dialog = new ProvisioningProfileDialog(userState);
const bot = new DialogBot(conversationState, userState, dialog);
dialog.telemetryClient = telemetryClient;

// Catch-all for errors.
const onTurnErrorHandler = async (context, error) => {
    // This check writes out errors to console log .vs. app insights.
    // NOTE: In production environment, you should consider logging this to Azure
    //       application insights.
    console.error(`\n [onTurnError] unhandled error: ${ error }`);

    // Send a trace activity, which will be displayed in Bot Framework Emulator
    await context.sendTraceActivity(
        'OnTurnError Trace',
        `${ error }`,
        'https://www.botframework.com/schemas/error',
        'TurnError'
    );

    // Send a message to the user
    await context.sendActivity('The bot encountered an error or bug.');
    await context.sendActivity('To continue to run this bot, please fix the bot source code.');
    // Clear out state
    await conversationState.delete(context);
};

// Set the onTurnError for the singleton BotFrameworkAdapter.
adapter.onTurnError = onTurnErrorHandler;

// Add telemetry middleware to the adapter middleware pipeline
var telemetryClient = getTelemetryClient(process.env.InstrumentationKey);
var telemetryLoggerMiddleware = new TelemetryLoggerMiddleware(telemetryClient);
var initializerMiddleware = new TelemetryInitializerMiddleware(telemetryLoggerMiddleware);
adapter.use(initializerMiddleware);

// Creates a new TelemetryClient based on a instrumentation key
function getTelemetryClient(instrumentationKey) {
    if (instrumentationKey) {
        return new ApplicationInsightsTelemetryClient(instrumentationKey);
    }
    return new NullTelemetryClient();
}

// Create HTTP server.
const server = restify.createServer();
server.listen(process.env.port || process.env.PORT || 3978, function() {
    console.log(`\n${ server.name } listening to ${ server.url }.`);
    console.log('\nGet Bot Framework Emulator: https://aka.ms/botframework-emulator');
    console.log('\nTo talk to your bot, open the emulator select "Open Bot"');
});

// Listen for incoming requests.
server.post('/api/messages', (req, res) => {
    adapter.processActivity(req, res, async (context) => {
        // Route the message to the bot's main handler.
        await bot.run(context);
    });
});

Whilst the Bot appears to run okay for the most part, am I missing something with these errors or is this expected behaviour since it's polling for a response?
Thanks in advance

A: *

*Does your bot contain a web page as well? The node samples do not, but .NET samples do. If not, it would make sense, of course, to receive a 404. I tend to agree with you that the polling might be the cause.

*Bots typically (especially when created from template or sample), do not handle GET endpoints to /api/messages. Everything is handled using POST.


text:
Q: If statement treating true as false I have stumbled across an extremely strange occurrence in Javascript that I can't make head or tail of.
Here's a very simple if statement:
let hours = 20;

I put a breakpoint here, and set hours = 0 in the debugger. I test !hours in the debugger to confirm the result is true, and click continue to run through the if statement.
if (!hours) {
  console.log("Hours is false: " + hours);
} else {
  console.log("Hours is true: " + hours);
}

Expected result to be logged:

Hours is false: 0

Actual result logged:

Hours is true: 0

^ Mouse is hovering over hours so current value is visible
This only happens when hours was originally set to an integer, and then set to 0 in the debugger.
Does Javascript have some obscure rule about truthy values retaining their status even after being changed?
Or is this a discrepancy between the debugger and the code (which, if true, would basically defeat the point of the console)?
Why on earth is this happening?

A: Check this one, open the devtools and run the code snippet, change the scope value to 0 or in the console put hours = 0. Both will work tested it
Chrom version : Version 79.0.3945.88 (Official Build) (64-bit)

let hours = 20;
debugger
if (!hours) {
  console.log("Hours is false: " + hours);
} else {
  console.log("Hours is true: " + hours);
}

A: Have you carefully parsed the hours received ?
!0 === false
!"0" === true
!parseInt("0") === false

Have you computed string as if it was integer ?
"0" +  0  === "00"
 0  + "0" === 0
+"0" + 0  === 0

A: if (!hours) {
    console.log("Hours is false: " + hours);
} else {
    console.log("Hours is true: " + hours);
}

if hours = 1 then

hours is true: 1

or if hours = 0 then

hours is false: 0

or if hours = 20 then

hours is true: 20

A:
I put a breakpoint here, and set hours = 0 in the debugger.

And that's probably the source of confusion. If your "here" is after the code tested the value of x, then your changing the value of x doesn't affect which branch gets executed.

A: You have to check the data type:
typeof hours;

0 as number return false in if statement, that's why with ! it return true.
var number = 0;
if (number) console.log(true); else console.log(false);
output -> false
if (!number) console.log(true); else console.log(false);
output -> true

That's clear JS.


text:
Q: How to lock documents in couchbase database and handle TemporaryLockFailureException I am using Playframework(scalaVersion 2.12.4) with Java 1.8 and Couchbase(Couchbase java-client 2.4.2). I am fetching UserDetails document and updating the same document in the database.

*

*My code is working in normal scenarios, couldn't test the conflicting edge cases. Hence, not sure whether my code will work or not.

*How to handle TemporaryLockFailureException? My current exception handling seems to be wrong.

@Override
public void submitUsersDetails(DashboardRequest request) {
    logger.debug("inside submitDashboardDetails");
    CompletableFuture.runAsync(() -> {
        try {
            bucket = cluster.openBucket(config.getString(PctConstants.COUCHBASE_BUCKET_NAME),
                    config.getString(PctConstants.COUCHBASE_BUCKET_PASSWORD));
            String documentID = PctConstants.USER_PROFILE;
            JsonDocument retrievedJsonDocument = bucket.getAndLock(documentID, 5);
            if (retrievedJsonDocument != null) {
                JsonNode json = Json.parse(retrievedJsonDocument.content().toString());
                UserDetails userDetails = Json.fromJson(json, UserDetails.class);
                // UPDATING userDetails
                JsonObject jsonObject = JsonObject.fromJson(Json.toJson(userDetails).toString());
                bucket.replace(JsonDocument.create(documentID, jsonObject, retrievedJsonDocument.cas()));
                logger.info("Successfully entered record into couchbase");
            } else {
                logger.error("Fetching User_details unsuccessful");
                throw new DataNotFoundException("User_details data not found");
            }
        } catch (TemporaryLockFailureException e) {
            try {
                logger.debug("Inside lock failure **************************");
                Thread.sleep(5000);
                String documentID = PctConstants.USER_PROFILE;
                JsonDocument retrievedJsonDocument = bucket.getAndLock(documentID, 5);
                if (retrievedJsonDocument != null) {
                    JsonNode json = Json.parse(retrievedJsonDocument.content().toString());
                    UserDetails userDetails = Json.fromJson(json, UserDetails.class);
                    // UPDATING userDetails
                    JsonObject jsonObject = JsonObject.fromJson(Json.toJson(userDetails).toString());
                    bucket.replace(JsonDocument.create(documentID, jsonObject, retrievedJsonDocument.cas()));
                    logger.info("Successfully entered record into couchbase");
                    submitDashboardDetails(request);
                } else {
                    logger.error("Fetching User_details unsuccessful");
                    throw new DataNotFoundException("User_details data not found");
                }
            } catch (InterruptedException e1) {
                e1.printStackTrace();
            }
        } catch (Exception e) {
            e.printStackTrace();
            try {
                throw e;
            } catch (Exception e1) {
                e1.printStackTrace();
            }
        }
    }, ec.current()).join();
}


text:
Q: Vcard sent as plain text I have generated a vcard of the selected contact. I am sending it through sms (though i know we could send it through mms, but there are some phones that dont support mms).
when I am sending it to another phone, the exact string is received as such,
BEGIN:VCARD
VERSION:2.1
N:Mahajan;Sahil;;;
FN:Sahil Mahajan
TEL;HOME:964-695-7130
EMAIL;HOME:sahilmahajanmj@gmail.com
END:VCARD

But I want that on receiving this message, there should be a default option of saving it as contact.
I am sending it using the following code,
SmsManager sms = SmsManager.getDefault();
sms.sendTextMessage(mobileNumber, null, vCardString, null, null);

here vCardString is the actual string containing the vcard. Let me know, if i need to post anything else.


text:
Q: Typescript discriminated unions: Property does not exist on type I'm going to use Discriminated Union type for Reducer Action.
But when I use it the compiler says the payload does not contain the property.
The code looks like

interface AuthenticatedUserState {
    user?: any
    isAdmin?: boolean
    isRegistered?: boolean
    err?: any
    isError?: boolean
    isSignedOut?: boolean
    authorizationData?: any
}

const INITIAL_STATE: AuthenticatedUserState = {
    user: null,
    isError: false,
    err: null,
    isSignedOut: false
}

interface AUTHENTICATED_USER_ACTION {
    type: 'authentication/AUTHENTICATED_USER'
    payload: {
        authenticatedUser: any
        isAdmin: boolean
    }
}

interface REGISTER_USER_ACTION {
    type: 'authentication/REGISTER_USER'
    payload: {
        isRegistered: boolean
        err: any
    }
}

const AUTHENTICATED_USER = 'authentication/AUTHENTICATED_USER'
const REGISTER_USER = 'authentication/REGISTER_USER'

type ACTION = AUTHENTICATED_USER_ACTION | REGISTER_USER_ACTION

const authenticatedUserReducer = (
    state: AuthenticatedUserState = INITIAL_STATE,
    action: ACTION
): AuthenticatedUserState => {
    const { type, payload } = action
    switch (type) {
        case AUTHENTICATED_USER:
            return {
                ...state,
                user: payload.authenticatedUser,
                isAdmin: payload.isAdmin
            }
        case REGISTER_USER:
            return {
                ...state,
                isRegistered: payload.isRegistered,
                err: payload.err
            }
        default:
            return state
    }
}

Then, the error is
Property 'err' does not exist on type '{ authenticatedUser: any; isAdmin: boolean; } | { isRegistered: boolean; err: any; }'.
  Property 'err' does not exist on type '{ authenticatedUser: any; isAdmin: boolean; }'.

A: You can fix the error by upgrading your TypeScript version. See playground with v4.9.4: Playground

A: It appears that you might be using a typescript version < 4.6.
With TS < 4.6, when you destructure a value with a discriminated-union type:
const { type, payload } = action

you are creating two new variables that have no connection with each other, nor the item from which they were destructured. The compiler is unable to narrow payload or action by means of checking type.
This behaviour changes in typescript > 4.6, so upgrading your typescript version should be considered.
Otherwise, in a pre-TS4.6 world, don't destructure items from your discriminated union for the purpose of type-narrowing/control-flow.
switch (action.type) {
    case AUTHENTICATED_USER:
        return {
            ...state,
            user: action.payload.authenticatedUser,
            isAdmin: action.payload.isAdmin
        }
    // ...
}


text:
Q: Match a number >= column A and < column B Return column C # I need to pull the number out of column C by matching a value to greater than or equal to from column A and then less than column B.
>=  <   Pull code
5   10  1       22
10  15  2
15  20  3       0
20  25  4
25  30  5
30  35  6
35  40  7
40  45  8
45  50  9
50  55  10
55  60  11
60  65  12

So the 22 should return a 4 but it returns a zero if I change the 22 to 56 it should give me 11. I have tried many different formulas like index and match also tried vlookup the latest one is
=SUMIFS(C:C,A:A,">=" & E2,B:B,"<" & G14)

A: Your columns overlap so not sure how you handle the boundary values, but here is a formula you can try, adjust the ranges to suit
=INDEX(C1:C12,MATCH(D1,A1:A12,1))

A: Alternatively, set up a DGET criteria range:

+------------+-----------+
| >=         | <         |
+------------+-----------+
| ="<=" & D2 | =">" & D2 |
+------------+-----------+

and use =DGET(A1:C13, C1, that_criteria_range).
It does not require the range to be sorted and will return an error if the record is not found or if more than one found.


text:
Q: Behaviour of DC series motors I'm having trouble implementing a DC series motor simulation, and I think this is due to the fact that I do not understand the motor behaviour itself.
Notice that the mechanical part of the simulation is completely functional, so I don't have to bother with this. I have a DC series motor (motor constant G, internal resistance R) which get some voltage V applied on its terminal, and a mechanical load (Torque T, angular speed w) applied on the shaft.
Here's what I currently do:

*

*Evaluate the current in the circuit: that'd be \$I = \dfrac{V - BackEMF}{R}\$

*Get the torque from that current: \$T = G \cdot I^2\$

*The mechanical simulation spits out the speed based on this torque and the load, and I compute the \$BackEMF = G \cdot I \cdot w\$

*Back to 1

The issue is getting to the steady state: I can't see what will prevent my motor to diverge.
The way I see it, when going to steady state, BackEmf gets close to V -> the torque gets very small...But so does the current, which means BackEmf becomes small on the next simulation step -> (V - BackEmf) grows again, the torque increases, etc.
So: what actually prevents that? Is it inherent to my step-by-step simulation? How can I circumvent this?
What I have tried so far, without success:

*

*the magnetic flux is actually not linear but should saturate at some point (when?)

*I tried to add a small friction torque so the motor isn't "perfect"

I also have the same (related, I think) instability issues when I reduce the applied voltage V.

A: If I understand you correctly, you have a function \$I\mapsto \omega(I) \$ (the mechanical simulation) and you are looking for \$I\$ that solves
\$ I = { V - G I \omega(I) \over R } \$.
This is a steady state solution, there are no system dynamics involved, so the issues are with the technique you are using to solve the equation.
There is no reason a priori that the 'relaxation' technique will work.
One hack you could try is to update the current \$I\$ incrementally, which
introduces some numerical 'damping'.
You could try a binary search to find the satisfying value.
You could implement a secant method (essentially estimate the slope by finite differences).


text:
Q: Creating/Importing A Custom Map in Python using Libtcod? I have been in the works of creating a Roguelike in Python, using Libtcod!
However, one of my major hurdles that i have been faced with - is that i have absolutely no idea how to make a CUSTOM map (as in, i define the cells and what elements they entail) OR, if it's possible - How you import a custom map into Python using Libtcod.
As of right now, i am using a definition that essentialy renders the map after certain patterns (number of rooms, no intersections etc.) - But i wish to make it so that i can import a already custom made map - Or actually just made a definition for one, so i can load it in given certain criterias.
Any help on this subject would be greatly appreciated, thanks! :)

A: There are lots of interesting ways you can import map data into your program.
Typically, with a roguelike, you would generate that data. Though, of course, this isn't strictly necessary.
A pretty basic way of generating would be to try out libtcod's heightmap toolkit. This is extracted from a game I've written, and might give you a decent idea how to approach the problem. This code is extracted from my Map class:
import random
import libtcodpy as libtcod
class Map
  def __init__(self,w,h) :

    self.width = w
    self.height = h

    self._hm = libtcod.heightmap_new(w,h)
    self._cells = []
    self.initMap()

  def initMap(self) :
    print "Initing map"
    for y in range(self.height) :
      for x in range(self.width) :
        c = cell.Cell(x,y)
        self._cells.append(c)
    self.resetMap()
    return

  def resetMap(self):
    print "Resetting map"
    for y in range(self.height) :
      for x in range(self.width) :
        self._cells[x + y * self.width].reset()
    ## Heightmap generation
    self.randomizeHeightmap()

    for y in range(self.height) :
      for x in range(self.width) :

        alt = libtcod.heightmap_get_value(self._hm, x, y)
        self._cells[x + y * self.width].dig(alt > 1)

  def randomizeHeightmap(self) :
    print "Setting up heightmap"
    hills = 1000
    hillSize = 7

    halfX = self.width / 2
    halfY = self.height / 2
    libtcod.heightmap_clear(self._hm)
    for i in range(hills) :
      size = random.randint(0,hillSize)

      hillX1 = random.randint(0,halfX - hillSize / 2)
      hillY1 = random.randint(0,self.height)

      hillX2 = random.randint(halfX + hillSize / 2, self.width)
      hillY2 = random.randint(0,self.height)

      libtcod.heightmap_add_hill(self._hm,hillX1, hillY1, size, size)
      libtcod.heightmap_add_hill(self._hm,hillX2, hillY2, size, size)

    libtcod.heightmap_normalize(self._hm, 0.0, 2.0)
[...]

Note I'm not using libtcod's map functionality here. You certainly can, and that would allow you to use the built in Field of View toolkit as well (which is pretty awesome!).
The Cell class's dig method accepts a boolean value to determine whether or not the cell is passable. After the heightmap is generated, I normalize it so it only contains values of 0, 1, and 2. Then I just make any corresponding cell that ended up with an "altitude" of 2 a wall, and 1 or 0 an opening. This gave me a good balance to work with.
The heightmap functions are great for creating an organic sort of layout, with round features, rather than the typical square-roomed dungeons often seen in roguelikes.
If you're looking to generate more traditional dungeons, there is a BSP toolkit included with libtcod that is designed exactly for this task. See the documentation for it here.
There's also an incredible python tutorial which has a dedicated map section here.
I've used other methods in the past, including, but not limited to reading each pixel in a simple .bmp image and interpreting the rgb values, each indicating something different about the given coordinate in the map (red might be wall/open, blue might indicate the presence/absence of a roof, etc).
The basic idea, though, is to just have an array of coordinates. It may be as simple as an array or integers, where 0 means passable, and 1 means a wall, or, as in my case, an array of objects that also store some other information that'd be useful for your game.
You can use a 2-d array (this is quite a bit more easy to wrap your head around, sometimes, as you would refer to the coordinates like map[x][y] rather than map[x + y*width]) rather than the single-dimension array that I've used in the example code.
The world is your oyster! :) Just get that data into a structure that you can read it out of, then examine the coordinate you're interested in.


text:
Q: How to properly update JIRA SVN plugin config after first initialization? After configuring 2 repos in subversion-jira-plugin.properties file according to instructions provided in readme file I copied 3 jar files to lib folder and properties file to class folder and restarted jira service. Then I made few commits containing issues IDs to the repos I declared in subversion-jira-plugin file. On the project main screen on the Subversion Commits  tab I can see all commits I made – everything works.
However  If I add another repository in config file this repo seems to be ignored – commits made to third repo doesn't appear on Subversion Commit tab.
I suppose that content of the subversion-jira-plugin.properties file has been cached somewhere because in the export file (C:\Program Files (x86)\Atlassian\Application Data\JIRA\export\.zip\entites.xml)  there are only entries "OSPropertyString" containing values of users, paths, names etc. of the 2 repositories that were first created, nothing about third repository.
I have restarted jira service and cleared folder {$jira's_index_dir}/plugins/atlassian-subversion-revisions/ few times with no luck. I have set Subversion Revision Indexing Service delay time to 3 minutes.
My config file:
C:\Program Files (x86)\Atlassian\JIRA\atlassian-jira\WEB-INF\classes\subversion-jira-plugin.properties:
svn.root=http://localhost:8080/svn/test1/trunk
svn.root.1=http://localhost:8080/svn/test2/trunk
#added after first initialization
svn.root.2=http://localhost:8080/svn/test3/trunk
svn.display.name=Test1 Repository
svn.display.name.1=Test2 Repository

#added after first initialization
svn.display.name.2=Repo3
# Subversion username same for all repos
svn.username=<user>
svn.password=<mypass>
…

Probably I am missing something, so my question is:
How to properly update svn plugin config after first initialization?
JIRA 4.4
SVN plugin 0.10.7

A: If you have access to the database, you can get the plugin to read all values from the configuration file by stopping Jira, deleting the previous values, and restarting. The values you define in the config file will be imported as new values.
You can find the setting entry values here:
SELECT *
FROM [jiradb].[jiraschema].[propertyentry]
WHERE ENTITY_NAME='jira.plugins.subversion.repo';

And the string entries themselves:
SELECT *
FROM [jiradb].[jiraschema].[propertystring]
WHERE ID IN(
    SELECT ID
    FROM [jiradb].[jiraschema].[propertyentry]
    WHERE ENTITY_NAME='jira.plugins.subversion.repo'
);

A: I have studied the documentation to Subversion JIRA Plugin and found there the following sentence:

If you make any configuration changes, please delete the $INDEXDIR/plugins/atlassian-subversion-revisions directory and restart JIRA to make the change take effect.

So perhaps you just forgot that.

A: I've received the answer at
how-to-properly-update-svn-plugin-config-after-first-initialization

"The way it works is confusing... the properties file appears to update the list of repos only if they don't already exist (in the database).
Instead of adding repos through the properties file, which is hard to maintain as you need >to bounce jira every time, add them through the UI. Admin -> Repositories." - Jamie Echlin


text:
Q: iptables rules for lvs using piranha gui I am trying to bulid an lvs system, where 202.141.81.239 is the virtual IP and 202.141.81.241 and 202.141.81.242 are the lvs routers.Ths system is working fine in our intranet but is not through internet.
The following is my iptables configuration
# Generated by iptables-save v1.4.7 on Tue Mar 25 12:30:26 2014
*mangle
:PREROUTING ACCEPT [96:9901]
:INPUT ACCEPT [65:5340]
:FORWARD ACCEPT [0:0]
:OUTPUT ACCEPT [48:3348]
:POSTROUTING ACCEPT [48:3348]
-A PREROUTING -d 202.141.81.239/32 -p tcp -m tcp --dport 80 -j MARK --set-xmark 0x50/0xffffffff
COMMIT
# Completed on Tue Mar 25 12:30:26 2014

A: It's quite difficult to know what is going on here with that information, but it depends on the routing method configured (NAT or Direct).
For example, if you are using Direct Method you should configure iptables as follows.
(Source). On each REAL SERVER:
iptables -t nat -A PREROUTING -p <tcp|udp> -d <vip> --dport <port> -j REDIRECT

If it works from the internal network but not from the external one, but the servers are using public IPs instead of private IPs, in fact, could be a firewall issue (do you have another firewall protecting your servers?). If not, please review iptables for all your servers (LVS routers and real servers).
Could be a good idea, also, disabling iptables and double checking (from the internal and the external network) just to see what happens. Maybe you are using arptables_jf instead of iptables to allow redirection...
If it still doesn't work, you can try using ARP tables instead of iptables for Direct Method (if you are actually using this method).


text:
Q: How to get the weights from regression coefficient(path coefficients) in structural equation model? I am reading about the structural equation model(SEM) and I have a use case that is going to be needing it. In my use-case, I don't have latent variables, so we can think of it as a Path analysis.
The output from SEM gives us couple of things p-value and Estimates are most important. p-value gives us significance of the feature, while Estimate gives us some quantitative figure that tells us how a certain feature impacts on the other dependent feature.
Sample output from a structural equation model:-
   lval  op rval    Estimate    Std. Err   z-value   p-value
0    a   ~    d    0.214797    0.405306  0.529962  0.596138
1    b   ~    d    0.197167    0.374708  0.526187  0.598758
2    c   ~    d   -0.608275    0.419378 -1.450421  0.146941
3    c  ~~    c  199.797329  126.362926  1.581139  0.113846
4    a  ~~    a  186.614202  118.025184  1.581139  0.113846
5    b  ~~    b  159.501184  100.877406  1.581139  0.113846

My variables in my use case look like this:-

In the above diagram, all the variables are measurable variables and the Deposit is dependent variables, while other variables are independent. The values written are the "Estimate" values obtained from the SEM, which are also called regression coefficients.
My question and requirements:-

*

*I basically need to find if we can interpret these "Estimate" values(Regression coefficient) as "weights" of those feature on how they are impacting the dependent variable?

*Can I sum up all the coefficients like this 2.44+1.32+0.65+0.32 = 4.73, and then to get weightage of each feature, later do (estimate of variable x)/(sum of all coefficients), for first variable Var 1 = 2.44/4.73 = 0.51 ?
I basically need some way I can get these estimates to be converted weights, so when I allocate the Dependent variable "Deposit" = say 100 million, I can allocate/distribute it to the independent variables in proportion to their impact on deposit.
Structural equation model is something I am asked to focus, but if this can be achieved in some other ways, I am more than thankful to hear them as well.


text:
Q: How minimize $\sum p_b \ln{p_b}$? I have a multiset $A = \{a_1,\dots,a_n\}$ of integers. Let $q = P(a_i = a_j)$ when $i$ and $j$ are chosen independently and uniformly from $\{1,\dots, n\}$.  Let $B$ be the set of integers in $A$. We know that $|B| \leq n$.  Finally let $p_b = P(a_i = b)$ when $i$ is chosen uniformly from $\{1,\dots, n\}$.

How small can $-\sum_{b \in B} p_b \ln{p_b}$ be as a function of $q$ and $n$?

A: Just to make contact with wikipedia, I'll note that $S=-\sum p_b \ln p_b$ is the entropy and $q$ is the Simpson index. As other people have noted, there's some trickiness with there being only certain allowed $(n,q)$ pairs, so to avoid this let's assume that $n$ is large and $q$ is not too close to 0 or 1.
To maximize the entropy, you want to spread out the distribution as much as possible, without having the Simpson index fall below $q$. The distribution that does this has $p_1 \approx \sqrt{q}$, $p_i=1/n$ for $i=2,\ldots,\sim n(1-\sqrt{q})$. (Obviously, for finite $n$, $p_1$ will have to be slightly smaller than $\sqrt{q}$.) This gives $S\sim (1-\sqrt{q})\ln n$.
To minimize the entropy, you want to concentrate the distribution as much as possible, without having the Simpson index go above $q$. To do this, let $|B|=\lceil 1/q\rceil$, and have $p_1, \ldots, p_{\lfloor 1/q \rfloor}$ close to $q$, with $p_{\lceil 1/q\rceil}$ getting the small remainder of the probability. This gives $S\sim -\ln q$.
Note that this also works the other way -- given $n$ and $S$, these same distributions give the maximum and minimum possible values of $q$.

A: A beginning:
In the first place a set $B:=[m]$ is given, and for each $k\in B$ we have a multiplicity $f(k)\in{\mathbb N}_{\geq1}$. The pair $(B,f)$ constitutes the multiset $A$ in your question.
Put $\sum_{k=1}^m f(k)=:n$. Then the probability that you choose the value $k$ when picking a random element from $A$ is ${f(k)\over n}=:p_k$, and the probability $q$ that you choose two equal values in two independent choices is given by
$$q={1\over n^2}\sum_{k=1}^m f^2(k)=\sum_{k=1}^m p_k^2\ .$$
It follows that we have to maximize/minimize the function
$$H(p):=-\sum_{k=1}^m p_k\>\log p_k$$
under the constraints
$$p_k\geq0,\quad \sum_{k=1}^m p_k=1,\quad \sum_{k=1}^m p_k^2=q\ .$$
Consider this as a continuous optimization problem. Depending on the value of $q$, the sphere $\sum_k p_k^2=q$ may intersect the simplex $p_k\geq0$, $\>\sum_k p_k=1$ in a complicated way, and setting up a simple Lagrange multiplier scheme does not sufficiently take care of the global situation, so much the more as it will lead to transcendental equations. But it seems that the following Lemma is true: When $H$ is extremal at an admissible ${\bf p}$ then we cannot have three values $p_1>p_2>p_3>0$. This is corroborated by the follwing figure which shows the level lines of $H$ on a subsimplex $p_1+p_2+p_3=s$ for $s=0.4$ and in red a curve $p_1^2+p_2^2+p_3^2={\rm const.}\ $. One can see that the red curve is tangent to the level lines of $H$ only in points where  two of the $p_k$ are equal.

Therefore one would have to do the following: For all possible choices of $m_1\geq0$, $m_2\geq0$ with $m_1+m_2\leq m$  solve
$$m_1p_1+m_2p_2=1,\qquad m_1p_1^2+m_2p_2^2=q$$
for $p_1$ and $p_2$. When an admissible solution exists compute the corresponding $$H({\bf p})=-m_1\> p_1\log p_1-m_2\>p_2\log p_2\ .$$
The smallest and the largest values found in this way are the extremal values of $H$ under the given constraint.


text:
Q: Class does not implement its superclass's required members So I updated to Xcode 6 beta 5 today and noticed I received errors in nearly all of my subclasses of Apple's classes.
The error states:

Class 'x' does not implement its superclass's required members

Here is one example I picked because this class is currently pretty lightweight so it will be easy to post.
class InfoBar: SKSpriteNode  { //Error message here

    let team: Team
    let healthBar: SKSpriteNode

    init(team: Team, size: CGSize) {
        self.team = team
        if self.team == Team.TeamGood {
            healthBar = SKSpriteNode(color: UIColor.greenColor(), size:size)
        }
        else {
            healthBar = SKSpriteNode(color: UIColor.redColor(), size:size)
        }
        super.init(texture:nil, color: UIColor.darkGrayColor(), size: size)

        self.addChild(healthBar)

    }

}

So my question is, why am I receiving this error, and how can I fix it? What is it that I am not implementing? I'm calling a designated initializer.

A: There are two absolutely crucial pieces of Swift-specific information that are missing from the existing answers which I think help clear this up completely.

*

*If a protocol specifies an initializer as a required method, that initializer must be marked using Swift's required keyword.

*Swift has a special set of inheritance rules regarding init methods.

The tl;dr is this:

If you implement any initializers, you are no longer inheriting any of the superclass's designated initializers.

The only initializers, if any, that you will inherit, are super class convenience initializers that point to a designated initializer which you happened to override.
So... ready for the long version?

Swift has a special set of inheritance rules regarding init methods.
I know this was the second of two points I made, but we can't understand the first point, or why the required keyword even exists until we understand this point.  Once we understand this point, the other one becomes pretty obvious.
All of the information I cover in this section of this answer is from Apple's documentation found here.
From the Apple docs:

Unlike subclasses in Objective-C, Swift subclasses do not inherit their superclass initializers by default. Swift's approach prevents a situation in which a simple initializer from a superclass is inherited by a more specialized subclass and is used to create a new instance of the subclass that is not fully or correctly initialized.

Emphasis mine.
So, straight from the Apple docs right there, we see that Swift subclasses will not always (and usually don't) inherit their superclass's init methods.
So, when do they inherit from their superclass?
There are two rules that define when a subclass inherits init methods from its parent.  From the Apple docs:

Rule 1
If your subclass doesn't define any designated initializers, it automatically inherits all of its superclass designated initializers.
Rule 2
If your subclass provides an implementation of all of its superclass designated initializers—either by inheriting them as per rule 1, or by providing a custom implementation as part of its definition—then it automatically inherits all of the superclass convenience initializers.

Rule 2 isn't particularly relevant to this conversation because SKSpriteNode's init(coder: NSCoder) is unlikely to be a convenience method.
So, your InfoBar class was inheriting the required initializer right up until the point that you added init(team: Team, size: CGSize).
If you were to have not provided this init method and instead made your InfoBar's added properties optional or provided them with default values, then you'd have still been inheriting SKSpriteNode's init(coder: NSCoder).  However, when we added our own custom initializer, we stopped inheriting our superclass's designated initializers (and convenience initializers which didn't point to initializers we implemented).
So, as a simplistic example, I present this:
class Foo {
    var foo: String
    init(foo: String) {
        self.foo = foo
    }
}

class Bar: Foo {
    var bar: String
    init(foo: String, bar: String) {
        self.bar = bar
        super.init(foo: foo)
    }
}

let x = Bar(foo: "Foo")

Which presents the following error:

Missing argument for parameter 'bar' in call.

If this were Objective-C, it'd have no problem inheriting.  If we initialized a Bar with initWithFoo: in Objective-C, the self.bar property would simply be nil.  It's probably not great, but it's a perfectly valid state for the object to be in.  It's not a perfectly valid state for the Swift object to be in.  self.bar is not an optional and cannot be nil.
Again, the only way we inherit initializers is by not providing our own.  So if we try to inherit by deleting Bar's init(foo: String, bar: String), as such:
class Bar: Foo {
    var bar: String
}

Now we're back to inheriting (sort of), but this won't compile... and the error message explains exactly why we don't inherit superclass init methods:

Issue: Class 'Bar' has no initializers
Fix-It: Stored property 'bar' without initializers prevents synthesized initializers

If we've added stored properties in our subclass, there's no possible Swift way to create a valid instance of our subclass with the superclass initializers which couldn't possibly know about our subclass's stored properties.

Okay, well, why do I have to implement init(coder: NSCoder) at all?  Why is it required?
Swift's init methods may play by a special set of inheritance rules, but protocol conformance is still inherited down the chain.  If a parent class conforms to a protocol, its subclasses must to conform to that protocol.
Ordinarily, this isn't a problem, because most protocols only require methods which don't play by special inheritance rules in Swift, so if you're inheriting from a class that conforms to a protocol, you're also inheriting all of the methods or properties that allow the class to satisfy protocol conformance.
However, remember, Swift's init methods play by a special set of rules and aren't always inherited.  Because of this, a class that conforms to a protocol which requires special init methods (such as NSCoding) requires that the class mark those init methods as required.
Consider this example:
protocol InitProtocol {
    init(foo: Int)
}

class ConformingClass: InitProtocol {
    var foo: Int
    init(foo: Int) {
        self.foo = foo
    }
}

This doesn't compile.  It generates the following warning:

Issue: Initializer requirement 'init(foo:)' can only be satisfied by a 'required' initializer in non-final class 'ConformingClass'
Fix-It: Insert required

It wants me to make the init(foo: Int) initializer required.  I could also make it happy by making the class final (meaning the class can't be inherited from).
So, what happens if I subclass?  From this point, if I subclass, I'm fine.  If I add any initializers though, I am suddenly no longer inheriting init(foo:).  This is problematic because now I'm no longer conforming to the InitProtocol.  I can't subclass from a class that conforms to a protocol and then suddenly decide I no longer want to conform to that protocol.  I've inherited protocol conformance, but because of the way Swift works with init method inheritance, I've not inherited part of what's required to conform to that protocol and I must implement it.

Okay, this all makes sense.  But why can't I get a more helpful error message?
Arguably, the error message might be more clear or better if it specified that your class was no longer conforming to the inherited NSCoding protocol and that to fix it you need to implement init(coder: NSCoder).  Sure.
But Xcode simply can't generate that message because that actually won't always be the actual problem with not implementing or inheriting a required method.  There is at least one other reason to make init methods required besides protocol conformance, and that's factory methods.
If I want to write a proper factory method, I need to specify the return type to be Self (Swift's equivalent of Objective-C's instanceType).  But in order to do this, I actually need to use a required initializer method.
class Box {
    var size: CGSize
    init(size: CGSize) {
        self.size = size
    }

    class func factory() -> Self {
        return self.init(size: CGSizeZero)
    }
}

This generates the error:

Constructing an object of class type 'Self' with a metatype value must use a 'required' initializer

It's basically the same problem.  If we subclass Box, our subclasses will inherit the class method factory.  So we could call SubclassedBox.factory().  However, without the required keyword on the init(size:) method, Box's subclasses are not guaranteed to inherit the self.init(size:) that factory is calling.
So we must make that method required if we want a factory method like this, and that means if our class implements a method like this, we'll have a required initializer method and we'll run into the exact same problems you've run into here with the NSCoding protocol.

Ultimately, it all boils down to the basic understanding that Swift's initializers play by a slightly different set of inheritance rules which means you're not guaranteed to inherit initializers from your superclass.  This happens because superclass initializers can't know about your new stored properties and they couldn't instantiate your object into a valid state.  But, for various reasons, a superclass might mark an initializer as required.  When it does, we can either employ one of the very specific scenarios by which we actually do inherit the required method, or we must implement it ourselves.
The main point here though is that if we're getting the error you see here, it means that your class isn't actually implementing the method at all.
As perhaps one final example to drill in the fact that Swift subclasses don't always inherit their parent's init methods (which I think is absolutely central to fully understanding this problem), consider this example:
class Foo {
    init(a: Int, b: Int, c: Int) {
        // do nothing
    }
}

class Bar: Foo {
    init(string: String) {
        super.init(a: 0, b: 1, c: 2)
        // do more nothing
    }
}

let f = Foo(a: 0, b: 1, c: 2)
let b = Bar(a: 0, b: 1, c: 2)

This fails to compile.

The error message it gives is a little misleading:

Extra argument 'b' in call

But the point is, Bar doesn't inherit any of Foo's init methods because it hasn't satisfied either of the two special cases for inheriting init methods from its parent class.
If this were Objective-C, we'd inherit that init with no problem, because Objective-C is perfectly happy not initializing objects' properties (though as a developer, you shouldn't have been happy with this).  In Swift, this simply will not do.  You can't have an invalid state, and inheriting superclass initializers can only lead to invalid object states.

A: Why has this issue arisen? Well, the plain fact is that it has always been important (i.e. in Objective-C, since the day I started programming Cocoa back in Mac OS X 10.0) to deal with initializers that your class is not prepared to handle. The docs have always been quite clear about your responsibilities in this regard. But how many of us bothered to fulfill them, completely and to the letter? Probably none of us! And the compiler did not enforce them; it was all purely conventional.
For example, in my Objective-C view controller subclass with this designated initializer:
- (instancetype) initWithCollection: (MPMediaItemCollection*) coll;

...it is crucial that we be passed an actual media item collection: the instance simply cannot come into existence without one. But I have written no "stopper" to prevent someone from initializing me with bare-bones init instead. I should have written one (actually, properly speaking, I should have written an implementation of initWithNibName:bundle:, the inherited designated initializer); but I was too lazy to bother, because I "knew" I would never incorrectly initialize my own class that way. This left a gaping hole. In Objective-C, someone can call bare-bones init, leaving my ivars uninitialized, and we are up the creek without a paddle.
Swift, wonderfully, saves me from myself in most cases. As soon as I translated this app into Swift, the whole problem went away. Swift effectively creates a stopper for me! If init(collection:MPMediaItemCollection) is the only designated initializer declared in my class, I can't be initialized by calling bare-bones init(). It's a miracle!
What's happened in seed 5 is merely that the compiler has realized that the miracle doesn't work in the case of init(coder:), because in theory an instance of this class could come from a nib, and the compiler can't prevent that — and when the nib loads, init(coder:) will be called. So the compiler makes you write the stopper explicitly. And quite right too.

A: add
required init(coder aDecoder: NSCoder!) {
  super.init(coder: aDecoder)
}

A: From an Apple employee on the Developer Forums:

"A way to declare to the compiler and the built program that you really
  don't want to be NSCoding-compatible is to do something like this:"

required init(coder: NSCoder) {
  fatalError("NSCoding not supported")
}

If you know you don't want to be NSCoding compliant, this is an option. I've taken this approach with a lot of my SpriteKit code, as I know I won't be loading it from a storyboard.

Another option you can take which works rather well is to implement the method as a convenience init, like so:
convenience required init(coder: NSCoder) {
    self.init(stringParam: "", intParam: 5)
}

Note the call to an initializer in self. This allows you to only have to use dummy values for the parameters, as opposed to all non-optional properties, while avoiding throwing a fatal error.

The third option of course is to implement the method while calling super, and initialize all of your non-optional properties. You should take this approach if the object is a view being loaded from a storyboard:
required init(coder aDecoder: NSCoder!) {
    foo = "some string"
    bar = 9001

    super.init(coder: aDecoder)
}


text:
Q: How to enable scrollbars in silverlight 3.0 I have set my canvas width to 1500 and height to 1600 in my xaml page in silverlight 3.0.
When I run the testpage I can't see scrollbars. So I am not able to scroll to view rest elements. I also need to set scrollbars for a grid.
How to enable scrollbars?
Please help.

A: Add your components as children of a ScrollViewer.

A: I have got a Scrollbar through this code:
ScrollViewer HorizontalScrollBarVisibility="Auto" VerticalScrollBarVisibility="Auto"


text:
Q: How can I override react-router-dom Link component back link? For what it's worth this is for react-router-dom v5.2.0.
I used to be able to easily override the back button link with the following code:
const MyLink = () => ({
    <Link
        to={{
            pathname: 'go-somewhere',
            state: { previousPath: 'override-previous-path'
        }}
    >
        Go Somewhere
    </Link>
})

By setting previousPath to whatever I would like to override to, it would override whatever I had visited previously. However, now that simply seemed to have stopped working one day.
Looking at the docs the to prop does not seem to have been changed, but the location has. Is it the previousPath state property that is incorrect?
Is there still a way to override the back link through the Link component?

A: Based on what we have discussed in the question comments, it doesn't seem possible to replace the current entry in the history stack by simply setting a previousPath on the state property (at least in react-router-dom v5.2.0).
An alternative solution could be something like this:
import { useHistory, Link } from "react-router-dom";

const MyLink = () => {
  const history = useHistory();

  return (
    <Link to="go-somewhere" onClick={() => history.replace("override-previous-path")}>
      Go Somewhere
    </Link>
  );
};

This will take the user to where you want him to go and it will replace the current entry in the history stack with the route that you want. So... if a .goBack() or a .go(-1) is executed, it will take the user "back" to where you wanted instead of the previous page.


text:
Q: Javascript "EventSource" in C# .NET 5.0 my company choose "Mercure" (https://mercure.rocks/docs/getting-started) to manage Server-Sent Events.
We install "Mercure HUB" on a server and now, in C# .NET 5.0, I must implement the server-side (publisher, that I already implemented) and the client-side (subscriber).
The subscriber must be done with a WPF
From the "getting-started" page I can see a Javascript example that I need to transform into C#
I don't know how to manage a "EventSource" in C#
Any ideas ?
// The subscriber subscribes to updates for the https://example.com/users/dunglas topic
// and to any topic matching https://example.com/books/{id}
const url = new URL('https://localhost/.well-known/mercure');
url.searchParams.append('topic', 'https://example.com/books/{id}');
url.searchParams.append('topic', 'https://example.com/users/dunglas');
// The URL class is a convenient way to generate URLs such as https://localhost/.well-known/mercure?topic=https://example.com/books/{id}&topic=https://example.com/users/dunglas
const eventSource = new EventSource(url);
// The callback will be called every time an update is published
eventSource.onmessage = e => console.log(e); // do something with the payload

A: The code of this page works (https://makolyte.com/event-driven-dotnet-how-to-consume-an-sse-endpoint-with-httpclient/)
static async Task Main(string[] args)
{
    HttpClient client = new HttpClient();
    client.Timeout = TimeSpan.FromSeconds(5);
    string stockSymbol = "VTSAX";
    string url = $"http://localhost:9000/stockpriceupdates/{stockSymbol}";

    while (true)
    {
        try
        {
            Console.WriteLine("Establishing connection");
            using (var streamReader = new StreamReader(await client.GetStreamAsync(url)))
            {
                while (!streamReader.EndOfStream)
                {
                    var message = await streamReader.ReadLineAsync();
                    Console.WriteLine($"Received price update: {message}");
                }
            }
        }
        catch(Exception ex)
        {
            //Here you can check for
            //specific types of errors before continuing
            //Since this is a simple example, i'm always going to retry
            Console.WriteLine($"Error: {ex.Message}");
            Console.WriteLine("Retrying in 5 seconds");
            await Task.Delay(TimeSpan.FromSeconds(5));
        }
    }
}


text:
Q: Background image size not appearing correctly - CSS I've been trying to insert a background image for a specific collection page on Shopify. I was able to edit the collection.liquid file, along with the main.ccs file that allowed the image to appear. I've done this in the past and the image has appeared just fine. I think the issue with the current image I am trying to upload is that it is horizontal. At the moment the image is being cut off and every single thing I have tried to edit the background-size has not worked at all. I just need for the image to fully appear on the screen.
Here is what is in the collection.liquid file:
   <style>
   body { background: url({{ 'slattzy-background-image.jpg' | asset_url }})
   </style>

And here is what is posted in the main.css file:
     .background-element {
       background-image: ({{ 'ssg-background-image.jpg' | asset_url }});
       background-size: 20px 20px;
       background-position: center; /* or 50% 50% */
       background-repeat: no-repeat;

      position: fixed;
      z-index: -1;
      top: 0;
      left: 0;
      right: 0;
      bottom: 0;
     }

A: Try background-size: auto; or background-size: contain; or background-size: cover; depending on wether or not you want the image to stretch.
A background-size of 20px 20px will only display the top left most 20 by 20 pixel part of the original image.
https://www.w3schools.com/cssref/css3_pr_background-size.asp


text:
Q: QQIS Web Client max zoom set to 1:2257: How to zoom more? A similar question was asked as Getting more details by zooming in web-client? but the answer did not work for me. Unfortunately, I can't comment there due to being new to GIS.SE.
Background: The QGIS project has a WMTS service layer of drone aerial imagery (from mbtiles). The Desktop QGIS displays this layer perfectly and lets me zoom in to see the higher resolution of the tiles.
The drone imagery displays OK in QWC but does not let me zoom any closer than 1:2257. The (original desktop) project CRS is EPSG::3857 and in the Desktop project settings>OWS Server>CRS Restrictions is set to EPSG::3857 as the first entry. This .qgs project file was copied to the server and displays OK.
I changed in GlobalOptions.js this
var MapOptions = {
  projection: new OpenLayers.Projection(authid),
  units: "m",
  maxScale:250,
  minScale:80000,
  numZoomLevels:ZOOM_LEVELS,
  fractionalZoom: !enableWmtsBaseLayers && !enableBGMaps,
  transitionEffect:"resize",
  controls: []
};

I cleared the browser cache and refreshed the QWC but the zoom function is still maxed at 1:2257.
I also tried changing in OpenLayers.js: numZoomLevels from 16 to 22.
None of these attempts has changed anything in the QWC.
How do I zoom in more (as there is more detail to see in the drone imagery)?

A: In GlobalOptions.js setting
var enableOSMMaps = false;

and enabling
var enableGoogleCommercialMaps = true;

Allowed me to zoom into 1:282


text:
Q: Changing Joomla 2.5 behaviour for opening articles that shall be edited in a new window I would like to have it so that users that are logged into the frontend of my Joomla site can edit their articles in a new window without any template applied as soon they press on the edit Button, so that only the editor (in this case JCE) is shown.
I found the source code in components/com_content/helpers/Icon.php, but have no idea if it's possible at all or how I have to re-code it. Any idea?
// Show checked_out icon if the article is checked out by a different user
if (property_exists($article, 'checked_out') && property_exists($article, 'checked_out_time') && $article->checked_out > 0 && $article->checked_out != $user->get('id')) {
    $checkoutUser = JFactory::getUser($article->checked_out);
    $button = JHtml::_('image', 'system/checked_out.png', NULL, NULL, true);
    $date = JHtml::_('date', $article->checked_out_time);
    $tooltip = JText::_('JLIB_HTML_CHECKED_OUT').' :: '.JText::sprintf('COM_CONTENT_CHECKED_OUT_BY', $checkoutUser->name).'
 '.$date;
    return ''.$button.'';
}

$url    = 'index.php?option=com_content&task=article.edit&a_id='.$article->id.'&return='.base64_encode(urlencode($uri));
$icon   = $article->state ? 'edit.png' : 'edit_unpublished.png';
$text   = JHtml::_('image', 'system/'.$icon, JText::_('JGLOBAL_EDIT'), NULL, true);

if ($article->state == 0) {
    $overlib = JText::_('JUNPUBLISHED');
}
else {
    $overlib = JText::_('JPUBLISHED');
}

$date = JHtml::_('date', $article->created);
$author = $article->created_by_alias ? $article->created_by_alias : $article->author;

$overlib .= '<br />';
$overlib .= $date;
$overlib .= '<br />';
$overlib .= JText::sprintf('COM_CONTENT_WRITTEN_BY', htmlspecialchars($author, ENT_COMPAT, 'UTF-8'));

$button = JHtml::_('link', JRoute::_($url), $text);

$output = ''.$button.'';

return $output;

A: You should create a template override for the view, in that you can place the link to edit adding:
&tmpl=component

to the url so that only the component part will be shown; and add the
target="_blank" to the <a href or the <form tag so it goes to a new window.
This will most likely open in a new tab, if you want a new window, build the url and pass it to the window.open call.


text:
Q: getelementbyid Multiple ID display I have a drop down where once a subject is clicked it opens selected fields on a list. Is it possible to display two or multiple div's from one click?
Here is my current code;

<select name="travel_arriveVia" id="travel_arriveVia" onchange="showfield(this.options[this.selectedIndex].value)">
    <option selected="selected">Please select ...</option>
    <option value="Hijacking">Hijacking</option>
    <option value="Theft">Theft</option>
    <option value="Overdue Rental">Overdue Rental</option>
    <option value="Other">Other</option>
</select>

So I have tried this;
if(name=='Hijacking')document.getElementById('div1' 'div2').innerHTML='Registration: <input type="text" name="reg" />' +
                'Make: <input type="text" name="make" /> ' + 'Model: <input type="text" name="model" />';
            else document.getElementById('div1').innerHTML='';

What my aim is is to have div1 and div2 show when lets say hijacking is selected, the reason is that lets say div 2 has common fields in other selections in my dropdown

Second Attempt:

<select name="travel_arriveVia" id="travel_arriveVia" onchange="showfield(this.options[this.selectedIndex].value)">
    <option selected="selected">Please select ...</option>
    <option value="Hijacking">Hijacking</option>
    <option value="Theft">Theft</option>
    <option value="Overdue Rental">Overdue Rental</option>
    <option value="Other">Other</option>
</select>

    Registration: <input type="text" name="reg" /> Make: <input type="text" name="make" /> Model: <input type="text" name="model" />

    More html

A: Using jQuery
As a reference: https://jquery.com/
You could change your code using jQuery.
Here is a working example: https://jsfiddle.net/8a20rkwt/
In your head section include jquery like so:

Then use it like so to show multiple elements by id with one click:

In your html:
 <select name="travel_arriveVia" id="travel_arriveVia">
    <option selected="selected">Please select ...</option>
    <option value="Hijacking">Hijacking</option>
    <option value="Theft">Theft</option>
    <option value="Overdue Rental">Overdue Rental</option>
    <option value="Other">Other</option>
</select>

    Registration: <input type="text" name="reg" /> Make: <input type="text" name="make" /> Model: <input type="text" name="model" />

    More html

More details about the jQuery change event handler are here: https://api.jquery.com/change/


text:
Q: SNMP (Ubuntu 18.04) on AudioCodes M500L not working i try to monitor values with nagios over snmp from my two audiocodes SBCs (M500L).
For these i download two MIBs "AC-ALARM-MIB" + "IP-MIB_rfc4293" from https://github.com/librenms/librenms/tree/master/mibs/audiocodes rename it to .txt at the end and upload it to my ubuntu server in path /usr/share/snmp/mibs/.
Then i try to use the following command in command line.
snmpget -v3 -l authPriv -u xxxxxx -a SHA -A xxxxx -x AES -X xxxxx 123.456.789.100 AcAlarm:acActiveAlarmName

and i get the following output
AcAlarm::acActiveAlarmName = No Such Instance currently exists at this OID

I try to find out the OID from these in MIB Browser - seems like it is " .1.3.6.1.4.1.5003.11.1.1.1.1.5". When i use these OID i get same output.
Anyone has an idea?

A: SNMP treats all values as being entries in some database. OIDs are used to identify entries in this conceptual database. MIB files allow an SNMP manager to translate OIDs into a human-readable string, with an accompanying textual description.
The issue here is not that the MIB files are bad, or the OIDs are wrong, the problem is that, either the devices that hold this (imaginary) database do not support the entries you are trying to access, or that your user is not authorized to access those entries. A simple way to find out what OIDs are supported would be to do a full walk of the database, using something like snmpwalk <hostname> 1.3.6.1


text:
Q: raspberry pi not sending to windowsform Any idea why my visual studio doesn't send to windowsform from pi but it does send when i'm using my school's visual studio ( same version ). Do I have to download any specific thing or whatsoever to make it work? Please help.
Here's my code in case too. Would be cool if some1 can go through it and help me with it ( school's project ) Much appreciated !
 string strConnectionString =
        ConfigurationManager.ConnectionStrings["DataCommsDBConnection"].ConnectionString;

    DataComms dataComms;

    public delegate void myprocessDataDelegate(string strData);

    private void saveWaterSensorDataToDB(string strTime, string strWaterValue, string strStatus)
    {
        SqlConnection myConnect = new SqlConnection(strConnectionString);

        string strCommandText = "INSERT MySensor (TimeOccurred, SensorValue, SensorStatus) +" +
            "VALUES (@time, @value, @status)";

        SqlCommand updateCmd = new SqlCommand(strCommandText, myConnect);
        updateCmd.Parameters.AddWithValue("@time", strTime);
        updateCmd.Parameters.AddWithValue("@value", strWaterValue);
        updateCmd.Parameters.AddWithValue("@status", strStatus);

        myConnect.Open();

        int result = updateCmd.ExecuteNonQuery();

        myConnect.Close();
    }

    private string extractStringValue(string strData, string ID)
    {
        string result = strData.Substring(strData.IndexOf(ID) + ID.Length);
        return result;
    }

    private float extractFloatValue(string strData, string ID)
    {
        return (float.Parse(extractStringValue(strData, ID)));
    }

    private void handleWaterSensorData(string strData, string strTime, string ID)
    {
        string strWaterValue = extractStringValue(strData, ID);

        txtWaterValue.Text = strWaterValue;
        txtWaterLevel.Text = strWaterValue;

        float fWaterValue = extractFloatValue(strData, ID);
        string status = "";
        if (fWaterValue <= 500)
            status = "Dry";
        else
            status = "Wet";
        txtRoomStatus.Text = status;

    }

    private void handleButtonData(string strData, string strTime, string ID)
    {
        string strbuttonValue = extractStringValue(strData, ID);

        txtButtonValue.Text = strbuttonValue;
        txtDoorBell.Text = strbuttonValue;
    }

    private void extractSensorData(string strData, string strTime)
    {
        if (strData.IndexOf("WaterLevel=") != -1)
            handleWaterSensorData(strData, strTime, "WaterLevel=");
        else if (strData.IndexOf("BUTTON=") != -1)
            handleButtonData(strData, strTime, "BUTTON=");
    }

    public void handleSensorData(string strData)
    {
        string dt = DateTime.Now.ToString();
        extractSensorData(strData, dt);

        string strMessage = dt + ":" + strData;
        lbDataComms.Items.Insert(0, strMessage);

    }

    public void processDataReceive(string strData)
    {
        myprocessDataDelegate d = new myprocessDataDelegate(handleSensorData);
        lbDataComms.Invoke(d, new object[] { strData });
    }

    public void commsDataReceive(string dataReceived)
    {
        processDataReceive(dataReceived);
    }

    public void commsSendError(string errMsg)
    {
        MessageBox.Show(errMsg);
        processDataReceive(errMsg);
    }

    private void InitComms()
    {
        dataComms = new DataComms();
        dataComms.dataReceiveEvent += new DataComms.DataReceivedDelegate(commsDataReceive);
        dataComms.dataSendErrorEvent += new DataComms.DataSendErrorDelegate(commsSendError);
    }

    public frmDataComms()
    {
        InitializeComponent();
    }

    private void frmDataComms_Load(object sender, EventArgs e)
    {
        InitComms();
    }

    private void btnClear_Click(object sender, EventArgs e)
    {
        lbDataComms.Items.Clear();
    }

    private void btnSendLight_Click(object sender, EventArgs e)
    {
        dataComms.sendData("SENDWATER");
    }

    private void btnSendButton_Click(object sender, EventArgs e)
    {
        dataComms.sendData("SENDBUTTON");
    }

    private void btnCmd_Click(object sender, EventArgs e)
    {
        dataComms.sendData(txtCmd.Text);
    }

    private void btnSendAll_Click(object sender, EventArgs e)
    {
        dataComms.sendData("SENDALL");
    }

    private void btnSendTemp_Click(object sender, EventArgs e)
    {
        dataComms.sendData("SENDTEMP");
    }
}

Form ***
namespace DataCommsRpi
{
public sealed class StartupTask : IBackgroundTask
{
    const int MODE_SENDWATER = 1;
    const int MODE_SENDBUTTON = 2;
    const int MODE_SENDALL = 3;
    const int MODE_SENDTEMP = 4;
    static int curMode;

    Pin waterPin = Pin.AnalogPin2;
    IButtonSensor button = DeviceFactory.Build.ButtonSensor(Pin.DigitalPin4);
    Pin tempPin = Pin.AnalogPin0;

    DataComms dataComms;

    string strDataReceived = "";

    private bool buttonPressed = false;
    private bool prevButtonStatus = false;

    int moistureAdcValue = 800;
    double tempDegree = 20;
    private bool moistureWet = false;
    private bool moistureDry = false;
    private bool tempHot = false;
    private bool tempCold = false;

    private void Sleep(int NoOfMs)
    {
        Task.Delay(NoOfMs).Wait();
    }

    private async void startWaterMonitoring()
    {
        int iPrevAdcValue = 800, iReadAdcValue, iDiff;
        await Task.Delay(100);
        while (true)
        {
            Sleep(500);
            iReadAdcValue = DeviceFactory.Build.GrovePi().AnalogRead(waterPin);
            if (iPrevAdcValue > iReadAdcValue)
                iDiff = iPrevAdcValue - iReadAdcValue;
            else
                iDiff = iReadAdcValue - iPrevAdcValue;
            iPrevAdcValue = iReadAdcValue;
            if (iDiff < 100)
                moistureAdcValue = iReadAdcValue;
        }

    }

    private async void startTempMonitoring()
    {

        await Task.Delay(100);
        int adcValue; double tempCalculated = 0, R;

        while (true)
        {
            Sleep(1000);
            adcValue = DeviceFactory.Build.GrovePi().AnalogRead(tempPin);

            int B = 4250, R0 = 100000;
            R = 100000 * (1023.0 - adcValue) / adcValue;
            tempCalculated = 1 / (Math.Log(R / R0) / B + 1 / 298.15) - 273.15;
            if (!Double.IsNaN(tempCalculated))
                tempDegree = tempCalculated;

        }

    }

    private async void startButtonMonitoring()
    {
        await Task.Delay(100);
        while(true)
        {
            Sleep(100);
            string buttonState = button.CurrentState.ToString();
            if (buttonState.Equals("On"))
            {
                Sleep(100);
                buttonState = button.CurrentState.ToString();
                if(buttonState.Equals("On"))
                {
                    buttonPressed = true;
                }
            }
        }
    }

    private void commsDataReceive(string dataReceived)
    {
        strDataReceived = dataReceived;
        Debug.WriteLine("Data Received : " + strDataReceived);
    }

    private void sendDataToWindows(string strDataOut)
    {
        try
        {
            dataComms.sendData(strDataOut);
            Debug.WriteLine("Sending Msg : " + strDataOut);
        }

        catch(Exception)
        {
            Debug.WriteLine("ERROR. Did you forget to initComms()?");
        }
    }

    private void initComms()
    {
        dataComms = new DataComms();
        dataComms.dataReceiveEvent += new DataComms.DataReceivedDelegate(commsDataReceive);

    }

    private void handleModeSendWater()
    {
        if (moistureAdcValue <= 500)
            moistureWet = true;
        else
            moistureWet = false;
        if (moistureAdcValue <= 500 && moistureDry != moistureWet)
            sendDataToWindows("WaterLevel=" + moistureAdcValue + " wet");
        if (moistureAdcValue > 500 && moistureDry != moistureWet)
            sendDataToWindows("WaterLevel=" + moistureAdcValue + " dry");
        moistureDry = moistureWet;

        if (strDataReceived.Equals("SENDBUTTON"))
        {
            curMode = MODE_SENDBUTTON;
            Debug.WriteLine("===Entering MODE_SENDBUTTON===");
        }
        else if (strDataReceived.Equals("SENDALL"))
        {
            curMode = MODE_SENDALL;
            Debug.WriteLine("===Entering MODE_SENDALL");
        }
        else if (strDataReceived.Equals("SENDTEMP"))
        {
            curMode = MODE_SENDTEMP;
            Debug.WriteLine("===Entering MODE_SENDTEMP");
        }

        strDataReceived = "";
    }

    private void handleModeSendTemperature()
    {
        if (tempDegree <= 31)
            tempCold = true;
        else
            tempCold = false;
        if (tempDegree <= 31 && tempCold != tempHot)
        {
            Sleep(3000);
            sendDataToWindows("Temperature = " + tempDegree.ToString("N2") + " : cold");
        }

        else if (tempDegree >= 32 && tempCold != tempHot)
        {
            Sleep(3000);
            sendDataToWindows("Temperature = " + tempDegree.ToString("N2") + " : hot");
        }

        if (strDataReceived.Equals("SENDBUTTON"))
        {
            curMode = MODE_SENDBUTTON;
            Debug.WriteLine("===Entering MODE_SENDBUTTON===");
        }
        else if (strDataReceived.Equals("SENDALL"))
        {
            curMode = MODE_SENDALL;
            Debug.WriteLine("===Entering MODE_SENDALL");
        }
        else if (strDataReceived.Equals("SENDWATER"))
        {
            curMode = MODE_SENDWATER;
            Debug.WriteLine("===Entering MODE_SENDWATER===");
        }
    }

    private void handleModeSendButton()
    {
        if(buttonPressed != prevButtonStatus)
        {
            sendDataToWindows("BUTTON=" + buttonPressed);
        }

        prevButtonStatus = buttonPressed;
        buttonPressed = false;

        if(strDataReceived.Equals("SENDWATER"))
        {
            curMode = MODE_SENDWATER;
            Debug.WriteLine("===Entering MODE_SENDWATER===");
        }
        else if(strDataReceived.Equals("SENDALL"))
        {
            curMode = MODE_SENDALL;
            Debug.WriteLine("===Entering MODE_SENDALL");
        }
        else if (strDataReceived.Equals("SENDTEMP"))
        {
            curMode = MODE_SENDTEMP;
            Debug.WriteLine("===Entering MODE_SENDTEMP");
        }
    }
    private void handleModeSendAll()
    {
        Sleep(5000);
        sendDataToWindows("Water Level=" + moistureAdcValue);
        sendDataToWindows("Temperature = " + tempDegree.ToString("N2"));

        if (strDataReceived.Equals("SENDWATER"))
        {
            curMode = MODE_SENDWATER;
            Debug.WriteLine("===Entering MODE_SENDWATER");
        }
        else if (strDataReceived.Equals("SENDBUTTON"))
        {
            curMode = MODE_SENDBUTTON;
            Debug.WriteLine("===Entering MODE_SENDBUTTON");
        }
        else if (strDataReceived.Equals("SENDTEMP"))
        {
            curMode = MODE_SENDTEMP;
            Debug.WriteLine("===Entering MODE_SENDTEMP");
        }
    }

    public void Run(IBackgroundTaskInstance taskInstance)
    {
        //
        // TODO: Insert code to perform background work
        //
        // If you start any asynchronous methods here, prevent the task
        // from closing prematurely by using BackgroundTaskDeferral as
        // described in http://aka.ms/backgroundtaskdeferral
        //

        initComms();

        startButtonMonitoring();
        startWaterMonitoring();
        startTempMonitoring();

        curMode = MODE_SENDWATER;

        Debug.WriteLine("===Entering MODE_SENDWATER===");

        while (true)
        {
            Sleep(300);

            if (curMode == MODE_SENDWATER)
                handleModeSendWater();
            else if (curMode == MODE_SENDBUTTON)
                handleModeSendButton();
            else if (curMode == MODE_SENDALL)
                handleModeSendAll();
            else if (curMode == MODE_SENDTEMP)
                handleModeSendTemperature();
            else
                Debug.WriteLine("ERROR: Invalid Mode. Please check your logic");
        }
    }
}
}


text:
Q: Conditional expectation and coupled set of ODEs How to find a coupled set of ODEs and initial conditions for the deterministic functions $a$ and $b$ such that
$$\mathbb{E}\left[e^{-\int_{t}^{T} W^2(u)du} | \mathcal{F(t)}\right] = e^{-a(T-t) - \frac{b(T-t)}{2} W^2(t)}$$
Here, W is a Brownian motion.
This is a homework problem, but I missed the class and now struggling with getting it done, could anyone please explain me how to do this one?
Thank you


text:
Q: Trying to evaluate integral with leftover algebraic terms I'm trying to evaluate the integral

with
import numpy as np
import matplotlib.pyplot as plt
from scipy import integrate

def function(tau, mu, eta):
    return np.cos(mu*tau)/(np.cosh(tau)+eta)**.5
def integrate_function(tau_min, tau_max, mu,eta):
    return integrate.quad(function, tau_min, tau_max, args=(mu,eta,))[0]

# define integration range
tau_min = 0
tau_max = 1000
# define range of a variable
eta_mu_points = np.linspace(1, 10, 100)

results = []
for eta_mu in eta_mu_points:
    value = integrate_function(tau_min, tau_max, eta_mu, eta_mu)
    results.append(value)

plt.plot(eta_mu, results)
plt.ylabel("Integral value")
plt.xlabel("a variable")
plt.show()

Ideally I want to perform the integration and leave mu and eta as parameters. I have tried to make them parameters varying between 1 and 10 but this hasn't worked. Any thoughts? Thank you.


text:
Q: SimpleXML namespaces and attributes I have an xml that looks like this:
<?xml version="1.0" encoding="UTF-8" standalone="no"?>
<epp xmlns="urn:ietf:params:xml:ns:epp-1.0" xmlns:xsi="http://www.w3.org/2001/XMLSchema-instance"
xsi:schemaLocation="urn:ietf:params:xml:ns:epp-1.0 epp-1.0.xsd">
    <response>
        <result code="1001">
            <msg>Command completed successfully; action pending</msg>
            <extValue>
            <value xmlns:epp="urn:ietf:params:xml:ns:epp-1.0">
            <epp:undef/>
            </value>
            <reason>200 Command completed successfully</reason>
            </extValue>
        </result>
        <extension>
            <keyvalue:extension xmlns:keyvalue="http://schema.ispapi.net/epp/xml/keyvalue-1.0"
            xsi:schemaLocation="http://schema.ispapi.net/epp/xml/keyvalue-1.0 keyvalue-1.0.xsd">
                <keyvalue:kv key="APPLICATION" value="3725"/>
                <keyvalue:kv key="AUTH" value="ZBh5ralfPl"/>
                <keyvalue:kv key="CLASS" value="APP_EOI"/>
                <keyvalue:kv key="CREATEDBY" value="SYSTEM"/>
                <keyvalue:kv key="CREATEDDATE" value="2012-09-03 09:47:10"/>
                <keyvalue:kv key="DOMAIN" value="example2.app"/>
                <keyvalue:kv key="DOMAINUMLAUT" value="example2.app"/>
                <keyvalue:kv key="PEERUSER" value=""/>
                <keyvalue:kv key="STATUS" value="REQUESTED"/>
                <keyvalue:kv key="UPDATEBY" value="SYSTEM"/>
                <keyvalue:kv key="UPDATEDDATE" value="2012-09-03 09:47:10"/>
                <keyvalue:kv key="USER" value="test.user"/>
            </keyvalue:extension>
        </extension>
        <trID>
        <svTRID>RW-22720-1346665630348630</svTRID>
        </trID>
    </response>
</epp>

I am trying to iterate through keyvalues until I find the one with the key of APPLICATION.
This is what I have so far
$xml = new SimpleXMLElement($response);
$namespaces = $xml->getNamespaces(true);
$nodes = $xml->response->extension->children($namespaces["keyvalue"])->extension->children($namespaces["keyvalue"])->children();
print_r($nodes);

That returns

SimpleXMLElement Object (
      [@attributes] => Array
          (
              [key] => APPLICATION
              [value] => 3725
          )
)

But I cannot call attributes() method on $nodes or $nodes[0] as it either throws a warning or returns empty element.
Could you please guide me in the right direction?
Thanks

A: Using
->children();

at the end, that is with the default namespace, will give you a child-collection of zero elements. As it's empty, SimpleXML internally runs some optimizations. Accessing it again might lead to errors:
$nodes->attributes()['value']

Warning: main(): Node no longer exists in ...

Perhaps the best way is to just leave it out and name the children you're looking for:
$nodes = ... ->extension->children($namespaces["keyvalue"])->kv;

print_r($nodes[1]->attributes()['value']);

Gives this output:
SimpleXMLElement Object
(
    [0] => ZBh5ralfPl
)

As it's the second <kv> element (zero-based) of which the attribute "value" is accessed.
If you want to leave the concrete element out of it, just leave it out (do not add ->children()). The same example:
$nodes = $xml->response->extension->children($namespaces["keyvalue"])->
               extension->children($namespaces["keyvalue"]);

print_r($nodes[1]->attributes()['value']);

This gives exactly the same output:
SimpleXMLElement Object
(
    [0] => ZBh5ralfPl
)

as there are only <kv> elements as children there, so the numbering does not change.
Hope this helps to shed some light. Perhaps better than all this is to use xpath:
$xml->registerXPathNamespace('kv', $namespaces["keyvalue"]);

var_dump($xml->xpath('//kv:kv[@key = "AUTH"]/@value')[0]);

Which gives:
class SimpleXMLElement#6 (1) {
  public $@attributes =>
  array(1) {
    'value' =>
    string(10) "ZBh5ralfPl"
  }
}

Xpath is specialized on traversal. This is even better when it comes to namespaces.


text:
Q: How many concurrent connections can MarkLogic server process? Is there an upper limit on how many concurrent connections that MarkLogic can process? For example, ASP.NET is restricted to processing 10 requests concurrently, regardless of infrastructure and hardware. Is there a similar restriction in MarkLogic server? If not, are there any benchmarks that give some indication as to how many connections a typical instance can handle?

A: Given a large enough budget there is no practical limit on the number of concurrent connections.
The basic limit is the application server thread count, although excess requests will also pile up in the backlog queue. According to groups.xsd each application server is limited to at most 256 threads. The backlog seems to have no maximum, but most operating systems will silently limit it to something between 256-4096. So depending on whether or not you count the backlog, a single app server on a single host could have 256-4352 concurrent connections.
After that you can use multiple app servers, and add hosts to the cluster. Use a load balancer if necessary. Most operating systems will impose a limit of around 32,000 - 64,000 open sockets per host, but there is no hard limit on the number of hosts or app servers. Eventually request ids might be a problem, but those are 64-bit numbers so there is a lot of headroom.
Of course none of this guarantees that your CPU, memory, disk, and network can keep up with the demand. That is a separate problem, and highly application-specific.


text:
Q: Apache Zeppelin Spark java.lang.NoSuchMethodError: io/netty/buffer/PooledByteBufAllocator.metric()Lio/netty/buffer/PooledByteBufAllocatorMetric; I am running a problem when I try to call pyspark in Apache Zeppelin, see below.
Apache Zeppelin Version 0.8.0
Spark 2.3.0 (git revision a0d7949896) built for Hadoop 2.7.3
Python 3.6.4
OpenJDK Runtime Environment (build 1.8.0_161-b14)
OpenJDK 64-Bit Server VM (build 25.161-b14, mixed mode)
I added in zeppelin-env.sh.
export PATH=$PATH:/usr/local/scala/bin
export PATH=$PATH:/usr/local/spark/bin
export SPARK_HOME=/usr/local/spark

Zeppelin notebook
%pyspark
from pyspark.sql.types import *
from pyspark.sql import functions

java.lang.NoSuchMethodError: io/netty/buffer/PooledByteBufAllocator.metric()Lio/netty/buffer/PooledByteBufAllocatorMetric;
    at org.apache.spark.network.util.NettyMemoryMetrics.registerMetrics(NettyMemoryMetrics.java:80)
    at org.apache.spark.network.util.NettyMemoryMetrics.<init>(NettyMemoryMetrics.java:76)
    at org.apache.spark.network.client.TransportClientFactory.<init>(TransportClientFactory.java:109)
    at org.apache.spark.network.TransportContext.createClientFactory(TransportContext.java:99)
    at org.apache.spark.rpc.netty.NettyRpcEnv.<init>(NettyRpcEnv.scala:71)
    at org.apache.spark.rpc.netty.NettyRpcEnvFactory.create(NettyRpcEnv.scala:461)
    at org.apache.spark.rpc.RpcEnv$.create(RpcEnv.scala:57)
    at org.apache.spark.SparkEnv$.create(SparkEnv.scala:249)
    at org.apache.spark.SparkEnv$.createDriverEnv(SparkEnv.scala:175)
    at org.apache.spark.SparkContext.createSparkEnv(SparkContext.scala:256)
    at org.apache.spark.SparkContext.<init>(SparkContext.scala:423)
    at org.apache.spark.SparkContext$.getOrCreate(SparkContext.scala:2486)
    at org.apache.spark.sql.SparkSession$Builder$$anonfun$7.apply(SparkSession.scala:930)
    at org.apache.spark.sql.SparkSession$Builder$$anonfun$7.apply(SparkSession.scala:921)
    at scala.Option.getOrElse(Option.scala:121)
    at org.apache.spark.sql.SparkSession$Builder.getOrCreate(SparkSession.scala:921)
    at sun.reflect.NativeMethodAccessorImpl.invoke0(Native Method)
    at sun.reflect.NativeMethodAccessorImpl.invoke(NativeMethodAccessorImpl.java:95)
    at sun.reflect.DelegatingMethodAccessorImpl.invoke(DelegatingMethodAccessorImpl.java:55)
    at java.lang.reflect.Method.invoke(Method.java:507)
    at org.apache.zeppelin.spark.BaseSparkScalaInterpreter.spark2CreateContext(BaseSparkScalaInterpreter.scala:202)
    at org.apache.zeppelin.spark.BaseSparkScalaInterpreter.createSparkContext(BaseSparkScalaInterpreter.scala:124)
    at org.apache.zeppelin.spark.SparkScala211Interpreter.open(SparkScala211Interpreter.scala:87)
    at org.apache.zeppelin.spark.NewSparkInterpreter.open(NewSparkInterpreter.java:102)
    at org.apache.zeppelin.spark.SparkInterpreter.open(SparkInterpreter.java:62)
    at org.apache.zeppelin.interpreter.LazyOpenInterpreter.open(LazyOpenInterpreter.java:69)
    at org.apache.zeppelin.spark.PySparkInterpreter.getSparkInterpreter(PySparkInterpreter.java:664)
    at org.apache.zeppelin.spark.PySparkInterpreter.createGatewayServerAndStartScript(PySparkInterpreter.java:260)
    at org.apache.zeppelin.spark.PySparkInterpreter.open(PySparkInterpreter.java:194)
    at org.apache.zeppelin.interpreter.LazyOpenInterpreter.open(LazyOpenInterpreter.java:69)
    at org.apache.zeppelin.interpreter.remote.RemoteInterpreterServer$InterpretJob.jobRun(RemoteInterpreterServer.java:617)
    at org.apache.zeppelin.scheduler.Job.run(Job.java:188)
    at org.apache.zeppelin.scheduler.FIFOScheduler$1.run(FIFOScheduler.java:140)
    at java.util.concurrent.Executors$RunnableAdapter.call(Executors.java:522)
    at java.util.concurrent.FutureTask.run(FutureTask.java:277)
    at java.util.concurrent.ScheduledThreadPoolExecutor$ScheduledFutureTask.access$201(ScheduledThreadPoolExecutor.java:191)
    at java.util.concurrent.ScheduledThreadPoolExecutor$ScheduledFutureTask.run(ScheduledThreadPoolExecutor.java:304)
    at java.util.concurrent.ThreadPoolExecutor.runWorker(ThreadPoolExecutor.java:1153)
    at java.util.concurrent.ThreadPoolExecutor$Worker.run(ThreadPoolExecutor.java:628)
    at java.lang.Thread.run(Thread.java:785)