text:
Q: Basis-free definition of Casimir element? Let $V$ be a finite-dimensional vector space and let $\mathfrak g \subset \mathfrak{gl}(V)$ be a representation of a semisimple Lie algebra on $V$. Let $e_1, \dots, e_n$ be a basis for $V$. Let $e_1', \dots, e_n'$ be the dual basis of $\{e_i\}$ under the Killing form $B_V(X,Y) = \mathrm{trace}(X \circ Y)$. The Casimir element of the universal enveloping algebra $U(\mathfrak g)$ (or $\mathrm{Sym}^2(V)$, if you prefer) is defined by
$c_V = \sum_i e_i \cdot e_i'$
One then proves that this definition is independent of the choice of basis.
My question is: is there a good definition of $c_V$ that can be stated without referring to a basis?
A perfunctory glance at Bourbaki, Humphreys, Fulton and Harris, and Wikipedia turned up none but the above definition.
I'm mostly interested in representations of ordinary finite-dimensional Lie algebras (over $\mathbb{C}$, even), but if the issue is more naturally addressed in the context of some more general sort of algebra, then I'd be interested to learn about it, even though I don't really know much about, say, Hopf algebras.
EDIT:
Qiaochu's answer below looks like just what I'm looking for. I wrote this clarification and will leave it up in case anyone' interested. But Qiaochu also improves on most of what I say here.
Peter McNamara gives a sensible definition below which I ought to have been aware of: the Casimir is the unique element of degree 2 in the center of the universal enveloping algebra, up to some normalization. I suppose this definition will probably work with some modification in cases where $\mathfrak g$ is not the adjoint rep. This is a nice definition: it sheds some light on what makes the Casimir tick, and points our attention to the center of the unversal enveloping algebra as an object of interest. Where is a good reference to read about the center of a universal enveloping algebra systematically?
I'm not entirely satisfied with this definition, though, and I'd like to illustrate why with a pair of examples: coordinate-free definitions of the determinant, and of the trace.
The determinant on an $n$-dimensional vector space $V$ may be defined (up to normalization) as the unique element of $\Lambda^{n}(V)$ (the highest-dimension grading of the alternating algebra). This definition is highly analogous to Peter McNamara's definition of the Casimir. In either case, we define widget by finding an algebra $A$ of which widget is naturally an element, and by careful analysis of $A$, we show that widget is uniquely characterized by the features of $A$. One of the benefits of this sort of definition is that it points our attention towards the algebra $A$ as a worthy object of study. On the other hand, one might wish to avoid using $A$ altogether.
In contrast, here is a definition of the trace on a finite-dimensional vector space $V$. Consider the isomorphism $ \mathrm{End}(V) \cong \mathrm{End}(V)^{*} $ given by viewing $\mathrm{End}(V)$ as $V \otimes V^{*} $, swapping the factors, and using the canonical isomorphism $V \cong V^{**}$. The trace is the image of the identity under this map. It might be said that the tensor algebra is used in an auxiliary manner, but there is (I think) a difference: only the most general, "hands-off" properties of tensor products are used. The heaviest lifting comes from the isomorphism $V^{**} \cong V$ (in order to show that it is actually an isomorphism, one must keep track of dimensions of a finite-dimensional vector space under dualization). So the only hard work comes on the original object of interest: the vector space $V$ itself. In contrast, the definition of the determinant required some detailed understanding of the alternating algebra, which was not originally in question.
There might be a logical way to state this: something along the lines of whether the definition can be given in an extremely weak fragment of logic (on the order of Horn logic?). It would have to be a fragment which doesn't easily allow definitions. More likely there's no real difference between the definition of the trace and the determinant beyond the former being "easier" than the latter. Nevertheless, if there were such an "easy" definition of the Casimir, it ought to be enlightening.

A: I can't help but add: consider the chain of $G$-equivariant natural maps, using the identification of the Lie algebra $g$ with its dual via the non-degenerate $G$-equivariant Killing form:
$$
End(g) \approx g\otimes g^* \approx g\otimes g \subset \bigotimes{}^\bullet g \rightarrow Ug
$$
The identity endomorphism of $g$ commutes with the (Adjoint) action of $G$, so its image on the far end does, as well, and is Casimir. The often-seen expressions in coordinates (chosen depending on the circumstance), derive from the expression for the identity map in $g\otimes g$.
(I also can't help but add that trying to understand where these quadratic expressions "live", it was a great relief at some point to understand that such computations take place in the enveloping algebra... so, even if it is possible to talk about Casimir without the enveloping algebra, it may be easier to explain the context with the enveloping algebra.)

A: Concerning your first question:  it's really an issue about finite dimensional vector spaces.
(1). If $V$ is a finite dimensional vector space over a field $k$, then one has an evaluation map
$$
e: V^\ast \otimes V \to k
$$
defined by $f\otimes v \mapsto f(v)$. Then
$$
e \in (V^{\ast} \otimes V)^\ast .
$$
There is a canonical isomorphism
$V \otimes V^\ast\to (V^\ast \otimes V)^\ast$ given by
$$
(v,f) \mapsto  ((g,w) \mapsto g(v)f(w)) .
$$
Using this isomorphism, we can regard $e$ corresponds to element $e'\in V\otimes V^\ast$.
This is the Casimir element.
Remark: $e'$ is characterized by the following property: it is the unique vector
in $V\otimes V^{\ast}$ such that for all vector spaces $W$, the map
$$
\hom(V,W) \to W\otimes V^\ast
$$
given by $f\mapsto  (f\otimes 1_{V^\ast})(e')$ is an isomorphism.
(2). More generally, if one is given a perfect pairing:
$$
e : U \otimes V \to k
$$
(meaning that the adjoint $U \to V^\ast$ is an isomorphism), one gets by the same procedure
an element $e'\in V\otimes U$.
(3). $V = \frak g$ is a semi-simple Lie algebra,  then the killing form
$V\otimes V \to k$ is perfect. So we get by (2) the (Casimir) element $e' \in V\otimes V$.

A: The Casimir element is dual to the Killing form.  (I think.  I am somewhat uncertain about this because nobody has ever said this to me, even though it seems like the right thing to say, and frankly I don't know why Lie algebra textbooks don't just say this.)  That is, the nondegeneracy of the Killing form is equivalent to its providing an isomorphism $\mathfrak{g} \to \mathfrak{g}^{\ast}$, and writing this isomorphism as a tensor exhibits it as an element of $\mathfrak{g} \otimes \mathfrak{g}$ - precisely the element $\sum e_i \otimes e_i'$ where $e_i$ is a basis.  This embeds into $U(\mathfrak{g}) \otimes U(\mathfrak{g})$ and the multiplication map into $U(\mathfrak{g})$ gives the Casimir element.
(Oh good, I see that this is the same definition Akhil gives in the blog post darij linked to above.  That makes me feel better.)
Also, you're using the "wrong" definition of the determinant.  The exterior powers are all functors, and they take linear maps $T : V \to V$ to linear maps $T : \Lambda^n V \to \Lambda^n V$.  Since $\Lambda^n V$ is one-dimensional when $n = \dim V$, the linear maps from $\Lambda^n V$ to itself are canonically isomorphic to the base field $k$.  There is also a slightly more transparent definition of the trace: $\text{End}(V)$ is canonically isomorphic to $V^{\ast} \otimes V$, and then one composes with the dual pairing $V^{\ast} \times V \to k$.
It seems to me the notion you're looking for is what general notion of monoidal category supports the definition you're looking at.  Traces can be defined in monoidal categories with duals, although I'm not sure what the natural setting for determinants is.

A: This is an answer to the question about the general structure of the centre of the enveloping algebra:
The centre of the enveloping algebra (in particular when $\mathfrak g$ is reductive) is one of the basic objects in the study of infinite-dimensional representations of Lie algebras and Lie groups.   It was first described in general (for reductive $\mathfrak g$) by Harish-Chandra, as far as I know, who proved the following:  let $\mathfrak g$ be a reductive Lie algebra (over $\mathbb C$, say) and let $\mathfrak h$ be a Cartan subalgebra.  Let $W$ be the Weyl group, which acts on $\mathfrak h$ via the adjoint action.
Then there is an isomorphism $Z(\mathfrak g) \cong  Sym(\mathfrak h)^W.$  (Here $Z(\mathfrak g)$ denotes the centre of the enveloping algebra $U(\mathfrak g)$, and $Sym(\mathfrak h)$ denotes the symmetric algebra of $\mathfrak h,$ which is the same as the enveloping algebra $U(\mathfrak h)$, since $\mathfrak h$ is abelian.)
E.g. if $\mathfrak g = {\mathfrak sl}_2$, then a Cartan subalgebra is one-dimensional,
therefore $Sym(\mathfrak h)^W$ turns out to be a polynomial ring in one generator, where
this generator can be taken to be the Casimir.
If $\mathfrak g$ is semi-simple of rank $l$, then the centre turns out to be a polynomial ring in $l$ generators, one of which is the Casimir, and the others of which can be taken to be the so-called higher Casimirs.  (Their degrees are the so-called exponents of $\mathfrak g$, or perhaps the exponents shifted by one; I'm unsure about the standard normalization. [Added: As Mike Skirvin confirms in a comment below, they are the exponents shifted by $1$.])
To learn more you can google Harish-Chandra isomorphism, or look in one of the many representation-theory texts that are out there.  (I like Knapp's book Representation Theory of Semisimple Groups: An Overview Based on Examples, but there are lots of choices.)


text:
Q: Replace debug messages by static final strings It is considered as a good practice to replace hard coded values by static final properties in a java class.
Nevertheless I notice that developers usually keep the logging message hard coded.
Does it makes sense to move logging messages to the static final properties ?
public class MyClass {

    private static final Logger LOGGER = Logger.getLogger(MyClass.class));

    public void foo() {
        LOGGER.info("My message");
    }

}

VS
public class MyClass {

    private static final Logger LOGGER = Logger.getLogger(MyClass.class);
    private static final String MY_MESSAGE = "My message";

    public void foo() {
        LOGGER.info(MY_MESSAGE);
    }

}

A: Yes, Its always be a best practice to separate Message/Hard code contents. Create other java file (e.g. Message.java) and define all the variables & their values.
You can also used Externalize string utility of eclipse.

redpajama_set_name: RedPajamaStackExchange


text:
Q: Infinite vertical carousel in Jetpack Compose I'm looking to make an infinite vertical carousel in Jetpack Compose but I can't find how to do it.
I want something like this.
I did not find an example on the internet in Compose, everything is in XML.
I try https://google.github.io/accompanist/pager/ but it's not exactly what I want.
Thanks for helping me.

A: Solution 1:
It depends, you can use Pager Accompanist library:
https://github.com/google/accompanist/tree/main/pager
And you can check the docs here:
https://google.github.io/accompanist/pager/
Solution 2:
You can also try:
@Composable
fun CircularList(
    items: List<String>,
    modifier: Modifier = Modifier
) {
    val listState = rememberLazyListState(Int.MAX_VALUE / 2)

  LazyColumn(state = listState, modifier = modifier) {
      items(
          count = Int.MAX_VALUE,
          itemContent = {
              // your content
          }
      )
  }
}

Good luck!


text:
Q: How to sign message body with RSASSA-PSS in mimekit? I am using Mimekit with .NET Core 2.2. I am trying to sign a message with RSASSA-PSS and cannot find a way to set the signing algorithm for the RSASignaturePadding. Changing the DigestAlgorithm results in the wrong padding to be used.
How can I fix this code snippet to sign with RSASSA-PSS instead of default for padding?
    public MimeMessage SignMessage(MimeMessage message, MailboxAddress address)
    {
        CryptographyContext.Register(typeof(WindowsSecureMimeContext));

        using (var ctx = new WindowsSecureMimeContext(StoreLocation.LocalMachine))
        {
            X509Certificate2 cert = null;
            string thumbprint = "<myThumbprint>";
            var machineStore = new X509Store(StoreName.My, StoreLocation.LocalMachine);
            machineStore.Open(OpenFlags.ReadOnly);
            X509Certificate2Collection machineCerts = machineStore.Certificates.Find(X509FindType.FindByThumbprint, thumbprint, false);
            if (machineCerts.Count == 1)
            {
                cert = machineCerts[0];
            }

            if (cert != null)
            {

                CmsSigner signer = new CmsSigner(cert)
                {
                    DigestAlgorithm = DigestAlgorithm.Sha256
                };

                message.Body = MultipartSigned.Create(ctx, signer, message.Body);
            }
        }

        return message;
    }

A: This is currently not possible to do in MimeKit and it seems that the SignedCms class does not have any way to specify the PSS padding mode unless it is a property on the private key of the X509Certificate2?
Update:
I've done a bit more research and I figured out how to support this using BouncyCastle so I've just added a CmsSigner.RsaSignaturePaddingScheme property that will allow you to specify RsaSignaturePaddingScheme.Pss.
This only works when using a BouncyCastle-based SecureMimeContext, however, so what you can do is this:
public MimeMessage SignMessage(MimeMessage message, MailboxAddress address)
{
    using (var ctx = new TemporarySecureMimeContext ())
    {
        X509Certificate2 cert = null;
        string thumbprint = "<myThumbprint>";
        var machineStore = new X509Store(StoreName.My, StoreLocation.LocalMachine);
        machineStore.Open(OpenFlags.ReadOnly);
        X509Certificate2Collection machineCerts = machineStore.Certificates.Find(X509FindType.FindByThumbprint, thumbprint, false);
        if (machineCerts.Count == 1)
        {
            cert = machineCerts[0];
        }

        if (cert != null)
        {
            CmsSigner signer = new CmsSigner(cert)
            {
                RsaSignaturePaddingScheme = RsaSignaturePaddingScheme.Pss,
                DigestAlgorithm = DigestAlgorithm.Sha256
            };

            message.Body = MultipartSigned.Create(ctx, signer, message.Body);
        }
    }

    return message;
}

To start using this feature today (I have not yet made a public release), you can go to https://github.com/jstedfast/MimeKit and grab the latest MyGet build (which is a CI-generated nuget package).


text:
Q: How to create a data.frame from expression? I want to create a data frame from an expression saved into an object.
Whereas this works:
library(dplyr)

regular_chr_vec <- c(a = "lion", b = "zebra")
bind_rows(regular_chr_vec)

##   a     b
##   <chr> <chr>
## 1 lion  zebra

This doesn't:
library(rlang)

as_expression_vec <- parse_expr("c(a = \"lion\", b = \"zebra\")")
bind_rows(!!!as_expression_vec)

Error: Argument 1 must be a data frame or a named atomic vector.

Nor this:
as_expression_vec <- parse_expr("c(a = \"lion\", b = \"zebra\")")
bind_rows(!!as_expression_vec)

Error: Can't use !! in a non-quoting function

So my question is: How can I create a dataframe if I'm just handed with as_expression_vec?
##   a     b
##   <chr> <chr>
## 1 lion  zebra

I intentionally kept the question minimal and with no context to not distract the point. Thanks!

A: Here is one solution
library(rland)
library(dplyr)

as_expression_vec <- parse_expr("c(a = \"lion\", b = \"zebra\")")

bind_rows(eval(as_expression_vec))

# A tibble: 1 x 2
  a     b
  <chr> <chr>
1 lion  zebra


text:
Q: Oozie: rerun all non-SUCCEEDED workflows in coordinator I scheduled a coordinator which initiated many individual workflows. This was a backfill coordinator, with both startdate and enddate in the past.
A small percentage of these jobs failed due to temporary issues with the input datasets, and now I need to re-run those workflows (without re-running the successful workflows). These unsuccessful workflows have a variety of statuses: KILLED, FAILED, and SUSPENDED.
What is the best way to do this?

A: I don't think whether the entire thing i.e. jobs with multiple statuses, can be run in a single command but with the oozie jobs, it can be attempted although three separate commands for the three statuses. If anyone else has a better approach, please post it.
oozie jobs filter -jobtype wf -filter status=<status> -resume

Ex:
# KILLED
oozie jobs filter -jobtype wf -filter status=SUSPENDED -resume

There are a whole lot of other sub-commands offered for jobs which can be viewed by oozie help jobs. Hope that helps!

A: I ended up writing a bash script to do this. I won't copy the whole script here, but this was the general outline:
First, parse the output of oozie job -info to get a list of actions with a given status for a given coordinator:
actions=$(oozie job -info $oozie_coord -filter status=$status -len 1000 |
          grep "\-C@" |
          awk '{print $1}' |
          sed -n "s/^.*@\([0-9]*\).*$/\1/p")

Then loop over these actions and issue rerun commands:
while read -r action; do
  oozie job -rerun $oozie_coord -action $action


text:
Q: Raspberry pi. Using two servos or ESC in perl with WiringPi::API im trying using two ESC or servos in WiringPi::API (perl). 1 servo works ok, when using 2 servos, it doesn't work. This is my code:
use WiringPi::API qw(:all);
use RPi::Const qw(:all);

setup_gpio();

pin_mode(ESC1_PIN, PWM_OUT);
pin_mode(ESC2_PIN, PWM_OUT);

pwm_set_mode(PWM_MODE_MS);
pwm_set_clock(NEUTRAL);
pwm_set_range(RANGE);

pwm_write(ESC1_PIN, 176);
pwm_write(ESC2_PIN, 176);

Thanks for help and reply.


text:
Q: Is there a way to implement actionbar to the activity that extends youtubebaseactivity I have an activity that extends youtubebaseActivity for playing youtube videos. i would like to have an actionbar in this activity. Is there a way to implement it?

A: YouTubePlayerFragment is designed so you can play YouTube videos and use any Activity class (such as AppCompatActivity):

Using this fragment is the preferred way of playing YouTube videos because your activity does not need to extend an activity provided by the library, as is the case with using the YouTubePlayerView directly.

There's also YouTubePlayerSupportFragment if you use Support Fragments.


text:
Q: Hide action bar on soft keyboard popup in fragment I want to hide action bar on soft keyboard popup. I have used the code the following code to get the result. But when i want to go back, the app crashes. I have included in which line i am getting the error also. Please guide me through this.
Thanks in advance.
private void createView() {
    mRootView.getViewTreeObserver().addOnGlobalLayoutListener(new ViewTreeObserver.OnGlobalLayoutListener() {

        @Override
        public void onGlobalLayout() {

            Rect rect = new Rect();
            //rect will be populated with the coordinates of your view that area still visible.

            mRootView.getWindowVisibleDisplayFrame(rect);
            int heightDiff = mRootView.getRootView().getHeight() - (rect.bottom - rect.top);

            if (heightDiff > 100) {

                // if more than 100 pixels, its probably a keyboard...
                //keyboard visible
                mBinding.healthRecordContainer.setVisibility(View.GONE);
                ((AppCompatActivity) getActivity()).getSupportActionBar().hide();

            } else {

                //keyboard not visible
                mBinding.healthRecordContainer.setVisibility(View.VISIBLE);
                ((AppCompatActivity) getActivity()).getSupportActionBar().show(); // app crashes
            } //java.lang.NullPointerException
        }
    });
}

A: Do only one thing in your manifest where you have declared your activity.
for e.g.
<activity
            android:name=".Your Activity here"
            android:windowSoftInputMode="stateVisible|adjustResize"
            >
        </activity>

A: You can use the following code. Then app wont crash.
Activity activity = getActivity();

if (activity instanceof ActionBarActivity) {

    ActionBarActivity actionBarActivity = (ActionBarActivity) activity;

    ActionBar actionBar = actionBarActivity.getSupportActionBar();

    if (actionBar != null) {
        actionBar.hide();
    }
}


text:
Q: How to handler errors/exceptions while using Spring Kafka framework? I am not able to find how to do custom error handling in for a spring kafka consumer.
My requirement is:

*

*For any deserialization errors, just write the error and message to database.

*For any errors in execution under @KafkaListener method, retry 3 times and then write the error and message to database.

From the spring docs, I found that,
For 1, I will have to use ErrorHandlingDeserializer and it will then call the @KafkaListener error handler.
For 2, framework provides SeekToCurrentErrorHandler which handles message retries.
I am not understanding where can I add the code to write the exception/message to database in addition to enable configured retries.

A: Add a recoverer to the SeekToCurrentErrorHandler
new SeekToCurrentErrorHandler((rec, ex) -> {
    Throwable cause = ex.getCause();
    if (cause instanceof DeserializationException) {
        ...
    }
    else {
        ...
    }, new FixedBackOff(2000L, 2L));

By default, deserialization exceptions are not retried; most others are retried before calling the recoverer.


text:
Q: Android Save and Restore List State with CursorAdapter I have a list view in a fragment that is populated by a CursorAdapter.
When the device rotates I want to save the state of the list, then restore it without having to make another call to the SQLite DB.
How do I do this?
I'm not using a ContentProvider or any CursorLoaders.

A: You could save your Cursor in the method onRetainNonConfigurationInstance() of your Activity or use a data fragment that holds the Cursor and call setReatinInstance() within the fragment's onCreate() method.
You then have to recreate the CursorAdapter within the onCreate() method.
Finally you have to store the currently visible topmost item of your ListView by calling getFirstVisiblePosition() on your ListView. This method returns an int value which you can store in a Bundle within the onSaveInstanceState() method of your Activity.
You use this value in the onCreate() method (it's part of the bundle passed to onCreate()). And after the adapter has been set, you call [setSelectionFromTop(yourValue, 0)](https://developer.android.com/reference/android/widget/ListView.html#setSelectionFromTop(int, int)).


text:
Q: What's wrong with my Tic Tac Toe AI? I read a tutorial about minimax, and tried to make a tac tac toe AI.
But the code doesn't work optimally for some reason, which I cannot find. The ai can place pieces, but it's not a smart ai. I expected it to be unbeatable. The higher the depth is, the dumber the ai becomes.
The 'game' is my an other class, where the actual game is.
private Game game;
private Piece[][] board;
private Piece ai = Piece.CIRCLE;
private Piece player = Piece.CROSS;

public AI(Game game) {
    this.game = game;
    this.board = game.getBoard();

}

public int[] move() {
    int[] result = minimax(1, ai);

    return new int[] {result[1], result[2]};
}

private int[] minimax(int depth, Piece piece) {
    List<int[]> possibleMoves = generateMoves();

    int bestScore = (piece == ai) ? Integer.MIN_VALUE : Integer.MAX_VALUE;
    int currentScore;
    int bestRow = -1;
    int bestCol = -1;

    if (possibleMoves.isEmpty() || depth == 0) {
        // Game over or depth reached
        bestScore = evaluate();
    }
    else {
        for (int[] move : possibleMoves) {
            // Try this move for the player
            board[move[0]][move[1]] = player;
            if (piece == ai) { // ai is maximizing player
                currentScore = minimax(depth - 1, player)[0];

                if (currentScore > bestScore) {
                    bestScore = currentScore;
                    bestRow = move[0];
                    bestCol = move[1];
                }
            }
            else { // player is minimizing player
                currentScore = minimax(depth - 1, ai)[0];

                if (currentScore < bestScore) {
                    bestScore = currentScore;
                    bestRow = move[0];
                    bestCol = move[1];
                }
            }

            // Undo move
            board[move[0]][move[1]] = null;
        }
    }

    return new int[] {bestScore, bestRow, bestCol};
}

private List<int[]> generateMoves() {
    List<int[]> possibleMoves = new ArrayList<int[]>();

    // If game over
    if (game.getWinner() != null) {
        return possibleMoves; // return empty list
    }

    // Add possible moves to list
    for (int x = 0; x < 3; x++) {
        for (int y = 0; y < 3; y++) {
            if (game.getBoard()[x][y] == null) {
                possibleMoves.add(new int[] {x, y});
            }
        }
    }

    return possibleMoves;
}

private int evaluate() {
    int score = 0;
    // Evaluate
    score += evaluateLine(0, 0, 0, 1, 0, 2); // row 0
    score += evaluateLine(1, 0, 1, 1, 1, 2); // row 1
    score += evaluateLine(2, 0, 2, 1, 2, 2); // row 2
    score += evaluateLine(0, 0, 1, 0, 2, 0); // col 0
    score += evaluateLine(0, 1, 1, 1, 2, 1); // col 0
    score += evaluateLine(0, 2, 1, 2, 2, 2); // col 0
    score += evaluateLine(0, 0, 1, 1, 2, 2); // diag 1
    score += evaluateLine(0, 2, 1, 1, 2, 0); // diag 2

    return score;
}

// Return +100, +10, +1 for 3-, 2-, 1-in-a-line for ai
// Return -100, -10, -1 for 3-, 2-, 1-in a line for player
// Else return 0
private int evaluateLine(int row1, int col1, int row2, int col2, int row3, int col3) {
    int score = 0;

    // First cell
    if (board[row1][col1] == ai) {
        score = 1;
    }
    else if (board[row1][col1] == player) {
        score = -1;
    }

    // Second cell
    if (board[row2][col2] == ai) {
        if (score == 1) { // board1 is ai
            score = 10;
        }
        else if (score == -1) { // board1 is player
            return 0;
        }
        else { // board1 is empty
            score = 1;
        }
    }
    else if (board[row2][col2] == player) {
        if (score == -1) { // board1 is player
            score = -10;
        }
        else if (score == 1) { // board1 is ai
            return 0;
        }
        else { // board1 is empty
            score = -1;
        }
    }

    // Third cell
    if (board[row3][col3] == ai) {
        if (score > 0) { // board1 and/or board2 is ai
            score *= 10;
        }
        else if (score < 0) { // board1 and/or board2 is player
            return 0;
        }
        else { // board1 and/or board2 is empty
            score = 1;
        }
    }
    else if (board[row3][col3] == player) {
        if (score < 0) { // board1 and/or board2 is player
            score *= 10;
        }
        else if (score > 1) { // board1 and/or board2 is ai
            return 0;
        }
        else { // board1 and/or board2 is empty
            score = -1;
        }
    }

    return score;
}

A: A couple of things I noticed:

*

*The first line in the loop going through possible moves says board[move[0]][move[1]] = player;. That should be piece instead of player, now your AI thinks that only pieces of the human player ever end up on the board.

*Minimax should be very easily capable of searching the complete game tree in less than a second. Therefore, I'd recommend allowing to to search as deep as it likes, instead of limiting to a search depth of 1. This would also eliminate the need for creating that heuristic evaluation function; you'd only give a large score for winning, 0 for tie, and a very negative score for losing. The main reason I'm recommending this is that I suspect there may be something wrong with the evaluation function too, though I'm not sure since I did not check it in detail. If you really do insist on terminating the search early and using a heuristic evaluation function, you need to make sure that the function is ''symmetrical''. With that, I mean that evaluating the board from the perspective of one player should always result in exactly -1 times the score of the same board were evaluated from the perspective of the opponent.

A: minimax is returning a move in terms of a row/column pair, not a score.  So
currentScore = minimax(depth - 1, player)[0];

makes no sense.  It probably causes any move to row 3 to  look better than any move to row 1 or row 2.
minmax needs to hand
back a score in addition to the best move.


text:
Q: What change needs to be made to IdIOHandler.hpp to resolve the resulting W8058 Cannot create pre-compiled header 'reason' warning? Using the IDE Embarcadero C++ Builder Tokyo 10.2, when I build all my project I get the following message repeated:
[bcc32 Warning] IdIOHandler.hpp(242): W8058 Cannot create pre-compiled header: initialized data in header
The specific line within IdIOHandler.hpp is:
System::UnicodeString __fastcall ReadLnSplit(bool &AWasSplit, System::UnicodeString ATerminator = L"\n", int ATimeout = 0xffffffff, int AMaxLineLength = 0xffffffff, Idglobal::_di_IIdTextEncoding AByteEncoding = Idglobal::_di_IIdTextEncoding());
Looking into this more, it's my understanding that this file is shipped with the IDE. Thus my question is, what is wrong with this file? Is there something I can manually change to resolve with warning? It's my understanding that if I resolve this warning/issue, the project will compile/build faster.
What change needs to be made to IdIOHandler.hpp to resolve the resulting W8058 Cannot create pre-compiled header 'reason' warning?


text:
Q: How to removing irrelevant data in a dataframe? I am having a large data(image:https://drive.google.com/file/d/1TFX1LQhQ-xwYp47fllL8PWwbwbv3wsb6/view?usp=drivesdk).The shape of data is 10000x100 .I want to remove irrelevant data by the condition(-0.5 =<angle<= 0.8).
the angle is a list of Angle_0,Angle_1,Angle_2......Angle_20.
ang = [f"Angle_{i}" for i in range(20)]
I want to have rows which follows the condition(-0.5 =<angle<= 0.8) for angle and delete other rows.
How to do this in python and pandas?
for example Angle_0 has value 0.1926715(row number 24) i want that row of entire dataset then in Angle_1 have data such as 0.1926715,0.192497 and i need those row(row number 7,9,14,16,19,21,23,26,28,29) similary for all other angles
I am a beginner in python.
Thank you very much in advance.

A: new_df = df[(df['angle']>=-0.5 and df['angle']<=0.8]

A: If you need to remove the rows that contain at least one angle that does not follow your conditions, this will solve your problem:
df.loc[(df>=-0.5 & df<=0.8).all(axis=1)]

A: Dirty way:
for n in range (20):
  column_name = "Angle_" + str(n)
  df = df[(df[column_name]>=-0.5 & df[column_name]<=0.8]

Since you need to adress several columns starting with the name Angle you could use regex like this to select them:
df = df.loc[(df.filter(regex='^Angle_') >=-0.5).all(axis=1) & (df.filter(regex='^Angle_')<=0.8).all(axis=1)]

The second solution is better in case you get a variable amount of angles or if it might change later


text:
Q: A question on limsup Let $a_n>0$. Prove that $$\varlimsup_{n\to\infty}n\left(\frac{1+a_{n+1}}{a_n}-1\right)\geq 1.$$
I argue by contradiction. If it is not ture, then $$\exists\ N,\ \forall\ n\geq N, n\left(\frac{1+a_{n+1}}{a_n}-1\right)<1\Rightarrow 1+a_{n+1}-a_n<\frac{a_n}{n}.$$
What contradiction shall I get then....

A: Suppose to the contrary that for $n\ge N$,
$$
n\left(\frac{1+a_{n+1}}{a_n}-1\right)\lt1
$$
Then, for $n\ge N$,
$$
\frac{a_{n+1}}{n+1}\lt\frac{a_n}{n}-\frac1{n+1}
$$
It can be shown by induction that
$$
\frac{a_{n+k}}{n+k}\lt\frac{a_n}n-\sum_{j=1}^k\frac1{n+j}
$$
Since the harmonic series diverges, at some point $\dfrac{a_{n+k}}{n+k}<0$, contrary to the hypothesis that $a_n\gt0$.


text:
Q: Button with name = submit becoming disable while using boot strap validations I am facing a very strange issue.
I have a simple form with a text box. I have two buttons of type submit. If I set name = submit on one of those buttons then buttons are becoming disabled when clicked and not getting posted.
Is this the standard behavior in a boot strap or this can be changed?

A: You should not name any form element "submit" since that will mask/eclipse the JavaScript form.submit() function and it will not be available!
You can address any form field by its name using document["nameOfForm"]["nameOfField"] or document.nameOfForm.nameOfField.  There are already form properties like document.myForm.name or methods like document.myForm.submit().
Using names of form properties or methods that are already defined by the browser will interfere with any functionality that depends on them.
Other common field names to avoid:

*

*action

*enctype

*method

*name

*target

It appears your JS library of choice is using form.submit() to submit the form.

A: Do not use the properties of a form, such as submit, reset, length, method to set the name or id attribute of form, field elements. Name conflicts can cause the problem.
For example, you cannot submit the form after validating if use submit to name the Submit button:
<button type="submit" name="submit" class="btn btn-primary">Submit</button>

DOMLint has a complete list of rules to check the markup for these kind of problems.
Reference : the name conflict warning in the official documentation.


text:
Q: вывод чисел от 1 до 100 без использования чисел в коде Всем привет....недавно начал изучать java, и попался мне на ютубе ролик, где один индус
показывал задание на собеседовании.
вывод чисел от 1 до 100 без использования чисел в коде.
вопрос к более опытным камрадам - реально такое на собесе встретить???
public static void main(String[] args) {
    int one = 'A' / 'A'; //1
    String s = ".........."; //10
    for (int i = one; i <= s.length() * s.length(); i++)
    {
        System.out.println(i);
    }

}

}

A: public static void main(String[] args) {
    for (char i = '!'; i < '\u0085'; i++) {

    }
}


text:
Q: BeautifulSoup - dealing with table like website structures|returning dictionary I have some html, that sort looks like a dictionary:
Manufacturer website: Website,
Headquarters: location, etc
..
Each portion is contained within its own div (so findAll, div class name).
Is there a elegant and simple way to extract such code into a dictionary?  Or does one have to iterate over each div, find both text items, and assume that first text item is key of dictionary, and second value is the value of the same dict element.
Sample Site Code:
    car = '''

          www.ford.com

         Headquarters

         Dearbord, MI

         Model

         Mustang

    '''

car_soup = BeautifulSoup(car, 'lxml')
print(car_soup.prettify())

elements = car_soup.findAll('div', class_ = 'infoEntity')
for x in elements:
    print(x)  ###and then we start iterating over x, with beautiful soup, to find value of each element.

Desired output is this
expected result result = {'manufacturer website':"ford.com", 'Headquarters': 'Dearborn, Mi', 'Model':'Mustang'}

P.S. I've done the non-elegant way a few times at this point, just wondering if I'm missing something, and if there is a better way to do this.  Thank you in advance!

A: The current HTML structure is quite generic, it contains multiple infoEntity divs with child content that can be formatted multiple ways. To handle this, you can iterate over infoEntity divs and apply formatting object like so:
from bs4 import BeautifulSoup as soup
result, label = {}, None
for i in soup(car, 'html.parser').find_all('div', {'class':'infoEntity'}):
   for b in i.find_all(['span', 'label']):
      if b.name == 'label':
         label = b.get_text(strip=True)
      elif b.name == 'span' and label is not None:
         result[label] = b.get_text(strip=True)
         label = None
      else:
         result[' '.join(b['class'])] = b.get_text(strip=True)

Output:
{'manufacturer website': 'www.ford.com', 'Headquarters': 'Dearbord, MI', 'Model': 'Mustang'}

A: Alternatively, to keep things more or less generic and simple, you can split out handling of fields with labels and the manufacturer website link:
soup = BeautifulSoup(car, 'lxml')

car_info = soup.select_one('.info')
data = {
    label.get_text(strip=True): label.find_next_sibling().get_text(strip=True)
    for label in car_info.select('.infoEntity label')
}
data['manufacturer website'] = car_info.select_one('.infoEntity a').get_text(strip=True)

print(data)

Prints:
{'Headquarters': 'Dearbord, MI',
 'Model': 'Mustang',
 'manufacturer website': 'www.ford.com'}


text:
Q: Getting different AES encrypted value when uploading a jar in Oracle database I am trying to do AES Encryption in Oracle database through Java.
Below is my java code
package com.test;

import java.io.ByteArrayInputStream;
import java.io.IOException;
import java.io.ObjectInputStream;
import java.math.BigInteger;
import java.security.InvalidAlgorithmParameterException;
import java.security.InvalidKeyException;
import java.security.NoSuchAlgorithmException;

import javax.crypto.BadPaddingException;
import javax.crypto.Cipher;
import javax.crypto.IllegalBlockSizeException;
import javax.crypto.NoSuchPaddingException;
import javax.crypto.spec.IvParameterSpec;
import javax.crypto.spec.SecretKeySpec;

import sun.misc.BASE64Decoder;
import sun.misc.BASE64Encoder;

public class AESTest {

  public static byte[] iv = {0x1, 0x1, 0x1, 0x1, 0x1, 0x1, 0x1, 0x1, 0x1, 0x1, 0x1, 0x1, 0x1, 0x1, 0x1, 0x1};
  public static byte[] key = {0x1, 0x1, 0x1, 0x1, 0x1, 0x1, 0x1, 0x1, 0x1, 0x1, 0x1, 0x1, 0x1, 0x1, 0x1, 0x1};

  public static String AES_Encrypt(String text) throws ClassNotFoundException, IOException, NoSuchAlgorithmException, NoSuchPaddingException, InvalidKeyException, InvalidAlgorithmParameterException, IllegalBlockSizeException, BadPaddingException {

    Cipher cipher;

    cipher = Cipher.getInstance("AES/CBC/PKCS5Padding");
    SecretKeySpec keySpec = new SecretKeySpec(key, "AES");
    IvParameterSpec ivSpec = new IvParameterSpec(iv);

    cipher.init(Cipher.ENCRYPT_MODE, keySpec, ivSpec);

    byte[] results = cipher.doFinal(text.getBytes("UTF-8"));
    BASE64Encoder encoder = new BASE64Encoder();
    return encoder.encodeBuffer(results);

  }

  public static String AES_Decrypt(String text) throws ClassNotFoundException, IOException, NoSuchAlgorithmException, NoSuchPaddingException, InvalidKeyException, InvalidAlgorithmParameterException, IllegalBlockSizeException, BadPaddingException {

    Cipher cipher;

    cipher = Cipher.getInstance("AES/CBC/PKCS5Padding");
    SecretKeySpec keySpec = new SecretKeySpec(key, "AES");
    IvParameterSpec ivSpec = new IvParameterSpec(iv);

    cipher.init(Cipher.DECRYPT_MODE, keySpec, ivSpec);

    BASE64Decoder decoder = new BASE64Decoder();
    //byte[] results = cipher.doFinal(decoder.decodeBuffer(text));
    byte[] results = cipher.doFinal(decoder.decodeBuffer(text));
    System.out.println(bytesToHex(results));
    return new String(results, "UTF-8");

  }

  public static void main(String[] args) throws InvalidKeyException, ClassNotFoundException, NoSuchAlgorithmException, NoSuchPaddingException, InvalidAlgorithmParameterException, IllegalBlockSizeException, BadPaddingException, IOException {

    System.out.println(AES_Encrypt("test_string"));
    System.out.println(AES_Decrypt("COIhB7Tc8AK5yUNufBBNgw=="));
  }

}

Output:
COIhB7Tc8AK5yUNufBBNgw==
test_string

Now I created jar file of above code AESTest.jar and uploaded the same on Oracle database using below commands.
loadjava -u uname/pwd AESTest.jar

After that created 2 functions in uname schema
create or replace function AES_Encrypt(originalval varchar2) RETURN varchar
as language java
NAME 'com/test/AESTest.AES_Encrypt(java.lang.String)
return java.lang.String';

create or replace function AES_Decrypt(originalval varchar2) RETURN varchar
as language java
NAME 'com/test/AESTest.AES_Decrypt(java.lang.String)
return java.lang.String';

Now When I am trying to run below query
select AES_Encrypt('test_string') from dual;

Output is different : COIhB7Tc8IO5yUNufBBNAA==
From java: COIhB7Tc8AK5yUNufBBNgw==
From DB: COIhB7Tc8IO5yUNufBBNAA==
Now, when I am, trying to decrypt (DB generated encrypted) value using DB function I am getting exception
select AES_Decrypt('COIhB7Tc8IO5yUNufBBNAA==') from dual;

ORA-29532: Java call terminated by uncaught Java exception: javax.crypto.BadPaddingException: Given final block not properly padded
29532. 00000 -  "Java call terminated by uncaught Java exception: %s"
*Cause:    A Java exception or error was signaled and could not be
           resolved by the Java code.
*Action:   Modify Java code, if this behavior is not intended.

However encrypted value generated by running Java code is getting decrypted successfully, even in the database.
select AES_Decrypt('COIhB7Tc8AK5yUNufBBNgw==') from dual;
Output : test_string
Not able to understand, what I am missing. Please suggest.
Oracle DB version - 11.2
JDK version - 1.5


text:
Q: how to change ZooKeeper ensemble I want to access hbase using hive 2.1.1 ,I use the command:
 hive -hiveconf hive.root.logger=DEBUG,console hbase.master=node131:16000
Then I try to create table:
CREATE TABLE iteblog(key int, value string) STORED BY 'org.apache.hadoop.hive.hbase.HBaseStorageHandler' WITH SERDEPROPERTIES ("hbase.columns.mapping" =":key,cf1:val") TBLPROPERTIES ("hbase.table.name" = "iteblog", "hbase.mapred.output.outputtable" = "iteblog");

I found log:
INFO [main] zookeeper.RecoverableZooKeeper: Process identifier=hconnection-0x7cf63b9a connecting to ZooKeeper ensemble=192.168.156.24:2181 .
but I don't config 192.168.156.24 in hive or hadoop, I don't know why it show up .where can I find this config or change it?
I install hive in 192.168.156.25 and node131 is where hbase was installed.

A: 192.168.156.24's problem has been solved, I find the config in an old hbase installation,but this time it always connect localhost . Neither -hiveconf hbase.master nor hbase.zookeeper.quorum can change its behavior . I'll create another new post.


text:
Q: Login with Twitter using passport.js in node.js not working I am using passport.js for twitter login in node.js. But it is not working. It is stay in process for sometime, then return without error or success.
My Code:
module.exports.loginWithTwitter = function (req, res) {

var passport = require('passport');
var Strategy = require('strategy');
var TwitterStrategy = require('passport-twitter').Strategy;

// used to serialize the user for the session
passport.serializeUser(function (user, done) {
    done(null, user.id);
});

// used to deserialize the user
passport.deserializeUser(function (id, done) {
    User.findById(id, function (err, user) {
        done(err, user);
    });
});

passport.use(new TwitterStrategy({
    consumerKey: "HMtGdCax3EMhUAikCi2uySwoQ",
    consumerSecret: "QZlWEdjVbPkWPr7cfS6ohbZgNAkpiboRbP0HGaiv1AvTJRtATw",
    callbackURL: "http://192.168.0.102:4000/api/userData/get"
}, function (token, tokenSecret, profile, cb) {
    console.log('call');
    process.nextTick(function () {
        console.log(profile);
    });
}));
}

I am not getting "console.log('call');" call.
My App.js Code
var express = require('express'),
    app = express(),
    bodyParser = require('body-parser'),
    mongoose = require('mongoose'),
    http = require('http'),
    cors = require('cors');

app.use(cors());

app.use(function(req, res, next) {
    var allowedorigins = ['http://localhost:4000'];
    var origin = req.headers.origin;
    //if (allowedorigins.indexof(origin) > -1) {
    //    res.setheader('access-control-allow-origin', origin);
    //}
    res.header("access-control-allow-credentials", "true");
    res.header("access-control-allow-headers", "x-requested-with");
    res.header("access-control-allow-headers", "origin, x-requested-with, content-type, accept,application/x-www-form-urlencoded");

    next();
});

app.get('/', function(req, res) {
    res.setHeader('Content-Type', 'application/json,application/x-www-form-urlencoded');
    res.send(JSON.stringify({
        Server: "A"
    }));
});

var passport = require('passport');
app.get('/auth/twitter', passport.authenticate('twitter'));

app.get('/auth/twitter/callback', passport.authenticate('twitter', {
    failureRedirect: '/login'
}), function(req, res) {
    console.log('callback')
        // Successful authentication, redirect home.
    res.redirect('/');
});

mongoose.Promise = global.Promise;
mongoose.connect('mongodb://localhost/Eviral'); // mongo DB Connection

var server = app.listen(4000);
var router = express.Router();
app.use(bodyParser.urlencoded({
    limit: '100mb',
    extended: true
})); // configure app to use bodyParser() this will let us get the data from a POST
app.use(bodyParser.json({
    limit: '100mb'
}));

app.use(function(req, res, next) {
    var _send = res.send;
    var sent = false;
    res.send = function(data) {
        if (sent) return;
        _send.bind(res)(data);
        sent = true;
    };
    next();
});

app.use(express.static(__dirname));
app.use(require('./routes/clientMSTRoute'));

A: You have not initialized passport in your app.js. You need to configure passport, before using its authentication strategies.
Also, you need to initialize express-session to create login sessions for you users.
Add these lines in your app.js. Ingore whatever you already have some of them. But, make sure you maintain the order.
app.use(express.cookieParser());
app.use(express.bodyParser());
app.use(express.session({ secret: 'your_secret_keyword' }));
//Below two lines are required to initialize passport
app.use(passport.initialize());
app.use(passport.session());//this should come after express-session
                            //to ensure login session is restored in correct order

Make sure you import all the required node modules. Below are the one's required for these. Add those you dont already have in your app.js
var cookieParser = require('cookie-parser');
var bodyParser = require('body-parser');
var expressSession = require('express-session');
var passport = require('passport');

Please read passport configure documentation for more information.


text:
Q: Long lived AssemblyLoadContext So this is what I'm trying to do. I would like to have a log lived AssemblyLoadContext instance in order to quickly execute loaded assemblies.
When the assemblies updated event comes I would like to unload the context (I'm using .net core 3) and create a new context with versions of assemblies. When I try to do that however I get an error when unloading for the second time

so I'm guessing I'm doing something (very) wrong. I'm guessing the context doesn't get actually unloaded?
If the loaded assembly depends on some external dll I also get an error that that dll cannot be loaded, even though it is in the same folder. How can I prevent that?
Any advice would be very appreciated. This is my code
class Program
{
    private static AssembliesContext assembliesContext;

    const int iterations = 10;

    static void Main(string[] args)
    {
        for (int i = 0; i < iterations; i++)
        {
            assembliesContext = new AssembliesContext();

            RunViaReflection();
            var wr = new WeakReference(assembliesContext);

            assembliesContext.Unload();
            assembliesContext = null;

            int retries = 0;
            while (wr.IsAlive && retries < 5)
            {
                GC.Collect();
                GC.WaitForPendingFinalizers();
                retries++;
            }

        }

    }

    [MethodImpl(MethodImplOptions.NoInlining)]
    static void RunViaReflection()
    {
        try
        {
            string dllPath = Path.Combine(Directory.GetCurrentDirectory(), "..", "..", "..", "..", "Execution.Sample", "bin", "Debug", "netcoreapp2.2", "win10-x64", "publish", "Execution.Sample.dll");

            using (var fs = new FileStream(dllPath, FileMode.Open, FileAccess.Read))
            {
                var assembly = assembliesContext.LoadFromStream(fs);

                var executableType = assembly.GetTypes()
                    .Where(x => typeof(IExecutableCode).IsAssignableFrom(x) && !x.IsInterface && !x.IsAbstract)
                    .FirstOrDefault();

                IExecutableCode instance = (IExecutableCode)Activator.CreateInstance(executableType);
            }

        }
        catch (Exception ex)
        {
            Console.WriteLine(ex.Message);
        }
    }

}

public class AssembliesContext : AssemblyLoadContext
{
    public AssembliesContext(): base(true)
    {

    }

    protected override Assembly Load(AssemblyName assemblyName)
    {
        return null;
    }
}

Edit

I got rid of the error by casting the invoke result to Task (since it's an async method):
((Task)method.Invoke(instance, new object[] { })).ConfigureAwait(false).GetAwaiter().GetResult();

I also loaded the depending assemblies like this:
foreach (var ass in assembly.GetReferencedAssemblies())
                    {
                        string path = Path.Combine(basePath, $"{ass.Name}.dll");
                        using (var dependantAssemblyStream = new FileStream(path, FileMode.Open, FileAccess.Read))
                        {
                            assembliesContext.LoadFromStream(dependantAssemblyStream);
                        }
                    }

I am still wondering how to manage a long lived AssemblyLoadContext since if I try to unload it as a class member it wil not unload, even if I set it to null and instantiate a new one.
Is a different approach warranted?
Edit #2
Right now I have a ConcurrentDictionary of WeakReference items which seems so work fairly ok, but every WeakReference in it loses it's target when the GC runs. Logical, but I still don't know how to make everything work.
If I do something like this
namespace AssemblyLoadTest
{
class Program
{
    static void Main(string[] args)
    {
        AssemblyExecutor executor = new AssemblyExecutor();

        for (int i = 0; i < 1; i++)
        {
            var assemblyPath = Path.Combine(Directory.GetCurrentDirectory(), "..", "..", "..", "..", "Assembly", "Sinapro.IoT.Testing.DotNetRuleTestImplementation.dll");
            executor.Execute(assemblyPath);

            Console.WriteLine($"Iteration {i} completed");

            if (i > 0 && i % 10 == 0)
            {
                executor.Clear();
            }
        }

        executor.Clear();

        while (true)
        {
            Thread.Sleep(100);

            GC.Collect();
            GC.WaitForPendingFinalizers();
        }
    }
}

public class AssemblyExecutor
{
    private readonly ConcurrentDictionary<string, CollectibleAssemblyLoadContext> references = new ConcurrentDictionary<string, CollectibleAssemblyLoadContext>();

    [MethodImpl(MethodImplOptions.NoInlining)]
    public void Clear()
    {
        var keys = references.Keys.ToList();
        foreach (var k in keys)
        {
            references.TryRemove(k, out CollectibleAssemblyLoadContext ctx);

            ctx.Unload();
        }
        GC.Collect();
        GC.WaitForPendingFinalizers();

        Console.WriteLine("GC called");
    }

    public void Execute(string assemblyPath)
    {
        var wr = references.AddOrUpdate(
                    assemblyPath,
                    (k) =>
                    {
                        return CreateReference(assemblyPath);
                    },
                    (k, existingReference) =>
                    {
                        if (existingReference == null || !existingReference.Assemblies.Any())
                        {
                            return CreateReference(assemblyPath);
                        }

                        return existingReference;
                    }
                );

        ExecuteAssembly(wr);
    }

    [MethodImpl(MethodImplOptions.NoInlining)]
    private void ExecuteAssembly(CollectibleAssemblyLoadContext context)
    {
        //CollectibleAssemblyLoadContext context = wr.Target as CollectibleAssemblyLoadContext;
        if (context == null)
            return;

        var assembly = context.Assemblies.FirstOrDefault(a => a.ExportedTypes.Any(t => t.Name == "TestEntry"));

        var types = assembly.GetTypes().ToList();

        var type = assembly.GetType("Sinapro.IoT.Testing.DotNetRuleTestImplementation.TestEntry");

        var greetMethod = type.GetMethod("Execute");

        var instance = Activator.CreateInstance(type);
        var result = greetMethod.Invoke(instance, new object[] { null, null });
    }

    [MethodImpl(MethodImplOptions.NoInlining)]
    private CollectibleAssemblyLoadContext CreateReference(string assemblyPath)
    {
        Console.WriteLine($"Creating new context");
        var context = new CollectibleAssemblyLoadContext(assemblyPath);
        using (var fs = new FileStream(assemblyPath, FileMode.Open, FileAccess.Read))
        {
            var assembly = context.LoadFromStream(fs);
        }

        return context;
    }
}

public class CollectibleAssemblyLoadContext : AssemblyLoadContext
{
    private AssemblyDependencyResolver _resolver;

    public CollectibleAssemblyLoadContext(string path)
        : base(isCollectible: true)
    {
        _resolver = new AssemblyDependencyResolver(path);
    }

    protected override Assembly Load(AssemblyName assemblyName)
    {
        var deps = AssemblyLoadContext.Default;
        var res = deps.Assemblies.Where(d => d.FullName.Contains(assemblyName.Name)).ToList();
        if (res.Any())
        {
            return Assembly.Load(new AssemblyName(res.First().FullName));
        }

        string assemblyPath = _resolver.ResolveAssemblyToPath(assemblyName);
        if (assemblyPath == null)
            return null;

        return LoadFromAssemblyPath(assemblyPath);
    }
}

}
everything runs fine, but the memory consumption keeps increasing. I find it curious though, since there shouldn't be any reference to the AssemblyLoadContext anymore so the GC should've cleared it?


text:
Q: Ошибка проверки задачи на сайте e-olimp Входные данные
В каждой строке задано два целых числа A и B (|A|, |B| ≤ 30000). Считывайте данные до конца файла.
Выходные данные
Для каждого приведенного примера выведите сумму A + B в отдельной строке.
1 1 | 2
На компьютере вроде все ок, но система не признает мое решение. В чем проблема? Вот код мой:
#include <iostream>
using namespace std;

int main()
{
int a; int b; int c;
cin >> a >> b;
c=a+b;
cout << c << endl;

return EXIT_SUCCESS;
}

A: http://www.e-olimp.com/problems/1000 ?
У вас на входе несколько строк, причём в файле. Просто ваша программа обрабатывает одну строку и выходит, а нужно чтобы она сначала собирала все данные а потом выводила по одной строке на каждую строку входных данных. Это во первых. Во вторых у вас должно быть считывание из файла, а не со стандартного ввода. Тут есть код того как это организовывается.
A: #include <iostream.h>
using namespace std;
int main()
{
int a, b,,c;
cin >> a >> b;
c=a+b;
cout << c << endl;

return 0;
}


text:
Q: Encapsulating a variable per instance in Angular 4 I have an application, where a ProductComponent is repeated multiple times as a list. Within this ProductComponent, there is a public boolean local variable  called this.showPriceLoadingText.
However when this variable is updated within an instance, all other instances within the list are updated.
I thought es6 encapsulated variables within the instance/scope it resides in, evidently not.
How could I make this variable behave independently?
class ProductComponent(){

 public showBasketLoadingText: boolean;
 public addingToBasketText: string = "";

 constructor() {
    this.showBasketLoadingText = false;
    this.addingToBasketText = environment.configurations.uiConfig.addingToBasketText;
 }

QuickAddtoCart(product: Product) {

    this.showBasketLoadingText = true;

    //DO STUFF

    let _self = this;
    setTimeout(function(){
        _self.showBasketLoadingText = false;
    }, 1000);
  }

}

HTML:
 Add to basket
{{ addingToBasketText }}

A: You should use this way (arrow notation) to preserve this:
setTimeout(() => {this.showBasketLoadingText = false;}, 1000);

more info here

An arrow function does not have its own this; the this value of the
  enclosing execution context is used.

A: Ive now worked it out... i discovered that the component actually only a product list as opposed to a single product. Apologies for wasting your time


text:
Q: Django: Get nearest object in future or past How can you achieve this with one query:
upcoming_events = Event.objects.order_by('date').filter(date__gte=today)
try:
    return upcoming_events[0]
except IndexError:
    return Event.objects.all().order_by('-date')[0]

My idea is to do something like this:
Event.objects.filter(Q(date__gte=today) | Q(date is max date))[0]

But I don't know how to implement the max date. Maybe I've just to do it with Func. Or When or Case in django.db.expressions might be helpful.

A: Here is a solution with one query (thanks to this post) but I'm not sure if it's faster than the implementation in my question:
from django.db.models import Max, Value, Q

latest = (
    Event.objects
         .all()
         .annotate(common=Value(1))
         .values('common')
         .annotate(latest=Max('date'))
         .values('latest')
)
events = Event.objects.order_by('date').filter(
    Q(date__gte=datetime.date.today()) | Q(date=latest)
)
return events[0]

In my case I finally just took the rows in question (the two latest) and checked for the right event on Python level.


text:
Q: Session window gapDuration in Apache beam I was looking to understand how session window works in apache beam. Let's say I have the following scenario.

*

*I specify a session window with gapDuration of 4 hours.

*Event 1 with key abc occurs now. A new session is created for this key and this session would last now + 4 hours.

*Event 2 with key abc occurs at now + 3 hours. So it belongs to the same session.

*I have a trigger set up to AfterWatermark.pastEndOfWindow().

Will this trigger occur at now + 4 hours or the session is extended due to the event that occurs at now + 3 hours and hence the trigger occurs at now + 3 + 4 hours?

A: The session window would trigger at now + 3 + 4 (i.e., after you had a gapSize period of time without new elements for that key).
Session windows are called "mergable windows" since they can be extended and don't have a fixed size as FixedWindows or SlidingWindows.
If you want more info, there's this talk I gave about Windows in Apache Beam Learning Month


text:
Q: Type/casting of compound assignment operators? (such as *= (star-equals)) I am confused as to this part of exemplary code:
float f = 3.01;
int i;

*

*Case 1: i = f * 100;    // i == 300

*Case 2: i = f *= 100;   // i == 301
I've no idea why in first case the decimal part gets "lost".
I've also tried:
(double) f * 100
f * 100.0

Then I tried volatile and flags to gcc that turn off all optimization.
The result is still the same.
Can somebody explain to me why does the first case behave so? Thank you.

A: The issue is in type conversion:
int i = f * 100 ;

is equivalent to
double tmp = f* 100.0;
int i = tmp;

And the difference with second case is that tmp is double! And yes, there is a case, where double is "less precise"
To illustrate this, I wrote the follwing program:
int main()
{
    float f = 3.01;
    float mf = f * 100;
    double md = f * 100;

    int if_ = mf;
    int id = md;

    std::cout << f << ' ' << mf << ' ' << md << ' ' << ' ' << (mf - md) << ' ' << if_ << ' ' << id << '\n';
}

Edit:
On my system I get same result for my gcc 4.6.1 and cl 16.00 (MS VS 10):
3.01 301 301  9.53674e-007 301 300

Edit2
Found, that enabling optimization -O2 eliminates issue. This explains difference with IDEONE.
Here is another code:
int main()
{
    float f = 3.01;
    float mf = f * 100;
    return mf + (f*100);

    //std::cout << f << ' ' << mf << ' ' << md << ' ' << ' ' << (mf - md) << ' ' << if_ << ' ' << id << '\n';
}

And its assembly with -O0
    movl    $0x4040a3d7, %eax
    movl    %eax, 28(%esp)

    flds    28(%esp)
    flds    LC1
    fmulp   %st, %st(1)
    fstps   24(%esp)
    flds    28(%esp)
    flds    LC1
    fmulp   %st, %st(1)
    fadds   24(%esp)
    fnstcw  14(%esp)
    movw    14(%esp), %ax
    movb    $12, %ah
    movw    %ax, 12(%esp)
    fldcw   12(%esp)
    fistpl  8(%esp)
    fldcw   14(%esp)
    movl    8(%esp), %eax

We can see only one explicit conversion to single precision instruction (fspts). This conforms my guess, that temporary evaluates from double, not float.
And with -O2 assembly is pretty simple:
    movl    $602, %eax

And at last
If we disable optimization of evaluting, IDEONE compiler reproduce behavior too:

A: I can only guess that in the first example, the temporary result has higher accuracy than float and the result is almost 301 (e.g. 300.999999999999). In the second example the result is put into f (which is a float) and is rounded to 301.
I'm not sure about that but it seems like a fair guess.

A: Your second case you take f, which is a float and multiply it by 100, which equals 301, then you put that value into your int i, there is no decimal place so there is no loss of data.

A: Compiler bug? It works fine here: http://ideone.com/FlQCL


text:
Q: Does partitioning help if you don't query on the partition value? Say I have an orders.Order table that is partitioned on CreatedWhen (a datetime column set to GetDate() when the row is created).
The table has over 10 million rows and the partition is quarterly (or some such regular interval).
If I run a query like:
SELECT ord.OrderId, ord.ClientId, ord.ReceptId, ord.Cost, agt.State
FROM   orders.Order ord
       join personnel.Agent agt
          on ord.AgentId = agt.AgentId
WHERE  agt.FirstName = 'Bob'
       and LastName = 'Whiely'
       and ord.Cost > 135

Am I going to see any benefit from the partition for this query?
I don't see how there could be a benefit because I am not using the partition value in my query and all of the table still needs to be searched.
Note: The results of the query will all be in the most recent partition.  But I don't see how that would help.
Second Note: The partitions are all on the same SAN drive (Sys Admins won't let it be any other way), so the disk IO will not be parallel.
Is there a better way to partition so that random queries, like the one above, will perform better?  (Maybe on the primary key?)
Third Note: The query above is made up.  I am using it to show that I have many queries that hit many random columns (which are properly indexed).

A: Partitioning is not typically a performance enhancer.  Normally, partitioning is employed to enable efficient data management.  For instance, you can employ partitioning to easily swap old rows out of a table into an archive table, one partition at a time.
Querying against a partitioned table where your query does not include the partitioning key forces SQL Server to look at the entire table.  This is less efficient than simply scanning or seeking into a non-partitioned table because each partition is essentially a table, necessitating a UNION ALL style query against all the partitions.  This is not particularly obvious when looking at a query plan for a partitioned table, although you can see it if you look carefully at the pop-up properties for an index or table seek or scan:

To make this more obvious, lets set up a simple test rig in tempdb, with a date-based partitioning key:
USE tempdb;
GO
IF OBJECT_ID(N'dbo.Tab', N'U') IS NOT NULL
BEGIN
    DROP TABLE dbo.Tab;
    DROP PARTITION SCHEME PartScheme;
    DROP PARTITION FUNCTION PartFun;
END
GO

CREATE PARTITION FUNCTION PartFun (datetime)
AS RANGE LEFT
FOR VALUES (
      N'2012-01-01T00:00:00'
    , N'2012-04-01T00:00:00'
    , N'2012-07-01T00:00:00'
    , N'2012-10-01T00:00:00'
    , N'2013-01-01T00:00:00'
    , N'2013-04-01T00:00:00'
    , N'2013-07-01T00:00:00'
    , N'2013-10-01T00:00:00'
    , N'2014-01-01T00:00:00'
    , N'2014-04-01T00:00:00'
    , N'2014-07-01T00:00:00'
    , N'2014-10-01T00:00:00'
);

CREATE PARTITION SCHEME PartScheme
AS PARTITION PartFun
ALL TO ([PRIMARY]);

IF OBJECT_ID(N'dbo.Tab', N'U') IS NOT NULL
DROP TABLE dbo.Tab;
CREATE TABLE dbo.Tab
(
    TabID int NOT NULL
    , CreateDate datetime NOT NULL
    , Data1 varchar(100) NOT NULL
    , Data2 varchar(10) NOT NULL
    , Data3 varchar(1000) NOT NULL
    , CONSTRAINT PK_Tab
        PRIMARY KEY CLUSTERED
        (CreateDate, TabID)
) ON [PartScheme](CreateDate);

This will populate the table with 1,000,000 rows with randomly generated data evenly spread over all partitions:
;WITH Ten AS
(
    SELECT v.Num
    FROM (VALUES (0), (1), (2), (3), (4), (5), (6), (7), (8), (9))v(Num)
)
, Million AS
(
    SELECT Num = (t6.Num * POWER(10, 5))
        + (t5.Num * POWER(10, 4))
        + (t4.Num * POWER(10, 3))
        + (t3.Num * POWER(10, 2))
        + (t2.Num * POWER(10, 1))
        + (t1.Num)
    FROM Ten t1
        CROSS JOIN Ten t2
        CROSS JOIN Ten t3
        CROSS JOIN Ten t4
        CROSS JOIN Ten t5
        CROSS JOIN Ten t6
)
INSERT INTO dbo.Tab (TabID, CreateDate, Data1, Data2, Data3)
SELECT m.Num, DATEADD(DAY, m.Num % 1000, N'2012-01-01T00:00:00')
    , CONVERT(varchar(100), CRYPT_GEN_RANDOM(100))
    , CONVERT(varchar(10), CRYPT_GEN_RANDOM(10))
    , CONVERT(varchar(1000), CRYPT_GEN_RANDOM(1000))
FROM Million m;

Let's go ahead and create a non-clustered index using our partitioning scheme:
CREATE NONCLUSTERED INDEX IX_Tab
ON dbo.Tab(Data1)
ON [PartScheme](CreateDate);

Now, let's look at three "typical" queries you might execute (the first query just gets an actual value out of the table, which is then used in the WHERE clause for the three queries):
DECLARE @d varchar(100);
SELECT TOP(1) @d = t.Data1
FROM dbo.Tab t
WHERE t.CreateDate > N'2013-08-24T00:00:00';

SELECT Data1
FROM dbo.Tab
WHERE Tab.Data1 = @d;

SELECT Data1
FROM dbo.Tab
WHERE Tab.Data1 = @d
    AND tab.CreateDate >= N'2013-08-23T00:00:00'

SELECT Data1
FROM dbo.Tab
WHERE Tab.Data1 = @d
    AND tab.CreateDate >= N'2013-08-23T00:00:00'
    AND tab.CreateDate <= N'2013-08-29T00:00:00';

Here is a quick screenshot of the execution plans so you can see the difference adding the partitioning key to the WHERE clause can make:

The "query costs relative to the batch" numbers are instructive here.  The first query consumes 50% of the batch cost since it performed a scan of all 13 partitions.  It does that since it has no idea where in the table the particular value of Data1 exists.  The second query consumes only 23% by virtue of the "Start Date" parameter, which can eliminate half the partitions.  Finally, the third query only consumes 4% since it only needs to look at a single partition, because we included a "start date" and an "end date".
The "statistics" for the 3 queries are:

Table 'Tab'. Scan count 13, logical reads 36, physical reads 0, read-ahead reads 0, lob logical reads 0, lob physical reads 0, lob read-ahead reads 0.
Table 'Tab'. Scan count 6, logical reads 16, physical reads 0, read-ahead reads 0, lob logical reads 0, lob physical reads 0, lob read-ahead reads 0.
Table 'Tab'. Scan count 1, logical reads 4, physical reads 0, read-ahead reads 0, lob logical reads 0, lob physical reads 0, lob read-ahead reads 0.

What if we add one of the other columns to these queries:
DECLARE @d varchar(100);
SELECT TOP(1) @d = t.Data1
FROM dbo.Tab t
WHERE t.CreateDate > N'2013-08-24T00:00:00';

SELECT Data1
    , Data2
FROM dbo.Tab
WHERE Tab.Data1 = @d;

SELECT Data1
    , Data2
FROM dbo.Tab
WHERE Tab.Data1 = @d
    AND tab.CreateDate >= N'2013-08-23T00:00:00'

SELECT Data1
    , Data2
FROM dbo.Tab
WHERE Tab.Data1 = @d
    AND tab.CreateDate >= N'2013-08-23T00:00:00'
    AND tab.CreateDate <= N'2013-08-29T00:00:00';

The execution plans:

The statistics for those:

Table 'Tab'. Scan count 13, logical reads 39, physical reads 0, read-ahead reads 0, lob logical reads 0, lob physical reads 0, lob read-ahead reads 0.
Table 'Tab'. Scan count 6, logical reads 19, physical reads 0, read-ahead reads 0, lob logical reads 0, lob physical reads 0, lob read-ahead reads 0.
Table 'Tab'. Scan count 1, logical reads 7, physical reads 0, read-ahead reads 0, lob logical reads 0, lob physical reads 0, lob read-ahead reads 0.

So, lets just do away with the partitioning, and re-run all those tests:
IF OBJECT_ID(N'dbo.TabU', N'U') IS NOT NULL
DROP TABLE dbo.TabU;
CREATE TABLE dbo.TabU
(
    TabID int NOT NULL
    , CreateDate datetime NOT NULL
    , Data1 varchar(100) NOT NULL
    , Data2 varchar(10) NOT NULL
    , Data3 varchar(1000) NOT NULL
    , CONSTRAINT PK_TabU
        PRIMARY KEY CLUSTERED
        (CreateDate, TabID)
) ON [PRIMARY];

;WITH Ten AS
(
    SELECT v.Num
    FROM (VALUES (0), (1), (2), (3), (4), (5), (6), (7), (8), (9))v(Num)
)
, Million AS
(
    SELECT Num = (t6.Num * POWER(10, 5))
        + (t5.Num * POWER(10, 4))
        + (t4.Num * POWER(10, 3))
        + (t3.Num * POWER(10, 2))
        + (t2.Num * POWER(10, 1))
        + (t1.Num)
    FROM Ten t1
        CROSS JOIN Ten t2
        CROSS JOIN Ten t3
        CROSS JOIN Ten t4
        CROSS JOIN Ten t5
        CROSS JOIN Ten t6
)
INSERT INTO dbo.TabU (TabID, CreateDate, Data1, Data2, Data3)
SELECT m.Num, DATEADD(DAY, m.Num % 1000, N'2012-01-01T00:00:00')
    , CONVERT(varchar(100), CRYPT_GEN_RANDOM(100))
    , CONVERT(varchar(10), CRYPT_GEN_RANDOM(10))
    , CONVERT(varchar(1000), CRYPT_GEN_RANDOM(1000))
FROM Million m;

CREATE NONCLUSTERED INDEX IX_TabU
ON dbo.TabU(Data1)
ON [PRIMARY];

Now, the first set of queries:
DECLARE @d varchar(100);
SELECT TOP(1) @d = t.Data1
FROM dbo.TabU t
WHERE t.CreateDate > N'2013-08-24T00:00:00';

SELECT Data1
FROM dbo.TabU
WHERE TabU.Data1 = @d;

SELECT Data1
FROM dbo.TabU
WHERE TabU.Data1 = @d
    AND TabU.CreateDate >= N'2013-08-23T00:00:00'

SELECT Data1
FROM dbo.TabU
WHERE TabU.Data1 = @d
    AND TabU.CreateDate >= N'2013-08-23T00:00:00'
    AND TabU.CreateDate <= N'2013-08-29T00:00:00';

And the plans:

And the stats:

Table 'TabU'. Scan count 1, logical reads 4, physical reads 0, read-ahead reads 0, lob logical reads 0, lob physical reads 0, lob read-ahead reads 0.
Table 'TabU'. Scan count 1, logical reads 4, physical reads 0, read-ahead reads 0, lob logical reads 0, lob physical reads 0, lob read-ahead reads 0.
Table 'TabU'. Scan count 1, logical reads 4, physical reads 0, read-ahead reads 0, lob logical reads 0, lob physical reads 0, lob read-ahead reads 0.

All three queries now have the same "cost", which is substantially lower than the partitioned version.
The queries with Data1 and Data2 columns:
DECLARE @d varchar(100);
SELECT TOP(1) @d = t.Data1
FROM dbo.TabU t
WHERE t.CreateDate > N'2013-08-24T00:00:00';

SELECT Data1
    , Data2
FROM dbo.TabU
WHERE TabU.Data1 = @d;

SELECT Data1
    , Data2
FROM dbo.TabU
WHERE TabU.Data1 = @d
    AND TabU.CreateDate >= N'2013-08-23T00:00:00'

SELECT Data1
    , Data2
FROM dbo.TabU
WHERE TabU.Data1 = @d
    AND TabU.CreateDate >= N'2013-08-23T00:00:00'
    AND TabU.CreateDate <= N'2013-08-29T00:00:00';

and the stats:

Table 'TabU'. Scan count 1, logical reads 8, physical reads 0, read-ahead reads 0, lob logical reads 0, lob physical reads 0, lob read-ahead reads 0.
Table 'TabU'. Scan count 1, logical reads 8, physical reads 0, read-ahead reads 0, lob logical reads 0, lob physical reads 0, lob read-ahead reads 0.
Table 'TabU'. Scan count 1, logical reads 8, physical reads 0, read-ahead reads 0, lob logical reads 0, lob physical reads 0, lob read-ahead reads 0.

Clearly, if you can't do the queries the correct way, by including the partitioning key, then you are going to see worse performance with partitioning than without.


text:
Q: Getting proper date format with php I have a date field in html. From it I transmit date via POST in php to another file and different browsers transmit it in different formats. For example, chrome 2014-12-30, mozilla 30.12.2014. How I can easily change date format, when I assign this field to php variable?

A: change with date() in php
$date = '30.12.2014';
echo date('Y-m-d', strtotime($date));

or datetime()
$datetime = new DateTime($date);
echo $datetime->format('Y-m-d');

A: If you use the DateTime class to create a date formatting the date is very easy.
$dateNow = new DateTime();

Then to format the date into the wanted format you use the format method
$dateNow->format('Y-m-d') // Google Chrome
$dateNow->format('d.m.Y') // Mozilla Firefox

A: Use date with strtotime. The first argument in date() is the format you desire, the second is  the strtotime'd date you have pulled.
echo date('d m y', strtotime("date POST var here"));

A: with the strftime function, you can get localized dates.
use it along with setlocale()
example from php.net:
setlocale(LC_TIME, "C");
echo strftime("%A");
setlocale(LC_TIME, "fi_FI");
echo strftime(" in Finnish is %A,");
setlocale(LC_TIME, "fr_FR");
echo strftime(" in French %A and");
setlocale(LC_TIME, "de_DE");
echo strftime(" in German %A.\n");

A: <?php

    $u_agent = $_SERVER['HTTP_USER_AGENT'];

    // Next get the name of the useragent yes seperately and for good reason
    if(preg_match('/MSIE/i',$u_agent) && !preg_match('/Opera/i',$u_agent))
    {
        echo date('Y-m-d', strtotime($date));
        //your code
    }
    elseif(preg_match('/Firefox/i',$u_agent))
    {
       echo date('d-m-Y', strtotime($date));
       //your code
    }
    elseif(preg_match('/Chrome/i',$u_agent))
    {
       echo date('Y-m-d', strtotime($date));
       //your code
    }
    elseif(preg_match('/Safari/i',$u_agent))
    {
       echo date('Y-m-d', strtotime($date));
       //your code
    }
    elseif(preg_match('/Opera/i',$u_agent))
    {
       echo date('Y-m-d', strtotime($date));
       //your code
    }
    elseif(preg_match('/Netscape/i',$u_agent))
    {
       echo date('Y-m-d', strtotime($date));
       //your code
    }

?>


text:
Q: Question about Hankel's contour applied for Gamma functions I would like to have some explanation (or pehaps some intuition) on the Hankel's contour for the following contour integral:  $$ F(n)= \oint_{C} \frac{e^{ -z} }{z^{n+1}} \,dz$$
,where n is non-integer.
Arfken's textbook shows how this end up relating to the gamma function, which it is not what I am asking here.  Also I understand that the cut is chosen to be on the positive real axis for convergence of the integrand.
My question/confusion is that we usually try to avoid enclosing a branch cut while evaluating complex integrals (Hankel's contour being an exception), but on the picture below, we end up including the branch cuts and branch points and never closing the contour (I also understand this has a residue at infinity for n non-integer):

If I could get explanation on why I am allowed to include branch cuts (counterclockwise direction instead of excluding them) and why not closing the contour (I am assuming it is because the branch cut goes to infinity and there is a residue at infinity, but I am not sure), it would be nice.


text:
Q: Loading database records into bootstrap datatable I have about 8000 customer records which I have to load all into a bootstrap datatable with ofcourse pagination using AJAX, it works fine,but my challenge is it takes a longer time to finish loading and populating the datatable.
I have to load all the 8000 customers because users may select any at anytime and work with
Please any idea as to how to optimize this,its really slowing down the  asp.net site
Below is my code

<script type="text/javascript">
        var datatableVariable = null
        $(document).ajaxSend(function (event, request, settings) {
            $('#loading-indicator').show();
        });
        $(document).ready(function () {
            "responsive"; true,
            "serverSide"; true,
            "info"; true,
            "stateSave"; true,
         $.ajax({
             type: "POST",
             dataType: "json",
             url: "CustomerService.asmx/GetCustomer",
             success: function (data) {
                 datatableVariable = $('#dtCustomers').DataTable({

                     data: data,
                     columns: [
                         { 'data': 'iD' },
                         { 'data': 'AccountNumber' },
                         { 'data': 'Name' },
                          { 'data': 'FirstName' },
                           { 'data': 'LastName' },
                            { 'data': 'Balance' },
                             { 'data': 'TypeOfAccount' },
                             { 'data': 'Phone' },
                             { 'data': 'SMSAlert' }
                     ],
                     columnDefs: [
                 { "visible": false, "targets": 0 },
                  { "visible": false, "targets": 3 },
                   { "visible": false, "targets": 4 },
                   { "visible": false, "targets": 5},
                   { "visible": false, "targets": 6 },
                   { "visible": false, "targets": 7 },
                   { "visible": false, "targets": 8 }
                     ]
                 });
                 datatableVariable.columns().every(function () {
                     var column = this;
                     $(this.footer()).find('input').on('keyup change', function () {
                         column.search(this.value).draw();
                     });
                 });
                 $('.showHide').on('click', function () {
                     var tableColumn = datatableVariable.column($(this).attr('data-columnindex'));
                     tableColumn.visible(!tableColumn.visible());
                 });
                 $(document).ajaxComplete(function (event, request, settings) {
                     $('#loading-indicator').hide();
                 });
             }
         });
        });
        $('#dtCustomers').on('click', 'tr', function () {
                     debugger
                     var data = datatableVariable.row(this).data();
                     $(document.getElementById('<%= customerids.ClientID %>')).val(data.iD);
                     $(document.getElementById('<%= lblFnames.ClientID %>')).val(data.FirstName);
                     $(document.getElementById('<%= lblLnames.ClientID %>')).val(data.LastName);
                     $(document.getElementById('<%= lblacc.ClientID %>')).val(data.AccountNumber);
                     $(document.getElementById('<%= lblBals.ClientID %>')).val(data.Balance);
                     $(document.getElementById('<%= acctypes.ClientID %>')).val(data.TypeOfAccount);
                     $(document.getElementById('<%= phone.ClientID %>')).val(data.Phone);
                     $(document.getElementById('<%= smsalert.ClientID %>')).val(data.SMSAlert);
                        var imgDisplay = $get("imgDisplay");
                        imgDisplay.src = "";
                        imgDisplay.style.cssText = "";
                        var img = new Image();
                        img.onload = function () {
                            imgDisplay.style.cssText = "height:150px;width:150px";
                            imgDisplay.src = img.src;
                        };
                        img.src = "<%=ResolveUrl(UploadFolderPath) %>" + data.CustomerPicture;
                     switch (data.TypeOfAccount) {
                         case 0:
                             $('#<%= withid.ClientID %>').hide()
                             break;
                         case 4:
                             $('#<%= withid.ClientID %>').show()

                             break;

                         default:

                     }
        });

    </script>


text:
Q: JavaScript/Coffeescript is not executing unless I refresh I have some coffeescript:
http://jsfiddle.net/jdell64/9v646/
that utilizes the jquery ui datepicker. On page load it gets an array of available dates (one month at a time) and displays them. This works on IE, but not on firefox or chrome. I have to refresh the page in order to get it to work.
Basically,
$ ->
  full_days = []
  partial_days = []
  getDays = (date) ->
     # return the available days for a given month (ajax call)

  getDays()

  formatDays = (date) ->
    # apply a 'full-day' class to days with 24 hours available and 'partial-day' if they have < 24 hours

  availableHours = (day) ->
     # manipulate the json response and make an array

  showdatepicker = ->
    $('.datepicker').datepicker(
     ...
     # make my text field a datepicker
     )
showdatepicker()

I tried to just leave bare-bones here, but I can post everything.
How do I get jquery-UI datepicker to make an ajax call to the db before the page loads AND every time I change the month?
Edit:
I added some console.log() to the coffeescript. I put one at the very beginning. It appears that the javascript is not executing at all unless I refresh the page (no output unless I refresh).
How do I fix this?

A: The issue I was having was in the Gemfile: turbolinks. Turbolinks was behaving as designed--it was not reloading the page unless I refreshed the page. The reason this worked in my IE browser is when turbolinks fails (old browser) it fails gracefully and allows the pages to be reloaded (I learned all of this from Rails Cast #390.
All I needed to do was

*

*put my code in a variable
ready = ->
        (all of my code)

*call this variable on document ready
$(document).ready(ready)

*Tell turbolinks about it
$(document).on('page:load', ready)


text:
Q: Toastr Alert Asp.Net Vb Im trying to do some alert messages on a web form in visual studio vb, but it keeps giving me this error when i try and code it dynamically in the action method
"only content controls are allowed directly in a content page that contains content controls"
i have left the old code in where it just produces a label error message into the HTML
getting a blue wave line underneath this line
popupScript = "<script language='javascript'>" + "showErrorToast();" + "</script>"

jquery function
<script type="text/javascript">
function showErrorToastr() {
    toastr.warning('Please enter at least 3 characters of the organisation name')
}

Vb Action method when cancel button its clicked
 Protected Sub btnSelect0_Click(ByVal sender As Object, ByVal e As System.EventArgs)
    Dim popupScript As String = ""
    If txtorgname.Text = "" Then
        lblerror.Text = "Please enter at least 3 characters of the organisation name"
        txtorgname.Focus()
        popupScript = "<script language='javascript'>" + "showErrorToast();" + "</script>"
    ElseIf Len(txtorgname.Text) < 3 Then
        lblerror.Text = "Please enter at least 3 characters of the organisation name"
        txtorgname.Focus()
    ElseIf Len(txtorgname.Text) > 50 Then
        lblerror.Text = "Organisation name too long. Max 50"
        txtorgname.Focus()
    Else
        BindData()
    End If
End Sub

A: showErrorToast does not exist in your example, but showErrorToastr does.
Try that change. If it doesn't work, please comment.


text:
Q: Create JSON from part of xml with php I am currently trying to parse an xml document with php. All is going well apart from one thing. Here is a sample of my xml:
<properties>
  <property>
    <propertyid>1</propertyid>
    <flags>
      <flag>This is a flag</flag>
      <flag>This is another flag</flag>
      <flag>This is yet another flag</flag>
      <flag>etc...</flag>
    </flags>
  </property>
  <property>
    ...
  </property>
<properties>

As you can see there are multiple <property> nodes. I am using SimpleXML which works perfectly fine. I just loop through each <property> with php and get the values, for example:
foreach ( $xml->$property as $property )
{
  echo $property->propertyid;
}

The problem is the <flag> nodes. Basically, I want to end up with JSON that looks like this:
{
  "flags1":
  {
    "flag": "This is a flag"
  },
  "flags2":
  {
    "flag": "This is another flag"
  },
  "flags3":
  {
    "flag": "This is yet another flag"
  }
  ,
  "flags4":
  {
    "flag": "..."
  }
}

There will be an indeterminate amount of flags for each property. I have tried a foreach loop to get the flag values which worked but then how can I get the values looking like the example JSON?
My foreach loop looks like this:
$flags = $property->flags;
foreach ( $flags->flag as $index => $flag )
{
  $arr = array($index => (string)$flag);
  echo json_encode($arr);
}

Which returns:
{"flag":"This is a flag"}{"flag":"This is another flag"}{"flag":"This is yet another flag"}{"flag":"etc..."}

This is so nearly there, I just don't know how to get it to be correct.

A: Hope this one will be helpful. Here we are using simplexml_load_string
Try this code snippet here
$result=array();
$counter=0;
$xml=simplexml_load_string($string);
foreach($xml->property as $data)//iterating over properties
{
    foreach($data->flags->flag as $flag)//iterating over flag
    {
        $result["flag$counter"]=array("flag"=>(string)$flag);
        $counter++;
    }
}

print_r(json_encode($result,JSON_PRETTY_PRINT));

A: {
"properties": {
    "parsererror": {
        "-style": "display: block; white-space: pre; border: 2px solid #c77; padding: 0 1em 0 1em; margin: 1em; background-color: #fdd; color: black",
        "h3": [
            "This page contains the following errors:",
            "Below is a rendering of the page up to the first error."
        ],
        "div": {
            "-style": "font-family:monospace;font-size:12px",
            "#text": "error on line 14 at column 13: Extra content at the end of the document"
        }
    },
    "property": [{
        "propertyid": "1",
        "flags": {
            "flag": [
                "This is a flag",
                "This is another flag",
                "This is yet another flag",
                "etc..."
            ]
        }
    }]
}

}


text:
Q: TableLayout, android:layout_weight, and include I have a layout with 6 included layouts in a TableLayout. I want to do this in landscape mode, because a ScrollView would be awkward in my scenario.
I have a 48dp-high horizontal layout, which contains a square ImageView, a SeekBar with full weight, and a square ImageButton. I set the drawables for the ImageView in Java.
In the main layout, I use an include for each one and I am trying to even out the columns, because they only take up half the screen, by the way this is an activity with Theme.Holo.Dialog as its theme.
However, when I run the app, I get a 40-60% unbalanced view. Why? What am I doing wrong?
Part of layout-land/main.xml
<LinearLayout
     xmlns:android="http://schemas.android.com/apk/res/android"
     android:layout_width="match_parent"
     android:layout_height="wrap_content"
      ... >
...
<TableLayout
    android:layout_width="match_parent"
    android:layout_weight="1"
    android:stretchColumns="1"
    android:layout_height="wrap_content">

    <TableRow android:layout_width="match_parent" android:layout_height="wrap_content">
        <include android:layout_weight="1" layout="@layout/toast_item" android:id="@+id/systemToast"/>
        <include android:layout_weight="1" layout="@layout/toast_item" android:id="@+id/ringerToast"/>
    </TableRow>

    <TableRow android:layout_width="match_parent" android:layout_height="wrap_content">
        <include android:layout_weight="1" layout="@layout/toast_item" android:id="@+id/notifyToast"/>
        <include android:layout_weight="1" layout="@layout/toast_item" android:id="@+id/mediaToast"/>
    </TableRow>

    <TableRow android:layout_width="match_parent" android:layout_height="wrap_content">
        <include android:layout_weight="1" layout="@layout/toast_item" android:id="@+id/alarmToast"/>
        <include android:layout_weight="1" layout="@layout/toast_item" android:id="@+id/inCallToast"/>
    </TableRow>

</TableLayout>
...
</LinearLayout>

layout-land/toast_item.xml
<?xml version="1.0" encoding="utf-8"?>
<LinearLayout xmlns:android="http://schemas.android.com/apk/res/android"
   android:layout_width="0dp"
   android:layout_height="48dp"
   android:layout_marginLeft="8dp"
   android:layout_marginRight="8dp"
   android:orientation="horizontal"
   android:gravity="center_vertical">

<ImageView
    android:id="@+id/icon"
    android:src="@drawable/ic_audio_alarm"
    android:layout_width="48dp"
    android:layout_height="48dp"
    android:scaleType="center"
    android:clickable="false"
    android:layout_weight="0"/>
<SeekBar
    android:layout_width="0dp"
    android:layout_height="48dp"
    android:layout_weight="1"
    android:gravity="center_vertical"
    android:layout_marginLeft="4dp"
    android:maxHeight="1000dp"
    android:layout_marginRight="4dp"
    android:id="@+id/seekbar"/>
<ImageButton
    android:id="@+id/schedules"
    android:layout_width="48dp"
    android:layout_height="match_parent"
    android:scaleType="center"
    android:layout_weight="0"
    android:src="@drawable/ic_action_event"
    android:background="?android:attr/selectableItemBackground"
/>
</LinearLayout>

A: I noticed you have android:layout_weight, but I didn't seem android:weightSum.
I would suggest you have android:weightSum="2" so that your two objects that have android:layout_weight="1" will distribute evenly.
According to the Android Documentation:

If there are three text fields and two of them declare a
weight of 1, while the other is given no weight, the third text field
without weight will not grow and will only occupy the area required by
its content. The other two will expand equally to fill the space
remaining after all three fields are measured.
If the third field is
then given a weight of 2 (instead of 0), then it is now declared more
important than both the others, so it gets half the total remaining
space, while the first two share the rest equally.


text:
Q: How to display the content of a JSON array? My Django app sends through AJAX POST/GET communications arrays representing parts of my DB. As you can see on the picture, this is a typical array with all the objects. The objects represent a messages to integrate in a chat box. Just to clarify, the amount of objects might vary, so I need a loop function or smthg to display all the objects within the response array .
Therefore, I need to display these arrays, combining HTML and JS.
This is my exact AJAX Json response
HTML:

JS:

But nothing is displaying.

A: you can do like this


text:
Q: 20.04 - How to change the size and appearance of desktop icons and the way they are handled? I've just upgraded from Ubuntu 18.04 to its newest LTS version - 20.04. While it comes with some interesting changes, the Desktop icon system was messed up in my opinion. When you hover the mouse cursor over the icons, you see a huge space marked around them that cannot be violated (as you can see in the image below) so that they need to be placed very far apart from each other.
18.04 allowed you to place icons much closer to each other and didn't have that marked space around them. This new way leaves much less space on the Desktop to organize large amounts of icons - including folders, files and shortcuts. Is there a way I can significantly reduce the size of icons and their "spaces" or go back to the old system of organizing files? On "Settings", there is a tool to change the size of Dock icons, but not of Desktop icons.
Also, every time I move or delete something, the Desktop "flashes" and the icons seem to rearrange themselves automatically, nothing of which happened in 18.04. I also can't move anything directly to the Desktop; I need to move to the Desktop folder on Nautilus. This makes me start to think about downgrading Ubuntu back to 18.04.

A: Since some previous versions of Ubuntu..
Desktop Icons are handled by desktop-icons gnome-shell extension.
you can achieve the sizes and spacing you mentioned in Question by editing the extensions prefs.js file. Take backup of the file before editing.
the extensions directory is /usr/share/gnome-shell/extensions/desktop-icons@csoriano
Original Content:
const ICON_SIZE = { 'small': 48, 'standard': 64, 'large': 96 };
const ICON_WIDTH = { 'small': 108, 'standard': 116, 'large': 116 };
const ICON_HEIGHT = { 'small': 86, 'standard': 102, 'large': 134 };

Edited Content:
const ICON_SIZE = { 'small': 48, 'standard': 64, 'large': 96 };
const ICON_WIDTH = { 'small': 52, 'standard': 116, 'large': 116 };
const ICON_HEIGHT = { 'small': 60, 'standard': 102, 'large': 134 };

I Have Configured the sizes for 'small', you can achieve with other sizes 'standard' and 'large' also.

Above method requires root privileges.. If you need to make changes locally..
Disable the system extension desktop-icons.
gnome-extensions disable desktop-icons@csoriano

create the local extensions directory.
install -d $HOME/.local/share/gnome-shell/extensions

Copy the system extension desktop-icons to local extensions directory and rename it as desktop-icons@csoriano-local
cp -r /usr/share/gnome-shell/extensions/desktop-icons@csoriano $HOME/.local/share/gnome-shell/extensions/desktop-icons@csoriano-local

Edit the metadata.json file of the local extension like below contents.
Observe that "local" is the main change
{ we need to edit the metadata.json file because extensions directory name and the UUID field in the metadata.json file must match }
gedit $HOME/.local/share/gnome-shell/extensions/desktop-icons@csoriano-local/metadata.json

Already Edited Content:
{
    "name": "Desktop Icons-local",
    "description": "Add icons to the desktop",
    "uuid": "desktop-icons@csoriano-local",
    "shell-version": ["3.34.0"]
}

Enable the local extension with below command
gnome-extensions enable desktop-icons@csoriano-local

Refresh the gnome-shell with Alt+F2 'r' Enter method.

Make sure you never turn on both the extensions desktop-icons@csoriano (System Extension) and desktop-icons@csoriano-local (Local Extension)

A: For Ubuntu 21.04 you can change the size of the desktop icons by simply adjusting it via the desktop settings again.
Right click on the desktop->choose settings
You can adjust the Icon size in the Dialog


text:
Q: Edit breadcrumble for EditUser I created a Moodle plugin based on the edit user admin page moodle/admin/user.php.
Everything works, except the breadcrumble from the top navigation is still pointing to the edit user admin page.
This is the starting script of the plugin that creates the invalid breadcrumble:
<?php
require('../../config.php');
require_once($CFG->dirroot.'/course/lib.php');
require_once($CFG->dirroot.'/report/log/locallib.php');
require_once($CFG->libdir.'/adminlib.php');
require_once($CFG->dirroot.'/lib/tablelib.php');
require_once($CFG->dirroot.'/user/filters/lib.php');
require_once($CFG->dirroot.'/user/lib.php');

  // Check if user is allowed to browse users
  admin_externalpage_setup('editusers');

  $sort         = optional_param('sort', 'name', PARAM_ALPHANUM);
  $dir          = optional_param('dir', 'ASC', PARAM_ALPHA);
  $page         = optional_param('page', 0, PARAM_INT);
  $perpage      = optional_param('perpage', 30, PARAM_INT);

  $returnurl = new moodle_url('/report/gnppoints/index.php', array('sort' => $sort, 'dir' => $dir, 'perpage' => $perpage, 'page'=>$page));

  $sitecontext = context_system::instance();
  $site = get_site();

  $strshowallusers = get_string('showallusers');

  $ufiltering = new user_filtering();

  echo $OUTPUT->header();

I don't know where the breadcrumble is created. Any suggestions?

A: First add this in settings.php:
$ADMIN->add('reports',
            new admin_externalpage('reportgnp', get_string('pluginname','report_gnppoints'),
            $url
          ));

Then replace
admin_externalpage_setup('editusers');

by
admin_externalpage_setup('reportgnp');


text:
Q: Binding Properties of Primitive Wrapper Types with Spring MVC It appears to me that Spring MVC cannot bind properties of primitive wrapper types(e.g. Integer, Boolean, etc). When it tries to bind such properties, it throws the following exception.
javax.servlet.ServletException: javax.servlet.jsp.JspException: javax.servlet.jsp.JspException: org.springframework.beans.NotReadablePropertyException: Invalid property 'assigned' of bean class [model.domain.Employee]: Bean property 'assigned' is not readable or has an invalid getter method: Does the return type of the getter match the parameter type of the setter?
    org.apache.jasper.runtime.PageContextImpl.doHandlePageException(PageContextImpl.java:858)
    org.apache.jasper.runtime.PageContextImpl.handlePageException(PageContextImpl.java:791)
    org.apache.jsp.WEB_002dINF.jsp.configuration.form.defaultForm_jsp._jspService(defaultForm_jsp.java:87)
    org.apache.jasper.runtime.HttpJspBase.service(HttpJspBase.java:70)
    javax.servlet.http.HttpServlet.service(HttpServlet.java:717)
    org.apache.jasper.servlet.JspServletWrapper.service(JspServletWrapper.java:377)
    org.apache.jasper.servlet.JspServlet.serviceJspFile(JspServlet.java:313)
    org.apache.jasper.servlet.JspServlet.service(JspServlet.java:260)
    javax.servlet.http.HttpServlet.service(HttpServlet.java:717)
    org.springframework.web.servlet.view.InternalResourceView.renderMergedOutputModel(InternalResourceView.java:238)
    org.springframework.web.servlet.view.AbstractView.render(AbstractView.java:250)
    org.springframework.web.servlet.DispatcherServlet.render(DispatcherServlet.java:1063)
    org.springframework.web.servlet.DispatcherServlet.doDispatch(DispatcherServlet.java:801)
    org.springframework.web.servlet.DispatcherServlet.doService(DispatcherServlet.java:719)
    org.springframework.web.servlet.FrameworkServlet.processRequest(FrameworkServlet.java:644)
    org.springframework.web.servlet.FrameworkServlet.doGet(FrameworkServlet.java:549)
    javax.servlet.http.HttpServlet.service(HttpServlet.java:617)
    javax.servlet.http.HttpServlet.service(HttpServlet.java:717)
    org.apache.tiles.web.startup.TilesFilter.doFilter(TilesFilter.java:75)

As soon as I changed the type of the 'assigned' property(getter, setter and instance variable) from Boolean to boolean, it worked fine.
Can anyone confirm Spring MVC cannot bind properties of primitive wrapper types? If so, is there any workaround? I can't change the property type to boolean because a null value in this property means something for my application.
Thanks.

A: Spring MVC works fine with Boolean.
This error may appear if your getter for Boolean is named isAssigned(). According to JavaBeans naming conventions, only boolean may have this form of getter name, Boolean should have getAssigned().

A: On workaround would be to create / register your own property editors.
Another workaround would be to add a second setter that allows you to set the property as a 'boolean'.  (You may need to fiddle around with your APIs to subvert Spring's "helpful" insistence that the getter and setter types parameter / result types match.  If I'm doing this kind of thing, I typically end up with two setters with different names for the same logical property.)