text:
Q: Unable to Upload file with filename with different extention in php Unable to Upload file with filename with different extention in php
echo basename( $_FILES['uploadedfile']['name']);
$target_path = $target_path . basename( $_FILES['uploadedfile']['name']);
if(move_uploaded_file($_FILES['uploadedfile']['tmp_name'], $target_path)) {
 //  header("Location: EHP_Configuration.html");
 } else{
  //   header("Location: EHP_Configuration.html");
        echo "Notdone";
 }

i have verified that on Echo it show proper filename
But move_upload give me "Notdone"
Regards

A: Have you got error_reporting on? If so check to see if a warning is thrown, if there is no warning and you're just getting FALSE retruned then PHP doesn't think the file is a valid uploaded file (done via PHPs HTTP POST) if you are getting a warning as well as a return value of FALSE this should give some indication as to what the problem with moving the file is.

A: May be you have missed slash here:
$target_path . '/' . basename( $_FILES['uploadedfile']['name']);

I miss it all the time :)


text:
Q: .val() is not working as expected with button. input[type=button] I just tried to create a button with multi-line text value,
<input type="button" value="Carriage
return
separators" style="text-align:center;">

The above piece of code works, however when i try to set the value using jquery it is not working, the inputted value has been rendered as it is. How can we render the inputted text as same as, while we set the value through HTML.?
JS:
$('input').val('Carriage
return');

NON WORKING DEMO

A: The string you give val isn't HTML, it's a JavaScript string. To use carriage returns and newlines, you use \r and \n:
$('input').val('Carriage\r\nreturn');

Updated Fiddle
In contrast (and a lot of people miss this, kudos to you on that), the text inside an attribute in HTML is HTML text, so you can (and sometimes must) use character entities there.

A: Use \n for new line when placing new strings to inputs
jsfiddle:
http://jsfiddle.net/nLf9deb0/

A: Try this:
$('input').val('Carriage\r\nreturn');

A: Try below code:
$('input').val('Carriage\r\nreturn');

Demo :-
http://jsfiddle.net/vjf4ctjg/6/

redpajama_set_name: RedPajamaStackExchange


text:
Q: How to identify a device scanning via bluetooth with other methods It's not a duplicate of any questions.
I'm creating an app which uses bluetooth to find other users using my app who are near you.
With android it's all right. But if I use iOS, is not possible, because as I've read here in stackoverflow, it's not possible to identify a device via bluetooth scan with something which shall be unique, (and if it exists please let me know!!!!) but let me give you an example of what i'm searching:
If two different people are registered in my app (respectively Robin1 and Robin2) and they have the same name in their bluetooth (for example "Robin's iphone"), there is a way to let me know in my app that the first "Robin's iphone" is "Robin1" (his nickname in my app) and the second "Robin's iphone" is "Robin2"?
The only thing I need is the bluetooth scanning 'cause my app is based of users really near you and GPS is not precise... not yet.
I hope this example is written good :/
Thank you

A: Strategies for identifying devices have been widely discussed on the bluetooth-dev mailing list and in many Stack Overflow questions as well. For example, check out this discussion: http://lists.apple.com/archives/bluetooth-dev/2013/Nov/msg00071.html
For simplicity here are two options:

*

*Set the user name to be advertised by the CBAdvertisementDataLocalNameKey in the startAdvertising: call. Though, this is a very brittle solution.

*More robust is to connect to the discovered peripheral and read a characteristic that your application includes to expose the user identifier.

Note that you cannot rely on using the CBPeripheral.identifier for identification as it is going to be a different random value on every device that discovers the peripheral. Also note that if you plan on using backgrounded operation, then that will require special care as many restrictions kick in when the app goes to background.


text:
Q: LazyImage Loading in Auth0 SDK for iOS I'm a brand new developer to swift, and am trying to understand how to load an image into the Auth0 SDK.
The documentation describes this:
        return Lock
            .classic()
            .withStyle {
                $0.logo = LazyImage(name: "myimagename")

However, I'm not sure where to put the image referenced in myimagename?
going into the LazyImage struct, it describes:
 Creates a LazyImage with a name and an optional Bundle.
 For images outside Lock's bundle you should specify the Bundle like

 ```
 let image = LazyImage(name: "image_name")
 ```

So do I somehow add this image to Assets, or in a .plist file or just put a JPG in a folder somewhere?
Thanks

A: If you add the image to the assets folder Images.xcassets it should be able to find it! Let me know if it works.


text:
Q: Where is "sprite" defined? Where exactly in this fiddle: (http://jsfiddle.net/wXs9J/) is "sprite" defined? I'm using the same type of animation in my own program but I get the line: "Uncaught TypeError: Cannot read property 'stateAnimations' of undefined" at the lines:
function drawSprite(sprite) {
    ctx.drawImage(
    sprite.stateAnimations[sprite.currentState].tileset.image,
    sprite.stateAnimations[sprite.currentState].frames[sprite.stateAnimations[sprite.currentState].currentFrame].split(',')[0] * sprite.stateAnimations[sprite.currentState].tileset.tileWidth,
    sprite.stateAnimations[sprite.currentState].frames[sprite.stateAnimations[sprite.currentState].currentFrame].split(',')[1] * sprite.stateAnimations[sprite.currentState].tileset.tileHeight,
    sprite.stateAnimations[sprite.currentState].tileset.tileWidth,
    sprite.stateAnimations[sprite.currentState].tileset.tileHeight,
    Math.round(sprite.positionX),
    Math.round(sprite.positionY),
    sprite.width,
    sprite.height
);
}

Thank you in advance

A: The object
var player = new Sprite({
    'left': spriteLeftAnim,
    'right': spriteRightAnim
}, 'right', canvas.width / 2, canvas.height / 2, 44, 108, 100);

is passed in as a parameter named sprite in the method render()
player is defined in a global scope in the same file.

A: The Sprite consructor is on line 28
A sprite (called player) is created on line 72
This sprite is passed to drawSprite on line 107


text:
Q: B-splines with Scipy : can I add a datapoint without full recompute? I have a bspline created with scipy.interpolate.splrep with points (x_0,y_0) to (x_n,y_n). Usual story. But I would like to add a data point (x_n+1,y_n+1) and appropriate knot without recomputing the entire spline. Can anyone think of a way of doing this elegantly?
I could always take the knot list returned by splrep, and add on the last knot of a smaller spline created with (x_n-2, y_n-2) to (x_n+1,y_n+1) but that seems less efficient than it could be.

A: Short answer: No.
Spline construction is a global process, so if you add a data point, you really need to recompute the whole spline. Which involves solving an N-by-N linear system etc.
If you're adding many knots sequentially, you probably can construct a process where you're using a factorization of the colocation matrix on step n to compute things on step n+1. You'll need to carefully check the stability of this process. And splrep and friends do not give you any help here, so you'll need to write this yourself. (If you do, you might find it helpful to check the sources of interpolate.CubicSpline).
But before you start on that, consider using a local interpolator instead.
If all you want is to add a knot given data, then there's scipy.interpolate.insert.


text:
Q: How to draw OpenGL triangle from other thread in Rust I'm learning OpenGL is Rust by this example: https://github.com/glium/glium/blob/84f82d3098fbc75aa22160b47bf0a2bdada01f07/examples/triangle.rs#L141
It uses a window wrapper called glutin, and draws the triangle once like this:
let draw = move || {
    // building the uniforms
    let uniforms = uniform! {
        matrix: [
            [1.0, 0.0, 0.0, 0.0],
            [0.0, 1.0, 0.0, 0.0],
            [0.0, 0.0, 1.0, 0.0],
            [0.0, 0.0, 0.0, 1.0f32]
        ]
    };

    // drawing a frame
    let mut target = display.draw();
    target.clear_color(0.0, 0.0, 0.0, 0.0);
    target.draw(&vertex_buffer, &index_buffer, &program, &uniforms, &Default::default()).unwrap();
    target.finish().unwrap();
};

The problem is: how can I draw from other threads? In order to call draw I'd have to share it with the other thread, but types like program, index_buffer, vertex_buffer, display are not Send+Sync.
Drawing from other threads is crucial in a window application so I guess they thought of it and there should be a simple way to do it, but I'm lost.

A: You cannot do that with Glium, but this is unlikely to be a problem.
As per issue #459, the memory model was reiterated to no longer allow for graphical resources in the API to be shared with multiple threads. Older versions of Glium were synchronizing calls through a background thread anyway, which means that there was no gain in parallelizing these calls. And although there are ways for OpenGL to have multiple contexts and to share certain resources among them, it is too complicated and inefficient for a Rust API to ensure safe and proper usage.

Drawing from other threads is crucial in a window application

Note that being unable to perform draw operations through multiple threads does not mean that the application itself becomes single-threaded. This is not crucial. The best way to work with this is to dedicate the same thread to rendering and channel commands from other threads into it.
See also:

*

*OpenGL multithreading/shared context and glGenBuffers


text:
Q: Select node in tree based on sibling I've run in to a problem when parsing a node tree. Here's an example XML Document of what I am working with:
<result>
    <type>street_address</type>
    <formatted_address>Krasickiego 6, 83-020 Cedry Wielkie, Poland</formatted_address>
    <address_component>
        <long_name>6</long_name>
        <short_name>6</short_name>
        <type>street_number</type>
    </address_component>
    <address_component>
        <long_name>Krasickiego</long_name>
        <short_name>Krasickiego</short_name>
        <type>route</type>
    </address_component>
    <address_component>
        <long_name>Cedry Wielkie</long_name>
        <short_name>Cedry Wielkie</short_name>
        <type>locality</type>
        <type>political</type>
    </address_component>
    <address_component>
        <long_name>Gmina Cedry Wielkie</long_name>
        <short_name>Gmina Cedry Wielkie</short_name>
        <type>administrative_area_level_3</type>
        <type>political</type>
    </address_component>
    <address_component>
        <long_name>Gdańsk County</long_name>
        <short_name>Gdańsk County</short_name>
        <type>administrative_area_level_2</type>
        <type>political</type>
    </address_component>
    <address_component>
        <long_name>Pomeranian Voivodeship</long_name>
        <short_name>Pomeranian Voivodeship</short_name>
        <type>administrative_area_level_1</type>
        <type>political</type>
    </address_component>
    <address_component>
        <long_name>Poland</long_name>
        <short_name>PL</short_name>
        <type>country</type>
        <type>political</type>
    </address_component>
    <address_component>
        <long_name>83-020</long_name>
        <short_name>83-020</short_name>
        <type>postal_code</type>
    </address_component>
</result>

I want to get the country code (PL) and the postal code (83-020) from this tree. I believe I am able to search the tree for nodes that contain the text "country" and "postal_code" and grab the sibling node with the correct name (for example, search for "country" and grab the sibling node named "short_name"), but I am unsure how. Could I get some help headed in the right direction? I am working in C# and using XPath.

A: This XPath query should return the short_name node that's got a sibling node named type with a value of "postal_code":
XmlNode node = doc.SelectSingleNode("result/address_component[type='postal_code']/short_name")

Do the same to find the country code:
XmlNode node = doc.SelectSingleNode("result/address_component[type='country']/short_name")


text:
Q: Totally ramified p-extension over $F_q((X))$ Let $K=F_q((X))$, from Artin-Schreier theory, for a cyclic extension $L/K$ of degree p, we have $L=K(x)$, $x^p-x=\alpha$. So when $L/K$ is totally ramified, could we find some $x$ s.t the corresponding $\alpha$ has valuation -1? or $\alpha$ has some bounded valuation independent of $L$? Thanks!

A: Artin-Schreier theory gives a bijection between the set of all degree-$p$ cyclic extension of a field $K$ of prime characteristic $p$ and the set of all $\mathbf{F}_p$-lines in the $\mathbf{F}_p$-space $K^+/\wp(K^+)$, where $\wp$ is the endomorphism $x\mapsto x^p-x$ of the additive group $K^+$ (thought of as an $\mathbf{F}_p$-space).
When $K=k((T))$ for some finite extension $k|\mathbf{F}_p$ of degree $f=[k:\mathbf{F}_p]$, the space $K^+/\wp(K^+)$ can be explicitly computed, along with its filtration.  This is done for example in arXiv:0909.2541, from which the following is extracted.
Denote by $\frak{o}$ the ring of integers of $K$, and by $\frak{p}\subset\frak{o}$
the unique maximal ideal of $\frak{o}$.  Concretely, we have ${\frak{o}}=k[[T]]$ and
${\frak{p}}=T{\frak{o}}$.
The filtration on the additive group $K^+$ is given by the powers $({\frak{p}}^n)$ of
$\frak{p}$, indexed by $n\in\mathbf{Z}$. It induces a filtration on the $\mathbf{F}_p$-space $\overline{K^+}=K^+/\wp(K^+)$.  We denote the
induced filtration by $\overline{{\frak{p}}^n}$; we have
$\overline{\frak{p}}=\{0\}$, and the codimension at each step is
given by
$$
\{0\}
\subset_1\overline{\frak{o}}
\subset_f\overline{\frak{p}^{-1}}
\cdots
\subset_f\overline{{\frak{p}}^{-pi+1}}
=\overline{{\frak{p}}^{-pi}}
\subset_f\cdots
\quad\subset\overline{K^+}
$$
Here, $i$ is any integer $>0$, and an
inclusion of $\mathbf{F}_p$-spaces $E\subset_rE'$ means that $E$ is a codimension-$r$
subspace of $E'$.
The unramified degree-$p$ extension of $K$ corresponds to the $\mathbf{F}_p$-line $\overline{\frak{o}}$ (which can be canonically identified with $\mathbf{F}_p$ using the trace map $k\to\mathbf{F}_p$).
So every other line $D$ in this infinite-dimensional $\mathbf{F}_p$-space $K^+/\wp(K^+)$ corresponds to a ramified cyclic degree-$p$ extension $L=K(\wp^{-1}(D))$ of $K$.  If the level of $D$ in the displayed filtration is $m$ (say), in the sense that $m>0$ is the smallest integer such that $D\subset\overline{{\frak{p}}^{-m}}$, then the unique ramification break of $\mathrm{Gal}(L|K)$ occurs at $m$.
Addendum. On my screen, the \overline does't seem to have any effect, which is very confusing.  It is best to read p.17 of the arXiv version referred to above, or 409 of the published version (Journal of the Ramanujan Mathematical Society 25 (2010) 4, 393--417).


text:
Q: RxJava - synchronized block - inner Source I want to use synchronized block for source of flatMap. But I need to use this construct for processing (method processItem), not only when inner source is created.
This Observable is called each 5 minutes (for example Observable.interval)
Observable.fromIterable(getSourceData())
.flatMapCompletable(item -> {
  synchronized(LockManager.getInstance().getLockObject(item.id)){
    return processItem(item)
          .subscribeOn(Schedulers.io());
  }
})

My processsItem method looks like:
public Completable processItem(Item item){
  return mApiSource.getItemById(item.id)
    .flatMap(item ->
      mItemRepository.replace(item)
    )
    .toCompletable();
}

Both inner methods return Single.
It is part of method for periodic updates from server. I need to serialize processItem method call (periodic synchronization of item from server) with methods for modifiction of Item (update, delete) which are called from other classes of project (synchronization for item with ).
Main problem is that periodic update can rewrite newly updated item.
Actually I use this solution:
Chain for updating new item:
public Completable updateItem(Item item){
  return Completable.fromAction(() -> {
        synchronized(LockManager.getInstance().getLockObject(item.id)){
          mApiSource.update(item)
          .flatMap(item ->
            mItemRepository.replace(item)
          )
          .toCompletable()
          .blockingAwait();
        }
      })
      .subscribeOn(Schedulers.io())
}

Chain for periodic update:
Observable.fromIterable(getSourceData())
    .flatMapCompletable(item -> {
      Completable.fromAction(() ->{
        synchronized(LockManager.getInstance().getLockObject(item.id)){
          processItem(item).blockingAwait();
        }
      })
      .subscribeOn(Schedulers.io())
    });

I know that is not clear RxJava solution.
Do you know better solution for this problem?


text:
Q: Why does the clipboard not work with RDP through Microsoft's Unified Access Gateway (UAG)? This one is really driving me nuts...
For one of our customers, we are allowed access using the Microsoft Unified Access Gateway, which provides an HTTPS-tunneled way to (among other things) run Remote Desktop (RDP) towards their server(s).
This works well for me except for one slight caveat: I cannot, by any means, get the clipboard working.
(The server is btw Windows 2008 R2.)
I've tried all the standard measures:

*

*Opening up mstsc.exe and ensuring that the Clipboard box is connected (which it is), connecting to a remote server (veryfing that copy/paste works)

*Running rdpclip manually on the server (it closes down immediately).

*Testing my account on a colleague's machine (running Windows 7 as client, straight on the metal - no virtual machine involved there) - working absolutely flawlessly.

*Testing in numerous different virtual machines myself (Windows 8, three different Windows 7 machines). Always the same issue.

*Logged off my other user account on the host (Mac OS X), to check if that would help.

*Rebooted the host.

*etc...

I'm quite out of ideas. What I did find out is that the .rdp file generated by iexplore/mstsc (in C:\users\plundberg\Local\Temp) incorrectly contains the redirectclipboard:i:0 setting, which is the reason why I cannot start rdpclip.exe manually, and the reason that clipboard redirection is malfunctioning. But why???
This is truly driving me nuts, so... let's hope we have someone out there who has seen the same issue and solved it already. 1000 thanks in advance!

A: Posting my own answer since I found it a while after posting...
It turned out that UAG checks the antivirus installed on the machine. I used to have Windows Defender only, which obviously wasn't considered "good enough". When I installed Symantec Endpoint Protection (which my colleagues were using), it started working instantly.
Thank you for that, Microsoft/whoever. 2 hours of debugging later. But nonetheless, it's quite nice to have it working now. :) :) :)


text:
Q: Is it possible to use one haproxy process to load-balance more than one protocol/port? I've got haproxy to work for us. But right now there are two haproxy processes running. One for HTTP and the other for TCP (RTMP). I've tried to configure both proxies in one configuration file but haproxy only handles HTTP then.
My configuration file:
global
    log 127.0.0.1 local0
    log 127.0.0.1 local1 notice
    #daemon
    debug
    user haproxy
    group haproxy
    maxconn 4096

defaults
    log global
    mode tcp
    option tcplog
    option dontlognull
    option redispatch
    retries 3
    maxconn 2000
    contimeout 10000
    clitimeout 50000
    srvtimeout 50000

listen http :80
    mode tcp
    balance roundrobin

    server h1 xxx.xxx.xxx.xxx:80 check
    server h2 xxx.xxx.xxx.xxx:80 check

listen rtmp :1935
   mode tcp
   balance roundrobin

   server s1 xxx.xxx.xxx.xxx:1935 check
   server s2 xxx.xxx.xxx.xxx:1935 check

This doesn't work for me. It only works when I split the configuration in two (one HTTP, one RTMP) and start two haproxy processes.

A: Ok, I have to answer my own question one more time. Yes, it is possible and my configuration file works. The problem was somewhere outside of HAProxy. Mea culpa.


text:
Q: How to comparing two x significant doubles correctly This is not a duplicate question. There is an answer posted in the question. Hope it can help.
There are two doubles with the same value with decimals.
(Sorry, this is not a good case. because it will return false sometimes, but I can't find the case. If you try this case, it may not have any problem. So don't waste time to test it.)
double a = 0.70448;
double b = 0.70441;

I want to compare them with only 4 decimals.
I have this helper function to round them down to 4 decimals first.
public static double RoundDown(this double value, int decimals)
{
    var multiplier = Math.Pow(10, decimals);
    return Math.Floor(value * multiplier) / multiplier;
}

And then I want to check if a is larger than b like this:
RoundDown(a, 4) > RoundDown(b, 4)
Sometimes, for some cases, it will return true even they look equal. I understand very well this is floating issue, so I would like to know if there any elegant solution to compare them.
Updates:
I have tried to multiply it and compare them in integer. However, for this solution, I need to handle double infinity and NAN.
    private static CompareResult Compare(double a, double b, double decimals = 0)
    {
        var multiplier = Math.Pow(10, decimals);
        var aInt = Convert.ToInt32(a * multiplier);
        var bInt = Convert.ToInt32(b * multiplier);
        return aInt > bInt ? CompareResult.Greater : aInt < bInt ? CompareResult.Less : CompareResult.Equal;
    }

    private enum CompareResult
    {
        Greater,
        Less,
        Equal
    }

System.OverflowException is thrown if one of the double is larger than int max or infinity. Also, this is not an elegant way to compare double.
Importants:
I am not going to round down with x significant figures. I have already provide this solution in my question, my question is: Even round down to x significant figures, it will return true when comparing them.
Again
I am not finding a way to round down or truncate the doubles to x significant digits. I have no problem on this part.
Answer
Thanks for @m88 answer. But it still cannot solve my problem.
I finally solve this issue using sigma. (Reference: http://forums.codeguru.com/showthread.php?506300-float-double-value-comparison-significant-figures.)
Thanks to some people misunderstand the problem and vote it as a duplicated question. I can't post my answer for others facing the same problem. So I post the answer in my question. I hope it can help others.
public static int CompareTo(this double value1, double value2, int decimals)
{
    var diff = value1 - value2;
    var sigma = Math.Pow(10, -decimals - 1);
    return Math.Abs(diff) < sigma ? 0 : diff > 0 ? 1 : -1;
}

A: If you use the Math.Round method to round a and b to 4 decimals, a (0.7045) will always be greater than b (0.7044):
const double a = 0.70448;
const double b = 0.70441;
if (Math.Round(a, 4) > Math.Round(b, 4))
...

If you want to truncate the values, you need to be aware of the fact that not all fractions can be accurately represented in a double. If you want "exact" truncating, you might consider converting the double value to a string, truncate the string and then convert the truncated string value back to double. Something like this:
private static double Truncate(double d, int decimals)
{
    string s = d.ToString(System.Globalization.CultureInfo.InvariantCulture);
    int index = s.IndexOf(System.Globalization.CultureInfo.InvariantCulture.NumberFormat.NumberDecimalSeparator);
    if (index > -1)
        return Convert.ToDouble($"{s.Substring(0, index + 1)}{s.Substring(index + 1, decimals)}", System.Globalization.CultureInfo.InvariantCulture);

    return d;
}

Usage:
const double a = 0.70448;
const double b = 0.70441;

if (Truncate(a, 4) >= Truncate(b, 4))
....

Obviously, if you don't want any "floating issues" as you said in the chat, you cannot work with floating point data types.

A: You want to truncate, not round:
double a = Math.Truncate(100 * 0.70448) / 100;
double b = Math.Truncate(100 * 0.70441) / 100;

if (a > b)
{
    // ...
}

Note that fractions cannot be accurately represented in a double, as per @mm8's comment.


text:
Q: SPWeb.GetFile for an old version of file I have a document library with enabled versioning, I added an xml file, then added it again, but I have edited one value in it. Now I would like to get the content of both files in C# to compare them. I know this could be achieved with SPFileVersion.OpenBinary(), but I would prefer to get it with myFile = web.GetFile(SPFileVersion.Url) and then operate on myFile.OpenBinary. Unfortunately GetFile() doesn't seem to be working here, I tried different path combinations (with site url, without it) and most of the fields in myFile throw FileNotFoundException. Does someone know, if is is possible at all to get the content of previous versions of the file like that?

A: You can't get a SPFile from the SPFileVersion.Url, the Exists property will be false as it isn't the right url for the file.
There is two ways for you to get the content of the old version:

*

*Through the SharePoint object mode SPFileVersion.OpenBinary/OpenBinaryStream

*Through a web request for SPFileVersion.Url (prefixed by SPWeb.Url)

If your code runs on the server you should always use method 1. Method 2 is for when you want to allow client computers to download the file.


text:
Q: PHP mention script I'm working on a mention script that gets an users profile link when it is being mentioned in a news article or something. I've done the mention script, but it splits the users name after it finds a space. When an user wants to mention somebody they will start their name with a @ symbol.
So my script stops after it finds a space. That means if I wanted to mention an username such as @This is. It would only pick up This.
Could anyone tell me how I can pick up usernames with spaces in? Here is my script.
    <?php

 $string = "I'm wanting to speak to the user @This is please.";
 $explosion = explode("@", $string);
 $count = count($explosion);

 for($i = 0; $i < $count; $i++){
    $explosion2 = explode(" ", $explosion[$i]);
    $explosion2 = $explosion2[0];

    $string = str_replace("@{$explosion2}", "{$explosion2} yeah", $string);
 }

 echo $string;
?>

Thank you.

A: What if there are two users named "This" and "This is" and you have a text: "@This is, do you think @This is being serious?"
My advice would be to disallow spaces in usernames. It can cause more trouble than it's worth in many other situations anyway (URL creation, for instance).

A: There's no way to figure out if a username is just one word or multiple words from your example because the username has the exact same formatting as the rest of the string. There are a few ways you can fix this.
You explode on @ then read up until you reach some indicator of the end of the username. So strings would then need to be altered to have special indicators at the beginning AND END of usernames:
$string = "I'm wanting to speak to the user @This is@ please.";

This would be very convenient for you because you would only have to call explode once since the whole username would be in the array's second element.

A: Do you have a way to look up names? What I mean is, you need to be able to exclude This is (and even This is please) in order to find the user This (if that was the intended user).
The naïve implementation would extract the string between the @ character and the first character not valid in a username (e.g., .). This would give the string This is please. You could then chop off one word at a time and see if a username matches.
This strategy, however, does not allow me to mention the user This in the string "@This is not me." if the user This is exists.
To overcome this, the mention should be explicit with regard to the username. This can be achieved via delimiters (character that can themselves not be part of the username), e.g.:
I'm wanting to speak to the user [This is] please.

See @Jons' answer, too.

A: You have to edit this line:
$explosion2 = explode(" ", $explosion[$i]);

Other wise it will get only the first word. If you want take all the name up until a dot for example do this:
$explosion2 = explode(".", $explosion[$i]);

A: You cannot do that. Usually username doesn't contain spaces.

A: You definitely need to use a callback and need some means to determine if a username exists. You cannot guess from the words alone. And for simplicity I would prefer a regex callback here:
$str= preg_replace_callback('/@(\w+)( \w+)?( \w+)?/', 'rx_users', $str);

function rx_users($match) {
    list($asis, $one, $two, $three) = $match;

    if (user_exists($user=$one)
    or  user_exists($user="$one$two")
    or  user_exists($user="$one$two$three"))
    {
        return "$user";
    }
    else return $asis;
}

So it doesn't work without a user_exists() test. But you can of course always fallback to assuming the username is just @$one word per default.

A: I believe the solution to this problem would be to assign a unique numerical identifier to each registered user on sign up.
Each user could then be referenced by username and/or their real name - with or without spaces between first and second names.
Strings beginning with @ would initiate a search of all users in a list which could then be selected from a drop down much like facebook or twitter.


text:
Q: Is IndexedDB suitable for providing suggestions as user types input Currently I have a website with an input element with an event listener that is fired by the input event. Any new input results in an Ajax request where an SQL query is made, which uses the LIKE keyword to find all records which have the contents of the input element as a substring. There can be as many as over a million records in the SQLite database.
I would like this to work for users when they are off line, so I have thought about using IndexedDB storage so they could download the data to their device when online and then use the system when they are offline. I did read at https://developer.mozilla.org/en-US/docs/Web/API/IndexedDB_API/Basic_Terminology that

The API does not have an equivalent of the LIKE operator in SQL.

I have almost no experience in any databases other than SQL types. I would like to find out before getting too involved whether the IndexedDB API would be suitable for achieving the type of auto suggestion feature for user input that I have described.

A: IndexedDB essentially only allows you to retrieve objects by primary key or by a property that you have specifically created an index for. These will be exact match or range match lookups. You can't look inside strings for substring matches.
However, this does not mean that you should not use IndexedDB to store your data. It just means that you need a layer on top such as Elasticlunr.js which will build a search index. You can rebuild that index every time the database changes, and persist that search index to the database.


text:
Q: How to use the method setPixels(rectangle, byteArray) of bitmapData in Adobe Flex Error #2030: End of file was encountered.

This method is not working
I am using it like this
var ba:ByteArray = new ByteArray();
ba = bmd.getPixels(bmd.rect);

bmd.setPixels(srcRect, ba);
bm.bitmapData = bmd;

img.source = bm;

A: You need to reset the possition of your Byte Array (ba.position = 0) before re-using it
var ba:ByteArray = new ByteArray();
ba = bmd.getPixels(bmd.rect);

ba.position = 0;
bmd.setPixels(srcRect, ba);
bm.bitmapData = bmd;

img.source = bm;


text:
Q: Reordering columns in a cursor passed as a ref cursor to a stored procedure Here is what I need to do...  I have a simple stored procedure that is defined like this...
TYPE p_CURSOR IS REF CURSOR;

CREATE PROCEDURE getAll_TableA(p_items OUT p_CURSOR) AS
BEGIN
    OPEN p_items FOR SELECT * FROM TableA;
END;

Now I have another stored procedure
CREATE PROCEDURE reorderCursorColumns_TableA(i_items IN p_CURSOR, p_items OUT p_CURSOR) AS
BEGIN
   /*
   DO SOMETHING LIKE THIS
   */
   OPEN p_items FOR SELECT col5, col3, col2, col4, col1 FROM i_items;
END;

Is this possible?
Essentially, given a cursor, can I select from it to reorder the columns?

A: You can't cast a cursor as a table. You would need to write a table function and then query that with something like:
select x, y, z
from   table(yourfunction(i_items));

The function would return a table (collection). You would need to define a collection type matching your requirement.


text:
Q: how to Find n nearest lines for the given points from a collection of lines? I have two tables, points and lines. For each point in point table, I want to find out nearest 3 points in the nearest 3 cables.
I almost developed a query, but it is best suitable for single point, but i need a query for all the points in the point table.
My query is
select * from (
with index_query as (
select l.data,p.data, ST_Distance(c.geom,p.geom) as distance,
ST_AsText(st_line_interpolate_point(l.geom,
st_line_locate_point(l.geom, p.geom))) as nearest_point_in_line,
from lines l,points p order by l.geom <#> p.geom limit 100)
select *,RANK() OVER (PARTITION BY pid order by distance ) AS r
from index_query ) as s where r < 4

LIMIT 100 is the limiting factor, which is limiting total output rows to 100 irrespective of number of points in Point table.
I need nearest 3 point_in_line for all points in my table. Total 3*no of rows in point table. How to achieve it?

A: I think your solution is quite elegant.
I guess what you want to do that you don't succeed in doing is getting help from indexes distance ordering.
From the query it looks like you are aware that the <#> operator only works on the bounding box not the real geoemtry.
But you will get in another trouble. As stated in the documentation: http://postgis.net/docs/manual-2.1/geometry_distance_box.html
"Index only kicks in if one of the geometries is a constant e.g. ORDER BY (ST_GeomFromText('POINT(1 2)') <#> geom) instead of g1.geom <#>."
That means you will not get the help from the index.
The best you can do is reducing the calculations done on all combinations. So what I have done in the example below is moving out the calculation of closest point on line to after you have fount the three closest lines. In your query you do that calculation on all combinations.
As you see I also use ST_ClosestPoint instead of the combination of st_line_interpolate_point and st_line_locate_point. ST_ClosestPoint was added in PostGIS 1.5.
select *, ST_AsText(ST_ClosestPoint(l.geom, p.geom)) nearest_point_in_line from (
with index_query as (
select l.id, p.pid, l.data,p.data,l.geom, p.geom, ST_Distance(l.geom,p.geom) as distance
from lines l,points p)
select *,RANK() OVER (PARTITION BY pid order by distance ) AS r
from index_query ) as s where r < 4

HTH

A: SELECT row_number() as gid,
ST_AsText(st_line_interpolate_point(g.geom, st_line_locate_point(g.geom, g.pgeom))) as nearest_point_in_line,
  FROM
  (SELECT p.geom, k.geom as pgeom,  p.gid as pgid, k.gid, ST_Distance(p.geom,k.geom)as dis
    , RANK() OVER (PARTITION BY k.gid ORDER BY ST_Distance(p.geom,k.geom) ASC)as r
  from lines p , points k )as u WHERE u.r<4) as g

Does that do the trick . inner sql returns 3 lines per point geom. Outer interpolates point. But main difference to your and @Nicklas Aven solution is that inner SQL does "everything" and outer just created new data. It would be fun to know if those two solutions have any performance difference for future reference.


text:
Q: SQL calculate SUM of part of the data I have a table date, subs, unsubs, where date is PK, and subs and unsubs are the number of subscribes and unsubscribes on that date.
I want to add a column to calculate the number of total subscribers on each day, that is, if sort date, subsall = subsall of last row + subs - unsubs.
For example: the table is
----------------
2012-01-01, 5, 2
2012-01-02, 6, 1
2012-01-03, 4, 3
----------------

I want to add a new column and the table becomes
-------------------
2012-01-01, 5, 2, 3
2012-01-02, 6, 1, 8
2012-01-03, 4, 3, 9
-------------------

What is the MySQL command to do that?

A: You are looking for a cumulative sum. Try this:
SELECT date, subs, unsubs, (@csum := @csum + subs - unsubs) cumulative
FROM table, (SELECT @csum :=0) c
ORDER BY date

A: You should create trigger on INSERT action, please see the manual: http://dev.mysql.com/doc/refman/5.0/en/create-trigger.html

A: You can just select the difference of the two columns and give it an alias of 'subsall' like this:
SELECT date, subs, unsubs, (subs - unsubs) as 'subsall' FROM table

A: SELECT (COUNT(subs) - COUNT(unsubs)) as total subscribers from table
GROUP BY DATE_FORMAT(date, '%d-%m-%Y')

Hope this works for you.


text:
Q: Authorize By Group in Azure Active Directory B2C I am trying to figure out how to authorize using groups in Azure Active Directory B2C. I can Authorize via User, for example:
[Authorize(Users="Bill")]

However, this is not very effective and I see very few use-cases for this. An alternate solution would be Authorizing via Role. However for some reason that does not seem to work. It does not work if I give a user the Role "Global Admin" for example, and try:
[Authorize(Roles="Global Admin")]

Is there a way to authorize via Groups or Roles?

A: Obtaining group memberships for a user from Azure AD requires quite a bit more than just "a couple lines of code", so I thought I'd share what finally worked for me to save others a few days worth of hair-pulling and head-banging.
Let's begin by adding the following dependencies to project.json:
"dependencies": {
    ...
    "Microsoft.IdentityModel.Clients.ActiveDirectory": "3.13.8",
    "Microsoft.Azure.ActiveDirectory.GraphClient": "2.0.2"
}

The first one is necessary as we need to authenticate our application in order for it to be able to access AAD Graph API.
The second one is the Graph API client library we'll be using to query user memberships.
It goes without saying that the versions are only valid as of the time of this writing and may change in the future.
Next, in the Configure() method of the Startup class, perhaps just before we configure OpenID Connect authentication, we create the Graph API client as follows:
var authContext = new AuthenticationContext("https://login.microsoftonline.com/<your_directory_name>.onmicrosoft.com");
var clientCredential = new ClientCredential("<your_b2c_app_id>", "<your_b2c_secret_app_key>");
const string AAD_GRAPH_URI = "https://graph.windows.net";
var graphUri = new Uri(AAD_GRAPH_URI);
var serviceRoot = new Uri(graphUri, "<your_directory_name>.onmicrosoft.com");
this.aadClient = new ActiveDirectoryClient(serviceRoot, async () => await AcquireGraphAPIAccessToken(AAD_GRAPH_URI, authContext, clientCredential));

WARNING: DO NOT hard-code your secret app key but instead keep it in a secure place. Well, you already knew that, right? :)
The asynchronous AcquireGraphAPIAccessToken() method that we handed to the AD client constructor will be called as necessary when the client needs to obtain authentication token. Here's what the method looks like:
private async Task<string> AcquireGraphAPIAccessToken(string graphAPIUrl, AuthenticationContext authContext, ClientCredential clientCredential)
{
    AuthenticationResult result = null;
    var retryCount = 0;
    var retry = false;

    do
    {
        retry = false;
        try
        {
            // ADAL includes an in-memory cache, so this will only send a request if the cached token has expired
            result = await authContext.AcquireTokenAsync(graphAPIUrl, clientCredential);
        }
        catch (AdalException ex)
        {
            if (ex.ErrorCode == "temporarily_unavailable")
            {
                retry = true;
                retryCount++;
                await Task.Delay(3000);
            }
        }
    } while (retry && (retryCount < 3));

    if (result != null)
    {
        return result.AccessToken;
    }

    return null;
}

Note that it has a built-in retry mechanism for handling transient conditions, which you may want to tailor to your application's needs.
Now that we have taken care of application authentication and AD client setup, we can go ahead and tap into OpenIdConnect events to finally make use of it.
Back in the Configure() method where we'd typically call app.UseOpenIdConnectAuthentication() and create an instance of OpenIdConnectOptions, we add an event handler for the OnTokenValidated event:
new OpenIdConnectOptions()
{
    ...
    Events = new OpenIdConnectEvents()
    {
        ...
        OnTokenValidated = SecurityTokenValidated
    },
};

The event is fired when access token for the signing-in user has been obtained, validated and user identity established. (Not to be confused with the application's own access token required to call AAD Graph API!)
It looks like a good place for querying Graph API for user's group memberships and adding those groups onto the identity, in the form of additional claims:
private Task SecurityTokenValidated(TokenValidatedContext context)
{
    return Task.Run(async () =>
    {
        var oidClaim = context.SecurityToken.Claims.FirstOrDefault(c => c.Type == "oid");
        if (!string.IsNullOrWhiteSpace(oidClaim?.Value))
        {
            var pagedCollection = await this.aadClient.Users.GetByObjectId(oidClaim.Value).MemberOf.ExecuteAsync();

            do
            {
                var directoryObjects = pagedCollection.CurrentPage.ToList();
                foreach (var directoryObject in directoryObjects)
                {
                    var group = directoryObject as Group;
                    if (group != null)
                    {
                        ((ClaimsIdentity)context.Ticket.Principal.Identity).AddClaim(new Claim(ClaimTypes.Role, group.DisplayName, ClaimValueTypes.String));
                    }
                }
                pagedCollection = pagedCollection.MorePagesAvailable ? await pagedCollection.GetNextPageAsync() : null;
            }
            while (pagedCollection != null);
        }
    });
}

Used here is the Role claim type, however you could use a custom one.
Having done the above, if you're using ClaimType.Role, all you need to do is decorate your controller class or method like so:
[Authorize(Role = "Administrators")]

That is, of course, provided you have a designated group configured in B2C with a display name of "Administrators".
If, however, you chose to use a custom claim type, you'd need to define an authorization policy based on the claim type by adding something like this in the ConfigureServices() method, e.g.:
services.AddAuthorization(options => options.AddPolicy("ADMIN_ONLY", policy => policy.RequireClaim("<your_custom_claim_type>", "Administrators")));

and then decorate a privileged controller class or method as follows:
[Authorize(Policy = "ADMIN_ONLY")]

Ok, are we done yet? - Well, not exactly.
If you ran your application and tried signing in, you'd get an exception from Graph API claiming "Insufficient privileges to complete the operation".
It may not be obvious, but while your application authenticates successfully with AD using its app_id and app_key, it doesn't have the privileges required to read the details of users from your AD.
In order to grant the application such access, I chose to use the Azure Active Directory Module for PowerShell
The following script did the trick for me:
$tenantGuid = "<your_tenant_GUID>"
$appID = "<your_app_id>"

$userVal = "<admin_user>@<your_AD>.onmicrosoft.com"
$pass = "<admin password in clear text>"
$Creds = New-Object System.Management.Automation.PsCredential($userVal, (ConvertTo-SecureString $pass -AsPlainText -Force))

Connect-MSOLSERVICE -Credential $Creds
$msSP = Get-MsolServicePrincipal -AppPrincipalId $appID -TenantID $tenantGuid

$objectId = $msSP.ObjectId

Add-MsolRoleMember -RoleName "Company Administrator" -RoleMemberType ServicePrincipal -RoleMemberObjectId $objectId

And now we're finally done!
How's that for "a couple lines of code"? :)

A: i implmented this as written , but as of May 2017 the line
((ClaimsIdentity)context.Ticket.Principal.Identity).AddClaim(new Claim(ClaimTypes.Role, group.DisplayName, ClaimValueTypes.String));

needs to be changed to
((ClaimsIdentity)context.Ticket.Principal.Identity).AddClaim(new Claim(ClaimTypes.Role, group.DisplayName));

To make it work with latest libs
Great work to the author
Also if your having a problem with Connect-MsolService giving bad username and password update to latest lib

A: Alex's answer is essential to figure out a working solution, thanks for pointing to the right direction.
However it uses app.UseOpenIdConnectAuthentication() which was long time depreciated already in Core 2 and completely removed in Core 3 (Migrate authentication and Identity to ASP.NET Core 2.0)
The fundamental task we must implement is attach an event handler to OnTokenValidated using OpenIdConnectOptions which is used by ADB2C Authentication under the hood. We must do this without interfering any other configuration of ADB2C.
Here is my take:
// My (and probably everyone's) existing code in Startup:
services.AddAuthentication(AzureADB2CDefaults.AuthenticationScheme)
        .AddAzureADB2C(options => Configuration.Bind("AzureAdB2C", options));

// This adds the custom event handler, without interfering any existing functionality:
services.Configure<OpenIdConnectOptions>(AzureADB2CDefaults.OpenIdScheme,
options =>
{
    options.Events.OnTokenValidated =
        new AzureADB2CHelper(options.Events.OnTokenValidated).OnTokenValidated;
});

All implementation is encapsulated in a helper class to keep Startup class clean. The original event handler is saved and called in case if it is not null (it is not btw)
public class AzureADB2CHelper
{
    private readonly ActiveDirectoryClient _activeDirectoryClient;
    private readonly Func<TokenValidatedContext, Task> _onTokenValidated;
    private const string AadGraphUri = "https://graph.windows.net";

    public AzureADB2CHelper(Func<TokenValidatedContext, Task> onTokenValidated)
    {
        _onTokenValidated = onTokenValidated;
        _activeDirectoryClient = CreateActiveDirectoryClient();
    }

    private ActiveDirectoryClient CreateActiveDirectoryClient()
    {
        // TODO: Refactor secrets to settings
        var authContext = new AuthenticationContext("https://login.microsoftonline.com/<yourdomain, like xxx.onmicrosoft.com>");
        var clientCredential = new ClientCredential("<yourclientcredential>", @"<yourappsecret>");

        var graphUri = new Uri(AadGraphUri);
        var serviceRoot = new Uri(graphUri, "<yourdomain, like xxx.onmicrosoft.com>");
        return new ActiveDirectoryClient(serviceRoot,
            async () => await AcquireGraphAPIAccessToken(AadGraphUri, authContext, clientCredential));
    }

    private async Task<string> AcquireGraphAPIAccessToken(string graphAPIUrl,
        AuthenticationContext authContext,
        ClientCredential clientCredential)
    {
        AuthenticationResult result = null;
        var retryCount = 0;
        var retry = false;

        do
        {
            retry = false;
            try
            {
                // ADAL includes an in-memory cache, so this will only send a request if the cached token has expired
                result = await authContext.AcquireTokenAsync(graphAPIUrl, clientCredential);
            }
            catch (AdalException ex)
            {
                if (ex.ErrorCode != "temporarily_unavailable")
                {
                    continue;
                }

                retry = true;
                retryCount++;
                await Task.Delay(3000);
            }
        } while (retry && retryCount < 3);

        return result?.AccessToken;
    }

    public Task OnTokenValidated(TokenValidatedContext context)
    {
        _onTokenValidated?.Invoke(context);
        return Task.Run(async () =>
        {
            try
            {
                var oidClaim = context.SecurityToken.Claims.FirstOrDefault(c => c.Type == "oid");
                if (!string.IsNullOrWhiteSpace(oidClaim?.Value))
                {
                    var pagedCollection = await _activeDirectoryClient.Users.GetByObjectId(oidClaim.Value).MemberOf
                        .ExecuteAsync();

                    do
                    {
                        var directoryObjects = pagedCollection.CurrentPage.ToList();
                        foreach (var directoryObject in directoryObjects)
                        {
                            if (directoryObject is Group group)
                            {
                                ((ClaimsIdentity) context.Principal.Identity).AddClaim(new Claim(ClaimTypes.Role,
                                    group.DisplayName, ClaimValueTypes.String));
                            }
                        }

                        pagedCollection = pagedCollection.MorePagesAvailable
                            ? await pagedCollection.GetNextPageAsync()
                            : null;
                    } while (pagedCollection != null);
                }
            }
            catch (Exception e)
            {
                Debug.WriteLine(e);
            }
        });
    }
}

You will need the appropriate packages I am using the following ones:
<PackageReference Include="Microsoft.AspNetCore.Authentication.OpenIdConnect" Version="3.0.0" />
<PackageReference Include="Microsoft.AspNetCore.Mvc.NewtonsoftJson" Version="3.0.0" />
<PackageReference Include="Microsoft.Azure.ActiveDirectory.GraphClient" Version="2.1.1" />
<PackageReference Include="Microsoft.IdentityModel.Clients.ActiveDirectory" Version="5.2.3" />

Catch: You must give your application permission to read AD. As of Oct 2019 this application must be a 'legacy' app and not the newest B2C application. Here is a very good guide: Azure AD B2C: Use the Azure AD Graph API

A: There is an official sample: Azure AD B2C: Role-Based Access Control
available here from the Azure AD team.
But yes, the only solution seems to be a custom implementation by reading user groups with the help of MS Graph.

A: Based on all the amazing answers here, getting user groups using the new Microsoft Graph API

IConfidentialClientApplication confidentialClientApplication = ConfidentialClientApplicationBuilder
          .Create("application-id")
          .WithTenantId("tenant-id")
          .WithClientSecret("xxxxxxxxx")
          .Build();

ClientCredentialProvider authProvider = new ClientCredentialProvider(confidentialClientApplication);

GraphServiceClient graphClient = new GraphServiceClient(authProvider);

var groups = await graphClient.Users[oid].MemberOf.Request().GetAsync();

A: This will work, however you have to write a couple of lines of code in your authentication logic in order to achieve what you're looking for.
First of all, you have to distinguish between Roles and Groups in Azure AD (B2C).
User Role is very specific and only valid within Azure AD (B2C) itself. The Role defines what permissions a user does have inside Azure AD .
Group (or Security Group) defines user group membership, which can be exposed to the external applications. The external applications can model Role based access control on top of Security Groups. Yes, I know it may sound a bit confusing, but that's what it is.
So, your first step is to model your Groups in Azure AD B2C - you have to create the groups and manually assign users to those groups. You can do that in the Azure Portal (https://portal.azure.com/):

Then, back to your application, you will have to code a bit and ask the Azure AD B2C Graph API for users memberships once the user is successfully authenticated. You can use this sample to get inspired on how to get users group memberships. It is best to execute this code in one of the OpenID Notifications (i.e. SecurityTokenValidated) and add users role to the ClaimsPrincipal.
Once you change the ClaimsPrincipal to have Azure AD Security Groups and "Role Claim" values, you will be able to use the Authrize attribute with Roles feature. This is really 5-6 lines of code.
Finally, you can give your vote for the feature here in order to get group membership claim without having to query Graph API for that.

A: I really like the answer from @AlexLobakov but I wanted an updated answer for .NET 6 and also something that was testable but still implemented the caching features. I also wanted the roles to be sent to my front end, be compatible with any SPA like React and use standard Azure AD B2C User flows for Role-based access control (RBAC) in my application.
I also missed a start to finish guide, so many variables that can go wrong and you end up with an application not working.
Start with creating a new ASP.NET Core Web API in Visual Studio 2022 with the following settings:

You should get a dialogue like this after creation:

If you don't see this then right click on the project in Visual Studio and click on Overview and then Connected services.

Create a new App registration in your Azure AD B2C or use an existing. I registered a new one for this demo purpose.

After creating the App registration Visual Studio got stuck on Dependency configuration progress so the rest will be configured manually:

Log on to https://portal.azure.com/, Switch directory to your AD B2C, select your new App registration and then click on Authentication. Then click on Add a platform and select Web.
Add a Redirect URI and Front-channel logout URL for localhost.
Example:
https://localhost:7166/signin-oidc
https://localhost:7166/logout

If you choose Single-page application instead it will look nearly the same. However you then need to add a code_challenge as described below. A full example for this will not be shown.
Is Active Directory not supporting Authorization Code Flow with PKCE?

Authentication should look something like this:

Click on Certificates & secrets and create a new Client secret.
Click on Expose an API and then edit Application ID URI.
Default value should look something like this api://11111111-1111-1111-1111-111111111111. Edit it to be https://youradb2c.onmicrosoft.com/11111111-1111-1111-1111-111111111111. There should be a scope named access_as_user. Create if it is not there.
Now click on API permissions:
Four Microsoft Graph permissions are needed.
Two Application:
GroupMember.Read.All
User.Read.All

Two Delegated:
offline_access
openid

You also need your access_as_user permission from My APIs. When this is done click on Grant admin consent for .... Should look like this:

If you don't have a User Flow already then create either a Sign up and sign in or a Sign in and select Recommended. My user flow is default B2C_1_signin.

Verify that your AD B2C user is a member of the group you want to authenticate against:

Now you can go back to your application and verify that you can get a code to login. Use this sample and it should redirect with a code:
https://<tenant-name>.b2clogin.com/tfp/<tenant-name>.onmicrosoft.com/<user-flow-name>/oauth2/v2.0/authorize?
client_id=<application-ID>
&nonce=anyRandomValue
&redirect_uri=https://localhost:7166/signin-oidc
&scope=https://<tenant-name>.onmicrosoft.com/11111111-1111-1111-1111-111111111111/access_as_user
&response_type=code

If it works you should be redirected to something like this after login:
https://localhost:7166/signin-oidc?code=

If you get an error that says:

AADB2C99059: The supplied request must present a code_challenge

Then you have probably selected platform Single-page application and needs to add a code_challenge to the request like: &code_challenge=123. This is not enough because you also need to validate the challenge later otherwise you will get the error below when running my code.

AADB2C90183: The supplied code_verifier is invalid

Now open your application and appsettings.json. Default should look something like this:
  "AzureAd": {
    "Instance": "https://login.microsoftonline.com/",
    "Domain": "qualified.domain.name",
    "TenantId": "22222222-2222-2222-2222-222222222222",
    "ClientId": "11111111-1111-1111-11111111111111111",

    "Scopes": "access_as_user",
    "CallbackPath": "/signin-oidc"
  },

We need a few more values so it should look like this in the end:
  "AzureAd": {
    "Instance": "https://<tenant-name>.b2clogin.com/",
    "Domain": "<tenant-name>.onmicrosoft.com",
    "TenantId": "22222222-2222-2222-2222-222222222222",
    "ClientId": "11111111-1111-1111-11111111111111111",
    "SignUpSignInPolicyId": "B2C_1_signin",
    "ClientSecret": "--SECRET--",
    "ApiScope": "https://<tenant-name>.onmicrosoft.com/11111111-1111-1111-11111111111111111/access_as_user",
    "TokenUrl": "https://<tenant-name>.b2clogin.com/<tenant-name>.onmicrosoft.com/B2C_1_signin/oauth2/v2.0/token",
    "Scopes": "access_as_user",
    "CallbackPath": "/signin-oidc"
  },

I store ClientSecret in Secret Manager.
https://learn.microsoft.com/en-us/aspnet/core/security/app-secrets?view=aspnetcore-6.0&tabs=windows#manage-user-secrets-with-visual-studio
Now create these new classes:
AppSettings:
namespace AzureADB2CWebAPIGroupTest
{
    public class AppSettings
    {
        public AzureAdSettings AzureAd { get; set; } = new AzureAdSettings();

    }

    public class AzureAdSettings
    {
        public string Instance { get; set; }

        public string Domain { get; set; }

        public string TenantId { get; set; }

        public string ClientId { get; set; }

        public string IssuerSigningKey { get; set; }

        public string ValidIssuer { get; set; }

        public string ClientSecret { get; set; }

        public string ApiScope { get; set; }

        public string TokenUrl { get; set; }

    }
}

Adb2cTokenResponse:
namespace AzureADB2CWebAPIGroupTest
{
    public class Adb2cTokenResponse
    {
        public string access_token { get; set; }
        public string id_token { get; set; }
        public string token_type { get; set; }
        public int not_before { get; set; }
        public int expires_in { get; set; }
        public int ext_expires_in { get; set; }
        public int expires_on { get; set; }
        public string resource { get; set; }
        public int id_token_expires_in { get; set; }
        public string profile_info { get; set; }
        public string scope { get; set; }
        public string refresh_token { get; set; }
        public int refresh_token_expires_in { get; set; }
    }
}

CacheKeys:
namespace AzureADB2CWebAPIGroupTest
{
    public static class CacheKeys
    {
        public const string GraphApiAccessToken = "_GraphApiAccessToken";
    }
}

GraphApiService:
using Microsoft.Extensions.Caching.Memory;
using Microsoft.Graph;
using System.Text.Json;

namespace AzureADB2CWebAPIGroupTest
{
    public class GraphApiService
    {
        private readonly IHttpClientFactory _clientFactory;
        private readonly IMemoryCache _memoryCache;
        private readonly AppSettings _settings;
        private readonly string _accessToken;

        public GraphApiService(IHttpClientFactory clientFactory, IMemoryCache memoryCache, AppSettings settings)
        {
            _clientFactory = clientFactory;
            _memoryCache = memoryCache;
            _settings = settings;

            string graphApiAccessTokenCacheEntry;

            // Look for cache key.
            if (!_memoryCache.TryGetValue(CacheKeys.GraphApiAccessToken, out graphApiAccessTokenCacheEntry))
            {
                // Key not in cache, so get data.
                var adb2cTokenResponse = GetAccessTokenAsync().GetAwaiter().GetResult();

                graphApiAccessTokenCacheEntry = adb2cTokenResponse.access_token;

                // Set cache options.
                var cacheEntryOptions = new MemoryCacheEntryOptions()
                    .SetAbsoluteExpiration(TimeSpan.FromSeconds(adb2cTokenResponse.expires_in));

                // Save data in cache.
                _memoryCache.Set(CacheKeys.GraphApiAccessToken, graphApiAccessTokenCacheEntry, cacheEntryOptions);
            }

            _accessToken = graphApiAccessTokenCacheEntry;
        }

        public async Task<List<string>> GetUserGroupsAsync(string oid)
        {
            var authProvider = new AuthenticationProvider(_accessToken);
            GraphServiceClient graphClient = new GraphServiceClient(authProvider, new HttpClientHttpProvider(_clientFactory.CreateClient()));

            //Requires GroupMember.Read.All and User.Read.All to get everything we want
            var groups = await graphClient.Users[oid].MemberOf.Request().GetAsync();

            if (groups == null)
            {
                return null;
            }

            var graphGroup = groups.Cast<Microsoft.Graph.Group>().ToList();

            return graphGroup.Select(x => x.DisplayName).ToList();
        }

        private async Task<Adb2cTokenResponse> GetAccessTokenAsync()
        {
            var client = _clientFactory.CreateClient();

            var kvpList = new List<KeyValuePair<string, string>>();
            kvpList.Add(new KeyValuePair<string, string>("grant_type", "client_credentials"));
            kvpList.Add(new KeyValuePair<string, string>("client_id", _settings.AzureAd.ClientId));
            kvpList.Add(new KeyValuePair<string, string>("scope", "https://graph.microsoft.com/.default"));
            kvpList.Add(new KeyValuePair<string, string>("client_secret", _settings.AzureAd.ClientSecret));

#pragma warning disable SecurityIntelliSenseCS // MS Security rules violation
            var req = new HttpRequestMessage(HttpMethod.Post, $"https://login.microsoftonline.com/{_settings.AzureAd.Domain}/oauth2/v2.0/token")
            { Content = new FormUrlEncodedContent(kvpList) };
#pragma warning restore SecurityIntelliSenseCS // MS Security rules violation

            using var httpResponse = await client.SendAsync(req);

            var response = await httpResponse.Content.ReadAsStringAsync();

            httpResponse.EnsureSuccessStatusCode();

            var adb2cTokenResponse = JsonSerializer.Deserialize<Adb2cTokenResponse>(response);

            return adb2cTokenResponse;
        }
    }

    public class AuthenticationProvider : IAuthenticationProvider
    {
        private readonly string _accessToken;

        public AuthenticationProvider(string accessToken)
        {
            _accessToken = accessToken;
        }

        public Task AuthenticateRequestAsync(HttpRequestMessage request)
        {
            request.Headers.Add("Authorization", $"Bearer {_accessToken}");

            return Task.CompletedTask;
        }
    }

    public class HttpClientHttpProvider : IHttpProvider
    {
        private readonly HttpClient http;

        public HttpClientHttpProvider(HttpClient http)
        {
            this.http = http;
        }

        public ISerializer Serializer { get; } = new Serializer();

        public TimeSpan OverallTimeout { get; set; } = TimeSpan.FromSeconds(300);

        public void Dispose()
        {
        }

        public Task<HttpResponseMessage> SendAsync(HttpRequestMessage request)
        {
            return http.SendAsync(request);
        }

        public Task<HttpResponseMessage> SendAsync(HttpRequestMessage request,
            HttpCompletionOption completionOption,
            CancellationToken cancellationToken)
        {
            return http.SendAsync(request, completionOption, cancellationToken);
        }
    }
}

At the moment only accessToken for GraphServiceClient is stored in memorycache but if the application requires better performance a users groups could also be cached.
Add a new class:
Adb2cUser:
namespace AzureADB2CWebAPIGroupTest
{
    public class Adb2cUser
    {
        public Guid Id { get; set; }

        public string GivenName { get; set; }

        public string FamilyName { get; set; }

        public string Email { get; set; }

        public List<string> Roles { get; set; }

        public Adb2cTokenResponse Adb2cTokenResponse { get; set; }
    }
}

and struct:
namespace AzureADB2CWebAPIGroupTest
{
    public struct ADB2CJwtRegisteredClaimNames
    {
        public const string Emails = "emails";

        public const string Name = "name";
    }
}

And now add a new API Controller
LoginController:
using Microsoft.AspNetCore.Authorization;
using Microsoft.AspNetCore.Mvc;
using System.IdentityModel.Tokens.Jwt;
using System.Text.Json;

namespace AzureADB2CWebAPIGroupTest.Controllers
{
    [Route("api/[controller]")]
    [ApiController]
    [Authorize]
    public class LoginController : ControllerBase
    {

        private readonly ILogger<LoginController> _logger;
        private readonly IHttpClientFactory _clientFactory;
        private readonly AppSettings _settings;
        private readonly GraphApiService _graphApiService;

        public LoginController(ILogger<LoginController> logger, IHttpClientFactory clientFactory, AppSettings settings, GraphApiService graphApiService)
        {
            _logger = logger;
            _clientFactory = clientFactory;
            _settings = settings;
            _graphApiService=graphApiService;
        }

        [HttpPost]
        [AllowAnonymous]
        public async Task<ActionResult<Adb2cUser>> Post([FromBody] string code)
        {
            var redirectUri = "";

            if (HttpContext != null)
            {
                redirectUri = HttpContext.Request.Scheme + "://" + HttpContext.Request.Host + "/signin-oidc";
            }

            var kvpList = new List<KeyValuePair<string, string>>();
            kvpList.Add(new KeyValuePair<string, string>("grant_type", "authorization_code"));
            kvpList.Add(new KeyValuePair<string, string>("client_id", _settings.AzureAd.ClientId));
            kvpList.Add(new KeyValuePair<string, string>("scope", "openid offline_access " + _settings.AzureAd.ApiScope));
            kvpList.Add(new KeyValuePair<string, string>("code", code));
            kvpList.Add(new KeyValuePair<string, string>("redirect_uri", redirectUri));
            kvpList.Add(new KeyValuePair<string, string>("client_secret", _settings.AzureAd.ClientSecret));

            return await UserLoginAndRefresh(kvpList);

        }

        [HttpPost("refresh")]
        [AllowAnonymous]
        public async Task<ActionResult<Adb2cUser>> Refresh([FromBody] string token)
        {
            var redirectUri = "";

            if (HttpContext != null)
            {
                redirectUri = HttpContext.Request.Scheme + "://" + HttpContext.Request.Host;
            }

            var kvpList = new List<KeyValuePair<string, string>>();
            kvpList.Add(new KeyValuePair<string, string>("grant_type", "refresh_token"));
            kvpList.Add(new KeyValuePair<string, string>("client_id", _settings.AzureAd.ClientId));
            kvpList.Add(new KeyValuePair<string, string>("scope", "openid offline_access " + _settings.AzureAd.ApiScope));
            kvpList.Add(new KeyValuePair<string, string>("refresh_token", token));
            kvpList.Add(new KeyValuePair<string, string>("redirect_uri", redirectUri));
            kvpList.Add(new KeyValuePair<string, string>("client_secret", _settings.AzureAd.ClientSecret));

            return await UserLoginAndRefresh(kvpList);
        }

        private async Task<ActionResult<Adb2cUser>> UserLoginAndRefresh(List<KeyValuePair<string, string>> kvpList)
        {
            var user = await TokenRequest(kvpList);
            if (user == null)
            {
                return Unauthorized();
            }

            //Return access token and user information
            return Ok(user);
        }

        private async Task<Adb2cUser> TokenRequest(List<KeyValuePair<string, string>> keyValuePairs)
        {
            var client = _clientFactory.CreateClient();

#pragma warning disable SecurityIntelliSenseCS // MS Security rules violation
            var req = new HttpRequestMessage(HttpMethod.Post, _settings.AzureAd.TokenUrl)
            { Content = new FormUrlEncodedContent(keyValuePairs) };
#pragma warning restore SecurityIntelliSenseCS // MS Security rules violation

            using var httpResponse = await client.SendAsync(req);

            var response = await httpResponse.Content.ReadAsStringAsync();

            httpResponse.EnsureSuccessStatusCode();

            var adb2cTokenResponse = JsonSerializer.Deserialize<Adb2cTokenResponse>(response);

            var handler = new JwtSecurityTokenHandler();
            var jwtSecurityToken = handler.ReadJwtToken(adb2cTokenResponse.access_token);

            var id = jwtSecurityToken.Claims.First(claim => claim.Type == JwtRegisteredClaimNames.Sub).Value;

            var groups = await _graphApiService.GetUserGroupsAsync(id);

            var givenName = jwtSecurityToken.Claims.First(claim => claim.Type == JwtRegisteredClaimNames.GivenName).Value;
            var familyName = jwtSecurityToken.Claims.First(claim => claim.Type == JwtRegisteredClaimNames.FamilyName).Value;
            //Unless Alternate email have been added in Azure AD there will only be one email here.
            //TODO Handle multiple emails
            var emails = jwtSecurityToken.Claims.First(claim => claim.Type == ADB2CJwtRegisteredClaimNames.Emails).Value;

            var user = new Adb2cUser()
            {
                Id = Guid.Parse(id),
                GivenName = givenName,
                FamilyName = familyName,
                Email = emails,
                Roles = groups,
                Adb2cTokenResponse = adb2cTokenResponse
            };

            return user;
        }
    }
}

Now it is time to edit Program.cs. Should look something like this for the new minimal hosting model in ASP.NET Core 6.0:
var builder = WebApplication.CreateBuilder(args);

// Add services to the container.
builder.Services.AddAuthentication(JwtBearerDefaults.AuthenticationScheme)
    .AddMicrosoftIdentityWebApi(builder.Configuration.GetSection("AzureAd"));

Notice that ASP.NET Core 6.0 are using JwtBearerDefaults.AuthenticationScheme and not AzureADB2CDefaults.AuthenticationScheme or AzureADB2CDefaults.OpenIdScheme.
Edit so Program.cs looks like this:
using AzureADB2CWebAPIGroupTest;
using Microsoft.AspNetCore.Authentication;
using Microsoft.AspNetCore.Authentication.JwtBearer;
using Microsoft.Extensions.Caching.Memory;
using Microsoft.Identity.Web;
using System.Security.Claims;

var builder = WebApplication.CreateBuilder(args);

//Used for debugging
//IdentityModelEventSource.ShowPII = true;

var settings = new AppSettings();
builder.Configuration.Bind(settings);
builder.Services.AddSingleton(settings);

var services = new ServiceCollection();
services.AddMemoryCache();
services.AddHttpClient();
var serviceProvider = services.BuildServiceProvider();

var memoryCache = serviceProvider.GetService<IMemoryCache>();
var httpClientFactory = serviceProvider.GetService<IHttpClientFactory>();

var graphApiService = new GraphApiService(httpClientFactory, memoryCache, settings);

// Add services to the container.
builder.Services.AddAuthentication(JwtBearerDefaults.AuthenticationScheme)
    .AddMicrosoftIdentityWebApi(options => {
        builder.Configuration.Bind("AzureAd", options);
        options.TokenValidationParameters.NameClaimType = "name";
        options.TokenValidationParameters.ValidateIssuerSigningKey = true;
        options.TokenValidationParameters.ValidateLifetime = true;
        options.TokenValidationParameters.ValidateIssuer = true;
        options.TokenValidationParameters.ValidateLifetime = true;
        options.TokenValidationParameters.ValidateTokenReplay = true;
        options.Audience = settings.AzureAd.ClientId;
        options.Events = new JwtBearerEvents()
        {
            OnTokenValidated = async ctx =>
            {
                //Runs on every request, cache a users groups if needed
                var oidClaim = ((System.IdentityModel.Tokens.Jwt.JwtSecurityToken)ctx.SecurityToken).Claims.FirstOrDefault(c => c.Type == "oid");
                if (!string.IsNullOrWhiteSpace(oidClaim?.Value))
                {
                    var groups = await graphApiService.GetUserGroupsAsync(oidClaim.Value);

                    foreach (var group in groups)
                    {
                        ((ClaimsIdentity)ctx.Principal.Identity).AddClaim(new Claim(ClaimTypes.Role.ToString(), group));
                    }
                }
            }
        };
    },
    options => {
        builder.Configuration.Bind("AzureAd", options);
    });

builder.Services.AddTransient<GraphApiService>();

builder.Services.AddHttpClient();
builder.Services.AddMemoryCache();

builder.Services.AddControllers();
// Learn more about configuring Swagger/OpenAPI at https://aka.ms/aspnetcore/swashbuckle
builder.Services.AddEndpointsApiExplorer();
builder.Services.AddSwaggerGen();

var app = builder.Build();

// Configure the HTTP request pipeline.
if (app.Environment.IsDevelopment())
{
    app.UseSwagger();
    app.UseSwaggerUI();
}

app.UseHttpsRedirection();

app.UseAuthentication();
app.UseAuthorization();

app.MapControllers();

app.Run();

Now you can run your application and use the code from earlier in a request like this:
POST /api/login/ HTTP/1.1
Host: localhost:7166
Content-Type: application/json

"code"

You will then receieve a response like this with an access_token:
{
    "id": "31111111-1111-1111-1111-111111111111",
    "givenName": "Oscar",
    "familyName": "Andersson",
    "email": "oscar.andersson@example.com",
    "roles": [
        "Administrator",
    ],
    "adb2cTokenResponse": {

    }
}

Adding [Authorize(Roles = "Administrator")] to WeatherForecastController.cs we can now verify that only a user with the correct role is allowed to access this resource using the access_token we got earlier:

If we change to [Authorize(Roles = "Administrator2")] we get a HTTP 403 with the same user:

LoginController can handle refresh tokens as well.
With NuGets Microsoft.NET.Test.Sdk, xunit, xunit.runner.visualstudio and Moq we can also test LoginController and in turn also GraphApiService used for ClaimsIdentity in Program.cs. Unfortunately due body being limited to 30000 charcters the entire test can not be shown.
It basically looks like this:
LoginControllerTest:
using AzureADB2CWebAPIGroupTest.Controllers;
using Microsoft.AspNetCore.Mvc;
using Microsoft.Extensions.Caching.Memory;
using Moq;
using Moq.Protected;
using System.Net;
using Xunit;

namespace AzureADB2CWebAPIGroupTest
{
    public class LoginControllerTest
    {

        [Theory]
        [MemberData(nameof(PostData))]
        public async Task Post(string code, string response, string expectedEmail, string expectedFamilyName, string expectedGivenName)
        {
            var controller = GetLoginController(response);

            var result = await controller.Post(code);

            var actionResult = Assert.IsType<ActionResult<Adb2cUser>>(result);
            var okResult = Assert.IsType<OkObjectResult>(result.Result);
            var returnValue = Assert.IsType<Adb2cUser>(okResult.Value);
            Assert.Equal(returnValue.Email, expectedEmail);
            Assert.Equal(returnValue.Roles[1], GraphApiServiceMock.DummyGroup2Name);
        }

        [Theory]
        [MemberData(nameof(RefreshData))]
        public async Task Refresh(string code, string response, string expectedEmail, string expectedFamilyName, string expectedGivenName)
        {
            var controller = GetLoginController(response);

            var result = await controller.Refresh(code);

            var actionResult = Assert.IsType<ActionResult<Adb2cUser>>(result);
            var okResult = Assert.IsType<OkObjectResult>(result.Result);
            var returnValue = Assert.IsType<Adb2cUser>(okResult.Value);
            Assert.Equal(returnValue.Email, expectedEmail);
            Assert.Equal(returnValue.Roles[1], GraphApiServiceMock.DummyGroup2Name);
        }

        //PostData and RefreshData removed for space

        private LoginController GetLoginController(string expectedResponse)
        {
            var mockFactory = new Mock<IHttpClientFactory>();

            var settings = new AppSettings();

            settings.AzureAd.TokenUrl = "https://example.com";

            var mockMessageHandler = new Mock<HttpMessageHandler>();

            GraphApiServiceMock.MockHttpRequests(mockMessageHandler);

            mockMessageHandler.Protected()
                .Setup<Task<HttpResponseMessage>>("SendAsync", ItExpr.Is<HttpRequestMessage>(x => x.RequestUri.AbsoluteUri.Contains(settings.AzureAd.TokenUrl)), ItExpr.IsAny<CancellationToken>())
                .ReturnsAsync(new HttpResponseMessage
                {
                    StatusCode = HttpStatusCode.OK,
                    Content = new StringContent(expectedResponse)
                });

            var httpClient = new HttpClient(mockMessageHandler.Object);

            mockFactory.Setup(_ => _.CreateClient(It.IsAny<string>())).Returns(httpClient);

            var logger = Mock.Of<ILogger<LoginController>>();

            var services = new ServiceCollection();
            services.AddMemoryCache();
            var serviceProvider = services.BuildServiceProvider();

            var memoryCache = serviceProvider.GetService<IMemoryCache>();

            var graphService = new GraphApiService(mockFactory.Object, memoryCache, settings);

            var controller = new LoginController(logger, mockFactory.Object, settings, graphService);

            return controller;
        }
    }
}

A GraphApiServiceMock.cs is also needed but it just adds more values like the example with mockMessageHandler.Protected() and static values like public static string DummyUserExternalId = "11111111-1111-1111-1111-111111111111";.

There are other ways to do this but they usually depend on Custom Policies:
https://learn.microsoft.com/en-us/answers/questions/469509/can-we-get-and-edit-azure-ad-b2c-roles-using-ad-b2.html
https://devblogs.microsoft.com/premier-developer/using-groups-in-azure-ad-b2c/
https://learn.microsoft.com/en-us/azure/active-directory-b2c/user-flow-overview

A: First of all, thank you all for the previous responses. I've spent the entire day to put this to work. I'm using ASPNET Core 3.1 and I was getting the following error when using the solution from previous response:
secure binary serialization is not supported on this platform

I've replaces to REST API queries and I was able to get the groups:
    public Task OnTokenValidated(TokenValidatedContext context)
    {
        _onTokenValidated?.Invoke(context);
        return Task.Run(async () =>
        {
            try
            {
                var oidClaim = context.SecurityToken.Claims.FirstOrDefault(c => c.Type == "oid");
                if (!string.IsNullOrWhiteSpace(oidClaim?.Value))
                {
                    HttpClient http = new HttpClient();

                    var domainName = _azureADSettings.Domain;
                    var authContext = new AuthenticationContext($"https://login.microsoftonline.com/{domainName}");
                    var clientCredential = new ClientCredential(_azureADSettings.ApplicationClientId, _azureADSettings.ApplicationSecret);
                    var accessToken = AcquireGraphAPIAccessToken(AadGraphUri, authContext, clientCredential).Result;

                    var url = $"https://graph.windows.net/{domainName}/users/" + oidClaim?.Value + "/$links/memberOf?api-version=1.6";

                    HttpRequestMessage request = new HttpRequestMessage(HttpMethod.Get, url);
                    request.Headers.Authorization = new AuthenticationHeaderValue("Bearer", accessToken);
                    HttpResponseMessage response = await http.SendAsync(request);

                    dynamic json = JsonConvert.DeserializeObject<dynamic>(await response.Content.ReadAsStringAsync());

                    foreach(var group in json.value)
                    {
                        dynamic x = group.url.ToString();

                        request = new HttpRequestMessage(HttpMethod.Get, x + "?api-version=1.6");
                        request.Headers.Authorization = new AuthenticationHeaderValue("Bearer", accessToken);
                        response = await http.SendAsync(request);

                        dynamic json2 = JsonConvert.DeserializeObject<dynamic>(await response.Content.ReadAsStringAsync());

                        ((ClaimsIdentity)((ClaimsIdentity)context.Principal.Identity)).AddClaim(new Claim(ClaimTypes.Role.ToString(), json2.displayName.ToString()));
                    }
                }
            }
            catch (Exception e)
            {
                Debug.WriteLine(e);
            }
        });
    }


text:
Q: Cookies to store quiz answers information in Django I'm trying to make a quiz app with Django as backend.
The way I want to do it is by showing a multiple choice question to the user, where he/she will select whatever answer he/she wants. After that, the user will click on "Next question", and that question will disappear and the next one will show up.
I was thinking about storing what questions and answers the user has already answered in a session cookie and once he/she answers the ten questions that would make up the quiz, the webpage shows the total score.
How could I store session info of that kind? Is there an easy way to do the "Next question" button and show the next question in the same page?
Thank you in advance!


text:
Q: Import NPM package only for server side rendering(SSR) in Next.js App I am trying to use one private NPM module only when the page is loading for the first time and rendering is happening on the server. I am using the following piece of code but I am still able to see my package in chunks in client.html using the build analyzer.
  if (typeof window === 'undefined') {
    const content = await import('@abc/my-npm-package');
    return conent(payload);
  } else {
    return null;
  }

A: Excellent question, I've poked around the Next.js's code and found out that in order to code that will be exists only on the server you need to use some variable which is passed to webpack.DefinePlugin (which at build time will replace the usage with the value, this what allows the tree-shake to work).
From this line, there is a special variable process.browser which will be true only in the browser.
Change your code to
if (!process.browser) {
  const content = await import('@abc/my-npm-package');
  return conent(payload);
} else {
  return null;
}

Update 16.03.2022
Next.js will deprecate process.browser soon, the new recommended way to distinguish between client & server is by checking type of window === 'undefined' // means that it's server side.
 if (typeof window === 'undefined') { // server side
    const content = await import('@abc/my-npm-package');
    return content(payload);
  } else { // client side
    return null;
  }


text:
Q: how to set the admin user with GAE dev app server? I want to create an Admin-only page for my GAE application. But I found there's no way to set a Admin user, so I cannot log on the page I created and test the function. I tried the local Admin console, but no luck. How can I do this?

A: Google App Engine provides a pretty straightforward way to create a private admin section of your web application.
1.
In your app.yaml, any URL handler can have a login setting to restrict visitors to only those users who have signed in, or just those users who are administrators for the application.
If the setting is login: admin, once the user has signed in, the handler checks whether the user is an administrator for the application. If not, the user is given an error message; if the user is an administrator, the handler proceeds.
Here a snippet of app.yaml where the /admin/.* routes are admin restricted :
 - url: /admin/.*
   script: admin.py
   login: admin

2.
Trying to access the admin url, the dev app server automatically shows the login panel where you should check the Sign in as Administrator checkbox.

A: When you log in (the blue box where you enter the email) there is a checkbox to apply the administrator flag to your session.

A: You can define admin only pages in your app.yaml, like so:
- url: /secrets/
  script: /secrets/example.py
  login: admin

an admin is whoever is so defined in your appengine.google.com control panel, under permissions.


text:
Q: d3.queue is not giving an output This is the page I am trying to make it dynamic by enabling cross-filtering.
So the thing is they are having multiple API.
For the top first two: TOTAL CASES & DAILY CASES
They are using this API and the third one in the top is based on this API.
The bottom three AGE, GENDER, and NATIONALITY are from this API.
In all the API one thing is common that is a date but there are some API in which some data are missing for few dates like there is a gap( Not available for some of the dates).
So I thought of combining all the JSON API in terms of dates and then allow cross filter because I believe I can enable cross-filtering between them. Correct me If I am wrong.
Like If I click on gender female since it gives info about total cases where the patient was female so only confirmed cases from the Total cases will change not the recovered, deaths as data is not available. SO I guess I should combine the top 3 charts together and gender, age and nationality charts, together. Then Dc js would be able to handle nicely filtering between each segments (cases related to landmark, cases related to person info).
Line 123:
var log = console.log;

var q = queue()
    .defer(d3.json, "https://api.covid19india.org/data.json")
      .defer(d3.json, "https://api.rootnet.in/covid19-in/unofficial/covid19india.org/statewise/history");

    q.await(function(error, data1, data2) {
      log("==========>");
    log("data1:", error,data1);
    log("data2:", data2);
});

This is not working because I can't see console.log() output.
https://blockbuilder.org/ninjakx/8c48ab6481311aa0452046d66c4d8701
So my questions are:
1) Why d3.queue is not working?
2) Suggestion whether combining all the datas together and allowing a filltering is a good idea or not as there is limited data. Should I go for cross filtering between the same api charts. So in this case I will have 2 segments (cases related to landmark, cases related to person info)..
Using DC js I want to make it more interactive and display more info.

A: d3.queue is obsolete
The answer to your first question is cut-and-dried: you don't need d3.queue, and it was deprecated and removed in d3@5.
As of d3@5, D3's data loading APIs use ES6 Promises instead of asynchronous callbacks, so you can use Promise.all([...]) instead of d3.queue. Apparently no way to make the new API emit errors when called in the old way, so it just fails silently. :-/
The new way to write your code is
Promise.all([
  d3.json("https://api.covid19india.org/data.json"),
  d3.json("https://api.rootnet.in/covid19-in/unofficial/covid19india.org/statewise/history")
]).then(([data1,data2]) => {
    log("==========>");
    log("data1:", data1);
    log("data2:", data2);
})
.catch(error => log('error', error))

I find this much easier to read and understand. A nice side effect is that if you neglect to do error handling (like most people), you'll automatically get a clear message in the log.
Working fork of your block.
Combining multiple data sets
Your second question is pretty open-ended, maybe it would be better to bring that to the dc.js users group?
In general, it's difficult to cross-filter more than one data set. You would have more than one chart group that redraws together, and you'd have to manually add handlers on some chart to initiate, clear filters, and redraw the other chart group.
I haven't seen too many dashboards that do this. You'd have to make it clear to users what is going on.


text:
Q: Confidence Band in GAMM I would like to know why, when adjusting the following model, the confidence band is wider in one of the factors than in the other, if the variability of the raw data seems to be the same in both factors.

Maybe it's because there is no significance for the smooth effect?
To graph I am using the visreg library.
I appreciate any idea.

A: The problem I think is a lack of identifiability on the Year smooths when you have a global smooth plus factor-by smooths of the same variable. Adding is the random factor-smooth probably isn't helping.
Often one needs to change the penalty on the by smooths so that they are more easily identifiable from the data. One way to do that is to place the penalty on the integrated squared first derivative of the by smooths. This has the effect of penalising deviations from a flat line. Now the smooth effect of Year in your groups is given by
$$ \gamma_{j[i]} + f(Year_{i}) + f_j(Year_{i}) $$
where $\gamma_{j[i]}$ is the $j$th group mean for the $i$th observation, and where the $f_j$ are penalised for deviating from a flat function. When coupled with the global smoother deviation from a flat function means deviation from the global function.
To do this for your model, you would need:
gam(pH ~ Impacted + s(Year) + s(Year, by = Impacted, m = 1) +
         s(Year, Stnumber, bs = 'fs'),
    method = 'REML', data = X)

The issue doesn't crop up as often with the "fs" basis as those bases are fully penalised and include a random intercept, so the penalties help I believe to make these terms identifiable.
You may also just not have enough data to uniquely identify three different kinds of smooth effect of Year. Do you need both the global and the Impacted-level smooths? Could you just work with the Impacted level smooths as in
gam(pH ~ Impacted + s(Year, by = Impacted) + s(Year, Stnumber, bs = 'fs'),
    method = 'REML', data = X)

where we no longer need the m = 1 bit for the first derivative-based penalty?
Nothing is really lost here as you could use methods to compare the by smooths to see how similar they are.


text:
Q: Regex to capture entire string in python panda series I have a sample series:
s = pd.Series(['Complexity Level 1', 'RandomName', 'I-Invoice Submission test', 'I-test2', 'I-string with multiple words'])

I'm trying to capture only strings that begin with "I-". Using extract.
extract1 = s.str.extract(r'I-(\w+)')

Current Output:
    0
0   NaN
1   NaN
2   Invoice
3   test2
4   string

It's currently only extracting the first word. But I want all words and white space after the identifier. This could be up to 5 words
Is this a regex adjustment or is there a better method?
What I want is:
    0
0   NaN
1   NaN
2   Invoice Submission test
3   test2
4   string with multiple words

A: The regex that will do the job is r'I-(.*)'?. Meaning: capture any character (until a newline) after "|-".

EDIT (From comments):
To capture any character up until a comma use I-([^,]*). Meaning: capture any character that is not a comma (,) after "|-".


text:
Q: different between limit query in mysql and php I'm trying to make page number for my table and need to know row count.
for example my query is SELECT * FROM tbl and the result is 100rows.
I should limit query to 10rows for one page.
if I do that I cant get all rows count.
I want to know is there any different between limit with mysql our php in process speed.
please tell me if you have any idea.

A: You shoud use LIMIT in your MySQL. Why?
*Because it will take you less time to fetch some amount of data and transmit it instead of getting everything.

*Because it will consume less memory.

*Because working with smaller arrays is generally faster.

As for me, I used PHP as a filter only when I could not perform the filtering in MySQL
Just to update my answer, as Joachim Isaksson already posted:
SQL_CALC_FOUND_ROWS will help you count all the rows, so you can perform a correct pagination.

A: The best way is probably to use FOUND_ROWS() and combine them both;
SELECT SQL_CALC_FOUND_ROWS * FROM tbl LIMIT 10

...to get the first 10 rows as a result. Then you can just do;
SELECT FOUND_ROWS()

...to get the total number of rows you would have got if you hadn't used LIMIT.

A: What happens if you will have 100k rows? Of course, you will get rows count, but performance significantly decrease (and memory usage significantly increase). Just use second query to obtain amount of rows and limit rows in mysql

A: As i understand your problem ,solution might be like this :Strictly by mysql

*

*Use two function first for counting total record

*second for getting result

*select count(1) as total from table_name

*select col1,col2.. from table_name limit $start , $slot_size

Now slot_size is number of record you want to show on page,say 10
start is value which will change according to page


text:
Q: Window Azure Tools for Eclipse - failed Im trying to install Windows Azure tools for Eclipse by following Tutorial. After i fill the location and name, it doesn't install but throw an error.
Error
Network connection problems encountered during search.
Unable to access "http://http://www.windowsazure4e.org/update".
Error parsing site stream. [Premature end of file.]
Premature end of file.
Error parsing site stream. [Premature end of file.]
Premature end of file.

A: Please check the link you have given. It says

http://http://www.windowsazure4e.org/update whereas it should be
  http://www.windowsazure4e.org/update

A: I downloaded new version of Eclipse and it working fine now.
Using :
Eclipse Java EE IDE for Web Developers.
Version: Helios Release
Build id: 20100617-1415


text:
Q: Show that G is open in X iff $\overline{G \cap \bar{A}}=\overline{G \cap A}$ for all $A\subset X$ I have tried
Suppose $G$ is open , we claim that  $\overline{G \cap \bar{A}}=\overline{G \cap A}$ for all $A\subset X$
Since $G \cap  A \subseteq G \cap \overline A$
$\Rightarrow \overline{G\cap A} \subseteq \overline{G\cap \overline A}$
Let $x \in \overline{G\cap \overline A}$ and $S_r(x)$ be a $nbd$ of $x$, then $S_r(x) \cap (G \cap \overline A) \neq \phi$, then $\exists$  $y \in S_r(x) \cap (G \cap \overline A) $ there exists $r'$ such that $S_{r'}(y) \subset (S_r(x)\cap G)$ and $S_{r'}(y) \cap A \neq \phi$ $\Rightarrow S_r(x) \cap (G\cap A) \neq \phi$
$\therefore$ $x \in \overline{G\cap A}$
Thus $\overline{G \cap \bar{A}}=\overline{G \cap A}$ for all $A\subset X$
Converse :
if $\overline{G \cap \bar{A}}=\overline{G \cap A}$ for all $A\subset X$, then $G$ is open.
Please tell how to show that $G$ is open. Thank you

A: Substitute $A=G^c$. Then,
$$\overline{G\cap \overline{G^c}}=\overline{G\cap G^c}=\varnothing \Rightarrow G\cap \overline{G^c}=\varnothing \Rightarrow \overline{G^c} =\overline{X\setminus G}\subset X\setminus G=G^c.$$
Therefore $G^c$ is closed and hence $G$ is open.

A: Hint: take $A=X\setminus G$. What does the condition tell you?


text:
Q: how to make structs point to different strings? I have a struct and in that a struct i have a character pointer but and i am creating different instances of this struct but when i am changing the pointer in one struct the other is also changing.
#include <stdio.h>
#include <stdlib.h>

typedef struct human{
    int age;
    char name[100];
} Human;

int main(){
    FILE *s = fopen("h.txt","r");
    if(s==NULL){
        printf("file not available");
    }

    for(int i=0 ;i<5;i++){
        Human h;

        fscanf(s,"%d",&h.age);
        fscanf(s,"%s",h.name);

        insertintolinkedlist(h);
        // this method is going to insert the human into the linked list
    }

    return 0;
}

what is happening that all humans in the linked list have different ages but same name!

A: You need to allocate memory to hold the name.
char* name is just a pointer - it has no memory for saving the name.
You change it to
char name[100];

Remember to check that the names you put into Human.name isn't longer than 100 characters.
To use a linked list you can do something like:
typedef struct human{
    int age;
    char name[100];
    struct human* next;
} Human;

int main()
{
    Human* head = NULL;
    Human* tail = NULL;

    for(.....)
    {
        Human* h = malloc(sizeof(Human));
        if (head == NULL) head = h;
        if (tail != NULL)
        {
            tail->next = h;
        }
        tail = h;
        h->next = NULL;
        h->age = ....;
        strncpy(h->age, "..name..", 100);
    }

    // ..... other code

    // Remember to free all allocated memory
}


text:
Q: Create Mutable Array with name from NSString Variable
I have searched the internet quite a while concerning this problem but didn't find anything related. So I have a simple question: Is it by any means possible to create a Mutable Array in Objective C by using a NSString Variable to name it?
To be more clear a code example (which doesn't work this way):
NSString* someString = @"RandomWord";

NSMutableArray* (someString) = [[NSMutableArray alloc] init];

Any help would be appreciated. If this does not work the way I intend to do it, it would be nice to know another way to dynamically create Arrays with reasonable, retrievable names.
Best Regards,
J

UPDATE:
I have an NSMutableDictionary in which I intend to save multiple NSMutableArray with URLs. The user can name the keys in the Dictionary himself.
For example: The user creates a category named "Animals" and stores multiple URLs in that category.
So what I want to achieve is to save the NSMutableArray filled with the URLs for the key "Animals" in the NSMutableDictionary.
I originally thought about just using one NSMutableArray but as I learned the copies of the Array in the NSMutableDictionary are only shallow, so each time I filled the array with something new and stored it the old values were lost in my NSMutableDictionary. But since the User creates as many categories as he wants and also names them how he wants to I need to somehow create arrays that I can reasonably retrieve and add as content to the NSMutableDictionary.
I know this sounds kind of confusing but I hope I made my goal somehow clear.
If there are any questions please ask!

A: No you can't. You can, however, use an NSMutableDictionary, to store the instances.
An example:
NSMutableDictionary *dict = [NSMutableDictionary dictionary];
NSString *someString = @"RandomWord";
[dict setObject:[NSMutableArray array] forKey:someString];

Then to use later:
[[dict objectForKey:someString] doSomethingToTheArray];