text:
Q: In urllib3, HTTP request hangs ... but doesn't in curl (Thanks for taking a look at this!)
I'm trying to use python3 and simple urllib3 http.request to read HTML from https://login.morganstanleyclientserv.com.
It seems like the server is resetting the connection, and eventually urllib3's retries give up.
Is there a TLS negotiation issue here? If so, how can urllib3 compensate?
Or is the problem elsewhere? How to troubleshoot this?

I have tried the identical(?) transaction using curl ... it returns the expected HTML without any delay.
I also tried reading from a different site (e.g., https://client.schwab.com/Login/SignOn/CustomerCenterLogin.aspx) ... no problem.
Chrome loads https://login.morganstanleyclientserv.com without problem.
uname -a ; python3 -V returns:
Linux ubuntu 4.18.0-17-generic #18~18.04.1-Ubuntu SMP Fri Mar 15 15:27:12 UTC 2019 x86_64 x86_64 x86_64 GNU/Linux
Python 3.6.7

This is the curl that works:
curl -v --user-agent "Mozilla/5.0 (Windows NT 10.0; Win64; x64) AppleWebKit/537.36 (KHTML, like Gecko) Chrome/73.0.3683.103 Safari/537.36" --header "Accept: text/html,application/xhtml+xml,application/xml;q=0.9,image/webp,image/apng,*/*;q=0.8,application/signed-exchange;v=b3" --header "Accept-Encoding: text/plain" --header "Accept-Language: en-US,en;q=0.9" --output foo  https://login.morganstanleyclientserv.com

This is the python3 + urllib3 code that hangs (after printing 1, then 2, but not anything else):
import urllib3
import certifi

print (1)
try:
    http = urllib3.PoolManager(cert_reqs = 'CERT_REQUIRED',
                               ca_certs = certifi.where())

    headers = {'User-Agent': 'Mozilla/5.0 (Windows NT 10.0; Win64; x64) AppleWebKit/537.36 (KHTML, like Gecko) Chrome/73.0.3683.103 Safari/537.36',
               'Accept': 'text/html,application/xhtml+xml,application/xml;q=0.9,image/webp,image/apng,*/*;q=0.8,application/signed-exchange;v=b3',
               'Accept-Encoding': 'text/plain',
               'Accept-Language':'en-US,en;q=0.9'
               }
    print (2)
# *** This hangs ***
    r = http.request("GET", "https://login.morganstanleyclientserv.com", headers)
    print (3)
    print (r.data)
    print (4)
except Exception as e:
    print(e)
except:
    print("error")

A: As a python newbie, I neglected to name the headers parameter in the http.request call. It should have read:
r = http.request("GET", "https://login.morganstanleyclientserv.com", headers=headers)

Thanks to Edeki!


text:
Q: Next.js global redirect to lowercase URLs It looks that by default Next.js handles URLs in a case-insensitive manner (at least when using rewrites).
I found this documentation on redirects and was wondering if there is a way to do a global redirect if a URL is found with capital letters, to its equivalent lowercase letter URL?
Is there a way to do this either with redirects or some other way? (ideally looking for a global solution)
Here is a pseudo-code (non-functional) of what I had in mind (this would be in next.config.js):
module.exports = {
  async redirects() {
    return [
      {
        source: '/:url*(\p{Alphabetic})',
        destination: `/${url.toLocaleLowerCase()}`,
        permanent: true,
      },
    ];
  }
};

A: It does not appear that such feature exists, but ultimately this type of feature might be better resolved by fixing this issues documented here: https://github.com/vercel/next.js/issues/21498
There might be other reasons for more advanced URL manipulation and this might become a feature request at some point if the community needs this.

redpajama_set_name: RedPajamaStackExchange


text:
Q: I can't see my CSS properties on my website while working NODE.JS and Liveserver I am new at Node.js so i have problem and I couldn't figure it out. Problem is I can't see my css properties in my website when I try to send my index.html with node.js. I will share with my directory and also codes so may you can find what is wrong. I should tell that when I try to click right on my html then hit the click on open with live server I can see my CSS properly but when I try to call with node.js I can't see them.
HTTP Status for CSS file is 200 so everything is fine there but I still can't see my css
// I send my index.html as a Homepage here

app.use('/', (req, res, next) => {
    res.sendFile(path.join(__dirname,'./','views','index.html'));
});

//Here my <link tag in index.html

   <link rel="stylesheet" type="text/css" href="/dist/css/style.css"/>

And you can see my directory here

A: You need to make the dist/ directory public so that browser can read files from them.
Try adding this line
app.use(express.static('dist'));

Recommended to put this before your routes start.


text:
Q: Перезагрузка ModalViewController в Xcode Всем привет!
У меня есть MVC, который открывается при нажатии на кнопку. В данном MVC (scrollView+pageControl+textView) находится "Избранное"(данные берутся из plist-файла) моего приложения. Я хотел бы реализовать возможность удаления. Хотел бы сделать так: удаляю из plist'a (сделал), а потом полностью перезагружаю View, то есть как-будто я закрыл его и снова открыл. Как это сделать (setNeedsDisplay, reloadInputViews и removeFromSuperview не предлагать)?
Как вариант:
UIStoryboard *sb = [UIStoryboard storyboardWithName:@"MainStoryboard_iPhone" bundle:nil];
UIViewController *vc = [sb instantiateViewControllerWithIdentifier:@"ModalViewName"];
[self presentModalViewController:vc animated:YES];

Только данный код открывает новый MVC, а не перезагружает. Спасибо.
A: Нужно заново загрузить данные из .plist и задать новые значения TextField. Зачем перезагружать целый ViewController, когда можно изменить пару элементов?


text:
Q: Error getting ancestor web element attributes I have a method to get an ancestor element of a web_element:
def find_ancestor(self, name):
    element = self.driver.find_element_by_name(name)
    ancestor = element.find_element_by_xpath("ancestor::*")
    print(ancestor)
    attr = ancestor.get_attribute("outerHTML")
    print(attr)

The output for print(ancestor) is <selenium.webdriver.remote.webelement.WebElement (session="43f99228044a37dab999a9512b5e268e", element="0.22129539497775563-3")>
When I try to access and print attributes I get an error: UnicodeEncodeError: 'charmap' codec can't encode character u'\xae' in position 292: character maps to <undefined>
The top of my script has # -*- coding: utf-8 -*  What am I missing/doing wrong? My feeling is 'ancestor' returns differently than other xpath axes!?
background/bonus help
Ideally, I want methods to get parent, preceding-sibling, following-sibling etc.
But when I try such actions on a table cell preceding-sibling is not getting the previous cell (no element found), and with parent I am getting back the same element (the same table cell and not table row).
I am showing python but don't mind answers in c#.

A: I changed the last line to print(attr.encode("utf-8"))
which works.  I don't get why that is required when I have # -*- coding: utf-8 -* at the top of my script. But I am now seeing the ancestor.


text:
Q: Trying to figure out pow source code in python | My function gone wrong I am doing an exercise of my school book which says :
"Write a code in python which calculates the power of a number without using the function pow()."
The first parts of my function are working fine. But when it comes to # elif b > 1
It just returns the number of a * b, not the a ** b ...
I would be really happy if you could help me with that. I have spent at least 1 hour trying to fix it.
def mypow(a,b):
    if b == 0:
        return 1
    if b == 1:
        return a
    elif b > 1:
        x = 0
        for i in range(b):
            x += 1 * a
        return x
    # I know I got to add what happens if the b is negative, but I will do this after fixing the bug.

A: That is probably because you're adding a to x b times. You should multiply, not add.

A: You appear to be adding instead of multiplying.
for i in range(b):
    x *= a

You don't need special cases for 0 and 1; b == 0 is sufficient.
def mypow(a, b):
    answer = 1  # a ** 0 == 1
    # The loop is only entered if b > 0
    for _ in range(b):
        answer *= a
    return answer


text:
Q: How to get values of 2 sides of jquery multiselect2side Here's the jsfiddle for the code http://jsfiddle.net/VFskn/2/
The jquery multiselect2side has 2 parts for the list say the Available and Selected
a.To get the values of Selected portion of the I used the following code:
var multipleValues = $("#columnList").val() || [];

b. To get all values of the list I can use:
$('#columnList option').each(function() {
    columns.push( $(this).attr('value') );
   });

My Question is how I can obtain the Available portion of the list

A: If I understand your question right, you want to get the value of every option that is in the select under Available?
In the given example this select has the id "columnListms2side__sx", so that you can get the values of its options with
var multipleValues = [];
    $("#columnListms2side__sx option").each(function()
{
    multipleValues.push($(this).val())
});

here's the updated fiddle: http://jsfiddle.net/VFskn/3/
!important notes though: its not a good idea to mess with it, other then the functions provided by the plugin.
And I'm not sure how safe it is too assume that this select will allways get this id (e.g. if you have multiple of them in one page). It might be smarter to, build a more generic select. (the plugin seems to create a div container after the select it replaces, you want to get the first select in there)
EDIT:
this would be more generic, but less efficient:
$("#columnList").next().find("select").filter(":first").children().each(function(){...}

updated fiddle: http://jsfiddle.net/VFskn/4/


text:
Q: Binary Classification vs. Aggregating Multi-Class Predictions Sorry for the convoluted question, I'm sure there is a better way to phrase this.  Basically, say I have a 5-class target vector, but I'm only interested in membership in a subset of the classes.
For example, classes = A,B,C,D,E and I'm interested in (A or B) vs. (C or D or E).  Is it better to 'recode' the labels in the training so that (A or B) = 1 and (C or D or E) = -1 and treat the problem as a binary classification.  Or is there a benefit to modeling the classes separately and assign based on P(A or B) vs P(C or D or E)?
To put it concretely, say I'm trying to determine if a patient has cancer and I have a sample of patients with the type of cancer included if they have it.  Is it better to model the chance of lymphoma, leukemia, etc. and aggregate for the chance of cancer, or to label all types as just cancer and model where the type is not distinguished.

A: It's better to recode the labels. In general, it's more sample efficient to train a machine directly for the task-at-hand.
In the recoded case, the classifier would just need to estimate the a single separating hyperplane. In the other case, you are expecting a classifier to accurately estimate multiple hyperplanes. With finite samples, the latter is more prone to error because it's a harder task.


text:
Q: angular jest, Testing effect throw Unhandled error Here is my effect spec file: when i run this
import { TestBed } from '@angular/core/testing';
import { Actions } from '@ngrx/effects';
import { provideMockActions } from '@ngrx/effects/testing';
import { cold, hot, getTestScheduler } from 'jasmine-marbles';
import { Observable } from 'rxjs';
import * as TranslationIdAction from './../actions/translationId.action';
import { EffectsTranslationId } from './../effects/translationId.effects';
import { TranslationIdService } from './../../services/translationId-service';
import { ModelTranslationId } from './../../models/model.translationId';

describe('TranslationIdEffects', () => {

    let db: any;
    let effects: EffectsTranslationId;
    let actions: Observable<any>;

    beforeEach(() => {

        TestBed.configureTestingModule({
            providers: [
                EffectsTranslationId,
                {
                    provide: TranslationIdService,
                    useValue: { getTranslationIds: jest.fn() }
                },
                provideMockActions(() => actions),
            ]
        });

        db = TestBed.get(TranslationIdService);
        effects = TestBed.get(EffectsTranslationId);
        actions = TestBed.get(Actions);

    });

    describe('check the storage stupport', () => {

        it('should called intial subscribe', () => {

            effects.EffLoadTranslationId.subscribe();
            expect(db.getTranslationIds).toHaveBeenCalled();

        });

    });

});

getting an error as:

jest translationId.effects.spec
  console.error node_modules/jest-jasmine2/build/jasmine/Env.js:289
    Unhandled error

  console.error node_modules/jest-jasmine2/build/jasmine/Env.js:290
    [
      CallSite {}, CallSite {},
      CallSite {}, CallSite {},
      CallSite {}, CallSite {},
      CallSite {}, CallSite {},
      CallSite {}, CallSite {}
    ]

 RUNS  src/app/pf-services/state/effects/translationId.effects.spec.ts

how to fix this?
my setup-js file:
// import 'jest';
import 'jest-preset-angular';

/* global mocks for jsdom */
const mock = () => {
  let storage: { [key: string]: string } = {};
  return {
    getItem: (key: string) => (key in storage ? storage[key] : null),
    setItem: (key: string, value: string) => (storage[key] = value || ''),
    removeItem: (key: string) => delete storage[key],
    clear: () => (storage = {})
  };
};

Object.defineProperty(window, 'localStorage', { value: mock() });
Object.defineProperty(window, 'sessionStorage', { value: mock() });
Object.defineProperty(window, 'getComputedStyle', {
  value: () => ['-webkit-appearance'],
});

Object.defineProperty(document.body.style, 'transform', {
  value: () => {
    return {
      enumerable: true,
      configurable: true,
    };
  },
});

/* output shorter and more meaningful Zone error stack traces */
// Error.stackTraceLimit = 2;


text:
Q: How to call an div's attributes value using a function if there are many div's with the same function? I have the following code:
function openCanviewer() {
    var cid = $(this).data('cid');
    alert(cid);
}

And the HTML:

My problem is that when I click the element with the onclick function, which I have many of because they get inserted from the database, the alert is just showing "undefined" instead of the contents of the data-cid attribute. Does someone have any idea what I have done wrong, or what I am missing here?

A: To capture the exact element, pass this from the element's click event handler
function openCanviewer(element) {
    var cid = $(element).data('cid');
    alert(cid);
}

                       ^^^ you have a typo here

Snippet

function openCanviewer(element) {
  var cid = $(element).data('cid');
  alert(cid);
}

Click

A:

$('#mi').click(function() {
  var cid = $(this).data('cid');
  alert(cid);
});

hello

A: In general you shouldn't use inline events like onclick="openCanviewer();", you should always keep js, css and html separate.
For your problem you could use delegate event listening:
function openCanviewer() {
  var cid = $(this).data('cid');
  alert(cid);
}

$(document).on('click', '[data-cid]', openCanviewer)


text:
Q: Create property with no implemented setter class Human:
    def __init__(self) -> None:
        self.name = None  # type: str

    def introduce(self):
        print("I'm " + self.name)

class Alice(Human):
    def __init__(self) -> None:
        super().__init__()
        self.name = "Alice"

class Bob(Human):
    def __init__(self, rude: bool) -> None:
        super().__init__()
        self.rude = rude

    @property
    def name(self) -> str:
        return "BOB!" if self.rude else "Bob"

if __name__ == '__main__':
    alice = Alice()
    alice.introduce()
    bob = Bob(rude=True)
    bob.introduce()

In the code above, there is an abstract Human class (in reality it is not a human and has more complex methods, not related to the problem). Most of its implementations would set their names by simply assigning a string to the name attribute (just as Alice). But there are few exceptions, like Bob, when there is more complex logic assigned (the value depends on the object state in the moment of resolving).
Therefore in Bob class I created a custom getter for the name property. But as an effect, it is impossible to create a class instance, because invoking the superconstructor results in the following error.
AttributeError: can't set attribute

And it is impossible to add a naive setter as well.
@name.setter
def name(self, name: str):
    self.name = name

Why? Because it would result in an infinite loop. How to solve that issue?

A: why not make a dummy setter
@name.setter
    def name(self, value):
        pass

When self.name = None is executed it will call this setter and actually do nothing

A: If you're certain that your subclasses will assign name, then you can leave out the assignment in the parent constructor. Right now, Human is attempting to set to name, when there is no setter. If you removed it from the Human constructor, then Human can look like this:
class Human:
    def introduce(self):
        print("I'm " + self.name)

A: For class BobI would have used something like this in this case:
@name.setter
def name(self, name: str):
    self._name = name

Afterwards you can do whatever you want in the more complex getter with the internal value. Or did I get the question wrong?
Executing the code would give:
I'm Alice
I'm BOB!


text:
Q: How to change style on zoom event I want to change chart by another chart on zoom event in Angular, I am trying to give one of the charts "display: none" on zoom event. following code print "It works" in console on zoom event ->
chart.chartContainer.events.on("wheel", change);

function change(visibility: any){
    console.log("It works")
    }

However, I want to change style of one of the chart's and make its display none. I tried following ->
component.html

component.ts
export class MapComponent implements OnInit {

  constructor() { }

  visibility = "flex"

  ngOnInit(): void {....

I want to make "visibility" none when change function runs
(it is located in chart's function)->
function hello(visibility: any){
      visibility = "none"
    }


text:
Q: Using too many Modules in Verilog affect timing? I have a straightforward quest about HDL and FPGA design.
If I seperate my code to a lot of modules, by modules I mean verilog files which do specifig things instead of writing close to the top module, does it affect clk timing?
Ill try to illustrate my question:
the first option the I write most of my code in 1 file (not a top file, I know I shouldnt write logic on the top):

the second option that I going deep with my modules, instead of write lot of code in 1 file, I will have seperate hdl files that does some functionality and bring back upstair the answers, something like this:

does it affect timings of the clock/reset etc?
does it good design to write lot of modules and going deep with the modules or I should stay close the the top?
In my opinion, I using Lattice FPGA and I "Share Resources" option in the syntesis, and than, its doesnt matter.

A: No, it doesn't affect the timing or final netlist. If you take a signal from the top level and assign it to successive modules, the compiler will recognise this is the same signal. Modules are there to allow you to:

*

*Group functionality into logical blocks.

*Reuse common designs.

*Keep design elements at a size you, as a human, can keep track of.

I try to have only assignments and very simple logic (e.g. ORing the output of two modules) at the top level. This keeps the namespace clean, and allows easy traversal of the hierarchy in the simulator.

A: I don't know about Lattice tools but my experience with Synopsys was that changing the module hierarchy could affect the timing results. The important issue was whether or not the compiler would completely flatten the design before starting optimization.
If the design is completely flattened then the tools will optimize across module boundaries, so that each instance of every module is optimized for the specific case of how it is connected to other modules.
If the design is not flattened then the lower level modules can only be optimized internally, without knowledge of how they are used, which can be less effective.

A: I'm not familiar with FPGA. But it will really worsen timing if we did bad design partition when designing ASICs. Too many hierarchies without care will possibily lead to a situation where a cloud of combinational gates is splitted into different modules, or feedthough happens. If we now synthesize this design without flattening, the tool will not optimize across module boundaries, and hence lower operating frequency. I agree with @Elliot Alderson.


text:
Q: Proof that any two random variables are independent Let X and Y be two continuous random variables with densities $p_X(x)$ and $p_Y(y)$, respectively.
By normalization, $\int p_X(x)dx = 1$. Viewed as a marginal distribution, we can express  $p_X(x)$ as $\int p_{X,Y}(x,y)dy$. Substituting back into the normalization condition and applying Fubini's theorem to switch the order of integration gives us $$\iint p_{X,Y}(x,y)dxdy = 1$$
Alternatively, consider the product $(\int p_X(x)dx)(\int p_Y(y)dy) = 1$. A corollary to Fubini's theorem lets us treat this product of integrals as an integral of the product of integrands: $$\iint p_X(x)p_Y(y)dxdy = 1$$
What's wrong with this reasoning? Clearly the joint distribution does not generally equal the product of the marginals without the assumption of independence (which is absent here).

A: It's not clear what you think the problem is.  You have found that $p_{X,Y}(x,y)$ and $p_X(x)p_Y(y)$ give the same result when integrated.  That doesn't mean they are the same function!  Indeed, any density function at all has an integral of $1$; that doesn't mean all distributions are the same.

A: You essentially established that $1\cdot1=1$, which is a known result.
It does not imply at all that $p(x,y)=p'(x)\cdot p''(y)$.


text:
Q: OneWayToSource binding not working for UserControl DependencyProperty (using VS 2010)
I have defined a UserControl with a Curves collection as a dependency property:
Public Class GroupedChartSetupControl
....
Public Shared ReadOnly CurvesProperty As DependencyProperty =
            DependencyProperty.Register("Curves", GetType(ObservableCollection(Of CurveVM)),   GetType(GroupedChartSetupControl), New UIPropertyMetadata(Nothing))

 Public Property Curves As ObservableCollection(Of CurveVM)
    Get
        Return CType(GetValue(CurvesProperty), ObservableCollection(Of CurveVM))
    End Get
    Set(value As ObservableCollection(Of CurveVM))
        SetValue(CurvesProperty, value)
    End Set
End Property

Then in the control's constructor, I initialize the Curve collection:
 Sub New()

    InitializeComponent()

    SetValue(CurvesProperty, New ObservableCollection(Of CurveVM))
    ....

Next, in a Window I'm placing this UserControl into the row template of a datagrid. I want to bind the Curves collection to the source property SubCurves in the datagrid's viewmodel:
 <DataGrid.ItemContainerStyle>
                <Style TargetType="{x:Type DataGridRow}">
                    <Setter Property="Template">
                        <Setter.Value>
                            <ControlTemplate TargetType="{x:Type DataGridRow}">
                                <Grid>
                                    <local:GroupedChartSetupControl Curves="{Binding SubCurves, Mode=OneWayToSource}"
....

Note the OneWaytoSource of the binding. The UserControl should be sending the Curves collection to the row's ViewModel, not the other way around. But when I debug, the viewmodel SubCurves property is always null. My WPF knowledge is fairly elementary, but I thought dependency properties were the way to go for exposing properties of a UserControl.


text:
Q: Ho to fix playsound excpetion "playbin.set_state returned I am trying to make a simple metronome in Python using the playsound module. But when I run it, there's the following error:
Traceback (most recent call last):
  File "/run/media/mb/Volume/Dokumente/Coding/Python/Metronom/metronom.py", line 5, in <module>
    playsound("Cowbell.wav")
  File "/usr/lib/python3.7/site-packages/playsound.py", line 106, in _playsoundNix
    "playbin.set_state returned " + repr(set_result))
playsound.PlaysoundException: playbin.set_state returned <enum GST_STATE_CHANGE_FAILURE of type Gst.StateChangeReturn>

A: #if its in the same folder as project
playsound('file.mp3')
#somewhere else? then full path (REMEMBER PYTHON USES FORWARDSLASHES /, NOT BACKSLASHES \)
playsound('C:/your/path/to/file.mp3')

Also be aware that some files will throw a playsound exception if they have a high enough bitrate (idk why, i suppose playsound cant handle some high quality bitrates)


text:
Q: How to use Jquery contains? I am looking at the jquery site at the contains selector.
$("div:contains('John')").css("text-decoration", "underline");

How can I make this so it takes a non hard-coded value in? I tried to do something like this
$("div:contains(" + name + ")")

but that does not seem to work and is very messy. I am probably just missing some brace or something but is there a clean way that will work? Since even if I get this to work the next time I have to expand it will be the same problem again with have so many concatenations and stuff.

A: try it $("div:contains('" + name + "')")

A: You're missing the quotes around the parameter.
$('div:contains("' + name + '")').css( ... );

I try to always use single quotes for string delimiters, and double quotes for actual quotes in strings when writing JS. Either way works, but being consistent helps reading the strings =)


text:
Q: is it possible to add time stamp on recorded video: android i am doing video recording and save recording in my folder inside sdcard..now when i play video from sdcard i want to add date and time in video view , i am done with image means able
 to add time stamp in Image view using frame layout and Z-index but how would it to be done with video recording ..is it possible or not? if yes please suggest any way..
my code for adding time stamp in Image are given below with refrence URl..:
http://www.ilovefreesoftware.com/29/android-2/how-to-auto-capture-date-and-time-on-photos-taken-from-android.html
now how to do this same for video?
any help would be greatly apprciated here...
 Bitmap src = BitmapFactory.decodeResource(getResources(), R.drawable.splashmodified); // the original file is cuty.jpg i added in resources
  Bitmap dest = Bitmap.createBitmap(src.getWidth(), src.getHeight(), Bitmap.Config.ARGB_8888);

  SimpleDateFormat sdf = new SimpleDateFormat("yyyy-MM-dd HH:mm:ss");
  String dateTime = sdf.format(Calendar.getInstance().getTime()); // reading local time in the system

  Canvas cs = new Canvas(dest);
  Paint tPaint = new Paint();
  tPaint.setTextSize(35);
  tPaint.setColor(Color.BLUE);
  tPaint.setStyle(Style.FILL);
  cs.drawBitmap(src, 0f, 0f, null);
  float height = tPaint.measureText("yY");
  cs.drawText(dateTime, 20f, height+15f, tPaint);
  try {
      dest.compress(Bitmap.CompressFormat.JPEG, 100, new FileOutputStream(new File("/sdcard/timeStampedImage.jpg")));
  } catch (FileNotFoundException e) {
      // TODO Auto-generated catch block
      e.printStackTrace();
  }

}

A: If you're asking how to simply display something on top of your video, the answer is sure... just use a relative layout and put your TextView in the same coordinates as the SurfaceView you're using for your Camera preview... as long as it is after the SurfaceView in the XML it will draw on top of it.
Or if you insist on drawing your text to Canvas, put your drawing surface view on top of the Camera preview. Either way, as long as it's added to the parent view after the Cam surface it will draw on top of it.


text:
Q: Android SQLLite, Syntax error when trying to get data from single database column im using the following code inside my DBAdapter.java file to select the values from a single column
// Get make column from DB
public Cursor getMakeCol() {
    String selectCol = "SELECT KEY_MAKE FROM " + DATABASE_TABLE;
    Cursor c = db.query(DATABASE_TABLE, new String[]{KEY_MAKE}, selectCol, null,
            null,null,null,null);
    if (c != null) {
        c.moveToFirst();
    }
    return c;
}

this is how im trying to use getMakeCol from inside main.java
// Display make recordset from database inside textview
private void displayMake(Cursor cursor) {
    String message = "";
    // populate the message from the cursor

    // Reset cursor to start, checking to see if there's data:
    if (cursor.moveToFirst()) {
        do {
            String make = cursor.getString(DBAdapter.COL_MAKE);
            // Append data to the message:
            message += "Make: " + make + "\n";
        } while(cursor.moveToNext());
}
    // Close the cursor to avoid a resource leak.
    cursor.close();
    displayText(message);
}

this is activated by an onClick event and then displayed inside a textview
// display column data
public void btnGetColClick(View v) {
    Cursor cursor = myDb.getMakeCol();
    displayMake(cursor);
}

however when im debugging the application and i activate the onClick event logcat displays the following
07-25 16:11:58.300: E/SQLiteLog(1738): (1) near "SELECT": syntax error

Are there any errors in the above code, can someone please explain why its not doing what i need.
Thank you

A: you are using db.query in wrong way
Cursor cursor = db.query(DATABASE_TABLE, new String[]{KEY_MAKE}, null, null, null);

should be equal to SELECT KEY_MAKE FROM DATABASE_TABLE
if you want to filter the table, use the third parameter for the where clause
String whereClause = "id=? AND group_id=?";
String[] args = new String[]{"1", "2"}; //some example data
Cursor cursor = db.query(DATABASE_TABLE, new String[]{KEY_MAKE}, whereClause, args, null);


text:
Q: Not able to split the div for rows and columns
creating this application in MVC5 with bootstrap....
I have added div :

                @Html.Label("Ext :")

                @Html.TextBox("txt_Ext", null, new { @class = "form-control" })

CSS :
  .wireframe_div {
    border: 1px solid black;
    background-color: darkgrey;
     padding: 15px 20px 25px 20px;
.Cell
    {
        display: table-cell;
        padding-left: 5px;
        padding-right: 5px;

    }
.Row
    {
        display: table-row;
    }
  .divFullWidth {
       float: left;
      width: 100%;

}

But am not able split the div exactly like in screen shot.
Can any one help on this. Am very new to web tech.

A:

        Ext <input type="text" style="width: 35%;"/>
        Area <input type="text"  style="width: 10%;"/>

        Activity Catagory <input type="text" style="width: 80%;"/>

                Activity Date To<input type="text" style="width: 80%;"/>

            Activity Date From <input type="text" style="width: 80%;"/>

also try bootstrap it makes life easy


text:
Q: Why should I call os.Exit at most once in the main function? I started a new job and we've been instructed to use Ubers Go coding standards. I'm not sure about one of their guidelines entitled "Exit Once":

If possible, prefer to call os.Exit or log.Fatal at most once in your main(). If there are multiple error scenarios that halt program execution, put that logic under a separate function and return errors from it.

Wouldn't this just mean offloading main() into another function (run())? This seems a little superfluous to me. What benefits does Uber's approach have?

A: I'm not familiar with Uber's entire Go coding standards, but that particular piece of advice is sound. One issue with os.Exit is that it puts an end to the programme very brutally, without honouring any deferred function calls pending:

Exit causes the current program to exit with the given status code. Conventionally, code zero indicates success, non-zero an error.
The program terminates immediately; deferred functions are not run.

(my emphasis)
However, those deferred function calls may be responsible for important cleanup tasks. Consider Uber's example code snippet:
package main

func main() {
  args := os.Args[1:]
  if len(args) != 1 {
    log.Fatal("missing file")
  }
  name := args[0]

  f, err := os.Open(name)
  if err != nil {
    log.Fatal(err)
  }
  defer f.Close()

  // If we call log.Fatal after this line,
  // f.Close will not be called.

  b, err := ioutil.ReadAll(f)
  if err != nil {
    log.Fatal(err)
  }

  // ...
}

If ioutil.ReadAll returns a non-nil error, log.Fatal is called; and because log.Fatal calls os.Exit under the hood, the deferred call to f.Close will not be run. In this particular case, it's not that serious, but imagine a situation where deferred calls involved some cleanup, like removing files; you'd leave your disk in an unclean state. For more on that topic, see episode #112 of the Go Time podcast, in which these considerations were discussed.
Therefore, it's a good idea to eschew os.Exit, log.Fatal, etc. "deep" in your programme. A run function as described in Uber's Go coding standards allows deferred calls to be run as they should before programme execution ends (potentially with a non-zero status code):
package main

func main() {
  if err := run(); err != nil {
    log.Fatal(err)
  }
}

func run() error {
  args := os.Args[1:]
  if len(args) != 1 {
    return errors.New("missing file")
  }
  name := args[0]

  f, err := os.Open(name)
  if err != nil {
    return err
  }
  defer f.Close()

  b, err := ioutil.ReadAll(f)
  if err != nil {
    return err
  }

  // ...
}

An additional benefit of this approach is that, although the main function itself isn't readily testable, you can design such a run function with testability in mind; see Mat Ryer's blog post on that topic.


text:
Q: How does Ghostscript handle vector objects that have no color I have CMYK vector logo PDF files that need to be converted into EPS files on the fly using Ghostscript on Linux. They all have a colorless vector outline around the page area to mark the safety zone (empty space necessary around the logo) which most graphic programs maintain when the file is opened or placed on a page document. Unfortunately Ghostscript does not seem to convert these outlines in the EPS conversion but drops them out.
Is there any way to get these outlines (or any colorless vector objects for that matter) to carry over into the converted EPS file and still keep them colorless? Maybe using something else than Ghostscript?
Follow up question: is there any way of also maintaining the boundingbox and page size in the conversion as well?
E.g. Adobe Illustrator or other graphic programs do not have these problems when saving EPS files.

A: Without seeing an example, there's no possible way to help. There is no such thing as a 'colourless' vector outline in PDF. You can describe a path, but that path must then either be stroked, filled or used as a clip, if it makes marks then its not 'colourless'. (Actually that's not quite true, you can use a /Separation colour with the specific ink name of /None, but that does seem rather pointless)
The MediaBox will be converted into a /PageSize setpagedevice when converted to a PostScript program. Note that EPS programs are not permitted to emit a PageSize request, so no, you cannot preserve the MediaBox from a PDF file into an EPS program.
Since the BoundingBox is derived from the marks on the media, and PDF files don't have a BoundingBox (elements of PDF files do have BoundingBox entries, but the PDF file or individual pages, don't). So no, you cannot preserve what isn't there to begin with.
The BoundingBox is defined as the smallest area which encloses all the marks on the media. If you want the BoundingBox to be larger than that (your so-called 'safety zone' then you need to leave space around the EPS when you place it in the document. Frankly anything else is just wrong.
It 'sounds like' you are expecting that some white space in the PDF file will be converted to white space in the EPS (there is no 'colourless vector outline', its just unmarked area). From the EPS specification:

For an EPS file, the bounding box is the smallest rectangle that
  encloses all the marks painted on the single page of the EPS file.

If you post a (simple) example file somewhere then I can look at it, but it seems you have answered your own question anyway:
"Is there any way to get these outlines (or any colorless vector objects for that matter) to carry over into the converted EPS file and still keep them colorless? Maybe using something else than Ghostscript?"
...
...
"E.g. Adobe Illustrator or other graphic programs do not have these problems when saving EPS files."
So, yes, you can use one of these other programs.


text:
Q: CS50 pset4 filter blur function I wrote a code for the blur function, but it returns a wrong output for reason which is not known for me (it just looks fine for me), here is an example (always same):
:( blur correctly filters middle pixel
    expected "127 140 149\n", not "126 140 149\n"
:) blur correctly filters pixel on edge
:) blur correctly filters pixel in corner
:( blur correctly filters 3x3 image
    expected "70 85 95\n80 9...", not "70 85 95\n80 9..."
:( blur correctly filters 4x4 image
    expected "70 85 95\n80 9...", not "70 85 95\n80 9..."

and the code is here:
void blur(int height, int width, RGBTRIPLE image[height][width])
{
    RGBTRIPLE original[height][width];
    for (int i = 0; i < height; i++)
    {
        for (int j = 0; j < width; j++)
        {
            original[i][j] = image[i][j];
        }
    }
    for (int i = 0; i < height; i++)
    {
        for (int j = 0; j < width; j++)
        {
            if (i == 0)
            {
                if (j == 0)
                {
                    image[i][j].rgbtRed = round((original[i][j].rgbtRed + original[i + 1][j].rgbtRed + original[i][j + 1].rgbtRed + original[i + 1][j + 1].rgbtRed) / 4);
                    image[i][j].rgbtGreen = round((original[i][j].rgbtGreen + original[i + 1][j].rgbtGreen + original[i][j + 1].rgbtGreen + original[i + 1][j + 1].rgbtGreen) / 4);
                    image[i][j].rgbtBlue = round((original[i][j].rgbtBlue + original[i + 1][j].rgbtBlue + original[i][j + 1].rgbtBlue + original[i + 1][j + 1].rgbtBlue) / 4);
                }
                else if (j == width - 1)
                {
                    image[i][j].rgbtRed = round((original[i][j].rgbtRed + original[i + 1][j].rgbtRed + original[i][j - 1].rgbtRed + original[i + 1][j - 1].rgbtRed) / 4);
                    image[i][j].rgbtGreen = round((original[i][j].rgbtGreen + original[i + 1][j].rgbtGreen + original[i][j - 1].rgbtGreen + original[i + 1][j - 1].rgbtGreen) / 4);
                    image[i][j].rgbtBlue = round((original[i][j].rgbtBlue + original[i + 1][j].rgbtBlue + original[i][j - 1].rgbtBlue + original[i + 1][j - 1].rgbtBlue) / 4);
                }
                else
                {
                    image[i][j].rgbtRed = round((original[i][j].rgbtRed + original[i + 1][j].rgbtRed + original[i][j - 1].rgbtRed + original[i + 1][j - 1].rgbtRed + original[i][j + 1].rgbtRed + original[i + 1][j + 1].rgbtRed) / 6);
                    image[i][j].rgbtGreen = round((original[i][j].rgbtGreen + original[i + 1][j].rgbtGreen + original[i][j - 1].rgbtGreen + original[i + 1][j - 1].rgbtGreen + original[i][j + 1].rgbtGreen + original[i + 1][j + 1].rgbtGreen) / 6);
                    image[i][j].rgbtBlue = round((original[i][j].rgbtBlue + original[i + 1][j].rgbtBlue + original[i][j - 1].rgbtBlue + original[i + 1][j - 1].rgbtBlue + original[i][j + 1].rgbtBlue + original[i + 1][j + 1].rgbtBlue) / 6);
                }
            }
            else if (i > 0 && i < height - 1)
            {
                if (j == 0)
                {
                    image[i][j].rgbtRed = round((original[i][j].rgbtRed + original[i + 1][j].rgbtRed + original[i - 1][j].rgbtRed + original[i + 1][j + 1].rgbtRed + original[i][j + 1].rgbtRed + original[i - 1][j + 1].rgbtRed) / 6);
                    image[i][j].rgbtGreen = round((original[i][j].rgbtGreen + original[i + 1][j].rgbtGreen + original[i- 1][j].rgbtGreen + original[i + 1][j + 1].rgbtGreen + original[i][j + 1].rgbtGreen + original[i - 1][j + 1].rgbtGreen) / 6);
                    image[i][j].rgbtBlue = round((original[i][j].rgbtBlue + original[i + 1][j].rgbtBlue + original[i - 1][j].rgbtBlue + original[i + 1][j + 1].rgbtBlue + original[i][j + 1].rgbtBlue + original[i - 1][j + 1].rgbtBlue) / 6);
                }
                else if (j == width - 1)
                {
                    image[i][j].rgbtRed = round((original[i][j].rgbtRed + original[i + 1][j].rgbtRed + original[i - 1][j].rgbtRed + original[i + 1][j - 1].rgbtRed + original[i][j - 1].rgbtRed + original[i - 1][j - 1].rgbtRed) / 6);
                    image[i][j].rgbtGreen = round((original[i][j].rgbtGreen + original[i + 1][j].rgbtGreen + original[i- 1][j].rgbtGreen + original[i + 1][j - 1].rgbtGreen + original[i][j - 1].rgbtGreen + original[i - 1][j - 1].rgbtGreen) / 6);
                    image[i][j].rgbtBlue = round((original[i][j].rgbtBlue + original[i + 1][j].rgbtBlue + original[i - 1][j].rgbtBlue + original[i + 1][j - 1].rgbtBlue + original[i][j - 1].rgbtBlue + original[i - 1][j - 1].rgbtBlue) / 6);
                }
                else
                {
                    image[i][j].rgbtRed = round((original[i][j].rgbtRed + original[i][j - 1].rgbtRed + original[i][j + 1].rgbtRed + original[i + 1][j - 1].rgbtRed + original[i + 1][j + 1].rgbtRed + original[i + 1][j].rgbtRed + original[i - 1][j - 1].rgbtRed + original[i - 1][j + 1].rgbtRed + original[i - 1][j].rgbtRed) / 9);
                    image[i][j].rgbtGreen = round((original[i][j].rgbtGreen + original[i][j - 1].rgbtGreen + original[i][j + 1].rgbtGreen + original[i + 1][j - 1].rgbtGreen + original[i + 1][j + 1].rgbtGreen+ original[i + 1][j].rgbtGreen + original[i - 1][j - 1].rgbtGreen + original[i - 1][j + 1].rgbtGreen + original[i - 1][j].rgbtGreen) / 9);
                    image[i][j].rgbtBlue = round((original[i][j].rgbtBlue + original[i][j - 1].rgbtBlue + original[i][j + 1].rgbtBlue + original[i + 1][j - 1].rgbtBlue + original[i + 1][j + 1].rgbtBlue + original[i + 1][j].rgbtBlue + original[i - 1][j - 1].rgbtBlue + original[i - 1][j + 1].rgbtBlue + original[i - 1][j].rgbtBlue) / 9);
                }
            }
            else if (i == height - 1)
            {
                if (j == 0)
                {
                    image[i][j].rgbtRed = round((original[i][j].rgbtRed + original[i - 1][j].rgbtRed + original[i][j + 1].rgbtRed + original[i - 1][j + 1].rgbtRed) / 4);
                    image[i][j].rgbtGreen = round((original[i][j].rgbtGreen + original[i - 1][j].rgbtGreen + original[i][j + 1].rgbtGreen + original[i - 1][j + 1].rgbtGreen) / 4);
                    image[i][j].rgbtBlue = round((original[i][j].rgbtBlue + original[i - 1][j].rgbtBlue + original[i][j + 1].rgbtBlue + original[i - 1][j + 1].rgbtBlue) / 4);
                }
                else if (j == width - 1)
                {
                    image[i][j].rgbtRed = round((original[i][j].rgbtRed + original[i - 1][j].rgbtRed + original[i][j - 1].rgbtRed + original[i - 1][j - 1].rgbtRed) / 4);
                    image[i][j].rgbtGreen = round((original[i][j].rgbtGreen + original[i - 1][j].rgbtGreen + original[i][j - 1].rgbtGreen + original[i - 1][j - 1].rgbtGreen) / 4);
                    image[i][j].rgbtBlue = round((original[i][j].rgbtBlue + original[i - 1][j].rgbtBlue + original[i][j - 1].rgbtBlue + original[i - 1][j - 1].rgbtBlue) / 4);
                }
                else
                {
                    image[i][j].rgbtRed = round((original[i][j].rgbtRed + original[i - 1][j].rgbtRed + original[i][j - 1].rgbtRed + original[i - 1][j - 1].rgbtRed + original[i][j + 1].rgbtRed + original[i - 1][j + 1].rgbtRed) / 6);
                    image[i][j].rgbtGreen = round((original[i][j].rgbtGreen + original[i - 1][j].rgbtGreen + original[i][j - 1].rgbtGreen + original[i - 1][j - 1].rgbtGreen + original[i][j + 1].rgbtGreen + original[i - 1][j + 1].rgbtGreen) / 6);
                    image[i][j].rgbtBlue = round((original[i][j].rgbtBlue + original[i - 1][j].rgbtBlue + original[i][j - 1].rgbtBlue + original[i - 1][j - 1].rgbtBlue + original[i][j + 1].rgbtBlue + original[i - 1][j + 1].rgbtBlue) / 6);
                }
            }
        }
    }
}

A: if the members of the structure RGBTRIPLE has integer types, integer division happens in the lines like
image[i][j].rgbtRed = round((original[i][j].rgbtRed + original[i + 1][j].rgbtRed + original[i][j + 1].rgbtRed + original[i + 1][j + 1].rgbtRed) / 4);

and the results are truncated to integers before passed to the round() function.
The dividers should be floating-point numbers like 4.0 instead of integers like 4.
If the judge still rejects your answer after applying this change, it should be due to the calculation errors in floating-point numbers. In this case, you should avoid using floating-point number calculation and think how to calculate the desired values using only calculation in integers.

A: My solution is much short I guess
void blur(int height, int width, RGBTRIPLE image[height][width])
{
//Iterates through all the pixels

for(int i = 0; i < height; i++)
{
    for(int j = 0; j < width; j++)
    {

        //Stores average of all the pixels around the certain color

        int avgrgb[3] = {0,0,0}, n = 0;

        // Matrix "a" and "b" represent the nine pixels address around the pixel of address i and j

        int a[3][3] = { {i-1, i-1, i-1}, {i, i, i}, {i+1, i+1,i+1} }, b[3][3] = { {j-1, j, j+1}, {j-1, j, j+1}, {j-1, j, j+1} };

        //Iterating through the pixels around the middle pixel

        for(int x = 0; x < 3; x++)
        {
            for(int y = 0; y < 3; y++)
            {

                // Checking if the index contains any negative integer(negative integer represents a pixel outside the image for corner or edge pixel)

                if (a[x][y] >= 0 && a[x][y] >= 0)
                {

                    // Calculates the sum of the valid pixel colours

                    avgrgb[0] += image[a[x][y]][b[x][y]].rgbtRed;
                    avgrgb[1] += image[a[x][y]][b[x][y]].rgbtGreen;
                    avgrgb[2] += image[a[x][y]][b[x][y]].rgbtBlue;
                    n++;
                }
            }
        }

        // Calculates the actual average

        avgrgb[0] /= n;
        avgrgb[1] /= n;
        avgrgb[2] /= n;

        // Assigning new pixel values

        image[i][j].rgbtRed = avgrgb[0];
        image[i][j].rgbtGreen = avgrgb[1];
        image[i][j].rgbtBlue = avgrgb[2];
    }
}
return;
}

A: MikeCAT's answer is surely right. Just as an alternative to his suggestion, you could avoid the conversions to and from floating point by adding half the divisor before the integer division, e. g.
image[i][j].rgbtRed = (original[i][j].rgbtRed + … + original[i+1][j+1].rgbtRed + 2) / 4;
…
image[i][j].rgbtRed = (original[i][j].rgbtRed + … + original[i-1][j  ].rgbtRed + 4) / 9;


text:
Q: Identical checkboxes bound together with jQuery don't sync I have a dynamically generated form with groups of checkboxes representing categories of companies. These eventually get plotted on a dynamic chart (not shown here). Each group of companies has a toggle button to turn all the checkboxes on or off in each category.
Some companies are in multiple categories. For example, Apple is in both the Tech Giants and Handset Manufacturers category. So I bind identical checkboxes together such that if Apple is checked/unchecked in one category, it will automatically change in any other category it's in. This works well when clicking individual checkboxes, such as Apple's.
However, the checkbox binding doesn't work when a toggle button is clicked that checks or unchecks entire categories of companies.
Here is a full working example of the code: https://jsfiddle.net/105q7d94/1/
Click Apple's checkbox in this Fiddle and you'll see it sync in both categories it's in. But when clicking either toggle button, Apple doesn't sync in the other category.
Any idea how to fix this?

<button class="button-text" id="customize-button">Open User Settings</button>

A:     // Arm the toggle buttons
$(document).ready(function() {
  $(document).on("click", ".category", function() {
    var buttonData = $(this).data();
    $(this).closest("div").find('input[type=checkbox]').prop('checked', !buttonData.checked).change(); //I made change here
    buttonData.checked = !buttonData.checked;
  });
});

// Bind identical checkboxes
// This works on individual checkboxes but not when clicking the toggle button
$(document).ready(function(){
  $('input:checkbox').on('change', function(){
    $('input[value="' + this.value + '"]:checkbox').prop('checked', this.checked);
    //refresh(); //I made change here
  });
});

There is refresh() function called which is not define so remove it,
and for triggering event just put change() function after trigger toggle.
Please check comment "I made change here"


text:
Q: Android Groupie - context menu on long press Using Groupie, along with view bindings, I can't figure out how to open a context menu when long pressing a Item.
I have a couple of overrides in the fragment which has the GroupieAdapter:
override fun onCreateContextMenu(
    menu: ContextMenu,
    v: View,
    menuInfo: ContextMenu.ContextMenuInfo?
) {
    super.onCreateContextMenu(menu, v, menuInfo)
    menu.setHeaderTitle("Pick option")
    requireActivity().menuInflater.inflate(R.menu.save_game_item_context_menu, menu)
}

override fun onContextItemSelected(item: MenuItem): Boolean {
    Timber.d("Context menu clicked: ", item.itemId)

    return super.onContextItemSelected(item)
}

and a OnItemLongClickListener
private val onLongItemClickListener = OnItemLongClickListener { item, view ->
    if (item is SaveGameItem) {
        registerForContextMenu(view)
        Timber.d("Registered for context menu")
    }

    return@OnItemLongClickListener true
}

However I'm not sure how I actually "open" the menu? When long pressing the I can see the log but no menu opens.
I've seen a few examples where the user isn't using Groupie but I wasn't able to peace that all together.
New to android so unsure where I've gone wrong here?
Edit:
Well, looks like I was way off. The trick looks to be to extend from View.OnCreateContextMenuListener in the Groupie Item, and register the context listener on each item.
Something a little like:
class SaveGameItem(
    private val saveGame: SaveGame
) :
    BindableItem<ItemSaveGameBinding>(), View.OnCreateContextMenuListener {

    //...

    override fun initializeViewBinding(view: View): ItemSaveGameBinding {
        view.setOnCreateContextMenuListener(this)

        return ItemSaveGameBinding.bind(view)
    }

    override fun onCreateContextMenu(
        menu: ContextMenu?,
        v: View?,
        menuInfo: ContextMenu.ContextMenuInfo?
    ) {
        menu?.add(0, v?.id ?: 0, 0, "Delete")
        menu?.add(0, v?.id ?: 0, 0, "Upload")
        menu?.add(0, v?.id ?: 0, 0, "Restore")
    }
}

The problem now is back in the fragment that makes use of all this, the onContextItemSelected is getting just the string title of the menu item selected, and not the ID or anything more useful
override fun onContextItemSelected(item: MenuItem): Boolean {
    Timber.d("Context menu clicked: ", item.toString())

    return super.onContextItemSelected(item)
}

Am I on the right track here or still way off?


text:
Q: Fluent Validation - How to ensure that a collection Count greater than zero when not null, but can be null I'm struggling to figure out how to define a rule that allows a collection property to be null, but not empty. Providing null for the collection property being a valid use case, but when the collection is provided, the collection needs to have at least one entry. Hence:
// Valid
{
    "codes": null
}

// Invalid
{
    "codes": []
}

// Valid
{
    "codes": ["Pass"]
}

I've been playing around and can't seem to find anything that works:
public class UpdateCodesRequest
{
    public IEnumerable<string> Codes { get; set; }
}

public class UpdateCodesRequestValidator : AbstractValidator<UpdateCodesRequest>
{
    public UpdateCodesRequestValidator()
    {
        // none of these will work if Codes is null
        RuleFor(x => x.Codes.Count()).GreaterThan(0).When(x => x != null);
        RuleFor(x => x.Codes).Must(x => x.Any()).When(x => x != null);
        RuleFor(x => x.Codes).Must(x => x != null && x.Any()).When(x => x != null);
    }
}

A: How about this one?
RuleFor(x => x.Codes).Must(x => x == null || x.Any());


text:
Q: CRM Fetchxml returns with missing attributes for blank rows I am using fetchxml query to get results from CRM dynamics however if my fetchxml is having 6 attributes and query this I get  less than 6 attributes, reason for this, if the row is having blank/null value then it does not return attribute name, I need the attribute names since I have written the code to get the attribute names and dynamically get data from attribute names.
Hers is my code.
Let says my fetchxml contains a string like this(Note: I 'm getting the string dynamically from view name, just showing the string)
string fetchxml= @"<fetch version='1.0' output-format='xml-platform' mapping='logical' distinct='false'>
  <entity name='cdi_postedsurvey'>
    <attribute name='cdi_postedsurveyid' />
    <attribute name='cdi_name' />
    <attribute name='createdon' />
    <order attribute='cdi_name' descending='false' />
    <filter type='and'>
      <condition attribute='statecode' operator='in'>
        <value>1</value>
        <value>0</value>
      </condition>
      <condition attribute='cdi_postedsurveyid' operator='not-null' />
      <condition attribute='createdon' operator='on-or-after' value='2016-09-09' />
      <condition attribute='createdon' operator='on-or-before' value='2016-09-13' />
    </filter>
  </entity>
</fetch>";

EntityCollection _viewResult = _orgService.RetrieveMultiple(new FetchExpression(_fetchxml));

 foreach (var e in _viewResult .Entities)   **//Here the entity return less attributes because the row is blank**
                        {
                            if (_keycnt == 0)
                            {
                                foreach (var keys in e.Attributes.Keys)
                                {
                                    _csvData.AppendFormat(keys + ",");  //Get all the Attribute names in comma separted format.
                                }
                                _splitIntoColumn = _csvData.ToString().TrimEnd().Split(',');
                            }
                            _keycnt = 1;
                            _csvData.Remove(_csvData.ToString().LastIndexOf(","), 1);           //Removes comma from the end of the string
                            _csvData.AppendLine();                                              //Enters new line
                            for (int j = 0; j < _splitIntoColumn.Length - 1; j++)
                            {
                                string _attributeName = _splitIntoColumn[j].ToString();
                          //Now get the values based on attribute name
                                if (e.FormattedValues.Contains(_attributeName))
                                {
                                    //append data in csv file
                                }

This is what I 'm getting in my CSV file wherein I have 4 attributes, but I 'm getting 3 because the first row is blank.
cdi_postedsurveyid  createdon   logicalname
A                   14-09-2011       sample
B                   14-09-2011       sample

This is what I want wherein cdi_name is included even if the first row is null
cdi_name  cdi_postedsurveyid    createdon   logicalname
             A                  14-09-2011       sample
test data    B                  14-09-2011       sample
test data    B                  14-09-2011       sample

Note: Just for your information(not using this library) here the powershell library is fixed for Microsoft.Xrm.Data.PowerShell https://github.com/seanmcne/Microsoft.Xrm.Data.PowerShell/releases
Have a workaround in the form of powershell, please help to convert in C#
 $atts = $xml.GetElementsByTagName('attribute');
                    foreach($att in $atts)
                    {
                        if($att.ParentNode.HasAttribute('alias'))
                        {
                            $attName = $att.ParentNode.GetAttribute('alias') + "." + $att.name
                             Write-Output $att.ParentNode.GetAttribute('alias') + "." + $att.name
                        }
                        else
                        {
                            $attName = $att.name
                             Write-Output $att.name
                        }
                        Add-Member -InputObject $psobj -MemberType NoteProperty -Name $attName -Value $null
                        Add-Member -InputObject $psobj -MemberType NoteProperty -Name ($attName + "_Property") -Value $null
                    }


text:
Q: Tracking HTML5 Video Closed Captions Visibility State I am attempting to determine if the TextTrack element of a html video is currently showing or hidden.
I took a look at the html specifications and at first glance, the texttracks.mode property would work perfectly according to: http://www.whatwg.org/specs/web-apps/current-work/multipage/the-video-element.html#text-track-hidden
I tested this property with the following html and code in google chrome version 35.0.1916.153:
HTML:
<video>
    <track id="en" kind="subtitles" src="transcript.vtt"></track>
    <source src = "samplevideo.mp4">
</video>

Code:
$(video)[0].textTracks[0].mode

Initially the code returns a "hidden", as expected, and upon clicking the transcript button on the video player and rerunning the code, it returns "showing".
If I toggle the player off after these steps and rerun the code, it still returns "showing" despite the transcripts being hidden on the video.
Is there a better way to detect the visible / non-visible state of transcripts on an html5 video player?

A: <video id="video" controls preload="metadata">
<source src="video/sintel-short.mp4" type="video/mp4">
<source src="video/sintel-short.webm" type="video/webm">
<track label="English" kind="captions" srclang="en" src="captions/vtt/sintel-en.vtt" default>
<track label="Deutsch" kind="captions" srclang="de" src="captions/vtt/sintel-de.vtt">
<track label="Español" kind="captions" srclang="es" src="captions/vtt/sintel-es.vtt">
</video>


text:
Q: jQuery Validation - Highlighting Radio Labels I'm trying to use jQuery validation to highlight the labels for my radio buttons only, and not the labels for my other inputs.  I have a label for my radio button set called 'type'.  I can't seem to get it to work!
$(document).ready(function(){
    $("#healthForm").validate({

 highlight: function(element, errorClass) {
     $(element).addClass(errorClass)
     $(element.form).find("label[for='type']")
                    .addClass("radioerror");
  },
  unhighlight: function(element, errorClass) {
     $(element).removeClass(errorClass)
     $(element.form).find("label[for='type']")
                    .removeClass("radioerror");
  },
    errorPlacement: function(error, element) {
        }
    });
  });

A: I'm not really familiar with jQuery's validation plugin, but this one doesn't seem right:
$(element.form).find("label[for='type']")

Firstly, I think $(element.form) should be $(element).closest('form')? I could be wrong :P
Secondly, .find("label[for='type']") has got nothing to do with the "element" as any other elements in the same form will fetch the same label.
If the label is the sibling of the radio button, you might want to use sibling() directly.

A: I changed your code to the following and then it works!
$(document).ready(function() {
    $("#healthForm").validate({
        highlight: function(element, errorClass) {

            if(element.type == 'radio') {
                $(element.form).find('[name="' + element.name + '"]').each(function(){
                    var $this = $(this);
                    $this.closest('label[for="' + $this.attr('id') + '"]').addClass(errorClass);
                });
            }

        },
        unhighlight: function(element, errorClass) {

            if(element.type == 'radio') {
                $(element.form).find('[name="' + element.name + '"]').each(function(){
                    var $this = $(this);
                    $this.closest('label[for="' + $this.attr('id') + '"]').removeClass(errorClass);
                });
            }

        },
        errorPlacement: function(error, element) {
        }
    });
});


text:
Q: Get the index of an element in an array of hashes with the maximum value for a particular attribute I have an array of hashes, each hash is like: {title: xxx, author: yyy, updated_at: zzz}
In an ERB template, I need to get the array key of the hash that as the biggest updated_at value.
I already found about max_by in Finding the element of a Ruby array with the maximum value for a particular attribute and did:
<% selected = my_array.max_by { |element| element.updated_at } %>

But what I need here is to get not the hash element itself, but its index in the array. How would I do that?

A: You want then
<% selected = my_array.each_index.max_by { |i| my_array[i].updated_at } %>

A: have a try:
array.index(array.max_by { |i| i["updated_at"] })


text:
Q: Commands not accepted by instrument over RS232 w/ ruby serialport script MY ENVIRONMENT
I'm sending commands to a camera simulator device made by Vivid Engineering (Model CLS-211) over RS-232 from my laptop which is running CentOS 7.
ISSUE
I have installed two different serial monitors (minicom, gtkterm) and can successfully send successive commands over and over to the device. I can send a command to dump the memory contents as well. There are several configuration commands I have to send to the CLS-211 to set it up per a specific test. I want to automate this process and have written a ruby script to write a list of commands to the CLS-211 to make this process easier. However, it appears that I am not terminating each command correctly or the CLS-211 requires a specific terminator/signal that I am not giving to it in my ruby script. I'm confused why I can successfully accomplish this task with a serial monitor but not a ruby script. I've configured the serial port settings correctly per their manual so I know this is not the issue. You'll see those settings below defined in my scirpts. Their manual points out they use HyperTerminal which I can't use because I'm on a Linux system. Manufacture mentioned that other serial terminals should work just fine but they have only chosen to test one out being HyperTerminal. I've asked for their feedback on the issue and they simply say "We don't use Linux but it shouldn't be much different, good luck".
TROUBLESHOOTING
I have verified that my "send.rb" script is working to the best of my knowledge by writing a "read.rb" script to read back what I sent. I essentially connected pin 2 "rx" to pin 3 "tx" on the RS-232 cable for a loopback test. Below is my two scripts and the resulting output from running this test.
## Filename send.rb

require 'serialport'
ser = SerialPort.new("/dev/ttyS0", 9600, 8, 1, SerialPort::NONE)
ser.write "LVAL_LO 5\r\n"
ser.write "LVAL_HI 6\r\n"
ser.write "FVAL_LO 7\r\n"
ser.write "FVAL_HI 8\r\n"
ser.close

## Filename read.rb

require 'serialport'
ser = SerialPort.new("/dev/ttyS0", 9600, 8, 1, SerialPort::NONE)
while true do
  printf("%c", ser.getc)
end
ser.close

Just found out that I cannot post more than 2 links since my reputation is so low. Anyways the output is just the following...
username@hostname $ ruby read.rb
LVAL_LO 5
LVAL_HI 6
FVAL_LO 7
FVAL_HI 8

I have hooked up the CLS-211 and dumped the memory contents by issuing the DUMP command using GtkTerm and this works fine. The following image shows the memory contents of the first four parameters being LVAL_LO, LVAL_HI, FVAL_LO, and FVAL_HI. I'm just choosing to show four values in the memory dump for the sake of keeping this thread short versus listing all of them. Since I cannot include more than 2 links because my reputation is low being a new guy I'm typing what the output looks like in GtkTerm instead...
CLS-211 initializing, please wait
............
ready

CLS211 Camera Link Simulator CLI
Vivid Engineering
Rev 3.0

DUMP
LVAL_LO    = 0x0020    / 32
LVAL_HI    = 0x0100    / 256
FVAL_LO    = 0x0002    / 2
FVAL_HI    = 0x0100    / 256

In the above image you can clearly see that the system boots as expected. After I typed in the command "DUMP" it printed out the memory contents successfully. You see that LVAL_LO = 32, LVAL_HI = 256, FVAL_LO = 2, and FVAL_HI = 256. As I mentioned before I can successfully type in a command to GtkTerm to change a specific parameter as well. The below images shows that after typing in the command LVAL_LO 5 to GtkTerm and then issuing a DUMP command the value 5 was read correctly and LVAL_LO was changed as expected. I can replicate this successful behavior with every command using GtkTerm.
Again, I can't post more than 2 links so I'm writing the output below...
LVAL_LO 5
DUMP
LVAL_LO    = 0x0005    / 5
LVAL_HI    = 0x0100    / 256
FVAL_LO    = 0x0002    / 2
FVAL_HI    = 0x0100    / 256

At this point I was like ok everything is working as expected. Lets see if I can execute my ruby script and replicate the same successfully. I then ran the script I typed up above titled "send.rb". Then I opened up GtkTerm and issued a DUMP command afterwards to see if those values were taken. Let it be known that before I ran "send.rb" the values that existed in memory on the CLS-211 were LVAL_LO = 32, LVAL_HI = 256, FVAL_LO = 2, and FVAL_HI = 256. You can see that after running "send.rb", opening GtkTerm back up and issuing the DUMP command the CLS-211 replied w/ "invalid entry". After issuing it again you'll see that it dumped the contents of memory and showed LVAL_LO was changed correctly but the other three values were not.
Almost Successful
At this point I assumed that the first value was being received and written to the memory contents of the CLS-211 correctly but the other commands were not being received correctly. I assumed this was most likely because of the lack of any delay. Therefore, I placed a 1 second delay between each ser.write command. I changed the script "send.rb" to the following.
## Filename send.rb

require 'serialport'
ser = SerialPort.new("/dev/ttyS0", 9600, 8, 1, SerialPort::NONE)
ser.write "LVAL_LO 9\r\n"
sleep(1)
ser.write "LVAL_HI 10\r\n"
sleep(1)
ser.write "FVAL_LO 11\r\n"
sleep(1)
ser.write "FVAL_HI 12\r\n"
sleep(1)
ser.close

The following is the result of running "send.rb" again with the above changes, opening up GtkTerm, and executing the DUMP command to verify memory.
Added sleep(1)
Nothing really changed. I was able to tell that the script took longer to execute and the first value did change but like before the last three values I sent did not get received and saved to memory on the CLS-211.
CONCLUSION
How can I continue troubleshooting this issue? What sort of terminations are happening to each command that I send through GtkTerm and is that different from what I have sent in my ruby script "send.rb" being "...\r\n". Totally lost and out of options on what I can do next.
[EDIT/UPDATE 10/09/17]
I'm so stupid. The one termination character I forgot to try out "by itself" was carriage return "\r". Using a carriage return by itself after each command fixed the issue. I'm curious what requirements drive a manufacturer to define how a serial packet should be constructed in terms of a termination character(s). I would think there would be a predefined standard to what termination character(s) should be used. For completeness I have included my code below to what it should be in the case of communicating correctly with the CLS-211 device. Basically, i took out the '\n' and kept the '\r' that was it.
## Filename send.rb

require 'serialport'
ser = SerialPort.new("/dev/ttyS0", 9600, 8, 1, SerialPort::NONE)
ser.write "LVAL_LO 9\r"
sleep(1)
ser.write "LVAL_HI 10\r"
sleep(1)
ser.write "FVAL_LO 11\r"
sleep(1)
ser.write "FVAL_HI 12\r"
sleep(1)
ser.close


text:
Q: Polar molecule in external electric field - problem with the Fourier transform I have a problem  where I am considering a polar molecule with dipole vector $\vec{p}$ moving in a plane and exposed to an electric field, so that the interaction potential is:
\begin{equation}\tag{1}
V_{e x t}=-\boldsymbol{E}(t) \cdot \boldsymbol{p}=-E(t) p \cos \theta
\end{equation}
The electric field is small so that the probability distribution of the angle between the dipole vector and the electric field can be seen as:
$$\tag{2}
P(\theta, t)=P_{0}+\tilde{P}(\theta, t)=\frac{1}{2 \pi}+\tilde{P}(\theta, t)
$$
I want to find an expression for this probability. I made a separation of variables $\tilde{P}(\theta, t)=\cos \theta g(t)$ and obtained the following differential equation from the Fokker-Planck equation:
$$\tag{3}
\frac{d g}{d t}+D_{r} g=\varepsilon_{0} e^{i\omega t}
$$
Where $\varepsilon_0$ and $D_r$ are constants and I assume an oscillating field, $E=E_0 e^{i\omega t}$. I was told by the professor that I can make a Fourier transform to solve for $\hat{g}(\omega)$, where $\hat{g}$ is the Fourier transform of $g(t)$. It is easy to find that the Fourier transform of $\frac{dg}{dt}$ can be written $i\omega \hat{g}(\omega)$. However, I cannot see how I can make a Fourier transform of the right-hand side of eq. (3), since the integral seems to blow up? Can someone see where I am going wrong, or what to do from here?

A: Fourier transforming $(3)$ yields
$$
\hat{g}(k)=\frac{\varepsilon_{0} \delta(k+\omega)}{i k+D_{r}}
$$
Inverse Transform would give -
$$g(t)=\int e^{ikt}\hat{g}(k)dk=\int e^{ikt}\frac{\varepsilon_{0} \delta(k+\omega)}{i k+D_{r}}dk$$
$$=\frac{\varepsilon_{0} e^{-i\omega t}}{-i\omega+D_{r}}\tag{E1}$$
It can be verified that this expression satisfies eqn $(3)$
Note : $(E1)$ is a particular solution of $(3)$. General solution is
$$g(t)=Ce^{-D_rt}+\frac{\varepsilon_{0} e^{-i\omega t}}{-i\omega+D_{r}}$$
where $e^{-D_rt}$ is the solution to the homogeneous version of $(3)$ and C is a constant.


text:
Q: How to convert ssd_resnet_50 tensorflow checkpoint to .tflite? I'm trying to convert the ssd_resnet_50 model from the tensorflow Object Detection API to .tflite format but it doesn't work.
Some background:

*

*I'm able to successfully convert the out of the box and retrained ssd_mobilenet_v2_quantized model to .tflite and run the .tflite model.

*Because the ssd_resnet_50 model is not quantized, I've added the following to the ssd_resnet_50 pipeline.config file and retrained the model:
graph_rewriter {
  quantization {
    delay: 48000
    weight_bits: 8
    activation_bits: 8
  }
}

After retraining ssd_resnet_50, I try to convert the model to .tflite format with the following commands:
# Produces tflite_graph.pb
python3 object_detection/export_tflite_ssd_graph.py \
        --pipeline_config_path=pipeline.config \
        --trained_checkpoint_prefix=model.ckpt-50000 \
        --output_directory=$OUTPUT_DIR \
        --add_postprocessing_op=true

# Produces detect.tflite
bazel run -c opt tensorflow/lite/toco:toco -- \
    --input_file=$OUTPUT_DIR/tflite_graph.pb \
    --output_file=$OUTPUT_DIR/detect.tflite \
    --input_shapes=1,640,640,3 \
    --input_arrays=normalized_input_image_tensor \
    --output_arrays='TFLite_Detection_PostProcess','TFLite_Detection_PostProcess:1','TFLite_Detection_PostProcess:2','TFLite_Detection_PostProcess:3'  \
    --inference_type=QUANTIZED_UINT8 \
    --mean_values=128 \
    --std_values=128 \
    --change_concat_input_ranges=false \
    --allow_custom_ops

Normally, TOCO would produce a valid detect.tflite that could be run. However, TOCO runs into the following error regarding quantization and Relu6.
Can anyone help?

Error :
2019-05-21 10:41:07.885065: F tensorflow/lite/toco/tooling_util.cc:1718] Array WeightSharedConvolutionalBoxPredictor_2/BoxPredictionTower/conv2d_0/BatchNorm/feature_2/FusedBatchNorm_mul_0, which is an input to the Add operator producing the output array WeightSharedConvolutionalBoxPredictor_2/Relu6, is lacking min/max data, which is necessary for quantization. If accuracy matters, either target a non-quantized output format, or run quantized training with your model from a floating point checkpoint to change the input graph to contain min/max information. If you don't care about accuracy, you can pass --default_ranges_min= and --default_ranges_max= for easy experimentation.
run_toco.sh: line 25:  3280 Aborted                 (core dumped) bazel run -c opt tensorflow/lite/toco:toco -- --input_file=$OUTPUT_DIR/tflite_graph.pb --output_file=$OUTPUT_DIR/detect.tflite --input_shapes=1,640,640,3 --input_arrays=normalized_input_image_tensor --output_arrays='TFLite_Detection_PostProcess','TFLite_Detection_PostProcess:1','TFLite_Detection_PostProcess:2','TFLite_Detection_PostProcess:3' --inference_type=QUANTIZED_UINT8 --mean_values=128 --std_values=128 --change_concat_input_ranges=false --allow_custom_ops

A: Reading your error it seems that the array WeightSharedConvolutionalBoxPredictor_2/BoxPredictionTower/ conv2d_0/BatchNorm /feature_2/FusedBatchNorm_mul_0 from WeightSharedConvolutionalBoxPredictor_2/ Relu6 does not have min/max information which is needed to do post-training quantization.
You can look at Use "dummy-quantization" to try out quantized inference on a float graph. section for an example and some details.
You can add --default_ranges_min=0  --default_ranges_max=255 to your command but you will lose accuracy doing so.
bazel run -c opt tensorflow/lite/toco:toco -- \
--input_file=$OUTPUT_DIR/tflite_graph.pb \
--output_file=$OUTPUT_DIR/detect.tflite \
--input_shapes=1,640,640,3 \
--input_arrays=normalized_input_image_tensor \
--output_arrays='TFLite_Detection_PostProcess','TFLite_Detection_PostProcess:1','TFLite_Detection_PostProcess:2','TFLite_Detection_PostProcess:3'  \
--inference_type=QUANTIZED_UINT8 \
--mean_values=128 \
--std_values=128 \
--default_ranges_min=0 \
--default_ranges_max=255 \
--change_concat_input_ranges=false \
--allow_custom_ops

From the Tensorflow Converter command line reference :
--default_ranges_min, --default_ranges_max. Type: floating-point. Default value for the (min, max) range values used for all arrays without a specified range. Allows user to proceed with quantization of non-quantized or incorrectly-quantized input files. These flags produce models with low accuracy. They are intended for easy experimentation with quantization via "dummy quantization"


text:
Q: Spring bind a bean to rest post request I have following REST service build around Spring. I want to implement a POST method which can add user. The data for user is in request body and can be either in JSON/XML. I want server side implementation

*

*to automatically map incoming data to Java bean

*and handle both type of data (JSON/XML) using single implementation.

I have tried with @ModelAttribute in addUser method of UserController but getting all fields empty in user object. Any clue?
Here is Spring configuration file
<mvc:annotation-driven />

<context:component-scan base-package="com.rest.sg.controller" />

<bean
    class="org.springframework.web.servlet.view.ContentNegotiatingViewResolver">
    <property name="order" value="1" />
    <property name="mediaTypes">
        <map>
            <entry key="json" value="application/json" />
            <entry key="xml" value="application/xml" />
        </map>
    </property>

    <property name="defaultViews">
        <list>
            <!-- JSON View -->
            <bean
                class="org.springframework.web.servlet.view.json.MappingJacksonJsonView">
            </bean>
            <!--  XML view -->
            <bean class="org.springframework.web.servlet.view.xml.MarshallingView">
                <constructor-arg>
                    <bean class="org.springframework.oxm.jaxb.Jaxb2Marshaller">
                        <property name="classesToBeBound">
                            <list>
                                <value>com.rest.sg.bean.User</value>
                            </list>
                        </property>
                    </bean>
                </constructor-arg>
            </bean>
        </list>
    </property>
    <property name="ignoreAcceptHeader" value="true" />

</bean>

UserController class and addUser method
@Controller
public class UserController {

    @RequestMapping(method=RequestMethod.POST, value="/user")
    @ResponseBody
    public User addUser(@ModelAttribute("user") User user) {
        userService.addUser(user);
        return user;
    }

}

And User Bean
@Entity
@XmlRootElement
@Table(name = "user", catalog = "blahblah")
public class User implements java.io.Serializable {

    // Fields
    // Getter , Setters
    ...

}

A: Your controller needs to know how to map the data. The default is mapping request parameters on the object's properties.
If you send JSON that represents the User object you can try
public User addUser(@RequestBody User user) {

A: Do like this:
  @RequestMapping(value="/persons", method = RequestMethod.POST,
                headers="Accept=*/*",
                consumes="application/json")
public User addUser( @RequestBody User u){
              //Code.
}

When sending request, send the header
Content-Type:application/json //This is important
Accept: application/json


text:
Q: Check if a String is HTML or XML Is there a way to check if a String is HTML or XML in JavaScript? Preferably using jQuery rather than some other library?
Why I need to do this is because I need to know if it possible to have a function into which XML or HTML can be passed. If it is HTML we take one action and if it is XML we take another action.

A:
Is there a way to check if a String is HTML or XML in JavaScript?

Not reliably. You can test for one (e.g. against a DTD or XSD) and if it fails, assume it's the other. However, those tests are meant to be run on entire documents with a valid DOCTYPE. There are many cases where a snippet of markup will pass validation for multiple markup languages. What then?
I think you need to explain why you need to know the difference.

A: The rule is that if it starts with <?xml version="1.0"> then it's XML-based. If it doesn't have it, it should NOT be considered XML as XML requires that particular tag.
"An XML file or stream is made up of the following structures:
One or more Processing directives, the most common being the required <?xml version="1.0">"
http://en.wikipedia.org/wiki/XML

A: I can think of two ways to do this.
The brute-force method is to have a list of all the valid html elements and if it isn't one of those then it must be xml.  This may be the cleanest approach.
If you use a namespace for the html then the xml will probably be in a default namespace, so if you look for this line (Implementing a default namespace for XML documents) on this page (https://developer.mozilla.org/en/Introduction_to_using_XPath_in_JavaScript) you will see that anything in the default namespace will return null when using an XPath evaluation.
According to this page (http://www.nczonline.net/blog/2009/04/04/xpath-in-javascript-part-3/), xpath doesn't work on HTML elements, which would be another way to tell xml from html.
I haven't used xpath, but the implementation may differ among different browsers, according to this page: http://www.yaldex.com/ajax-tutorial-4/BBL0029.html, as Firefox may allow xpath to work on html elements.
So, xpath may be a good solution, depending on browsers supported and whether your xml may use a namespace, but since the number of elements supported in html is finite it would seem that looking within that group would be the most precise solution.


text:
Q: Google test framework parametrize fixtures i have a one question. i use the following structure as fixture:

class unvalidSDPTest : public ::testing::Test{
protected:
    virtual void SetUp(){
        std::string Name("name");
        Server=new SipServer(Name);
        std::ifstream offerFile,answerFile;
        offerFile.open("unvalidOfferSDP.txt");
        answerFile.open("unvalidAnswerSDP.txt");
        std::string offerRawSDP,answerRawSDP;
        offerFile>>offerRawSDP;
        answerFile>>answerRawSDP;
        offerSDPSession = Server->MakeSDPSession( const_cast(offerRawSDP.c_str()) ) ;
        answerSDPSession = Server->MakeSDPSession( const_cast(answerRawSDP.c_str()) ) ;
    }
    virtual void TearDown(){
        delete Server;
    }
    pjmedia_sdp_session *offerSDPSession, *answerSDPSession ;
    SipServer *Server;
    SDPNeg Negotiator;
};

and i want to parametrize this class by file name. how make it better?

A: There's many ways to do this - I'll show you two:
Method 1: Create a base class with a virtual functions, then derive from it.
class unvalidSDPTestBase : public ::testing::Test{
  virtual const char * offer_filename() const =0;
  virtual const char * answer_filename() const =0;
  protected:
    virtual void SetUp(){
        std::string Name("name");
        Server=new SipServer(Name);
        std::ifstream offerFile,answerFile;
        offerFile.open( offer_filename());
        answerFile.open(answer_filename());
        std::string offerRawSDP,answerRawSDP;
        offerFile>>offerRawSDP;
        answerFile>>answerRawSDP;
        offerSDPSession = Server->MakeSDPSession( const_cast(offerRawSDP.c_str()) ) ;
        answerSDPSession = Server->MakeSDPSession( const_cast(answerRawSDP.c_str()) ) ;
    }
    virtual void TearDown(){
        delete Server;
    }
    pjmedia_sdp_session *offerSDPSession, *answerSDPSession ;
    SipServer *Server;
    SDPNeg Negotiator;
 };

 class unvalidSPDTestBase: public unvalidSDPTestBase
 {
     virtual const char * offer_filename() const { return "..."; }
     virtual const char * answer_filename() const { return "..."; }
 }

Method 2: use a traits like system and templating:
template<typename FILENAME_SOURCE>
class SDPTest : public ::testing::Test{
  protected:
    virtual void SetUp(){
        std::string Name("name");
        Server=new SipServer(Name);
        std::ifstream offerFile,answerFile;
        offerFile.open( FILENAME_SOURCE::offer_filename());
        answerFile.open( FILENAME_SOURCE::answer_filename());
        std::string offerRawSDP,answerRawSDP;
        offerFile>>offerRawSDP;
        answerFile>>answerRawSDP;
        offerSDPSession = Server->MakeSDPSession( const_cast(offerRawSDP.c_str()) ) ;
        answerSDPSession = Server->MakeSDPSession( const_cast(answerRawSDP.c_str()) ) ;
    }
    virtual void TearDown(){
        delete Server;
    }
    pjmedia_sdp_session *offerSDPSession, *answerSDPSession ;
    SipServer *Server;
    SDPNeg Negotiator;
 };

 struct InvalidFilenames
 {
   static const char * offer_filename()  { return "..."; }
   static const char * answer_filename() { return "..."; }
 };

 typedef SDPTest<InvalidFilenames> unvalidSDPTest;