text:
Q: net.corda.serialization.internal.amqp.IllegalCustomSerializerException during the start for flow I am getting below error while executing one of the corda flow.
start ApplyLoCFlow beneficiary: "", issuingBank: "", advisingBank: "", locID: null, applicationDate: null, amount: 1000, locStatus: "create": exception: net.corda.serialization.internal.amqp.IllegalCustomSerializerException: exception(java.lang.Throwable) -> Custom serializer net.corda.serialization.internal.amqp.custom.ThrowableSerializer registered to serialize non-custom-serializable type class net.corda.core.flows.IllegalFlowLogicException
Mon Sep 30 10:40:03 IST 2019>>>

Mon Sep 30 10:40:03 IST 2019>>> [ERROR] 10:40:03+0530
  [pool-8-thread-2] command.CRaSHSession.execute - Error while
  evaluating request 'start ApplyLoCFlow beneficiary: "", issuingBank:
  "", advisingBank: "", locID: null, applicationDate: null, amount:
  1000, locStatus: "create"' start ApplyLoCFlow beneficiary: "",
  issuingBank: "", advisingBank: "", locID: null, applicationDate: null,
  amount: 1000, locStatus: "create": exception:
  net.corda.serialization.internal.amqp.IllegalCustomSerializerException:
  exception(java.lang.Throwable) -> Custom serializer
  net.corda.serialization.internal.amqp.custom.ThrowableSerializer
  registered to serialize non-custom-serializable type class
  net.corda.core.flows.IllegalFlowLogicException [errorCode=g3v6fv,
  moreInformationAt=https://errors.corda.net/OS/4.1/g3v6fv]

LoCState:
package com.template.states;

import com.template.contracts.LoCContract;
import net.corda.core.contracts.*;
import net.corda.core.identity.AbstractParty;
import net.corda.core.identity.Party;
import net.corda.core.serialization.CordaSerializable;

import java.time.LocalDate;
import java.util.Arrays;
import java.util.Currency;
import java.util.Date;
import java.util.List;

// *********
// * State *
// *********
@BelongsToContract(LoCContract.class)
@CordaSerializable
public class LoCState implements LinearState {
    private Party applicant;
    private Party beneficiary;
    private Party issuingBank;
    private Party advisingBank;
    private UniqueIdentifier locID;
    private Date applicationDate;
    private int amount;
    private String locStatus;

    public LoCState(Party applicant, Party benificiery, Party issuingBank,
                    Party advisingBank, UniqueIdentifier locID, Date applicationDate,
                    int amount, String locStatus) {
        this.applicant = applicant;
        this.beneficiary = benificiery;
        this.issuingBank = issuingBank;
        this.advisingBank = advisingBank;
        this.locID = locID;
        this.applicationDate = applicationDate;
        this.amount = amount;
        this.locStatus = locStatus;
    }

    public List<AbstractParty> getParticipants() {
        return Arrays.asList(applicant, beneficiary, issuingBank, advisingBank);
    }

    public UniqueIdentifier getLinearId() {
        return this.locID;
    }

    public Party getApplicant() {
        return applicant;
    }

    public void setApplicant(Party applicant) {
        this.applicant = applicant;
    }

    public Party getBeneficiary() {
        return beneficiary;
    }

    public void setBeneficiary(Party beneficiary) {
        this.beneficiary = beneficiary;
    }

    public Party getIssuingBank() {
        return issuingBank;
    }

    public void setIssuingBank(Party issuingBank) {
        this.issuingBank = issuingBank;
    }

    public Party getAdvisingBank() {
        return advisingBank;
    }

    public void setAdvisingBank(Party advisingBank) {
        this.advisingBank = advisingBank;
    }

    public UniqueIdentifier getLocID() {
        return locID;
    }

    public void setLocID(UniqueIdentifier locID) {
        this.locID = locID;
    }

    public Date getApplicationDate() {
        return applicationDate;
    }

    public void setApplicationDate(Date applicationDate) {
        this.applicationDate = applicationDate;
    }

    public int getAmount() {
        return amount;
    }

    public void setAmount(int amount) {
        this.amount = amount;
    }

    public String getLocStatus() {
        return locStatus;
    }

    public void setLocStatus(String locStatus) {
        this.locStatus = locStatus;
    }
}

LoCContract:
package com.template.contracts;

import net.corda.core.contracts.CommandData;
import net.corda.core.contracts.Contract;
import net.corda.core.transactions.LedgerTransaction;

public class LoCContract implements Contract {

            @Override
            public void verify(LedgerTransaction tx) {}

            public interface Commands extends CommandData {
                class CreateLoC implements Commands {}
            }
        }

ApplyLoCFlow:
package com.template.flows;

import co.paralleluniverse.fibers.Suspendable;
import com.template.contracts.LoCContract;
import com.template.states.LoCState;
import net.corda.core.contracts.Amount;
import net.corda.core.contracts.Command;
import net.corda.core.contracts.UniqueIdentifier;
import net.corda.core.flows.*;
import net.corda.core.identity.CordaX500Name;
import net.corda.core.identity.Party;
import net.corda.core.transactions.SignedTransaction;
import net.corda.core.transactions.TransactionBuilder;
import net.corda.core.utilities.ProgressTracker;

import java.time.LocalDate;
import java.util.Arrays;
import java.util.Currency;
import java.util.Date;

import static com.template.flows.ProgressTrackerStates.*;

@InitiatingFlow
@StartableByRPC
public class ApplyLoCFlow extends FlowLogic<SignedTransaction> {

    public ApplyLoCFlow(String beneficiary, String issuingBank, String advisingBank,
                        UniqueIdentifier locID, LocalDate applicationDate,
                        int amount, String locStatus) {
        this.beneficiary = beneficiary;
        this.issuingBank = issuingBank;
        this.advisingBank = advisingBank;
    //    this.locID = locID;
    //    this.applicationDate = applicationDate;
        this.amount = amount;
        this.locStatus = locStatus;
    }

    private String beneficiary;
    private String issuingBank;
    private String advisingBank;
  //  private UniqueIdentifier locID;
  //  private LocalDate applicationDate;
    private int amount;
    private String locStatus;

    private final ProgressTracker progressTracker = new ProgressTracker(GETTING_NOTARY, GETTING_COUNTERPARTIES,GENERATING_TRANSACTION, VERIFYING_TRANSACTION, SIGNING_TRANSACTION, FINALISING_TRANSACTION);

    @Override
    public ProgressTracker getProgressTracker() {
        return progressTracker;
    }

    @Suspendable
    @Override
    public SignedTransaction call() throws FlowException {
        progressTracker.setCurrentStep(GETTING_NOTARY);
        final Party notary=getServiceHub().getNetworkMapCache().getNotaryIdentities().get(0);

        progressTracker.setCurrentStep(GETTING_COUNTERPARTIES);
        Party bName=null;
        Party iBank= null;
        Party aBank= null;
      //  if(getServiceHub().getIdentityService().partiesFromName(beneficiary, false).iterator().hasNext()){
            CordaX500Name counterPartyName = new CordaX500Name("PartyA", "Hyderabad", "IN");
            bName = getServiceHub().getIdentityService().wellKnownPartyFromX500Name(counterPartyName);
           // bName=getServiceHub().getIdentityService().partiesFromName(beneficiary, false).iterator().next();

      //  }
        /*if(getServiceHub().getIdentityService().partiesFromName(issuingBank, false).iterator().hasNext()){
             iBank=getServiceHub().getIdentityService().partiesFromName(issuingBank, false).iterator().next();
        }*/
        CordaX500Name issuingName = new CordaX500Name("BankA", "Chennai", "IN");
        iBank = getServiceHub().getIdentityService().wellKnownPartyFromX500Name(issuingName);
       /* if(getServiceHub().getIdentityService().partiesFromName(advisingBank, false).iterator().hasNext()){
             aBank=getServiceHub().getIdentityService().partiesFromName(advisingBank, false).iterator().next();
        }*/
        CordaX500Name advName = new CordaX500Name("BankB", "Mumbai", "IN");
        aBank = getServiceHub().getIdentityService().wellKnownPartyFromX500Name(advName);
        TransactionBuilder txBuilder= new TransactionBuilder(notary);
        Command command= new Command(new LoCContract.Commands.CreateLoC(), Arrays.asList(getServiceHub().getMyInfo().getLegalIdentities().get(0).getOwningKey()));
        LoCState state= new LoCState(getOurIdentity(), bName, iBank, aBank,  new UniqueIdentifier(), new Date(), amount, "Open");

        txBuilder.addOutputState(state, LoCContract.ID);
        txBuilder.addCommand(command);

        progressTracker.setCurrentStep(VERIFYING_TRANSACTION);
        txBuilder.verify(getServiceHub());

        progressTracker.setCurrentStep(SIGNING_TRANSACTION);
        SignedTransaction stx= getServiceHub().signInitialTransaction(txBuilder);

        progressTracker.setCurrentStep(FINALISING_TRANSACTION);
        return subFlow(new FinalityFlow(stx));
        // Initiator flow logic goes here.

    }
}

A: If you are using Corda v4, there should be ResponderFlows for all the participants(not only signers) of the state.
Keep empty constructors for the Corda state.


text:
Q: Xcode 9 Conflicting provisioning settings I have a nativescript angular app that is showing an error whenever I try to run it on a real IOS device. The app runs fine on an emulator and on android.
The error log is reproduced below. I have tried to use automatically manage signing option in Xcode a suggested in this SO answer. However this does not work and I keep getting the same error.
I also tried building an archive in Xcode. When I try to Export the archive xcode just shuts down with an error.
The error log is as follows:
Xcode build...
2017-10-22 14:14:29.951 xcodebuild[69327:634958] [MT] IDEDistribution: -[IDEDistributionLogging _createLoggingBundleAtPath:]: Created bundle at path '/var/folders/73/29kcfd816cd6jbsm48mqkp2r0000gp/T/questNewS_2017-10-22_14-14-29.950.xcdistributionlogs'.
2017-10-22 14:14:34.389 xcodebuild[69327:634958] [MT] DVTAssertions: Warning in /Library/Caches/com.apple.xbs/Sources/DVTFrameworks/DVTFrameworks-13233/DVTFoundation/DeveloperStructure/DVTPlatformFamily.m:192
Details:  Error Domain=DVTMachOErrorDomain Code=1 "Reached end of file while looking for: Mach-O slice." UserInfo={NSLocalizedDescription=Reached end of file while looking for: Mach-O slice., NSLocalizedRecoverySuggestion=}
Object:   <NSBundle>
Method:   +dvt_platformFamilyForBundleAtPath:error:
Thread:   <NSThread: 0x7ff668d15a50>{number = 1, name = main}
Please file a bug at http://bugreport.apple.com with this warning message and any useful information you can provide.
2017-10-22 14:14:34.510 xcodebuild[69327:634958] [MT] DVTAssertions: Warning in /Library/Caches/com.apple.xbs/Sources/DVTFrameworks/DVTFrameworks-13233/DVTFoundation/DeveloperStructure/DVTPlatformFamily.m:192
Details:  Error Domain=DVTMachOErrorDomain Code=1 "Reached end of file while looking for: Mach-O slice." UserInfo={NSLocalizedDescription=Reached end of file while looking for: Mach-O slice., NSLocalizedRecoverySuggestion=}
Object:   <NSBundle>
Method:   +dvt_platformFamilyForBundleAtPath:error:
Thread:   <NSThread: 0x7ff668d15a50>{number = 1, name = main}
Please file a bug at http://bugreport.apple.com with this warning message and any useful information you can provide.
2017-10-22 14:14:34.512 xcodebuild[69327:634958] [MT] DVTAssertions: Warning in /Library/Caches/com.apple.xbs/Sources/DVTFrameworks/DVTFrameworks-13233/DVTFoundation/DeveloperStructure/DVTPlatformFamily.m:192
Details:  Error Domain=DVTMachOErrorDomain Code=1 "Reached end of file while looking for: Mach-O slice." UserInfo={NSLocalizedDescription=Reached end of file while looking for: Mach-O slice., NSLocalizedRecoverySuggestion=}
Object:   <NSBundle>
Method:   +dvt_platformFamilyForBundleAtPath:error:
Thread:   <NSThread: 0x7ff668d15a50>{number = 1, name = main}
Please file a bug at http://bugreport.apple.com with this warning message and any useful information you can provide.
2017-10-22 14:14:34.513 xcodebuild[69327:634958] [MT] DVTAssertions: Warning in /Library/Caches/com.apple.xbs/Sources/DVTFrameworks/DVTFrameworks-13233/DVTFoundation/DeveloperStructure/DVTPlatformFamily.m:192
Details:  Error Domain=DVTMachOErrorDomain Code=1 "Reached end of file while looking for: Mach-O slice." UserInfo={NSLocalizedDescription=Reached end of file while looking for: Mach-O slice., NSLocalizedRecoverySuggestion=}
Object:   <NSBundle>
Method:   +dvt_platformFamilyForBundleAtPath:error:
Thread:   <NSThread: 0x7ff668d15a50>{number = 1, name = main}
Please file a bug at http://bugreport.apple.com with this warning message and any useful information you can provide.
2017-10-22 14:14:34.863 xcodebuild[69327:634958] [MT] IDEDistribution: Step failed: <IDEDistributionSigningAssetsStep: 0x7ff66e134cc0>: Error Domain=IDEDistributionSigningAssetStepErrorDomain Code=0 "Locating signing assets failed." UserInfo={NSLocalizedDescription=Locating signing assets failed., IDEDistributionSigningAssetStepUnderlyingErrors=(
    "Error Domain=IDEProvisioningErrorDomain Code=8 \"adb has conflicting provisioning settings.\" UserInfo={NSLocalizedDescription=adb has conflicting provisioning settings., NSLocalizedRecoverySuggestion=adb is automatically signed for distribution, but a conflicting code signing identity iPhone Developer has been manually specified. Remove the \"signingCertificate\" entry from your Export Options property list, or switch to manual signing by setting \"signingStyle\" to \"Manual.}",
    "Error Domain=IDEProvisioningErrorDomain Code=8 \"ios-device-lib has conflicting provisioning settings.\" UserInfo={NSLocalizedDescription=ios-device-lib has conflicting provisioning settings., NSLocalizedRecoverySuggestion=ios-device-lib is automatically signed for distribution, but a conflicting code signing identity iPhone Developer has been manually specified. Remove the \"signingCertificate\" entry from your Export Options property list, or switch to manual signing by setting \"signingStyle\" to \"Manual.}"
)}
error: exportArchive: adb has conflicting provisioning settings.

Error Domain=IDEProvisioningErrorDomain Code=8 "adb has conflicting provisioning settings." UserInfo={NSLocalizedDescription=adb has conflicting provisioning settings., NSLocalizedRecoverySuggestion=adb is automatically signed for distribution, but a conflicting code signing identity iPhone Developer has been manually specified. Remove the "signingCertificate" entry from your Export Options property list, or switch to manual signing by setting "signingStyle" to "Manual.}

error: exportArchive: ios-device-lib has conflicting provisioning settings.

Error Domain=IDEProvisioningErrorDomain Code=8 "ios-device-lib has conflicting provisioning settings." UserInfo={NSLocalizedDescription=ios-device-lib has conflicting provisioning settings., NSLocalizedRecoverySuggestion=ios-device-lib is automatically signed for distribution, but a conflicting code signing identity iPhone Developer has been manually specified. Remove the "signingCertificate" entry from your Export Options property list, or switch to manual signing by setting "signingStyle" to "Manual.}

** EXPORT FAILED **

Unable to apply changes on device: 2f5eb251a28d7102c8c421f1f8477b21f67a1470. Error is: Command xcodebuild failed with exit code 70

redpajama_set_name: RedPajamaStackExchange


text:
Q: Check time range between two columns laravel The following is migration. I want to implement a condition. But I don't know how to check time range between start_time and end_time.
  Schema::create('settings', function (Blueprint $table) {
            $table->id();
            $table->unsignedBigInteger('user_id');
            $table->time('start_time');
            $table->time('end_time');
            $table->foreign('user_id')->references('id')->on('users');
            $table->timestamps();
        });

following is what I'm trying.
     $date =  new DateTime("Asia/Karachi");
     $date = $date->format('Y-m-d H:i:s');
     $date = date('H:i:s',strtotime($date));

        $users_with_crypto_only_sms_alert =
      User::whereNotNull('device_key')
        ->where('subscription_package', 'LIKE', '%Morpheus%')
         ->where('role', '=', 'user')
         ->where('sms_alerts', '=', 1)
         ->where('is_email', '=', 0)
         ->where('is_blocked', '=', 0)
         ->where('mobile_no', '!=', '')
          ->whereHas('setting',function($q) use($date){
                        $q->whereTime('start_time','>=',$date);
                        $q->whereTime('end_time','<=',$date);
                    })->pluck('device_key')->all();
                    dd($users_with_crypto_only_sms_alert);

A: [Opinionated] You should not use time as the field type of start_time and end_time.
You can use whether timestamp or datetime to be able calculate the time differences.
If you want to use datetime, you can use this answer
https://stackoverflow.com/a/39665726/3673225
If you want to use timestamp, you can use this answer
https://stackoverflow.com/a/2920518/3673225


text:
Q: Proof that the Sum of Products is Zero This is part of my answer to a question of a contest. But I ask about a really specific part of my answer and I can show the behaviour, but somehow don't know how to proof it generally. This is probably because of my missing experience with the summation symbol. The proof should be fairly simple, since it's right there but I don't know how to handle it.
There is a row of b Zeros for Example: $ Z_q = 0; Z_{q+1} = 0 ... Z_{q + b - 1} = 0$
$q+b-1 = p \quad S(p) = 0 \quad  if \quad p < 2b $
$$S(n) = \sum_{m=0}^n Z_m * Z_{n - m}$$
When I write down the Sums, it seems rather obvious that this must be true:
$S(p) = Z_{0}*Z_{p} + Z_{1}*Z_{p-1} + Z_{2}*Z_{p-2} ... + Z_{p} * Z_{p - p}$ $For\;example:\;S(5) = Z_0 * Z_5 + Z_1 * Z_4 + Z_2 * Z_3 + Z_3*Z_2 + Z_4* Z_1 + Z_5*Z_0$
$If \; b = 2 \; then \; 5 > 2*b,\; but \; if \; b \ge 3 \; then \,5 < 2 * b \land S(5) = 0 \qquad\qquad\qquad\qquad\qquad\qquad$
But I somehow fail to proof it generally.

A: S(p) is the sum of p + 1 products. Since the first b products are equal to zero and the last b products are equal to zero, all products are equal to zero if $(p+1) - 2b \le 0 \to p + 1 \le 2b \to p < 2b$


text:
Q: UpdateModel raise exception I have a strong typed view model and a MetaData partial class which has annotation attributes on required fields and field type.  The Create.aspx view page has a form when submitted will execute Create method in the controller. When the user submit the form without all the required fields entered, upon reaching UpdateModel() line an exception is thrown.  However, none of the error messages specified in the annotated fields is shown.  Instead, the execution iterate through the RuleViolation() and landed at the most generic exception message.  Thus, the user does not know that some required fields are not entered.  If I define the checking if empty of required fields in the RuleVilolation() method then it is not DRY.  Does anyone know why the error messages are not shown from the MetaClass? Thank you.
///Controller method
[AcceptVerbs(HttpVerbs.Post)]
[ValidateInput(false)]
public ActionResult Create(string id, [Bind(Prefix = "Transfer")]TransferFormViewModel newTransferViewModel, string cancel)
{
  ....
  if (ModelState.IsValid)
  {
      Transfer newTransfer = new Transfer();

      if (ModelState.IsValid)
      {
        try
          {
            Person person = base.ApplicaitonRepository.GetPerson(intID);
            UpdateModel<Transfer>(newTransfer, "Transfer");
            .....
          }
        catch (Exception ex)
          {
            newTransfer.MiscException = ex;
            HelpersLib.ModelStateHelpers.AddModelErrors(this.ModelState, newTransfer.GetRuleViolations());
          }
      }
   }
   return View(new TransferFormViewModel(base.ApplicaitonRepository, newTransfer));
}

///partial domain objec class
[MetadataType(typeof(TransferMetaData))]
public partial class Transfer
{
  public IEnumerable<RuleViolation> GetRuleViolations()
  {
    ....
  }
}

///MetaData class
class TransferMetaData
{
[Display(Name="List Type")]
public int ListType { get; set; }

[Required(ErrorMessage = "Notification Date/Time is required."), Display(Name = "Notification Date/Time")]
        public DateTime AddedToListDate { get; set; }

[Required(ErrorMessage="Admit Date/Time is required."), Display(Name="Admit Date/Time")]
...
}

A: Do you have <%= Html.ValidationSummary() %> somewhere in your view?
What entries are in your ModelState?


text:
Q: Specify timeout when tracing HTTP request in Go I know the usual method of specifying a timeout with HTTP requests by doing:
httpClient := http.Client{
    Timeout: time.Duration(5 * time.Second),
}

However, I can't seem to figure out how to do the same when tracing HTTP requests. Here is the piece of code I am working with:
func timeGet(url string) (httpTimingBreakDown, error) {
    req, _ := http.NewRequest("GET", url, nil)

    var start, connect, dns, tlsHandshake time.Time
    var timingData httpTimingBreakDown
    timingData.url = url

    trace := &httptrace.ClientTrace{
        TLSHandshakeStart:    func() { tlsHandshake = time.Now() },
        TLSHandshakeDone:     func(cs tls.ConnectionState, err error) { timingData.tls = time.Since(tlsHandshake) },
    }

    req = req.WithContext(httptrace.WithClientTrace(req.Context(), trace))
    start = time.Now()

    http.DefaultTransport.(*http.Transport).ResponseHeaderTimeout = time.Second * 10 // hacky way, worked earlier but don't work anymore

    if _, err := http.DefaultTransport.RoundTrip(req); err != nil {
        fmt.Println(err)
        return timingData, err
    }

    timingData.total = time.Since(start)

    return timingData, nil
}

I am firing this function inside a goroutine. My sample data set is 100 urls. All goroutines fire, but eventually the program ends in 30+ secs as if the timeout is 30secs.
Earlier I made the same to work by using the hacky way of changing the default inside of it to 10 secs and anything that took too long, timed out and the program ended at 10.xxx secs but now its taking 30.xx secs.
What would be a proper way of specifying a timeout in this scenario?

A:
I know the usual method of specifying a timeout with HTTP requests by doing:
httpClient := http.Client{
    Timeout: time.Duration(5 * time.Second),
}

Actually, the preferred method is to use a context.Context on the request. The method you've used is just a short-cut suitable for simple use cases.
req, err := http.NewRequest(http.MethodGet, url, nil)
if err != nil {
    return nil, err
}
ctx, cancel := context.WithTimeout(context.Background(), 5 * time.Second)
defer cancel()
req = req.WithContext(ctx)

And this method should work nicely for your situation as well.


text:
Q: How can I add a file to an existing Mac OS X .app bundle? I'm writing a modification for Arduino that turns an Arduino board into a game controller.
In order to add my board-specific files to the programming environment, right now, the user needs to open up the Arduino.app package, and then add a few different files into a various folders in the Arduino.app package. It is hardly user friendly. How can I make an installer which automatically moves my files into the appropriate locations within Arduino.app, or is that impossible?

A: You can download PackageMaker (available here, in the Auxiliary Tools for Xcode download).
You will then be able to make a .pkg that the user will be able to install simply by double clicking. You can also make a script that will check if Arduino is already installed and stop the installation if it's not. You get the idea.

A: Normally, especially in today's code-signed MacOS app approach (where any modifications to the app or its resources/files would break the app & make it not-launchable), I would say "you're out of luck".
But Arduino is one of the rare OPEN SOURCE apps.
You can fetch the source code from this page:
http://arduino.cc/en/Main/Software
And make your modifications to the project and then build a fresh, customized copy for yourself.

A: I figured out how to do it using the magic of scripting!
You can take a look at my solution here:
http://code.google.com/p/unojoy/source/browse/#hg%2FLeoJoy%2FLeoJoy%20Installer.app%2FContents%2FMacOS
The folder structure it's in makes it show up as an app on OSX, and the two scripts (LeoJoy Installer and LeoJoyInstaller.command) copy the files. There's two scripts there because I wanted to have a console window pop up to show the user progress, and that's the only way I could figure out how to do that.  But, if you run this app in the same directory as the Arduino app, it copies files from the installer app into the Arduino.app package, updating the Arduino app so I don't have to distribute a whole separate version of Arduino.


text:
Q: Does Mongodb have something like SQL "As" feature? For example, if I want to simplify the result set for a nested doc', get the field score.date as score_date in order to get a flat result

A: Yes, this is possible through the aggregation framework, in particular you would want to use the $project operator. This reshapes each document in the stream, such as by adding new fields or removing existing fields. For each input document, outputs one document. Using your example, suppose your collection has documents with this schema:
{
    "_id" : ObjectId("557330473a79b31f0c805db3"),
    "player": "A",
    "score": {
        "date": ISODate("2015-05-30T15:14:48.000Z"),
        "value": 2
    }
}

Then you would apply the $project operator in the aggregation pipeline as:
db.collection.aggregate([
    {
        "$project": {
            "player": 1,
            "score_date": "$score.date",
            "score_value": "$score.value"
        }
    }
]);

Result:
/* 0 */
{
    "result" : [
        {
            "_id" : ObjectId("557330473a79b31f0c805db3"),
            "player" : "A",
            "score_date" : ISODate("2015-05-30T15:14:48.000Z"),
            "score_value" : 2
        }
    ],
    "ok" : 1
}


text:
Q: How can i make params `out` in C#? I find myself in the situation requiring this
public static void Fill(this SomeClass c, params out object[] p)

and calling it as
c.Fill(out i, out i2, out sz, out i3, out sz2);

However i get the error error CS1611: The params parameter cannot be declared as ref or out
How can i pass in variable length arguments and make them writeable? All of these are a mixture of ints and strings

A: There is no technical need for out here. This works:
void Fill(object[] p)
{
    p[0] = 1;
    p[1] = 42;
    p[2] = "Hello";
    p[3] = -1;
    p[4] = "World";
}

object[] p = new object[5];
foo.Fill(p);
i = (int)p[0];
i2 = (int)p[1];
sz = (string)p[2];
i3 = (int)p[3];
sz2 = (string)p[4];

You could return your values as Tuple:
(define your own tuple class if you're not using .NET4.0)
static Tuple<int, string> Fill()
{
    return new Tuple(42, "Hello World");
}

and then define extension methods to unpack tuples:
public static class TupleExtensions
{
    public static void Unpack<T1, T2>(
        this Tuple<T1, T2> tuple,
        out T1 item1,
        out T2 item2)
    {
        item1 = tuple.Item1;
        item2 = tuple.Item2;
    }
}

Then you can write this:
int i;
string sz;

foo.Fill().Unpack(out i, out sz);

A: You can't have it treat the arguments as out (or ref) and make use of the params feature at the same time. It simply doesn't work. The best you can do is to create an array parameter, make the array out, declare an array variable and call the method passing the array, then inspect each element manually by index.
Foo(out object[] data) {...}
object[] result;
Foo(out result);
// look at result[0], result[1], result[2] etc

So: you cannot do what you want. Even if you could, ref / out never work unless there is an exact match between data type, so it would still have to be:
object o1, o2, o3, o4;
Foo(out o1, out o2, out o3, out o4);
// cast o1, o2, o3, o4

Which still isn't what you want.

A: 1) If you can avoid the need to get the values in declared variables, then passing the array and populating it is the best option, as shown by dtb's answer.
2) Otherwise you can have a simple wrapper for your variable.
public class Wrapper //or may be generic?
{
    public object Value { get; set; }

    public Wrapper(object value)
    {
        Value = value;
    }
}

Now you can call
var i = new Wrapper(0), i2 = new Wrapper(0), i3 = new Wrapper(0);
c.Fill(i, i2, i3);
i.Value //your value here

public static void Fill(this SomeClass c, params Wrapper[] p)
{
    for (int i = 0; i < p.Length; i++)
    {
        p[i].Value = 1; //assigning
    }
}

You will have to deal with Value property after calling Fill method.
3) You can make use of closure. Something like the Ref<T> class implemented as shown:
public static class Ref
{
    public static Ref<T>[] Create<T>(params Expression<Func<T>>[] getters)
    {
        return getters.Select(Create).ToArray();
    }

    public static Ref<T> Create<T>(Expression<Func<T>> getter)
    {
        return new Ref<T>(getter);
    }
}

public sealed class Ref<T>
{
    readonly Func<T> getter;
    readonly Action<T> setter;

    public Ref(Expression<Func<T>> getter)
    {
        var output = getter.Body;
        var input = Expression.Parameter(output.Type); //or hardcode typeof(T)
        var assign = Expression.Assign(output, input);
        var setter = Expression.Lambda<Action<T>>(assign, input);

        this.getter = getter.Compile();
        this.setter = setter.Compile();
    }

    public T Value
    {
        get { return getter(); }
        set { setter(value); }
    }
}

public static void Fill(this SomeClass c, params Ref<object>[] p)
//assign inside

object i = 0, i2 = 0, i3 = 0;
c.Fill(Ref.Create(() => i, () => i2, () => i3));
//i, i2 etc changed

Few things to note:

*

*All the above approaches are basically ref approaches, compiler doesn't simply force assigning value of parameters inside the method before the control leaves as in the case of out which is your question, but as far as I know out is not possible here.

*I like the first one, simple, and conventional. If not possible my vote is for 3rd approach.

*As others have talked about, you can only pass the exact same type as ref/out parameters. So if your method by definition takes arbitrary references of object type, you have to declare even your variables as object locally. In the last approach, you can make the whole thing generic like by changing parameter type to Ref<T> from Ref<object> but that means your all local variables should also be one T.

*You can use a dictionary structure to cache Ref<T> to avoid recompiling same trees.

*The same implementation can be used to pass properties and variables as method arguments or return values by reference.

A: As others have said, you can't use params and out together. You have to construct an array at the call site.
This is because params tells the compiler to do the same thing - construct an array from the specified arguments. Unfortunately, when the compiler creates the array, you don't get a reference to it; even if the variable is written with a new array, you can never get to it.
I would guess you are asking for a thin metal ruler. What problem are you trying to solve with this mechanism?

A: You could pass an array by ref.
Edit:
This would of course change your calling method:
object[] array = new object[] { i, i2, sz, i3, sz2 };
c.Fill(ref array);

A: I think I might have an answer to your question; Consider the following code snippet, with the main "InvokeMemberMethod" function doing the job you ask for. I encountered the same problem as you and came up with this solution:
Note: the "isOutXX" parameter specifies if the preceeding parameter is an "out" parameter.
static object InvokeMemberMethod(object currentObject, string methodName, int argCount,
        ref object arg1, bool isOut1,
        ref object arg2, bool isOut2,
        ref object arg3, bool isOut3,
        ref object arg4, bool isOut4,
        ref object arg5, bool isOut5,
        ref object arg6, bool isOut6)
    {
        if (string.IsNullOrEmpty(methodName))
        {
            throw new ArgumentNullException("methodName");
        }

        if (currentObject == null)
        {
            throw new ArgumentNullException("currentObject");
        }

        Type[] argTypes = null;
        object[] args = null;
        if (argCount > 0)
        {
            argTypes = new Type[argCount];
            args = new object[argCount];

            argTypes[0] = arg1.GetType();
            if (isOut1)
            {
                argTypes[0] = arg1.GetType().MakeByRefType();
            }
            args[0] = arg1;

            if (argCount == 2)
            {
                argTypes[1] = arg2.GetType();
                if (isOut2)
                {
                    argTypes[1] = arg2.GetType().MakeByRefType();
                }
                args[1] = arg2;
            }

            if (argCount == 3)
            {
                argTypes[2] = arg3.GetType();
                if (isOut3)
                {
                    argTypes[2] = arg3.GetType().MakeByRefType();
                }
                args[2] = arg3;
            }

            if (argCount == 4)
            {
                argTypes[3] = arg4.GetType();
                if (isOut4)
                {
                    argTypes[3] = arg4.GetType().MakeByRefType();
                }
                args[3] = arg4;
            }

            if (argCount == 5)
            {
                argTypes[4] = arg5.GetType();
                if (isOut5)
                {
                    argTypes[4] = arg5.GetType().MakeByRefType();
                }
                args[4] = arg5;
            }

            if (argCount == 6)
            {
                argTypes[5] = arg6.GetType();
                if (isOut6)
                {
                    argTypes[5] = arg6.GetType().MakeByRefType();
                }
                args[5] = arg6;
            }
        }

        MethodInfo methodInfo = currentObject.GetType().GetMethod(methodName, argTypes);
        int retryCount = 0;
        object ret = null;
        bool success = false;
        do
        {
            try
            {
                //if (methodInfo is MethodInfo)
                {
                    Type targetType = currentObject.GetType();
                    ParameterInfo[] info = methodInfo.GetParameters();
                    ParameterModifier[] modifier = new ParameterModifier[] { new ParameterModifier(info.Length) };
                    int i = 0;
                    foreach (ParameterInfo paramInfo in info)
                    {
                        if (paramInfo.IsOut)
                        {
                            modifier[0][i] = true;
                        }
                        i++;
                    }
                    ret = targetType.InvokeMember(methodName, BindingFlags.InvokeMethod, null, currentObject, args,
                        modifier, null, null);
                    //ret = ((MethodInfo)methodInfo).Invoke(currentObject, args,);
                    success = true;
                }
                //else
                {
                    // log error
                }
            }
            catch (TimeoutException ex)
            {

            }
            catch (TargetInvocationException ex)
            {
                throw;
            }
            retryCount++;
        } while (!success && retryCount <= 1);

        if (argCount > 0)
        {
            if (isOut1)
            {
                arg1 = args[0];
            }

            if (argCount == 2)
            {
                if (isOut2)
                {
                    arg2 = args[1];
                }
            }

            if (argCount == 3)
            {
                if (isOut3)
                {
                    arg3 = args[2];
                }
            }

            if (argCount == 4)
            {
                if (isOut4)
                {
                    arg4 = args[3];
                }
            }

            if (argCount == 5)
            {
                if (isOut5)
                {
                    arg5 = args[4];
                }
            }

            if (argCount == 6)
            {
                if (isOut6)
                {
                    arg6 = args[5];
                }
            }
        }

        return ret;

    }

    public int OutTest(int x, int y)
    {
        return x + y;
    }

    public int OutTest(int x, out int y)
    {
        y = x + 1;
        return x+2;
    }

    static void Main(string[] args)
    {
        object x = 1, y = 0, z = 0;
        Program p =  new Program();
        InvokeMemberMethod(p, "OutTest", 2,
            ref x, false,
            ref y, true,
            ref z, false,
            ref z, false,
            ref z, false,
            ref z, false);
    }

A: I don't imagine the original questioner needs this answer 11 years later, but I found this old question when searching for an overlapping requirement... and thinking through the answer to this question made me realise why my related one wouldn't work very neatly.
For this question, it was implied that the caller needs to communicate the number of parameters and their types to the Fill(...) function - how else does it match up the types to the calling site?
The intended syntax at the calling site could be achieved like this:
public class SomeClass { }

public static void Fill(this SomeClass c, Type[] outputTypes, out object[] p)
{
  p = new object[outputTypes.Length];
  // TODO: implementation to fill array with values of the corresponding types.
}

// this overload can be removed if "fill" of an empty array is meaningless.
public static void Fill(this SomeClass c)
{
  c.Fill(new Type[0], out _);
}

public static void Fill<T>(this SomeClass c, out T r1)
{
  c.Fill(new[] { typeof(T) }, out var p);
  r1 = (T)p[0];
}

public static void Fill<T1, T2>(this SomeClass c, out T1 r1, out T2 r2)
{
  c.Fill(new[] { typeof(T1), typeof(T2) }, out var p);
  r1 = (T1)p[0];
  r2 = (T2)p[1];
}

// ... extend as required depending on maximum number of out parameters that might be needed
// in particular the 5-parameter version is included in this sample to make OP's sample code line work.

public static void Fill<T1, T2, T3, T4, T5>(this SomeClass c, out T1 r1, out T2 r2, out T3 r3, out T4 r4, out T5 r5)
{
  c.Fill(new[] { typeof(T1), typeof(T2), typeof(T3), typeof(T4), typeof(T5) }, out var p);
  r1 = (T1)p[0];
  r2 = (T2)p[1];
  r3 = (T3)p[2];
  r4 = (T4)p[3];
  r5 = (T5)p[4];
}

public static void someFunction()
{
  SomeClass c = new SomeClass();
  int i, i2, i3;
  string sz, sz2;
  // the line below is exactly as shown in question.
  c.Fill(out i, out i2, out sz, out i3, out sz2);
}


text:
Q: r animation, parametric curve I am using the animation package to plot the parametric curve for
$x=sin(t)$ and $y=sin(t)^2$ along with the circle tracing the curve using the following code:
require(animation)
x <- seq(-1,1,length=20)
y <- x^2
plot(x,y,type="l")
library(animation)
ani.record(reset=TRUE)
t <- seq(0,4*pi,by=pi/30)
for (i in 1:length(t)) {
    points(sin(t[i]),sin(t[i])^2,pch=19,cex=2)
    ani.record()
    plot(x,y,type="l")  # I have a question in this line
 }
 ani.replay()

It works (please copy and paste this code) but recording takes quite a time. This is a simple curve, but should I have wanted to
do the complicated one, it will take too much time to finish recording the animation.
One thing I may improve upon this is not to use the 2nd plot function to redraw the parobola to get rid of the circle appear in the previous plot.
Is there anything I can make it better?

A: The base R package grDevices has two functions that allows for the saving and playback of a plot, designed for situations like this:

*

*recordPlot()

*replayPlot()
A somewhat subjective test on my machine seems to indicate that it is faster than replotting the entire plot:
require(animation)
x <- seq(-1,1,length=20)
y <- x^2
plot(x,y,type="l")
oopts <- ani.opts(interval=0.25)
p <- recordPlot()   # <== Record plot here =============
ani.record(reset=TRUE)
t <- seq(0,4*pi,by=pi/30)

for (i in 1:length(t)) {
  replayPlot(p)     # <== Replay plot here =============
  points(sin(t[i]),sin(t[i])^2,pch=19,cex=2)
}
ani.replay()


text:
Q: Mapping multiple IDs using R The idea is as follows. Every patient has a unique patient id, which we call hidenic_id. However this patient may be admitted to the hospital multiple times. On the other hand every entry has unique emtek_id.
Patient 110380 was admitted to the hospital 4/14/2001 11:08 and then transferred through the hospital and discharged on 4/24/2001 18:16. Now this patient again admitted on  5/11/2001 23:24 because he has different emtek_id now. He is discharged from the hospital on 5/25/2001 16:26. So you need to assign correct emtek_ids by checking the dates. If the date in the combined file is within the admission and discharge time period (or very close like 24 hours) we can assign that emtek_id.
How can I assign different emtek_IDs to entries with hidenic_id and admit time?

A: I had a couple ideas worth sharing.
First, make emtek_id from hidenic_id and date. Second, make the emtek_id logical for parsing, e.g., emtek_id@dataTime. Third, make the database a global vector. Depending on memory limits, there has to be a faster way than this, but it might give you a few ideas.
The main problems are handling NA values and incorrect hidenic_id, validating hidenic_id(s), and padding the IDs if you don't characters leading (which would be a quick fix). Lastly, how do you want to handle input that's incorrect but not NA/null? For instance, say you input "ID" instead of "ID12345", do you want to treat that as a call to assign a new value or prompt for a correct input XOR NA value? I will assume you only feed it correct ID inputs or NA values, but this is my trivializing assumption.
Here's some pseudo-code to start the idea. You choose how to store the data (eg. csv file then use data.table::fread()):
#this file's name is "make.hidenic_id.R"
library(data.table)
library(stringr)
set.seed(101)
#one might one a backup written, perhaps conditionally updating it every hour or so.
database.hidenic_id <<-data.table::fread("database.filename.hidenic_id.csv")
database.emtek_id   <<-data.table::fread("database.filename.emtek_id.csv")

make.hidenic_Id = function(in.hidenic_id){
            if(is.na(in.hidenic_id) | !(in.hidenic_id %in% database.hidenic_id)){
                new.hidenic_id=NA
                #conditionally make new hidenic_id
                while( new.hidenic_id %in% database.hidenic_id){
                    new.hidenic_id = paste0("ID",str_pad(sample.int(99999, 1),5,pad=0))
                }
                #make new emtek_id
                new.emtek_id <- paste0(new.hidenic_id,  sep="@",  str_sub(Sys.time(),1,16))

                #update databases; e.g., c(database.emtek_id, new.emtek_id)
                database.hidenic_id <<- c(database.hidenic_id, new.hidenic_id)
                database.emtek_id   <<- c(database.emtek_id,   new.emtek_id)
            }else{
                new.emtek_id <- paste0(in.hidenic_id,  sep="@",  str_sub(Sys.time(),1,16))
              # update database.emtek_id
              database.emtek_id   <<- c(database.emtek_id,   new.emtek_id)
            }
            return(new.emtek_id)
}
temp = readline(prompt="Enter hidenic_id OR type \"NA\": ")
data.table::fwrite(database.emtek_id,  "database.filename.emtek_id.csv")
data.table::fwrite(database.hidenic_id,"database.filename.hidenic_id.csv")

and call the file with
source("make.hidenic_id.R")

There are a lot of "good-practice" things I don't do to manage poor input data or optimizing searching, but this is a strong start. Some other good-practice would be to have longer integers or a different leading string, but you never said we could use input value to make the IDs.
You could say this was inspired by the census since everything is just one massive string per geographic ID variable.

A: I was intrested in your problem so I created some mock data and tried to solve the problem but I ran into some confusion myself and then posted my question, which I think is what you are asking but more general.  You can see the response here: How can I tell if a time point exists between a set of before and after times
My post generates what I believe is what you are starting with and the checked answer is what I believe you are looking for. The full code is below. You will need to install zoo and IRanges.
Also, I did this in version 2.15.3.  IRanges did not install properly in 3.0.0.
## package installation
source("http://bioconductor.org/biocLite.R")
  biocLite("IRanges")
install.packages("zoo")

## generate the emtek and hidenic file data
library(zoo)
date_string <- paste("2001", sample(12, 10, 3), sample(28,10), sep = "-")
time_string <- c("23:03:20", "22:29:56", "01:03:30", "18:21:03", "16:56:26",
                 "23:03:20", "22:29:56", "01:03:30", "18:21:03", "16:56:26")

entry_emtek <- strptime(paste(date_string, time_string), "%Y-%m-%d %H:%M:%S")
entry_emtek <- entry_emtek[order(entry_emtek)]
exit_emtek <- entry_emtek + 3600 * 24
emtek_file <- data.frame(emtek_id = 1:10, entry_emtek, exit_emtek)

hidenic_id <- 110380:110479
date_string <- paste("2001", sample(12, 100, replace = TRUE), sample(28,100, replace = T), sep = "-")
time_string <- rep(c("23:03:20", "22:29:56", "01:03:30", "18:21:03", "16:56:26",
                 "23:03:20", "22:29:56", "01:03:30", "18:21:03", "16:56:26"),10)
hidenic_time <- strptime(paste(date_string, time_string), "%Y-%m-%d %H:%M:%S")
hidenic_time <- hidenic_time[order(hidenic_time)]
hidenic_file <- data.frame(hidenic_id, hidenic_time)

## Find the intersection of emtek and hidenic times.  This part was done by user: agstudy
library(IRanges)
## create a time intervals
subject <- IRanges(as.numeric(emtek_file$entry_emtek),
        as.numeric(emtek_file$exit_emtek))
## create a time intervals (start=end here)
query <- IRanges(as.numeric(hidenic_file$hidenic_time),
        as.numeric(hidenic_file$hidenic_time))
## find overlaps and extract rows (both time point and intervals)
emt.ids <- subjectHits(findOverlaps(query,subject))
hid.ids <- queryHits(findOverlaps(query,subject))
cbind(hidenic_file[hid.ids,],emtek_file[emt.ids,])


text:
Q: Know the number of times this word appears: PYTHON 2.7 I have a file.txt with about 1,000 lines that look like this:
--- Adding sections to FwLogger: [],2020-01-13 16:09:18,2020-01-13 16:09:22

--- Clearing all sections from FwLogger,2020-01-13 16:09:17,2020-01-13 16:09:22
--- (1/0) The value was discarded due to being too separated from previous value
--- (1/0) ContinueBoot@b7630fd  Rebooting device due to capabilities request freeze

And I would need to know how many times the word  "FwLogger" appears ( in number ).

A: There are definitely more elegant ways to do it, but in my version you replace the delimiters manually:
with open('test.txt') as file:
    for line in (line.strip() for line in file):
       #here you replace all possible delimiters in your file with a space to split afterwards according to the spaces
        c=line.replace(","," ").replace(";"," ").replace("@"," ").replace(":"," ")
        for word in c.split(" "):
            if word == "FwLogger":
#                print(line)
                counter= counter+1
                print(counter)

A: read in your txt file and use the string find method like below
loop
istart = str.find(sub, istart)
I= I + 1.
end loop
I start is the position where the string you're looking for was last found. before starting your loop assign istart = 1
each time one is found increment a counter
i.e. I= I + 1


text:
Q: Using hibernate validator JodaTime bean validation constraints in JBoss We have an enterprise application that uses the Joda DateTime library. The application is deployed into a JBoss 7.2.0 Alpha1 Container. Some classes in our domain model have @Past annotations on fields of type DateTime. In order to validate these constraints we'd like to use the constraint validators provided by hibernate-validator. Therefore we added a dependency 'org.hibernate.validator' to the MANIFEST.MF of our ear file. We are using version 2.0 of the Joda library. Therefore we have packaged the joda-time-2.0.jar file in our ear. We are not using the version 1.6.2 that is available as a module of JBoss 7
When validating an object with a DateTime field following exception is thrown:
10:51:41,140 ERROR [org.acme.GlobalExceptionHandler] (EJB default - 10) Exception caught by global exception handler: javax.validation.UnexpectedTypeException: No validator could be found for type: org.joda.time.DateTime
at org.hibernate.validator.engine.ConstraintTree.verifyResolveWasUnique(ConstraintTree.java:383) [hibernate-validator-4.2.0.Final.jar:4.2.0.Final]
at org.hibernate.validator.engine.ConstraintTree.findMatchingValidatorClass(ConstraintTree.java:364) [hibernate-validator-4.2.0.Final.jar:4.2.0.Final]
at org.hibernate.validator.engine.ConstraintTree.getInitializedValidator(ConstraintTree.java:313) [hibernate-validator-4.2.0.Final.jar:4.2.0.Final]
at org.hibernate.validator.engine.ConstraintTree.validateConstraints(ConstraintTree.java:144) [hibernate-validator-4.2.0.Final.jar:4.2.0.Final]
at org.hibernate.validator.engine.ConstraintTree.validateConstraints(ConstraintTree.java:117) [hibernate-validator-4.2.0.Final.jar:4.2.0.Final]
at org.hibernate.validator.metadata.MetaConstraint.validateConstraint(MetaConstraint.java:84) [hibernate-validator-4.2.0.Final.jar:4.2.0.Final]
at org.hibernate.validator.engine.ValidatorImpl.validateConstraint(ValidatorImpl.java:452) [hibernate-validator-4.2.0.Final.jar:4.2.0.Final]

After some debugging we detected that the call to 'TypeUtils.isAssignable( validatorType, type )' in 'ConstraintTree.findSuitableValidatorTypes' fails since the available validator types are taken from the Joda library that has been shipped with JBoss instead of the Joda library that is packaged in our ear file.
I guess we are doing something wrong regarding classloading. Can anybody give me a hint?

A: Have you tried adding a jboss-deployment-structure.xml to your ear file? This way you should be able to exclude the Joda time module:
<?xml version="1.0" encoding="UTF-8"?>
<jboss-deployment-structure>
    <deployment>
        <exclusions>
            <module name="org.joda.time"/>
        </exclusions>
    </deployment>
</jboss-deployment-structure>

See also https://docs.jboss.org/author/display/AS7/Class+Loading+in+AS7

A: Following Hardy's idea I solved my problem creating a jboss-deployment-structure.xml in my application's WEB-INF folder containing this:
<?xml version="1.0" encoding="UTF-8"?>
<jboss-deployment-structure>
    <deployment>
        <exclusions>
            <module name="org.hibernate.validator" />
        </exclusions>
    </deployment>
</jboss-deployment-structure>

In stead of excluding org.joda.time I excluded org.hibernate.validator. I hope this works for you too.


text:
Q: SQLAlchemy Example Projects Are there any good example projects which uses SQLAlchemy (with Python Classes) that I can look into? (which has at least some basic database operations - CRUD)
I believe that, it is a good way to learn any programming language by looking into someone's code.
Thanks!

A: My Flask-Security-Admin-Example project might help. It uses SQLAlchemy ORM in a Python Flask web application that also integrates Flask-Security and Flask-Admin.
Also, although it's not a project, the SQLAlchemy ORM tutorial is quite good, and walks you through writing the code you would need in a SQLAlchemy project.
Note that both of the above examples use SQLAlchemy ORM. If you don't want an object relational mapper, you can use SQLAlchemy Core. I don't have a project that illustrates that, though.

A: What kind of environment are you looking to work with on top of SQLAlchemy?
Most likely, if you are using a popular web framework like django, Flask or Pylons, you can find many  examples and tutorials specific to that framework that include SQLAlchemy.
This will boost your knowledge both with SQLAlchemy and whatever else it is you are working with.
Chances are, you won't find any good project examples in 'just' SQLAlchemy as it essentially a tool.


text:
Q: Is Win2D yet available in C++/WinRT? I need to use win2D in my cppwinrt project. Using the Win2D sample file as a model I've tried to mimic its setup, putting in the package file for win2d from that project, duplicating the custom build step, but I can't get it to compile. I remember some talk about Win2D being added soon to the standard cppwinrt headers so that it could be accessed like others of these wonderful cppwinrt interfaces. Is this something that might happen soon? Or does anyone have some really specific instructions for using Win2D in the current Visual Studio 2017 environment? I'm in the Insider preview program but haven't seen anything come up. Thanks.

A: Once you have downloaded Win2D and assuming you have the latest RS4 Windows SDK installed, you can simply use cppwinrt to generate the Win2D headers for consumption:
cppwinrt -in lib\uap10.0\Microsoft.Graphics.Canvas.winmd -ref sdk

This will generate a winrt folder that contains the headers that you need to include in order to use Win2D. You will then need to add the parent folder to your include paths and ensure that the Win2D DLL is copied to your package or build output folder.

A: As of the recent update, using Newget to install Win2D into a C++/WinRT project will automatically generate the headers and install them in "GeneratedFiles\winrt\"


text:
Q: Why i can't delete my array pointer when i declared it with the 'new' keyword I don't know if it is the correct title but can someone explain to me why this is happening?
class asd {
public:
    asd() {
        const char* bufferX = new char[16];
        const char* bufferY = new char[16];
        const char Player = 'O';
    }

    ~asd() {
        delete[] bufferX;
        delete[] bufferY;
    }
};

I'm getting this error: identifier "bufferY" is undefined

A: Because your pointers (bufferX, bufferY) are local to the asd constructor.  This means that they are not visible within the destructor, or anywhere outside the constructor.
If you must use raw pointers, you probably want to make the pointers class members.  But it's generally a bad idea to work with raw pointers in C++.  Consider using std::vector or std::array.
If you must to use char[], then consider using C++14 smart pointers such as std::unique_ptr<char[]>.  Then you don't need to worry about calling delete.  The memory will be freed automatically as soon as it no longer has any references.
Example:
std::unique_ptr<char[]> bufferX(new char[16]);

Then we asd gets destroyed, this memory will be freed automatically.

A: Your bufferX and bufferY variables are not declared as class members but rather as variables in the asd() function/constructor and they are deleted when that function exits.
You should declare them as class members if you want to retain them.
Also, please do not post code as images, it makes it harder to help you.
class asd
{
    public:
    const char *bufferX, *bufferY;
    const char Player = '0';

    asd()
    {
        bufferX= new char[16];
        bufferY= new char[16];
    }

    ~asd()
    {
        delete[] bufferX;
        delete[] bufferY;
    }
};


text:
Q: JAXB Custom Binding for Untyped Element? I have a very large and complex XSD for a SOAP service which I do not control.  There are several elements which always contain string data which are not typed. Typically these are very deeply-nested elements.
For example
...
  <xs:complexType>
      <xs:sequence>
          <xs:element name="foo"/>
          <xs:element name="bar"/>
      </xs:sequence>
  </xs:complexType>
...

Is there a way to tell JAXB to always bind untyped elements (such as foo and bar above) to java.lang.String?
I understand that I can call out these exceptions individually using an XPath query string, but is there a one liner for this?

A: In an external binding file an XPath expression like
//xs:element[not(@type)][not(xs:simpleType)][not(xs:complexType)]

would match any such element (assuming XJC has full XPath support rather than just a subset of the language).


text:
Q: TypeError: 'NoneType' object is not subscriptable for res object type # ROW 4
start_date = DateEntry(start_frame, selectmode='day', year=2020, month=11, day=22)
start_date.grid(row=4, column=0, sticky=W, padx=10, pady=10)

end_date = DateEntry(start_frame, selectmode='day', year=2020, month=11, day=22)
end_date.grid(row=4, column=1, sticky=W, padx=10, pady=10)

I keep gettin the erorr for Nonetype, what am i doing wrong? the
databse connected is mongoDB for GridFS below for res object

 res = (test.find_one({"_id": 1}))['models']
    clicked.set(res[0])

res = (test.find_one({"_id": 1}))['models'] TypeError: 'NoneType' object is not subscriptable

drop = OptionMenu(start_frame, clicked, *res)
drop.grid(row=4, column=2, sticky=W, padx=10, pady=10)


text:
Q: Ansible: build a Mac Adresse from a string Ansible Noob here.
I have a string and I need to build a specific MAC format.

*

*string i got: 1a2b3c4e5f6g

*string i need: 1a:2b:3c:4e:5f:6g

I have a method that works but maybe there is a easier way.
I write the string in a tempfile and start a python script and save the output in a variable.
python code in my script that builds the format.
mac="%s:%s:%s:%s:%s:%s" %(mac\[0:2\],mac\[2:4\],mac\[4:6\],mac\[6:8\],mac\[8:10\],mac\[10:12\])

Is there a way where i can do this in the playbook and not with tempfile and python script ?

A: You can do pretty much the same thing in your Ansible playbook. Because there is no tuple filter in jinja templates, it's easier to use the string .format(...) method rather than % style formatting:
---
- hosts: localhost
  gather_facts: false

  vars:
    macaddr: "5281a421770f"

  tasks:
    - set_fact:
        modified_macaddr: "{{ '{}{}:{}{}:{}{}:{}{}:{}{}:{}{}'.format(*macaddr) }}"

    - debug:
        var: modified_macaddr

This will output:
TASK [debug] *************************************************************************
ok: [localhost] => {
    "modified_macaddr": "52:81:a4:21:77:0f"
}

A: Use hwaddr filter. For example
  vars:
    macaddress: '1a2b3c4d5e6f'
  tasks:
    - debug:
        msg: "{{ macaddress|hwaddr('unix') }}"

gives
msg: 1a:2b:3c:4d:5e:6f


text:
Q: Show() and hidden table rows I have a table with some hidden rows and a clickable button that reveals those hidden rows.
The problem is that, when I use the link, the rows get revealed but the body doesn't update its height. (But it does update when I open the chrome console and close it)
css:
table tr.hide-row {
   display:none;
}

jquery:
$(document).on('click', 'a.openallrows', function(e) {
    $('.hide-row').show();
    e.preventDefault();
});

html

            visible

            This is hidden
            -
            --
            ---

I have a lot of hidden rows. And when they all get shown, they overlap the page footer and that's not what I was going for..
Update!

     table is inside here

The table is inside a grid which has position absolute! The position is automatically added by BlocksIt.js

A: try this css code
table{
height:auto !important;
}

A: What happens if you change the containing div as such:

     table is inside here

A: Ive got a cool idea.
You could easily just put a container around it with a height and width of 100% and then grab its height and the height of the parent element to boxes.
Everytime a new box is opened, compare it to the height of the container, and add to the container's height if the margin between the two becomes to small.
Ive made a fiddle.
I used an increment code on the height. Imagine the red box is your "hide-row" class.
In this situation(because Im pressed for time,) I have pretended to add on 40px(which will represent the height of a td.) Everytime it increases, the container increases IF the maximum margin would be exceeded in the following add. So I incremented the height of the container. I recommend your container contain the entire page.
$(".higher").click(function(){
    var allheight = $(".all").height() - 80;
    var red = $(".higher").height();
    $(".higher").css("height", "+=40px");
    if(red > allheight){
        $(".all").css("height", "+=40px");
    }
});

Click Here to see it.
You could place as many block columns in this section as needed.

A: The block was overlapping the footer because it didn't update its height value.
Luckily I was able to find a different script that lays out the blocks. It has a function to call a refresh to itself so it doesn't overlap other elements.
If someone ever has a similar problem I suggest you try out
https://github.com/GBKS/Wookmark-jQuery it has all the same functions as BlocksIt.js and even more.
This was the function that I found very necessary for my project that Wookmark has $('.grid').trigger('refreshWookmark'); it refreshes the block.


text:
Q: What is the tightest asymptotic growth rate I have solved all of them however i have been told there are some mistakes, can somebody please help me
n^4 - 10^3 n^3 + n^2 + 4n + 10^6 =  O(n^4)
10^5 n^3 + 10^n =   O(10^n)
10 n^2 + n log n + 30 √n = O(n^2)
25^n =  O(1)
n^2+ n log n + 7 n =    O(n^2)
(n^3 + 10) (n log n+ 1) / 3 = O(n^4  log n)
20 n^10 + 4^n   = O(4^n)
n^2 log n^3 + 10 n^2    = O(n^2  log n)
10^20 = O(1)
n^2 log (6^2)n =    O(n^2  log n)
n log(2n) = O(n log n)
30 n + 100 n log n + 10 =   O(n log n)
(n+√n) log n^3  = O(n+√n log n)
n (n + 1) + log log n = O(n^2)
4n log 5^(n+1)  = O(n log 5^n)
3^(n+4) =   O(3^n)
n^2 log n^2 + 100 n^3 = O(n^3)
(n log n) / (n + 10) =  O(n^2 log n)
5n + 8 n log(n) + 10n^2 =   O(n^2)
2n^3 + 2n^4 + 2^n + n^10 =  O(2^n)

A: Hints:

*

*if you have n on the left, you should have it on the right

*there should not be any + operations on the right

*log(x^y) can be simplified

A: Most of your answers look correct, but you have 25^n = O(1) which looks wrong (unless it's 0.25^n), and also you have (n log n) / (n + 10) = O(n^2 log n) which does not look like the tightest possible bound (I'm assuming you want the tightest possible upper bound function). Also you should never have to add functions in your big-O, unless your original function is taking the sum or max of two functions or something and the two functions have cris-crossing different growth rates at different values of n as n goes to infinity. And that very rarely happens.


text:
Q: wordpress paginate_links url my code looks like this:
paginate_links(
  array(
   'next_text' => __('>'),
   'prev_text' => __('<'),
   'base' => @add_query_arg('page', '%#%'),
   'format' => '?page=%#%&a='.$a,
   'total' => ceil($count/$per_page),
   'current' => $page)
)

Everything works perfectly but if I click on for example second page my url goes to www.domain.com/something/2/?a=5 instead of www.domain.com/something/?page=2&a=5
Is it possible to change it into www.domain.com/something/?page=2&a=5?

A: It is because you use permalinks :

format (string) (optional) Used for Pagination structure. The default
  value is '?page=%#%', If using pretty permalinks this would be
  '/page/%#%', where the '%#%' is replaced by the page number. Default:
  '?page=%#%'

Just rename the var page into something else


text:
Q: How Can i get my direct messages in slack api? How Can i get my direct messages in slack api ?
i have try these methods search.messages etc and this link
https://slack.com/api/search.messages but can not show result.

A: To get all your private messages:

*

*Get the list of direct message channels you are a member of with conversations.list by setting the types property to im

*Do a loop over the list of all channel and query each with conversations.history to get all messages.
Make sure to use an access token authorized by yourself to see all private channels.


text:
Q: Firebase firestore function deploy failed due to unexpected token "." optional chaining I am trying to deploy node.js trigger and functions with code that contains optional chaining. I previously deployed this code without error, but now am facing this error:
return this.roles?.includes(role.toString()) ? true : false;
                  ^

SyntaxError: Unexpected token '.'
    at wrapSafe (internal/modules/cjs/loader.js:915:16)
    at Module._compile (internal/modules/cjs/loader.js:963:27)
    at Object.Module._extensions..js (internal/modules/cjs/loader.js:1027:10)
    at Module.load (internal/modules/cjs/loader.js:863:32)
    at Function.Module._load (internal/modules/cjs/loader.js:708:14)
    at Module.require (internal/modules/cjs/loader.js:887:19)
    at require (internal/modules/cjs/helpers.js:74:18)
    at Object.<anonymous> (/workspace/diwimaModelWeb/lib/network/index.js:13:14)
    at Module._compile (internal/modules/cjs/loader.js:999:30)
    at Object.Module._extensions..js (internal/modules/cjs/loader.js:1027:10)

I use typescript and the build target as configured in tsconfig.ts is "es2020". I could go through the code and replace all the optional chaining with null cheking, but I'd rather not because I previously deployed it without problems.

A: For anyone having this issue. I fixed it during writing this question myself, I noticed that I was using different node and npm verisons for building and uploading, nvm is tricky like that :D. Also I selected "es2017" in tsconfig. Not 100% sure what fixed it.

A: I had the same issue and it was indeed the mismatching node version.
(Not npm though, that shouldn't matter).
Steps for resolving:

*

*Check your local node version: nvm --version
(in case you installed manually from their website I'd suggest starting to use nvm now :)

*Make sure the same is set in your package.json,
e.g. "engines": {"node": "14"},

*Set your ES version in your tsconfig.json as needed.
e.g. "target": "ES2020", it should be compatible with your node version.
A list of ES versions' feature highlights here and the list of node versions supported by firebase here.
Optionally, if you still have issues:

*Make sure everything mentioned so far is in the functions folder of your firebase app (and for example you didn't install dependencies in the root folder by accident).

*Check and update firebase-tools and firebase packages if needed. e.g. npm install --save firebase-functions

*Delete package-lock.json then build + deploy again (npm run lint && tsc and firebase deploy --only functions). Chances are some of your dependency installations got messed up, e.g. you didn't --save them (at least I did that while trying to solve the initial problem in the previous step).


text:
Q: Invalid data from GPS (Ublox LEA-6T), would like it to be valid I have recently started a quadcopter project where my end goal is to fly a quad with DGPS. I am just in the beginning stages of this goal and have recently purchased a GPS but am having problems with the data I receive from it.
At present I have a ublox LEA-6T that I hope to mount on my drone. However, the GPS is not giving me valid data; it is finding satellites in view yet provides no fix. Here is an example of what I am receiving:
$GPVTG,,,,,,,,,N*30
$GPGGA,,,,,,0,00,99.99,,,,,,*48
$GPGS99,,,,,,*48
$GPGSA,A,1,,,,,,,,,,,,,99.99,99.99,99.99*30
$GPGSV,3,1,12,01,,,22,02,,
$GPRMC,,V,,,,,,,,,,N*53
$GPVTG,,,,,,,,,N*30
$GPGGA,,,,,,0,00,99.99,,,,,,*48

Can anyone offer any advice on how to get valid data? I have downloaded u-center but am unsure what to change to get a fix.
I would greatly appreciate any help!

A: This, that, is the return of a gps that does not have a fix.
There can be a number a reasons.  The two main reasons are:
Time to first fix, or
No signal.  (Location or antenna problems.)
If giving it time doesn't rectify the problem consider location or hardware issues.
This is an example...https://superuser.com/questions/736939/cgps-gps-timeout-sierra-wireless

Turns out the problem was that the antenna that was purchased was only
  half of a GPS antenna.


text:
Q: Wordpress: Email Linking Issue I have got quite a weird issue, on my website.
On the top right, there is an email address and a phone number.
The email address is set in the general settings in the dashboard.
The problem, is that when I rollover the email address, only the tip of the "m" in .com becomes active. It is as if there is an invisible object lying above the email address.
What I need, is for the whole email address to be active, when the user rolls over.
Any help would be appreciated.
Thanks in advance

A: The element
<header class="big box unit whole">

Has it's z-index set to 770. You should reduce this, or increase the z-index to 771 on the
<div class="header-info-block">

element.
You'll need to do some digging into the sites css / theme files to do this.


text:
Q: how to get json data one by one This is my script in getting the json file:
$.getJSON(jsonURL, function(json)
    {
        var imgFloorList= "";

        $.each(json.floorTile, function(){
            imgFloorList += '';
        });
        $('.img-container').append(imgFloorList);
    })

I want to get one image in json file and put it in the div img-container. What should I do so i can only get one image and not all the images I have in the json file?

A: Below is a complete example, you can have a look how I've done it and change your solution accordingly
Controller:
public class TestController : Controller
{
    public ActionResult Index()
    {
        return View();
    }

    public JsonResult GetProducts()
    {
        var p1 = new Product { name = "fruit", img_src = "http://kingofwallpapers.com/fruit/fruit-005.jpg" };
        var p2 = new Product { name = "vegetables", img_src = "http://blogs.extension.iastate.edu/foodsavings/files/2014/06/vegetables-variety.jpg" };
        return Json(new List<Product> { p1, p2 }, JsonRequestBehavior.AllowGet);
    }
}

public class Product
{
    public string name { get; set; }
    public string img_src { get; set; }
}

View:


text:
Q: How to stop Cisco Services Application objects from stacking I am working with Cisco phones and i want to send them alert messages.
I do this by posting the following to the phone
"<CiscoIPPhoneExecute><ExecuteItem URL=\"Play:chime.raw\"/><ExecuteItem Priority=\"0\" URL=MY GET MESSAGE URL></CiscoIPPhoneExecute>";

My HTTP server then responds with a CiscoIPPhoneText xml object.
This is all working fine, however it is my desire not to have the messages stacking up on top of each other so that the user does not have to dismiss each message individually. I wish only for the most recent message to remain active on the phone so regardless of how many messages the phone has received the user can dismiss one and be returned home.
At first i included an init:services uri in the post but this caused a conflict with another service and my CiscoIPPhoneText was being dismissed immediately by the other service (i have no control over the other service).
Is there a way to return the phone to the home screen before an CiscoIPPhoneText is displayed or any other way to ensure that only one message is active?
Thanks

A: I found the answer
App:Close:0 is an internal URI which closes the current (or specified) application.
All my messages have the same AppId so when this URI is invoked all my messages close


text:
Q: ecs.runTask not executing in Lambda I have a lambda function that is supposed to start an ecs task when invoked. It gets all the way down to the "Starting execution..." log then it logs "done.". It seems to just skip right over ecs.runTask(). I have tried getting the returned json output by setting the runtask function to a variable, but that has not helped. I have also tried changing some of my parameters and that has not worked as well.
const AWS = require('aws-sdk');
var ecs = new AWS.ECS()

exports.handler = async (event) => {
var params = {
  cluster: "ec2-cluster",
  enableECSManagedTags: true,
  launchType: "FARGATE",
  count: 1,
  platformVersion: 'LATEST',
  networkConfiguration: {
    awsvpcConfiguration: {
        assignPublicIp: "ENABLED",
        securityGroups: [ "sg" ],
        subnets: [ "subnet" ]
    }
  },
  startedBy: "testLambda",
  taskDefinition: "definition"
}

console.log("Starting execution...");

ecs.runTask(params, function(err, data) {
  console.log(err, data)
});
// console.log(myReturn)
console.log("done.")

}
When I run this locally everything works great. When I run this in lambda however it does not start my task.

A: In your case, you will need to add Promise to ecs.runTask(). In the AWS Lambda documentation, they mentioned that we have to

Make sure that any background processes or callbacks in your code are complete before the code exits.

meaning that we need to await for the ecs.runTask() process to resolve. Here is an example of how we can apply async/await on aws-sdk. From the references above, the way to make your code work would be:
const AWS = require('aws-sdk');
var ecs = new AWS.ECS()

exports.handler = async (event) => {
var params = {
  cluster: "ec2-cluster",
  enableECSManagedTags: true,
  launchType: "FARGATE",
  count: 1,
  platformVersion: 'LATEST',
  networkConfiguration: {
    awsvpcConfiguration: {
        assignPublicIp: "ENABLED",
        securityGroups: [ "sg" ],
        subnets: [ "subnet" ]
    }
  },
  startedBy: "testLambda",
  taskDefinition: "definition"
}

console.log("Starting execution...");

// Added promise here
await ecs.runTask(params).promise();
// console.log(myReturn)
console.log("done.")

This is a common mistake that we might make when we first get into Lambda, especially when we try to make our Lambda functions work with some other AWS services via aws-sdk.


text:
Q: Why does a const reference to volatile int need a static_cast? Given the following code:
struct Foo {
    volatile int i;
};

const int& bar = foo.i;

I get:
error: invalid initialization of reference of type 'const int&' from expression of type 'volatile int'

Unless I provide a static_cast<volatile int>.

A: "Volatility" of types in C++ works in pretty much exactly the same way as "const-ness" -- that is, an object that is volatile cannot be assigned to a non-volatile reference, in just the same way that
const int i = 3;
int& j = i; // won't work

Similarly, only methods marked volatile can be called on a volatile object:
struct S
{
    void do_something() volatile {}
    void do_something_else() {}
};

volatile S s;
s.do_something(); // fine
s.do_something_else(); // won't work

Methods can be overloaded by "volatility", in the same way they can be overloaded by const-ness.
In C++ standardese, these things are known as cv-qualifiers, to emphasise that they work in exactly the same way. (C99 adds a third that works in the same way, restrict, available as an extension in some C++ compilers). You can change cv qualifiers using const_cast<> -- the more powerful static_cast<> isn't required.
EDIT:
Just to make clear, a type can have both const and volatile modifiers at the same time, giving a total of four possibilities:
int i;
const int j;
volatile int k;
const volatile int l;

A: As with const, a volatile object can only be referred to by a volatile reference. Otherwise, the compiler has no way of knowing that accesses to the object via the reference need to be volatile.
volatile const int& bar = foo.i;
^^^^^^^^

Unless I provide a static_cast<volatile int>

It's rarely a good idea to silence a compiler error by adding casts. This doesn't give you a reference to foo.i, but to a separate copy of it.
If you are doing something really strange that requires a non-volatile reference to a volatile object, you'd need const_cast to remove the qualifer:
const int& weird = const_cast<int&>(foo.i);


text:
Q: passing counting argument into a recursive python function I successfully solved an algorithm question to serialize and deserialize binary tree.
class Codec:
    def __init__(self):
        self.i=0
    def serialize(self, root):
        store=[]
        def preorder(node):
            if not node:
                store.append("N")
                return
            store.append(str(node.val))
            preorder(node.left)
            preorder(node.right)
        preorder(root)
        return ",".join(store)

    # serialized data is passed here as "data" argument
    def deserialize(self, data):
        values=data.split(",")
        def helper():
            if values[self.i]=="N":
                self.i+=1
                return
            root=TreeNode(int(values[self.i]))
            self.i+=1
            root.left=helper()
            root.right=helper()
            return root
        return helper()

to solve the deserialize function, I created a top-level state variable self.i. Instead, I want to pass i to the helper function but I cannot figure it out. I tried to code like this with local variable:
    def deserialize(self, data):
        values=data.split(",")
        def helper(i):
            if values[i]=="N":
                i+=1
                return
            root=TreeNode(int(values[i]))
            i+=1
            root.left=helper(i)
            # i think issue is here.
            # Because i is modified inside root.left=helper(i)
            # so somehow I need to keep track of this modification
            root.right=helper(i)
            return root
        return helper(0)

A: Instead of using an instance attribute (i), you could use a local variable i like you tried, but then not passing it as argument to helper, but referencing it as a nonlocal name. But I would not advise that. Instead create an iterator over the given values. Then you can call next on it to get the next value.
Once you got rid of the ugly instance attribute, you no longer need instances at all, and I wonder why you would need a class Codec at all. It you really want to keep it, then create those two functions as static methods as it doesn't make sense to ever need to create an instance of Codec:
Here is complete code with a run on a sample tree:
class TreeNode:
    def __init__(self, val):
        self.val = val
        self.left = self.right = None

    def add(self, val):
        if val < self.val:
            if self.left:
                self.left.add(val)
            else:
                self.left = TreeNode(val)
        else:
            if self.right:
                self.right.add(val)
            else:
                self.right = TreeNode(val)

    def print(self, tab=""):
        if self.right:
            self.right.print(tab +  "  ")
        print(tab, self.val)
        if self.left:
            self.left.print(tab +  "  ")

    @staticmethod
    def of(*values):
        if values:
            root = TreeNode(values[0])
            for val in values[1:]:
                root.add(val)
            return root

class Codec:
    @staticmethod
    def serialize(root):
        store=[]
        def preorder(node):
            if not node:
                store.append("N")
                return
            store.append(str(node.val))
            preorder(node.left)
            preorder(node.right)
        preorder(root)
        return ",".join(store)

    @staticmethod
    def deserialize(data):
        values = iter(data.split(","))

        def helper():
            val = next(values)
            if val=="N":
                return
            root = TreeNode(int(val))
            root.left = helper()
            root.right = helper()
            return root
        return helper()

tree = TreeNode.of(4,2,6,1,3,5,7)
tree.print()
s = Codec.serialize(tree)
print(s)
root = Codec.deserialize(s)
root.print()


text:
Q: Make matched letters highlighted in autocomplete in javascript/jquery I have a set of airport names along with their codes to be displayed in autocomplete.
E.g. Amsterdem (AMS)
I want to match the value entered in the search box,I want to display the matched airport name as well as airportcode bold as follows.
if I enter ams in search box,i want to highlight 'Ams'terdem ('AMS') in my autocomplete.
I have written a code as below:
function () {
    var oldFn = $.ui.autocomplete.prototype._renderItem;
    $.ui.autocomplete.prototype._renderItem = function( ul, item) {
        var re = new RegExp("^" + this.term, "i") ;
        var t = item.label.replace(re,"" + this.term + "");
        return $( "

" )
            .data( "item.autocomplete", item )
            .append( "" + t + "" )
            .appendTo( ul );
    };
};

it results as 'Ams'terdem (AMS) instead of 'Ams'terdem (AMS).
Note:Amsterdem (AMS) is a single term
Please advice.

A: you have to change
var re = new RegExp("^" + this.term, "i") ;

with this code
var re = new RegExp(this.term, "ig") ;

this will replace all instance in your string
"^" denotes start of string, and "g" in regular expression works on all instance
here is working example
replace your code with this one
function () {
var oldFn = $.ui.autocomplete.prototype._renderItem;
$.ui.autocomplete.prototype._renderItem = function( ul, item) {
    var re = new RegExp(this.term, "ig") ;
    var t = item.label.replace(re,"" + this.term + "");
    return $( "

" )
        .data( "item.autocomplete", item )
        .append( "" + t + "" )
        .appendTo( ul );
};
};


text:
Q: How would I stop one tab from closing as the other opens in my script? So I have 3 scripts
Script 1 which opens tab one and closes upon mouseleave()
$(document).ready(function(){
var myTimeOut;
var rightSlide1 = ".rightslide1";

$(rightSlide1).mouseenter(function(){
    myTimeOut = setTimeout(function (){
        $(rightSlide1).stop(true,true).animate({"left": "9.5vw"}, "300");
    }, 1000);
});

$(rightSlide1).mouseleave(function(){
    clearTimeout(myTimeOut);
    $(rightSlide1).animate({"left": "37vw"}, "300");
});

Script 2  which opens tab one and 2 and closes upon mouseleave()
$(document).ready(function(){
    var myTimeOut;
    var rightSlide1 = ".rightslide1";
    var rightSlide2 = ".rightslide2";

    $(rightSlide2).mouseenter(function(){
        myTimeOut = setTimeout(function (){
            $(rightSlide1).stop(true,true).animate({"left": "9.5vw"}, "300");
            $(rightSlide2).animate({"left": "14vw"}, "300");
        }, 1000);
    });

    $(rightSlide2).mouseleave(function(){
        clearTimeout(myTimeOut);
        $(rightSlide1).animate({"left": "37vw"}, "300");
        $(rightSlide2).animate({"left": "41.5vw"}, "300");
    });
});

And Script 3  which opens tab one, two and three and closes them all upon mouseleave()
$(document).ready(function(){
    var myTimeOut;
    var rightSlide1 = ".rightslide1";
    var rightSlide2 = ".rightslide2";
    var rightSlide3 = ".rightslide3";

    $(rightSlide3).mouseenter(function(){
        myTimeOut = setTimeout(function (){
            $(rightSlide1).stop(true,true).animate({"left": "9.5vw"}, "300");
            $(rightSlide2).animate({"left": "14vw"}, "270");
            $(rightSlide3).animate({"left": "18.5vw"}, "300");
        }, 1000;
    });

    $(rightSlide3).mouseleave(function(){
        clearTimeout(myTimeOut);
        $(rightSlide1).animate({"left": "37vw"}, "300");
        $(rightSlide2).animate({"left": "41.5vw"}, "270");
        $(rightSlide3).animate({"left": "46vw"}, "300");
    });
});

So basically on this page, I have 3 tabs. 1|2|3| and I want to to be able to open the tabs and have them slide against each other.  I have gotten the tabs to slide left as I want but the problem is now I cant figure out how to keep tab 1 open while someone opens tab 2. It closes when I go to open tab 2 which just looks tacky.

A: there are two tiny issues, which are causing your problem:

Issue #1:  Your tabs close right away, when you leave, but the opening is delayed by 1 second. If you want to keep it like that, your tabs will always close first and open delayed. If you lessen the delay time, they may close and open simultaneously. However, they will keep sliding round a bit too much. I would recommend to get rid of that delay, or add it to the close animation as well. You also could make one general delay, when entering the accordion.

Issue #2: This is the more important one. You are using jQuery's stop() method. First, you should use it consistently throughout all your animations, so they get executed immediately and not queued, which can result in very weird behaviour. Second, don't set the second parameter to true. This will make the current animation to go to its end immediately, which causes the tabs to "jump". If you set it to false instead, the tab will stop at its current position and continue with the new animation from this point on. This will result in a far better user experience.

If you get rid of the delay, and change the second parameter, your close will beautifully slide against each other.
With best regards,Syntac


text:
Q: Iterating through comma-separated arguments I've looked all over and can't seem to find a succinct answer to this question.  Is it possible (and if so, how) to create a command that will iterate through its `arguments' of comma-separated values and act upon them?
Example mostly stolen from "For loop" in newcommand:
\newcommand{\pdfappendix}[1]{
    for \image in #1
    {
       \includegraphics[scale=0.6]{\image.pdf}
    }
}

The goal here is to create a command that can print a file menu structure (or some arbitrary path) like so:
\ppath{Command,TeXing Options,Generate PDF (C-c C-t C-p)}

potentially with an optional argument for a delimiter (defaulting to \to or something)
which would produce
Command -> TeXing Options -> Generate PDF (C-c C-t C-p)

In the words of holy ed, ?

A: Here is a solution with LaTeX3, which might be simpler
Since may 2021
\clist_use:nn and \clist_use:nnnn are available as pointed out by egreg in the comments.
\documentclass{standalone}
\ExplSyntaxOn
\NewDocumentCommand \ppath { O{$\;\triangleright\;$} m } {
  \clist_use:nn { #2 } { #1 }
}
\ExplSyntaxOff
\begin{document}
A decent file path is \ppath{File,New,Document}.
\end{document}

The output is

Before may 2021
The instruction \clist_use:nn { #2 } { #1 } should be replaced by
  \group_begin:
  \clist_set:Nn \l_tmpa_clist { #2 }
  \clist_use:Nn \l_tmpa_clist { #1 }
  \group_end:

Some explanations:
In the second example,

*

*We wrap the commands in a group to use local variables

*We store the mandatory argument in a scratch variable named \l_tmpa_clist of type clist

*We "use" that variable to display the list with the given separator

Notice the use of \clist_use:Nn instead of \clist_use:nn.
The LaTeX3 commands documentation is available on CTAN as interface3.pdf and may be available locally with texdoc interface3.

A: etoolbox's list processing capabilities are straight forward:

\documentclass{article}
\usepackage{etoolbox}% http://ctan.org/pkg/etoolbox
\newcommand{\ppath}[2][$\;\triangleright\;$]{%
  \def\nextitem{\def\nextitem{#1}}% Separator
  \renewcommand*{\do}[1]{\nextitem\textsf{##1}}% How to process each item
  \docsvlist{#2}% Process list
}
\begin{document}
A decent file path is \ppath{File,New,Document}.
\end{document}

The separator \nextitem is defined to do nothing during its first use. \do defines how each item is processed, while \docsvlist processes a comma-separated list. See Cunning (La)TeX tricks for a short discussion on the use of \nextitem.

A: Found an answer in another question's answer.  With @Werner's help (specifically the deferred \def trick), the pure TeX solution works without the need for extra packages. What follows is a minimal working example of what I was looking for.
\documentclass{article}

\makeatletter
\newcommand{\ppath}[2][ $\triangleright$ ]{%
  \def\nextitem{\def\nextitem{#1}}%
  \@for \el:=#2\do{\nextitem\el}%
}
\makeatother

\begin{document}
  A decent file path is \ppath{File,New,Why}.  I said, Why.
\end{document}

Output:

(Thanks @Peter, @jon.)

Explanation for the comments:
\def\nextitem{\def\nextitem{#1}} here is defining \nextitem to, when it is used, redefine \nextitem to expand to the argument it was given the first time.  This is a pretty tricky operation, so read that again.
So, if I call \nextitem{foo}, that expands to \def\nextitem{foo}. The \nextitem token, having been consumed and expanded, is gone. Note that \nextitem goes from having one argument to having no arguments; after using \nextitem{foo}, that itself redefines \nextitem to foo -- and doesn't emit foo the first time (since the first time is just the redefinition.
This is heart of the trick: the for loop provides a way to output >File>New>Why -- the \nextitem trickery is a way to make the first > 'disappear' -- because the first time \nextitem is used, all it's doing is a redefinition.

A: In OpTeX we have \foreach command with the syntax
\foreach <list of object>\do <parameter-mask for sigle object>{<what to do>}

For example
\foreach a,b,c,d,\do #1,{do something with #1}

does (expadable) loop over the given list of objects separated by comma. Your task should be solved by the following macro:
\def\ppath#1{\ppathA#1,\end}
\def\ppathA#1,#2\end{#1\foreach #2\do ##1,{$\,\triangleright\,$##1}}

\ppath{Command,TeXing Options,Generate PDF (C-c C-t C-p)}

\ppath{Cmd}

\bye


text:
Q: Why my overlay div is not centering I am sure it is a "simple" for the pros:
I am at lost on how to center (horizontally and vertically) the overlay to its parent. Please see the jsfiddle link for the details.
Thank you in advance for your time...
LB

1-1

1-2

1-3

2-1

2-2

2-3

3-1

3-2

3-3

            Overlaysdfds
            line2sdf sdfdsf sdfsdf sfdsdf

line 3

and the CSS:


text:
Q: weifenluo.winformsui.docking dll for Linux I have C# application which uses weifenluo.winformsui.docking.dll 2.3.1.0 for Docking. It runs nicely in Windows but does not run in Mono on Linux, ubuntu version 10.04 32-bit. It gives the exception with the weifenluo.winformsui.docking library.
Can anyone help me in solving this problem? or share the weifenluo.winformsui.docking.dll library which is compatible in both Windows and Linux.

A: This library unfortunately uses PInvoke to call Win32 APIs, so it is not portable for Linux usage.
Unless you decide to give up drag and drop support, then you can use a lite version,
http://www.lextm.com/2010/05/dockpanel-suite-tip-4-we-could-go-mono.html
This is the modified source code,
https://github.com/lextm/sharpsnmplib/tree/master/WinFormsUI
Update: I have become one of the maintainers for this project. Please visit http://dockpanelsuite.com to check out the latest information.


text:
Q: How to make queue calling in salesforce using Twilio? I am integrating my salesforce with Twilio to make calls.I am able to call person individually. But my requirement is to allow multiple persons to be called one by one using a queuing in Twilio. How is it achievable in apex?

A: You can use  tag in  tag to make calls to multiple numbers.
Please follow this this link.
https://www.twilio.com/docs/api/twiml/queue


text:
Q: How to set image alt text to be fontawsome in asp.net? I am developing a website using ASP.Net. In the navbar, I put the profile photo of the current logged-in user.
In case the user doesn't have a profile photo, I want to show an alt text.
can I use fontawsome in the alt text?

A: You cannot next an html tag within another for instance
<img alt="<i class="fas fa"

Im sure you can see the problem right away
You may however be able to use an HTML Entity
http://dnozay.github.io/cheatsheet/2014/09/23/fontawesome.html
Hopefully this helps


text:
Q: LINQ query to return distinct field values from list of objects class obj
{
    int typeId; //10 types  0-9
    string uniqueString; //this is unique
}

Assume there is a list with 100 elements of objs, but only 10 unique typeIDs.
Is it possible to write a LINQ query that returns the 10 unique ints from the list of objs?

A: Assuming you want the full object, but only want to deal with distinctness by typeID, there's nothing built into LINQ to make this easy. (If you just want the typeID values, it's easy - project to that with Select and then use the normal Distinct call.)
In MoreLINQ we have the DistinctBy operator which you could use:
var distinct = list.DistinctBy(x => x.typeID);

This only works for LINQ to Objects though.
You can use a grouping or a lookup, it's just somewhat annoying and inefficient:
var distinct = list.GroupBy(x => x.typeID, (key, group) => group.First());

A: Sure, use Enumerable.Distinct.
Given a collection of obj (e.g. foo), you'd do something like this:
var distinctTypeIDs = foo.Select(x => x.typeID).Distinct();

A: I think this is what your looking for:
    var objs= (from c in List_Objects
orderby c.TypeID  select c).GroupBy(g=>g.TypeID).Select(x=>x.FirstOrDefault());

Similar to this Returning a Distinct IQueryable with LINQ?

A: If just want to user pure Linq, you can use groupby:
List<obj> distinct =
  objs.GroupBy(car => car.typeID).Select(g => g.First()).ToList();

If you want a method to be used all across the app, similar to what MoreLinq does:
public static IEnumerable<TSource> DistinctBy<TSource, TKey>
    (this IEnumerable<TSource> source, Func<TSource, TKey> keySelector)
{
    HashSet<TKey> seenKeys = new HashSet<TKey>();
    foreach (TSource element in source)
    {
        if (!seenKeys.Contains(keySelector(element)))
        {
            seenKeys.Add(keySelector(element));
            yield return element;
        }
    }
}

Using this method to find the distinct values using just the Id property, you could use:
var query = objs.DistinctBy(p => p.TypeId);

you can use multiple properties:
var query = objs.DistinctBy(p => new { p.TypeId, p.Name });

A: I wanted to bind a particular data to dropdown and it should be distinct.
I did the following:
List<ClassDetails> classDetails;
List<string> classDetailsData = classDetails.Select(dt => dt.Data).Distinct.ToList();
ddlData.DataSource = classDetailsData;
ddlData.Databind();

See if it helps

A: If just want to use Linq, you can override Equals and GetHashCode methods.
Product class:
public class Product
{
    public string ProductName { get; set; }
    public int Id { get; set; }

    public override bool Equals(object obj)
    {
        if (!(obj is Product))
        {
            return false;
        }

        var other = (Product)obj;
        return Id == other.Id;
    }

    public override int GetHashCode()
    {
        return Id.GetHashCode();
    }
}

Main Method:
static void Main(string[] args)
    {

        var products = new List<Product>
        {
            new Product{ ProductName="Product 1",Id = 1},
            new Product{ ProductName="Product 2",Id = 2},
            new Product{ ProductName="Product 4",Id = 5},
            new Product{ ProductName="Product 3",Id = 3},
            new Product{ ProductName="Product 4",Id = 4},
            new Product{ ProductName="Product 6",Id = 4},
            new Product{ ProductName="Product 6",Id = 4},
        };

        var itemsDistinctByProductName = products.Distinct().ToList();

        foreach (var product in itemsDistinctByProductName)
        {
            Console.WriteLine($"Product Id : {product.Id} ProductName : {product.ProductName} ");
        }

        Console.ReadKey();
    }

A: objList.Select(o=>o.typeId).Distinct()


text:
Q: Global Error Handling in ASP.NET Core MVC I tried to implement a global error handler on my Asp.net core mvc web page. For that I created an error handler middleware like described on this blog post.
    public class ErrorHandlerMiddleware
{
    private readonly RequestDelegate _next;

    public ErrorHandlerMiddleware(RequestDelegate next)
    {
        _next = next;
    }

    public async Task Invoke(HttpContext context)
    {
        try
        {
            await _next(context);
        }
        catch (Exception error)
        {
            var response = context.Response;
            response.ContentType = "application/json";

            switch (error)
            {
                case KeyNotFoundException e:
                    // not found error
                    response.StatusCode = (int)HttpStatusCode.NotFound;
                    break;
                default:
                    // unhandled error
                    response.StatusCode = (int)HttpStatusCode.InternalServerError;
                    break;
            }

            var result = JsonSerializer.Serialize(new { message = error?.Message });
            await response.WriteAsync(result);
            context.Request.Path = $"/error/{response.StatusCode}"; // <----does not work!
        }
    }
}

The middleware works as expected and catches the errors. As a result i get a white page with the error message. But i am not able to display a custom error page. I tried it with the following line of code. But this does not work.
context.Request.Path = $"/error/{response.StatusCode}";

Any ideas how I can achive my goal?
Thanks in advance

A: It seems that you wish to redirect the browser to an error page.
To do this you'll need to replace:
context.Request.Path = $"/error/{response.StatusCode}";

With
context.Reponse.Redirect($"/error/{response.StatusCode}");

Also, since you're sending a redirect, the response content needs to be empty, so remove the response.WriteAsync bit too.
var result = JsonSerializer.Serialize(new { message = error?.Message });
await response.WriteAsync(result);


text:
Q: How many students need to be checked to be 90% sure they got a grade of 70..80? Can you help me on some question i'm stuck on?
Let X be a random variable of the average grade of the students in some course.
E[X] = 75
Var[X] = 25
What's the number of students that need to be checked in order to assure in at least 90% that their average grade is between 70 and 80?
Here's what i've done:
$P(70<X<80) < P(|X-75|<5) = 1-P(|X-75|>=5) >= 0.9$ (according to Chebyshev)
Now let $5=a*s$ (s = standard deviation , a is a parameter). Then we need:
$1-\frac{1}{a^2} = 0.9$
That is $a=\sqrt{10}$
Which means $s=\frac{5}{\sqrt{10}}$
Which means Variance = $s^2 = 2.5$
So apparently this is wrong because i believe i can't change the variance in the question... Plus, i didn't conclude anything about the number of students...
Any help?
Thanks

A: We have a population mean of $\mu=75$ and variance of $\sigma^2=25$. So the distribution of the sample average form a sample of size $n$ also has mean $75$ and has a variance of $\frac{25}{n}$.
So if you decided to use Chebyshev's inequality of the form $\Pr(|Y-E[Y]| \ge t] \le \text{Var}(Y)/t^2$ you would want $ \dfrac{\frac{25}{n}}{5^2} \lt 0.1$, i.e. a sample size of $n \gt 10$.
If you assumed a normal distribution, you would want to look at $ \sqrt{\frac{25}{n}} \Phi^{-1}(0.95) \lt 5$ which would lead to a sample size $n \gt 2.706$.