text:
Q: jquery Colorbox data scrolling with flot graph Good Day,
I use colorbox for displaying data in new window.
Everything was good, but I have to display dynamically created data (table with data) and then to draw graph. It was decided to draw data with flot graph jQuery library.
It was tested in firefox and ie. Graph is good. But when colorbox window is scrolling in ie, graph remains in the same place and other content (table) is scrolling. In firefox scrolling works good.
Colorbox init:
$.colorbox({ maxWidth:"95%",
             maxHeight:"80%",
             scrolling:true,
             html: htmlData,
             onComplete: function(){$.graphCreate();}});

htmlData -

......

then when colorbox complete - $.graphCreate();
$.plot($("#placeholder"),data, {
    series: {
        stack: stack,
    },
    xaxis: {
        ticks: [[1, "Fri, Mar 02 2012"], [2, "Sat, Mar 03 2012"], [3, "Sun, Mar 04 2012"], [4, "Mon, Mar 05 2012"]],
    }
});


text:
Q: accessing web method declared in .cs file not associated to any aspx or ascx file in ajax(jquery) Hi I moved a web method from code behind file of an aspx page to another cs file which is present in data section(which doesn't contain any aspx page). Previously I used to access web method by using Ajax, the url like
type: "post",
contentType: "application/json; charset=utf-8",
dataType: "json",
url: "Results.aspx/EmployeeSummaryHistory",   // call history function
data: JSON.stringify(emp),
success: function (resp) {

but now I am trying to access the moved web method by using the Url
type: "post",
contentType: "application/json; charset=utf-8",
dataType: "json",
url: "~/Model/Data/EmployeeRepository.cs/EmployeeSummaryHistory",   // call history function
data: JSON.stringify(emp),
success: function (resp) {

but I am getting error and I don't know how to access web method declared in .cs file which doesn't contain any aspx file associated to it please help me with this.
My web method is like
[WebMethod]
public static List<RefEmployee> EmployeeSummaryHistory(string empNo)
{
    var employee = new RefEmployeeRepository();
    //Employee History.
    List<RefEmployee> list = new List<RefEmployee>();
    list = employee.SummaryHistEmployee(empNo);
    return list;
}

A: They are called ASP.NET AJAX Page Methods for a reason, the endpoint must be public static methods, decorated with the WebMethod attribute, that are within a Page class or class that derives from Page.

A: Try this
    var theWebRequest = HttpWebRequest.Create("http://localhost:51045/Default.aspx/Senddata");
                theWebRequest.Credentials = new NetworkCredential(tobj.Username, tobj.Password,tobj.propertyID);
                theWebRequest.Method = "POST";
                theWebRequest.ContentType = "application/json; charset=utf-8 ";
                //theWebRequest.Headers.Add(HttpRequestHeader.Pragma.ToString, "no-cache");
                using (var writer = theWebRequest.GetRequestStream())
                {
                    string json = new JavaScriptSerializer().Serialize(new
                    {
                        something = value
                    });

                    var data = Encoding.UTF8.GetBytes(json);

                    writer.Write(data, 0, data.Length);
                    writer.Flush();
                    writer.Close();
                }

                var theWebResponse = (HttpWebResponse)theWebRequest.GetResponse();
                var theResponseStream = new StreamReader(theWebResponse.GetResponseStream());
                string result = theResponseStream.ReadToEnd().ToString();
   var data1 = new JavaScriptSerializer().DeserializeObject(result);

redpajama_set_name: RedPajamaStackExchange


text:
Q: Is there the empty topological space?
*

*May the empty set be a topological space?
Is the set $\{\emptyset\}$ its topology?

*What about the empty metric space?

A: *

*Definitely yes and yes. In point of fact, it's the initial object of the category of topological spaces. It is compact, but as far as I know it is currently a matter of debate whether it should be considered connected or not.

*I would say yes (like wikipedia does). It's homeomorphic to the empty topological space and it still is the initial object in all the categories I can think of putting on metric spaces (namely: the category with continuous maps, or the category of uniformly continuous maps, or the category of Lipschitz maps, or the category of non-expansive maps).


text:
Q: Getting error in finding spatial reference of shapefile I am working on Ubuntu, when I tried to read spatial reference of shapefile it give me this error.
spatialRef = layer.GetSpatialRef().ExportToProj4()

Traceback (most recent call last):
File "< stdin >", line 1, in < module >
AttributeError: 'NoneType' object has no attribute 'GetSpatialRef'

Help me to remove it

A: I don't understand your problem. You need a layer or a geometry or an EPSG code
With the www2.census.gov/geo/tiger//TIGER2009/tl_2009_us_state.zip shapefile
from osgeo import ogr
file = ogr.Open('tl_2009_us_state.shp') # from www2.census.gov/geo/tiger/TIGER2009/tl_2009_us_state.zip
layer = file.GetLayer()
spatialRef = layer.GetSpatialRef()
spatialRef.ExportToProj4()
'+proj=longlat +datum=NAD83 +no_defs '
spatialRef.AutoIdentifyEPSG()
spatialRef.GetAuthorityCode(None)
'4269'

With a geometry
feature = layer.GetNextFeature()
geometry = feature.GetGeometryRef()
spatialRef = geometry.GetSpatialReference()
spatialRef.ExportToProj4()
'+proj=longlat +datum=NAD83 +no_defs '

With an EPSG code (EPSG:4269)
spatialRef = osr.SpatialReference()
spatialRef.ImportFromEPSG(4269)
spatialRef.ExportToProj4()
'+proj=longlat +ellps=GRS80 +towgs84=0,0,0,0,0,0,0 +no_defs '

A: This is how I read the spatial reference of a shapefile.
from osgeo import ogr
file = ogr.Open("C:\file_path\file_name.shp")
layer = file.GetLayer()
spatial_ref= layer.GetSpatialRef()
print spatial_ref

To get the individual spatial reference attributes:
spatial_attr = spatial_ref.GetAttrValue('projcs')
print spatial_attr

This will output the projection coordination system, e.g. "WGS_1984_UTM_Zone_38N".

A: AttributeError: 'NoneType' object has no attribute 'GetSpatialRef'

The error message means, that your layer variable is empty. Check the way you obtain it.


text:
Q: remove indentation and formatting in html string I am using the below code snippet to get the html string of a control. This response has a lot of formatting characters like \n, \t, \r for indenting the html. How do i remove this without wihtout affecting formatting of actual text within the controls.
public static string RenderControl( Control control )
{
            string renderedString;

            using ( TextWriter writer = new StringWriter( ) )
            {
                control.RenderControl( new HtmlTextWriter( writer ) );
                renderedString = writer.ToString( );
            }

            return renderedString;
}

For ex-
if i see the response of a table control it looks something like -

\r\n\t\t
\r\n\t\t
abc\r\n def	...

the output i need is -

abc\r\n def	...

A: If the generated markup is XML-compatible, then you could parse the result with an XmlReader or even an XmlDocument instance and use an XmlWriter to rewrite the markup but with XmlWriterSettings set to remove all unnecessary whitespace.
An alternative (and potentially easier) strategy is described below:
In XML (and HTML) only single whitespace characters are significant, so you could do a quick and easy fix by putting the generated markup into a regular expression replacement that removes all adjacent whitespace characters (i.e. replace "\s\s+" with "" - '\s' is the .NET Regex symbol for any whitespace character).


text:
Q: Using set -e / set +e in bash with functions I've been using a simple bash preamble like this in my scripts:
#!/bin/bash
set -e

In conjunction with modularity / using functions this has bitten me today.
So, say I have a function somewhere like
foo() {
  #edit: some error happens that make me want to exit the function and signal that to the caller
  return 2
}

Ideally I'd like to be able to use multiple small files, include their functions in other files and then call these functions like
set +e
foo
rc=$?
set -e

. This works for exactly two layers of routines. But if foo is also calling subroutines like that, the last setting before the return will be set -e, which will make the script exit on the return - I cannot override this in the calling function. So, what I had to do is
foo() {
  #calling bar() in a shielded way like above
  #..

  set +e
  return 2
}

Which I find very counterintuitive (and also not what I want - what if in some contexts I'd like to use the function without shielding against failures, while in other contexts I want to handle the cleanup?) What's the best way to handle this? Btw. I'm doing this on OSX, I haven't tested whether this behaviour is different on Linux.

A: Shell functions don't really have "return values", just exit codes.
You could add && : to the caller, this makes the command "tested", and won't exit it:
foo() {
    echo 'x'
    return 42
}

out=$(foo && :)
echo $out

The : is the "null command" (ie. it doesn't do anything). In this case it doesn't even get executed, since it only gets run if foo return 0 (which it doesn't).
This outputs:
x

It's arguably a bit ugly, but then again, all of shell scripting is arguably a bit ugly ;-)
Quoting sh(1) from FreeBSD, which explains this better than bash's man page:
 -e errexit
         Exit immediately if any untested command fails in non-interactive
         mode.  The exit status of a command is considered to be explicitly
         tested if the command is part of the list used to control an if,
         elif, while, or until; if the command is the left hand operand of
         an "&&" or "||" operator; or if the command is a pipeline preceded
         by the ! operator.  If a shell function is executed and its exit
         status is explicitly tested, all commands of the function are con‐
         sidered to be tested as well.


text:
Q: Angular: mat-form-field must contain a MatFormFieldControl I am trying to add a form field with custom telephone number input control. I used the example of the phone from https://material.angular.io/components/form-field/examples.
Here is the code:
<mat-form-field>
  <example-tel-input placeholder="Phone number" required></example-tel-input>
  <mat-icon matSuffix>phone</mat-icon>
  <mat-hint>Include area code</mat-hint>
</mat-form-field>

import {FocusMonitor} from '@angular/cdk/a11y';
import {coerceBooleanProperty} from '@angular/cdk/coercion';
import {Component, ElementRef, Input, OnDestroy} from '@angular/core';
import {FormBuilder, FormGroup} from '@angular/forms';
import {MatFormFieldControl} from '@angular/material';
import {Subject} from 'rxjs';

/** @title Form field with custom telephone number input control. */
@Component({
  selector: 'form-field-custom-control-example',
  templateUrl: 'form-field-custom-control-example.html',
  styleUrls: ['form-field-custom-control-example.css'],
})
export class FormFieldCustomControlExample {}

/** Data structure for holding telephone number. */
export class MyTel {
  constructor(public area: string, public exchange: string, public subscriber: string) {}
}

/** Custom `MatFormFieldControl` for telephone number input. */
@Component({
  selector: 'example-tel-input',
  templateUrl: 'example-tel-input-example.html',
  styleUrls: ['example-tel-input-example.css'],
  providers: [{provide: MatFormFieldControl, useExisting: MyTelInput}],
  host: {
    '[class.example-floating]': 'shouldLabelFloat',
    '[id]': 'id',
    '[attr.aria-describedby]': 'describedBy',
  }
})
export class MyTelInput implements MatFormFieldControl<MyTel>, OnDestroy {
  static nextId = 0;

  parts: FormGroup;
  stateChanges = new Subject<void>();
  focused = false;
  ngControl = null;
  errorState = false;
  controlType = 'example-tel-input';
  id = `example-tel-input-${MyTelInput.nextId++}`;
  describedBy = '';

  get empty() {
    const {value: {area, exchange, subscriber}} = this.parts;

    return !area && !exchange && !subscriber;
  }

  get shouldLabelFloat() { return this.focused || !this.empty; }

  @Input()
  get placeholder(): string { return this._placeholder; }
  set placeholder(value: string) {
    this._placeholder = value;
    this.stateChanges.next();
  }
  private _placeholder: string;

  @Input()
  get required(): boolean { return this._required; }
  set required(value: boolean) {
    this._required = coerceBooleanProperty(value);
    this.stateChanges.next();
  }
  private _required = false;

  @Input()
  get disabled(): boolean { return this._disabled; }
  set disabled(value: boolean) {
    this._disabled = coerceBooleanProperty(value);
    this.stateChanges.next();
  }
  private _disabled = false;

  @Input()
  get value(): MyTel | null {
    const {value: {area, exchange, subscriber}} = this.parts;
    if (area.length === 3 && exchange.length === 3 && subscriber.length === 4) {
      return new MyTel(area, exchange, subscriber);
    }
    return null;
  }
  set value(tel: MyTel | null) {
    const {area, exchange, subscriber} = tel || new MyTel('', '', '');
    this.parts.setValue({area, exchange, subscriber});
    this.stateChanges.next();
  }

  constructor(fb: FormBuilder, private fm: FocusMonitor, private elRef: ElementRef<HTMLElement>) {
    this.parts = fb.group({
      area: '',
      exchange: '',
      subscriber: '',
    });

    fm.monitor(elRef, true).subscribe(origin => {
      this.focused = !!origin;
      this.stateChanges.next();
    });
  }

  ngOnDestroy() {
    this.stateChanges.complete();
    this.fm.stopMonitoring(this.elRef);
  }

  setDescribedByIds(ids: string[]) {
    this.describedBy = ids.join(' ');
  }

  onContainerClick(event: MouseEvent) {
    if ((event.target as Element).tagName.toLowerCase() != 'input') {
      this.elRef.nativeElement.querySelector('input')!.focus();
    }
  }

  }

example-tel-input-example.html

      <input class="example-tel-input-element" formControlName="area" size="3">
      –
      <input class="example-tel-input-element" formControlName="exchange" size="3">
      –
      <input class="example-tel-input-element" formControlName="subscriber" size="4">

But I get the following error:

ERROR Error: mat-form-field must contain a MatFormFieldControl.

A: Need to import two module and add those in imports and exports section.

import { MatFormFieldModule } from '@angular/material/form-field';
import { MatInputModule } from '@angular/material/input';

@NgModule ({
  imports: [ MatFormFieldModule, MatInputModule ],
  exports: [ MatFormFieldModule, MatInputModule ]
})

And the most thing which everybody miss this '/' character. if you see the  Angular Material Documentation , they also miss this (Last Checked 16 Jun 2020, don't know they even updated or not). I make an example for clarifications

<mat-form-field>
  <input matInput>
</mat-form-field>

<mat-form-field>
  <input matInput />
</mat-form-field>

Look at the snippet carefully. when <input begin it must close with /> but most people miss the / (backslash) character.

A: You need to specify your class as a provider for MatFormFieldControl
https://material.angular.io/guide/creating-a-custom-form-field-control#providing-our-component-as-a-matformfieldcontrol
@Component({
  selector: 'form-field-custom-control-example',
  templateUrl: 'form-field-custom-control-example.html',
  styleUrls: ['form-field-custom-control-example.css'],
  providers: [
    { provide: MatFormFieldControl, useExisting: FormFieldCustomControlExample }
  ]
})

A: Also, don't forget to write the name attribute in the input tag:
name="yourName"

A: *

*if you are using any 'input' tag in your code along with 'mat-form-field', make sure to include 'matInput' in the input tag

*if there is any *ngIf present in child tag of 'mat-form-field', specify the *ngIf condition in 'mat-form-field' tag

A: Another possible issue closing the input tag. If you copy code from one of the Angular examples (https://material.angular.io/components/datepicker/overview), you may end up with the code:
<mat-form-field appearance="fill">
  <mat-label>Choose a date</mat-label>
  <input matInput [matDatepicker]="picker">
  <mat-datepicker-toggle matSuffix [for]="picker"></mat-datepicker-toggle>
  <mat-datepicker #picker></mat-datepicker>
</mat-form-field>

The input should have the close tag (slash):
<input matInput [matDatepicker]="picker" />

A: Make sure MatInputModule is imported and <mat-form-field> contains <input> with matInput / matSelect directives.
https://github.com/angular/material2/issues/7898

A: Import MatInputModule, solved my error

A: This will fix your issue
 import {
      MatFormFieldModule,
      MatInputModule
    } from "@angular/material";

A: Error says that mat-form-field should contain at least one form field from which input is taken.
Ex : matInput mat-select etc.
In your case you may add matInput tag to your input fields within example-tel-input-example.html. And also you could move mat-form-field inside example-tel-input-example component and add it against each matInput field.

      <mat-form-field>
         <input matInput class="example-tel-input-element" formControlName="area" size="3">
      </mat-form-field>
      –
      <mat-form-field>
          <input matInput class="example-tel-input-element" formControlName="exchange" size="3">
      </mat-form-field>
      –
      <mat-form-field>
          <input matInput class="example-tel-input-element" formControlName="subscriber" size="4">
      </mat-form-field>

Note : mat-icon or mat-hint cannot be considered as form-fields


text:
Q: Auto play audio files in Swift I'm making a very simple app in which the user get to select some audio files he wants to play.
Then, he pushes the Play button and, it would play all the files selected one after another.
To do so, I made an array that stores the name of the files the users wants to play. Then, a function triggered by the Play button would make a iteration of the array, look for the names and play the files.
It's something like this :
//declaring the audioplayer
var audioPlayer = AVAudioPlayer()

//declaring the array
var selectedMusic = [String]()

The interface got 6 buttons, one of each is linked to a specific music. The user can trigger the music instantly by tapping the button, or make a selection for a sequential play by a long press. Let's assume that the user got a selection and the array would look something like this :
selectedMusic = ["Song 1", "Song 5", "Song 3", "Song 2"]

My function to play the songs is :
for selection in selectedMusic {

        if selection == "Song 1" {

            guard let alertSound = Bundle.main.url(forResource: "Song 1", withExtension: "mp3") else {return}

            do {
                try AVAudioSession.sharedInstance().setCategory(AVAudioSessionCategoryPlayback)
                try AVAudioSession.sharedInstance().setActive(true)

                audioPlayer = try AVAudioPlayer(contentsOf: alertSound)
                audioPlayer.prepareToPlay()
                audioPlayer.play()

            } catch let error {
                print(error.localizedDescription)
            }

        } else if selection == "Song 2" {

            guard let alertSound = Bundle.main.url(forResource: "Song 2", withExtension: "mp3") else {return}

            do {
                try AVAudioSession.sharedInstance().setCategory(AVAudioSessionCategoryPlayback)
                try AVAudioSession.sharedInstance().setActive(true)

                audioPlayer = try AVAudioPlayer(contentsOf: alertSound)
                audioPlayer.prepareToPlay()
                audioPlayer.play()

            } catch let error {
                print(error.localizedDescription)
            }

Etc, until Song 5.
What I want is to play the selected songs in a specific order (1 to 5) and not the order the user chose (it's important).
Yet, this function is not giving the expected results, it's just playing the last item of the selection.
So, how should I make this work ? Is the array not the best option here ?
As i mentioned, the fact that the songs are played in chronological order is mandatory.
Any help would be greatly appreciated :)
Thanks !

A: Well first, you're using a for and repeating the code inside it.. in theory you could just do
audioUrls.forEach { (url) in
        guard let alertSound = Bundle.main.url(forResource: url, withExtension: "mp3") else {return}

        do {
            try AVAudioSession.sharedInstance().setCategory(AVAudioSessionCategoryPlayback)
            try AVAudioSession.sharedInstance().setActive(true)

            audioPlayer = try AVAudioPlayer(contentsOf: alertSound)
            audioPlayer.prepareToPlay()
            audioPlayer.play()

        } catch let error {
            print(error.localizedDescription)
        }
    }

second, you're not tracking the audio so your program does not know that the track finished playing and you're overwriting the player with a new object.
For instance, in the following code, I am keeping track of my audio player and updating a label with the current time.
func keepTrackOfAudio() {
    audioPlayer?.addObserver(self, forKeyPath: "currentItem.loadedTimeRanges", options: .new, context: nil)

    //track progress

    let interval = CMTime(value: 1, timescale: 2)
    audioPlayer?.addPeriodicTimeObserver(forInterval: interval, queue: DispatchQueue.main , using: { (progressTime) in
        let seconds = CMTimeGetSeconds(progressTime)
        let secondsString = String(format: "%02d", Int(seconds.truncatingRemainder(dividingBy: 60)))
        let minutesString = String(format: "%02d", Int(seconds / 60))

        self.audioCurrentTimeLabel.text = "\(minutesString):\(secondsString)"

        //lets move the slider thumb
        if let duration = self.audioPlayer?.currentItem?.duration {
            let durationSeconds = CMTimeGetSeconds(duration)

            self.audioSlider.value = Float(seconds / durationSeconds)

        }
    })

}

override func observeValue(forKeyPath keyPath: String?, of object: Any?, change: [NSKeyValueChangeKey : Any]?, context: UnsafeMutableRawPointer?) {

        if let duration = audioPlayer?.currentItem?.duration {
            let seconds = CMTimeGetSeconds(duration)

            let secondsText = String(format: "%02d", Int(seconds) % 60)
            let minutesText = String(format: "%02d", Int(seconds) / 60)
            audioLengthLabel.text = "\(minutesText):\(secondsText)"
        }

    }
}

your homework is to calculate when the audio has reached the end and only then, play the next track.


text:
Q: New to SQLite - how to store data which is a list of object with sub objects and array? I am trying to store data with the following format, and am not sure of the best way to organize in SQLite:
-Main item
-- Field 1
-- Field 2
-- Field 3 (main image)
---- image path
---- date image was taken
-- Field 4
-- Field 5 (array of images)
---- each image is a path and date pair as above
I was thinking 2 tables? 1 for the main item, with the main image path and date as just two specific columns; then the second table would be the list of images with an id tied to the main item?
Is there a better way to do this? Seems like it would be hassle to manage and update both tables, but if that's the best way then that's how it is

A: As noted in the comments, you should read up on relational database basics. The vocabulary for databases is different from programming. SQLite is a basic database engine and only supports basic data types, so after learning relational database concepts, you should read up on sqlite specifically.
Here's an informal summary for your problem:

*

*Your data model requires two tables as you noted.

*What you call 'Fields' are 'columns' in the tables. Columns have a type such as INTEGER or TEXT (https://www.sqlite.org/datatype3.html).

*Arrays are expressed with FOREIGN KEYs (https://sqlite.org/foreignkeys.html). A foreign key is a property that references a record in another column by matching a unique value in a specific column of the other table. You build an array of values by selecting records from the table with the foreign key that match the object you care about.

*Note that SQL code in an app generally isn't required. Try looking for a framework or Object Relational Mapper (ORM) that takes care of mapping database tables to objects, columns to properties and handles the persistence and schema updates for you. I can say from experience, manual SQL code is difficult to maintain and seriously complicates testing.

Your specific problem could be solved with this schema:
CREATE TABLE mainitem(
  id        INTEGER PRIMARY KEY,
  field1    TEXT,
  field2    INTEGER
);

CREATE TABLE image(
  id          INTEGER PRIMARY KEY,
  datetaken   TEXT,
  path        TEXT,
  mainitem    INTEGER,
  FOREIGN KEY(mainitem) REFERENCES mainitem(id)
);

ALTER TABLE mainitem
ADD COLUMN mainimage INTEGER REFERENCES mainitem(id) DEFAULT NULL;

To get your array of images, where the id of your mainitem == 3:
SELECT * FROM image WHERE mainitem = 3;

To get your main item with its main image:
SELECT *
FROM mainitem
LEFT OUTER JOIN image
ON mainitem.mainimage = image.id
WHERE mainitem.id = 3;


text:
Q: C program that prints whats inside quotation marks.". In a textfile Hey all I am trying to transfer some data through textfiles in c. I seemed to have been able to transfer most of the data over except for the items in " " quotation marks. An example below of what i'm trying to do is:
Example textfile:

This is a test 123.
There "are (123) tests" &here. // print "are (123) tests" as a string.
There are a lot of lines.

I'm simply trying to print "are (123) tests" as it's own string literal, or on it's own line. Separate from the other alpha/nonalpha chars. I've tried multiple ways of reading my file in using getc, read, gets, buffers, etc. Any ideas would be appreciated thank you.
Edit: I figured out a workable, but messier solution to this using fgetc, thanks to the help of other developers on here. I'm welcome to more ideas.  Functions are below.

    int main()
    {
        int ch;
        FILE * fp;
        fp = fopen("test.txt", "r");

    }

    while ((ch = fgetc(fp)) != EOF)
    {
        check_comment(ch);

    }

    fclose(fp);
    .
    .
    .

    void check_comment(char c)
    {
        int d;

        if (c == '"')   // if the character starts with '"', it 'could' be a string
        {
            printf("\n%c", c);  //print '"', it will remove otherwise.

            ret_string();   // try to find the end of " string, and return it.
            //fputc(c,fp);  // optional
        }
    }

    void ret_string()
    {
        int d, e;
        char buffer[256];   //optional to load into a buffer
        int j = 0;

        while ((d = fgetc(fp)) != EOF)  //find " in the file again
        {
            if (d == '"')
            {
                e = fgetc(fp);  // find the ending "

                if (!isalpha(e))    // confirm it's the end by looking for a nonalpha after the "
                    printf("%c", d);    //print the ending '"'
                printf("\n%c", e);  // not needed but will next non alpha char after end '"'
                return;
            }

            // fputc(d, fp);    //optional
            printf("%c", d);    //print the entire ".." line
        }
    }

A: In order to print all characters that are in quotation marks in an input file, you could use the following code:
#include <stdio.h>
#include <assert.h>

int main( void )
{
    FILE *fp = fopen( "inputfile.txt" , "r" );
    assert( fp != NULL );

    int c;

    for (;;) //infinite loop
    {
        //loop for handling characters that **are not** in quotation marks
        while ( ( c = getc( fp ) ) != '\"' )
        {
            if ( c == EOF ) goto finished;
        }

        //loop for handling characters that **are** in quotation marks
        while ( ( c = getc( fp ) ) != '\"' )
        {
            if ( c == EOF ) goto finished;
            putchar( c );
        }
    }

finished:
    fclose( fp );
}

If you don't like these nested loops and the goto statement to escape them, an alternative would be the following code, which only uses one loop:
#include <stdio.h>
#include <stdbool.h>
#include <assert.h>

int main( void )
{
    FILE *fp = fopen( "inputfile.txt" , "r" );
    assert( fp != NULL );

    bool is_inside_quotation_marks = false;
    int c;

    while ( ( c = getc( fp ) ) != EOF )
    {
        if ( c == '\"' )
        {
            is_inside_quotation_marks = !is_inside_quotation_marks;
            continue;
        }

        if ( is_inside_quotation_marks )
        {
            putchar( c );
        }
    }

    fclose( fp );
}


text:
Q: Program exiting unexpectedly w/o exception when running main method from jar I'm trying to run a project in Eclipse Indigo where my main class (containing the main method) is in an external .jar file I created from another project. The program is run based upon passing the name of a class in the current project to the main method as a command line argument.
When I try to run this project, the first few lines of the main method (in the .jar) are executed, but then the program exits. The debugger has informed me that it exits with an error code of 1. No exceptions are thrown (or at least, none appear in the console or in my try-catch blocks) and I make no assertion statements of calls to System.exit.
When run directly, the main method complete's normally. This unexpected exit occurs only when the project is exported to a .jar.
I find this exceptionally confusing, especially considering that debugging has confirmed that the main method is called, and simply quits near the end without completing. Here is my main method:
public static void main(String[] args) throws ClassNotFoundException, InstantiationException, IllegalAccessException, IllegalArgumentException, SecurityException
{
    Class<?> c = Class.forName(args[0]);

    OpenGL.Renderer r = null;

    Class<? extends OpenGL.Renderer> c2 = c.asSubclass(OpenGL.Renderer.class);

    r = c2.newInstance();

    OpenGL.init(r);
}

The debugger reaches the breakpoint at line 16 (r = c2.newInstance()) before terminating.
EDIT: The problem appears to lie with the reflection code that initializes the variable r. No matter where I put my breakpoints I can't step to a situation in which r is not null.
EDIT #2: After using the debugger some more, I can step into the constructor being called in the c2.newInstance() call, but the program exits immediately after method entry, before any of the constructor is executed. The constructor doesn't contain anything other than a syso call for debugging.
Any help in getting this program to run correctly would be appreciated.

A: Okay, it's kind of embarrassing, but I finally found the problem, very far away from where my debugger had led to me to believe.
In short, I had a try block that loaded some data from a file and made call to System.exit(1) in the catch block if an exception was thrown. Since the file was located inside the .jar, the path to it was different from what it had been when it located in the src folder in my original project. This caused a FileNotFoundException to be thrown, exiting the program.
For some reason, my debugger reported that the program failed long before it reached this code. For this I continue to have no explanation. If anyone else has this problem, I recommend removing ALL occurrences of System.exit from your code, regardless of where they are, and then continuing to debug.


text:
Q: How do you do this style of dice problem: If your roll three dice what's the probability that the sum is x? So effectively what I'm asking is how you do problems like with a number of dice y, what is the probability that the sub is x? Is there any way to do this besides memorizing the parabolas of amount of possibilities for each answer for each  dice.

A: Generalized Pascal's Triangle
One of the simpler ways is to use a generalized version of Pascal's Triangle.
In Pascal's triangle, we add the two entries just above the current one we want to calculate.  In the generalized version, we add more entries.
In the case of six-sided dice, we add the six entry above each new one and get the following structure.
$$ 1 \\
1~~1~~1~~1~~1~~1 \\
1 ~~ 2 ~~ 3 ~~ 4 ~~ 5 ~~ 6 ~~ 5 ~~ 4 ~~ 3 ~~ 2 ~~ 1 \\
1 ~~ 3 ~~ 6 ~~ 10 ~~ 15 ~~ 21 ~~ 25 ~~ 27 ~~ 27 ~~ 25 ~~ 21 ~~ 15 ~~ 10 ~~ 6 ~~ 3~~ 1
$$
From this we can build a table.
$$
\begin{matrix}
\text{roll total} & 3 & 4 & 5 & 6 & 7 & 8 & 9 & 10 & 11 & 12 & 13 & 14 & 15 & 16 & 17 & 18 \\
\text{ways it can happen} &1 & 3 & 6 & 10 & 15 & 21 & 25 & 27 & 27 & 25 & 21 & 15 & 10 & 6 & 3 & 1
\end{matrix}
$$
So, for instance, if we want to find the probability of rolling a 7, we see that there are 15 ways this can happen.  Since there are $6^3=216$ total possibilities, we have
$$P(7)=\frac{15}{216}=\frac{5}{72}$$
I usually use Excel to run the actual calculations if I go beyond 3 levels (it gets pretty tedious otherwise).

A: Suppose you are exploring $x=10$.  Start by imagining ghe dice to be distinct, call them red, green and blue.  To get that you need one of the following:
Red + green total is 4, blue gives 6 --> 3 permutations
Red + green total is 5, blue gives 5 --> 4 permutations
Red + green total is 6, blue gives 6 --> 5 permutations
Red + green total is 7, blue gives 5 --> 6 permutations
Red + green total is 8, blue gives 2 --> 5 permutations
Red + green total is 9, blue gives 1 --> 4 permutations
Add that up to get a total of $27$ out of $216$ so the probability for $x=10$ is one-eighth.
You should be able to figure out other values of $x$ similarly.
As an aside:  $10$ divided by $7$ gives a remainder of $3$.  If you add up the permutations for all sums giving this remainder ($3, 10, 17$) you get $31$ permutations.  You also get $31$ for each other remainder except $0$; that gives $30$ permutations.  Thus summing three standard dice modulo $7$ closely approximates a fair seven-sided die.

A: Encode using probability generating functions (pgfs). Let $X$ be the sum after performing the experiment. Then $X=\sum_{i=1}^3 X_i$ where $X_i$ are indepedent uniform $\{1,\dotsc, 6\}$ random variables. Let $g_X$ be the pgf of $X$. Since the $X_i$ are independent, it follows that
$$
\sum_{i}P(X=i)t^i=g_X(t)=Et^{X}=\prod_i Et^{X_i}=\frac{1}{6^3}(t+t^2+\dotsb+t^6)^3=\frac{t^3}{6^3}\frac{(1-t^6)^3}{(1-t)^3}.
$$
Using the extended binomial theorem we can rewrite the previous line as
$$
\sum_{i}P(X=i)t^i=\frac{t^3(1-t^6)^3}{6^3}\left(\sum_{m=0}^\infty\binom{m+2}{2}t^m\right)
$$
Thus to find the probability $P(X=i)$ it sufficies to compute the coefficient of $t^i$ on the RHS.


text:
Q: UISearchBar app crashes when pressing a letter Hey guys. I have a problem, when i press a letter in the search bar the app crashes. I have no errors only this threat when i press a letter terminating with uncaught exception of type NSException
Here in the sample code please help.
#import "BIDFirstLevelViewController.h"
#import "BIDSecondLevelViewController.h"
#import "MangaliaViewController.h"
#import "Country.h"
#import "LimanuViewController.h"

@interface BIDFirstLevelViewController ()<UISearchDisplayDelegate>

@property (strong, nonatomic) NSArray *controllers;
@property (nonatomic, strong) NSMutableArray *searchResults;

@end

@implementation BIDFirstLevelViewController

- (id)initWithStyle:(UITableViewStyle)style
{
    self = [super initWithStyle:style];
    if (self) {
        // Custom initialization

        self.title = @"Plecare";

    }
    return self;
}

- (void)viewDidLoad
{
    [super viewDidLoad];

    self.controllers = [@[
                         [[MangaliaViewController alloc] init],
                         [[LimanuViewController alloc] init],

                         ]mutableCopy];

    self.searchResults = [NSMutableArray arrayWithCapacity:[self.controllers count]];
}

#pragma mark - Table view data source

- (NSInteger)numberOfSectionsInTableView:(UITableView *)tableView
{
    // Return the number of sections.
    return 1;
}

- (NSInteger)tableView:(UITableView *)tableView numberOfRowsInSection:(NSInteger)section
{
    // Return the number of rows in the section.
    if (tableView == self.searchDisplayController.searchResultsTableView)
    {
        return [self.searchResults count];
    } else {
        return [self.controllers count];
    }
}

- (UITableViewCell *)tableView:(UITableView *)tableView cellForRowAtIndexPath:(NSIndexPath *)indexPath
{
    static NSString *CellIdentifier = @"Cell";

    UITableViewCell *cell = [tableView dequeueReusableCellWithIdentifier:CellIdentifier];

    BIDSecondLevelViewController *controller = self.controllers[indexPath.row];

    if (cell == nil) {
        cell = [[UITableViewCell alloc] initWithStyle:UITableViewCellStyleDefault reuseIdentifier:CellIdentifier];
    }

    if (tableView == self.searchDisplayController.searchResultsTableView) {
        cell.textLabel.text = [self.searchResults objectAtIndex:indexPath.row];
    } else {
        cell.textLabel.text = controller.title;
    }

    UIImage *image = [UIImage imageNamed:@"bus.gif"];
    cell.imageView.image = image;

    return cell;
}

#pragma mark UISearchDisplay delegate

- (void)filterContentForSearchText:(NSString*)searchText scope:(NSString*)scope
{
    [self.searchResults removeAllObjects];

    NSPredicate *resultPredicate = [NSPredicate
                                    predicateWithFormat:@"SELF contains[cd] %@",
                                    searchText];

    self.searchResults = [NSMutableArray arrayWithArray:[self.controllers filteredArrayUsingPredicate:resultPredicate]];//[self.tableData filteredArrayUsingPredicate:resultPredicate];
}

-(BOOL)searchDisplayController:(UISearchDisplayController *)controller
shouldReloadTableForSearchString:(NSString *)searchString
{
    [self filterContentForSearchText:searchString
                               scope:[[self.searchDisplayController.searchBar scopeButtonTitles]
                                      objectAtIndex:[self.searchDisplayController.searchBar
                                                     selectedScopeButtonIndex]]];

    return YES;
}

#pragma mark - Table view delegate

- (void)tableView:(UITableView *)tableView didSelectRowAtIndexPath:(NSIndexPath *)indexPath
{
    BIDSecondLevelViewController *controller = self.controllers[indexPath.row];
    [self.navigationController pushViewController:controller animated:YES];
}

@end

A: you needs to change your code of method searchDisplayController and replce following code for serching data and remove filterContentForSearchText method
- (BOOL)searchDisplayController:(UISearchDisplayController *)controller shouldReloadTableForSearchString:(NSString *)searchString
{
    NSPredicate *resultPredicate = [NSPredicate predicateWithFormat:
                                    @"SELF contains[cd] %@", searchString];

    [self.searchResults removeAllObjects];
    self.searchResults = [[NSMutableArray alloc] initWithArray:[self.controllers filteredArrayUsingPredicate:resultPredicate]];

    return YES;
}


text:
Q: Navigation Drawer below Tool bar in Material Design I want my drawer to open from the left below the tool bar. But, according to Material Design aspects that's not good. But still I want to do that.
Here I have changed my XML file.
---Relative Layout
-----Tool bar
-----Drawer
-------container
-------drawer List
here is my XML file. My app crashes when it opens. I don't know where I made a mistake and XML doesn't show any errors.
<RelativeLayout xmlns:android="http://schemas.android.com/apk/res/android"
android:layout_width="match_parent"
android:layout_height="match_parent">

<include
    android:id="@+id/toolbar"
    layout="@layout/toolbar" />

<android.support.v4.widget.DrawerLayout
    xmlns:app="http://schemas.android.com/apk/res-auto"
    xmlns:tools="http://schemas.android.com/tools"
    android:id="@+id/drawer_layout"
    android:layout_width="match_parent"
    android:layout_height="match_parent">

    <FrameLayout
        android:id="@+id/container_body"
        android:layout_width="fill_parent"
        android:layout_height="0dp"
        android:layout_weight="1" />

    <fragment
        android:id="@+id/fragment_navigation_drawer"
        android:name="com.myApp.activity.FragmentDrawer"
        android:layout_width="@dimen/nav_drawer_width"
        android:layout_height="match_parent"
        android:layout_gravity="start"
        app:layout="@layout/fragment_navigation_drawer"
        tools:layout="@layout/fragment_navigation_drawer" />

</android.support.v4.widget.DrawerLayout>

</RelativeLayout>

A: I have created New XML file main_activity_appbar and added tool bar first and in same layout file I added my Drawer Layout. and in mainAcitity.java file I changed layout of that file.
main_activity_appbar.xml
<?xml version="1.0" encoding="utf-8"?>
<LinearLayout xmlns:android="http://schemas.android.com/apk/res/android"
android:orientation="vertical"
android:layout_width="match_parent"
android:layout_height="match_parent">

<include
    android:id="@+id/toolbar"
    layout="@layout/toolbar" />

<android.support.v4.widget.DrawerLayout
    xmlns:app="http://schemas.android.com/apk/res-auto"
    xmlns:tools="http://schemas.android.com/tools"
    android:id="@+id/drawer_layout"
    android:layout_width="match_parent"
    android:layout_height="match_parent">

    <LinearLayout
        android:layout_width="match_parent"
        android:layout_height="match_parent"
        android:orientation="vertical">

        <FrameLayout
            android:id="@+id/container_body"
            android:layout_width="fill_parent"
            android:layout_height="0dp"
            android:layout_weight="1" />

    </LinearLayout>

    <fragment
        android:id="@+id/fragment_navigation_drawer"
        android:name="com.myApp.activity.FragmentDrawer"
        android:layout_width="@dimen/nav_drawer_width"
        android:layout_height="match_parent"
        android:layout_gravity="start"
        app:layout="@layout/fragment_navigation_drawer"
        tools:layout="@layout/fragment_navigation_drawer" />

</android.support.v4.widget.DrawerLayout>

</LinearLayout>

MainActivity.java
protected void onCreate(Bundle savedInstanceState) {
    super.onCreate(savedInstanceState);
    setContentView(R.layout.activity_main_appbar);

This is working fine.

A: Here is the latest solution for material design

<android.support.design.widget.AppBarLayout
    android:layout_width="match_parent"
    android:layout_height="wrap_content"
    tools:openDrawer="start">

    <android.support.v7.widget.Toolbar
        android:id="@+id/toolbar"
        android:layout_width="match_parent"

android:layout_height="@dimen/abc_action_bar_default_height_material"
        android:background="?attr/colorPrimary"
        android:theme="@style/ThemeOverlay.AppCompat.Dark.ActionBar"/>

</android.support.design.widget.AppBarLayout>

<android.support.v4.widget.DrawerLayout
    android:id="@+id/drawer_layout"
    android:layout_width="match_parent"
    android:layout_height="match_parent">

   <!--content_main is my layout you can design your own-->
    <include layout="@layout/content_main" />

    <FrameLayout
        android:id="@+id/content"
        layout="@layout/content_main"
        android:layout_width="match_parent"
        android:layout_height="match_parent" />

    <!-- The navigation drawer -->
    <android.support.design.widget.NavigationView
        android:id="@+id/nav_view"
        android:layout_width="wrap_content"
        android:layout_height="match_parent"
        android:layout_gravity="start"
        app:menu="@menu/activity_main_drawer" />

</android.support.v4.widget.DrawerLayout>

</LinearLayout>

Hope it helps


text:
Q: How to change the color of objects on hover in Javascript? I'm fairly new to Javascript/Canvas and I wanted to create an animation that creates circles whenever I click within the canvas, then it changes colors when I hover over them and reverts back to the original color when the mouse is not hovering over them. I was able to create the animation of drawing circles on click, but can't get the hover color to work. I'm trying to get this done completely with Javascript, using HTML only for creating the canvas. Any advice is appreciate!

    let dots = [];

    /** @type {HTMLCanvasElement} */
    let canvas = ( /** @type {HTMLCanvasElement} */ document.getElementById("canvas"));
    let context = canvas.getContext('2d');

    //some state
    let mouseX = -10;
    let mouseY = -10;

    //remember mouse click position
    canvas.onclick = function (event) {
        mouseX = event.clientX;
        mouseY = event.clientY;

        let box = (event.target).getBoundingClientRect();
        mouseX -= box.left;
        mouseY -= box.top;
    };

    canvas.onmouseleave = function () {
        mouseX = -10;
        mouseY = -10;
    };

    var drawCirc = function (hover) {
        //clear the canvas
        context.clearRect(0, 0, canvas.width, canvas.height);

        //determine mouse location when outside
        //if inwide canvas, make a dot
        if ((mouseX > 0) && (mouseY > 0)) {
            dots.push({
                "x": mouseX,
                "y": mouseY
            });
        }

        //draw circles/dots
        dots.forEach(function (d) {
            context.fillStyle = "#808080";
            context.beginPath();
            context.arc(d.x - 3, d.y - 3, 10, 0, 2 * Math.PI);
            context.fill();
        });
        window.requestAnimationFrame(drawCirc);
    }
    drawCirc();
canvas{
  border:1px solid black
}
<canvas id="canvas" width="200" height="200"></canvas>

A: Javascript:
object.addEventListener("mouseover", myScript);

example:
var e = document.getElementById('elementID')

e.onmouseover = function(){e.style.backgroundColor = "blue"}

A: you can use mousehover method
for jquery here's the sample
$("p").mouseover(function(){
$("p").css("background-color", "yellow");
 });

for javascript
<script>
   document.getElementById("demo").addEventListener("mouseover", mouseOver);
   document.getElementById("demo").addEventListener("mouseout", mouseOut);

   function mouseOver() {
   document.getElementById("demo").style.color = "red";
   }

   function mouseOut() {
    document.getElementById("demo").style.color = "black";
    }
</script>


text:
Q: how jsf get server url all
My web project run in tomcat.Its path ishttp://localhost:8080/test/index.html.
How to get the url = "http:/localhost:8080/test/" throught ExternalContext?
thanks advanced.

A: You can access to the context path using ExternalContext#getRequestContextPath. From its javadoc:

Return the portion of the request URI that identifies the web application context for this request.
Servlet: This must be the value returned by the javax.servlet.http.HttpServletRequest method getContextPath().

Usage in code:
FacesContext.getCurrentInstance().getExternalContext().getRequestContextPath()


text:
Q: My plugin code slows down Eclipse, what could I improve? I have a ITextViewer object and from that the StyledText widget in which Eclipse displays code. I want to hihglight one single line that is defined by the line number. Therefore I added a LineBackgroundListener to the StyledText object an wrote the following code:
private class HighlightLine implements LineBackgroundListener {

        @Override
        public void lineGetBackground(LineBackgroundEvent event) {
            if (lineToHighlight != -1) {
                int line = ((StyledText) event.widget).getLineAtOffset(event.lineOffset);
                if (line == lineToHighlight) {
                    event.lineBackground = styledText.getSelectionBackground();
                } else if (line == previousLineToHighlight) {
                    event.lineBackground = styledText.getBackground();
                }
                styledText.redraw();
                styledText.update();
            }
        }

    }

This work more or less fine, but the problem is, it very much slows down Eclipse. It's probably the case because it has to update the Widget very often and that's not optimal. However, I couldn't think of another way to to it after a lot of trials. Any idea?

A: You don't need these (expensive) calls:
styledText.redraw();
styledText.update();

lineGetBackground is called during the draw line operation so it does not need a redraw or update.
Note: If the StyledText control has any StyleRange ranges they may override the background.


text:
Q: RethinkDb: Has many query Have two table, Quiz and Questions
Quiz table store questions id and its display position.
Display position is different for every Quiz.
Quiz table:
{
 id: '1'
 name: 'Quiz 1'
 questions: [
  {
   question_id: '1',
   position: 4
  },
  {
   question_id: '2',
   position: 1
  },
  ......
 ]
}
...

Question Table:
[
 {
  id: '1',
  title: 'Question 1'
 },
 {
  id: '2'
  title: 'Question 2'
 }
]

I want the the return result like this
{
 id: '1',
 name: 'Quiz 1',
 questions: [
   {
    position: 4,
    title: 'Question 1'
   },
   {
    position: 1,
    title: 'Question 2'
   }
 ]
}

How can i get the desired result?
thanks

A: I got the desired result by using following query
r.db('database').table("quizes").get(id)
  .do((quiz) => {
    return quiz.merge({'questions': quiz('questions').map((q) => {
     return q.merge((r.db('database').table('questions').get(q('id')).without('id')))
    })
   })
 })


text:
Q: Updating a record using Entity Framework context without manually setting properties I am trying to update a record using Entity Framework but want to avoid manually setting each property and then calling save changes. I have an instance of this class bound to a dataform that updates all its properties as a user changes them. The nicest way I can see using this would be to set the object in the context equal to the object bound to my dataform but this does not work. I tried removing the object from the context then adding the dataform bound object but it creates a completely new record (I expected this but decided it was worth a shot to try it out). I assume there is some type of flag with in the context that is used to detect if a record is a new row or not considering the fact that replacing the context object with the databound object (which has the same pk value) does not work.
using (var scope = new TransactionScope())
        {
            try
            {
                using (var context = new CIS_DEVEntities())
                {
                    GangMemberBio bio = context.GangMemberBios.First(P => P.id == this.id);
                    bio = this; //this does not work.
                    context.SaveChanges();
                }
                //If the top code is successfully completed then the transaction will be commited
                //if not this line will be skipped and execution will be given to the catch block
                scope.Complete();
            }
            catch
            {

            }
        }

Edit Idea 1
I was thinking I could create a context object on my wpf window itself and then bind the dataform to my gangmemberbio object retrieved from this context. Then when I call save changes nothing else needs to be done. I heard that having a datacontext in memory is bad though.. Or is it just bad if I use it outside the context of a using statement?

A: In your edit page, load the object from the database first which will cause your form's fields to all be populated with existing data from the database. When the form is posted then, all the values of your data object model will be set.

A: DbContext keeps track of each entity's state internally, so it knows whether to add/update/delete any given one. When you Add() an entity to the context, even though it might already have an id, it's default state is Added (might be New, not sure), which causes the existing id to be ignored and a new record inserted into the db.
What you want to do is attach the already existing entity to the DbContext, and then let the DbContext know that it's to be treated as an existing entity so that it's updated, rather than inserted.
You do that by setting the EntityState in the DbContext for the given entity to Modified (by default it's New when adding an entity to the DbContext).
Try something like this:
using (var context = new CIS_DEVEntities())
{
    context.Entry(this).State = EntityState.Modified;
    context.SaveChanges();
}


text:
Q: SFTP on Linux to linux fails on multiple concurrent connections but filezilla could connect multiple I have a test setup between two linux systems, one is local and another is remote server being used for production deployment. We tried to run simple command-line sftp client from 2-3 separate terminal windows. And, we got connection failures couple of times stating:
ssh_exchange_identification: read: connection reset by peer
Couldn't read packet, connection reset by peer

This shows there is some problem/shortcoming/restriction/configuration in remote machine's sftp settings in terms of what is allowed/disallowed, how it is allowed/disallowed etc and must be having some configuration issues. We are yet to figure that out.
However, when we connect the same remote server from windows through Filezilla software, we could be able to connect in multiple sessions (different tab) and could download multiple files from each of those tabs. In Filezilla, is the same physical connection shared among multiple logical connections? Please throw some light on this why this could happen.
Also, how can we check how many concurrent socket connections (for running sftp) are allowed to be open for concurrent download of files? Is there nay diagnostic through which we would be able to judge where lies the configuration that might not allow more than one SFTP connection.


text:
Q: How to highlight Google Sheets Tab based on Day of the week I am trying to get the specific tab corresponding to the Day of the week to highlight based on which day of the week it is. I have only Monday - Friday, and I am using the WEEKDAY attribute to get the day of the week in number format then converting to dddd Full weekday name format. Not I also want this to be checked when the sheet is opened for the day. Below is the code I have, however, I am not able to get any tab to highlight.
function onOpen(e) {
var ss = SpreadsheetApp.getActiveSpreadsheet();
var Master = ss.getSheetByName("Master");
var Monday = ss.getSheetByName("Monday");
var Tuesday = ss.getSheetByName("Tuesday");
var Wednesday = ss.getSheetByName("Wednesday");
var Thursday = ss.getSheetByName("Thursday");
var Friday = ss.getSheetByName("Friday");
var highlight = ss.getRange("E1");
 if (highlight == "Monday") {
Monday.setTabColor("ff0000");
 }
 if (highlight == "Tuesday") {
Tuesday.setTabColor("ff0000");
 }
 if (highlight == "Wednesday") {
Wednesday.setTabColor("ff0000");
 }
 if (highlight == "Thursday") {
Thursday.setTabColor("ff0000");
 }
 if (highlight == "Friday") {
Friday.setTabColor("ff0000");
 }
}

E1 is the current cell that the spelled-out weekday is in. Any help shedding some light on this would be appreciated.

A: It is almost working. You don't store the value, just the range of the cell. Modify:
function onOpen(e) {
var ss = SpreadsheetApp.getActiveSpreadsheet();
var Master = ss.getSheetByName("Master");
var Monday = ss.getSheetByName("Monday");
var Tuesday = ss.getSheetByName("Tuesday");
var Wednesday = ss.getSheetByName("Wednesday");
var Thursday = ss.getSheetByName("Thursday");
var Friday = ss.getSheetByName("Friday");
var highlight = ss.getRange("E1").getValue();
Logger.log(highlight);
 if (highlight == "Monday") {
Monday.setTabColor("ff0000");
 }
 if (highlight == "Tuesday") {
Tuesday.setTabColor("ff0000");
 }
 if (highlight == "Wednesday") {
Wednesday.setTabColor("ff0000");
 }
 if (highlight == "Thursday") {
Thursday.setTabColor("ff0000");
 }
 if (highlight == "Friday") {
Friday.setTabColor("ff0000");
 }
}

Use the Logger.log(highlight) to see what value you get in the protocol, to debug your code. You can delete or comment this line in production.


text:
Q: DataGridView insert in DB on new row I have the following code to populate a DataGridView:
private void LoadCashOut_raRecSheetChecks(int recID)
  {
   SqlDataAdapter SqlAdapter = new SqlDataAdapter();

   SqlCommand SqlCommand_Select = new SqlCommand("raRecSheetChecks_Get", SqlConn);
   SqlCommand_Select.CommandType = CommandType.StoredProcedure;
   SqlCommand_Select.Parameters.Add(new SqlParameter("@recID", recID));

   SqlAdapter.SelectCommand = SqlCommand_Select;

   DataSet DS_recSheetChecks = new DataSet();

   SqlAdapter.Fill(DS_recSheetChecks);

   // DataGridView GV_ChecksRolledCoins
   GV_ChecksRolledCoins.DataSource = DS_recSheetChecks.Tables[0];
  }

What I would like to do is insert into the same DB whenever a user completes a new row.
How do I tell the DataGridView to fire an event to insert when a new row has been created?
Side question: I need to do the same thing except update instead of insert for rows that have been modified.
I'd like to do this without a "Save" button. Simply, I want the data to be inserted or updated as soon as the user leaves the row.


text:
Q: How to set two different jre in two different eclipse in window 7 machine I am working in two different project and both the projects are running in two different java (jdk6 and jdk 8) version in eclispe kepler .
Therefore i need to set the java in both the projects , so have a compile class file in same java version.
I can use two different eclipse kepler for this.
Installed java is jdk 6.
Thanks is advance for help.

A: In Preferences, go to "Installed JREs", add both JREs there.
Then use different workspaces for each project.


text:
Q: combining two data sources in a database I have a question about best practices when combining two data sources which both have partial data and occasionally contradictory data.
I have two different data sources that I'm using to get variables related to specific houses (Zillow and Redfin).
There are discrepancies between the two data sources. For the same house, one of the data sources may be missing a particular variable, and so I collect that data from the other source. Sometimes both sources may have the variable, but the values differ for the same house, indicating that one of the sources must be wrong.
I'm not sure what best practices are for storing the data and ensuring that the final data set has the most coverage and is most likely to include the correct data.
Some of the ideas I am toying with are:
1) Store both in separate tables, and then combine in a third table which contains the statistics that I create from the underlying data. The problem with this approach is that I would need a substantially bigger database.
2) Insert one set of data, and then grab the same data from the other source, and overwrite in the same table wherever relevant. The problem with this approach is that if I want to go back and make changes to how I compute the statistics, I may not know which source I retrieved the data from.
Are there any best practices for combining different data sets?
I'm also not entirely sure how to make the choice between conflicting values of the same variable for the same house. Should I always stick with one of the sources?
Any help would be appreciated!


text:
Q: Why is the AngularFire chat example breaking? As an exercise I was adding email authentication to the base angularFire chat app as seen on http://angularfire.com/tutorial/.
In the process I noticed deleting the first entry through the forge an undefined entry showed up in the DOM where the 0 entry used to be.
When I deleted the second (id 1) entry nothing showed up due to the following error message:
Duplicates in a repeater are not allowed. Repeater: msg in messages key: undefined:undefined
I noticed the first undefined shows up in the tutorial my code was derived from, but not the second.. until I substitute the .firebaseio-demo.com url with the one to my firebase. This leads me to believe it isn't my implementation of the code.
What is behind the smoke and mirrors of .firebaseio-demo.com that I'm missing?
Is there a mystery validation rule or something?
At some point the Wire up a Backend example on angularjs.org had the same issue.. recently it seems to have been corrected.

A: I'm seeing the same thing, that feels like a bug to me (items deleted from an array in the forge shouldn't be showing up in an angularFire bound model array on the client). This effect also doesn't happen when using object collections instead of arrays, e.g. when using angularFireCollection or when setting the original messages type to an object: $scope.messages = {} instead of $scope.messages = [].
However, since those deleted items are showing up in the resulting array as undefined, having more than one undefined in your array results in an AngularJS repeater with identical values, which are not allowed. So the error you are seeing after deleting multiple messages is actually expected.
Regardless, for now it seems like the best ways to avoid it are using object collections instead of arrays as mentioned above or setting up some kind of Angular filter to weed out any undefined members of your repeater.


text:
Q: WordPress media library, change existing URLS to AWS s3 I am having trouble mass changing the locations in WordPress for the images.
I have ran this request in PHPMyAdmin
UPDATE wp_posts SET guid = replace(guid, 'http://www.oldsite.com','http://www.newsite.com');
UPDATE wp_posts SET post_content = replace(post_content, 'http://www.oldsite.com', 'http://www.newsite.com');
UPDATE wp_postmeta SET meta_value = replace(meta_value, 'http://www.oldsite.com', 'http://www.newsite.com');

Where newsite.com is the url for the S3 bucket.
However, when I go into the media library for wordpress none of the images are loading. When I click an image, the URL for that image is still oldsite.com/wp-content/uploads/...
Can someone please help me make wordpress media manager use my s3 url instead?
p.s I have just over 12 thousand images. Would ideally not want to do this manually.


text:
Q: Error while trying to re-direct application to new server port Im creating new server to listen to new port(with the second create below),now when I call to the application with some port I want to redirect it to the new created server port, and put the message in the browser "Request route to on 9009"
I use the following code to create server
httpProxy = require('http-proxy');

proxy = httpProxy.createProxyServer({});

    http.createServer(function (req, res) {
            var hostname = req.headers.host.split(":")[0];
             if  (hostname ==='localhost') {
              proxy.web(req, res, {target: 'http://localhost:9009'});
             }
}    }).listen(3000, function () {
        console.log('App listening on port 3000');
    });
now I create the new server

http.createServer(function (req, res) {
 res.writeHead(302, {
    'Location': 'http://localhost:9009'
 });

   res.end("Request route to  9009");
}).listen(9009);

now when I put  localhost:3000 it redirects me to localhost:9009 (which is exactly what I need I can see in the browser) but I got error This webpage has a redirect loop ERR_TOO_MANY_REDIRECTS
If I remove from the second createServer function the following
res.writeHead(302, {
    'Location': 'http://localhost:9009'
 });

it is not redirects and I dont got the error...
did I put the this code in the wrong place?or there is a way to do it diffrent?
I use https://github.com/nodejitsu/node-http-proxy
update
I change the code to following
var http = require('http');

http.createServer(function (req, res) {
    console.log("Server created");
    res.writeHead(200, { 'Content-Type': 'text/plain' });
    res.write('9009 here' + '\n' + JSON.stringify(req.headers, true, 2));
    res.end();
}).listen(9009);

http.createServer(function(req, res) {
    console.log("Server 2 created");
    res.writeHead(302, {
        'Location': 'http://localhost:9009/'
    });
    res.end("Request route to 9009");
}).listen( 3001 );

A: in the code you show, the proxy make port 9009 show up on port 3000, more like an apache url rewrite than a url redirect.
if you want to send visitors landing on port 3000 to port 9009, simple http is plenty:
var http = require('http');

http.createServer(function (req, res) {
  res.writeHead(200, { 'Content-Type': 'text/plain' });
  res.write('9009 here' + '\n' + JSON.stringify(req.headers, true, 2));
  res.end();
}).listen( 9009 );

http.createServer(function(req, res) {
    res.writeHead(302, {
        'Location': 'http://X.X.X.X:9009/' // fix me
     });
    res.end("Request route to  9009");
}).listen( 3000 );

if you want every visitor to a new personal port, this is a simple but naive way to do so (not accounting for repeated ports, which will crash node 1/1000 times):
var http = require('http');
http.createServer(function(req, res) {
    var port=Math.floor(Math.random()*1000)+12000;
    http.createServer(function (req, res) {
      res.writeHead(200, { 'Content-Type': 'text/plain' });
      res.write( port + ' talking' + '\n' + JSON.stringify(req.headers, true, 2));
      res.end();
    }).listen( port );

    res.writeHead(302, {
        'Location': 'http://X.X.X.X:'+ port +'/'  // fix me
     });
    res.end("Request route to " + port );
}).listen( 3000 );


text:
Q: Optimal value of spark.sql.shuffle.partitions for a Spark batch Job reading from Kafka I have a Spark batch job that consumes data from a Kafka topic with 300 partitions. As part of my job, there are various transformations like group by and join which require shuffling.
I want to know if I should go with the default value of spark.sql.shuffle.partitions which are 200 or set it to 300 which is the same as the number of input partitions in Kafka and hence the number of parallel tasks spawn to read it.
Thanks

A: In the chapter on Optimizing and Tuning Spark Applications of the book "Learning Spark, 2nd edition" (O'Reilly) it is written that the default value

"is too high for smaller or streaming workloads; you may want to reduce it to a lower value such as the number of cores on the executors or less.
There is no magic formula for the number of shuffle partitions to set for the shuffle stage; the number may vary depending on your use case, data set, number of cores, and the amount of executors memory available - it's a trial-and-error-approach."

Your goal should be to reduce the amount of small partitions being sent accross the network to executor's task.
There is a recording of a talk on Tuning Apache Spark for Large Scale Workloads which also talks about this configuration.
However, when you are using Spark 3.x, you do not think about that much as the Adaptive Query Execution (AQE) framework will dynamically coalesce shuffle partitions based on the shuffle file statistics. More details on the AQE framework are given in this blog.


text:
Q: filename..extension // Paperclip reprocess Some kind of problem I can't resolve…
In some app, a method called on :before_create was prefixing the file's extension with a double-dot (ex. /images/13402/medium/hey-1..jpg)
The problem is fixed for the new ones, but nothing occurs when I apply a reprocess! on the old ones; and I'd like to know if anyone could help about it

A: Reprocess / refresh only takes your original image and recreates the defined styles in your model class. So if your original image contains a file path with double dots in it, these are also applied to the generated styles. You have to clean up your original files and the stored file paths in your model records.
The only way I know would be to write a little script to modify this. Basically
foreach image
  strip out double dots from original file name
  rename file
  store new file path in model record
end

And then rake paperclip:refresh


text:
Q: Show images from my cloudinary library in pug template I get an error when I display the images in timeline which it comes from my cloudinary on the format "https://res.cloudinary.........."
That does not display using this code
timeline.pug
each post in posts
  .main-card.col-md-6.col-lg-4
    .right-content
      .card-container
        .card.left-card
          .product-img
            img.c-image(src= `${post.imageCover}` alt=`${post.name}`)


text:
Q: Alterar dados em uma planilha através de uma listbox Tenho um formulário com duas caixas de texto, três botões de comando, uma listbox e algumas labels.
O objetivo do formulário é listar dados que são inseridos no banco de dados (que é a própria planilha do excel).
Como funciona o código:
São inseridos os textos nas 2 texbox e a listbox é alimentada através do rowsource em código.
Funciona quase tudo certo; cadastra o texto, a listbox é alimentada pela BD através do rowsource porém no último estágio que é alterar os dados inseridos o botão não ativa.
Segue o código:
'CADASTRAR TEXTO NO LISTBOX

Private Sub Boão_Cadastrar_Click()

If VerificaCampo(Me.CAIXA_DE_TEXTO01.Text) = False Then
    MsgBox "Informe o texto desejado", vbExclamation, "ERRO"
    Exit Sub

End If

If VerificaCampo(Me.CAIXA_DE_TEXTO02.Text) = False Then
    MsgBox "Informe o texto desejado", vbExclamation, "ERRO"
    Exit Sub

End If

    Sheets("VALIDAÇÃO").Activate 'ATIVA A PLANILHA CORRESPONDENTE
    Range("E2").Select 'SELECIONA A CÉLULA ESPECIFICADA ENTRE OS PARENTESES

Do 'FAÇA
        If ActiveCell.Value <> Empty Then  'SE O VALOR DA CELULA SELECIONADA FOR DIFERENTE DE VAZIO ENTÃO

            ActiveCell.Offset(1, 0).Select  'A CELULA ATIVA VAI PARA O CAMINHO INDICADO NOS PARENTESES
        End If                              'FIM DO SE

Loop Until ActiveCell.Value = Empty         'REPETIR ATÉ QUE O VALOR DA CÉLULA ATIVA SEJA IGUAL A VAZIO

    ActiveCell.Value = Me.CAIXA_DE_TEXTO01 'O VALOR DA CÉLULA ATIVA VAI RECEBER O QUE FOR DIGITADO NA CAIXA DE TEXTO CORRESPONDENTE

    ActiveCell.Offset(0, 1).Value = Me.CAIXA_DE_TEXTO02.Text 'O MESMO DE CIMA

    MsgBox ("Atualização efetuada com SUCESSO!!") 'MESSAGEM DO SISTEMA

    Me.CAIXA_DE_TEXTO01.Text = Empty 'LIMPA A CAIXA DE TEXTO
    Me.CAIXA_DE_TEXTO02.Text = Empty 'LIMPA A CAIXA DE TEXTO

    'ATUALIZA OS DADOS PARA QUE ELES APARECAM NO FORMULÁRIO SEM PRECISAR FECHÁ-LO
    Unload Me
    Userform.Show

End Sub

'CAMPO DE VERIFICAÇÃO

Private Function VerificaCampo(Texto As String) As Boolean

    If Texto = "" Then
    VerificaCampo = False

    Else
    VerificaCampo = True

    End If

End Function

'SELECIONA OS DADOS NA LISTBOX PARA PODER SER FEITA A ALTERAÇÃO EM DADOS

Private Sub ListBox1_Change()

Me.CAIXA_DE_TEXTO01.Text = ListBox1.List(ListBox1.ListIndex, 0) '1ª COLUNA
Me.CAIXA_DE_TEXTO02.Text = ListBox1.List(ListBox1.ListIndex, 1) '2ª COLUNA

End Sub

'BOTÃO QUE ALTERA LEGISLAÇÕES E/OU ARTIGOS

Private Sub Botão_Alterar_Legislações_Artigos_Click()

If VerificaCampo(Me.CAIXA_DE_TEXTO01.Text) = False Then
    MsgBox "Informe a legislação desejada", vbExclamation, "ERRO"
    Exit Sub

End If

If VerificaCampo(Me.CAIXA_DE_TEXTO02) = False Then
    MsgBox "Informe o texto desejado", vbExclamation, "ERRO"
    Exit Sub

End If

Dim X As String
Dim Y As String

X = Me.CAIXA_DE_TEXTO01.Text
ARTIGO = Me.CAIXA_DE_TEXTO02.Text

Dim LINHA As Integer
LINHA = ListBox1.ListIndex

ListBox1.List(LINHA, 0) = X
ListBox1.List(LINHA, 1) = Y

Me.CAIXA_DE_TEXTO01 = ""
Me.CAIXA_DE_TEXTO02 = ""

Me.CAIXA_DE_TEXTO01.SetFocus

End Sub

'LIMPAR TUDO/APAGAR DA PLANILHA

Private Sub Botão_Limpar_Tudo_Click()

[E2:F100000].ClearContents

Unload Me

Userform.Show

End Sub

'POPULAR LISTBOX:

Private Sub UserForm_Initialize()

Ulinha = Range("e1000000").End(xlUp).Row

ListBox1.RowSource = "VALIDAÇÃO!E2:F" & Ulinha

End Sub


text:
Q: How can you rename a label on a button using JQuery? I'm trying to work out a way of replacing a button label 'Add to bag' to 'Add to basket' using JQuery as I don't have access to the HTML on the page.
The HTML looks like this:

        <button type="submit" class="submit button btn btn_primary btn_large">Add to bag</button>

I've tried various versions of this JS:
$(document).ready(function() {
    $('#main button.submit button btn btn_primary btn_large').replaceWith('Add to basket');
});

Clearly it's wrong but I don't quite know how to target the content within the  tag.
JFiddle is here: [http://jsfiddle.net/0wwhrfry/]
Any help would be great.
Thanks,
Adam

A: Two issues:
1) you need to use correct selector to target button
2)Use .text() to set the text:
$('#main .btn_large').text('Add to basket');

Working Demo

A: You can change the selectors as per requirement. The thing here you need is jQuery code.
Kindly find below snippet:
$(document).ready(function() {
    $('button').html('Add to basket');
});

If you have parent ID (like here) you have #main so can simply change the selector as below:
 $(document).ready(function() {
        $('#main button').html('Add to basket');
 });

OR
 $(document).ready(function() {
        $('#main button.submit').html('Add to basket');
 });

DEMO
Hope this will fix your query.
Thanks.

A: You can do this using .text()
$('button.submit').text('Add to basket');

Edit: Also, as Milind points out, you don't need such a huge selector.
In fact, (I know you're probably using it anyway), but you don't need jQuery for something so simple:
var button = document.querySelector(".button.submit");
button.textContent = "New value"


text:
Q: GROUP_Concat Hyperlink  So I have in my database a table called "Clients" and an other one called "Pets". They are linked by an associative table which means that a "Clients" can have two "Pets".
I am using this SQL Query to display many pets for one client :
SELECT *,
GROUP_CONCAT(DISTINCT petName ORDER BY petName) AS petsNames
FROM clients
LEFT JOIN owners ON owners.idClients = clients.idClients
LEFT JOIN pets ON pets.idPets = owners.idPets
LEFT JOIN clientsdocs ON clientsdocs.idClients = clients.idClients
WHERE clients.idClients='$id'

And I am using this foreach loop :
foreach ($files as $file) :
echo $file['address'];
endforeach

My issue is the following :
Pets :  <a href="?profilePet=<?= $file['idPets']; ?>"> <?= $file['petsNames']; ?>

I am using this line of code to print the client's pets but I want them to be hyperlinked, Which means that I would be able to Click on the differents pets. The problem is that GROUP_Concat linked all of the pets which mean that when I click on one pet I always go to the first written.

As you can see, the pet "Penelope" and "W" are linked by "GROUP_COncat". So when I click on it, it sends me to the first pet (Penelope).

A: You can split your petnames about comma and add a tags to each of it :
$pets = explode(',',$file['petsNames']);
foreach($pets as $pet){
echo ''.$pet.'';
}


text:
Q: Error while getting response from the server using ajax var x = document.getElementById("demo");

function geoapp() {
    if (navigator.geolocation) {
        navigator.geolocation.getCurrentPosition(showPosition);
    }
    else {
        x.innerHTML = "Geolocation is not supported by this browser.";
    }
}

function showPosition(position) {
    var lat = position.coords.latitude;
    var longi = position.coords.longitude;
    var appid = * * * * ;
    var geoapp = 'http://where.yahooapis.com/geocode?       l                        location=' + lat + ',' + longi + '&flags=J&gflags=R&appid=' + appid;
    document.getElementById("demo").innerHTML = geoapp;
    var my_JSON_object = {};
    var http_request = new XMLHttpRequest();
    http_request.open("GET", geoapp, true);
    http_request.onreadystatechange = function() {
        var done = 4,
            ok = 200;
        if (http_request.readyState == done && http_request.status == ok) {
            my_JSON_object = JSON.parse(http_request.responseText);
            document.getElementById("demo").innerHTML = my_JSON_object;
        }
    };
    http_request.send(null);
}

this piece of code get coordinates from html5 geoapi then send them to the yahoo placefinder api but
i am not able to receive json object while the query is working fine.
any help will be appreciated


text:
Q: Округлить число Мне нужно округлить число , которое в итоге получается
$("#total_video span").Math.round(summ);

сам код
$(function(){
    $('#subscribe_video input:checkbox').on("change", function(){
        var summ = 35.99;
        $('#subscribe_video input:checkbox:checked').each(function(index, element){
            var add = parseInt($(element).val(), 10);
            if(!isNaN(add))
                summ += add;
        });
        $("#total_video span").text(summ);
    })
});

A:
var add = parseInt($(element).val(), 10);

var add = +$(element).val();

$("#total_video span").text(summ);

$("#total_video span").text(Math.round(summ));

$("#total_video span").text(summ.toFixed(2));

И полный код, но по-другому:

$(function () {
  $('#subscribe_video').on("change", 'input[type="checkbox"]', function () {
    $("#total_video span").text(Array.prototype.reduce.call(
      $('#subscribe_video input[type="checkbox"]:checked'),
      function (sum, inp) { return +$(inp).val() + sum; },
      35.99
    ).toFixed(2));
  });
});

  <input type=checkbox value="2.65">2.65
  <input type=checkbox value="2.99">2.99
  <input type=checkbox value="0.004">0.004
  <input type=checkbox value="0.006">0.006
  <input type=checkbox value="0.004">0.004
  <input type=checkbox value="0.004">0.004

Total:


text:
Q: Cannot find the DropDownList in DetailView Insert Mode I created a DetailView which is bound. I would like to have a DropDownList for the ProposalStatus field instead of a TextBox. I can add the DropDownList dynamically, but cannot find the control after clicking the Insert.
Is there way to find the DropDownList in behind code? Or do I have to use the ItemTemplate?
Thank you
test.aspx
<form runat="server">
    <asp:DetailsView ID="dvProposal" runat="server" Height="50px" Width="100%"
    OnModeChanging="dvProposal_OnModeChanging" OnItemInserting="dvProposal_OnItemInserting"
    OnItemDeleting="dvProposal_OnItemDeleting">
    </asp:DetailsView>
</form>

test.aspx.cs
using System;
using System.Collections.Generic;
using System.Linq;
using System.Web;
using System.Web.UI;
using System.Web.UI.WebControls;
using System.Web.Configuration;
using System.Data.OleDb;
using System.Data.SqlClient;
using System.Data;

public partial class test : System.Web.UI.Page
{
    string connectionString = WebConfigurationManager.ConnectionStrings["WildfireOperationsResearch"].ConnectionString;
    protected void Page_Load(object sender, EventArgs e)
    {
        if (!this.IsPostBack)
        {
            dvProposal_DataRebind();
        }
    }

    protected DropDownList LoadProposalStatusDropDownList()
    {
        DropDownList ProposalStatusList = new DropDownList();
        string SelectString = "select ProposalStatus from ProposalStatus order by ProposalStatus";
        OleDbConnection MyConnection = new OleDbConnection(connectionString);
        OleDbDataAdapter MyDataAdapter = new OleDbDataAdapter(SelectString, MyConnection);
        DataSet MyDataSet = new DataSet();

            MyDataAdapter.Fill(MyDataSet);
            ProposalStatusList.DataSource = MyDataSet;
            ProposalStatusList.DataValueField = "ProposalStatus";
            ProposalStatusList.DataTextField = "ProposalStatus";
            ProposalStatusList.ID = "ddProposalStatus";

            ProposalStatusList.DataBind();

        return ProposalStatusList;
    }

    protected void dvProposal_DataRebind()
    {

        string SelectString = "select ProposalNo,ProposalCode, ProposalTitle, YearSubmitted, ProposalStatus, ProposalLink " +
            "from Proposal where ProposalNo=64" ;
        OleDbConnection MyConnection = new OleDbConnection(connectionString);
        OleDbDataAdapter MyDataAdapter = new OleDbDataAdapter(SelectString, MyConnection);
        DataSet MyDataSet = new DataSet();

            MyDataAdapter.Fill(MyDataSet);

            //load into detail view
            dvProposal.DataSource = MyDataSet;
            dvProposal.AutoGenerateEditButton = true;
            dvProposal.AutoGenerateDeleteButton = true;
            dvProposal.AutoGenerateInsertButton = true;

            dvProposal.DataBind();

            if (dvProposal.CurrentMode != DetailsViewMode.ReadOnly)
            {

                // add the DropDownList to the DetailView
                DropDownList ProjectProposalList = LoadProposalStatusDropDownList();
                dvProposal.Rows[4].Cells[1].Controls.Add(ProjectProposalList);

                dvProposal.Rows[4].Cells[1].Controls[0].Visible=false;

                ((TextBox)dvProposal.Rows[0].Cells[1].Controls[0]).Enabled = false;

            }

    }

    protected void dvProposal_OnModeChanging(Object sender, DetailsViewModeEventArgs e)
    {

        dvProposal.ChangeMode(e.NewMode);

        dvProposal_DataRebind();

    }

//give me a NullReferenceException. Cannot find the DropDownList control in the DetailView.
    protected void dvProposal_OnItemInserting(object sender, DetailsViewInsertEventArgs e)
    {

        string proposalCode = e.Values[1].ToString();
        string proposalTitle = e.Values[2].ToString();
        string YearSubmitted = e.Values[3].ToString();

        **//give me a NullReferenceException. Cannot find the DropDownList control in the DetailView.**
        string proposalStatus = ((DropDownList)dvProposal.Rows[4].Cells[1].FindControl("ddProposalStatus")).SelectedValue;
        string ProposalLink = e.Values[5].ToString();

        string insertString = " insert into Proposal (ProposalCode, ProposalTitle, YearSubmitted, ProposalStatus, ProposalLink) " +
            "values('" + proposalCode + "','" + proposalTitle + "'," + YearSubmitted + ",'" + proposalStatus + "','" + ProposalLink + "')";

        OleDbConnection MyConnection = new OleDbConnection(connectionString);
        OleDbCommand MyCommand = new OleDbCommand(insertString, MyConnection);
        MyConnection.Open();

            MyCommand.ExecuteNonQuery();

            MyConnection.Close();

            dvProposal_DataRebind();
    }

    protected void dvProposal_OnItemDeleting(object sender, DetailsViewDeleteEventArgs e)
    {
        string deleteString = "delete from Proposal where ProposalNo=" + e.Values[0];

        OleDbConnection MyConnection = new OleDbConnection(connectionString);
        OleDbCommand MyCommand = new OleDbCommand(deleteString, MyConnection);
        MyConnection.Open();

        MyCommand.ExecuteNonQuery();

        MyConnection.Close();
        dvProposal_DataRebind();
    }

}

A: Thanks Garrison Neely's suggestion. I guess using TemplateField is the fast way for now. So, I modified the code.
test.aspx
<form id="Form1" runat="server">

<asp:DetailsView ID="dvProposal" runat="server" Height="50px" Width="100%"
    OnModeChanging="dvProposal_OnModeChanging" OnItemInserting="dvProposal_OnItemInserting"
    OnItemDeleting="dvProposal_OnItemDeleting" OnDataBound="dvProposal_OnDataBound"  AutoGenerateRows="false">
    <Fields>
        <asp:BoundField DataField="ProposalNo" HeaderText="ProposalNo"/>
        <asp:BoundField DataField ="ProposalCode" HeaderText ="ProposalCode" />
        <asp:BoundField DataField ="ProposalTitle" HeaderText ="ProposalTitle" />
        <asp:BoundField DataField ="YearSubmitted" HeaderText ="YearSubmitted" />

        <asp:TemplateField HeaderText ="ProposalStatus">
            <InsertItemTemplate>
                <asp:DropDownList runat="server" DataTextField ="ProposalStatus" DataValueField ="ProposalStatus"
                ID="ddlProposalStatus" ></asp:DropDownList>
            </InsertItemTemplate>
            <EditItemTemplate>
                <asp:DropDownList runat="server" DataTextField ="ProposalStatus" DataValueField ="ProposalStatus"
                ID="ddlProposalStatus" ></asp:DropDownList>
            </EditItemTemplate>
            <ItemTemplate>
                <asp:Label runat="server" Text='<%# Bind("ProposalStatus") %>' ID="Label1"></asp:Label>
            </ItemTemplate>
        </asp:TemplateField>
        <asp:BoundField DataField ="ProposalLink" HeaderText ="ProposalLink" />
    </Fields>
</asp:DetailsView>
</form>

test.aspx.cs
using System;
using System.Collections.Generic;
using System.Linq;
using System.Web;
using System.Web.UI;
using System.Web.UI.WebControls;
using System.Web.Configuration;
using System.Data.OleDb;
using System.Data.SqlClient;
using System.Data;

public partial class test : System.Web.UI.Page
{
    string connectionString = WebConfigurationManager.ConnectionStrings["WildfireOperationsResearch"].ConnectionString;
    protected void Page_Load(object sender, EventArgs e)
    {
        if (!this.IsPostBack)
        {
            dvProposal_DataRebind();
        }
    }

    protected void LoadProposalStatusDropDownList()
    {
        DropDownList ProposalStatusList = (DropDownList)this.dvProposal.FindControl("ddlProposalStatus");
        string SelectString = "select ProposalStatus from ProposalStatus order by ProposalStatus";
        OleDbConnection MyConnection = new OleDbConnection(connectionString);
        OleDbDataAdapter MyDataAdapter = new OleDbDataAdapter(SelectString, MyConnection);
        DataSet MyDataSet = new DataSet();

            MyDataAdapter.Fill(MyDataSet);
            ProposalStatusList.DataSource = MyDataSet;

            ProposalStatusList.DataBind();

            if (dvProposal.CurrentMode == DetailsViewMode.Edit)
            {
                DataRowView drv=(DataRowView)this.dvProposal.DataItem;

                ProposalStatusList.Items.FindByValue(drv.Row[4].ToString()).Selected = true;
            }

    }

    protected void dvProposal_DataRebind()
    {

        string SelectString = "select ProposalNo,ProposalCode, ProposalTitle, YearSubmitted, ProposalStatus, ProposalLink " +
            "from Proposal where ProposalNo=64" ;
        OleDbConnection MyConnection = new OleDbConnection(connectionString);
        OleDbDataAdapter MyDataAdapter = new OleDbDataAdapter(SelectString, MyConnection);
        DataSet MyDataSet = new DataSet();

            MyDataAdapter.Fill(MyDataSet);

            //load into detail view

            dvProposal.DataSource = MyDataSet;
            dvProposal.AutoGenerateEditButton = true;
            dvProposal.AutoGenerateDeleteButton = true;
            dvProposal.AutoGenerateInsertButton = true;

            dvProposal.DataBind();

    }

    protected void dvProposal_OnDataBound(Object sender, EventArgs e)
    {
        if (this.dvProposal.CurrentMode != DetailsViewMode.ReadOnly)
        {
            LoadProposalStatusDropDownList();
            ((TextBox)dvProposal.Rows[0].Cells[1].Controls[0]).Enabled = false;

        }

    }

    protected void dvProposal_OnModeChanging(Object sender, DetailsViewModeEventArgs e)
    {

        dvProposal.ChangeMode(e.NewMode);

        dvProposal_DataRebind();

    }

    protected void dvProposal_OnItemInserting(object sender, DetailsViewInsertEventArgs e)
    {

        string proposalCode = e.Values[1].ToString();
        string proposalTitle = e.Values[2].ToString();
        string yearSubmitted = e.Values[3].ToString();

        //give me a NullReferenceException. Cannot find the DropDownList control in the DetailView.
        string proposalStatus = ((DropDownList)dvProposal.Rows[4].Cells[1].FindControl("ddlProposalStatus")).SelectedValue;

        string proposalLink = e.Values[4].ToString();

        string insertString = " insert into Proposal (ProposalCode, ProposalTitle, YearSubmitted, ProposalStatus, ProposalLink) " +
            "values('" + proposalCode + "','" + proposalTitle + "'," + yearSubmitted + ",'" + proposalStatus + "','" + proposalLink + "')";

        OleDbConnection MyConnection = new OleDbConnection(connectionString);
        OleDbCommand MyCommand = new OleDbCommand(insertString, MyConnection);
        MyConnection.Open();

            MyCommand.ExecuteNonQuery();

            MyConnection.Close();

            dvProposal_DataRebind();

    }

    protected void dvProposal_OnItemDeleting(object sender, DetailsViewDeleteEventArgs e)
    {
        string deleteString = "delete from Proposal where ProposalNo=" + e.Values[0];

        OleDbConnection MyConnection = new OleDbConnection(connectionString);
        OleDbCommand MyCommand = new OleDbCommand(deleteString, MyConnection);
        MyConnection.Open();

        MyCommand.ExecuteNonQuery();

        MyConnection.Close();

        dvProposal_DataRebind();
    }

}


text:
Q: How To Use GraphQL To get Product Entity? I want to built custom extension to get product entity using GraphQL.
I referred below links.
https://www.rakeshjesadiya.com/get-product-collection-using-graphql-magento-2/
https://amasty.com/blog/magento-2-api-updates-graphql/
Still if anyone have good reference extension then please help me.


text:
Q: Conditional Formatting cells surrounding a given value So I've set up a conditional formatting VBA macro to highlight two cells: The one with the given string, and the one next to it.
The data set is:
A1          B1
------------------------
PluginID    NUM
Host        ADDRESS
Severity    High
Port        PORT
Description DESCRIPTION
Solution    SOLUTION
References  CVE

The VBA code is:
    Sub High2()
'
' High2 Macro
'

'
    Columns("A:B").Select
    Selection.FormatConditions.Add Type:=xlExpression, Formula1:= _
        "=AND($B1=""High"",A1)"
    Selection.FormatConditions(Selection.FormatConditions.Count).SetFirstPriority
    With Selection.FormatConditions(1).Interior
        .PatternColorIndex = xlAutomatic
        .Color = 255
        .TintAndShade = 0
    End With
    Selection.FormatConditions(1).StopIfTrue = False
End Sub

This highlights the cell with 'High' in it, and the cell to the left, 'Severity'.
If I change the "=AND($B1=""High"",A1)" line to "=AND($B2=""High"",A1)" then excel will highlight the 2 cells above it in red instead, i.e. Host.
Can anyone help me with highlighting the 4 cells above and 8 cells below the string search-term as well (i.e. the Port, Description, Solution and References cells)?

A: What you are actual doing if you "change the "=AND($B1=""High"",A1)" line to "=AND($B2=""High"",A1)"" is simply add a new rule. So this will be really the best approach. Adding as much rules as necessary.
Sub High2()
 With Columns("A:B").Cells
  .Range("A1").Activate
  .FormatConditions.Delete
  For i = 1 To 3 ' 3 above
   .FormatConditions.Add Type:=xlExpression, Formula1:="=($B" & i & "=""High"")"
   .FormatConditions(.FormatConditions.Count).SetFirstPriority
   With .FormatConditions(1).Interior
    .PatternColorIndex = xlAutomatic
    .Color = 255
    .TintAndShade = 0
   End With
   .FormatConditions(1).StopIfTrue = False
  Next
  For i = 0 To 3 ' 4 below
   .FormatConditions.Add Type:=xlExpression, Formula1:="=($B" & .Rows.Count - i & "=""High"")"
   .FormatConditions(.FormatConditions.Count).SetFirstPriority
   With .FormatConditions(1).Interior
    .PatternColorIndex = xlAutomatic
    .Color = 255
    .TintAndShade = 0
   End With
   .FormatConditions(1).StopIfTrue = False
  Next
 End With
End Sub

This could also be reached with only one rule:
=OR($B1048573:$B1048576="High", $B1:$B3="High")
But this will lead to bad performance since it is working as an array formula.


text:
Q: How can I call module function in ASPX markup? I have a VB.NET WebForms app and am trying to use inline server tags in the markup to call a function that's located in a module.  No matter what I do, I cannot get intellisense to show the method when I use <%= %> or <%# %> tags.  Here's my module:
Module TestModule

    Function test() As String

        Return String.Empty

    End Function

End Module

However, when I convert the module into a class and convert the methods into shared methods, I can do this:
Public Class TestClass

    Shared Function test() As String

        Return String.Empty

    End Function

End Class

I can place this within my form:
<%= MyApp.TestClass.test%>

I can use this in control binding:
<asp:Button ID="cmWhatever" Text='<%#MyApp.TestClass.test%>' runat="server" />

How can I reference module methods from the markup?

A: 'Use this instead:
    Public Module TestModule
        Public Function test() As String
          Return String.Empty
        End Function
    End Module

'More over you have to use <%@ Import Namespace="Your root namespace" %> on the start of the aspx page