text:
Q: Angular 2 component directive not working with service I am a beginner in angular 2 and I am building my first App whilst following a Pluralsight Course.
I am using TypeScript.
I have the a particular component (named: property-detail.component.ts) in which I am trying to reference the directives from a service (property.service.ts).
I am registering the service in the root module and am injecting the services into the component using the "contructor" method.
In the one component (property-list.component.ts) i call a list of products and this works fine.
I then try call the same service in the (property-detail.component.ts) in which i only want to show details of a single property, but when i run the app, i get the following error
ERROR MESSAGE
    {node_modules/@angular/core/bundles/core.umd.js:3462 EXCEPTION: Uncaught (in promise): Error: Error in app/property/property-detail.component.html:9:42 caused by: Cannot read property 'propertyName' of undefined
TypeError: Cannot read property 'propertyName' of undefined
    at _View_PropertyDetailComponent0.detectChangesInternal (PropertyDetailComponent.ngfactory.js:284:62)}

I am using a single app module (app.module.ts) for the entire application to simplify it for myself.
Here are the components and the modules:
app.module.ts
import { NgModule } from '@angular/core';
//brownermodule exposes the ngIg and ngFor directive
import { BrowserModule } from '@angular/platform-browser';
import { FormsModule } from '@angular/forms';
import { HttpModule } from '@angular/http';
import { RouterModule } from '@angular/router';

import { AppComponent } from './app.component';
import { PropertyListComponent } from "./property/property-list.component";
import { PropertyCityFilterPipe } from "./property/property-cityfilter.pipe";
import { StarComponent } from "./shared/star.component";
import { PropertyDetailGuard } from "./property/property-guard.service";
import { PropertyDetailComponent } from "./property/property-detail.component";
import { WelcomeComponent } from "./home/welcome.component";
import { PropertyService } from "./property/property.service";

@NgModule({
    imports: [
        BrowserModule,
        FormsModule,
        HttpModule,
        RouterModule.forRoot([
            { path: 'property', component: PropertyListComponent },
            { path: 'property/:id',
                canActivate: [PropertyDetailGuard],
                component: PropertyDetailComponent
            },
            { path: 'welcome', component: WelcomeComponent },
            { path: '', redirectTo: 'welcome', pathMatch: 'full' },
            { path: '**', redirectTo: 'welcome', pathMatch: 'full' }

        ])

    ],
    declarations: [
        AppComponent,
        PropertyListComponent,
        PropertyCityFilterPipe,
        StarComponent,
        PropertyDetailComponent,
        WelcomeComponent,

    ],

    providers: [PropertyDetailGuard, PropertyService],
    bootstrap: [ AppComponent ]
})
export class AppModule { }

property.service.ts
import { Injectable,    } from "@angular/core";
//import { IProperty } from "./property";
import { Http, Response } from "@angular/http";
import { Observable } from "rxjs/Observable";
import "rxjs/add/operator/catch";
import "rxjs/add/operator/do";

import "rxjs/add/operator/map";

import { IProperty } from "./property";

@Injectable()
export class PropertyService {
    private _propertyUrl = 'api/property/property.json';

    constructor(private _http: Http) { }

    getPropertys(): Observable<IProperty[]> {
        return this._http.get(this._propertyUrl)
            .map((response: Response) => <IProperty[]>response.json())
            .do(data => console.log('All: ' + JSON.stringify(data)))
            .catch(this.handleError);
    }

    getProperty(id: number): Observable<IProperty> {
        return this.getPropertys()
            .map((property: IProperty[]) => property.find(p => p.propertyId === id));
    }

    private handleError(error: Response) {
        // in a real world app, we may send the server to some remote logging infrastructure
        // instead of just logging it to the console
        console.error(error);
        return Observable.throw(error.json().error || 'Server error');
    }
}

property-list.component.ts
import { Component, OnInit } from "@angular/core";
import { IProperty } from "./property";
import { PropertyService } from "./property.service";

@Component({
    moduleId: module.id,
    templateUrl: 'property-list.component.html',
    styleUrls: ['property-list.component.css']
    })

export class PropertyListComponent implements OnInit {
    pageTitle: string = 'Rental Listings';
    imageWidth: number = 120;
    imageMargin: number = 2;
    listFilter: string;
    errorMessage: string;

    property: IProperty[];

    constructor(private _propertyService: PropertyService) {

    }

    ngOnInit(): void {
        this._propertyService.getPropertys()
            .subscribe(property => this.property = property,
                        error => this.errorMessage = <any>error);

    }

    onRatingClicked(message: string): void {
         this.pageTitle = "Property: " + message;
    }

}

property-detail.component.ts
import { Component, OnInit, OnDestroy } from "@angular/core";
import { ActivatedRoute, Router } from "@angular/router";

import { Subscription } from "rxjs/Subscription";

import { IProperty } from "./property";
import { PropertyService } from "./property.service";

@Component({
    templateUrl: 'app/property/property-detail.component.html'
})

export class PropertyDetailComponent implements OnInit, OnDestroy {
    pageTitle: string = 'Property Detail';
    property: IProperty;
    errorMessage: string;
    private sub: Subscription;

    constructor(private _route: ActivatedRoute,
                private _router: Router,
                private _propertyService: PropertyService) {
    }

    ngOnInit(): void {
        this.sub = this._route.params.subscribe(
            params => {
                let id = +params['id'];
                this.getProperty(id);
            });

    }

    ngOnDestroy() {
        this.sub.unsubscribe();
    }

    getProperty(id: number) {
        this._propertyService.getProperty(id).subscribe(
            property => this.property = property,
            error => this.errorMessage = <any>error);
    }

    onBack(): void {
        this._router.navigate(['/property']);
    }

    onRatingClicked(message: string): void {
        this.pageTitle = 'Property Detail: ' + message;
    }
}

property-detail.component.html (you will see that i only inserted a single directive - {{property.propertyName}} to simplify things

        {{pageTitle}}

Name:

{{property.propertyName}}

Code:

Description:

Availability:

Price:

5 Star Rating:

             Back

Any assistance in this regard will be highly appreciated

A: put *ngIf="property" inside tag {{property.propertyName}} else before the subscriber return value and when render the template property.propertyName is undefined – alehn96 14 hours ago


text:
Q: Postgres FTS. Tweak parsing behavior Question is regarding FTS configuration.
SELECT * FROM ts_debug('english',
  '1056
01:31:06,375 --> 01:31:11,004
I hear it. I think there''s some guys
coming this way, a lot of them.

1057
01:31:11,172 --> 01:31:12,678
We gotta get out of here.');

I have a plenty of series subtitles that contains time intervals where in episode this phrase is takes place, like for example
01:31:06,375 --> 01:31:11,004.

When FTS parses text it segregates whole interval to individual integers like it shown in example above.
Is it any way to make FTS to parse this intervals as intervals or at leas as 2 timestamps?

A: Pre-process the string with
regexp_replace(searchstring, '(\d\d):(\d\d):(\d\d),(\d\d\d)', '\1\2\3\4', 'g')

Then 01:31:12,678 will turn to 013112678, which will work fine with full text search.

redpajama_set_name: RedPajamaStackExchange


text:
Q: In Visual Studio, how do you print the list of breakpoints to a file? I'd like to print a list of my breakpoints to a file, but I don't see a way to do it other than taking a screenshot of the Breakpoints window and printing that. Searching the Internet for "print breakpoints Visual Studio" brings up a lot of information about getting breakpoints to print information, but not about how to print out the breakpoints themselves.
As a bonus, I'd like to display more information within the Breakpoints window as well as in the file that I can (ideally) print out to. In particular, I'd like to be able to add a column to display the full filepath for the breakpoint. I would expect to see such an option under Tools/Settings, but I don't.

A: In versions of Visual Studio that include the Nuget Package Manager (VS 2012+ or VS 2010 with the Nuget plugin) you can use the Package Manager Console (View -> Other Windows -> Package Manager Console).  The console is a Powershell console and has been injected with a variable $dte which represents the Visual Studio automation interface.
You can get to the breakpoints using the $dte.Debugger.Breakpoints property, which you can then output to a file using the following command:
$dte.Debugger.Breakpoints | select Name  | Out-File breakpoints.txt

This will output the Filename, line number and character of each breakpoint to the file breakpoints.txt.
You can select any of the properties of the Breakpoint Interface and do any other formatting using Powershell prior to sending the output to the file.

A: I now see that it's possible to export breakpoints to an XML file (by clicking the first curved arrow near the top of the Breakpoints window). The XML contains, among other information, the full path to each file, which is more than the GUI displays. Of course, the XML file contains a lot more information than I would want to print, but I could process it, manually or automatically, to make it more manageable.


text:
Q: JQuery onclick toggle on elements with diffrent id I have a table with a status column that displays a material icon play/pause depending on the status. Each row has a different ID, my problem is that I can't make the icon toggle onclick unless I use the ID directly in the code and this won't solve my issue. I want the code to handle the different Ids. I tried this.id, it works with an alert(), but in the code, it doesn't.
What am I doing wrong?
HTML

                    satatus
                    Position
                    Office
                    Age
                    Start date
                    Salary

                    pause_circle_outline
                    System Architect
                    Edinburgh
                    61
                    2011/04/25
                    $320,800

                    play_circle_outline
                    Accountant
                    Tokyo
                    63
                    2011/07/25
                    $170,750

JS
    $(document).ready(function(){
    $("i").click(function() {
            //alert($(this).attr("id"));
            $(this).attr("id").click(function(){
            //$("#status-1").click(function(){
                $(this).text($(this).text() == 'play_circle_outline' ? 'pause_circle_outline' : 'play_circle_outline');
            });
        });
         });

A: You don't need ids in this situation, just use a object what cause the event. Try this:
$(document).ready(function(){
    $(document).on('click', "i", function() {
            alert($(this).attr("id"));
            $(this).text($(this).text() == 'play_circle_outline' ? 'pause_circle_outline' : 'play_circle_online');
        });
});

$(document).ready(function(){
        $(document).on('click', "i", function() {
                alert($(this).attr("id"));
                $(this).text($(this).text() == 'play_circle_outline' ? 'pause_circle_outline' : 'play_circle_outline');
            });
    });

                    satatus
                    Position
                    Office
                    Age
                    Start date
                    Salary

                    pause_circle_online
                    System Architect
                    Edinburgh
                    61
                    2011/04/25
                    $320,800

                    play_circle_outline
                    Accountant
                    Tokyo
                    63
                    2011/07/25
                    $170,750


text:
Q: CKEDITOR 4.0 detach toolbar dynamically I am trying to figure out how to create a ckeditor instance with the toolbar attached to a seperate DIV from the DIV I am creating the instance on.  I see in the config array you can set config.sharedSpaces = { top: 'divid' } (at least in older versions you could), but I can't do that on the config page, it needs to be done on the page I am creating the instances on.  Does anyone know how to do this?
Here is how I am creating my instance:
CKEDITOR.replace( 'editor', {
        toolbarGroups: [
            { name: 'document', groups: [ 'mode', 'document', 'doctools' ] },
            { name: 'clipboard',   groups: [ 'clipboard', 'undo' ] },
            { name: 'basicstyles', groups: [ 'basicstyles', 'cleanup' ] },
            { name: 'colors' },
            { name: 'styles'},
            { name: 'paragraph', groups: [ 'list', 'align' ], items: [ 'NumberedList', 'BulletedList', '-', 'Outdent', 'Indent', '-', 'Blockquote' ] },
            { items: [ 'Image', 'Table', 'HorizontalRule', 'SpecialChar' ] },
            { name: 'links' },
            { name: 'editing', groups: [ 'find', 'selection', 'spellchecker' ] },
            { name: 'tools'}
        ]
    });

Yes I do know I can use clone() and what not but I was hoping for a more clean solution.

A: The shared spaces feature is not available in CKEditor 4.0. It'll be reintroduced very soon in CKEditor 4.1 - see the ticket (it's already merged to major).

A: Before your initialize the editor, write this :

If the sharedspaces plugin is not available download it from http://ckeditor.com/addon/sharedspace

A: For CKEditor 4.1+ you can use the optional Shared Space plugin (needs to be added to your CKEditor build).

    <textarea id="editor1" name="editor1">My editor content</textarea>

See the "Shared Toolbar and Bottom Bar" documentation with code examples and a working demo with source code to copy & download.


text:
Q: How could I do make both vertices and edges in a graph moveable? How could I make both vertices and edges moveable like this.
(source: https://csacademy.com/app/graph_editor/)
(In the image only nodes are movable but I would like to do this for edges as well)

Graph[{1, 2, 3, 4, 5, 6}, {1 \[UndirectedEdge] 3,
  1 \[UndirectedEdge] 5, 1 \[UndirectedEdge] 6, 2 \[UndirectedEdge] 5,
   2 \[UndirectedEdge] 6, 1 \[UndirectedEdge] 6,
  3 \[UndirectedEdge] 4, 3 \[UndirectedEdge] 5, 3 \[UndirectedEdge] 6,
   5 \[UndirectedEdge] 6}, VertexLabels -> "Name"]

A: Use the option PerformanceGoal -> "Quality" in Graph
g1 = Graph[{1 -> 2, 2 <-> 3, 3 -> 1, 1 -> 3},
  VertexLabels -> Placed["Name", Center], VertexSize -> {v_ :> v/10},
  VertexStyle -> Directive[EdgeForm[{Thick, Black}], White],
  VertexLabelStyle -> Large, PerformanceGoal -> "Quality"]

To move vertices interactively (with the edges adjusting automatically to new vertex locations), use Show @ g1 to get a Graphics object which can be interactively manipulated after double-clicking on it:
Show @ g1


text:
Q: How to make a service "fail" or restart I'm trying to hack up a way to deal with some programming issues by having my Windows service shutdown and restart itself (don't ask why, that's another topic). I see in the properties for the service, I can set it to restart on the 1st, 2nd, and subsequent failures.  How do I make it "fail" in my code (besides doing something like overwriting memory, etc.)?  I figured I could call SetServiceStatus() and set dWin32ExitCode to ERROR_SERVICE_SPECIFIC_ERROR and dwServiceSpecificExitCode to some number, but that doesn't do the trick.  Any ideas?  Or is there some other way to restart a service without user intervention?

A: Well, just doing an exit(1) seems to work.


text:
Q: Bash - PWD not executing in current folder I am using the following executable to download a zip from the web, extract it and then delete the zip.
#!/usr/bin/env bash

echo "Downloading project resources from Storage..."

filename="outfile.zip"

if curl --silent -o "${PWD}/${filename}" -L "https://mylink.com"; then
    unzip "${filename}"
    if [[ -f "${PWD}/${filename}" ]]; then
        echo "Removing the file.."
        rm -f "${PWD}/${filename}"
    fi
else
    echo "Something went wrong"
fi
echo "Done!"

However, PWD does not seem to work as the zip is downloaded in the home directory of my Mac and the files are extracted there as well. I want to the zip to download and extract in the same folder of the executable file, no matter where it is.
What am I doing wrong here?


text:
Q: Checkbox losing value after sorting I have a sortable table that uses tablesorter and a parser which allows me to sort checkboxes in checked/unchecked order. I have also added a show values button that displays the values of the selected checkboxes. In this fiddle everything works as expected. The show values button displays the values correctly before and after sorting.
However, in my website the show values button displays the values only prior to sorting any of the columns. If I sort the table and then try to use the show values button, it doesn't display any of the checkbox values.
I initialize the checkboxes as such:
Student with value 25

    <input type='checkbox' name='cb' id='cb25' value='25' />

The show values button is used to display the values of the checkboxes. This is how it is initialized:
<input type="Button" value="Show values" onClick="showVal(this.form)" />

And this is the show val function definition in jquery, which displays the alert with the checkbox values:
function showVal(table) {
    var arr = [];
    for (var i in table.cb) {
        if (table.cb[i].checked) {
            arr.push(table.cb[i].value);
            arr.push("\n");
        }
    }
    alert(arr);
    return arr
}

Please let me know what am I missing and/or doing wrong.
Thanks!


text:
Q: Trusted clients I need to add trusted clients in SSO using Authlib. These clients are parts of my system and I don't need to the user confirmed it. Now, I use the next code for authorization:
@bp.route("/oauth/authorize", methods=['GET', 'POST'])
def authorize():
    user = current_user()
    if not user:
        return redirect('/sign_in')
    if request.method == 'GET':
        grant = server.validate_consent_request(end_user=user)
        return render_template(
            "authorize.html",
            grant=grant,
            user=user
        )
    confirmed = request.form['confirm']
    if confirmed:
        # granted by resource owner
        return server.create_authorization_response(user)
    # denied by resource owner
    return server.create_authorization_response(None)

But how can I pre-register all my clients to they were confirmed automatically?

A: It could be solved with:
if request.method == 'GET':
    grant = server.validate_consent_request(end_user=user)
    if is_trust_client(grant.client):
        return server.create_authorization_response(user)

You can get the client model instance with grant.client. e.g. You define a column called trusted, then you can use if grant.client.trusted to tell if the client is trusted, if so, return the authorization response.


text:
Q: How do I select random element from an array? I ended up with the following plus a few modifications:
NSArray *Quotes = @[@"test1",@"test2"];
NSString *Quoteselected = arc4random() % [quotes];
self.label.text = Quoteselected;

I found the error, which probably also caused the SIGARBT -my randomization created values bigger than what I had element for in the array - thereby making the code try to pick elements not existing.
thanks for all the help

A: Assuming you're okay with typing out every quote, you could use a property list
plist tutorial
Unless it's a very large database

A: I think this is what you look for:
http://www.raywenderlich.com/934/core-data-tutorial-for-ios-getting-started
This is called core data that comes with Objective-C. It is what I use for small, LOCAL database.
On the other hand, for small to medium size of database for a starter like you (I presume you just started making programs?) Check out ruby on rails and AFNetworking library. BTW, this is ONLINE or REMOTE databse. (Just saying, but in ruby on rails, database can be created with using command line, you'll know how simple it is)
http://guides.rubyonrails.org/getting_started.html
Two options, you can choose either one.


text:
Q: How to filter outlook mails on a subject using Python and win32com.client? I was trying to download attachments from outlook which satisfy a particular subject but i got an exception that have no idea how to correct my code from below is my code:
import win32com.client
import os
get_path = os.getcwd()
outlook = win32com.client.Dispatch("Outlook.Application").GetNameSpace("MAPI")
inbox = outlook.GetDefaultFolder(6)
messages = inbox.Items
message2 = messages.GetLast()
subject = message2.Subject
body = message2.body
sender = message2.Sender
attachments = message2.Attachments
for m in messages:
    if m.Subject == "Test Mail":
        for x in message2.Attachments:
            x.SaveASFile(os.path.join(get_path,x.FileName))
            print "successfully downloaded attachments"

and here is the problem:
Traceback (most recent call last):
  File "C:/Users/LENOVO USER/PycharmProjects/FlaskProject/EmailFilter/TestFile.py", line 4, in <module>
    outlook = win32com.client.Dispatch("Outlook.Application").GetNameSpace("MAPI")
  File "C:\Python27\lib\site-packages\win32com\client\__init__.py", line 95, in Dispatch
    dispatch, userName = dynamic._GetGoodDispatchAndUserName(dispatch,userName,clsctx)
  File "C:\Python27\lib\site-packages\win32com\client\dynamic.py", line 114, in _GetGoodDispatchAndUserName
    return (_GetGoodDispatch(IDispatch, clsctx), userName)
  File "C:\Python27\lib\site-packages\win32com\client\dynamic.py", line 91, in _GetGoodDispatch
    IDispatch = pythoncom.CoCreateInstance(IDispatch, None, clsctx, pythoncom.IID_IDispatch)
pywintypes.com_error: (-2147221005, 'Invalid class string', None, None)

A: As the traceback shows, the error is at the line where you define outlook. Actually, there is no cap S in GetNamespace so replace this line by:
outlook = win32com.client.Dispatch("Outlook.Application").GetNamespace("MAPI")

but other errors occur, at the line where body is defined, a cap is mandatory for the attribute, such as body = message2.Body, and another cap issue in x.SaveASFile, it should be x.SaveAsFile
Finally, I'm not sure that your code will do what you describe as you try to download the attachments of message2, being your last message, while you iterate through messages, I don't see the point then.
Let me know if you need more help or if I misunderstood your problem.


text:
Q: Static variable used for Recurssion check Scenario:
I have two objects - Object A and Object B.Object A has recursion checking mechanism using Static Boolean variables covering different events(IsBeforeUpdate,IsBeforeInsert etc..)
I have two apex classes (Class 1 and Class 2) running on Object B that updates Object A on after update.
Question:
Let us say an update operation happens on Object B.
whats happens to the Static Boolean (IsBeforeUpdate on Object A) will it be set to false by the first class 1 ? and second class 2 will not be able do its update on Object A?
if this is true , how can i make sure both my class 1 and 2 from Object B update Object A?
//MasterTaskTrigger
if (trigger.isUpdate && trigger.isAfter)
{
    handler.afterUpdate(trigger.old, trigger.oldMap, trigger.new, trigger.newMap);
    system.debug('inside After Update');
}

//This is an handler for Task Object
public class TriggerhandlerTask extends TriggerHandler
{
    public void afterUpdate(List<Task> originalTask,Map<ID, Task> originalTaskMap,List<Task>updatedTask,Map<ID, Task>  updatedTaskMap)
    {
        if(afterUpdateHasRun())
        {
            return;
        }
        //Call Class 1 - has logic to update Object A
        Class1 Cs =  new Class1();
        //Call Class 2 - has logic to update Object A
        Class2 Cs =  new Class2();
    }
}

//this handler is extended across all other objects Triggerhandlers
public virtual class TriggerHandler
{
    public   static  boolean isBeforeInsertFirstRun   = true;
    public   static  boolean isBeforeUpdateFirstRun   = true;
    public   static  boolean isBeforeDeleteFirstRun   = true;
    public   static  boolean isAfterInsertFirstRun    = true;
    public   static  boolean isAfterUpdateFirstRun    = true;
    public   static  boolean isAfterDeleteFirstRun    = true;
    public   static  boolean isAfterUndeleteFirstRun  = true;

    protected boolean beforeInsertHasRun()
    {
        if (isBeforeInsertFirstRun)
        {
            return isBeforeInsertFirstRun = false;
            System.debug('---->isBeforeInsertFirstRun'+isBeforeInsertFirstRun);
        }
        return true;
    }
    protected boolean beforeUpdateHasRun()
    {
        if (isBeforeUpdateFirstRun)
        {
            return isBeforeUpdateFirstRun = false;
            System.debug('---->beforeUpdateHasRun'+beforeUpdateHasRun);
        }
        return true;
    }
}

A: You should handle recursion as a locking mechanism. That means that the trigger should first see if it's locked, and if not, lock itself, and when done, unlock itself. Here's the basic design:
public class TriggerLocks {
    public static Boolean triggerA_beforeUpdate = false;
    // and so on
}

trigger triggerA_BeforeUpdate on A (before update) {
    if(TriggerLocks.triggerA_beforeUpdate) {
        return;
    }
    TriggerLocks.triggerA_beforeUpdate = true;
    // Do your logic here
    // When done...
    TriggerLocks.triggerA_beforeUpdate = false;
}

This way, if you have two or more updates on A records, you can do both of them without the trigger flag getting in the way.
Note: "Class 1" nor "Class 2" should update the Boolean flag without good reason. The data is conceptually internal to the trigger itself, but due to language limitations, can't actually be protected in the same way. The trigger, and only the trigger, should modify that flag directly. This limits the responsibility of breaking recursion to just the single trigger's logic.

Here's a "not very optimized" version of a handler I might build to help with consistency.
public virtual class BaseTriggerHandler {
    static Map<Type, BaseTriggerHandler> cache = new Map<Type, BaseTriggerHandler>();

    Boolean inBeforeInsert = false, inBeforeUpdate = false, inBeforeDelete = false,
            inAfterInsert = false, inAfterUpdate = false, inAfterDelete = false, inAfterUndelete = false;

    protected virtual void beforeInsert(SObject[] records) {

    }
    protected virtual void beforeUpdate(SObject[] oldRecords, SObject[] records) {

    }
    protected virtual void beforeDelete(SObject[] oldRecords) {

    }
    protected virtual void beforeUndelete(SObject[] records) {

    }
    protected virtual void afterInsert(SObject[] records) {

    }
    protected virtual void afterUpdate(SObject[] oldRecords, SObject[] records) {

    }
    protected virtual void afterDelete(SObject[] oldRecords) {

    }
    protected virtual void afterUndelete(SObject[] records) {

    }
    void doBeforeInsert(SObject[] records) {
        if(!inBeforeInsert) {
            inBeforeInsert = true;
            beforeInsert(records);
            inBeforeInsert = false;
        }
    }
    void doBeforeUpdate(SObject[] oldRecords, SObject[] records) {
        if(!inBeforeUpdate) {
            inBeforeUpdate = true;
            beforeUpdate(oldRecords, records);
            inBeforeUpdate = false;
        }
    }
    void doBeforeDelete(SObject[] oldRecords) {
        if(!inBeforeDelete) {
            inBeforeDelete = true;
            beforeDelete(oldRecords);
            inBeforeDelete = false;
        }
    }
    void doAfterInsert(SObject[] records) {
        if(!inAfterInsert) {
            inAfterInsert = true;
            afterInsert(records);
            inAfterInsert = false;
        }
    }
    void doAfterUpdate(SObject[] oldRecords, SObject[] records) {
        if(!inAfterUpdate) {
            inAfterUpdate = true;
            afterUpdate(oldRecords, records);
            inAfterUpdate = false;
        }
    }
    void doAfterDelete(SObject[] oldRecords) {
        if(!inAfterDelete) {
            inAfterDelete = true;
            afterDelete(oldRecords);
            inAfterDelete = false;
        }
    }
    void doAfterUndelete(SObject[] records) {
        if(!inAfterUndelete) {
            inAfterUndelete = true;
            afterUndelete(records);
            inAfterUndelete = false;
        }
    }
    // The only method you need to call
    public void dispatch() {
        if(Trigger.isInsert && Trigger.isBefore) {
            doBeforeInsert(Trigger.new);
        }
        if(Trigger.isUpdate && Trigger.isBefore) {
            doBeforeUpdate(Trigger.old, Trigger.new);
        }
        if(Trigger.isDelete && Trigger.isBefore) {
            doBeforeDelete(Trigger.old);
        }
        if(Trigger.isInsert && Trigger.isAfter) {
            doAfterInsert(Trigger.new);
        }
        if(Trigger.isUpdate && Trigger.isAfter) {
            doAfterUpdate(Trigger.old, Trigger.new);
        }
        if(Trigger.isDelete && Trigger.isAfter) {
            doAfterDelete(Trigger.old);
        }
        if(Trigger.isUndelete && Trigger.isAfter) {
            doAfterUndelete(Trigger.new);
        }
    }

    protected BaseTriggerHandler() {

    }

    // Singleton/factory
    public static BaseTriggerHandler getHandlerFor(Type handlerType) {
        if(!cache.containsKey(handlerType)) {
            cache.put(handlerType, (BaseTriggerHandler)handlerType.newInstance());
        }
        return cache.get(handlerType);
    }
}

And here's a possible implementation:
public class TaskTriggerHandler extends BaseTriggerHandler {
    protected override void afterUpdate(SObject[] records) {
        Class1 c1 = new Class1();
        Class2 c2 = new Class2();
    }
}

And here's the trigger you use to actually call this entire framework:
trigger TaskTrigger on Task (before insert, before update, before delete, after insert, after update, after delete, after undelete) {
    BaseTriggerHandler.getHandlerFor(TaskTriggerHandler.class).dispatch();
}


text:
Q: i want to ask how to replace local asset using existing data in API i want to replace assets/1.json to api URL because the required data is in API not local, and how do i change it, i have tried but still getting error.
Thank you
static Future<Map<String, DataKuliahModel>> getDataKuliah() async {
    String url = Constant.baseURL;
    String token = await UtilSharedPreferences.getToken();
    await Future.delayed(const Duration(seconds: 4));
    // String responseJson = await rootBundle.loadString('assets/1.json');

    Map<String, DataKuliahModel> finalResult = {};
    final response = await http.get(
      Uri.parse(
        '$url/auth/mhs_siakad/perwalian/get_paket',
      ),
      headers: {
        'Authorization': 'Bearer $token',
      },
    );
    final result = jsonDecode(response)['data'] as Map<String, dynamic>;
    result.forEach((key, value) {
      DataKuliahModel dataKuliah = DataKuliahModel.fromMap(value);
      finalResult.addAll({
        key: dataKuliah,
      });
    });
    return finalResult;
  }

A: I don't know your API or it's response, but you probably want to pass response.body to your jsonDecode.


text:
Q: Vue.js: show profile image in laravel public folder I am creating commenting system.
And I integrated vue.js in my laravel project.

In my comment area, I want to show user profile image in my laravel
  public folder.

But I have no idea how to show image.
What I want to achieve is,

if user has a profile image, I want to show it in comment area. But if
  user doesn't have a profile image, I want to show an avatar.

I used vue avatar component so I think I want to use it.
My profile images are stored in public/uploads/profile.
comment.vue
<template>

                <avatar :username="comment.user.name" :size="45"></avatar>

                {{ comment.user.name }}

{{ comment.body }}

        <button @click="addingReply = !addingReply" class="reply-button" :class="{ 'red' : !addingReply, 'black' : addingReply }">
            {{ addingReply ? 'Cancel' : 'Add Reply'}}
        </button>

            <input v-model='body' type="text">

            <button @click="addReply" class="comment-button">Add Reply</button>

     <replies ref='replies' :comment="comment"></replies>

</template>

profile.php
public function user(){
    return $this->belongsTo(User::class, 'user_id');
}

user.php
public function profile(){
        return $this->hasOne(Profile::class);
    }

 public function comments()
    {
        return $this->hasMany(Comment::class);
    }

comment.php
protected $with = ['user'];

protected $appends = ['repliesCount'];

web.php
Route::get('results/{post}/comments', 'CommentController@index');

A: If your database column name for the image file is img then
you can do it like below:

If you are using multiple images for a user you need to add a loop as follow:

 0">


text:
Q: Slider not working properly for android 4.0.3 but working for 2.3.5 ,4.1,4.2 I am working on project which needs slider for better navigation.so, I found out slider after searching on internet.It's working cool on android 2.3.5, 4.1, 4.2 that much devices I Have.but not working properly on 4.0.3 , 4.0.4 .I have one listview in slider panel and other in my main layout.When I open slider it opens up and I can click on list of slider but when I close it n try to click on main listview in my main layout I cannot click on it.I got nothing in logcat no exception.
I have posted whole sample project code here please help me.
slider sample project
If I donot find the solution for this I have to change slider which will be very much complicated for me in my main project.
Thanks in advance.

A: Finally got the solution for issue of slider not working for 4.0.3 ,4.0.4.
The problem was I could not able to click on any list when I was openeing slider and closing it.I fixed this issue by just refreshing adapter for both list i.e list in slider and list in my main layout while opening or closing slider function.
Still don't know why it was not working for 4.0.3,4.0.4 before applying this solution though it was working for other android versions.


text:
Q: Removing trailing pipe delimiter and pipe in between I am loading three phone numbers separated by pipe delimiter to a column in Teradata DWH.

*

*If all three phone numbers are present for a row, value should
look like this 123 | 456 | 789.

*If first and the third are present then 123 | 789

*If first and second are present than 123 | 456

*If second and third are present then 456 | 789.

The query that is written is having some issues and if any of the phone numbers are missing say if the second phone number is missing it is storing values like this 123 | | 789 or if the third phone number is missing it is giving 123 | 456 |.
We do not want trailing pipe or 2 pipes in between. Please suggest a Teradata query to implement this.

A: The logic is:
Assign different weights to each column and then evaluate weighted sum of length of all 3 columns. Assuming each phone number is 10 digits long. Here is the query/pseudocode.
Query:
Select
case 1*LENGTH(firstCol)+2*LENGTH(secondCol)+4*LENGTH(thirdCol)
when 70 then CONCAT( firstcol,'|', secondcol,'|', thirdCol)
when 60 then CONCAT( secondcol, '|', thirdCol)
when 50 then CONCAT( firstcol, '|', thirdCol)
when 30 then CONCAT (firstcol, '|', secondcol)
when 10 then firstcol
when 20 then secondcol
when 40 then thirdCol
else null
end
from phoneNumbersTable


text:
Q: What does the writing on Poe Dameron's flight vest say? Not the most vital fact, I know, but what does the writing on Poe's vest-thingy say?

A: It's clearly in Aurebesh, so we're going to need a translation table1:

Now, what's tricky is that the text is upside-down, so we have to do a bit more detective work. Here's a pretty high-res shot of Poe's chest (linked to the right-side-up version):

From this, we can work out that the first word is "PULL", and that the bottom word starts "INFLA"
Now we have another image:

Where we can make out the "TO", and just enough to confirm that the last word ends with "AT", and then one more letter I can't quite make out. I'm going to make an educated guess that the last letter is an "E"
Which leaves us with:

PULL TO INFLATE

Kind of anti-climactic, really.

1 Taken from the back of a Star Wars: Rebels identification card (PDF link)


text:
Q: How to delete a git head but not a tag having the same name I have a branch and tag having the same name abc as follows:
> git show-ref abc
c7f57ba70d1ee9624df2d288f9934d1f086dc4e5 refs/heads/abc
d23de1ba0faed701fd64ccd53c0aa03455f6edd6 refs/tags/abc

Now I want to delete the heads abc and want to retain the tags abc. How can I do that? Will the following delete only the heads abc keeping the tags abc as it is:
> git branch -D refs/heads/abc

Please note I cannot afford to delete the tags abc. So what command can I run ?

A: Yes, you can execute the branch command you propose, you won't delete the same-name tag.
The branch command doesn't delete tags, you'd have to explicitly delete it with git tag -d abc if you wanted to.
You can just test it in a tiny test repo if my word isn't enough to reassure you.
$ git init testrepo
Initialized empty Git repository in <somepath>/testrepo/.git/

$ cd testrepo

$ echo "test" > test.txt

$ git commit -am "First commit"
[master (root-commit) 80f9162] First commit
 1 file changed, 1 insertion(+)
 create mode 100644 test.txt

$ git branch myref

$ git tag myref

$ git branch
* master
  myref

$ git tag -l
myref

$ git branch -D myref
Deleted branch myref (was 80f9162).

$ git branch
* master

$ git tag -l
myref

As a sidenote, branches you feed to the git branch command are expected in their short form (abc), not the complete path (refs/heads/abc)


text:
Q: CodeIgniter nested query issue I have tried to convert the code below to codeigniter active record without any success. I searched through here for any related question but the one I found here codeigniter active record nested query is not working for me.
Below is the sql am trying to convert
SELECT "BCB_ID","BCB_COST_CENTRE_NUMBER","BCB_TRANSFER_DATE","BCB_ARRIVAL_SEQUENCE","BCB_LOCATION_TYPE", "BCB_REFERENCE",
SUM(cfb) as CFB, SUM(ctb) as CTB, SUM(cts) as CTS, SUM(cfs) as CFS
FROM(SELECT "BCB_ID","BCB_COST_CENTRE_NUMBER", "BCB_DATE", "BCB_ARRIVAL_SEQUENCE","BCB_LOCATION_TYPE", "BCB_TRANSFER_DATE", "BCB_REFERENCE", "BCB_SOURCE",
    SUM(BCB_CASH_FROM_BANK )as CFB, SUM(BCB_CASH_TO_BANK ) as CTB, SUM(BCB_CASH_TO_SHOPS )as CTS, SUM(BCB_CASH_FROM_SHOPS ) as CFS
    FROM "WHOUSE1"."DLY_BWR_CASH_AND_BANKING"
    WHERE "BCB_COST_CENTRE_NUMBER" =  '1222'
    AND "BCB_TRANSFER_DATE" >= 20130130
    and bcb_source in ('A','C')
    GROUP BY "BCB_ID","BCB_COST_CENTRE_NUMBER", "BCB_DATE", "BCB_ARRIVAL_SEQUENCE", "BCB_LOCATION_TYPE", "BCB_TRANSFER_DATE", "BCB_REFERENCE", "BCB_SOURCE"
    ORDER BY "BCB_TRANSFER_DATE" DESC
    )
GROUP BY  "BCB_ID", "BCB_COST_CENTRE_NUMBER",  "BCB_TRANSFER_DATE", "BCB_ARRIVAL_SEQUENCE", "BCB_LOCATION_TYPE", "BCB_REFERENCE"
ORDER BY  "BCB_TRANSFER_DATE" DESC

Any help will be well appreciated. Thanks

A: $this->db->query("SELECT "BCB_ID","BCB_COST_CENTRE_NUMBER","BCB_TRANSFER_DATE","BCB_ARRIVAL_SEQUENCE","BCB_LOCATION_TYPE", "BCB_REFERENCE",
SUM(cfb) as CFB, SUM(ctb) as CTB, SUM(cts) as CTS, SUM(cfs) as CFS
FROM(SELECT "BCB_ID","BCB_COST_CENTRE_NUMBER", "BCB_DATE", "BCB_ARRIVAL_SEQUENCE","BCB_LOCATION_TYPE", "BCB_TRANSFER_DATE", "BCB_REFERENCE", "BCB_SOURCE",
    SUM(BCB_CASH_FROM_BANK )as CFB, SUM(BCB_CASH_TO_BANK ) as CTB, SUM(BCB_CASH_TO_SHOPS )as CTS, SUM(BCB_CASH_FROM_SHOPS ) as CFS
    FROM "WHOUSE1"."DLY_BWR_CASH_AND_BANKING"
    WHERE "BCB_COST_CENTRE_NUMBER" =  '1222'
    AND "BCB_TRANSFER_DATE" >= 20130130
    and bcb_source in ('A','C')
    GROUP BY "BCB_ID","BCB_COST_CENTRE_NUMBER", "BCB_DATE", "BCB_ARRIVAL_SEQUENCE", "BCB_LOCATION_TYPE", "BCB_TRANSFER_DATE", "BCB_REFERENCE", "BCB_SOURCE"
    ORDER BY "BCB_TRANSFER_DATE" DESC
    )
GROUP BY  "BCB_ID", "BCB_COST_CENTRE_NUMBER",  "BCB_TRANSFER_DATE", "BCB_ARRIVAL_SEQUENCE", "BCB_LOCATION_TYPE", "BCB_REFERENCE"
ORDER BY  "BCB_TRANSFER_DATE" DESC");////TRY THIS CODE

---AND THIS LINK FOR GUIDE http://ellislab.com/codeigniter/user-guide/database/results.html


text:
Q: How to remove default keyboard from emulator in android? m surffing from one proble. in my project layout i put one edit text to put the text from search data from the database but when i write in edit text that time default keyboard opens so i want to hide this keyboard

A: Using InputMethodManager, you can force android to hide/show the keyboards.
Calling hideSoftInputFromWindow, passing in the token of the window containing your edit field.
InputMethodManager imm = (InputMethodManager)getSystemService(Context.INPUT_METHOD_SERVICE);
imm.hideSoftInputFromWindow(myEditText.getWindowToken(), 0);

With this you will not see the keyboard at all.


text:
Q: Optimize python code for working with object names I have a pygtk Table with 16 squares, each of them containing a label. Label names are: label1, label2, label3, ..., label16.
I also have a timer that fires every n seconds. When the timer is fired one of the squares is highlighted (just set the font size of it to 18 and the font size of the rest to 12).
If there would be only 3 labels, the code would be something like this:
def update_grid(self):
    if self.timer_id is not None:
        self.__actual_choice = (self.__actual_choice % 16)+1
        if self.__actual_choice == 1:
            self.label1.modify_font(self.__font_big)
            self.label2.modify_font(self.__font_small)
            self.label3.modify_font(self.__font_small)
        elif self.__actual_choice == 2:
            self.label1.modify_font(self.__font_small)
            self.label2.modify_font(self.__font_big)
            self.label3.modify_font(self.__font_small)
        elif self.__actual_choice == 3:
            self.label1.modify_font(self.__font_small)
            self.label2.modify_font(self.__font_small)
            self.label3.modify_font(self.__font_big)

But having 16 labels, the code would be huge. I wonder if there is a way in python of doing something like:
            self.(label+"i").modify_font(self.__font_small)

A: You could use the built-in function, getattr() as others have suggested:
label = getattr(self, 'label%d' % i)
label.modify_font(self.__font_small)

But in reality, you'd be better off storing your 16 labels in a list. Lots of variables with numbers at the end is a terrible code smell.
for index, label in enumerate(self.labels):
    if index == self.__actual_choice:
        label.modify_font(self.__font_big)
    else:
        label.modify_font(self.__font_small)

A: You should look into the getattr function.

A: Use getattr:
self.__actual_choice = (self.__actual_choice % 16)+1
for i in range(1, 17):
    if i == self.__actual_choice:
        getattr(self, 'label' + str(i)).modify_font(self.__font_big)
    else:
        getattr(self, 'label' + str(i)).modify_font(self.__font_small)

A: Why in the world would you write that as a bunch of if statements?
modify_fonts = [getattr(self, "label%s" % i).modify_font for i in xrange(1, 17)]

You now have a list of the methods you can call for each label. That is, modify_fonts[0] is self.label1.modify_font and so on. Then you call them in a loop.
actual_choice = (self.__actual_choice % 16)   # no +1, we're zero-based
for index, modify_font in enumerate(modify_fonts):
    modify_font(self.__font_big if index == actual_choice else self.__font_small)


text:
Q: How to make a python program to convert a bunch of pdfs to html? I was trying to do a program that would read all the pdfs in a folder and convert all of them to htmls, for example file1.pdf, file2.pdf, file3.pdf then run the program and create something like file1.html, file2.html, file3.htm. Without losing the main pdf of course, untill now I only could do it to one file, I don't how to make for every file on the folder with a loop.
Here's my code:
import shlex
import subprocess
import os
import platform

def run(command):
    if platform.system() != 'Windows':
        args = shlex.split(command)
    else:
        args = command
    s = subprocess.Popen(args,
                         stdout=subprocess.PIPE,
                         stderr=subprocess.PIPE)
    output, errors = s.communicate()
    return s.returncode == 0, output, errors

# Change this to your PDF file base directory
base_directory = 'C:\\PROJECT\\pdfs'
if not os.path.isdir(base_directory):
    print "%s is not a directory" % base_directory
    exit(1)
# Change this to your pdf2htmlEX executable location
#bin_path = 'C:\\Python27\\pdf2htmlEX\\pdf2htmlEX.exe'
#if not os.path.isfile(bin_path):
#    print "Could not find %s" % bin_path
#    exit(1)
for dir_path, dir_name_list, file_name_list in os.walk(base_directory):
    for file_name in file_name_list:
        # If this is not a PDF file
        if not file_name.endswith('.pdf'):
            # Skip it
            continue
        file_path = os.path.join(dir_path, file_name)
        # Convert your PDF to HTML here
        args = (file_name, file_path)
        success, output, errors = run("pdf2txt.py -o %s.html %s" %args)
        if not success:
            print "Could not convert %s to HTML" % file_path
            print "%s" % errors

A: to compile pdf2html project by https://github.com/coolwanglu/pdf2htmlEX, and system call cmd pdf2html by python

A: This is a complete solution that uses os.walk and pdf2htmlEX:
import shlex
import subprocess
import os
import platform

def run(command):
    if platform.system() != 'Windows':
        args = shlex.split(command)
    else:
        args = command
    s = subprocess.Popen(args,
                         stdout=subprocess.PIPE,
                         stderr=subprocess.PIPE)
    output, errors = s.communicate()
    return s.returncode == 0, output, errors

# Change this to your PDF file base directory
base_directory = 'C:\\Users\\Admin\\Desktop\\learningpython\\PROJECT'
if not os.path.isdir(base_directory):
    print "%s is not a directory" % base_directory
    exit(1)
# Change this to your pdf2htmlEX executable location
bin_path = 'C:\\Python27\\pdf2htmlEX-master\\pdf2htmlEX.exe'
if not os.path.isfile(bin_path):
    print "Could not find %s" % bin_path
    exit(1)
for dir_path, dir_name_list, file_name_list in os.walk(base_directory):
    for file_name in file_name_list:
        # If this is not a PDF file
        if not file_name.endswith('.pdf'):
            # Skip it
            continue
        file_path = os.path.join(dir_path, file_name)
        # Convert your PDF to HTML here
        args = (bin_path, dir_path, file_path)
        success, output, errors = run("%s --dest-dir %s %s" % args)
        if not success:
            print "Could not convert %s to HTML" % file_path
            print "%s" % errors


text:
Q: Regex for Google analytics I am trying to match a set of data but not if it contains certain strings in the query:
The strings that I do not want to allow are
/hd/805
/hd/864
/hd/999
/hd/???????debugUser??????
/hd/208?debugUser=test&MediaCode=XXXXX&CMP=XXXXX
/hd/208?debugUser=john&MediaCode=XXXXX&CMP=XXXXX

But I do want to match everything else
/hd/123
/hd/654?test=test

etc
I have this regex to exclude the first part /hd/(?!864)(?!805)(?!999)[0-9]+
But I cannot get it to catch if the string contains debugUser
I have tried /hd/(?!864)(?!805)(?!999)[0-9]+\??(?!\?debugUser.*).*
But that still includes the url
Does anyone have ideas?
This regular expression will be used with google analytics.

A: What you could do is use this regex: /hd/(805|864|999|208|\?\?\?\?\?\?\?debugUser\?\?\?\?\?\?) to match to the ones you don't want, and if it matches then just ignore it. So your psuedo code will look like -
for(String url : urls){
    if(regex.matches(url) continue;
    //else do processing
}

A: You can try this pattern to check a string or a line in multiline mode that contains only an uri:
^\/hd\/(?:[0-7]|8(?!05\b|64\b)|9(?!99\b))\d*(?:\?(?:[^d\s]+|d+(?!ebugUser))+)?$

or this to find the string you want inside a larger string:
(?<=^|["']|\s)\/hd\/(?:[0-7]|8(?!05\b|64\b)|9(?!99\b))\d*(?:\?(?:[^d\s]+|d+(?!ebugUser))+)?(?=\s|['"]|$)

for this one, don't forget to escape the quote (single or double) you use.


text:
Q: Where can I find static Xerces 3.0.0 lib for AIX I got the binaries from the xerces apache site but they only have dynamic lib.
I am wondering why they do not include static version of the lib?
And is there a place to get static Xerces 3.0.0 for AIX.
And its C version of it
Thanks for any input
P.S. Other then building it myself I am aware of this option but I want something that is more standardized. Meaning using their generic build flags that they used to build dynamic version of the lib

A: Just as you mention in your postscript, download from Apache's site and then run the configure script:
./configure --enable-static


text:
Q: Should exceptions thrown from class member initializers call std::terminate()? Given this code:
struct A {
    A(int e) { throw e; }
};

struct B {
    A a{42}; // Same with = 42; syntax
};

int main() {
    try {
        B b;
    } catch (int const e) {
        return e;
    }
}

When compiled with GCC (versions 4.7.4, 4.8.5, 4.9.3, 5.4.0, 6.3.0):
$ g++ -std=c++11 test.cpp -o test; ./test ; echo $?
terminate called after throwing an instance of 'int'
Aborted
134

But when compiled with Clang (version 4.0.0):
$ clang++ -std=c++11 test.cpp -o test; ./test ; echo $?
42

Which behavior is correct?

A: Clang is correct. References about that can be found in C++ standard reference draft n4296 (emphasize mine):

15.3 Handling an exception [except.handle]
...3 A handler is a match for an exception object of type E if
(3.1) — The handler is of type cv T or cv T& and E and T are the same type (ignoring the top-level cv-qualifiers),

Here an int is thrown, and the handler declares a const int. There is a match and the handler shall be invoked.

A: This is a bug in GCC (Bug 80683).
If the constructor is the first op in the try/catch clause, then the compiler considered it as being outside of it although it should include it.
For example, the following works just fine:
#include <iostream>

struct A {
    A(int e) { throw e; }
};

struct B {
    A a{42}; // Same with = 42; syntax
};

int main() {
    try {
        // The following forces the compiler to put B's contructor inside the try/catch.
        std::cout << "Welcome" << std::endl;
        B b;
    } catch (int e) {
        std::cout << "ERROR: " << e << std::endl; // This is just for debugging
    }

    return 0;
}

Running:
g++ -std=c++11 test.cpp -DNDEBUG -o test; ./test ; echo $?

Outputs:
Welcome
ERROR: 42
0

My guess is that is that due to compiler optimization, it moves the constructor to the beginning of the main function. It assumes that the struct B has no constructor, then it assumes that it would never throw an exception, thus it is safe to move it outside of the try/catch clause.
If we will change the declaration of struct B to explicitly use struct A constructor:
struct B {
    B():a(42) {}
    A a;
};

Then the result will be as expected and we will enter the try/catch, even when removing the "Welcome" printout:
ERROR: 42
0


text:
Q: convert speech into text in excel - can this be done I am working on a form, for which I would rather not rely on the one fingered typists in the workshop to fill in (with the inevitable typo's).  Therefore I wondered if anyone know how to speak directly into some cells in excel and have that speech turned into text?
I have searched the net and constantly find the text to speech option which is the exact opposite of what I would like to do.

A: Although this question might be more appropriate for a different site (e.g. https://superuser.com/), here's some information that's out there.
Windows has built-in support to speech-to-text. This article is for Windows 7, but I was able to do something similar to get it to work for Windows 10 (I'm not sure what version of Windows your shop uses). I'm sure there are other commercial products you can use.
With Windows 10, I had to enable speech services, then use the Win+H keyboard shortcut to activate dictation. With Excel open and in focus, anything I said was entered into the active cell.


text:
Q: Frontend design difference between VS2017 chrome (debug) and Google Chrome I deployed my local version and viewed it on Google Chrome and noticed differences in the font size, position of elements and the layout.
Example:

The left part of the image is Google Chrome running on Windows 10 and the right part is the built in Chrome that runs when I debug the project.
CSS & JS are minified in the release but match the development versions...
Microsoft Edge looks the same as Google Chrome (left part)
Libraries:
"jQuery": "3.2.1",
"bootstrap": "v4.0.0-alpha.6",
"bootstrap-validator": "v0.11.9",
"signalr": "v2.2.2",
"cookie": "v1.2.2"

Includes:
<environment names="Development">
    <link rel="stylesheet" href="~/lib/tether/dist/css/tether.css" />
    <link rel="stylesheet" href="~/lib/tether/dist/css/tether-theme-basic.css" />
    <link rel="stylesheet" href="~/lib/bootstrap/dist/css/bootstrap.css" />
    <link rel="stylesheet" href="~/css/site.css" />
</environment>
<environment names="Staging,Production">
    <link rel="stylesheet" href="~/lib/tether/dist/css/tether.min.css" asp-append-version="true" />
    <link rel="stylesheet" href="~/lib/tether/dist/css/tether-theme-basic.min.css" asp-append-version="true" />
    <link rel="stylesheet" href="~/lib/bootstrap/dist/css/bootstrap.min.css" asp-append-version="true" />
    <link rel="stylesheet" href="~/css/site.min.css" asp-append-version="true" />
</environment>

CSS code that applies font family (site.css):
body {
    font-family: Georgia, "Times New Roman", Times, serif;
    color: #555;
}

After inspecting the  element I noticed that on the dev version, the element is styled with a border loaded from bootstrap.css.
However on the release version the border is missing because the CSS is loaded from bootstrap/reboot.scss.

Still investigating...

A: Usually browsers use Arial,Times New Roman,Courier New, As their defualt fonts. however it can be difference in other OS (for example chrome use Helvetica instead of Arial in Mac OS ).
users can change the default browsers fonts also.
Do you use any specific font? check your font-family, if it not used the Standard fonts, make sure your fonts files are in correct path in release version of your website.

A: The correct answer is, like said in comments: "impossible to know from an image". However I'm going to try:
There are obviously multiple things that are "off".

*

*Different fonts, see inputs.

*Different paddings, see forms.

*Different markup, see horizontal line right image (and black bar on top).

Long story short: It looks like a different stylesheet is being used.
This make me believer that a different stylesheet IS being used. So you need to check the next steps.

*

*Are you looking at a cached version? Try putting chrome in incognito mode, flush cache etc...

*Are preprocessors being run, is everything compiled OK? (If appliccable.)

*Is your deployment successful?, did you run required preprocessor on deployment (if needed)? Did you perform a cache bust at the deployment target?

Please inspect the page and validate the stylesheets match.


text:
Q: Constructor Argument Unrecognized I am getting a compiler error when trying to construct an instance of nested class A::B in the following code:
#include <cstdio>

using namespace std;

struct A{
    int n;

    A():
    n(1){}

    struct B{
        A& a;

        B(A a):
        a(a){
            a.n=2;
        }

        ~B(){
            a.n=0;
        }
    };
};

int main() {
    A a;
    printf("%d\n",a.n);
    do{
        A::B(a);
        printf("%d\n",a.n);
    }while(false);
    printf("%d\n",a.n);
    return 0;
}

When I call the constructor of A::B the compiler does not recognize the argument. What did I do wrong?

A: This line doesn't do what you think it does:
A::B(a);

The parentheses are actually superfluous. That line is equivalent to:
A::B a;

And there's no default constructor for B, hence the compile error. You need to provide a name for the object, which you can call _ as additional indication that it's just there as a scope guard:
A::B _(a);

A: This is basically a variant of the most vexing parse. The code:
CriticalSection::Locker(cs);

...doesn't define an object of type CriticalSection::Locker because you haven't supplied an argument to the ctor as needed.
The cure is to define the name of the object:
CriticalSection::Locker lock(cs);

You could also use "universal" initialization:
CriticalSection::Locker lock{cs};

This way, if you accidentally leave out the name of the object you're trying to define, you'll probably get an error message that's at least a little clearer about what's going on.
As an aside: unless you're pretty sure you gain something from using the wx variants, I'd at least consider using std::mutex and std::lock_guard instead.


text:
Q: Programmatically stopping MDB in JBoss 5.1.0GA I am trying to stop a MDB in JBoss 5.1.0.
My code is as follows :
public static void stopAllMDB()
        throws InterruptedException, MalformedObjectNameException, NullPointerException {

        String currentVersion = "1.0";

        for (String name : Util.MDB_NAMES) {
            String mbean = "jboss.j2ee:ear=myEar" + currentVersion + ".ear,jar=myJar.jar,name=myMDB,service=EJB3";
            ObjectName objName = new ObjectName(mbean);

            System.out.println("Stop MDB " + name);
            try {
                MBeanServer mbeanServer = MBeanServerLocator.locateJBoss();
                MessagingDelegateWrapperMBean invoker = (MessagingDelegateWrapperMBean)MBeanProxy.get(MessagingDelegateWrapperMBean.class,
                        objName, mbeanServer);
                invoker.stopDelivery();
                }
            } catch (Exception e) {
            }
 }

But if fails at
MessagingDelegateWrapperMBean invoker = (MessagingDelegateWrapperMBean)MBeanProxy.get(MessagingDelegateWrapperMBean.class,objName, mbeanServer)

with

Illegal argument exception.

A: Apparently the code I was using wasn't working. Don't know why. On a JBoss 5.1.0 GA platform the following apply :
MBeanServer mbeanServer = MBeanServerLocator.locateJBoss();
String mbean = "jboss.j2ee:ear=myEar.ear,jar=all-ejbs.jar,name=" + name + ",service=EJB3";
ObjectName objectName = new ObjectName(mbean);
mbeanServer.invoke(objectName, "stopDelivery", new Object[] {}, null);

And as a remark I didn't experience the session exception you got.


text:
Q: Why would CSS stop working when a snippet is made into a directive? I made a directive for a specifically styled Comment Item (ionic)
<comment-item file="commentItemDefault" comment="obj.comment></comment-item>
All of the code is the same with in the template commentItemDefault
<ion-item ng-class="{ 'read': comment.read }">

{{comment.from}}

{{comment.copy}}

</ion-item>

The read class is never applied.
.read{
  background-color: #660000 !important;
}

Can anyone help on this?

A: Maybe there's another syntax I'm unaware of, but it looks like you're doing an odd variation of ng-class's map syntax, which looks like this:
<ion-item ng-class="{ 'read': comment.read }"> ... </ion-item>

A: Solution:
.read{
    background-color: #bddef4 !important;
    .item-content{
        background-color: transparent !important;
    }
}

in ionic you have to bypass the .item-content class to see custom item colors and styles.
I hope this helps.
Thanks


text:
Q: Receiving events created when using a custom calendar like iCal Lets say I've used a library like https://github.com/markuspoerschke/iCal to transform my event data into a ical feed.
This feed is then consumed by a client.
On the client they can see the events in their calendar.
When new events are created on the client, how can I get this information and process it on the web server?
Can this be done with something like ical? Where the client has a callback to the web server with the altered feed, containing the new events data?
Or is this functionality reserved only for apps using the native language to hook into native APIS?


text:
Q: Как добавить кнопку в модальном окне, которая откроет еще одно модальное окно? никак не получается

// Get the modal
var modal = document.getElementById('myModal');

// Get the button that opens the modal
var btn = document.getElementById("myBtn");

// Get the  element that closes the modal
var span = document.getElementsByClassName("close")[0];

// When the user clicks the button, open the modal
btn.onclick = function() {
    modal.style.display = "block";
}

// When the user clicks on  (x), close the modal
span.onclick = function() {
    modal.style.display = "none";
}

// When the user clicks anywhere outside of the modal, close it
window.onclick = function(event) {
    if (event.target == modal) {
        modal.style.display = "none";
    }
}
/* The Modal (background) */
.modal {
    display: none; /* Hidden by default */
    position: fixed; /* Stay in place */
    z-index: 1; /* Sit on top */
    left: 0;
    top: 0;
    width: 100%; /* Full width */
    height: 100%; /* Full height */
    overflow: auto; /* Enable scroll if needed */
    background-color: rgb(0,0,0); /* Fallback color */
    background-color: rgba(0,0,0,0.4); /* Black w/ opacity */
    -webkit-animation-name: fadeIn; /* Fade in the background */
    -webkit-animation-duration: 0.4s;
    animation-name: fadeIn;
    animation-duration: 0.4s
}

/* Modal Content */
.modal-content {
    position: fixed;
    bottom: 0;
    background-color: #fefefe;
    width: 100%;
    -webkit-animation-name: slideIn;
    -webkit-animation-duration: 0.4s;
    animation-name: slideIn;
    animation-duration: 0.4s
}

/* The Close Button */
.close {
    color: white;
    float: right;
    font-size: 28px;
    font-weight: bold;
}

.close:hover,
.close:focus {
    color: #000;
    text-decoration: none;
    cursor: pointer;
}

.modal-header {
    padding: 2px 16px;
    background-color: #5cb85c;
    color: white;
}

.modal-body {padding: 2px 16px;}

.modal-footer {
    padding: 2px 16px;
    background-color: #5cb85c;
    color: white;
}

/* Add Animation */
@-webkit-keyframes slideIn {
    from {bottom: -300px; opacity: 0}
    to {bottom: 0; opacity: 1}
}

@keyframes slideIn {
    from {bottom: -300px; opacity: 0}
    to {bottom: 0; opacity: 1}
}

@-webkit-keyframes fadeIn {
    from {opacity: 0}
    to {opacity: 1}
}

@keyframes fadeIn {
    from {opacity: 0}
    to {opacity: 1}
}

Bottom Modal

<button id="myBtn">Open Modal</button>

      ×

Modal Header

Some text in the Modal Body

Some other text...

Modal Footer

A: Как вариант можно поместить еще одну кнопку для нового окна в первое модальное и создавать новое окно динамически через document.createElement. В нашем случае document.createElement('div');. А далее в функции onclick написать что-то подобное (Простите за повтор было лень, но думаю смысл понятен)
newModalBtn.onclick = () => {
        modal.style.display = "none";
        var newModalWindow = document.createElement('div');

        newModalWindow.innerHTML =
            "
\n" +
            "
\n" +
            "            ×\n" +
            "
Modal Header2
\n" +
            "
\n" +
            "
\n" +
            "
Some text in the Modal Body
\n" +
            "
Some other text...
\n" +
            "
\n" +
            "
\n" +
            "
Modal Footer
\n" +
            "
\n" +
            "        <button id=\"newModalBtn\">newModal</button>\n" +
            "
"

        document.body.appendChild(newModalWindow);
        newModalWindow.style.display = "block";
    }


text:
Q: File class AS3 / AIR: let user choose only save location, not file name or extension When using browseForSave method, is it possible to let the user choose only the location of a file, and not the file name or the extension?
I'm creating an encrypted file, and I need its name and extensions not to be changed by the user.
Thx!

EDIT (AFTER SOLVED)
I was simply looking for the browseForDirectory method. Shame on me. :)

A: For a reference on how to open a browse dialog to choose a folder see the example here:
How to create "Browse for folder" dialog in Adobe FLEX?
once you have your directory you can piece that together with code here to save a file using the FileStream object:
http://blog.everythingflex.com/2008/02/25/file-and-filestream-within-air/
copied here since it's an external link
    private function saveFile():void{
        var myPattern:RegExp = / /g;
        var newFileName:String = fileName.text.replace('.txt','');
        if(newFileName.length > 1){
            var file:File = File.desktopDirectory.resolvePath("Files/" + newFileName.replace(myPattern,'_') + ".txt");
            var stream:FileStream = new FileStream()
            stream.open(file, FileMode.WRITE);
            var str:String = contents.text;
            str = str.replace(/\r/g, File.lineEnding);
            stream.writeUTFBytes(str);
            stream.close();
            fdg.directory = File.desktopDirectory.resolvePath("Files/");
            fileName.text = "";
            contents.text = "";
          } else {
              mx.controls.Alert.show("File name is required", "Error Saving File");
          }
    }

A: One solution would be to set the file object like this:
var f:File = File.desktopDirectory.resolvePath("*.txt");
f.addEventListener(Event.SELECT, onSelected);
f.browseForSave("save txt file");

Although user can still override that in the opened dialog, but at least the dialog shows the file extension. And later in the Event.SELECT you can check and confirm what user has selected.


text:
Q: Python Requests sends TLS_EMPTY_RENEGOTIATION_INFO_SCSV in Client Hello? I am using Python requests on a client to make a TLS connection to a server. This is the code that i am using:
import ssl
import requests

from requests.adapters import HTTPAdapter
from requests.packages.urllib3.poolmanager import PoolManager
from requests.packages.urllib3.util import ssl_

CIPHERS = (
    'RSA+AES'
)

class TlsAdapter(HTTPAdapter):

    def __init__(self, ssl_options=0, **kwargs):
        self.ssl_options = ssl_options
        super(TlsAdapter, self).__init__(**kwargs)

    def init_poolmanager(self, *pool_args, **pool_kwargs):
        ctx = ssl_.create_urllib3_context(ciphers=CIPHERS, cert_reqs=ssl.CERT_REQUIRED, options=self.ssl_options)
        print(ssl.PROTOCOL_TLS)
        self.poolmanager = PoolManager(*pool_args,
                                       ssl_context=ctx,
                                       **pool_kwargs)

session = requests.session()
adapter = TlsAdapter(ssl.OP_NO_TLSv1 | ssl.OP_NO_TLSv1_1)
session.mount("https://", adapter)
r = session.request('GET', 'https://awesome.com', verify='/etc/ssl/certs/ca-certificates.crt')
print(r)

When i examine the client hello message in Wireshark, i see an additional cipher "TLS_EMPTY_RENEGOTIATION_INFO_SCSV" in the list of ciphers provided by the client.
Can anyone tell me what this cipher is and what it does? Is there a way to remove this from the list of ciphers being sent in the client hello message?
I tried looking up this issue but could not find a suitable answer.
Thanks!


text:
Q: How to recieve socket.io message from node.js server to android client I have an application that in server side we configured a socket.IO for it.
and I want to connect my application to that, listening to server when an event happened ,then my application Log a message in android side.
I have a BaseActivity that all of my activities extends from that. and in BaseActivity I setup Socket.IO:
    protected var mSocket: Socket? = null

    try {
         mSocket = IO.socket("http://myDomain.co")
    } catch (e: URISyntaxException) {
    }

    mSocket!!.connect()

then in target activity I use this code:
mSocket!!.on("record_create", { args ->
    this@MainPage.runOnUiThread({
        val data = args[0] as JSONObject
        Log.i("LOGGG", data.getString("record_create").toString())
    })
})

but nothings happened!
whats my problem?
Or
How can I do this job in best way?

A: I solved this problem by myself:
by initializing socket.io in target activity, and call socket.io listeners in this class


text:
Q: php time handling NULL as 00:00:00 I have a database with times stored as TIME as in 00:00:00 format. The database accepts NULL, but I also use functions that convert the time to a 12-hour format for viewing only.
The problem is: when the time input is empty, the functions that convert the format are changing the NULL to 00:00:00 which I would be fine with, but I cannot get it to not print 12:00 AM when converting it back to 12-hour time.
I need to either:

*

*Have the input go into the database as NULL not 00:00:00
OR

*

*Display nothing when converting 00:00:00 to 12-hour time.

These are the variations of the functions I have been using, again it is working if the value is a real time.
function time_12_to_24_sql ($value, $default) {
    $time = $_POST[$value];

    return ((!array_key_exists($value,$_POST)) || $_POST[$value] == NULL) ? $defaultValue : date("H:i:s", strtotime($time));
}

function time_12_to_24 ($input) {

if($input == NULL) {
    $retVal = $input;
}
if($input == 'NULL') {
    $retVal = $input;
}
if (!isset($input)) {
    $retVal = NULL;
}
if($input == '12:00 AM') {
    $retVal = NULL;
}
if($input == '') {
    $retVal = NULL;
}
else {
    $retVal = date("H:i:s", strtotime($input));
}
return $retVal;
}

function time_24_to_12 ($input) {
    if($input == NULL) {
        $retVal = $input;
    }
    if (strtotime($input) == '00:00:00') {
        $retVal = '';
    }
    if ($input == '') {
        $retVal = '';
    }
    if (!isset($input)) {
        $retVal = '';
    }
    else {
        if(strtotime($input) > 0){
            $retVal = date("g:i A", strtotime($input));
        }
    }
    return $retVal;
}

A: You're kind of abusing strtotime() here. What you want to be doing is using PHP's date formatting functions:
function time_24_to_12 ($input) {
    // empty checks for null, empty string, zero, false, unset, etc.
    if (empty($input)) {
        return "";
    }
    $date = DateTime::createFromFormat("H:i:s", $input);
    $time = $date->format("h:i:s A");
    return ($time === "12:00:00 AM") ? "" : $time;
}

function time_12_to_24 ($input) {
    if (empty($input)) {
        return "";
    }
    $date = DateTime::createFromFormat("h:i:s A", $input);
    $time = $date->format("H:i:s");

    return ($time === "00:00:00") ? "" : $time;
}

(If you wanted to get fancy you could do a regular expression check on the input, instead of just checking for empty.)
Now this should work as you're looking for:
echo time_24_to_12("23:34:29") . "\n";
echo time_24_to_12("00:00:00") . "\n";
echo time_24_to_12("") . "\n";

echo time_12_to_24("11:34:29 PM") . "\n";
echo time_12_to_24("12:00:00 AM") . "\n";
echo time_12_to_24(null) . "\n";

Result:
11:34:29 PM

23:34:29


text:
Q: Maths problem on distance Distance from city $x$ to $y$ is 1000 kms. A merchant has 3 elephants and 3000 bananas. The merchant wants to transport bananas from $x$ to $y$. The maximum capacity of an elephant is 1000 bananas, and it consumes 1 banana per km. What is the maximum number of bananas the merchant can transport?

A: Put 1000 bananas on each elephant. Start walking.
333km later, your elephants have consumed 999 bananas.
Each elephant has 667 bananas.
From one of the three elephants, distribute all his bananas among the other two elephants.
There is one banana left over. Throw it away.
Throw away the useless elephant.
You now have two elephants with 1000 bananas each.
Have both elephants walk 500km.
Now both elephants have 500 bananas each.
Your elephants have now walked 833km.
Take all the bananas from one elephant and put them on the other elephant.
Throw away the useless elephant.
You now have one elephant with 1000 bananas.
Have your elephant walk the remaining 167km.
Your elephant arrives with 833 bananas.
This is assuming that (a) the merchant is not interested in saving all his elephants (this would be clearly impossible) and (b) there is no postal service.


text:
Q: Problem with Solr dynamic/copy Field I have a problem that i have a dynamic field in schema.xml
as <dynamicField name="sec_*" type="text" indexed="true" stored="false"/>
and <field name="Contents" type="text" indexed="true" stored="false" multiValued="true"/>
dynamic field is copied to Contents field as
<copyField source="sec_*" dest="Contents"/>

now when i perform search using some dynamic fields like "sec_1069:risk" it filters documents that does not contains that dynamic field called sec_1069 can any body help how i can force this thing that solr should not filter documents that don't have that dynamic field.

A: Try sec_1069:risk OR -sec_1069:[* TO *]


text:
Q: Add rows in a dataframe when a special character is encountered in a row My initial data looks like following :
ColA   ColB                 ColC
Sku1   Life/Personal        NA
Sku2   Children             NA
Sku3   Grooming/Hair/Makeup NA

I want for ever slash ("/") in Col B, text after that should come in another row. For ex, above data should look like below :
ColA   ColB          ColC
Sku1   Life          NA
Sku1   Personal      NA
Sku2   Children      NA
Sku3   Grooming      NA
Sku3   Hair          NA
Sku3   Makeup        NA

A: First split the values in column B by the delimiter '/'.
df['ColB'] = df['ColB'].str.split('/')

Then use explode to split the lists in column B into new rows.
df = df.explode('ColB')


text:
Q: Can pthreads only share global resources? I'm trying to share a structure between two threads that is not a global variable. The variable itself is instantiated on the stack in the main function, then its pointer is passed as the parameter to both threads on the start up of both threads.
What I'm finding is that when I change the value of a member of that structure that change is not reflected ever in the other pthread. Is there a way to share a non-global variable (say an integer for example) between two threads, such that changes done to that variable in one thread appear in the other?
This is all because I want to avoid adding global variables for code-maintainability.

A: Remember that threads get their own stack -- so if you pass an integer in and the function goes out of scope, you're referring to memory that now holds something entirely different.
void foo(void)
{
    pthread_t t1, t2;
    struct foo common_value;

    if (pthread_create(&t1, NULL, a, &common_value) != 0)
    {
        return -1;
    }

    if (pthread_create(&t2, NULL, b, &common_value) != 0)
    {
        return -1;
    }

    // upon exiting this function, common_value is no longer what you think it is!
}

A: I make no pretence at elegance, but this seems to work for me on MacOS X 10.5.8.
#include <pthread.h>
#include <stdio.h>
#include <stdlib.h>
#include <unistd.h>

static void *writer(void *arg)
{
    int * volatile i = arg;

    for (*i = 1; *i < 10; (*i)++)
    {
        printf("writer(): pseudo_global = %d\n", *i);
        fflush(stdout);
        sleep(1);
    }
    printf("writer(): pseudo_global = %d (exiting)\n", *i);
    fflush(stdout);
    return(0);
}

static void *reader(void *arg)
{
    int * volatile i = arg;
    while (*i < 10)
    {
        printf("reader(): pseudo_global = %d\n", *i);
        fflush(stdout);
        sleep(1);
    }
    printf("reader(): pseudo_global = %d (exiting)\n", *i);
    fflush(stdout);
    exit(0);
}

int main(void)
{
    volatile int pseudo_global = 0;
    pthread_t t1;
    pthread_t t2;
    if (pthread_create(&t1, 0, writer, &pseudo_global) != 0)
    {
        perror("pthread_create() for thread 1");
        exit(1);
    }
    if (pthread_create(&t2, 0, reader, &pseudo_global) != 0)
    {
        perror("pthread_create() for thread 1");
        exit(1);
    }
    while (pseudo_global < 10)
    {
        printf("main():   pseudo_global = %d\n", pseudo_global);
        fflush(stdout);
        sleep(1);
    }
    printf("main():   pseudo_global = %d (exiting)\n", pseudo_global);
    fflush(stdout);
    return(0);
}

Note that I put the 'volatile' qualifier into the code to 'make sure', but apart from eliciting warnings about discarded qualifiers in the calls to pthread_create(), it didn't make any significant difference.  I also ran the code without any volatile qualifiers without problem.
This code demonstrates, I think, that on at least one POSIX threads implementation, you can indeed share a local variable on the stack of a function that has not exited while the threads are running.
I am willing to believe I should be more careful about the thread termination and should make sure that main() does not exit without using pthread_join() to ensure that the threads have exited first.
Example output:
$ make ptex
gcc -O ptex.c -o ptex
ptex.c: In function 'main':
ptex.c:40: warning: passing argument 4 of 'pthread_create' discards qualifiers from pointer target type
ptex.c:45: warning: passing argument 4 of 'pthread_create' discards qualifiers from pointer target type
$ ./ptex
writer(): pseudo_global = 1
main():   pseudo_global = 0
reader(): pseudo_global = 1
writer(): pseudo_global = 2
main():   pseudo_global = 2
reader(): pseudo_global = 2
writer(): pseudo_global = 3
main():   pseudo_global = 3
reader(): pseudo_global = 3
writer(): pseudo_global = 4
main():   pseudo_global = 4
reader(): pseudo_global = 4
writer(): pseudo_global = 5
reader(): pseudo_global = 5
main():   pseudo_global = 5
writer(): pseudo_global = 6
reader(): pseudo_global = 6
main():   pseudo_global = 6
writer(): pseudo_global = 7
reader(): pseudo_global = 7
main():   pseudo_global = 7
writer(): pseudo_global = 8
reader(): pseudo_global = 8
main():   pseudo_global = 8
writer(): pseudo_global = 9
reader(): pseudo_global = 9
main():   pseudo_global = 9
writer(): pseudo_global = 10 (exiting)
reader(): pseudo_global = 10 (exiting)
main():   pseudo_global = 10 (exiting)
$

A: You are doing the right thing, but your experience suggests you are doing it wrong.  Please try moving it into a global variable and see if you continue to experience non sharing.
Once you have checked that please post some simple example code illustrating your problem that others can test.

A: In my opinion sharing a stack variable is worse than having a global variable.  At the very least I would allocate some memory on the heap to share between the threads.  If the memory is meant to live for the lifetime of the program, you don't even have to worry about freeing it and the main thread can return immediately.  With the stack variable, you have to make sure that you don't prematurely pop the stack frame where the variable is located.
Having said that, I think using a global is actually the better solution.  Put the global in a separate file and declare it static so that it is only global to the file.  Then, only put your thread functions in that file so only they have access to the variable.  I like this better since it makes it explicit that the memory is being shared by the threads.  The argument to pthread_create is really meant to be thread-specific context, and it won't necessarily be clear from looking at the thread functions that all the threads are being passed the same pointer.


text:
Q: Likelihood function when there is no common dominating measure? When we have a statistical model $\{ P_\theta, \theta\in\Theta\}$ on some common probability space, usually we define "the" likelihood function $L(\theta)$ via a Radon-Nikodym derivative with respect to some common dominating measure, say $\mu$. For that to be possible it is necessary that all the $P_\theta$ are equivalent in the sense that they agree on which events have probability zero or one. Without that assumption there is no common dominating measure.
What can we do to get a likelihood function when this is not the case? For instance, in the nonparametric setting of Is Maximum Likelihood Estimation (MLE) a parametric approach?  there is no common dominating measure. Ideas or references?

A: (Not really an answer, simply an elaboration on the comment. Apologies in advance.
It is a very interesting question. Hopefully the comment will be complementary to the answer(s) when they come along.)
It seems that, in order to make meaningful statistical statements, one needs densities/likelihood functions. Therefore a dominating measure necessarily shows up somewhere in the formulation, even in the non-parametric setting.
For example, take the classical fixed design non-parametric regression problem
$$
y_t = f(t) + \epsilon_t, \;\;t = \frac{k}{n}, \; k = 0, \cdots, 1,
$$
where $\epsilon_t \stackrel{i.i.d.}{\sim} (0, \sigma^2)$, and $f$ lies in, say, $C[0,1]$, the continuous functions on $[0,1]$.
The problem of estimating $f$ from $(y_t)$ is asymptotically equivalent to estimating drift $f$ from a sample path $Y_t$ of the stochastic process (Ito diffusion)
$$
dY_t = f dt + \sigma dW_t
$$
where $W_t$ is standard Brownian motion.
In this formulation, the problem becomes estimating a element $f$ of an infinite dimensional "parameter space" $C[0,1]$.
Statistically speaking, $Y_t$ is a probability measure $\mathbb{Q}^f$ on the Skorohod space $D[0,1]$, with Radon-Nikodym density
$$
\frac{d \mathbb{Q}^f}{ d \mathbb{P}} =e^{\int_0^1 \frac{f}{\sigma} dW_t - \frac{1}{2} \int_0^1 \frac{f^2}{\sigma^2} dt}
$$
with respect to the Wiener measure $\mathbb{P}$, which defines the law of $W$ (i.e. $f = 0$).
This is exactly like the parametric setting, except the model $\{ \mathbb{Q}^f \}_{ f \in C[0,1] }$ has an infinite dimensional "parameter space".
I believe the notion of contiguity, introduced by Le Cam, is in similar spirit---to introduce a framework where one can speak about densities and likelihood functions, when the parameter space is not necessarily finite-dimensional.


text:
Q: Change marker color base on values in matplotlib I have a simple data and would like to plot it by using python and matplotlib.
There are some "None" values in y values so I want to change the color of the marker when y value is None.
Please help.
Here is my code:
import random
import matplotlib.pyplot as plt

plt.style.use("fivethirtyeight")

x_vals = [1, 2, 3, 4, 5]
y_vals = [3, 5, "None", 6, "None"]

plt.plot(x_vals, y_vals, marker='o', markerfacecolor="y", label="Y-Value")

plt.legend(loc="upper left")
plt.tight_layout()

plt.tight_layout()
plt.show()


text:
Q: I want to automatically select combobox with value Could you please tell me how to solve this problem?
I want to autoselect combobox with value form database for display (not select with text).
Add the value and text to ComboBox
public void ComBoList(JArray Data)
{
        comboBoxBrand.Items.Clear();
        comboBoxSize.Items.Clear();
        comboBoxPCBrand.Items.Clear();
        comboBoxProductOf.Items.Clear();

        comboBoxBrand.DisplayMember = "Text";
        comboBoxBrand.ValueMember = "Value";
        comboBoxSize.DisplayMember = "Text";
        comboBoxSize.ValueMember = "Value";
        comboBoxPCBrand.DisplayMember = "Text";
        comboBoxPCBrand.ValueMember = "Value";
        comboBoxProductOf.DisplayMember = "Text";
        comboBoxProductOf.ValueMember = "Value";

        JArray AllData = JArray.Parse(Data.ToString());
        int JCount = AllData.Count;

        for (int i = 0; i <= (JCount - 1); i++)
        {
            foreach (var Values in AllData[i])
            {
                if (i == 0)
                {
                    int BId = int.Parse(Values["HddBrandId"].ToString());
                    comboBoxBrand.Items.Add(new { Text = Values["BrandName"].ToString(), Value = BId });
                }
                else if (i == 1)
                {
                    int SId = int.Parse(Values["SizeId"].ToString());
                    comboBoxSize.Items.Add(new { Text = Values["Size"].ToString(), Value = SId });
                }
                else if (i == 2)
                {
                    int PId = int.Parse(Values["PCBrandId"].ToString());
                    comboBoxPCBrand.Items.Add(new { Text = Values["BrandName"].ToString(), Value = PId });
                }
                else if (i == 3)
                {
                    int CId = int.Parse(Values["CountryId"].ToString());
                    comboBoxProductOf.Items.Add(new { Text = Values["CountryName"].ToString(), Value = CId });
                }
            }
        }
}

Select combobox with value from database:
comboBoxBrand.SelectedValue = Data.BrandId; // int Data from Database
comboBoxSize.SelectedValue = Data.SizeId; // int Data from Database
comboBoxPCBrand.SelectedValue = Data.PCBrandId; // int Data from Database
comboBoxProductOf.SelectedValue = Data.ProductOfId; // int Data from Database

Please help me.
Thank you.

A: DisplayMember and ValueMember are used when a combobox is populated using databinding (by setting the .DataSource property to a bindable collection)
Instead of putting things in your combo .Items collection, put them in a List, set the .DataSource to the list and then when you set .SelectedValue it will select an item from the list if the value you set equals the value of one of the .Value properties of the list items
To this end it's probably easier to use something like a ValueTuple (or a full class) than an anonymous type, but an anonymous type could be bound, you'd just have to have a fiddle to create a list for it, perhaps
var listToBind = new int []{}.Select(s=> new{ Text = "", Val=0}).ToList();

This would give you a List<anonymoustype<string,int>> into which you can load your anonymous typed items.. you can then set the combo DataSource to it and things should work as you expect.. though getting them out via SelectedItem will return you an object wrapping around the anonymous type, which you'll struggle to work with (my vote; make a proper class for DisplayValue pairs, or use a tuple, or something that already exists like KeyValuePair<T,T2>


text:
Q: How Do I Properly Determine User File System Permissions for a File? I am currently writing an application that needs to examine the current user's permission for a file in the Windows file system given the file path. The application is written in C# .Net 4.0. I believe I am "in the right area", but am in need of help "driving it home". This question is in the right ballpark:Iterate through permissions on a file in the windows file system in C#, but is more concerned with multiple users - I am concerned with the current user.
Here is what I have so far:
FileSecurity fsObj = file.GetAccessControl(AccessControlSections.Access);
foreach (FileSystemAccessRule fsar in fsObj.GetAccessRules(true, true, typeof(System.Security.Principal.NTAccount)))
{
    FileSystemRights fsr = fsar.FileSystemRights;
    // examine current fsr for permissions...
}

My goal is to determine whether the user has write access to the file.

A: I believe it can be done as such (untested):
if ((FileSystemRights.Write & fsar.FileSystemRights) != FileSystemRights.Write)
    return false;

return true;


text:
Q: How to use jQuery Datatable in asp.net core mvc I donwload jQuery Datatable and the files I put it in my wwwroot folder. This is the structure of wwwroot folder:
 -wwwroot
             -css
             -DataTable
               -DataTables-1.10.21
                  -css
                  -images
                  -js
               -datatables.css
               -datatables.js
             -IMG
             -js
             -lib

In my _Layout.cshtml I inserted :
  <link rel="stylesheet" href="~/DataTable/datatables.css" />

to use jQuery Datatable.
But I can't use it in my view page. This is what I try to do in my view page :
 *

                    @Html.DisplayNameFor(model => model.Nome)

                .....

*

Is it correct to do like this or not? I don't know if my  <link> and


text:
Q: Convert columns to list I have data in 2 columns (Region and GroupedCateg). Refer the dataframe below. I want to convert it into nested lists. I tried using group_by and do() function of dplyr and then convert into list but it didn't work.
df <- read.table(header = T,
                 text = '
Region  GroupedCateg
Beja    Alentejo
Evora   Alentejo
Portalegre  Alentejo
Faro    Algarve
Aveiro  Central
"Castelo Branco"    Central
Coimbra Central
Leiria  Central
Santarem    Central
Acores  Islands
Madeira Islands
Lisboa  Lisbon
Setubal Lisbon
Braga   North
Braganca    North
"Viana do Castelo"  North
"Vila Real" North
Porto   Porto
')

Desired Output in lists. Region would be in names. Respective GroupedCateg in nested list
list(
  list(
    name =  "Alentejo",
    categories = list("Beja", "Evora", "Portalegre")
  ),
  list(
    name =  "Algarve",
    categories = list("Faro")
  ),
  list(
    name =  "Central",
    categories = list("Aveiro", "Castelo Branco", "Coimbra", "Leiria", "Santarem" )
  ),

  list(
    name =  "North",
    categories = list("Braga", "Braganca", "Viana do Castelo", "Vila Real")
  ),
  list(
    name =  "Lisbon",
    categories = list("Lisboa", "Setubal")
  ),
  list(
    name =  "Islands",
    categories = list("Acores", "Madeira")
  ),

  list(
    name =  "Porto",
    categories = list("Porto")
  )

)

A: You can use pmap() in purrr.
library(dplyr)
library(purrr)

x <- df %>%
  group_by(GroupedCateg) %>%
  summarise(Region = list(Region)) %>%
  pmap(~ list(name = .x, categories = as.list(.y)))

The corresponding base R version:
y <- apply(aggregate(Region ~ GroupedCateg, df, c),
     1, function(y) list(name = y[[1]], categories = as.list(y[[2]])))

all.equal(x, y)
# [1] TRUE

Output
[[1]]
[[1]]$name
[1] "Alentejo"

[[1]]$categories
[[1]]$categories[[1]]
[1] "Beja"

[[1]]$categories[[2]]
[1] "Evora"

[[1]]$categories[[3]]
[1] "Portalegre"

[[2]]
[[2]]$name
[1] "Algarve"

[[2]]$categories
[[2]]$categories[[1]]
[1] "Faro"

[[3]]
[[3]]$name
[1] "Central"

[[3]]$categories
[[3]]$categories[[1]]
[1] "Aveiro"

[[3]]$categories[[2]]
[1] "Castelo Branco"

[[3]]$categories[[3]]
[1] "Coimbra"

[[3]]$categories[[4]]
[1] "Leiria"

[[3]]$categories[[5]]
[1] "Santarem"

[[4]]
[[4]]$name
[1] "Islands"

[[4]]$categories
[[4]]$categories[[1]]
[1] "Acores"

[[4]]$categories[[2]]
[1] "Madeira"

[[5]]
[[5]]$name
[1] "Lisbon"

[[5]]$categories
[[5]]$categories[[1]]
[1] "Lisboa"

[[5]]$categories[[2]]
[1] "Setubal"

[[6]]
[[6]]$name
[1] "North"

[[6]]$categories
[[6]]$categories[[1]]
[1] "Braga"

[[6]]$categories[[2]]
[1] "Braganca"

[[6]]$categories[[3]]
[1] "Viana do Castelo"

[[6]]$categories[[4]]
[1] "Vila Real"

[[7]]
[[7]]$name
[1] "Porto"

[[7]]$categories
[[7]]$categories[[1]]
[1] "Porto"

A: Using base split on column, then lapply to re-format as desired:
x <- split(df$Region, df$GroupedCateg)

res <- lapply(names(x), function(i){
  list(name = i,
       categories = as.list(x[[ i ]]))
})

A: In Base-R
apply(aggregate(Region~GroupedCateg,df,c),1, function(x) list(name=x[1], category=as.list(x[2]$Region)))

[[1]]
[[1]]$name
[[1]]$name$GroupedCateg
[1] "Alentejo"

[[1]]$category
[[1]]$category[[1]]
[1] "Beja"

[[1]]$category[[2]]
[1] "Evora"

[[1]]$category[[3]]
[1] "Portalegre"

[[2]]
[[2]]$name
[[2]]$name$GroupedCateg
[1] "Algarve"

[[2]]$category
[[2]]$category[[1]]
[1] "Faro"

[[3]]
[[3]]$name
[[3]]$name$GroupedCateg
[1] "Central"

[[3]]$category
[[3]]$category[[1]]
[1] "Aveiro"

[[3]]$category[[2]]
[1] "Castelo Branco"

[[3]]$category[[3]]
[1] "Coimbra"

[[3]]$category[[4]]
[1] "Leiria"

[[3]]$category[[5]]
[1] "Santarem"

[[4]]
[[4]]$name
[[4]]$name$GroupedCateg
[1] "Islands"

[[4]]$category
[[4]]$category[[1]]
[1] "Acores"

[[4]]$category[[2]]
[1] "Madeira"

[[5]]
[[5]]$name
[[5]]$name$GroupedCateg
[1] "Lisbon"

[[5]]$category
[[5]]$category[[1]]
[1] "Lisboa"

[[5]]$category[[2]]
[1] "Setubal"

[[6]]
[[6]]$name
[[6]]$name$GroupedCateg
[1] "North"

[[6]]$category
[[6]]$category[[1]]
[1] "Braga"

[[6]]$category[[2]]
[1] "Braganca"

[[6]]$category[[3]]
[1] "Viana do Castelo"

[[6]]$category[[4]]
[1] "Vila Real"

[[7]]
[[7]]$name
[[7]]$name$GroupedCateg
[1] "Porto"

[[7]]$category
[[7]]$category[[1]]
[1] "Porto"


text:
Q: What will happen if function goes out of stack space during infinite recursion? There is a function that calls itself recursively infinitely.
This function has some arguments too.
For every function call the arguments and return address are pushed on the stack .
For each process there is fixed size of stack space that cannot grow dynamically like heap.
And I guess each thread also has its own stack.
Now if a function is called recursively infinitely and process runs out of stack space , what will happen?
Will program crash?
Will OS handle the situation?
There is 4GB of address space so why cannot OS do something to increase stack size.

A: stack overflow.
In UNIX and compatible the process will get terminated throwing SIGSEGV or SIGSTKFLT signal.
In Windows the process will get terminated throwing exception STATUS_STACK_OVERFLOW.

A: For C++ at least, you will be in the realms of "undefined behaviour" - a bit like the Twilight Zone, anything could happen.
And if the recursion is infinite, what good will increasing the stack size do? Better to fail early than later.

A: Depending on the language you will either get an exception (e.g. in Java) or the program will crash (in C, C++).
Typically the stack is relatively small, because that suffices, and a stack overflow signals an error. In Java you can increase the stack space with a command line option if you must.
Also note that functional languages typically compile tail recursion into a loop, and no stack space is used in that case.

A: This isn't language-agnostic - it very much depends on the language/platform.
In C# (or any .NET language) you'll get a StackOverflowException, which as of .NET 2.0 cannot be caught and will bring down the process.
In Java (or any JVM language) you'll get a StackOverflowError (as specified here).
I'll leave it to other answers to deal with other languages and platforms :)

A: A typical Unix result will be a segmentation fault. Don't know about Windows.

A: Yes, your program will crash. There is no way for the OS to "handle the situation", other than preventing your buggy code from damaging other processes (which it is already doing). The OS has no way of knowing what it was you really wanted your program to do, rather than what you told it to do.

A: There are plenty of answers what will happen, but I want to mention the extremely easy solution:
Just by a turing machine and let your code run on that. It will have plenty of space.

A: The program will crash. Usually stack is limited by operating systems in order to trap bugs like this before they consume ALL available memory. On Linux at least the stack size can be changed by the user by issuing the limit command in shell.


text:
Q: Deleting from sqlite database using IN I am deleting from an sqlite database using the ids of the records like this
(the dirID is an array of the IDs):
Dim i As Integer = 0
        Dim conn As New SQLiteConnection("Data Source=" & DBPath)

        Dim cmd As New SQLiteCommand("DELETE FROM directory WHERE id IN (@ID)", conn)
        cmd.Parameters.AddWithValue("@ID", Join(dirID, ","))
        'conn.SetPassword(dbPassword)
        conn.Open()
        Try

            mytransaction = conn.BeginTransaction()
            '// delete directory //
            If dirID IsNot Nothing Then
                cmd.ExecuteNonQuery()
            End If

            mytransaction.Commit()
            conn.Close()

        Catch ex As Exception
            mytransaction.Rollback()
            strLastError = ex.Message
            Debug.Print(strLastError)
        Finally
            cmd.Dispose()
            conn.Dispose()
        End Try

The problem is that it doesn't always delete from the database, and its not throwing any errors.
Could there be a better way of deleting?

A: That's not how parameters work.
If your IN list is 1, 2, 3, the command is trying to delete the record where ID equals "1, 2, 3", which is none. So no error is thrown and no record is deleted, because none was found. Thus, you will also find out that your code only works when your list contains 1 item.
Solution: You have to build your delete query (string manipulation), instead of working with parameters. Just beware of SQL Injection.
Update
From your code, it would be something  like that:
Dim delcmd = "DELETE FROM directory WHERE id IN (" + Join(dirID, ",") + ")"
Dim cmd As New SQLiteCommand(delcmd, conn)

And no parameter call. Beware: I just tweaked your code, but it is not SQL Injection safe. You should read about that and about what's been written on the subject here in StackOverflow.