text:
Q: React Dynamic Form // form
import { useFormContext } from 'react-hook-form';
// @mui
import { Box, Stack, Divider, Typography } from '@mui/material';
// components
import { RHFTextField, RHFCheckbox } from '@/components/hook-form';

// ----------------------------------------------------------------------

type Props = {
  serviceFields: Field[];
  serviceId: string;
};

export default function TicketNewEditDetails({ serviceFields, serviceId }: Props) {
  const { control, watch } = useFormContext();

  const values = watch();

  return (
    <Box sx={{ p: 3 }}>
      <Typography variant="h6" sx={{ color: 'text.disabled', mb: 3 }}>
        Details:
      </Typography>

      <Stack divider={<Divider flexItem sx={{ borderStyle: 'dashed' }} />} spacing={3}>
        <Stack alignItems="flex-end" spacing={1.5}>
          <Stack direction={{ xs: 'column', md: 'column' }} spacing={2} sx={{ width: 1 }}>
            {serviceId && serviceFields.map((field, index) => <InputField key={index} field={field} index={index} />)}
          </Stack>
        </Stack>
      </Stack>
    </Box>
  );
}

type Field = {
  _id: string;
  name: string;
  placeholder: string;
  inputType: string;
  required: boolean;
  options: string[];
};

enum Input {
  TextField = 'textField',
  RadioGroup = 'radioGroup',
  Checkbox = 'checkbox',
  MultiCheckbox = 'multiCheckbox',
  Select = 'select',
  UploadSingleFile = 'uploadSingleFile',
  UploadMultiFile = 'uploadMultiFile',
}

type InputFieldProps = {
  field: Field,
  index: number
}

function InputField({ field, index }: InputFieldProps) {
  switch (field.inputType) {
    case Input.TextField: {
      return (

          <RHFTextField
            sx={{ display: 'none' }}
            name={`data[${index}].name`}
            defaultValue={'dsa'}
            value={field.name}
          />

          <RHFTextField
            key={field._id}
            size="small"
            name={`data[${index}].value`}
            placeholder={field.placeholder}
            label={field.name}
            InputLabelProps={{ shrink: true }}
          />

      );
    }
    case Input.RadioGroup: {
      return
;
    }
    case Input.Checkbox: {
      return
;
    }
    case Input.MultiCheckbox: {
      return
;
    }
    case Input.Select: {
      return
;
    }
    case Input.UploadSingleFile: {
      return
;
    }
    case Input.UploadMultiFile: {
      return
;
    }
    default:
      return
;
  }
};

what im trying to achieve is to have a data array for the field values
where data: [{ name: 'name of field'  , value: 'value of field'}
name would be holding the field.name from serviceFields array
and value would be the value for that field

Example:
serviceFields: [
  {
   name: 'Description',
   placeholder: 'write your description',
   inputType: 'textField'
  }
]

so the form would have some like:
function InputField({ field, index }: InputFieldProps) {
  switch (field.inputType) {
    case Input.TextField: {
      return (

          <RHFTextField
            sx={{ display: 'none' }}
            name={`data[${index}].name`}
            defaultValue={'dsa'}
            value={field.name}
          />

          <RHFTextField
            key={field._id}
            size="small"
            name={`data[${index}].value`}
            label={field.name}
            InputLabelProps={{ shrink: true }}
          />

      );
    }
    default:
      return
;
  }
};

and data would be:
data: [
  { name: 'Category', value: 'the user input for category text field' }
]

what's currently happening on mount:
I get this error:
Warning: A component is changing an uncontrolled input to be controlled. This is likely caused by the value changing from undefined to a defined value, which should not happen.

data: [
  { name: undefined, value: undefined }
]

and after typing in text field:
data: [
  { name: undefined, value: 'value of category text field' }
]

what I want to happen:
data: [
  { name: 'Category', value: '' }
]

after typing in text field:
data: [
  { name: 'Category', value: 'value of category text field' }
]


text:
Q: Split nested list based on unique value I have got a list with vector points which I would like to split based on the second value of the nested list, the y position. So, points[0][1].
The example list contains two unique y heights: 920 and 940. But a list could have easily 10 unique y heights.
points = [(418, 920), (558, 920), (726, 920), (858, 920), (906, 920), (1042, 920), (418, 940), (558, 940), (734, 940), (865, 940), (899, 940), (1034, 940)]

# Desired result:
newPoints = [ [ [x,920], [x,920]  ], [ [x,940], [x,940] ] ]

A: This is where a collections .defaultdict comes in:
from collections import defaultdict
new_points = defaultdict(list)
for point in points:
    new_points[point[1]].append(point)

defaultdict(<class 'list'>, {
920: [(418, 920), (558, 920), (726, 920), (858, 920), (906, 920), (1042, 920)],
940: [(418, 940), (558, 940), (734, 940), (865, 940), (899, 940), (1034, 940)]
})

If you need the lists, you can do new_points.values() or list(new_points.values())

[[(418, 920), (558, 920), (726, 920), (858, 920), (906, 920), (1042, 920)],
 [(418, 940), (558, 940), (734, 940), (865, 940), (899, 940), (1034, 940)]]

A: I created a dictionary of y-values to its list of  x values, then iterated through the y-values, creating a sublist for each one, and iterated through the x-values, create a sublist for each of those.
points = [(418, 920), (558, 920), (726, 920), (858, 920), (906, 920), (1042, 920), (418, 940), (558, 940), (734, 940), (865, 940), (899, 940), (1034, 940)]

y_dict = dict()

for point in points:
    x = point[0]
    y = point[1]
    if y in y_dict.keys():
        #already found this y
        y_dict[y].append(x)
    else:
        #haven't found this y
        y_dict[y] = [x]

newPoints = []

for y in y_dict.keys():
    sublist = []
    for x in y_dict[y]:
        sublist.append([x, y])
    newPoints.append(sublist)

print(newPoints)

Then the result is:
[[[418, 920], [558, 920], [726, 920], [858, 920], [906, 920], [1042, 920]], [[418, 940], [558, 940], [734, 940], [865, 940], [899, 940], [1034, 940]]]

redpajama_set_name: RedPajamaStackExchange


text:
Q: How can i test react components based on jQuery-UI? I need to test functionality of slider component in react based on jQuery-UI slider.
i tried using Jest and unMock jQuery but i'm getting an outerWidth undefined error from jQuery.
no luck so far googling this :)

A: found this, looks like the solution
http://yahooeng.tumblr.com/post/102274727496/to-testutil-or-not-to-testutil


text:
Q: why a javascript event not working on firefox? I have an input type file , once the user click to upload his image , the process
of the upload starts and a little thumbnail of that image is displayed, that's works normal on chrome , with firefox there is an issue , no thumbnail is showing after click to upload , this is the code that I am using to make this process :
var input = event.target;

// Instantiate FileReader
var reader = new FileReader();
reader.onload = function(){
    TheFileContents = reader.result;
    // Update the output to include the  tag with the data URL as the source
    document.getElementById("img").src = TheFileContents;
};

// Produce a data URL (base64 encoded string of the data in the file)
// We are retrieving the first file from the FileList object
reader.readAsDataURL(input.files[0]);

A: In your example, reader.onload is not a valid method on FileReader.  If you want to add an event on reader then add it like this:

function previewFile() {
  var preview = document.querySelector('img');
  var file    = document.querySelector('input[type=file]').files[0];
  var reader  = new FileReader();

  reader.addEventListener("load", function () {
    preview.src = reader.result;
  }, false);

  if (file) {
    reader.readAsDataURL(file);
  }
}
<input type="file" onchange="previewFile()">

I just checked and this is working on Firefox.

A: The updated value is given to onload by an event property : event.target.result
var input = event.target;

// Instantiate FileReader
var reader = new FileReader();
reader.onload = function(event){
    var fileContent = event.target.result;
    // Update the output to include the  tag with the data URL as the source
    document.getElementById("img").src = fileContent;
};

// Produce a data URL (base64 encoded string of the data in the file)
// We are retrieving the first file from the FileList object
reader.readAsDataURL(input.files[0]);


text:
Q: Consume Scala syntax-trees from external tool I would like to develop a tool that would consume scala syntax-trees (as the title suggests). More specifically it would be great if I could consume the trees after each compilation phase.
My research led me to Dotty's TASTY interchange format which seemed to be what I was looking for. Perhaps it is.
However, I was not able to find adequate documentation on-line to figure out how to extract it and consume it.
I also looked at dotc compiler flags and couldn't figure out an obvious approach.
I noticed the option : "-print-tasty" but I couldn't verify the expected output or perhaps I am missing something ?
Of course I can always print the AST after each phase using the scala printer (i.e., -Yshow-trees etc.). Is this my only option ? If it is, then fine.
Ideally, it would be great if I could consume the ASTs in a more "machine-friendly" format if you will. TASTY seems to be what I want in theory, i.e., a serialization of the AST, but I am not sure how to extract this after each phase.
I do apologize if my question is too trivial or has already been addressed. Any feedback would be highly appreciated ! Thanks !
P.S.: What if the ASTs were encoded in a JSON format ? Would a scala tool like that make sense, (i.e., a tool that converts Scala ASTs to JSON and back) ?


text:
Q: Explanation of tuple notation in code snippet This a code snippet for peak element search in 2D array
(subStartR, subNumR) = (0, problem.numRow)
(subStartC1, subNumC1) = (0, mid)
(subStartC2, subNumC2) = (mid + 1, problem.numCol - (mid + 1))

subproblems = []
subproblems.append((subStartR, subStartC1, subNumR, subNumC1))
subproblems.append((subStartR, subStartC2, subNumR, subNumC2))

What is the need for parentheses in the first assignments and why are they used when appending to a list?

A: the append function adds only a single element to a list.  extend is what to use for multiple elements.
So what is happening is at each step, subproblems is having a "tuple" added to the end of it.  The inner () denote the tuple.  Add a print subproblems at the end and you'll get something of the form
[(.,.,.,.), (.,.,.,.)]

that is, a list of 2 tuples, each containing 4 elements.
The (a,b) = (c,d) is equivalent to a=c, b=d.

A: Statements like:
(subStartR, subNumR) = (0, problem.numRow)

are packing two values into a tuple on the RHS of the =, and unpacking them into two variables on the LHS.  The parentheses are redundant -- just code
subStartR, subNumR = 0, problem.numRow

and you'll have the same effect with less punctuation noise:-)
In
subproblems.append((subStartR, subStartC1, subNumR, subNumC1))

the situation is very different.  The outside parentheses indicate the call to append; the inside ones group four values into one tuple, and they are necessary -- if you removed them, leaving just the outside ones, you'd actually be calling append with four arguments, which is not correct.
It's unfortunate that some punctuation characters (such as commas and parentheses) are overloaded with a few separate meanings, but, there just aren't enough distinct characters in ASCII to assign them differently!-)


text:
Q: Symfony2 Functional Testing: Is a database required or not? I have to write functional tests for a controller that registers a user in the application.
The controller has two methods (and routes):

*

*registrationAction (route=registration)

*endAction (route=registration/end)

Now I would like to write functional tests for those two methods.
My question is: as the controller creates and persists a new user in the database, should have I to use a test database? Is the mocking of entity manager a solution? And how can I test that the user is correctly created in the database?
The Symfony's documentation, speaking about functional testing of forms, don't mention database, but generally the filling of the form and the submit of it. But if i try to do the same thing in my functional tests, they return errors (and I think they are right: there is no database where to save submitted data!).
So, I think I should use a database for functional tests, but I don't understand why:

*

*Symfony's documentation doen't mention the database

*Someone suggests to use mocks of the Entity Manager.

I'm a bit confused: should have I to use a database or not?

A: Answer to this question in not simple yes/no, you can do it in both ways, both have its advantages and disadvantages.
1. With test database
You mention that you need to write controller test. Testing controller is testing of almost top layer of your application flow. Controller depends on many class implementations which you would need to mock if you would like to test your controllers logic with isolation. If your controller has it's dependencies injected into contructor using service container I would possibly think of mocking but if it extends Symfony's Controller I would use test database mocking everything in this case would be harsh.
2. Without database
In this case you need to mock your entity manager and this is possible. However in your case I would think of refactoring. Move logic outside your controller to some UserManager or similar class. Register this class as a service and inject all required dependencies. Think of injecting repository instead of whole EntityManager as described here. Now, because your code is more single responsible it's easier to write tests and it's easier to mock all of your dependencies.
Conclusion: do refactoring, move your logic outside of controller, write test for single responsible class by injecting mocks of dependencies into it.


text:
Q: conversion of JS button to Lightning salesforce I have a JS button, which is calling a web service class method and doing some process. I am trying to convert that to call a VF page and make it lightning compatible. But I am stuck on an error while calling the web service method in the pageref. Pls suggest
global class AddUserToNewTeam{
    public Opportunity objOpp;

    global AddUserToTeam(ApexPages.StandardController stdcontroller) {
        objOpp = (Opportunity)stdController.getRecord();
    }

    public pagereference addTeam(){

     addTeamMember(objOpp.Id); ****ERROR HERE: Error: Compile Error: Method does not exist or incorrect signature: void addTeamMember(Id) from the type  AddUserToNewTeam****

      return new pagereference(url.getsalesforcebaseurl().toexternalform()+'/'+objOpp.Id);
    }

 webservice static boolean addTeamMember(List<Id> opptyIds)
    {
    //all logic
    }

A: You're passing a single Id objOpp.Id, but your method expects a List<Id>
addTeamMember(List<Id> opptyIds)
So, you can create a list and pass that to the method
public pagereference addTeam(){
  List<Id> opportunityIds = new List<Id>();
  opportunityIds.add(objOpp.Id);
  addTeamMember(opportunityIds);
}

Or, depending on whether this is the only use case for this method - update the method to accept a single Id and keep the other parts of your code
addTeamMember(Id opptyId)


text:
Q: Write to last Node using linq to xml I am using Linq to xml for creating a xml file. My xml format is like below.
enter image description here
<weather> element will be created in every time I iterate through loop. And every time I want to write something into latest <weather> element created. How do I do that?

A: This should do the trick:
foreach (XElement element in xdoc.Elements("Language").Elements("Text"))
{
    // method 1, store a reference..
    var weather = new XElement("weather");
    xTSDoc.Element("data").Add(weather);
    weather.Add(new XElement("Text", element.Attribute("Number").Value));
    weather.Add(new XElement("Name", element.Attribute("Name").Value));

    // method 2, get last element
    xTSDoc.Element("data").Add(new XElement("weather"));
    xTSDoc.Element("data").Elements("weather").Last().Add(new XElement("Text", element.Attribute("Number").Value));
    xTSDoc.Element("data").Elements("weather").Last().Add(new XElement("Name", element.Attribute("Name").Value));
}


text:
Q: Immediately stop jQuery animate positioning animation I use the following script to move elements in a canvas randomly:
function makeNewPosition(){

    var h = $(window).height() - 50;
    var w = $(window).width() - 50;

    var nh = Math.floor(Math.random() * h);
    var nw = Math.floor(Math.random() * w);

    return [nh,nw];

}

function animateDiv(element){

    var newq = makeNewPosition();
    $(element).animate({ top: newq[0], left: newq[1] }, 5000, function(){
        animateDiv(element);
    });

};

Now i need to immediately stop the animation when clicking a button. How is this possible?


text:
Q: Criar uma rota no Google Maps V3 como faço para adaptar o script abaixo para o seguinte próposito:
O usuário abre a página e aparece o mapa em um lugar pré-definido (empresa). Depois ele clica em um input e digita a localização dele, (o input fica acima do mapa), depois ele clica em um botao "chegar", e no mesmo instante, uma rota é traçada do ponto onde ele está, até o lugar que já estava pré-definido anteriormente. (ex: uma empresa).
**Segue o código:**
 <!DOCTYPE html>

<meta http-equiv="Content-Type" content="text/html; charset=UTF-8">
<title>Traçar Rota</title>

    <form method="post" action="">
                <fieldset>

                        <input type="text" id="txtEndereco" name="txtEndereco" size="50" style="padding: 15px; border: 1px solid #cdcdcd;" placeholder="Onde estou..."/>
                        <input type="button" id="btnEndereco" name="btnEndereco" value="CHEGAR" style=" padding: 15px;" />

                    <input type="hidden" type="submit" value="Enviar" name="btnEnviar" />

                    <input type="hidden" id="txtLatitude" name="txtLatitude" />
                    <input type="hidden" id="txtLongitude" name="txtLongitude" />

                </fieldset>
    </form>

A: Primeiro você precisa do serviço DirectionsService, este você pode colocar junto das variáveis que estão no topo dos seu script:
var directionsService = new google.maps.DirectionsService();

E então, no clique do botão btnEndereco, você pode substituir pela chamada deste serviço que consiste em iniciar o objeto de renderização das direções, criar um objeto com os parâmetros necessários para realizar a requisição e realiza-la de fato:
var directionsDisplay = new google.maps.DirectionsRenderer();

var request = {
        origin: $("#txtEndereco").val(),
        destination: marker.position,
        travelMode: google.maps.DirectionsTravelMode.DRIVING
};

directionsService.route(request, function(response, status) {
        if (status == google.maps.DirectionsStatus.OK) {
            directionsDisplay.setDirections(response);
            directionsDisplay.setMap(map);
        }
});

Após concluir a requisição com sucesso, a rota será desenhada no mapa. Na documentação deste serviço você encontra mais informações, caso queira mais detalhes desta solução.


text:
Q: How to navigate to a new page in custom cell? I have a custom cell FeedCell.swift and the controller FeedViewController.swift. And I set a btn in each cell so that I can navigate to detailController.swift. But in custom cell I can't use self.navigation. What should I do?

A: You can set an outlet of Button in cell and addTarget it like :
    func tableView(_ tableView: UITableView, cellForRowAt indexPath: IndexPath) -> UITableViewCell {
        let cell = tableView.dequeueReusableCell(withIdentifier: "cellID") as! yourCell
        cell.yourButton.addTarget(self, action: #selector(goDetail), for: .touchUpInside)
        return cell
    }

    @objc func goDetail(){
        let vc = // Declare your viewController
        self.navigationController?.pushViewController(vc, animated:true)
    }

Btw you can add this action when a cell selected instead of using button
func tableView(_ tableView: UITableView, didSelectRowAt indexPath: IndexPath)
{
 let vc = // Declare your viewController
 self.navigationController?.pushViewController(vc, animated:true)
}

If you want to send which cell's button clicked just add cell.yourButton.tag = indexPath.row in cellForRowAt and modify goDetail with
 @objc func goDetail(sender : UIButton){
     sender.tag // while give your selected cell index
    }


text:
Q: Passing object to FormTokenField suggestions I know FormTokenField suggestions prop is for arrays, but what is the best way to go about it if I need to get the key value of an object? I want the objects keys values to show in the suggestions, but when selected I need the key.
const names = { 123: "John", 321: "Sam" };

const MyFormTokenField = () => {
const [ selectedNames, setSelectedNames ] = useState( [] );

return (
    <FormTokenField
        value={ selectedNames }
        suggestions={ names }
        onChange={ ( tokens ) => setSelectedNames( tokens ) }
    />
);
};

UPDATE 9/27/22
I found this repo of a modified FormTokenField that takes an object like I want, but can this be done in some what with the default up to date version? https://github.com/rmorse/wp-token-multiselect-control


text:
Q: What does C++ using mean inside a class? What does it mean to have a using inside a class definition?
class myClass {
public:
  [...]
  using anotherClass::method;
};

A: The case I've seen it:
class A
{
    void foo(int);
    void foo(float);
}

class B : public A
{
    void foo(string);
}

B b;
b.foo(12); // won't work!

Because I have implemented a new foo function in B with a different signature it hides the foo functions from A. In order to override this behavior I would do:
   class B : public A
   {
       void foo(string);
       using A::foo;
   }

A: Most often, syntax like this is used like so:
class derived : public base {
public:
    [...]
    using base::method;
};

The using declaration here unhides a member declaration from the parent class. This is sometimes necessary if another member declaration in derived may hide the member from base.

A: That declaration unhides a base class member.  This is most often used to allow overloads of a member function.  Example:
class Base {
public:
   void method() const;
};

class Derived : public Base {
public:
   void method(int n) const;
   // Without the using, you would get compile errors on d.method();
   using Base::method;
};

A: If anotherClass is a base class that contains a member function like
virtual void f();

and you decide to overload the function in the derived class like
virtual void f(int);

it "hides" f() in the base class. Calling f() through a pointer to the derived class for example, would result in an error, since the compiler does not "see" the version of f() taking no arguments from the base class anymore.
By writing
using Base::f;

you can bring the base classes function back into scope, thus enabling overload resolution as you might have expected it to work in the first place.


text:
Q: Hyperlink not working on popup I have a website Here.
There's a pop up window that appears as soon as the page is loaded. However, I'm unable to utilize links in the HTML content.
Here's the HTML...

Updates to the AR Toolbox

• Check out the new rotating Announcement Board on the AR Toolbox!

• Have you seen the new SUO Tour yet? Click here to check it out!

• South University and The Education Foundation Scholarship Committee are now on SharePoint. Click  here!

When you look at the popup, you'll see all my links are grouped in the upper right corner of the popup window, with the 'X'.
Here's the CSS for the Popup...
#blanket {
   background-color:#111;
   opacity: 0.65;
   filter: alpha(opacity=65)
   *background:none;
   position:absolute;
   z-index: 9001;
   top:0px;
   left:0px;
   width:100%;
}

#popUpDiv {
    position:absolute;
    background-color: #fff;
    background-image:url(../images/popup_bg.png);
    background-repeat:no-repeat;
    width:400px;
    height:400px;
    border:5px solid #000;
    z-index: 9002;
}

#popUpDiv a {
    background-image: url(../images/x.png);
    background-repeat: no-repeat;
    position:absolute; top:10px; right:10px}

I think it lies in the '#popUpDiv a' section, but I'm not sure how to fix it.
Any ideas?
Edit: Here is the jsfiddle
On the 2nd bullet, you'll see "Click to check it out!" when it should be "Click here to check it out!"
On the 3rd bullet, you'll see "Click", when it should be "Click here."
But, again, all the the links are bundled up in the top right-hand corner for some reason.

A: Instead of applying the style to a, just create a style class and apply that to the popUpDiv. Like this...
#popUpDiv .close {
    background-image: url(../images/x.png);
    background-repeat: no-repeat;
    position:absolute;
    top:10px;
    right:10px
}

and apply it to the popup href...

jsFiddle DEMO here
Hope this helps!


text:
Q: Confusion in how to find number of onto functions if two sets are given In the book it is given if A and B are two finite sets containing $m$ and $n$ elements, respectively, then the number of onto functions from A to B will be if
$n \leq m$
$$\sum_{r=1}^n (-1)^{(n-r)} {n \choose r}(r)^m $$
well I can't understand it and I am aware with combinations.


text:
Q: Redshift Insert Multiple Rows I'm struggling to insert multiple rows into Redshift. Here are the SQL queries:
CREATE TABLE tblA (
  column1 bigint primary key,
  column2 varchar(255) default null,
  column3 varchar(255) default null,
  recordModifiedTimestamp timestamp
);

INSERT INTO tblA (column1, column2, column3) VALUES
  (1, "DES", "article"),
  (2, "DES", "slideshow"),
  (3, "DES", "video");

When I run last query, here is what I get back:
ERROR:  column "des" does not exist in tblA

Am I missing something?

A: Well, thanks to Gordon Linoff, here is the correct SQL query:
INSERT INTO tblA (column1, column2, column3) VALUES
  (1, 'DES', 'article'),
  (2, 'DES', 'slideshow'),
  (3, 'DES', 'video');

Unbelievable! :-)


text:
Q: create and set variables at same time in a loop tkinter I want to create a label and assign it at the same time.
For example,
ivar=StringVar()
for i in range(0,len(str)):
   w = Label(master, textvariable=ivar)
   w.grid(row=r,column=c)
   ivar.set(i)
   r++
   c++
.......
root.update()

This is just a sudo example. I just want to generate n labels where I don't know value to n and it changes everytime I update. I am using root.update() for updating labels. Can anyone help me on this?
Thanks in advance.

A: I generally save them in a list, which is a convenient way to save references to them all.  And please don't use i,l, or o as single digit variables as they can look like numbers, i.e.
i=1
i=l
l=O
import sys
if sys.version_info[0] < 3:
    import Tkinter as tk     ## Python 2.x
else:
    import tkinter as tk     ## Python 3.x

class TestLabels():
    def __init__(self, parent, num_labels):
        self.parent = parent
        self.string_var_list=[]
        tk.Button(self.parent, text="Exit", command=self.parent.quit,
                  bg="orange").grid(row=100)
        self.create_labels(num_labels)

        ## change one label
        str_var=self.string_var_list[10]
        str_var.set("***changed***")

    def create_labels(self, num_labels):
        """create labels, 5 to a row
        """
        r=0
        c=0
        colors=["lightblue", "yellow", "white", "pink", "lightgreen"]
        for ctr in range(num_labels):
            s_var=tk.StringVar()
            ## won't save the Label ID since you use StringVar to change it
            tk.Label(self.parent, textvariable=s_var,
                     bg=colors[c]).grid(row=r, column=c, sticky="nsew")
            s_var.set("Label #%d" % (ctr))
            self.string_var_list.append(s_var)
            c += 1
            if c > 4:
                c=0
                r += 1

if __name__ == "__main__":
    root = tk.Tk()
    MA=TestLabels(root, 14)
    root.mainloop()


text:
Q: Do I need foomatic printer drivers? I just installed a print to pdf back-end for cups, and it gave the warning that foomatic printer modules would need to be removed. Do I need foomatic printer drivers, for when i want to print to physical devices?
What am I giving up here? Will I be having other problems in the near future for having removed foomatic printer support?

A: The only package which is pre-installed on your system is foomatic-db-compressed-ppds. ubuntu-desktop depends on foomatic-db-compressed-ppds, but the removal of foomatic-db-compressed-ppds, which also removes ubuntu-desktop, doens't destroys your system, as ubuntu-desktop is only a meta-package.

This package contains all PPD files which can be generated from the
  Foomatic database as one small compressed archive. This reduces the
  disk space consumption compared to the Foomatic XML database vastly
  and in addition makes listing of all available PPDs and extracting the
  needed PPD much faster than using the Foomatic XML database.

Both packages, cups-pdf and printer-driver-cups-pdf, don't depends on foomatic-db-compressed-ppds.

On the other side, if you need any foomatic package later by a dependency, let's resolve this problem later, if there is any.


text:
Q: Configuring keep-alive timeout in Elasticsearch server I was wondering if Elasticsearch provides a way of configuring a keep-alive timeout.
I can see that this page describes a network.tcp.keep_alive TCP setting that can be used to enable TCP Keep Alive. I'm searching for a way in Elasticsearch to configure the actual timeout value.
I'm using Elasticsearch 5.6.8.

A: I believe you would have to configure this on the client.
https://www.elastic.co/guide/en/elasticsearch/client/javascript-api/current/configuration.html#config-keep-alive-free-socket-timeout


text:
Q: Merge objects in JavaScript I have two objects and I want to merge them, but it should not replace the object.
var x = {'one':1, 'two': {'b': 2, 'c': 3}}
var y = {'two': {'b': 4}}

When I merge them The out put should be :
{'one':1, 'two': {'b': 4, 'c': 3}}

A: You can use recursive approach for updating nested object.

var x = {
  'one': 1,
  'two': {
    'b': 2,
    'c': 3
  }
}
var y = {
  'two': {
    'b': 4
  }
}

function merge(a, b) {
// create new object and copy the properties of first one
  var res = Object.assign({}, a);
  //iterate over the keys of second object
  Object.keys(b).forEach(function(e) {
    // check key is present in first object
    // check type of both value is object(not array) and then
    // recursively call the function
    if (e in res && typeof res[e] == 'object' && typeof res[e] == 'object' && !(Array.isArray(res[e]) || Array.isArray(b[e]))) {
   // recursively call the function and update the value
   // with the returned ne object
   res[e] = merge(res[e], b[e]);
    } else {
      // otherwise define the preperty directly
      res[e] = b[e];
    }
  });
  return res;
}

var res = merge(x, y);

console.log(res);

UPDATE : If you want to merge the array then you need to do something like this.

var x = {
  'one': 1,
  'two': {
    'b': [22, 23],
    'c': 3
  }
}
var y = {
  'two': {
    'b': [24]
  }
}

function merge(a, b) {
  var res = Object.assign({}, a);
  Object.keys(b).forEach(function(e) {
    if (e in res && typeof res[e] == 'object' && typeof res[e] == 'object' && !(Array.isArray(res[e]) || Array.isArray(b[e]))) {
      res[e] = merge(res[e], b[e]);
      // in case both values are array
    } else if (Array.isArray(res[e]) && Array.isArray(b[e])) {
      // push the values in second object
      [].push.apply(res[e], b[e]);
      // or use
      // res[e] = res[e].concat(b[e]);
    } else {
      res[e] = b[e];
    }
  });
  return res;
}

var res = merge(x, y);

console.log(res);


text:
Q: Is it possible to flag change language with Jquery I'm doing my own portfolio website (2 language TH/EN).
The buttons for changing languages. I can do it.
But I think if I change the page, the language button must have problems
because new page loads.
My question is
What should I do?
When I changed the page The language I chose from the beginning is still active.
Example :
The default language is Thai. But I click changed to English.The information in the home page changes to English.
If I click on another menu like About Us, the information on that page is displayed in English.

$("html").each(function () {
  if ($(".lang-select.th").hasClass('active')) {
   $('.lang-select').parents('html').attr('lang', 'th');
   $('.content-th').show();
   $('.content-en').hide();

  } else if ($(".lang-select.en").hasClass('active')) {
   $('.lang-select').parents('html').attr('lang', 'en');
   $('.content-th').hide();
   $('.content-en').show();
  }
 });

$(".lang-select.th").click(function () {
  $(this).addClass("active");
  $(".lang-select.en.active").removeClass("active");
  $('.lang-select').parents('html').attr('lang', 'th');
  $('.content-th').show();
  $('.content-en').hide();
 });

 $(".lang-select.en").click(function () {
  $(this).addClass("active");
  $(".lang-select.th.active").removeClass("active");
  $('.lang-select').parents('html').attr('lang', 'en');
  $('.content-th').hide();
  $('.content-en').show();
 });
.lang-select {
width:30px;
height:30px;
background:#eaeaea;
cursor:pointer;
}
.lang-select.active {
background:yellow;
}

<!DOCTYPE html>

 <meta charset="UTF-8">
 <title>Document</title>

          TH
          EN

ภาษาไทย Thailand

ภาษาอังกฤษ English

A: If I understand correct, you don't want to pass the language information to the server-side.
If you want to use pure jquery/javascript you should pass the language information to the URL. Once you have it there you should use some javascript method to parse URL. I found this method, which may help you:
How to read GET data from a URL using JavaScript?
Good luck!


text:
Q: MSTest Code Coverage Is there a way to test code coverage within visual studio if I'm using MSTest? Or do I have to buy NCover?
Is the NCover Enterprise worth the money or are the old betas good enough if Microsoft doesn't provide built in tools to do code coverage?
EDIT:
Description of VS Products and which ones include code coverage
https://www.visualstudio.com/vs/compare/
TestDriven.NET (http://testdriven.net/) can be used if your VS version doesn't support it.

A: (Note, this answer (here/below) is for DotNet FRAMEWORK.  I've created a dotnet-core answer here : How to get code coverage report in donetcore 2 application )
...............................
For future readers:
Wow, this was NOT fun.  I hope this helps someone out there in internet land.
Please note that the existence of "CodeCoverage.exe" may depend on the version of Visual Studio you have.  And you may have to install VS (some enhanced version) in the build server.
set __msTestExe=C:\Program Files (x86)\Microsoft Visual Studio 14.0\Common7\IDE\MSTest.exe
set __codeCoverageExe=C:\Program Files (x86)\Microsoft Visual Studio 14.0\Team Tools\Dynamic Code Coverage Tools\CodeCoverage.exe

rem (the below is a custom C# console application, code seen below)
set __customCodeCoverageMergerExe=CoverageCoverterConsoleApp.exe

rem below exe is from https://www.microsoft.com/en-us/download/details.aspx?id=21714
set __msXslExe=C:\MyProgFiles\MsXslCommandLine\msxsl.exe

REM the below calls will create the binary *.coverage files
"%__codeCoverageExe%" collect /output:"D:\BuildStuff\TestResults\AAA_DynamicCodeCoverage.coverage" "%__msTestExe%" /testcontainer:"D:\BuildStuff\BuildResults\My.UnitTests.One.dll" /resultsfile:"D:\BuildStuff\TestResults\My.UnitTests.One.trx"
"%__codeCoverageExe%" collect /output:"D:\BuildStuff\TestResults\BBB_DynamicCodeCoverage.coverage" "%__msTestExe%" /testcontainer:"D:\BuildStuff\BuildResults\My.UnitTests.Two.dll" /resultsfile:"D:\BuildStuff\TestResults\My.UnitTests.Two.trx"
"%__codeCoverageExe%" collect /output:"D:\BuildStuff\TestResults\CCC_DynamicCodeCoverage.coverage" "%__msTestExe%" /testcontainer:"D:\BuildStuff\BuildResults\My.UnitTests.Three.dll" /resultsfile:"D:\BuildStuff\TestResults\My.UnitTests.Three.trx"

rem below, the first argument is the new file, the 2nd through "N" args are the result-files from the three "%__codeCoverageExe%" collect above
rem this will take the three binary *.coverage files and turn them into one .xml file
"%__customCodeCoverageMergerExe%" "D:\BuildStuff\TestResults\DynamicCodeCoverage.merged.coverage.converted.xml" "D:\BuildStuff\TestResults\AAA_DynamicCodeCoverage.coverage" "D:\BuildStuff\TestResults\BBB_DynamicCodeCoverage.coverage" "D:\BuildStuff\TestResults\CCC_DynamicCodeCoverage.coverage"

"%__msXslExe%" "D:\BuildStuff\TestResults\DynamicCodeCoverage.merged.coverage.converted.xml" "D:\BuildStuff\Xsl\VSCoverageToHtml.xsl" -o "D:\BuildStuff\TestResults\CodeCoverageReport.html"

You can also combine the 3 UnitTests.dlls into one call
REM the below calls will create the binary *.coverage files
"%__codeCoverageExe%" collect /output:"D:\BuildStuff\TestResults\ZZZ_DynamicCodeCoverage.coverage" "%__msTestExe%" /testcontainer:"D:\BuildStuff\BuildResults\My.UnitTests.One.dll" /testcontainer:"D:\BuildStuff\BuildResults\My.UnitTests.Two.dll" /testcontainer:"D:\BuildStuff\BuildResults\My.UnitTests.Three.dll" /resultsfile:"D:\BuildStuff\TestResults\My.UnitTests.AllOfThem.trx"

rem below, the first argument is the new file, the 2nd through "N" args are the result-files from the three "%__codeCoverageExe%" collect above
rem this will take the one binary *.coverage files and turn them into one .xml file
"%__customCodeCoverageMergerExe%" "D:\BuildStuff\TestResults\DynamicCodeCoverage.merged.coverage.converted.xml" "D:\BuildStuff\TestResults\ZZZ_DynamicCodeCoverage.coverage"

"%__msXslExe%" "D:\BuildStuff\TestResults\DynamicCodeCoverage.merged.coverage.converted.xml" "D:\BuildStuff\Xsl\VSCoverageToHtml.xsl" -o "D:\BuildStuff\TestResults\CodeCoverageReport.html"

VSCoverageToHtml.xsl
I also found some xsl in the internet.
(the 3 links below are pretty much the same xsl)
http://codetuner.blogspot.com/2011_09_01_archive.html
http://jp.axtstar.com/?page_id=258
http://codetuner.blogspot.com/2011/09/convert-mstest-code-covarage-results-in.html
I'm posting the xsl here "just in case" those URL's die in the future.
Put the below xsl in a file called "VSCoverageToHtml.xsl" (as referenced above).
<?xml version="1.0" encoding="utf-8"?>
<xsl:stylesheet version="1.0" xmlns:xsl="http://www.w3.org/1999/XSL/Transform">
    <xsl:output method="html" indent="yes"/>
    <xsl:template match="/" >

                <title>Code Coverage Report</title>

Code Coverage Report

                        Name
                        Blocks Covered
                        Blocks Not Covered
                        Coverage

                    <xsl:apply-templates select="//CoverageDSPriv/Module" />

    </xsl:template>

    <xsl:template match="Module">
        <xsl:variable name="parentId" select="generate-id(./..)" />
        <xsl:variable name="currentId" select="generate-id(.)" />

            [+]

                <xsl:value-of select="ModuleName" />

                <xsl:value-of select="BlocksCovered" />

                <xsl:value-of select="BlocksNotCovered" />

            <xsl:call-template name="CoverageColumn">
                <xsl:with-param name="covered" select="BlocksCovered" />
                <xsl:with-param name="uncovered" select="BlocksNotCovered" />
            </xsl:call-template>

        <xsl:apply-templates select="NamespaceTable" />

    </xsl:template>

    <xsl:template match="NamespaceTable">
        <xsl:variable name="parentId" select="generate-id(./..)" />
        <xsl:variable name="currentId" select="generate-id(.)" />

             -
            [+]

                <xsl:value-of select="NamespaceName" />

                <xsl:value-of select="BlocksCovered" />

                <xsl:value-of select="BlocksNotCovered" />

            <xsl:call-template name="CoverageColumn">
                <xsl:with-param name="covered" select="BlocksCovered" />
                <xsl:with-param name="uncovered" select="BlocksNotCovered" />
            </xsl:call-template>

        <xsl:apply-templates select="Class" />

    </xsl:template>

    <xsl:template match="Class">
        <xsl:variable name="parentId" select="generate-id(./..)" />
        <xsl:variable name="currentId" select="generate-id(.)" />

             -
             -
            [+]

                <xsl:value-of select="ClassName" />

                <xsl:value-of select="BlocksCovered" />

                <xsl:value-of select="BlocksNotCovered" />

            <xsl:call-template name="CoverageColumn">
                <xsl:with-param name="covered" select="BlocksCovered" />
                <xsl:with-param name="uncovered" select="BlocksNotCovered" />
            </xsl:call-template>

        <xsl:apply-templates select="Method" />

    </xsl:template>

    <xsl:template match="Method">
        <xsl:variable name="parentId" select="generate-id(./..)" />

             -
             -
             -

                <xsl:value-of select="MethodName" />

                <xsl:value-of select="BlocksCovered" />

                <xsl:value-of select="BlocksNotCovered" />

            <xsl:call-template name="CoverageColumn">
                <xsl:with-param name="covered" select="BlocksCovered" />
                <xsl:with-param name="uncovered" select="BlocksNotCovered" />
            </xsl:call-template>

    </xsl:template>

    <xsl:template name="CoverageColumn">
        <xsl:param name="covered" select="0" />
        <xsl:param name="uncovered" select="0" />

            <xsl:variable name="percent"
                select="($covered div ($covered + $uncovered)) * 100" />
                            <xsl:attribute name="style">
                background-color:
                <xsl:choose>
                    <xsl:when test="number($percent >= 90)">#86ed60;</xsl:when>
                    <xsl:when test="number($percent >= 70)">#ffff99;</xsl:when>
                    <xsl:otherwise>#FF7979;</xsl:otherwise>
                </xsl:choose>
            </xsl:attribute>
            <xsl:if test="$percent > 0">
                <xsl:value-of select="format-number($percent, '###.##' )" />%
            </xsl:if>
            <xsl:if test="$percent = 0">
                <xsl:text>0.00%</xsl:text>
            </xsl:if>

    </xsl:template>
</xsl:stylesheet>

Here is a small command line tool to help.
https://www.microsoft.com/en-us/download/details.aspx?id=21714
using System;

using Microsoft.VisualStudio.Coverage.Analysis;
using System.Collections.Generic;

/* References
\ThirdPartyReferences\Microsoft Visual Studio 11.0\Microsoft.VisualStudio.Coverage.Analysis.dll
\ThirdPartyReferences\Microsoft Visual Studio 11.0\Microsoft.VisualStudio.Coverage.Interop.dll
*/

namespace MyCompany.VisualStudioExtensions.CodeCoverage.CoverageCoverterConsoleApp
{
    class Program
    {
        static int Main(string[] args)
        {
            if (args.Length < 2)
            {
                Console.WriteLine("Coverage Convert - reads VStest binary code coverage data, and outputs it in XML format.");
                Console.WriteLine("Usage:  ConverageConvert <destinationfile> <sourcefile1> <sourcefile2> ... <sourcefileN>");
                return 1;
            }

            string destinationFile = args[0];
            //destinationFile = @"C:\TestResults\MySuperMergedCoverage.coverage.converted.to.xml";

            List<string> sourceFiles = new List<string>();

            //files.Add(@"C:\MyCoverage1.coverage");
            //files.Add(@"C:\MyCoverage2.coverage");
            //files.Add(@"C:\MyCoverage3.coverage");

            /* get all the file names EXCEPT the first one */
            for (int i = 1; i < args.Length; i++)
            {
                sourceFiles.Add(args[i]);
            }

            CoverageInfo mergedCoverage;
            try
            {
                mergedCoverage = JoinCoverageFiles(sourceFiles);
            }
            catch (Exception e)
            {
                Console.WriteLine("Error opening coverage data: {0}", e.Message);
                return 1;
            }

            CoverageDS data = mergedCoverage.BuildDataSet();

            try
            {
                data.WriteXml(destinationFile);
            }
            catch (Exception e)
            {

                Console.WriteLine("Error writing to output file: {0}", e.Message);
                return 1;
            }

            return 0;
        }

        private static CoverageInfo JoinCoverageFiles(IEnumerable<string> files)
        {
            if (files == null)
                throw new ArgumentNullException("files");

            // This will represent the joined coverage files
            CoverageInfo returnItem = null;
            string path;

            try
            {
                foreach (string sourceFile in files)
                {
                    // Create from the current file

                    path = System.IO.Path.GetDirectoryName(sourceFile);
                    CoverageInfo current = CoverageInfo.CreateFromFile(sourceFile, new string[] { path }, new string[] { path });

                    if (returnItem == null)
                    {
                        // First time through, assign to result
                        returnItem = current;
                        continue;
                    }

                    // Not the first time through, join the result with the current
                    CoverageInfo joined = null;
                    try
                    {
                        joined = CoverageInfo.Join(returnItem, current);
                    }
                    finally
                    {
                        // Dispose current and result
                        current.Dispose();
                        current = null;
                        returnItem.Dispose();
                        returnItem = null;
                    }

                    returnItem = joined;
                }
            }
            catch (Exception)
            {
                if (returnItem != null)
                {
                    returnItem.Dispose();
                }
                throw;
            }

            return returnItem;
        }
    }
}

Also see:
Code Coverage files merging using code in VS 2012 Dynamic Code Coverage

A: MSTest includes code coverage, at least it does in the version of VS I have. However, you need to enable the instrumentation in the testrunconfig, which is just ugly and a major PITA.
A much easier option is to use TestDriven.NET, which can automate coverage, even for MSTest. And since it uses the MSTest core, you still get all the VS goodness such as colorization (red/blue lines for covered code). See here (including a screencast), or since an image says a thousand words:

(source: mutantdesign.co.uk)

A: Yes, you can find code coverage information from within Visual Studio, provided that you have a version of Visual Studio that provides that functionality, such as the Team System.
When setting up the unit tests in VS.NET, a localtestrun.testrunconfig file will be created and added as part of the solution. Double-click this file and find the option Code Coverage option on the left of the dialog. Select the assemblies for which you want to collect code coverage information and then re-run the unit tests. Code coverage information will be collected and is available. To get the code coverage information open the test results window and click on the code coverage results button, which will open an alternative window with the results.


text: Q: Windows Icon Overlay Limit I've tried to read as much about this as possible but I am confused...  Microsoft claims overlays are not the prefered method for conveying file metadata, but if this is true, why does OneDrive use a maximal number of overlays?  Also, I have found some posts from ~2017 that indicated OneDrive was using a "status" field for the file (I guess similar to "date modified", etc), but when I began using OneDrive recently, it did not automatically start displaying this status, but it did begin hogging all the overlays.  How do you prevent it from using overlays and use the "status" instead?


text:
Q: Why is the button iset to high even when not pressing the button (Arduino Uno) I am trying to make a random number generator that when a button is pressed will display a random number on a 16x2 LCD screen, but the button output always equals 1 even when the button is not being pressed.
Image of the setup not running:

Image of the setup running (NOTE: the button seems to do nothing when pressed):

The code:
#include <Adafruit_LiquidCrystal.h>
long randNumber;
int seconds = 0;
int buttonState = 2;
const int ledPin = 13;

Adafruit_LiquidCrystal lcd_1(0);

void setup() {
  pinMode(buttonState,INPUT_PULLUP);
  pinMode(ledPin,OUTPUT);
  lcd_1.begin(16, 2);
  lcd_1.print("hello world");
  randomSeed(analogRead(0));
}

void loop() {
  delay(500);
  buttonState = digitalRead(0);
  digitalWrite(ledPin, !digitalRead(buttonState));
  delay(250);
  if (buttonState == 1) {
    randNumber = random(0,9 + 1);
    lcd_1.setCursor(0, 1);
    lcd_1.print(randNumber);
    lcd_1.print(buttonState);
    lcd_1.setBacklight(1);
    delay(500);
  } else {
    lcd_1.setBacklight(0);
    lcd_1.setCursor(0, 1);
    lcd_1.print(buttonState);
    delay(500);
  }
}


text:
Q: Display contents of text file in man page without formatting I'm working on an Open Source contribution. I need to use its print_usage() function which contains printf() statements for help message (myprogram --help) to generate manpage using myprogram --man automatically. I've setup command line args to use freopen() to print the help message directly to file myprogram.1. But when executed with man -l myprogram.1 it changes the line length which indeed changes the output's expected indentation.
Expected text as in help message:
To see This Help Message: -h or --help

File name related options:
            inputfile: file(s) to process
    -o outputfilename: Use -o parameters to define output filename if you don't
                       like the default ones (same as infile plus _1 or _2 when
                       needed and file extension, e.g. .srt).
         -cf filename: Write 'clean' data to a file. Cleans means the ES
                       without TS or PES headers.
              -stdout: Write output to stdout (console) instead of file. If
                       stdout is used, then -o, -o1 and -o2 can't be used. Also
                       -stdout will redirect all messages to stderr (error).

Output when man -l myprogram.1 is executed:
To see This Help Message: ‐h or ‐‐help

File name related options:
            inputfile: file(s) to process
    ‐o  outputfilename:  Use ‐o parameters to define output file‐
name if you don't
                       like the default ones (same as infile plus
_1 or _2 when
                       needed and file extension, e.g. .srt).
         ‐cf filename: Write 'clean' data to a file. Cleans means
the ES
                       without TS or PES headers.
              ‐stdout: Write output to stdout  (console)  instead
of file. If
                       stdout is used, then ‐o, ‐o1 and ‐o2 can't
be used. Also
                       ‐stdout  will  redirect  all  messages  to
stderr (error).

How can I correct this? I can add sections like NAME, SYNOPSIS, etc. through C code later on but currently I just need to get the formatting right. Any help is appreciated.
EDIT
To make it clear. myprogram.1 obtained doesn't contain any type of groff formatting (no macros are used). It's just plain text document having the help message as plain text with indentation.


text:
Q: How do I make Grails 2.3.1 notice changes to BuildConfig.groovy? I've got a Grails 2.3.1 project that compiles and runs fine. But when I add or remove dependencies in BuildConfig.groovy (and then run grails clean, grails refresh-dependencies), the framework simply doesn't notice my changes.
If I introduce a syntax error, my code fails to compile. But my (syntactically valid) changes never even show up in grails dependency-report.
I can "fix" things via rm -rf ~/.grails/2.3.1/projects/myproject.
But that is terrible.
What's the right way to deal with this?

A: Does it work if you run grails compile instead of clean and refresh-dependencies? If not, and you can create a small app that demonstrates this behavior, run grails bug-report and attach that ZIP to an issue at http://jira.grails.org/browse/GRAILS

A: Try grails clean-all instead. The regular clean command is not going to clean all files...


text:
Q: is this network structure viable?
I would like to know if this network structure it would be viable or not.
The main reason it would be to be able to switch manually, the ISP. If one is going down than use the other one.
as I know public web hosting aren't made to his structure. Eg www.mycompany.com has a dedicated hosting plan somewhere in cloud.
At workstations are PC for developers, somewhere it is a Wi-Fi network too for cellphones.
Is there any software, which are doing the automated switching from ISP1 to ISP2 automatically?
Probably I haven't used the networking terms correctly, because lack of deep knowledge, what are the keywords for search?

A: Most enterprise firewalls will support what you are trying to do and we use Dell Sonicwall which certainly does.
If you are trying to "roll your own" then something link pfSense may do the trick and a quick look at their docs does show that it support multiple WAN links - see https://doc.pfsense.org/index.php/Multi-WAN_2.0

A: Not sure you want to put that level of trust into a PC which is not designed to be "on" 24/7, or even just office hours. What happens if that PC has a software/hardware problem? Means that you will have no internet connectivity for the rest of the office.
There are many routers that support this configuration, and even if you don't have the budget- why not just have 2 routers setup in the same way, but to different ISPs. If one of the ISPs goes down, physically switch the connection?

A: Viable, possibly. There's a lot to look at on that dedicated PC. In general, you're going to want a dedicated piece of hardware to be your router rather than a PC, if for no other reason to reduce the visible attack surface on an internet facing device. A support contract to handle the hardware on the single point of failure wouldn't be a bad idea, either. :)
The usual suspects in router or firewall hardware should be able to provide what you need. Be sure to mention load-balancing when you ask, or you may end up with a simple failover solution on the router/firewall. Not that that's necessarily a bad thing.


text:
Q: How can I track system call in win32 API program with debugger(VS 2013)? Well, I wrote a code for File I/O with Win32 API.
(I'm using Visual studio 2013)
It just gets two file name(one for source, one for destination) and duplicate one to another.
I used CreateFile, ReadFile, WriteFile.
It's functionally simple. It's not problem. But..
I wanna SEE the system call in these function being called in debugger.
How can I do this?
with Call stack? Disassembler?

A: So you want to be able to debug not only your own code but also the API itself.
There are different ways to do that.
At the simplest level, just use the debugger from VS2013. You won't be able to trace into kernel code, but all the user level code in the API. But of course as you will use a non debug version of Windows with no symbol table you will only see low-level machine code (*).
If you really want to go deeper, you will have to use the Debugging Tools for Windows. As you say you want to debug system calls, my advice would be to use the Windows Driver Kit, the Windows Symbols, and if you really go down to kernel mode the Windows Remote Debugging Client for Windows (all those tools are available from Windows Dev Center).
All those tools integrate nicely in VisualStudio, but be prepared to hard low level work :-)
(*) You can also use the Microsof Symbol Server to access windows symbolic information - thanks to IInspectable for his comment. But I've never tested.


text:
Q: Label and text not aligning properly on text overflow in bootstrap I have an inline label and readonly text. When readonly text overflows it goes under the label. I would like text to not go under label.
This is what i am getting:

Where as i would like:

Employer Information

                    Name
                    <bean:write name="myform" property="name" />

            .........

word-wrap class is as follows:
.word-wrap {
    word-wrap: break-word;
}

A: If you want the text to wrap but are not concerned with the  content indenting to another column, you should change your .word-wrap class to contain word-break: break-all; (and that's all you need):
.word-wrap {
    word-break: break-all;
}

And then enclose your elements with the .form-group class (you need to use .control-label for your label):

Employer Information

                    Name
                    <bean:write name="myform" property="name" />

        .........

http://www.bootply.com/ST1AlByo4g
However, if you want the entire contents of  indented, you are better off creating another set of columns - and then apply .word-wrap class to the  element or a wrapper:

Employer Information

        Name

        <bean:write name="myform" property="name" />

http://www.bootply.com/JLnvtz9o4i

A:

  <form class="form-horizontal">

Employer Information

        Name

          <input type="text" class="form-control" id="your_id_here">

  </form>

Bootply.
If you decide to stay with , just add form-control class to it and it shall align properly.

A: If word-break: break-all or word-wrap:break-word doesn't work, probably your white-space  is set to nowrap.
Try setting:
white-space:normal;

A:

    Name
    dsfdsfdsfdfdsfASSs

http://www.bootply.com/KK1MlNLy5V


text:
Q: How to hide or show controls while selecting mutilple checkboxes in orbeon form I have a requirement in which I have multiple checkboxes.
On selecting one checkbox, I want to unhide some input field which is possible but if I select multiple checkbox including one which unhides the field, the input field is not visible.
For only one checkbox value, I am using  tokenize(../@control-value, '\s+') = 'some Value'
and also how do I use multiple condition ? Is is possible to use '&&' and '||'  in Orbeon. Also please tell me how to use multiple checkboxes value to unhide the input field.

A: In XPath, which is the language Orbeon Forms uses for formulas "and" is expressed with and and "or" with or (so no && and || as is the case in many languages).
So now it comes down to what your condition is, something like "show the control if this checkbox is selected but no other checkbox is selected". Maybe the following could do the trick:
tokenize(../@control-value, '\s+') = 'some Value' and
not(count(tokenize(../@control-value, '\s+')) gt 1)

or:
let $tokens := tokenize(../@control-value, '\s+')
return
    $tokens = 'some Value' and not(count($tokens) gt 1)

If you are using Form Runner, and use the xxf:split() function:
let $tokens := xxf:split($my-control)
return
    $tokens = 'some Value' and not(count($tokens) gt 1)


text:
Q: backbone.js / access view from model How can I access the view from a model in backbone.js.
I would love to re-render the view on model.change().

A: Adding views to the model's attribute is a no-no.
Why would you need to access the view from model on its change?
In your view, simply bind:
this.model.bind('change', this.modelChanged, this) // (event, function, context)

and from now on, when your model changes, your view's modelChanged method will be called automatically.

in version >0.9, the proper syntax will be like this in the view.
this.model.on('change', this.modelChanged, this) // (event, function, context)

A: You may use one of two bindings:
this.model.bind('change', this.modelChanged)

this.model.bind('refresh', this.modelRefreshed)

Check the docs to see the differences.

A: There's another potential snafu to adding a view property to the model.  It's possible that a model might be represented by multiple views.  When this happens you'd have to change the view property to (an array) views.  That's harry coding.  I started off doing just this thing and realized my faux pas once I saw that multiple views could be involved.  I realized this was just another way of handling the publisher-subscriber pattern.
Others have been happy to have the model and view reference the other as a means of two-way communication. Gravel-Niquet does so in his Todos sample app.  Lerner suggests this in his June 2011 Linux Journal article on Backbone.js.  A matter of preference, perhaps, but I am with with pawlik.  Stick to events; that's what they're for.


text:
Q: Dynamically change src path in vuejs I want to dynamically change the path of my <img>'s src in Vue:
<template>
  <img :src="'../../assets/logo/'+LogoSrc()" alt="logo black" :height="height+'px'" />
</template>

<script>
export default {
  name: "Logo",
  props: {
    logoColor: {
      type: String,
      default: "dark"
    },
    height: {
      type: Number,
      default: 10
    }
  },
  data() {
    return {};
  },

  methods: {
    LogoSrc() {
      if (this.logoColor === "dark") {
        return "logo-black.svg";
      }
    }
  }
};
</script>

<style scoped>
</style>

Though the path is right, the image is still not loading. I tried using src without the v-bind with path being the same (../../assets/logo/logo-black.svg), and it seems to be working fine.

A: For dynamic URLs, use require():
<img :src="require('../../assets/logo/' + LogoSrc())">

demo

A: Make it a computed value:
<template>
  <img :src="LogoSrc" alt="logo black" :height="height+'px'" />
</template>

<script>
export default {
  name: "Logo",
  props: {
    logoColor: {
      type: String,
      default: "dark"
    },
    height: {
      type: Number,
      default: 10
    }
  },
  data() {
    return {};
  },

  computed: {
    LogoSrc() {
      if (this.logoColor === "dark")
        return "../../assets/logo/logo-black.svg";

      return "";
    }
  }
};
</script>

<style scoped>
</style>


text:
Q: Base of Global Call Stack in C/C++ I have read that each function invocation leads to pushing of a stack frame in the global call stack and once the function call is completed the call stack is popped off and the control passes to the address that we get from the popped of stack frame. If a called function calls on to yet another function, it will push another return address onto the top of the same call stack, and so on, with the information stacking up and unstacking as the program dictates.
I was wondering what's at the base of global call stack in a C or C++ program?
I did some searching on the internet but none of the sources explicitly mention about it. Is the call stack empty when our program starts and only once a function is called, the call stack usage starts? OR Is the address where main() function has to return, gets implicitly pushed as the base of our call stack and is a stack frame in our call stack? I expect the main() would also have a stack frame in our call stack since we are always returning something at end of our main() function and there needs to be some address to return to. OR is this dependent on compiler/OS and differs according to implementation?
It would be helpful if someone has some informative links about this or could provide details on the process that goes into it.

A: I'm not sure if there is a universal answer, as stack is something that may be implemented differently per architecture. For example a stack may grow up (i.e. stack position pointer value increases when pushing onto the stack) or grow downwards.
Exiting main() is usually done by calling an operating function to indicate the program wishes to to terminate (with the specified return code), so I don't expect a return address for main() to be present on the stack, but this may differ per operating system and even compiler.
I'm not sure why you need to know this, as this is typically something you leave up to the system.

A: main() is invoked by the libc code that handles setting up the environment for the executable etc. So by the time main() is called, the stack already has at least one frame created by the caller.

A: First of all, there is no such thing as a "global call stack". Each thread has a stack, and the stack for the main thread is often looking quite different from the thread of any thread spawned later on. And mostly, each of these "stacks" is just an arbitrary memory segment currently declared to be used as such, sub-allocated from any arbitrary suitable memory pool.
And due to compiler optimizations, many function calls will not even end up on the stack, usually. Meaning there isn't necessarily a distinguishable stack frame. You are only guaranteed that you can reference variables you put on the stack, but not that the compiler must preserve anything you didn't explicitly reference.
There is not even a guarantee that the memory layout for your call stack must even be organized in distinguishable frames. Function pointers are never guaranteed to be part of the stack frame, just happens to be an implementation detail in architectures where data and function pointers may co-exist in the address space. (As there are architectures which require return addresses to be stored in a different address space than the data used in the call stack.)
That aside, yes, there is code which is executed outside of the main() function. Specifically initializers for global static variables, code to set up the runtime environment (env, call parameters, stdin/stdout) etc.
E.g. when having linked to libc, there is __libc_start_main which will call your main function after initialization is done. And clean up when your main function returns.
__libc_start_main is about the point where "stack" starts being used, as far as you can see from within the program. That's not actually true though, there has already been some loader code been executed in kernel space, for reserving memory for your process to operate in initially (including memory for the future stack), initializing registers and memory to well defined values etc.
Right before actually "starting" your process, after dropping out of kernel mode, arbitrary pointers to a future stack, and the first instruction of your program, are loaded into the corresponding processor registers. Effectively, that's where __libc_start_main (or any other initialization function, depending on your runtime) starts running, and the stack visible to you starts building up.
Getting back into the kernel usually involves an interrupt now, which doesn't follow the stack either, but may just directly access processor registers to simply swap the contents of the corresponding processor registers. (E.g. if you call a function from the kernel, the memory required by the call stack inside the function call is not allocated from your stack, but from one you don't even have access to.)
Either way, everything that happens before main() is called, and whenever you enter a syscall, is implementation dependent, and you are not guaranteed any specific observable behavior. And messing around with processor registers, and thereby alternating the program flow, is also far outside defined behavior as far as a pure C / C++ run time is concerned.

A: Every system I have seen, when main() is called a stack is setup.  It has to be or just declaring a variable inside main would fail.  A stack is setup once a thread or process is created.  Thus any thread of execution has a stack.  Further in every assembly language i know, a register or fixed memory location is used to indicate the current value of the stack pointer, so the concept of a stack always exists (the stack pointer might be bad, but stack operations always exist since they are built into the every mainstream assembly language).


text:
Q: Fullscreen modes in Ubuntu (SDL + OpenGL) I've got some odd issue with fullscreen behaviour on Ubuntu. Windowed mode is working fine, but both "fake" (SDL_WINDOW_FULLSCREEN) and "real" (SDL_WINDOW_FULLSCREEN_DESKTOP) fullscreen modes are not.
On Windows, "fake" fullscreen mode does a videomode change and we see window's content stretched to a whole display. "Real" fullscreen mode takes the size of the desktop. In this mode I draw window's content in the top-left corner and leave extra area empty.
On Ubuntu, "fake" fullscreen mode does a videomode change and window's content is stretched to a whole display, but only part of it is drawn. It's either top part (more than 90% of the display) or bottom part (less than 10% of the display). The part that is not drawn is black or contains something that was drawn on the screen before the application was statred. Sometimes application does not change videomode back on exit. Cursor is locked inside top part even if only bottom part is drawn.
"Real" fullscreen mode is either completely black or shows window's contents in the center of the display. Contents are shifted to the top, and everything around that area is black (though background color is not). In this mode cursor is locked inside that area.
Behaviour differs a bit if I change fullscreen mode in run-time - drawn area (which is also area where cursor is locked) can be anywhere, not only top/bottom in "fake" mode or center in "real".

*

*"Fake" fullscreen mode on Windows:
(800x600 videomode)

*"Real" fullscreen mode on Windows:
(800x600 window's content is drawn in the corner, other area is empty)

*"Fake" fullscreen mode on Ubuntu:
(800x600 videomode, but not whole area is visible. You can see a part of gedit though.)

*"Real" fullscreen mode on Ubuntu:
(800x600 area in center, but image is shifted to the top (red square meant to be in the corner))

I'm manually using OpenGL to draw on screen instead of SDL. I've wrote a small example that shows the problem. It creates a 800x600 window and draws a blue triangle in it's center. Green square is drawn in the corner of the screen and red square is drawn in the corner of the window (those can be in the same place, so green square is bigger and red square is drawn on top of it). One can enter windowed, "fake" or "real" fullscreen modes using '1', '2' or '3' key respectively. Escape key closes the application.
#include <SDL.h>
#include <GL/gl.h>

#define FULLSCREEN 0
#define WIDTH 800
#define HEIGHT 600

//fullscreen:
// 0 - windowed mode,
// 1 - "fake" fullscreen mode,
// 2 - "real" fullscreen mode

int real_width;
int real_height;

//screen width & height - to draw green square that shows us actual screen size

void set_viewport(SDL_Window* window);
void draw(SDL_Window* window);

int main(int argc, char* argv[]) {
 SDL_Init(SDL_INIT_VIDEO);

 int position;
 #if FULLSCREEN == 0
  position = SDL_WINDOWPOS_CENTERED;
 #else
  position = 0;
 #endif

 //the only thing I've found - some guy said it works
 //if window is in (0,0) while entering fullscreen
 //well, it's not, but I've kept it

 int flags = SDL_WINDOW_OPENGL;
 #if FULLSCREEN == 1
  flags |= SDL_WINDOW_FULLSCREEN;
 #elif FULLSCREEN == 2
  flags |= SDL_WINDOW_FULLSCREEN_DESKTOP;
 #endif

 SDL_GL_SetAttribute(SDL_GL_RED_SIZE, 5);
 SDL_GL_SetAttribute(SDL_GL_GREEN_SIZE, 5);
 SDL_GL_SetAttribute(SDL_GL_BLUE_SIZE, 5);
 SDL_GL_SetAttribute(SDL_GL_DEPTH_SIZE, 16);
 SDL_GL_SetAttribute(SDL_GL_DOUBLEBUFFER, 1);

 SDL_Window* window = SDL_CreateWindow(
  "",
  position, position, /* centered/(0,0) */
  WIDTH, HEIGHT, /* request 800x600 window */
  flags /* needed mode */
 );

 //setup GL
 SDL_GLContext glcontext = SDL_GL_CreateContext(window);

 glShadeModel(GL_SMOOTH);
 glCullFace(GL_BACK);
 glFrontFace(GL_CCW);
 glEnable(GL_CULL_FACE);

 //viewport and projection
 set_viewport(window);

 draw(window);

 bool done = false;
 while(!done) {
  draw(window);

  SDL_Event event;
  while(SDL_PollEvent(&event)) {
   switch(event.type) {
    case SDL_QUIT: done = true; break;
    case SDL_KEYDOWN:
     if(event.key.keysym.scancode == SDL_SCANCODE_ESCAPE)
      done = true;
     else if(event.key.keysym.scancode == SDL_SCANCODE_1) {
      SDL_SetWindowFullscreen(window, 0);
      set_viewport(window);
     } else if(event.key.keysym.scancode == SDL_SCANCODE_2) {
      SDL_SetWindowFullscreen(window, SDL_WINDOW_FULLSCREEN);
      set_viewport(window);
     } else if(event.key.keysym.scancode == SDL_SCANCODE_3) {
      SDL_SetWindowFullscreen(window, SDL_WINDOW_FULLSCREEN_DESKTOP);
      set_viewport(window);
     }
    break;
   }
  }
 }

 SDL_GL_DeleteContext(glcontext);
 SDL_DestroyWindow(window);
 SDL_Quit();
 return 0;
}

void set_viewport(SDL_Window* window) {
 SDL_GetWindowSize(window, &real_width, &real_height);

 glClearColor(1, 1, 1, 1);
 glViewport(0, 0, real_width, real_height);
 glMatrixMode(GL_PROJECTION);
 glLoadIdentity();
 glOrtho(0, real_width, real_height, 0, -1, 0);
}

void draw_triangle();
void draw_square(int x, int y, float side);

void draw(SDL_Window* window) {
 glClear(GL_COLOR_BUFFER_BIT);
 glEnable(GL_BLEND);
 glBlendFunc(GL_SRC_ALPHA, GL_ONE_MINUS_SRC_ALPHA);

 //triangle on while background
 glClearColor(1, 1, 1, 1);
 draw_triangle();

 //green square at screen corner
 glColor3f(0, 1, 0);
 draw_square(real_width, real_height, 20);

 //red square at window corner
 glColor3f(1, 0, 0);
 draw_square(WIDTH, HEIGHT, 10);

 SDL_GL_SwapWindow(window);
}

void draw_triangle() {
 const float w = 460;
 const float h = 400;

 float colorBuffer[9] = {
  0, 0.43f, 0.85f /*#006dd9*/,
  0, 0.22f, 0.43f /*#00376e*/,
  0, 0.43f, 0.85f /*#006dd9*/
 };
 float vertexBuffer[9] = {
  0, 0, 0,
  w/2, h, 0,
  w, 0, 0
 };

 glEnableClientState(GL_VERTEX_ARRAY);
 glEnableClientState(GL_COLOR_ARRAY);

 glTranslatef((WIDTH-w)/2,(HEIGHT-h)/2,0);

 glColorPointer(3, GL_FLOAT, 0, colorBuffer);
 glVertexPointer(3, GL_FLOAT, 0, vertexBuffer);
 glDrawArrays(GL_TRIANGLE_FAN, 0, 3);

 glTranslatef(-(WIDTH-w)/2,-(HEIGHT-h)/2,0);

 glDisableClientState(GL_COLOR_ARRAY);
 glDisableClientState(GL_VERTEX_ARRAY);
}

void draw_square(int x, int y, float side) {
 float vertexBuffer[12] = {
  0, 0, 0, /*top left*/
  0, side, 0, /*bottom left*/
  side, side, 0, /*bottom right*/
  side, 0, 0 /*top right*/
 };

 glEnableClientState(GL_VERTEX_ARRAY);

 glTranslatef(x-side/2, y-side/2, 0);

 glVertexPointer(3, GL_FLOAT, 0, vertexBuffer);
 glDrawArrays(GL_TRIANGLE_FAN, 0, 4);

 glTranslatef(-x+side/2, -y+side/2, 0);

 glDisableClientState(GL_VERTEX_ARRAY);
}

A: Modechanges are eeeeevil, especially in multi-display environments.
Try borderless, desktop-sized windows instead:
#include <GL/glew.h>
#include <SDL2/SDL.h>

// use border state as proxy for fullscreenedness
SDL_Rect ToggleFakeFullscreen( SDL_Window* window, const SDL_Rect& oldBounds )
{
    if( SDL_GetWindowFlags( window ) & SDL_WINDOW_BORDERLESS )
    {
        SDL_SetWindowBordered( window, SDL_TRUE );
        SDL_SetWindowSize( window, oldBounds.w, oldBounds.h );
        SDL_SetWindowPosition( window, oldBounds.x, oldBounds.y );
        return oldBounds;
    }
    else
    {
        SDL_Rect curBounds;
        SDL_GetWindowPosition( window, &curBounds.x, &curBounds.y );
        SDL_GetWindowSize( window, &curBounds.w, &curBounds.h );

        int idx = SDL_GetWindowDisplayIndex( window );
        SDL_Rect bounds;
        SDL_GetDisplayBounds( idx, &bounds );
        SDL_SetWindowBordered( window, SDL_FALSE );
        SDL_SetWindowPosition( window, bounds.x, bounds.y );
        SDL_SetWindowSize( window, bounds.w, bounds.h );

        return curBounds;
    }
}

int main( int argc, char **argv )
{
    if( SDL_Init( SDL_INIT_EVERYTHING ) < 0 )
        return -1;

    SDL_Window* window = SDL_CreateWindow
        (
        "Test",
        SDL_WINDOWPOS_CENTERED, SDL_WINDOWPOS_CENTERED,
        640, 480,
        SDL_WINDOW_RESIZABLE | SDL_WINDOW_SHOWN | SDL_WINDOW_OPENGL
        );
    if( NULL == window )
        return -1;

    SDL_GLContext ctx = SDL_GL_CreateContext( window );
    if( GLEW_OK != glewInit() )
        return -1;

    SDL_Rect curBounds;

    bool running = true;
    while( running )
    {
        SDL_Event ev;
        while( SDL_WaitEventTimeout( &ev, 16 ) )
        {
            if( ev.type == SDL_QUIT )
                running = false;
            if( ev.type == SDL_KEYUP &&
                ev.key.keysym.sym == SDLK_ESCAPE )
                running = false;

            if( ev.type == SDL_KEYUP &&
                ev.key.keysym.sym == SDLK_f )
                curBounds = ToggleFakeFullscreen( window, curBounds );
        }

        int w, h;
        SDL_GetWindowSize( window, &w, &h );
        glViewport( 0, 0, w, h );

        glClearColor( 0, 0, 0, 1 );
        glClear( GL_COLOR_BUFFER_BIT );

        glMatrixMode( GL_PROJECTION );
        glLoadIdentity();

        glMatrixMode( GL_MODELVIEW );
        glLoadIdentity();

        glColor3ub( 255, 0, 0 );
        glBegin( GL_TRIANGLES );
        glVertex2i( -1, -1 );
        glVertex2i(  1, -1 );
        glVertex2i(  0,  1 );
        glEnd();

        SDL_GL_SwapWindow( window );
    }

    SDL_GL_DeleteContext( ctx );
    SDL_DestroyWindow( window );
    SDL_Quit();

    return 0;
}

Hit f to toggle "fullscreen".


text:
Q: C# DirectoryEntry Error? I have a Web setup project. In the setup I have an input field where the user can insert a connectionstring. When I run the setup I get this error:
Error 1001. Unknown error (0x8000x5000)
To track where the error exists I create a file and in every method I write something to this file. Now I think the error is raised by this line:
string friendlySiteName = entry.Properties["ServerComment"].Value.ToString();

But I don't know how to correct this problem. I hope you can help me out!
Code:
    public override void Install(System.Collections.IDictionary stateSaver)
    {
        base.Install(stateSaver);

        // Retrieve configuration settings
        string targetSite = Context.Parameters["targetsite"];
        string targetVDir = Context.Parameters["targetvdir"];
        string targetDirectory = Context.Parameters["targetdir"];
        string targetConnectionString = Context.Parameters["targetconn"];

        FileStream f = new FileStream("c:\\myfile.txt", FileMode.OpenOrCreate, FileAccess.ReadWrite);
        StreamWriter w = new StreamWriter(f);
        w.WriteLine("targetSite: " + targetSite);
        w.WriteLine("targetVDir: " + targetVDir);
        w.WriteLine("targetDirectory: " + targetDirectory);
        w.WriteLine("targetConnectionString: " + targetConnectionString);
        w.Close();
        w.Dispose();
        f.Close();
        f.Dispose();

        ConfigureWebConfig(targetSite, targetVDir, targetConnectionString);
    }

    void ConfigureWebConfig(string targetSite, string targetVDir, string targetConn)
    {
        try
        {
            // Retrieve "Friendly Site Name" from IIS for TargetSite
            DirectoryEntry entry = new DirectoryEntry("IIS://LocalHost/" + targetSite);

            FileStream f = new FileStream("c:\\myfile.txt", FileMode.Append, FileAccess.Write);
            StreamWriter w = new StreamWriter(f);
            w.WriteLine("In ConfigureWebConfig stap 1 ");
            w.Close();
            w.Dispose();
            f.Close();
            f.Dispose();

            string friendlySiteName = entry.Properties["ServerComment"].Value.ToString();

            f = new FileStream("c:\\myfile.txt", FileMode.Append, FileAccess.Write);
            w = new StreamWriter(f);
            w.WriteLine("In ConfigureWebConfig friendlySiteName: " + friendlySiteName);
            w.Close();
            w.Dispose();
            f.Close();
            f.Dispose();

            // Open Application's Web.Config
            Configuration config = WebConfigurationManager.OpenWebConfiguration("/" + targetVDir, friendlySiteName);
            addConnectionStringAttribute(targetConn, config);

            f = new FileStream("c:\\myfile.txt", FileMode.Append, FileAccess.Write);
            w = new StreamWriter(f);
            w.WriteLine("In ConfigureWebConfig stap 2 ");
            w.Close();
            w.Dispose();
            f.Close();
            f.Dispose();
            // togleCompilationAttribute(config);

            // Persist web.config settings
            config.Save();

            f = new FileStream("c:\\myfile.txt", FileMode.Append, FileAccess.Write);
            w = new StreamWriter(f);
            w.WriteLine("In ConfigureWebConfig stap 3 ");
            w.Close();
            w.Dispose();
            f.Close();
            f.Dispose();
        }
        catch (Exception)
        {
            throw;
        }

    }

    private static void addConnectionStringAttribute(string connectionStringValue, Configuration config)
    {
        ConnectionStringSettings appDatabase = new ConnectionStringSettings();

        appDatabase.Name = "dataConnectionString";
        appDatabase.ConnectionString = connectionStringValue;
        appDatabase.ProviderName = "System.Data.SqlClient";

        FileStream f = new FileStream("c:\\myfile.txt", FileMode.Append, FileAccess.Write);
        StreamWriter w = new StreamWriter(f);
        w.WriteLine("In addConnectionStringAttribute stap 1 ");
        w.Close();
        w.Dispose();
        f.Close();
        f.Dispose();

        config.ConnectionStrings.ConnectionStrings.Clear();
        config.ConnectionStrings.ConnectionStrings.Add(appDatabase);

        f = new FileStream("c:\\myfile.txt", FileMode.Append, FileAccess.Write);
        w = new StreamWriter(f);
        w.WriteLine("In addConnectionStringAttribute stap 2 ");
        w.Close();
        w.Dispose();
        f.Close();
        f.Dispose();
    }

A: if (m_targetSite.StartsWith("/LM/"))
    m_targetSite = m_targetSite.Substring(4);

use above code before this :-
// Retrieve "Friendly Site Name" from IIS for TargetSite
DirectoryEntry entry = new DirectoryEntry("IIS://LocalHost/" + m_targetSite);
m_siteName = entry.Properties["ServerComment"].Value.ToString();

A: Maybe this or this will help you.
If it's neither of those causes then the attribute probably doesn't exist.
Edit:
According to this, if you're using Win2k8 you need to enable "The IIS Metabase and IIS6 Configuration Compatibility" if you get this error. It is not automatically installed when the Web Server role is enabled.
Here is a related question.


text: Q: Converting geographic coordinate "DMS" string to float using C# I have geographical coordinates in DMS format and I want to convert it into corresponding decimal/float value. An example is -33° 51' 21.91" how do I convert it into decimal value? Is there any library available or .Net provide inbuilt function for this?


text:
Q: For a universal covering morphism $p:E\rightarrow B$, how to prove $E$ connected implies $B$ connected? Definition. An arrow $\alpha:A\rightarrow B$ in $\mathsf C=\mathsf{Fam}(\mathsf A)$ is said to be a covering morphism if there exists an effective descent morphism $p:E\rightarrow B$ that splits it, i.e such that the square below is a pullback.
$$\require{AMScd} \begin{CD}
    E\times_BA @>{\eta_{E\times_BA}}>> H\Pi_0(E\times_BA)\\ @V{p^\ast\alpha}VV @VV{H\Pi_0(p^\ast\alpha)}V\\
    E @>>{\eta_E}> H\Pi_0(E)
    \end{CD}$$
Here $\Pi_0$ is the connected component functor while $H$ is its right adjoint, defined by taking copowers of $\mathbf 1$.
Definition. An object $E$ is Galois closed if every covering morphism $E^\prime \rightarrow E$ is split by $1_E$.
Definition. A covering morphism $p:E\rightarrow B$ is said to be a universal covering of $B$ if it's an effective descent morphism and $E$ is Galois closed.

For a universal covering morphism $p:E\rightarrow B$, how to prove $E$
  connected implies $B$ connected?

For a trivial covering morphism in the concrete setting of topological spaces, I know being of effective descent implies surjectivity. Since for trivial covering morphisms, the connected components of the total space are duplicates of connected components of the base (with multiplicity given by the size of the fiber), it's clear that in the surjective case the total space has at least as many connected components as the base space and that finishes the proof.
However, for the nontrivial case, and more generally, for the nontrivial case in a general setting, I'm clueless. Help!
Added. My question arises from two statements in Borceux and Janelidze's Galois Theories which together confuse me. On one hand, at the top of p.213, the authors write

... is defined only for connected spaces $B$ which admit a universal covering map $p:E\rightarrow B$ with connected $E$...

On the other hand, the beginning of theorem 6.7.4 reads:

Let $p:E\rightarrow B$ be a universal covering morphism with connected $E$ (and therefore also connected $B$).

The latter makes it seem that the connectedness of $B$ is redundant in the former, and, of course - I don't know how to prove it.

Related

A: A groupoid is connected if and only if the diagram below is a coequalizer, since it means all objects are connected by arrows.
$$\mathsf{Arr}(\mathsf G)\rightrightarrows \mathsf{Ob}(\mathsf G)\rightarrow \mathbf 1$$
$B$ is connected if and only iff $\Pi_0B=\bf 1$. Hence, as the authors write in the proof of Lemma 6.7.1, $\mathsf{Gal}[p]$ is connected if and only if the diagram below is a coequalizer.
$$\Pi_0(E\times _BE)\rightrightarrows \Pi_0(E)\rightarrow \Pi_0(B)$$
If $E$ is connected, the groupoid is a group and in particular connected, so
$$\Pi_0(E\times _BE)\rightrightarrows \Pi_0(E)\rightarrow \bf1$$
is a coequalizer.
Now, $E\times _BE\rightrightarrows E\rightarrow B$ is a coequalizer diagram because $p$ is of effective descent and $\Pi_0$ preserves coequalizers as a left adjoint, so $\Pi_0(B)\cong \bf 1$, i.e $B$ is connected, as desired.

A: Here is a general claim: in an extensive category $\mathbf{C}$, if $p: E \to B$ is an epimorphism and $E$ is connected (i.e., $\hom(E, -): \mathbf{C} \to \text{Set}$ preserves finite coproducts), then also $B$ is connected.
Lemma: If a coproduct inclusion $i_U: U \to U + V$ is epic, then $V$ is initial. Proof: let $i_1, i_2: V \rightrightarrows V + V$ be the two coproduct inclusions. Then $i_U$ equalizes $U + i_1, U + i_2: U + V \rightrightarrows U + V + V$. Hence $U + i_1 = U + i_2$ since $i_U$ is epic. Pulling back these arrows along the coproduct inclusion $V + V \to U + (V + V)$, we deduce $i_1 = i_2$ since we are in an extensive category. By disjointness of coproduct inclusions, we find that $V$ is initial.
Proof of claim: It suffices to show that in any coproduct decomposition $B = U + V$, exactly one of $U, V$ is not initial. By connectedness of $E$, the map $p: E \to U + V$ factors through one of the summands, say the inclusion $i_U: U \to U + V$. But since $p$ is epic, so must be $i_U$. This forces $V$ to be initial by the lemma. And then $U$ must not be initial, else by strictness of initial objects, $E$ would be too (and initial objects are never connected).
More details at the nLab.


text:
Q: Download and open .APK file automatically on Mobile I have a button in my Native App(Cordova) :

Download

The button download is not working on mobile... And I would like, when download's finished, that the apk file opens automatically.

A: Problem seems like in your path. If you have the apk stored in somewhere in server, you can provide the path of the file.
For example

Download link

This will download the image specified in href tag.
Make sure your url starts with 'http'. If you didn't specify a path which didn't start with http, cordova will look for the file with respect to the root folder (where your index.html is located).
So if you simply specify

 Download link

This will look for the file myApp.apk inside the root folder of your app. The above code will work if your myApp.apk is indside your www folder.
www
---- index.html
---- myApp.apk
---- app.js
So based on the location of the file, you specify path.


text:
Q: Update existing post times to random times? I have found a code here that will randomize the date of all posts to a random date. Here is the code that someone has posted:
<?php
/**
 * Plugin Name: WPSE 259750 Random Dates
 * Description: On activation, change the dates of all posts to random dates
 */

//* We want to do this only once, so add hook to plugin activation
register_activation_hook( __FILE__ , 'wpse_259750_activation' );
function wpse_259750_activation() {

  //* Get all the posts
  $posts = get_posts( array( 'numberposts' => -1, 'post_status' => 'any' ) );
  foreach( $posts as $post ) {

    //* Generate a random date between January 1st, 2015 and now
    $random_date = mt_rand( strtotime( '1 January 2015' ), time() );
    $date_format = 'Y-m-d H:i:s';

    //* Format the date that WordPress likes
    $post_date = date( $date_format, $random_date );

    //* We only want to update the post date
    $update = array(
      'ID' => $post->ID,
      'post_date' => $post_date,
      'post_date_gmt' => null,
    );

    //* Update the post
    wp_update_post( $update );
  }
}

How would you do the same, but only randomize the time without randomizing the date of the post. So, the posts should keep the same date they currently have, but only randomize the time of the day they were posted.
I tried changing the post_date to post_time and changing the random_date to time() only. Then of course changing the date_format to 'H:i:s' however it did nothing.

A: This is the part that is responsible for random date:
//* Generate a random date between January 1st, 2015 and now
$random_date = mt_rand( strtotime( '1 January 2015' ), time() );

So you need to change it. And if you want to randomize only the time part, then this is one way to achieve that:
$random_date = strtotime( date( 'Y-m-d 00:00:00', strtotime($post->post_date) ) ) + mt_rand(0, 24*60*60);

This line will:

*

*take the date of post

*get only day part of it

*concert it to time

*add random number of seconds to it

So it will randomize the time of publication.

A: how can I set up a cronjob for this? My website has 10k post and I want to setup a cronjob to random date for 10k post each day?


text:
Q: HTML table stretches and not allow overflow I'm currently building a web app with vuetify, and i'm having an issue with a table that is taking me a lot of time. I'd like to have like a scroller on mobile that allow you to see the table while keeping the aspect ratio and not stretching itself. I'll post the code down here and a picture of how the table is showed in a mobile view. I already tried adding overflow: auto and overflow: scroll but nothing it's changing. Can you help me?
Code:

          Buca
          1
          2
          3
          4
          5
          6
          7
          8
          9
          10
          11
          12
          13
          14
          15
          16
          17
          18
          =
          +/-

          PAR
          5
          4
          3
          4
          5
          4
          4
          5
          3
          5
          4
          3
          4
          5
          4
          4
          5
          3
          72

          Score
          4
          4
          5
          5
          3
          7
          5
          4
          3
          9
          4
          3
          5
          4
          9
          5
          3
          3

          -9

And the css i tried using:
table#tabellaPunteggi{
  margin: 0 auto;
  border-collapse: collapse;
}

table#tabellaPunteggi tr td:not(.remove){
  width: 45px;
  height:45px;
}

table#tabellaPunteggi tr td {
  border: solid 1px black;
}

table#tabellaPunteggi tr td.remove {
  width: 75px;
}

Any help is appreciated!
Thanks for your time! Have a nice day!

Edit (28/01/2022):
I tried using your answers (i really appreciate them), but there is like another problem.
I screenshot it so you can see clearly at this link: https://imgur.com/a/AQfQdOz
Thanks for your help!

A: Set a min width on the td
you don't need the :not(.remove) since you set the width for .remove afterwards.
table#tabellaPunteggi tr td{
  min-width: 45px;
  height: 45px;
}

table#tabellaPunteggi tr td.remove {
  min-width: 75px;
}

This will keep things as is

A:
just update your this css lines as i updated for you

 table#tabellaPunteggi{ border-collapse: collapse; overflow: hidden; min-width:500px }


text:
Q: Problems with import ADASYN I try to import ADASYN on my MAC.but Here are some problems I can't fix.
my code:
from imblearn.over_sampling import ADASYN
And the problem is :

ImportError                               Traceback (most recent call last)
<ipython-input-89-48cae80b06ea> in <module>
----> 1 from imblearn.over_sampling import ADASYN

//anaconda3/lib/python3.7/site-packages/imblearn/__init__.py in <module>
     32     Module which allowing to create pipeline with scikit-learn estimators.
     33 """
---> 34 from . import combine
     35 from . import ensemble
     36 from . import exceptions

//anaconda3/lib/python3.7/site-packages/imblearn/combine/__init__.py in <module>
      3 """
      4
----> 5 from ._smote_enn import SMOTEENN
      6 from ._smote_tomek import SMOTETomek
      7

//anaconda3/lib/python3.7/site-packages/imblearn/combine/_smote_enn.py in <module>
      8 from sklearn.utils import check_X_y
      9
---> 10 from ..base import BaseSampler
     11 from ..over_sampling import SMOTE
     12 from ..over_sampling.base import BaseOverSampler

//anaconda3/lib/python3.7/site-packages/imblearn/base.py in <module>
     14 from sklearn.utils.multiclass import check_classification_targets
     15
---> 16 from .utils import check_sampling_strategy, check_target_type
     17 from .utils._validation import ArraysTransformer
     18

//anaconda3/lib/python3.7/site-packages/imblearn/utils/__init__.py in <module>
      5 from ._docstring import Substitution
      6
----> 7 from ._validation import check_neighbors_object
      8 from ._validation import check_target_type
      9 from ._validation import check_sampling_strategy

//anaconda3/lib/python3.7/site-packages/imblearn/utils/_validation.py in <module>
     11
     12 from sklearn.base import clone
---> 13 from sklearn.neighbors._base import KNeighborsMixin
     14 from sklearn.neighbors import NearestNeighbors
     15 from sklearn.utils import column_or_1d

//anaconda3/lib/python3.7/site-packages/sklearn/neighbors/_base.py in <module>
     25 from ..metrics.pairwise import PAIRWISE_DISTANCE_FUNCTIONS
     26 from ..utils import check_X_y, check_array, gen_even_slices
---> 27 from ..utils import _to_object_array
     28 from ..utils.multiclass import check_classification_targets
     29 from ..utils.validation import check_is_fitted

ImportError: cannot import name '_to_object_array' from 'sklearn.utils' (//anaconda3/lib/python3.7/site-packages/sklearn/utils/__init__.py)```

A: update your sklearn package to newer version


text:
Q: Looking for a post-apocalyptic movie about a man who is alone after an 'event' I vaguely recall this film from when I was young. It has stuck in my mind and is probably at least partly responsible for my interest in post-apocalyptic films and literature.
The plot centred around an 'event' a flash of light or sound or something that had seemingly wiped out (vanished) all the humans on Earth. The narrative follows a lone man until he eventually finds some other survivors and they journey for a while. They then find a way to trigger the event, or the event happens again, and the film ends with the man truly alone.
I don't know any more details, but would love to find it again. Thanks!

A: You're probably remembering the visually stunning but awful The Quiet Earth.  From Wikipedia:

5 July begins as a normal winter morning near Hamilton, New Zealand. At 6:12 a.m., the Sun darkens for a moment, and a red light surrounded by darkness is briefly seen.
Zac Hobson (Bruno Lawrence) is a scientist working for Delenco, part of an international consortium working on "Project Flashlight", an experiment to create a global energy grid. He awakens abruptly; when he turns on his radio, he is unable to receive any transmissions. Zac gets dressed and drives into the deserted city. Investigating a fire, he discovers the wreckage of a passenger jet, but there are no bodies, only empty seats.

... and so on.