text:
Q: Laravel 5.2 Eloquent relationship I currently have 4 tables that consist of:

*

*Users

*Providers

*Projects

*Project_Bids

I'm trying to query Laravel's eloquent model on a project's table so when the given user visits a link similar to the following:  example.com/project/{projectid}
The view uses a foreach loop to loop through all the project bids that are relevant to that project id.
I'm having the issue of being able to display /loop through all the bids and have them render correctly, I have tried using the following:
$projectBids = ProjectBids::where('project_id', '=', $projectid)
                            ->get();

And I have tried from both these relationships:
public function project_bids(){

    return $this->hasMany(ProjectBids::class, 'project_id');

}

public function project_bids(){

    return $this->belongsTo(ProjectBids::class, 'project_id');

}

However when I try and loop through the returned database data I can not display the relevant bid unless I manually have use the following:
return $project->project_bids[0]->bid_price;
and specifiy the [0] row or [1] and so on...
Surely there has to be a much easier way of doing this and as a total novice, after watching days of tutorials and videos I'm loosing myself within the functionality, All I am trying to do is reference the project_bids table to retrieve all the bids where the project_id matches the given id then loop through them within the view.
I want to be able to display the bids that are relevant to the project_id and be able to use the method like this:
$project->projectbids->bid_price
Any help is greatly appreciated, I understand that this question is not the best asked question, this is mainly due to spending 36 hours or more trying to resolve it so my mind is boggled with the amount of tutorials I have tried to follow.

A: You can get the project with Project with:
$project = Project::with('project_bids')->find($id); //id is the id from URL

Now you can loop through the bids in the blade:
@foreach($project->project_bids as $bids)

@endforeach

If you just want the first bid, you can use:
$project->project_bids->first()->bid_price;

A: If you have many record related to Project, it's obvious you cannot do something like this:
$project->projectbids->bid_price

because projectbids here is not a single element but collection of elements.
To get all the bids, you need to use loop:
@foreach ($project->projectbids as $bid)
   {{ $bid->bid_price }}
@endofreach

A: You are doing it wrong. Assuming User hasMany Project and Project hasMany Bid so for Project & Bid relationship you have to declare hasMany relationship in your app\Project model first, for example:
// App\Project.php
public function bids()
{
    rturn $this->hasMany(Bid::class);
}

Now, you can do something like this:
$projectWithBids = Project::with('bids')
                          ->where('project_id', $projectid)
                          // assuming projects table gas a user_id field
                          ->where('user_id', auth()->user()->id)
                          ->first();

So to access them in your view, you'll do something like this:
@foreach($project->bids) as $bid)
    {{ $bid->price }}
    {{-- More --}}
@endforeach


text:
Q: How should I spec this The following spec works but I know it shouldn't be like this.  I am having a hard time getting my head around rspec, in particular mocks and stubs.
This is the model code
class RecipeFermentable < ActiveRecord::Base
  belongs_to :recipe
  belongs_to :product

  def set_attributes()
    attrs = product.product_attributes
    self.ppg = attrs.find_by_name(:ppg.to_s).value
    self.ecb = attrs.find_by_name(:ecb.to_s).value
  end
end

And this is the spec I have written
  it "should set the attributes from the product" do
    @product_attribute1 = mock_model(ProductAttribute, :name => :ppg, :value => 40)
    @product_attribute2 = mock_model(ProductAttribute, :name => :ecb, :value => 1)

    @product = Product.new
    @product.product_attributes << @product_attribute1
    @product.product_attributes << @product_attribute2
    @recipe_fermentable = RecipeFermentable.new
    @recipe_fermentable.product.should_receive(:product_attributes).and_return(@product_attributes)
    @product_attributes.stub(:find_by_name).with(:ppg.to_s).and_return(@product_attribute1)
    @product_attributes.stub(:find_by_name).with(:ecb.to_s).and_return(@product_attribute2)

    @recipe_fermentable.set_attributes

    @recipe_fermentable.ppg.should eql(40)
    @recipe_fermentable.ecb.should eql(1)
 end

For a start my spec is way bigger than my method, and I am using a real Product.  Some pointers on the way to write a goodbetter spec for this would be really helpfull.  Also if anyone knows of a good resource for learning rspec using mocks and stubs, please could you add some links.
Thanks

A: I would change a couple of things here:

*

*Much of the code in your it is just providing context, so it should be in your before(:each) block.

*You are setting a message expectation, but it doesn't really seem like you are testing for that. I think the expectation should be switched to a stub instead. Another test could be it 'should call product_attributes', where you would in fact test that expectation - I am not advocating you do this since you would be testing implementation and not behavior, but just making the point.

*You are returning @product_attributes in that message expectation, and using it right after to stub the find_by_name calls. However, you never defined @product_attributes. I assume that should be a mock object, and I'm not sure what it really is in that context. Maybe it is nil, and you are stubbing a couple of methods on it.

With those two changes, here's where we are:
before(:each) do
  @product                = mock_model(Product)
  @product_attribute_ppg  = mock_model(ProductAttribute, :name => :ppg, :value => 40)
  @product_attribute_ecb  = mock_model(ProductAttribute, :name => :ecb, :value => 1)
  @product_attributes     = mock('product_attributes')
  @product_attributes.stub!(:find_by_name).with(:ppg.to_s).and_return(@product_attribute_ppg)
  @product_attributes.stub!(:find_by_name).with(:ecb.to_s).and_return(@product_attribute_ecb)
  @product.stub!(:product_attributes).and_return(@product_attributes)

  @recipe_fermentable = RecipeFermentable.new
  @recipe_fermentable.stub!(:product).and_return(@product)
end

it 'should set the attributes from the product' do
  @recipe_fermentable.set_attributes
  @recipe_fermentable.ppg.should eql(40)
  @recipe_fermentable.ecb.should eql(1)
end

With all of that all of the way, I don't completely agree with your approach here. I think that you are repeating data and moving away from DB normalization. Unless there's a real reason for that (could be that your way ahead and for performance reasons you had to do this), I would suggest the following instead:
class RecipeFermentable < ActiveRecord::Base
  def ppg
    #rescue nil here so that if attributes is nil, or find_by_name('ppg') is nil, things don't blow up
    product.attributes.find_by_name('ppg').value rescue nil
  end

  #other
end

A couple of resources for testing:

*

*RSpec book

*xUnit patterns: not RSpec nor Ruby, but a must.

redpajama_set_name: RedPajamaStackExchange


text:
Q: Space between axis categories and bars in coord_flip() in ggplot Currently I have the following graph, which is a geom_bar after adjusting by coord_flip()

But there is too much space between the y axis categories and the bars (the area that I've marked in yellow).
How can I modify it?


text:
Q: dnssec remove keys from zone is there a way to remove all dnssec related stuff from a zone on a running  bind server?
I configured bind like like here described.
If i use rndc signing -clear all domain.tld nothng happens to the zone.
If i delete the dnssec signed zone via rndc delzone domain.tld
and recreate it via rndc addzone domain.tld ... , the domain.tld.jnl file with the related dnssec data will be automaticly recreated and the zone is dnssec signed again.
How can i remove all dnssec related data from a zone with rndc ?

A: (i use the inline-signing option to auto sign the zones in another file called {Zonename}.signed)
To remove all DNSSEC related Data of the Zone u have to remove the {ZoneName}.signed and {ZoneName}.jnl file of the Zone.
Remove also all the Key Files of the Zone (which should be in the keys - Directory) - otherwhise bind9 will autoresign the Zone.
After all the deletion it would be the clear way to rndc delzone {ZoneName} and reinititate the unsigned Zone with rndc addzone {Options without DNSSEC}


text:
Q: How to share APC cache between several PHP processes when running under FastCGI? I'm currently running several copies of PHP/FastCGI, with APC enabled (under Apache+mod_fastcgi, if that matters).  Can I share cache between the processes?  How can I check if it's shared already?  (I think the apc.mmap_file_mask ini setting might be involved, but I don't know how to use it.)
(One of the reasons I think its not shared at the moment is that the apc.mmap_file_mask, as reported by the apc.php web interface flips between about 3 different values as I reload.)

A: APC does not currently share its cache between multiple php-cgi workers running under fastcgi or fcgid. See this feature request for details: "this behaviour is the intended one as of now".
One workaround is to allow PHP to manage its own workers. You can do this using the PHP_FCGI_CHILDREN environment variable in your wrapper script (plenty of examples all over the web for that). You should also stop fastcgi/fcgid from spawning more than one PHP process if you want to use this method.
The disadvantage with PHP_FCGI_CHILDREN is that its management of the workers is not as good as that provided by fcgid/fastcgi.
So, there we are. APC in a fcgid/fastcgi environment means giving each PHP worker their own cache, or disabling fcgid/fastcgi's process spawning in favor of PHP's built-in management. Let's hope this changes in the future.

A: While it's not perfect the method Domster suggested is the best.  I've been doing this for a short time on some low volume sites without errors.  I wrote up a detailed explanation on how to set up mod_fastcgi with a shared opcode cache last night.
I found it very important to use mod_fastcgi rather than the newer mod_fcgid because mod_fcgid will only send one request at a time to the PHP process regardless of how many children PHP has spawned via PHP_FCGI_CHILDREN.

A: The cache should be shared between processes. You should be seeing the same value for the mmap file between phpinfo() and apc.php invocations. It is working for me with the suggested default APC configuration settings:
extension="apc.so"
apc.enabled=1
apc.shm_segments=1
apc.shm_size=128
apc.ttl=7200
apc.user_ttl=7200
apc.num_files_hint=1024
apc.mmap_file_mask="/tmp/apc.XXXXXX"
apc.enable_cli=1

You may want to post your settings. I've seen warnings that the mmap_file_mask must be exactly one of the values they allow. So if you are missing one of those Xs there is no telling what you will get.
Maybe it involves your fastcgi+apache configuration.


text:
Q: How to set layout width of a button from code behind in Android Xamarin in C#? I am working with an Android button in Xamarin Android C# project.
<Button
android:id="@+id/btn1"
android:layout_width="120dp"
android:layout_height="120dp"
android:background="@drawable/ButtonImages"
android:layout_marginLeft="35dp"   />

Here I want to set this Android: layout_width="120dp" and Android: layout_marginLeft="35dp" from code behind.
I got the button control from code behind by
Button btn1 = FindViewById<Button>(Resource.Id.btn1);

But unable to set width and marginLeft
How can I do this?

A: Haven't tested this is xamarin, but ideally, this should work, please try and update. Here, I have set the height and weight to 120dp, you can modify it according to your need. Also can set the margins to your need by replacing the text.
Button btn1 = FindViewById<Button>(Resource.Id.btn1);
LinearLayout.LayoutParams params = new LinearLayout.LayoutParams (120,120);
params.setMargins(left, top, right, bottom);
btn1.setLayoutParams(params);


text:
Q: Python iloc slice range from dictionary value I am trying to use a dictionary value to define the slice ranges for the iloc function but I keep getting the error  --  Can only index by location with a [integer, integer slice (START point is INCLUDED, END point is EXCLUDED), listlike of integers, boolean array] .  The excel sheet is built for visual information and not in any kind of real table format (not mine so I can't change it) so I have to slice the specific ranges without column labels.
tried code - got the error
cr_dict= {'AA':'[42:43,32:65]', 'BB':'[33:34, 32:65]'}

df = my_df.iloc[cr_dict['AA']]

the results I want would be similar to
df = my_df.iloc[42:43,32:65]

I know I could change the dictionary and use the following but it looks convoluted and not as easy to read– is there a better way?
Code
cr_dict= {'AA':[42,43,32,65], 'BB':'[33,34, 32,65]'}
df = my_df.iloc[cr_dict['AA'][0]: cr_dict['AA'][0], cr_dict['AA'][0]: cr_dict['AA'][0]]

A: Define your dictionaries slightly differently.
cr_dict= {'AA':[42,43]+list(range(32,65)),
          'BB':[33,34]+list(range(32,65))}

Then you can slice your DataFrame like so:
>>> my_df.iloc[cr_dict["AA"], cr_dict["BB"]].sort_index()


text:
Q: SQL Trigger can't detect my identity column I want to have this column HiddenID which I use as IDENTITY so that when my trigger updates a column, it will know which to update because currently it does not, so whenever I insert a new record, the trigger updates what its supposed to for all the columns with the value which is meant for the new record. But it returns me the error

The multi-part identifier "inserted.HiddenId" could not be bound.

Trigger
CREATE TRIGGER InsertNoOfDays ON CurrentApplication
AFTER INSERT
AS
BEGIN
    DECLARE @temp INT
    SELECT @temp = (coalesce(DATEDIFF(day, StartDate, EndDate),0)+1) --Default 0
    FROM inserted

    UPDATE CurrentApplication SET NoOfDays = @temp WHERE CurrentApplication.HiddenID = inserted.HiddenId
END

Table
CREATE TABLE CurrentApplication
(
StartDate       datetime        ,
EndDate         datetime        ,
NoOfDays        integer,
StaffID         integer         ,
AppStatus       varchar(30)     DEFAULT 'PENDING',
HiddenID        integer         IDENTITY
)

A: Totally normal.
Your update statement does not specify the "inserted" table.
Statement "from inserted" is missing. Therefore, "inserted" cannot be found.

A: I wouldn't use a trigger for this at all. A computed column would work fine for this case, and handle multiple-row inserts:
ALTER TABLE CurrentApplication DROP COLUMN NoOfDays;
ALTER TABLE
    CurrentApplication
    ADD NoOfDays AS (coalesce(DATEDIFF(day, StartDate, EndDate),0)+1) PERSISTED

This drops your existing NoOfDays column and then replaces it with a new computed column that calculates NoOfDays whenever StartDate or EndDate changes and stores the calculated value alongside the other table data for speed.

A: probably you are looking for a update join syntax; like
UPDATE c
SET NoOfDays = @temp
FROM CurrentApplication c
JOIN inserted i
ON c.HiddenID = i.HiddenId;

A: RMS is right, your trigger should look like this :
CREATE TRIGGER InsertNoOfDays ON CurrentApplication
AFTER INSERT
AS
BEGIN
    UPDATE ca
    SET NoOfDays = (coalesce(DATEDIFF(day, i.StartDate, i.EndDate),0)+1)
    FROM CurrentApplication ca
    INNER JOIN Inserted ON ca.HiddenID = i.HiddenId
END


text:
Q: Is the jackknife estimate parametric or non-parametric? The jackknife is often described as non-parametric, and not relying on distributional assumptions.
For example: https://blogs.sas.com/content/iml/2017/06/21/jackknife-estimate-standard-error-sas.html says: "The jackknife method estimates the standard error (and bias) of statistics without making any parametric assumptions about the population that generated the data. It uses only the sample data."
However when I calculate the jackknife standard error of the mean it is identical to the plug-in formula:
Python example:
import numpy as np
import pandas as pd

from scipy.stats import bootstrap

np.random.seed(1234)
n = 5
y = np.random.uniform(0, 1, n)
df = pd.DataFrame({'y': y})
m = []
for i in range(n):
  new_df = df.drop(index=df.index[i], inplace = False)
  m.append(np.mean(new_df["y"]))

jack_se = (n - 1) * np.std(m, ddof = 1) / n**0.5
print(jack_se)

calc_se = df["y"].std() / (n**0.5)
print(calc_se)

Which gives:
0.11262904921394813
0.11262904921394809

The bootstrap standard error (which, to my understanding, is non-parametric) is consistently smaller, which is what I would expect:
print(bootstrap((df["y"],), np.mean).standard_error)
0.10078617321044048


text:
Q: How to save requests and responses to database in spring boot I would like to write an aspect or something like that and whenever a request comes to the controller it saves the request and the response to the database.
First question is what type I should use in my entity for request and response ( string, blob, etc)
Second question, how to get request,response and its controller name  to create the entity to save to database ?
Lastly, is it possible to calculate response time (time spent in the controller) of the controller ?

A:
First question is what type I should use in my entity for request and
response ( string, blob, etc)

It mainly depends on the database vendor and request/response length.
String may be limited for some vendors and blob is so required.
On the other hand, matching on blob is slower.
Another alternative is using a nosql format such as JSON.

Second question, how to get request,response and its controller name
to create the entity to save to database ?

There are really several ways.
You could take advantage of built-in Spring Boot http tracing features but it has a limitation : posted/received of request/responses are not available.

5.8. HTTP Tracing
HTTP Tracing can be enabled by providing a bean of type
HttpTraceRepository in your application's configuration. For
convenience, Spring Boot offers an InMemoryHttpTraceRepository that
stores traces for the last 100 request-response exchanges, by default.
InMemoryHttpTraceRepository is limited compared to other tracing
solutions and we recommend using it only for development environments.
For production environments, use of a production-ready tracing or
observability solution, such as Zipkin or Spring Cloud Sleuth, is
recommended. Alternatively, create your own HttpTraceRepository that
meets your needs.
The httptrace endpoint can be used to obtain information about the
request-response exchanges that are stored in the HttpTraceRepository.
5.8.1. Custom HTTP tracing
To customize the items that are included in each trace, use the
management.trace.http.include configuration property. For advanced
customization, consider registering your own HttpExchangeTracer
implementation.

Alternatives are implementing a filter for requests/responses and log in it.
For example :
@Component
public class RequestResponseStoringFilter implements Filter {

  @Override
  public void doFilter(ServletRequest req, ServletResponse res,
      FilterChain chain) throws IOException, ServletException {

    HttpServletRequest request = (HttpServletRequest) req;
    HttpServletResponse response = (HttpServletResponse) res;

    long start = System.currentTimeMillis();
    try {
        chain.doFilter(req, resp);
    } finally {
       // Measure elapsed time
        long elapsed = System.currentTimeMillis() - start;
       // store request data and store response data in a DB
       .....
    }

  }

  @Override
  public void destroy() {}

  @Override
  public void init(FilterConfig arg0) throws ServletException {}

}

Lastly, is it possible to calculate response time (time spent in the
controller) of the controller ?

The way implement a Filter can do that as shown above.
The httptrace endpoint way provides that with the timeTaken field.
FIY, here is the content of a HttpTrace instance :

HttpTrace.Principal getPrincipal()
HttpTrace.Request   getRequest()
HttpTrace.Response  getResponse()
HttpTrace.Session   getSession()
Instant getTimestamp()
Long    getTimeTaken()

A: This kinda expands on the other answers, but I think It warrants a separate answer.
If your pulling in spring-boot-starter-web, then you're already pulling in spring-aop. If your going to go down the point cut route though, I'd highly recommend just using the Micrometer @Timed annotation which comes with spring-boot-starter-actuator. I've written my own metric pointcuts a many times, but if your just after timings and counts of successes and failures, @Timed works great.
I'd also highly recommend looking into using a time series database (e.g influx) for storing things like response times and other performance metrics. Keep your raw payloads and other possible auditing concerns in a separate DB. There are some very powerful things you can do with influx and running Grafana or Chronograf on top of it. Without a doubt one of the best things my current company has done is years is adopting Influx/Chronograf.
With regards to the request/response capture, I had a weird edge case in my work flow once where the http trace just wasn't working for some hard requirements. You can capture the contents directly in a chain filter yourself with a ContentCachingRequestWrapper
Then you can access them with:
 @Component
class MyPayloadCapturingFilter extends OncePerRequestFilter {

    @Override
    protected void doFilterInternal(HttpServletRequest request, HttpServletResponse response, FilterChain filterChain) throws ServletException, IOException {
        ContentCachingRequestWrapper requestWrapper = new ContentCachingRequestWrapper(request)
        ContentCachingResponseWrapper responseWrapper = new ContentCachingResponseWrapper(response)

        filterChain.doFilter(requestWrapper, responseWrapper)

        def requestBody = new String(requestWrapper.contentAsByteArray)
        def responseBody = new String(responseWrapper.contentAsByteArray)
        //..do something with them
    }
}

note the OncePerRequestFilter, I found times when my Filter was firing multiple times for the same request. This prevents that.

A: Add this dependency:
<dependency>
     <groupId>org.springframework.boot</groupId>
     <artifactId>spring-boot-starter-aop</artifactId>
</dependency>

then, create an Around aspect for your controllers' methods' execution:
    @Around("within(path.to.your.controller.*)")
    public Object pointcutWithin(ProceedingJoinPoint joinPoint) throws Throwable {
        logger.info(" ###### pointcutWithin() before");
        long start = System.nanoTime();

        Object result = joinPoint.proceed();

        logger.info(" ###### pointcutWithin() after");
        long end = System.nanoTime();

        long timeElapsedInMillis = (end - start) / 1000000;
        logger.info(" ###### elapsed time in millis: "+timeElapsedInMillis);

        return result;
    }

As for persisting: first, get the req and resp like so:
MyRequest req = (MyRequest) joinPoint.getArgs()[0];

MyResponse resp = (MyResponse) result;

then it's up to you what you actually want t o persist. For classes with simple fields I'd go with a varchar, just remember to override their toString methods.


text:
Q: How realize internationalization using by ngx-translate via dropdown menu? I want realize internationalization by dropdown menu. There are 3 json files with 3 languages which are in assets. When I select language in dpopdown menu, the value displayed in another component but value returns "object Object" and I cant undestand how fix that.
https://imgur.com/5sFpurF - Template
Component with template where will be display value translated text

import { Component, OnInit, HostBinding } from '@angular/core';
import { TranslateService } from '@ngx-translate/core';

@Component({
  selector: 'app-home',
  templateUrl: './home.component.html',
  styleUrls: ['./home.component.css'],
})

export class HomeComponent implements OnInit {

  constructor( private translate: TranslateService ) {

  }

  ngOnInit() {
    this.translate.use('ru')
  }

}

      {{ translate || title }}

Component with dropdown menu

import { Component, OnInit } from '@angular/core';
import { TranslateService } from '@ngx-translate/core';

@Component({
  selector: 'app-navbar',
  templateUrl: './navbar.component.html',
  styleUrls: ['./navbar.component.css']
})
export class NavbarComponent implements OnInit  {
  constructor(private translate: TranslateService) {
    translate.setDefaultLang('ru');

  }

  ngOnInit() {
    this.translate.use('en')
    this.translate.use('de')
  }

  changeLanguage(lang: string) {
    this.translate.use(lang);

  }
}

    Husserliana

          Главная

          Биография

          Работы

          Гуссерль и история

          Фотогалерея

          Библиография

        <button class="btn btn-light dropdown-toggle"
        type="button" id="dropdownMenuButton"
        data-toggle="dropdown" aria-haspopup="true" aria-expanded="false">
            Translate
        </button>
        <button class="btn btn-light">Login</button>

          <button class="dropdown-item btn-light" (click)="changeLanguage('ru')">
            ru
          </button>
          <button class="dropdown-item btn-light" (click)="changeLanguage('en')">
            en
          </button>
          <button class="dropdown-item btn-light" (click)="changeLanguage('de')">
            de
          </button>

AppModule

import { BrowserModule } from '@angular/platform-browser';
import { NgModule } from '@angular/core';
import { BrowserAnimationsModule } from '@angular/platform-browser/animations';
import AppRoutingModule from '../app/feature/app-routing/app-routing.module';
import { TranslateModule, TranslateLoader, TranslatePipe } from '@ngx-translate/core';
import {TranslateHttpLoader} from '@ngx-translate/http-loader';
import { HttpClient } from '@angular/common/http';
import {HttpClientModule} from '@angular/common/http';

import { AppComponent } from './app.component';
import { HomeComponent } from './core/components/home/home.component';
import { BioComponent } from './core/components/bio/bio.component';
import { WorksComponent } from './core/components/works/works.component';
import { HusserlComponent } from './core/components/husserl/husserl.component';
import { GalleryComponent } from './core/components/gallery/gallery.component';
import { BibliographyComponent } from './core/components/bibliography/bibliography.component';
import { NavbarComponent } from './core/components/navbar/navbar.component';
import { SpringerApiService } from './shared/springer-api.service';

export function HttpLoaderFactory(http: HttpClient) {
  return new TranslateHttpLoader(http, '../../../assets/i18n/', '.json');
}

@NgModule({
  declarations: [
    AppComponent,
    HomeComponent,
    BioComponent,
    WorksComponent,
    HusserlComponent,
    GalleryComponent,
    BibliographyComponent,
    NavbarComponent
  ],
  imports: [
    BrowserModule,
    BrowserAnimationsModule,
    AppRoutingModule,
    TranslateModule.forRoot({
      loader: {
          provide: TranslateLoader,
          useFactory: HttpLoaderFactory,
          deps: [HttpClient]
      }
  }),
  HttpClientModule
  ],
  exports: [],
  providers: [SpringerApiService],
  bootstrap: [AppComponent]
})
export class AppModule { }

A: You should change your template like this:

      {{ title | translate }}

Where title is one of the resource keys.
See the example from official ngx-translate - https://stackblitz.com/github/ngx-translate/example
https://github.com/ngx-translate/core#ngx-translatecore--


text:
Q: How to retrieve the id attribute value in MagicSuggest? I am using a couple of MagicSuggest controls on my page, with the following code:

...

var ms = $('.magicsuggest').magicSuggest({});
$(ms).on('selectionchange', function(event, combo, selection){
    var id = combo.input[0].offsetParent.id;

    ...
});

I have found this quite cumbersome way to retrieve back the id of my
, but am wondering if there is more elegant way to do this?

A: You are actually not trying to get the ID of the combobox but of its container.
How about this:
    var ms = $('.magicsuggest').magicSuggest({});
    $(ms).on('selectionchange', function(event, combo, selection){
        var id = combo.container[0].id;

        ...
    });


text:
Q: Why was this Discovery episode named "Unification III"? The name of S03E07 of Star Trek: Discovery is Unification III. The Unification word has some connection with the story, but what does the suffix III signify?

A: There have been two episodes in Star Trek: The Next Generation:

*

*Unification I, S05E07

*Unification II, S05E08
In these episodes, Spock travels to Romulus in order to reunite the Romulans and Vulcans as one people.
The synopsis of the episodes from the respective Memory Alpha articles linked above:

Unification I
To the Federation's surprise, Ambassador Spock has traveled to Romulus. Fearing he has defected, they send Captain Picard and Data on a covert mission to determine why.
Unification II
On Romulus, Picard and Data meet with Spock, who claims to be trying to reunite the Romulans and Vulcans. While Spock works to achieve his goal, powers within the Romulan government seek to pervert his mission into an invasion of the Federation.

So, the reunited Romulans and Vulcans are a result of what Spock did, therefore Unification III.


text:
Q: Why won't this PC power supply run my BLDC? I would like to power my Arduino and BLDC to be powered with an old computer power supply. My Arduino needs 5V and my 3 phase BLDC needs 12V.

simulate this circuit – Schematic created using CircuitLab
Details

*

*I'm using a SLA5068 N-channel MOSTFET bridge. Datasheet Here.

*My sequence is taken from the library AccelStepper--here is the homepage. The sequence has 3 steps; during each step, only one phase will be on.

*The BLDC motor I'm using is one from an old Western Digital 500gb HDD. I can't find the specs for it, but I know it's rated for 12V because I looked up a datasheet for the motor controller chip that was on the board with it.

The power supply I'm using:

Behaviour

*

*If I use the 5V for powering my BLDC, it works just fine (except I can't go very fast).

*If I use the 12V supply, it works for a moment and then shuts off.

Things I've tried

*

*Putting a 1K resistor from the 12V to ground. Also tried with a 570 ohm

*Putting in a capacitor to ground.

*Putting a fan from the 5V to ground so it has a constant load.

*Putting a flyback diode in the circuit.

The most puzzling thing
This works fine with my computer fan, which is a BLDC that has a controller circuit built inside it; this leads me to believe I am missing something in my design.
Perhaps this is an important detail, when I use the 5V supply for my 3 phase BLDC, I don't hear any clicking, but when I use the 12V supply, I hear a lot of clicking and then it shuts down quite promptly.

A: I figured out what the problem was.
CLUES

*

*There would be a clicking noise when I was using the 12V output and it would run for a moment before shutting down.

*

*This hinted that the power draw was not constant.

*My BLDC would run when connected to the 5V output and there were no clicking noises.

*

*This hinted that the problem was to do with the amount of current being drawn.

*The power supply would stay off until I hit the switch off and then back on.

*

*This hinted that it was due to a safety feature since it entered a mode where functionality was ceased completely until I restarted the supply.

Solution
One of these:

A large capacitor connected from the positive to the negative feed of the power supply smoothed out the sudden changes in current draw and fixed the problem.
Now there is no clicking noise and the motor runs just perfectly.
I hope this helped someone else.


text:
Q: SharePoint Foundation 2013 Installation/Upgrade Guide In previous versions of SharePoint, I've always been able to find a one-stop-shop Microsoft Help file that provided all the neccessary details and specific steps to install or upgrade SharePoint. With the release of SharePoint 2013 - I can't seem to find a guide of this type (the closet I've come is the 674-page deployment .PDF).
Does anyone know if they created simple, straightforward documentation for installing this software and, if so, where I can find it?

A: I guess you already saw the eBook: Deployment guide for SharePoint 2013 http://www.microsoft.com/en-us/download/details.aspx?id=30384 which is, by memory, around that amount of page but if you read it carefully, you just need to fully read a couple of chapters as they are describing all kind of farm implementation (from the standalone with built-in database to a multi tiers production ready farm) and services setup. It's currently the recommended guide as it covers nearly everything we need to know right now. (edit : and you can access each scenario through this page : http://technet.microsoft.com/en-us/library/cc303424.aspx which will be less impressive than the 600+ pages guide !)
That's the guide that I used to deploy my first SharePoint 2013 production farm (in a medical environment) with great success.
For simpler scenarii, you can trust these guides, although they are more limited in their content : http://technet.microsoft.com/en-us/library/hh872914.aspx
And finally, to have an environment up & running (but developer oriented) you can fully trust the CriticalPath guide : http://www.andrewconnell.com/blog/archive/2012/08/27/now-available-critical-path-trainingrsquos-sharepoint-2013-setup-guide-for.aspx
And don't forget the invaluable http://autospinstaller.codeplex.com/ project that will help you setting up your farm and doing most of the hard work for you.


text:
Q: convert tree into 2D array in java I have a tree:
"Apple"----"Banana"----"Cat"
|           |----"Cool"----"Door"------"Eleplant"
|--"Blueberries"---"Can"           |--"Egg"
|--"Bag"]image here for clearer
I want the output to be
**[["Apple","Banana","Cat"],
["Apple","Banana","Cool","Door","Eleplant"],
["Apple","Banana","Cool","Door","Egg"],
["Apple","Blueberries","Can"],
["Apple","Bag"],
]**

I have contruct the tree as
public static things{
    public String currentThings;
    public things[] child;
    }

How could I format the tree into a 2D-array?
Thanks,


text:
Q: How to use interface and observable in angular module to display results using *ngFor from the result from HTTP GET request? I'm trying to use interface as data type in angular app, but I keep getting error. I understand what the error means, but I don't know how to fix it.
Error: Cannot find a differ supporting object '[{"id":1,"type":"Diagnostic"},{"id":2,"type":"Impact"}]' of type 'string'. NgFor only supports binding to Iterables such as Arrays.

HTML
<mat-form-field appearance="standard">
<mat-label>Select a report type</mat-label>
<mat-select placeholder ="Report Type" formControlName="reportType" required>
  <mat-option *ngFor="let report of reportTypes"  [value]=report>
    {{ report.type }}
  </mat-option>
</mat-select>

Interface
export interface IReportTypes{
  id: number;
  type: string;
}

Component
export class HomeComponent implements OnInit {

  reportForm: any;

  reportTypes: Array<IReportTypes>;

  reportType: string;
  teamCode: string;
  orgName: string;

  constructor(private formBuilder: FormBuilder,
    private _el: ElementRef,
    private reportTypesService: ReportTypesService,
    private _bottomSheet: MatBottomSheet) {
  }

  ngOnInit(): void {

    this.createForm();

    this.getReportTypes();

  }

  getReportTypes() {

    this.reportTypesService.getReportTypes().subscribe(
      reportTypes => {
      this.reportTypes = reportTypes; console.log(typeof(reportTypes)), //<--- string
        error => console.log(error)});

  }

}

Service
 export class ReportTypesService {

  constructor(private http: HttpClient,
    private router: Router) { }

  // get report types available. This is returned from REST API provided by R
  getReportTypes(): Observable<IReportTypes[]> {

    return this.http.get<IReportTypes[]>('/api/v1/reportTypes');

  }

}

UPDATE
I tried several different variations (too many to count and mention), but none of those work in declaring array. So, I wanted to see what is the value that the service is returning. So, I printed out the following in the component after
this.reportTypes = reportTypes; console.log(typeof(reportTypes)). The result was [. So, it seems like to that the service is literally sending the results as string.

A: this.http.get<IReportTypes[]> doesn't actually convert the data to an array of IReportTypes, you are just asserting that it is.
If you are getting data as a string back from the server (Angular should try to run JSON.parse on it automatically if you are on a recent version and the response says its JSON), you will ned to better format your data in a map function.
// get report types available. This is returned from REST API provided by R
  getReportTypes(): Observable<IReportTypes[]> {

    return this.http.get<IReportTypes[]>('/api/v1/reportTypes').pipe(
       // import map from rxjs/operators in your service
       map(response => {
         // depending on what response is, you will need to format it, possibly JSON.parse again
         console.log(typeof response, response);
         let reportTypes = JSON.parse(response);
         return reportTypes;
       });
    );
  }

You can also check in the Network tab from Chrome to see the raw response from the server along with Headers.  If its not sending the data as JSON or its in extra quotes, thats likely while it's still a string.

A: change reportTypes: Array;
to
reportTypes: Array<IReportTypes[]>;
or
reportTypes: Array<IReportTypes[]> = [];
try this out  <mat-option *ngFor="let report of reportTypes | async"  [value]=report>


text:
Q: How do you correctly shorten "ask her what's her hair color"? How do you correctly shorten "ask her what's her hair color"? I thought you can just say "ask her her hair color", but then I find it weird, so I don't know if it's correct.
For example:

She asked her what's her hair color. She replied yellow.

A: Your first choice, "Ask her what's her hair color." has the words in non-standard order, but for informal speech it's quite acceptable.
The usual word order ("inverted") would be "Ask her what her hair color is." That would always be considered grammatical at any level of formality.
"Ask her her hair color." is also idiomatic and easily understood. It sounds fine, not weird (to me).


text:
Q: JMeter - How to extract Properties data from the Sample Result tab After using JMS Subscriber, is it possible to extract the Properties data from the Sample Result tab.
Response headers:
JMSCorrelationId null
JMSMessageId     ID:yyy-me-me-7:1:1:1:1725
JMSTimestamp     1400089667055
JMSType          null
JMSExpiration    0
JMSPriority      4
JMSDestination   topic://xyz
Properties:
NAME    3bdfe64dd452.xxx
PATH
TYPE    XXX
OP      CREATE
REL

SampleResult fields:
ContentType:
DataEncoding: null

Any help would be appreciated.

A: You can extract JMS headers normally using Regular Expression Extractor Post-Processor. For instance, if you want to get JMSMessageId

*

*Add Regular Expression Extractor as a child of the request which returns above headers

*Configure it as follows:

*

*Field to check: Response headers

*Name of created variable: anything meaningful, i.e. JMSMessageId

*Regular Expression: JMSMessageId (.*)

*Template: $1$

*That's it, now you should have the value stored in JMSMessageId JMeter Variable and will be able to refer it as ${JMSMessageId} where required. The value can be validated using Debug Sampler

If you want to store all headers change your Regular Expression to be (?s)(^.*).


text:
Q: OpenGL auto code generator from a vector image Is there any kind of application, tool, lib, ... that generates OpenGL functions from a vector image?
To avoid any misunderstanding: I don't want to render something like an SVG file in my 2D OpenGL project, I want to create vector image in my favourite vector app and convert it to OpenGL code instead of create it by code. That will saves lots of time.

A: Don't generate OpenGL code. Store the vertex data in a form that's ready to load into a VBO. It's OK to generate code for the data — something like this:
struct { float position[3]; float texcoord[2]; float color[4]; } vertices[] =
{
    // Auto-gen code here...
    { {1, 1, 0}, {0, 1}, {1, 0, 1, 1} },
    ...
};

But you might find that it's just as easy (and faster to compile) if you memory map the data straight in from a binary data file. Of course, the code version has the advantage of living right inside your executable without having to mess around with app resources, which in turn has the disadvantage of not letting you change the vector image without a recompile.


text:
Q: arraylist with object type hi i using arraylist and storing simple object array in that , my sample code snipt
  ArrayList rows = new ArrayList();

        object[] objs = new object[3];

        objs[0] = 1;
        objs[1] = "dilip";
        objs[2] = 27;
        rows.Add(objs);

        objs = new object[3];

        objs[0] = 2;
        objs[1] = "lucky";
        objs[2] = 42;
        rows.Add(objs);

        objs = new object[3];
        objs[0] = 3;
        objs[1] = "user";
        objs[2] = 46;
        rows.Add(objs);
        objs = new object[3];
        objs[0] = 4;
        objs[1] = "testing";
        objs[2] = 76;
        rows.Add(objs);
        objs = new object[3];
        objs[0] = 5;
        objs[1] = "trying";
        objs[2] = 44;
       rows.Add(objs);

How can i apply asc or desc sorting on any index of object
for example sorting based on name which index 1 or sorting based on age which index 2 ..
please provide any suggestion .
Thanks ..

A: Most of LINQ methods will work with a strongly typed IEnumerable<T> interface.
Use OfType method like this rows.OfType<object[]>().OrderBy(x => x[1])
Though the way you approach your data structures will quickly make the code unmaintainable. You'd better consider using classes to reflect your data.

A: Is there a reason you could not use List<object[]> instead of using ArrayList?
For example:
List<object[]> rows = new List<object[]>();

object[] objs = new object[3];

objs[0] = 1;
objs[1] = "dilip";
objs[2] = 27;
rows.Add(objs);

var query = rows.Where(r => (string)r[1] == "dilip");

You could then do all your various sorting, etc.
var query = rows
    .OrderBy(r => (int)r[0])
    .OrderBy(r => (string)r[1])
    .OrderByDescending(r => (int)r[2]);

A: You need to have comparer to sort your ArrayList type. In your case it would look something like this:
public class MyComparer : IComparer
{
    int IComparer.Compare(Object x, Object y)
    {
        int sortingIndex = 1;

        var xUnbox = x as object[];
        var yUnbox = y as object[];

        return ((new CaseInsensitiveComparer()).Compare(yUnbox[sortingIndex], xUnbox[sortingIndex]));
    }
}

Having this, you can now sort your ArrayList:
var comparer = new MyComparer();
rows.Sort(comparer);

foreach (object[] line in rows)
{
    Console.WriteLine(line[1]);
}

This example would sort your ArrayList by index 1.
Although I would highly recommend using strongly typed collection, like List<YourType> instead, since then you could just Linq order that.


text:
Q: JSON DeserializeObject that has a list of strings [
  {
        "Title": "TOY STORY 4",
        "Genre": "COMEDY",
        "Actors": [
            "Tom Hanks",
            "Tim Allen",
            "Annie Potts"
        ],
        "Id": 1
    },
    {
        "Title": "The Matrix",
        "Genre": "Action",
        "Actors": [
            "Keanu Reeves",
            "Laurence Fishburne",
            "Carrie-Anne Moss"
        ],
        "Id": 2
    }
]

I have this JSON string that I want to convert C# object  :
public class Movies1
{
    public string Title { get; set; }
    public string Genre{ get; set; }
    public List<Actor> Actors { get; set; }
    public int id { get; set; }
}

public class Actor
{
    public string Actors { get; set; }
    public int Id { get; set; }
}

My deserialize code :
List<movies> = JsonConvert.DeserializeObject<List<Movies1>>(json);

I am getting the following error :

"ExceptionMessage": "Could not cast or convert from System.String to
XXXXX.Models.Actor.",
"ExceptionType": "System.ArgumentException",
"StackTrace": "   at Newtonsoft.Json.Utilities.ConvertUtils.EnsureTypeAssignable(Object
value, Type
initialType, Type targetType)\r\n   at Newtonsoft.Json.Utilities.ConvertUtils.ConvertOrCast(Object
initialValue, CultureInfo culture, Type targetType)\r\n   at
Newtonsoft.Json.Serialization.JsonSerializerInternalReader.EnsureType(JsonReader
reader, Object
value, CultureInfo culture, JsonContract contract, Type targetType)"

A: It seems the Actors is a list of strings, what you need is something like this:
public class Movies1
{
    public string Title { get; set; }
    public string GENRE { get; set; }
    public List<string> Actors { get; set; }
    public int Id { get; set; }
}

public class Root
{
    public List<Movies1> Movies { get; set; }
}

Then:
Root myDeserializedClass = JsonConvert.DeserializeObject<Root>(myJsonResponse);

A: It's because entry in "Actors" array cannot be deserialized to Actor class instance. It can be deserialized to string. So in your Movie class you should have "public List Actors { get; set; }".
In my the best approach for this would be to have to sets of classes - one for deserializing JSON with POCO objects. And the other with some additional properties not available in JSON (like adding id for actor since this isn't available in JSON). This way you separate your application's logic from storage and thus making it possible to change JSON format easily as well as evolve your logic without being constrained by JSON format.


text:
Q: Cannot access value of associative array in JavaScript Context: I am successfully reading a CSV file into an array with d3. The data consists of personal IDs (which occur multiple times) and of one item (out of A, B, C, D, E, F, G) associated with the ID. I want to summarize this data in a histogram-like way: I want to create a 2D associative array, which, for every ID and every item, stores the frequency of the item in all data rows containing the ID. The IDs are not continuous from 0 to n, but rather random numbers, that's why I want to use an associative array for the first dimension, too, rather than a normal array.
The following code works and returns just what I want at the call of console.log(results), at least, when I tap the expand sign.
However, calling console.log(results[0]) does not work, where 0 is an existing key in the results array, as it should be and as I can see in the console.
There are very similar questions on SO, and the answer is to use Object.keys(results) or JSON.stringify(results). But these do not work for me, either (see code).
I am very confused. In Python or Java this would be the easiest thing in the world. Why doesn't it work in JavaScript? And how can I make it work?
var results = {};

d3.csv("data.csv", data => {
    data.forEach(row => {
        if (!(row["id"] in results)) {
            results[row["id"]] = {"A": 0, "B": 0,"C": 0, "D": 0, "E": 0, "F": 0, "G": 0};
        }
        results[row["id"]][row["category"]]++;
    });
});

console.log(results);
// {}
// on expansion:
// 0: {A: 1, B: 5, C: 0, D: 0, E: 0, ...}
// 1: {A: 0, B: 3, C: 0, D: 1, E: 0, ...}
// ...

console.log(results[0]);
// undefined

console.log(results["0"]);
// undefined

console.log(Object.keys(results));
// []
// on expansion:
// length: 0

console.log(JSON.stringify(results));
// {}
// not expandable

Example of data.csv:
id,category
0,A,
0,B,
0,C,
0,C,
0,C,
1,D,
2,D,
2,E,
5,A,
5,B,
5,C,

SOLUTION:
Quentin is right that this is about asynchronicity, however I'd like to point out how I adapted the specific code:
The problem has been: The console.logs are executed before the results are calculated, because forEach() is an asynchronous function and d3.csv() is also an asynchronous function. The console is funny: When I click on the expand button, the results have already been calculated because some seconds have passed.

*

*So, I changed the asynchronous forEach function into a normal for loop.

*As there is no synchronous CSV-function in d3, I put the rest of the data-processing code inside the d3-CSV-callback.

Code:
var results = {};

d3.csv("data.csv", data => {
    for (key in Object.keys(data)) {
        row = data[key];
        if (!(row["id"] in results)) {
            results[row["id"]] = {"A": 0, "B": 0,"C": 0, "D": 0, "E": 0, "F": 0, "G": 0};
        }
        results[row["id"]][row["category"]]++;
    }
    console.log(results);
    // 0: {A: 1, B: 5, C: 0, D: 0, E: 0, ...}
    // 1: {A: 0, B: 3, C: 0, D: 1, E: 0, ...}
    // ...

    console.log(results[0]);
    // {A: 1, B: 5, C: 0, D: 0, E: 0, ...}

    // do all the consequent data processing in here
});


text:
Q: How to add distinct value in database using Entity Framework IEnumerable<WebsiteWebPage> data = GetWebPages();

foreach (var value in data)
{
    if (value.WebPage.Contains(".htm"))
    {
        WebsiteWebPage pagesinfo = new WebsiteWebPage();
        pagesinfo.WebPage = value.WebPage;
        pagesinfo.WebsiteId = websiteid;

        db.WebsiteWebPages.Add(pagesinfo);
    }
}
db.SaveChanges();

I want to add only distinct values to database in above code. Kindly help me how to do it as I am not able to find any solution.

A: Assuming that you need them to be unique by WebPage and WebSiteId
IEnumerable<WebsiteWebPage> data = GetWebPages();
foreach (var value in data)
{
    if (value.WebPage.Contains(".htm"))
    {
        WebsiteWebPage pagesinfo = new WebsiteWebPage();
        if (db.WebsiteWebPages.All(c=>c.WebPage != value.WebPage|| c.WebsiteId != websiteid))
        {
            pagesinfo.WebPage = value.WebPage;
            pagesinfo.WebsiteId = websiteid;
            db.WebsiteWebPages.Add(pagesinfo);
        }
     }
}
db.SaveChanges();

UPDATE
To optimize this (given that your table contains much more data than your current list), override your equals in WebsiteWebPage class to define your uniqueness criteria then:
var myWebsiteWebPages = data.select(x=> new WebsiteWebPage { WebPage = x.WebPage, WebsiteId = websiteid}).Distinct();
var duplicates = db.WebsiteWebPages.Where(x=> myWebsiteWebPage.Contains(x));
db.WebsiteWebPages.AddRange(myWebsiteWebPages.Where(x=> !duplicates.Contains(x)));

this is a one database query to retrieve ONLY duplicates and then removing them from the list

A: I assume that by "distinct values" you mean "distinct value.WebPage values":
// get existing values (if you ever need this)
var existingWebPages = db.WebsiteWebPages.Select(v => v.WebPage);
// get your pages
var webPages = GetWebPages().Where(v => v.WebPage.Contains(".htm"));

// get distinct WebPage values except existing ones
var distinctWebPages = webPages.Select(v => v.WebPage).Distinct().Except(existingWebPages);
// create WebsiteWebPage objects
var websiteWebPages = distinctWebPages.Select(v =>
    new WebsiteWebPage { WebPage = v, WebsiteId = websiteid});

// save all at once
db.WebsiteWebPages.AddRange(websiteWebPages);
db.SaveChanges();

A:    IEnumerable<WebsiteWebPage> data = GetWebPages();

                        foreach (var value in data)
                        {
                            if (value.WebPage.Contains(".htm"))
                            {
                                var a = db.WebsiteWebPages.Where(i => i.WebPage == value.WebPage.ToString()).ToList();
                                if (a.Count == 0)
                                {
                                    WebsiteWebPage pagesinfo = new WebsiteWebPage();
                                    pagesinfo.WebPage = value.WebPage;
                                    pagesinfo.WebsiteId = websiteid;
                                    db.WebsiteWebPages.Add(pagesinfo);
                                    db.SaveChanges();
                                }
                            }
                        }

This is the code that I used to add distinct data.I hope it helps

A: You can use the following code,
IEnumerable<WebsiteWebPage> data = GetWebPages();

var templist = new List<WebsiteWebPage>();
foreach (var value in data)
{
    if (value.WebPage.Contains(".htm"))
    {
        WebsiteWebPage pagesinfo = new WebsiteWebPage();
        pagesinfo.WebPage = value.WebPage;
        pagesinfo.WebsiteId = websiteid;

        templist.Add(pagesinfo);
    }
}
var distinctList = templist.GroupBy(x => x.WebsiteId).Select(group => group.First()).ToList();
db.WebsiteWebPages.AddRange(distinctList);
db.SaveChanges();

Or you can use MoreLINQ here to filter distinct the list by parameter like,
var res = tempList.Distinct(x=>x.WebsiteId).ToList();
db.WebsiteWebPages.AddRange(res);
db.SaveChanges();

A: In addition to the code sample Furkan Öztürk supplied, Make sure your DB has a constraint so that you cannot enter duplicate values in the column. Belt and braces approach.


text:
Q: dropzone - var this not working (xhr formdata) inside another function's callback the first click I have a register form with dropzone and I'd like to validate it (the fields) using a plugin. I call this plugin inside the dropzone init and inside its function's callback I process the dropzone queue and attach the form data.
The problem is that, the first time I click the Send button, nothing happens: it just enters the callback of the function and does nothing (myDropzone not working), only the console.log() (that I put for debugging).
This is the plugin I'm using:
(function($) {
    $.fn.formly = function(callback) {
        $('a#click').on('click', function() {
            if (callback) {

                var clientInfo = form.find(':input').serializeArray();

                clientInfo.splice(-1, 1);
                clientInfo.splice(-1, 1);

                // Password hash function
                var p = $('#reg_pwd').val(),
                    c = $('#confirm_pwd').val(),
                    shaObj = new jsSHA('SHA-512', 'TEXT');

                shaObj.update(p);
                var p_hash = shaObj.getHash("HEX"),
                    shaObj = new jsSHA('SHA-512', 'TEXT');

                shaObj.update(c);
                var c_hash = shaObj.getHash("HEX");

                callback(clientInfo, p_hash, c_hash);
            }
        });
    };
})( jQuery );

And this is the dropzone init:
init: function() {
    var myDropzone = this;

    $('#register').formly(function(clientInfo, p_hash, c_hash) {
console.log(myDropzone);
        myDropzone.processQueue();

        myDropzone.on('sending', function(data, xhr, formData) {
            formData.append('client_info', JSON.stringify(clientInfo)),
            formData.append('particular', 0),
            formData.append('reg_pwd', p_hash),
            formData.append('confirm_pwd', c_hash)
        });

    });

    myDropzone.on('success', function(file, response) {
        myDropzone.removeFile(file);
        console.log( 'Error: ' + response );
    });
}

I can see the object logged in the console.
It's like nothing (no xhr request) is sent to the server when I first click the button.
The second time I click "Send" it does work (it sends the xhr request) and I get a server response (myDropzone.on('success').
Why does it work after the first time? What Am I doing wrong and how can I fix this?

A: I have a vague idea of why the code is acting like that, but I lack the necessary knowledge (theory) to properly explain it.
Anyways, I (think) found a proper way of doing it, I hope it's up to the standards of good techniques. I'm now using a function to populate a scoped object in the dropzone init so that .on('sending') (that should be outside the plugin callback) can access the form data:
init: function() {

    var myDropzone = this,
        client = {};

    function getClientData(clientInfo, p_hash, c_hash) {
        client.clientInfo   = clientInfo;
        client.p_hash       = p_hash;
        client.c_hash       = c_hash;
        myDropzone.processQueue();
    };

    $('#register').formly(function(clientInfo, p_hash, c_hash) {

        getClientData(clientInfo, p_hash, c_hash);

    });

    myDropzone.on('sending', function(data, xhr, formData) {
        formData.append('client_info', JSON.stringify(client.clientInfo)),
        formData.append('particular', 0),
        formData.append('reg_pwd', client.p_hash),
        formData.append('confirm_pwd', client.c_hash)
    });

    myDropzone.on('success', function(file, response) {
        myDropzone.removeFile(file);
        console.log( 'Error: ' + response );
    })

}

I'll gladly accept another answer that explains the behavior of the original code and have a better approach (if any).


text:
Q: Additive Exact Functors Commute with Homology I am trying to prove the following:
Let $R$ and $A$ be rings, and let $\mathscr M_R$ and $\mathscr M_A$ be the categories of $R$ and $A$ modules respectively. Let $\mathrm T:$$\mathscr M_R$ $\to $$\mathscr A_R$ be an exact, additive, covariant functor. I want to prove that $\mathrm T$ commutes with homology, i.e., $H_i(\mathrm TM_\bullet)\cong\mathrm T(H_i(M_\bullet))$ for every complex $M_\bullet$, where $H_i$ is the ith homology.
Can someone teach me how to prove this? Thanks.

A: In fact there is even  a result for contravariant  functors:
In page 93 of the book "AN INTRODUCTION TO HOMOLOGICAL ALGEBRA" BY D.G.NORTHCOTT you can see:

Theorem 1. Let T(A) be an additive exact functor of  a single variable
  module and let X be a complex. Then  if T is covariant in A, we have,
  for each n a canonical isomorphism
  $$H_n(T(X))\cong T(H_n(X)).$$
  While if T is contravariant in A, this must replaced by an isomorphism
  $$H_n(T(X))\cong T(H^n(X)).$$
  In either case, the isomorphism  determines a natural equivalence between
  the two sides regarded as functors of X.

If this is not helpful, let me know.


text:
Q: The expected value of an order statistic for normal random variables Let $X_1$ and $X_2$ be a random sample from normal distribution with mean equal to zero and variance $\sigma^2$. Prove $E[X_{(1)}]= \frac{-\sigma}{\sqrt{\pi}}$.
May I have to standarize the sample? Looks like it has a lot of tricky parts. I don't know how to proceed.

A: We start with a little trick. Let $Y$ be the minimum of $X_1$ and $X_2$. Then
$$Y=\frac{1}{2}\left(X_1+X_2-|X_1-X_2|\right).$$
Since the $X_i$ have mean $0$, we have
$$E(Y)=-\frac{1}{2}E(|X_1-X_2|).$$
The random variable $X_1-X_2$ is normally distributed mean $0$, variance $2\sigma^2$.
If $W$ is normal with this mean and variance, the mean of its absolute value is $2\int_0^\infty wg(w)\,dw$, where $g(w)$ is the density function of $w$. Thus
$$E(Y)=\int_0^\infty -wg(w)\,dw.$$
But
$$g(w)=\frac{1}{2\sigma\sqrt{\pi}}\exp(-w^2/(4\sigma^2)).$$
To evaluate, make the substitution $u=w^2/(4\sigma^2)$. Then $du=\frac{w}{2\sigma^2}\,dw$, and we end up with
$$\int_0^\infty -\frac{\sigma}{\sqrt{\pi}}e^{-u}\,du.$$
This is $-\frac{\sigma}{\sqrt{\pi}}$.


text:
Q: How to assign an output to a shellscript variable? How to assign this result to a shell variable?
Input:
echo '1+1' | bc -l
Output:
2
Attempts:
(didn't work)
#!bin/sh
a=echo '1+1' | bc -l
echo $a

A: You're looking for the shell feature called command-substitution.
There are 2 forms of cmd substitution

*

*Original, back to the stone-age, but completely portable and available in all Unix-like shells (well almost all).
You enclose your value generating commands inside of the back-ticks characters, i.e.
$ a=`echo 1+1 | bc -l`
$ echo $a
2
$

*Modern, less clunky looking, easily nestable cmd-substitution supplied with $( cmd ), i.e.
$ a=$(echo 1+1 |  bc -l)
$ echo $a
2
$

Your 'she-bang' line says, #!/bin/sh, so if you're running on a real Unix platform, then it's likely your /bin/sh is the original Bourne shell, and will require that you use option 1 above.
If you try option 2 while still using #!/bin/sh and it works, then you have modern shell. Try typing echo ${.sh.version} or /bin/sh -c --version and see if you get any useful information. If you get a version number, then you'll want to learn about the extra features that newer shells contain.
Speaking of newer features, if you are really using bash, zsh, ksh93+, then you can rewrite your sample code as
a=$(( 1+1 ))

Or if you're doing more math operations, that would all stay inside the scope, you can use shell feature arithmetic like:
(( b=1+1 ))
echo $b
2

In either case, you can avoid extra process creation, but you can't do floating point arithmetic in the shell (whereas you can with bc).


text:
Q: Preserve unicode whitespace characters during .NET XmlSerializer deserialize I have a problem. I'm deserializing XML-document and performing a schema validation for it. This works fine but if a field value contains a Unicode whitespace character (Tab/U+0009), it will be replaced with a space.
I've narrowed this functionality down to schema validation. Without schema validation, the Unicode characters will be preserved. I believe the XmlReader performs normalization when performing the schema validation.
Here's the simplified code:
var settings = new XmlReaderSettings
{
    Schemas = ...,
    ValidationType = ValidationType.Schema,
    ValidationFlags = XmlSchemaValidationFlags.ReportValidationWarnings
}
// ...
// doc is XDocument
using (var reader = XmlReader.Create(doc.CreateReader(), settings)
{
    var deserializedObject = serializer.Deserialize(reader);
}

I found a suggestion to use XmlTextReader manually, but I can't set XmlReaderSettings for the reader that way. XmlTextReader would have a property Normalize that would (probably) fix my issue.
Another suggestion I found was to set XmlReader Normalization private property via reflection, but it seems that it has been removed in later versions as it seems it doesn't exist in .NET 6.
I can't edit the XML document or the schema file.
Any suggestions how to workaround this issue?


text:
Q: Jupyter extension for VSCode on Linux throws error when doing anything Jupyter related After installing code-oss on Manjaro Linux along with the Jupyter extension for code and jupyter-notebooks itself, the extension seems to error when I try to do anything Jupyter related inside code. If I try to create a new notebook from the command pallete, it pops up a dialog saying this:
Command 'Jupyter: Create New Jupyter Notebook' resulted in an error (command 'jupyter.createnewnotebook' not found)

Code then tells me that the extension activation failed and to open the chrome developer console for more information. This is what the chrome console then says:
extension activation failed Error: Extension 'ms-toolsai.jupyter' CANNOT use API proposal: notebookEditor. Its package.json#enabledApiProposals-property declares:  but NOT notebookEditor. The missing proposal MUST be added and you must start in extension development mode or use the following command line switch: --enable-proposed-api ms-toolsai.jupyter

Initial Pop-up error
Chrome Console error

A: Had the same problem and found out this is happening because of the open source version of code - OSS. It does not have the proper config in the product.json.
The accepted solution to add to Runtime Arguments unfortunately didn't work on Arch.
Easiest solution for me was to install code-features from AUR.
You can find more info on arch wiki site
Or directly on microsoft docs regarding oss code issues.

A: You can solve that problem by inserting"enable-proposed-api": ["ms-toolsai.jupyter"] in the start settings of vs code. So press CTRL+ALT+P -> "Preference: Configure Runtime Arguments" then insert the upper line. After that restart vscode.

A: The solution to add "enable-proposed-api": ["ms-toolsai.jupyter"] to the runtime of vscode didn't work for me on Arch linux. But when I started vscode from the command line using the argument "--enable-proposed-api  ms-toolsai.jupyter" the problem was solved. So I created a custom desktop launcher for this:
Fist, copy the desktop launcher to your applications folder
$ cp /usr/share/applications/code-oss.desktop ~/.local/share/applications/.

Then edit the new file:
$ nano ~/.local/share/applications/code-oss.desktop

Now add "--enable-proposed-api ms-toolsai.jupyter" to both of the Exec lines like so:
[Desktop Entry]
Name=Code - OSS
Comment=Code Editing. Redefined.
GenericName=Text Editor
Exec=/usr/bin/code-oss --enable-proposed-api ms-toolsai.jupyter --unity-launch %F
Icon=com.visualstudio.code.oss
Type=Application
StartupNotify=false
StartupWMClass=Code
Categories=TextEditor;Development;IDE;
MimeType=text/plain;application/x-code-oss-workspace;
Actions=new-empty-window;
Keywords=vscode;

[Desktop Action new-empty-window]
Name=New Empty Window
Exec=/usr/bin/code-oss --enable-proposed-api ms-toolsai.jupyter --new-window %F
Icon=com.visualstudio.code.oss

I restarted my computer and the problem was solved.


text:
Q: Ruby on Rails Update saving to wrong ID I have this site where a user can have many pets.  These pets are listed on there profile, and clicking on a pet takes them to that pets profile, where they have the option to edit the pet.  Loading the form for the pets works great, it gets the correct information for each one, but then there's the problem with updating.  Clicking submit on the edit form causes all updates to go to the first pet they have.  Like, if the have the pets with the IDs 2, 5 and 11, and updates on 5 or 11 go to 2.  I'm not quite sure what's going on.
Here are my edit and update actions for the PetsController:
#GET to /users/:user_id/pet/edit
def edit
  @user = User.find( params[:user_id] )
  @pet = Pet.find_by_id( params[:id] )
end

#PUT to /users/:user_id/pet/
def update
  #Retrieve user from database
  @user = User.find( params[:user_id] )
  #Retrieve user's pet
  @pet = @user.pets.find_by( params[:id] )
  #Mass assign edited pet attributes and save (update)
  if @pet.update_attributes(pet_params)
    flash[:success] = "Pet updated!"
    #Redirect user to profile page
    redirect_to user_path(id: params[:user_id] )
  else
    render action: :edit
    Rails.logger.info(@pet.errors.messages.inspect)
  end
end

I've tried different ways of finding the users pet, such as
@user.pet(params[:id])

That resulted in an error of it saying it couldn't find a pet without an ID, so next I tried
@user.pet.find_by_id(params[:id])

But that resulted in update_attribute not being defined, so I assumed I shouldn't be using find_by_id anyways
Is there another way I should be doing this perhaps?  I'm thinking the error is that the pet's ID isn't being passed in correctly.  If so, what could be a fix for that?  I tried passing the ID as a hidden field from the edit form, but that didn't work.
Here's what happens in the terminal when a user tries to update a pet
Processing by PetsController#update as HTML
Parameters: {"utf8"=>"✓",   "authenticity_token"=>"0tC+qRK01CMCEZWbDtJyZ4QNmXQxnaAPKT+anRKGKh5hTWekTbEHzAd+8 +YOVIWBB0/imVrMVNcpkeBR18SHNw==", "pet"=>{"color"=>"Darigan",  "species"=>"Yurble", "gender"=>"Male", "level"=>"25", "hp"=>"50",  "strength"=>"50", "defence"=>"50", "movement"=>"50", "uc"=>"1", "rw"=>"0", "rn"=>"0", "uft"=>"1", "ufa"=>"0", "description"=>"uiy7i77i7i", "id"=>"5",  "name"=>"Fouany", "hsd"=>"150"}, "user_id"=>"5"}
User Load (0.3ms)  SELECT  "users".* FROM "users" WHERE "users"."id" = ?  LIMIT ?  [["id", 5], ["LIMIT", 1]]
Pet Load (0.3ms)  SELECT  "pets".* FROM "pets" WHERE "pets"."user_id" = ? LIMIT ?  [["user_id", 5], ["LIMIT", 1]]
(0.1ms)  begin transaction
Pet Exists (0.2ms)  SELECT  1 AS one FROM "pets" WHERE "pets"."name" = ? AND ("pets"."id" != ?) LIMIT ?  [["name", "Fouany"], ["id", 2], ["LIMIT", 1]]
(0.1ms)  rollback transaction
Rendering pets/edit.html.erb within layouts/application
User Load (0.3ms)  SELECT  "users".* FROM "users" WHERE "users"."id" = ? ORDER BY "users"."id" ASC LIMIT ?  [["id", 5], ["LIMIT", 1]]
Rendered pets/edit.html.erb within layouts/application (12.4ms)
Profile Load (0.4ms)  SELECT  "profiles".* FROM "profiles" WHERE "profiles"."user_id" = ? LIMIT ?  [["user_id", 5], ["LIMIT", 1]]
{:name=>["has already been taken"], :color=>[], :species=>[], :gender=>[], :level=>[], :hp=>[], :strength=>[], :defence=>[], :movement=>[], :uc=>[], :rw=>[], :rn=>[], :uft=>[], :ufa=>[], :description=>[]}
Completed 200 OK in 202ms (Views: 136.1ms | ActiveRecord: 5.0ms)

As you can see, the pet's ID goes from 5 to 2 back from 5, so maybe that's somewhere to start for fixing the issue?
Any suggestions and advice is greatly appreciated!

A: @user.pets.find_by(params[:id])

Should be
@user.pets.find_by(id: params[:id])

A: If your user should have only one pet (the route suggests this), then the pet id is not needed to access it. You can get the pet by
@user = User.find( params[:user_id] )
@pet = @user.pet

Have a look at this comment in your code:
#PUT to /users/:user_id/pet/

It mentions the user_id, but not the id


text:
Q: WPF Binding to properties of an object with specific attributes I have a listbox to which I have bound the data context to an object. This object has a number of properties some of which will have a particular attribute.
What I want to do from this is to have the items source set to the properties of the object but to only display those properties that have a particular attribute set.
Can anyone help with where I would start on this?

A: You could use LINQ and reflection to get the values of the properties which have that attribute set:
Class1 class1 = new Class1 { Name = "Sam", DOB = DateTime.Now, SSN = "123" };

MyListBox.ItemsSource = from p in typeof(Class1).GetProperties()
                        where p.IsDefined(typeof(Att), false)
                        select p.GetValue(class1, null);

Name and DOB are marked as [Att] in my test, and their values are added to the ListBox. SSN is not.

A: One way is to build your data context object dynamically and bind the Visibility properties to properties on this dynamically built object.  You would then use it in the following way:
var provider = new MyDynamicProvider();
// Add the names of the properties with the particular attribute with
// initial values (found using reflection elsewhere).
provider.MyValues.Add("PropertyWithAttribute", "Test");
provider.MyValues.Add("PropertyWithAttributeVisibility", Visibility.Visible);
// Add properties that do not have the attribute
provider.MyValues.Add("PropertyWithoutAttributeVisibility", Visibility.Collapsed);
view.DataContext = provider.CreateDynamicWrapper();

In the view you can now do the following:
<TextBlock
    Visibility="{Binding PropertyWithAttributeVisibility}"
    Text="{Binding PropertyWithAttribute}"
    />


text:
Q: basename command not working as expected I wrote a shell script to convert a lot of JPGs at my end to pdf
 #!/bin/bash
set -xv
for i in `ls -v *.JPG`;
 do i=$(basename "$i")
 convert "$i" "$i.pdf" ;
 done

the JPGs are

DSCN2612.JPG  DSCN2618.JPG  DSCN2624.JPG

and the converted pdfs I get are having names

DSCN2612.JPG.pdf  DSCN2618.JPG.pdf  DSCN2624.JPG.pdf

Now note the use of basename command in my shell script I expect the resulting name of pdf to be

DSCN2612.pdf  DSCN2618.pdf  DSCN2624.pdf

Where is the output is different.
I am using Ubuntu 12.04 and basename --version shows

basename (GNU coreutils) 8.13 Copyright (C) 2011 Free Software
  Foundation, Inc. License GPLv3+: GNU GPL version 3 or later
  http://gnu.org/licenses/gpl.html. This is free software: you are
  free to change and redistribute it. There is NO WARRANTY, to the
  extent permitted by law.

when on a terminal I just type

basename DSCN2612.JPG
  I get the output
DSCN2612.JPG

where as I expect

DSCN2612

only  so is my understanding wrong or there is some error the way I am using this script.

A: The basename command has two uses, stripping path prefixes and (optionally) stripping suffixes.
To strip a path prefix, you can simply pass it a path, for example
basename /path/to/file.ext
# file.ext

To additionally strip a suffix, you need to tell basename the suffix you wish to strip, for example
basename /path/to/file.ext .ext
# file

basename DSCN2612.JPG .JPG
# DSCN2612

So, basename won't "auto-detect" a suffix because in unix, files don't necessarily have suffixes.  In other words, letters after a period aren't necessarily suffixes, so you need to explicitly tell it what suffix to strip.
There are some bash-specific alternatives to "auto-detect" and strip, however.  For example,
x="file.ext"
echo ${x%.*}
# file

Without knowing more, I might write your script as
for jpg in *.JPG; do
    base=${jpg%.*}
    convert "$jpg" "$base.pdf"
done


text:
Q: What is the best way to update firebase database? I am wondering if somebody could give me some advice regarding a firebase database.
I am going to create a firebase database, where I want to store around 1000 to 1500 events.
I am going to be running a script which will retrieve these 1000 to 1500 events from multiple API's, every hour. Every event also has a score which can be different from the hour.
But here's my problem: I am doubting if I should loop through all the events and check if the score variable is different from the older one and update it accordingly.
Or that it' more efficient/faster to clear the database everyhour and than add all events again?
Thanks in advance!


text:
Q: calling the correct virtual method using member function pointer In the example below, where I tried to reduce the problem to its minimal, there are 4 classes A,B,C,D., which form an inheritance hierarchy
When the program starts, an object d from class D is created and the test method of the D class is called. This method in turns calls the caller method of the C class. This method tries to use member function pointer to call the correct f method. In this case it should call the f method associated to class D but it calls the one associated to class B.
How come ?
class A {
    public:
    virtual void f() = 0;
};

class B : public A{
    public:
    virtual void f() { cout << "IN B" << endl;}
};

class C : public B{
    public:
    virtual void f() { B::f(); cout << "IN C" << endl; }
    virtual void caller(){
        void (A::*cb)() = NULL;
        cb = &A::f;
        (this->*cb)();
    }
};

class D : public C{
    public:
    virtual void f() { C::f(); cout << "IN D" << endl; }
    void test(){
         caller();
    }
};

int main(){
    D d;
    d.test(); // Why does this prints only "IN B"
    return 0;
}

UPDATE : The code actually works, the problem had nothing to due with the presented code and seemed to come from a version mismatch between the library providing class A,B,C and the one providing class D.

A: You sure it prints only "IN B"? I compile it on MSVC2012, I got
IN B
IN C
IN D

What's more, your original code does not compile on VS2012, at least not before I add public: to every class. e.g.:
class C : public B{
public:  // <--- here
    virtual void f() { B::f(); cout << "IN C" << endl; }
    virtual void caller(){
        void (A::*cb)() = NULL;
        cb = &A::f;
        (this->*cb)();
    }
};

A: It prints
IN B
IN C
IN D

So, the problem is somewhere else.

A: it works. add public: declaration. also warning about different behavior of overloading and virtualisation. best approach is to use pointer or reference.
class A {
public:
    virtual void f() = 0;
};

class B : public A{
    public:
    virtual void f() { std::cout << "IN B" << std::endl;}
};

class C : public B{
    public:
    virtual void f() { B::f(); std::cout << "IN C" << std::endl; }
    virtual void caller(){
        void (A::*cb)() = NULL;
        cb = &A::f;
        (this->*cb)();
    }
};

class D : public C{
    public:
    virtual void f() { C::f(); std::cout << "IN D" << std::endl; }
    void test(){
         caller();
    }
};

output:

IN B
  IN C
  IN D


text:
Q: GAE (Python) Cloud Resource Manager - Permission denied I am trying to create a project using the appengine urlfetch but I get a 403 "The caller does not have permission" error. I'm running this code in production, which should be given permission automatically.
Here's the code:
from google.appengine.api import app_identity
from google.appengine.api import urlfetch
import json

project_data = {
    'projectId': 'test-project-84873',
    'name': 'TEST PROJECT'
}

auth_token, _ = app_identity.get_access_token('https://www.googleapis.com/auth/cloud-platform')
response = urlfetch.fetch(
    'https://cloudresourcemanager.googleapis.com/v1/projects',
    payload = json.dumps(project_data),
    method = urlfetch.POST,
    headers = {
        'Authorization': 'Bearer {}'.format(auth_token),
        'Content-Type': 'application/json'
    }
)

My API has been enabled, and I was able to successfully create a project using the APIs Explorer at the bottom of this page https://cloud.google.com/resource-manager/reference/rest/v1/projects/create
If I run the same code but with GET instead of POST, it successfully returns the current project information.
Thanks
EDIT
Strangely, this code works perfectly on my local development server, just not in production... ???
EDIT 2
I tried to use the Python Client Library which I found near the bottom of this page: https://cloud.google.com/docs/authentication
The code:
from oauth2client.client import GoogleCredentials
from apiclient.discovery import build

credentials = GoogleCredentials.get_application_default()
service = build('cloudresourcemanager', 'v1', credentials=credentials)

project_data = {
    'projectId': 'project-test-12345',
    'name': 'YAY NEW PROJECT'
}
projects = service.projects().create(body=project_data).execute()

I get the same result. It works locally, but not in production :(


text:
Q: how can I fix position of divs in html? when I zoom-in, zoom-out my web page the position of all divs and items get disturbed.and when I again reset zoom to 100% it comes fine.Even this problem comes when open the same page in big screen laptop.How can I fix the div position.some of my css code-
/* hbg */
.hbg {
background-color:transparent;
float:left;
margin:2px 0 0 45px;
padding:65px 456px 0 56px;
width:137px;
height:190px;
background:#fff url(images/hbg_img.jpg) no-repeat top left;
}

/*solutions*/
.solu{ background-color:transparent;}
.solu_resize { margin:0 auto; padding:0; width:auto;}
.solu .smenu ul { margin:0 0 0 45px; padding:0; float:left; width:auto; list-         style:none;}
.solu .smenu ul li { margin:0 0; float:left;}
.solu .smenu ul li a { display:block; margin:0; padding:0; color:#5f5f5f; text-    decoration:none;}
.solu_resize img{ float:left; padding:0 0 0 0;}
........

A: This is because you provided absolute widths with floating elements. If you change the screen-size, the elements seem to be unsorted, because they are still of the specified size. Maybe size-definitions in percentage can help you out with this issue.

A: Zoom-in and zoom-out means different things on different browsers.  For instance on FF, you can zoom in "text-only."  When the zoom feature affects text size, absolutely positions divs get messed up as you saw.
You can fix this problem by designing your page to be "elastic."  Instead of using pixels, you define both coordinates and measurements in "em" units.  An em is equal to the browser default text-size, which is usually 16px.  To make life easier, reset em to 10px by putting the following in your stylesheet:
body {
font-size: 62.5%;
}

If the above code is in your style sheet, you can convert your pixels to em easily by dividing each pixel value by 10.  For instance, using your code above:
margin:.2em 0 0 4.5em;
padding:6.5em 45.6em 0 5.6em;
width:13.7em;
height:19em;

This should fix the zoom problem and also allow people to change text-size when viewing your page.  This won't work for your sprites and you may still run into overlapping issues.  If it gets messy, you may have to consider changing your layout approach.  If you do experience overlap, I'd suggest you use overflow:hidden on all your divs and specify max-height and max-width where appropriate.
If you need to read more about ems and elastic design, here's a good tutorial: http://jontangerine.com/log/2007/09/the-incredible-em-and-elastic-layouts-with-css
And here's the W3 reference on max-height:
http://www.w3schools.com/Css/pr_dim_max-height.asp


text:
Q: command to find port used by IIS 6.0 website Given the name of a website and an app pool in IIS 6.0, is there a command that can list the port number used by that website?

A: Cscript.exe adsutil.vbs get W3SVC/1234/ServerBindings
where 1234 is the website Identifier number found in IIS Manager "Web Sites" list.


text:
Q: Linearity of fourier series I am given the following function:
$$ g(x) =
\begin{cases}
sin(\frac{\pi^2}{x}),  & x \in[-\pi,\pi),x\neq0 \\
0, & x=0
\end{cases}$$
It's fourier series is: $\sum_{n=1}^\infty b_nsin(nx)$
Now I am trying to find the fourier series of $f(x) :=g(x)+1$.
I want to say that the series is $1+\sum_{n=1}^\infty b_nsin(nx)$, but why is this allowed? I know that $\hat f(n)+\hat g(n) = \widehat {(f+g)}(n)$ ($\hat f(n)$ denotes the n fourier coeffiecient of f). But can I conclude that I am allowed to add the series ? or is it only allowed in case both of the series absolutely converge?
Edit:
Basically that I'm trying to prove is the following:
$$\sum_{n \in \Bbb Z} (\hat g(n)+1)e^{inx} = \sum_{n \in \Bbb Z} \hat g(n)e^{inx}+\sum_{n \in \Bbb Z}1e^{inx} = \sum_{n \in \Bbb Z}\hat g(n)e^{inx}+1$$
(The first quailty is what I don't get)

A: 1 is orthogonal to all the terms $\sin(nx)$. In fact, it is one of the basis elements for Fourier series $\{1,\cos(nx),\sin(nx) \}$, which form an orthogonal basis.
Edit:
Your equations are incorrect. It should read as follows, with f(x)=1
\begin{equation}
\sum\widehat{(g+f)}e^{inx}
=
\sum(\widehat{g}+\widehat{f})e^{inx}
=
\sum\widehat{g}e^{inx} +\sum\widehat{f}e^{inx}
=
\sum b_n \sin(nx) + 1
\end{equation}
Note that the only nonzero Fourier coefficient of 1 is the constant term.

A: The type of Fourier series is no longer the same because you no longer have the same boundary condition. Accordingly you become forced to include a constant term as one of your basis functions. But unlike what you wrote, making this change does not add $1$ to each Fourier coefficient. It just adds in a term, say $\phi_0(x)=1$ so that $b_0=1$.


text:
Q: Simple CUDA kernel with Bizarre Result? I am using a CUDA kernel object in MATLAB in order to fill a 2D array with all '55's. The result is very strange. The 2D array only fills up to a certain point as shown below. After row 1025, the array is all zeros. Any idea what could be going wrong?

A: As I mentioned in the comment above, you are mistakenly offsetting the matrix rows. The code below is a full working example proving this point.
#include<thrust\device_vector.h>

__global__ void myKern(double* masterForces, int r_max, int iterations) {

    int threadsPerBlock = blockDim.x * blockDim.y;
    int blockId         = blockIdx.x + (blockIdx.y * gridDim.x);
    int threadId        = threadIdx.x + (threadIdx.y * blockDim.x);
    int globalIdx       = (blockId * threadsPerBlock) + threadId;

    //for (int i=0; i<iterations; i++) masterForces[globalIdx * r_max + i] = 55;
    for (int i=0; i<iterations; i++) masterForces[globalIdx * iterations + i] = 55;

}

void main() {

    int ThreadBlockSize = 32;
    int GridSize        = 32;

    int reps            = 1024;
    int iterations      = 2000;

    thrust::device_vector<double> gpuF_M(reps*iterations, 0);

    myKern<<<GridSize,ThreadBlockSize>>>(thrust::raw_pointer_cast(gpuF_M.data()),reps,iterations);

    int numerrors = 0;
    for (int i=0; i<reps*iterations; i++) {
        double test = gpuF_M[i];
        if (test != 55) { printf("Error %i %f\n",i,test); numerrors++; }
    }

    printf("Finished!\n");
    printf("The number of errors is = %i\n",numerrors);
    getchar();

}


text:
Q: Google Maps: Display the current users location with a custom marker I have the following example that displays the current users location on a Google map: http://dev.driz.co.uk/googlemap/
As you can see I have three pieces (I have borrowed Foursquare icons for the demo):
1.) The marker where the user is located
2.) The avatar of the user (note this may changed dependant if the user is logged in or not and has a custom avatar or just has the mystery man)
3.) The avatar frame that sits on top of BOTH the avatar and the marker.
What I want to do is make it so that the avatar sits nicely inside the frame perhaps as a background image instead if that's possible? Not seen anything in the docs about this, but the frame needs to be above the avatar so it creates the rounded corners mask.
And also I want them to fall down all together as sometimes the frame appears below the marker dot and not always on top as it should be. So they need to act as one piece and drop at the same time.
Can anyone with Google Map knowledge help me out with these two parts? Thanks

A: There are a couple things worth noting about the entire animation as it stands:

*

*Marker z-index is inconsistent during animation since it is not set until the marker is in its final position, so the only thing you can really do to control that during the drop is to order your calls to each marker's setMap function as best as you can to coax them to stack in order while dropping. That means calling the back-most object's function first, proceeding to closer images in the stacking order. Once the animation is done, however, they will invariably be in the correct order.

*In order to control the order of the setMap calls, you're going to have to uniquely name the variables that store your Marker objects.

*Markers aren't added to the map and animated until they load, so it would probably be best to create image objects in code and pre-load your images, then set the marker animation as a callback from the onload event once they're all finished.

Even with all this in place, the images are still going to drop individually so it may not have exactly the effect you're looking for, but this is probably the way to get it as close as can be managed.
Setting Z-Index
First, the z-index of your markers can be easily set as one of the MarkerOptions you pass in to the Marker constructor:
var marker1 = new google.maps.Marker({
    animation: google.maps.Animation.DROP,
    position: pos,
    map: map,
    icon: image1,
    zIndex: 1
});

Setting Icon Anchoring
Next, to change the positioning of the image you provide to the marker, the MarkerOptions object can contain MarkerImage as its icon member, so use this object to indicate the anchor of your icon:
var image1 = new google.maps.MarkerImage(
    "http://dl.dropbox.com/u/1597153/00000000000000000000000000000000.png",
    null,
    null,
    new google.maps.Point(16, 49));

The second and third parameters are optional and will be constructed for you if not specified, so we are really only interested in providing a value for the anchor parameter.
Creating an Image OnLoad Callback
If you're going to pre-load the images, which I highly recommend, do so by creating three image objects, binding an OnLoad handler to each object, and then setting the image's src property—in that order. Your code to create markers and add them to the map should only happen once all three images have loaded.
// Create image objects to force pre-loading
var domImg1 = new Image(),
    domImg2 = new Image(),
    domImg3 = new Image();

// Instantiate variables for iteration
var images = [domImg1, domImg2, domImg3],
    j = 0;

// Bind an OnLoad handler that checks to see if all three images have been pre-loaded
for (i in images) {
    images[i].onload = function() {
       if (++j == 3) {
           // Create markers and add to map here
       }
     }
}

// Set the src property to start the download and trigger the onload events
domImg1.src = "http://dl.dropbox.com/u/1597153/00000000000000000000000000000000.png";
domImg2.src = "http://dl.dropbox.com/u/1597153/pin-white.png";
domImg3.src = "http://dl.dropbox.com/u/1597153/marker.png";

I've provided a working demo of the techniques I've demonstrated here on this Fiddle, so check it out and it will hopefully give you an idea of how it comes together.


text:
Q: Ideas on how to organize a project I know that questions that are mainly there to be discussed are not liked very much, but I still hope that you can think with me and give me some ideas. So thanks in advance to those of you, who are willing to help :)
I'm very new in Wordpress Development and I am facing some problems on how to organize all the files. For a better understandig I will split all the questions up.
Author rights
I'm developing a site for several authors and I only want them to have access to some pages. For example they shouldn't be able to see in the backend or edit the legal sites, the contact site, the homepage and so on.
As my site has static pages and a blog it isn't enough to restrict their access to the blog.
So how can I have several types of static pages?
Custom post types
My idea was to create some custom post types. One for all the sites they shouldn't edit, one for the Practical courses and one for the Theory. There it would be very easy to restrict access to the administrator only and it would clear up the backend, because the posts and pages would be sorted within their topics.
The problem I have with this is that I want the permalink structure %postname%. With my actual custom post types I wasn't able to get it working with that permalink. I always got a 404. Then I saw a plugin that allowed you to set the permalink structure to %postname% and it worked well, but now I was forced to have the slug in there too. And well, you maybe guessed it: I don't want it to be in there for some post types, while on others it would be great to have it. Remember: I just wanted to have a custom taxonomy for the restricted pages, like the contact page, the legals page and so on.
So at the moment, my permalinks would be something like this: http://www.example.com/cpt-slug/contact
I do want it to be http://www.example.com/contact
Now I saw a plugin that allows you to remove the slug from all the CPT, but for the practical courses and the theory I want to have them there, because it is more clear for the user.
How can I remove the slug from a custom post type in the permalink structure %postname%, without removing the slug on all the CPTs?
Custom taxonomies
Furthermore I would like to be able to have an "intelligent" search.
If a user enters to a site and searches something, he should only get results of that page and all the sub-pages of that page.
The hierarchy looks like this:

Practical courses (custom post type)

*

*Qualitative analysis (parent taxonomy category)

*

*Proofs for anions (child taxonomy category)

*

*Sulfate (Post)

*Phosphate (Post)

*Sulfide (Post)

*Proofs for cations (child taxonomy category)

*Quantitative analysis (parent taxonomy category)
Theory (custom post type)

*

*Statistical thermodynamics (parent taxonomy category)

*

*Partition function (Post)

*Schrödinger equation (parent taxonomy category)

You can see what my idea was on how to solve this problem. With these taxonomy categories, it should be easy to get the wanted intelligent search, BUT as far as I know WordPress has no function to display the taxonomy categories. And I have to be able to do so, because the pages Practical courses, Qualitative Analysis, Proofs for Anions are pages that only list their subpages. Oh, and before I forget, it isn't enough tho get a simple list with the different taxonomy categories, because we have thumbnails for each category. So I also need a method to set a thumbnail to these categories and than display them nicely on a page.
So on Practical courses you are able to click on Qualitative Analysis, Quantitative analysis, or other courses. You are then redirected to that page. That page, lets say Qualitative Analysis lists all the subpages of itself. So on that page you would be able to click on Proofs for anions, Proof for cations and so on. And now, when clicking on, lets say Proofs for anions, you will see a list of all the proofs. When clicking one, the post will open and you can read.
I'm coming back to the search for a second: If you search for something on the homepage, the whole database should be searched for that keyword and you'll get all the results. When searching for something on the Practical courses site, you should only get results that show up in this branch of the hierarchy. No results of the Theory should be shown. A search inside Qualitative analysis should only return results that are on that page or on ALL the subpages of itself. Same for all the other search forms.
So the search should never return results from parent pages.

So that were my questions with my ideas on how to solve them and the problelms I have with my solutions.
My main question to you, as more experienced WordPress developers, is the following: Are my ideas good, and should I do it like mentioned, or are there better ways to acieve what I'm trying to get? If my ideas a good, could you please help me around my problems?
Again, thank you very much!!

A: You find it difficult to explain because it is still unclear what you are trying to achieve, even for you.
I think you should go over each of the obstacles/problems you face and formulate a clear question and ask again.
The way this is brought up, we could have millions of answer and a lot based on opinions and that is, like you said it, considered off topic here and for good reasons.
It's fairly easy to check a user role/capability and grant or restrict access to certain features, categories, settings, post type, etc. and etc. based on that.
You are saying that you don't want authors to modify /legal page, /contact page, etc. This looks like a job for current_user_can( 'manage_options' )  checks (only admins can manage options, not authors) and show, hide, redirect,  according to capabilities.
You say search form on page A should return page A results.  This looks like a job for a custom query maybe filtering by categories.
So again, I would dissect your project and ask questions related to specific obstacles you face so we could better assist you on those specific issues.  And remember that big sites and business are also using WordPress in complex and less complex situations, so a lot is possible when we our end objective is clear.