text:
Q: What is the proper way to save a slice of structs into Cloud Datastore (Firestore in Datastore Mode)? I want to save a slice of structs in Google Cloud Datastore (Firestore in Datastore mode).
Take this Phonebook and Contact for example.
type Contact struct {
  Key         *datastore.Key `json:"id" datastore:"__key__"`
  Email       string         `json:"email" datastore:",noindex"`
  Name        string         `json:"name" datastore:",noindex"`
}
type Phonebook struct {
  Contacts []Contact
  Title    string
}

Saving and loading this struct is no problem as the Datastore library takes care of it.
Due to the presence of some complex properties in my actual code, I need to implement PropertyLoadSaver methods.
Saving the Title property is straightforward. But I have problems storing the slice of Contact structs.
I tried using the SaveStruct method:
func (pb *Phonebook) Save() ([]datastore.Property, error) {
  ps := []datastore.Property{
    {
      Name:    "Title",
      Value:   pb.Title,
      NoIndex: true,
    },
  }
  ctt, err := datastore.SaveStruct(pb.Contacts)
  if err != nil {
    return nil, err
  }
  ps = append(ps, datastore.Property{
    Name:    "Contacts",
    Value:   ctt,
    NoIndex: true,
  })

  return ps, nil
}

This code compiles but doesn't work.
The error message is datastore: invalid entity type
Making a slice of Property explicitly also does not work:
func (pb *Phonebook) Save() ([]datastore.Property, error) {
  ps := []datastore.Property{
    {
      Name:    "Title",
      Value:   pb.Title,
      NoIndex: true,
    },
  }
  cttProps := datastore.Property{
    Name:    "Contacts",
    NoIndex: true,
  }
  if len(pb.Contacts) > 0 {
    props := make([]interface{}, 0, len(pb.Contacts))
    for _, contact := range pb.Contacts {
      ctt, err := datastore.SaveStruct(contact)
      if err != nil {
        return nil, err
      }
      props = append(props, ctt)
    }
    cttProps.Value = props
  }
  ps = append(ps, cttProps)

  return ps, nil
}

Making a slice of Entity does not work either:
func (pb *Phonebook) Save() ([]datastore.Property, error) {
  ps := []datastore.Property{
    {
      Name:    "Title",
      Value:   pb.Title,
      NoIndex: true,
    },
  }
  cttProps := datastore.Property{
    Name:    "Contacts",
    NoIndex: true,
  }
  if len(pb.Contacts) > 0 {
    values := make([]datastore.Entity, len(pb.Contacts))
    props := make([]interface{}, 0, len(pb.Contacts))
    for _, contact := range pb.Contacts {
      ctt, err := datastore.SaveStruct(contact)
      if err != nil {
        return nil, err
      }
      values = append(values, datastore.Entity{
        Properties: ctt,
      })
    }
    for _, v := range values {
      props = append(props, v)
    }
    cttProps.Value = props
  }
  ps = append(ps, cttProps)

  return ps, nil
}

Both yielded the same error datastore: invalid entity type
Finally I resorted to using JSON. The slice of Contact is converted into a JSON array.
func (pb *Phonebook) Save() ([]datastore.Property, error) {
  ps := []datastore.Property{
    {
      Name:    "Title",
      Value:   pb.Title,
      NoIndex: true,
    },
  }
  var values []byte
  if len(pb.Contacts) > 0 {
    js, err := json.Marshal(pb.Contacts)
    if err != nil {
      return nil, err
    }
    values = js
  }
  ps = append(ps, datastore.Property{
    Name:    "Contacts",
    Value:   values,
    NoIndex: true,
  })

  return ps, nil
}

Isn't there a better way of doing this other than using JSON?

A: I found this document and it mentions src must be a struct pointer.

A: The only reason you seem to customize the saving of PhoneBook seems to be to avoid saving the Contacts slice if there are no contacts. If so, you can just define your PhoneBook as follows and directly use SaveStruct on the PhoneBook object.
type Phonebook struct {
  Contacts []Contact `datastore:"Contacts,noindex,omitempty"`
  Title    string `datastore:"Title,noindex"`
}


text:
Q: How do I get outer divs to stack properly when there is absolute positioning inside the first one? I am confused on how to get these divs to stack the way I want them to. I can't get the main content div (.innerdiv2) to stack below the first header div (.innerdiv1) that has/involves absolute positioning (so that the one image is on top of the other).
I also need to refrain from using fixed height on the image. This is the suggestion I have found most when searching for related posts and solutions. But I don't want that (fixed height) to lock in where the second div starts on the page. If the screen is sized down then I want the two header images to size down proportionally, which means they will decrease in height and the second div should start higher, which is why I don't want to use fixed height. Is this possible?
Here is the code I am working with:

  .maindiv {
    position: relative;
  }

  .innerdiv1 {
    max-width: 975px;
    width: 100%;
  }

  .imgbg {
    position: absolute;
    z-index: 102;
    max-width: 975px;
    width: 100%;
  }

  .imglogo {
    position: absolute;
    z-index: 103;
    margin-left: 40px;
    margin-top: 20px;
    width: 33%;
  }

  .innerdiv2 {
    position: relative;
    width: 100%;
  }

  .tbl1 {
    width: 100%;
    max-width: 975px;
    " border="0" cellpadding="0" cellspacing="0;
  }

  .imgfooter {
    width: 100%;
    max-width: 975px;
    position: relative;
    cursor: pointer;
  }

        <img class="imglogo" src="data:image/jpeg;base64,[encoded data, 9132 characters]">

                1. Lorem ipsum dolor sit amet, consectetur adipiscing elit. Fusce ultrices justo justo, ac consequat arcu pellentesque id. Nulla hendrerit dui vitae neque venenatis consequat. Morbi justo eros, dictum et enim et, pellentesque fermentum augue. Aliquam
                non sapien eros. Sed auctor enim ac blandit rhoncus. Vivamus condimentum ex nulla, quis laoreet risus sodales quis. Vivamus interdum aliquam ultricies. Donec consectetur turpis et vehicula hendrerit. Fusce ac dui nec odio convallis malesuada
                id ultricies lectus.

                2. Nam mi enim, bibendum id porttitor quis, posuere ac arcu. Donec pulvinar enim nec gravida accumsan. Fusce enim risus, laoreet nec venenatis aliquam, feugiat a sapien. Aenean vulputate fermentum ex, at cursus diam cursus vel. Vivamus maximus velit mi,
                ut auctor libero hendrerit ut. Donec vel pharetra nulla. Aenean imperdiet elementum felis vel finibus. Aenean eu luctus velit, nec accumsan velit.

                3. Nullam pharetra orci nec lacinia bibendum. Ut tortor dolor, feugiat sed nulla ac, ultricies vehicula mi. Donec in arcu tincidunt, convallis lectus eu, ornare eros. Duis mollis ultrices lacus vulputate iaculis. Quisque urna lorem, consectetur in sollicitudin
                ut, volutpat et ex. Integer finibus malesuada ipsum, eget consequat nulla interdum et. Maecenas ullamcorper ante turpis, vitae mattis libero ultricies a. Duis bibendum sapien vitae molestie interdum.

                4. Vestibulum cursus ipsum augue, eget consequat dui ullamcorper sed. Phasellus a ligula eu tellus posuere tristique quis eu odio. Nullam id est in orci pharetra tempus sed dictum sem. Phasellus vehicula iaculis augue ac scelerisque. Sed pretium eros
                sed tortor condimentum viverra. Quisque euismod sed ante eu facilisis. Quisque rhoncus auctor arcu at aliquet. Pellentesque eleifend leo at nisl fringilla sagittis. Sed augue erat, faucibus a nulla at, porttitor volutpat dui.

                5. Maecenas semper erat euismod, ultricies augue et, aliquam ipsum. Sed commodo diam a posuere tristique. Vestibulum placerat risus orci, vitae finibus libero vulputate sed. Vestibulum ac nulla maximus, lobortis turpis interdum, tempor lectus. Fusce pretium
                scelerisque viverra. Vestibulum aliquam at ex eget sollicitudin. Proin in vehicula velit. Nam eget metus sed dui lobortis pulvinar sit amet sed tortor. Aliquam eu nunc a tortor ultricies euismod.

https://jsfiddle.net/b2tngLym/8/

A: EDIT : See this fiddle
      .imgbg { width: 100%; }
      .innerdiv1 {
        max-width: 975px;
        width: 100%;
        position: relative;
      }

      .imglogo {
        position: absolute;
        z-index: 103;
        margin-left: 40px;
        margin-top: 20px;
        width: 33%;
        left: 0;
        top: 0
      }

redpajama_set_name: RedPajamaStackExchange


text:
Q: django custom manager result rearranging I have the list of all countries. When I need to get the list of English speaking countries i do:
Country.objects.filter(lang='English')

Which  works great. However, I want to let say have US and Canada to show up at the start of the list at all times, as my primary focus is in North America.
Now, should I do the query in a custom manager and remove the two countries from the list and insert them at the start or should I have a template tag that takes a list and returns a rearranged list.
It would have been nice to have used sort_by to do this, and I don't mind to overwrite some function to get the job done.
Sample code is appreciated.


text:
Q: Uncaught ReferenceError: WE is not defined in WebGL Earth I'm implementing WebGL Earth on my local system i'm getting this error
Uncaught ReferenceError: WE is not defined

I have checked this link also
https://codepen.io/sketchpads/pen/WRVrQK?editors=1111
still getting the same error

Uncaught ReferenceError: WE is not defined   at
https://cdpn.io/cp/internal/boomboom/pen.js?key=pen.js-1cdbdb91-b3f9-3e06-0627-7cd650ea5199:3

http://examples.webglearth.com/#helloworld

Code:

    <meta charset="utf-8" />

Any help is highly appreciated. Thanks


text:
Q: IIS7 - What permission to grant to which account, and where? I need my ASP page (intranet) to read files from another local Windows server.
I know that IIS7 has different system user accounts which it uses depending on the security context etc. but to be honest I don't really get it!
What I'd like to know is, what permission do I need to grant to what account, and where.
Also if possible, How :)
Ideally I really only want the minimum permission required to do this.
If it helps, the site is called with purely anonymous access as security is handled elsewhere.
Thanks, and I'd be happy to provide more info although you might need to help me get it :)

A: By default, IIS refuses to serve content originating from UNC locations over plain HTTP - it requires you to use SSL and authentication.
While you can hack this by running the web page under an account that already has access to the UNC share, you should instead consider the wider security implications: this account probably has more access to the UNC content than the web page needs, so it represents a decrease in overall security.
Start by defining your security requirements, then implement them using the least possible set of permissions.
Following the reverse path does not guarantee any level of security.


text:
Q: Springdata MongoDB automatically generates and undesired unique index in subdocuments I and storing Doc objects in the mongodb repository ensuring that the barcode property is unique across the collection:
@Document(collection = "Doc")
public class Doc {
  @Id
  private String id;

  @Indexed(unique = true)
  private String barcode;
  ...
}

I also store a DocAudit collection which stores lists of Doc as sub-documents:
@Document(collection = "DocAudit")
public class DocAudit {
  @Id
  private String id;

  private List<Doc> docs;
  ...
}

As DocAudit entries are generated, the same Doc can be present in the docs list of two or more DocAudit entries.
The @Indexed(unique = true) on the barcode property of the Doc object is automatically generating mongodb indexes on Doc.barcode (desired) and DocAudit.docs.doc.barcode (undesired)
What's the best way to avoid the automatic generation of the undesired index?
Alternatively, what's the best way to remove the undesired index as soon as it is created?

A: DocAudit is of course having these properties of Doc, because DocAudit is the inheritor.
To achieve what you want, you may consider one of following:

*

*create another Doc without that annotation, then inherited by DocAudit;

*remove that annotation in Doc, and ensure index for Doc by your independent codes (not recommended);

It's not good to create an index and then drop immediately.


text:
Q: Can not transfer an image of an icon from a JLabel to another I want to drag an image from an icon on a jlabel to drop it on another icon on a second jlabel. The problem is that some implementations of drag and drop Transferhandler methods do not seem to be called and I can not retrieve the image from the first jlabel's icon. Hope you will find the issue in my code.
class dndHandler extends TransferHandler implements Transferable {

    private final DataFlavor flavors[] = { DataFlavor.imageFlavor };

    private Image image;

        @Override
        public int getSourceActions(JComponent c) {
            System.out.println("test"); // Does not work
            return TransferHandler.COPY;
        }

        @Override
        public Transferable createTransferable(JComponent comp) {
            System.out.println("test"); // Does not work
             image = null;
             image = (Image)((ImageIcon) (((JLabel)comp).getIcon())).getImage(); //We transfer image //image stays null
             return this;
        }

        @Override
        public boolean canImport(JComponent comp, DataFlavor flavor[]) {
            if (!(comp instanceof JLabel)) {
                return false;
            }
            System.out.println("test"); //It works here
            return true;
        }

        @Override
        public boolean importData(JComponent comp, Transferable t) {
            if (comp instanceof JLabel) {

                    System.out.println(((JLabel)comp).getName()); //It works but the image is null
                    ((JLabel)comp).setIcon(new ImageIcon(image)); //The label stays empty
                    return true;
            }
            return false;
        }

        @Override
        public Object getTransferData(DataFlavor flavor) {
            if (isDataFlavorSupported(flavor)) {
                return image;
            }
            return null;
        }

        @Override
        public DataFlavor[] getTransferDataFlavors() {
            return flavors;
        }

        @Override
        public boolean isDataFlavorSupported(DataFlavor flavor) {
            return flavors[0].equals(flavor);
        }

    }

    MouseListener specialListener = new SpecialDragMouseAdapter();

    class SpecialDragMouseAdapter extends MouseAdapter {
        @Override
        public void mousePressed(MouseEvent evt) {
            JComponent comp = (JComponent)evt.getSource();
            TransferHandler th = comp.getTransferHandler();

            // Start the drag operation
            th.exportAsDrag(comp, evt, TransferHandler.COPY);
        }

    }

public class PrincipalFrame extends javax.swing.JFrame {

    TransferHandler dropHandler = new dndHandler();

    public PrincipalFrame()
    {
        JLabel label1 = new JLabel();
        JLabel label2 = new JLabel();

        label1.setName("label "+i+"-"+j);
        label1.setSize(50,50);
        label1.setBorder(BorderFactory.createLineBorder(java.awt.Color.black));
        label1.setIcon(new ImageIcon("put a file path on your computer"))
        label1.addMouseListener(specialListener);
        label1.setTransferHandler(dropHandler);

        label2.setName("label "+i+"-"+j);
        label2.setSize(50,50);
        label2.setBorder(BorderFactory.createLineBorder(java.awt.Color.black));
        label2.addMouseListener(specialListener);
        label2.setTransferHandler(dropHandler);
  }
}

public static void main(String args[]) {

    /*
     * Create and display the form
     */
    java.awt.EventQueue.invokeLater(new Runnable() {

        @Override
        public void run() {
            javax.swing.JFrame principalFrame = new PrincipalFrame();
            //Size of the window
            Dimension screenSize = Toolkit.getDefaultToolkit().getScreenSize();
            principalFrame.setSize(Toolkit.getDefaultToolkit().getScreenSize().width,
                                   Toolkit.getDefaultToolkit().getScreenSize().height-40);
            //Center the window
            principalFrame.setLocation(0,0);
            principalFrame.setVisible(true);
        }
    });
}

A: I'm sorry I'm only volunteer,
one error

second error

third error

.
then please read tutorial about Drag and Drop, example here


text:
Q: Rename levels using wildcard matching in r Is it possible to replace the levels using wildcard matching in R?
I have a column named years of experience values as "0 YEAR, 9 MONTHS",   "1 YEAR, 0 MONTHS",   "1 YEAR, 1 MONTHS",   "1 YEAR, 10 MONTHS", "1 YEAR, 9 MONTHS",   "10 YEAR, 0 MONTHS",  "10 YEAR, 1 MONTHS",  "10 YEAR, 10 MONTHS", like-wise nearly 600 levels; I wish to bucket all "0 YEAR... as "<1", 1 YEAR as "1", more than 5 YEAR as ">5", giving 5 levels in total.
grep("9 YEAR", data$Service, ignore.case = TRUE, value = TRUE)

Tried mutate and I can't exactly narrow down for each level, I expect only to get 5 or 6 levels finally.

A: First let's generate some random sample data
set.seed(2018)
x <- factor(paste(sample(0:10, 10, replace = T), "YEAR,", sample(0:11, 10, replace = T), "MONTHS"))
df <- data.frame(years_of_experience = x)
#   years_of_experience
#1     3 YEAR, 4 MONTHS
#2     5 YEAR, 7 MONTHS
#3    0 YEAR, 11 MONTHS
#4     2 YEAR, 8 MONTHS
#5     5 YEAR, 9 MONTHS
#6     3 YEAR, 7 MONTHS
#7     6 YEAR, 3 MONTHS
#8     1 YEAR, 6 MONTHS
#9    10 YEAR, 8 MONTHS
#10    6 YEAR, 9 MONTHS

Then we can use case_when to bin years_of_experience based on the years
df.new <- df %>%
    mutate(
        yr = as.numeric(gsub(" YEAR.*$", "", x)),
        bucket = case_when(
            yr < 1 ~ "<1",
            yr >= 5 ~ ">=5",
            TRUE ~ as.character(yr)))
df.new
#   years_of_experience yr bucket
#1     3 YEAR, 4 MONTHS  3      3
#2     5 YEAR, 7 MONTHS  5    >=5
#3    0 YEAR, 11 MONTHS  0     <1
#4     2 YEAR, 8 MONTHS  2      2
#5     5 YEAR, 9 MONTHS  5    >=5
#6     3 YEAR, 7 MONTHS  3      3
#7     6 YEAR, 3 MONTHS  6    >=5
#8     1 YEAR, 6 MONTHS  1      1
#9    10 YEAR, 8 MONTHS 10    >=5
#10    6 YEAR, 9 MONTHS  6    >=5

We can convert df.new$bucket to a factor which has 5 levels
df.new %>% mutate(bucket = as.factor(bucket)) %>% pull(bucket)
# [1] 3   >=5 <1  2   >=5 3   >=5 1   >=5 >=5
#Levels: <1 >=5 1 2 3


text:
Q: Align sticky menu under normal menu I am trying to have two sticky headers.
One is the menu and 1 should be the buy box of a product.
Unfortuantely right now the buy button is ABOVE the menu, and i need it to be below.
I have tried changing the css position but cannot seem to get it to work.
Does anybody have pointers on how I can get this to work?
Much appreciated!
Link:
https://www.agreenstory.de/shop/greenbook/greenbook-a4/
Edit:
This would be the situation I'd like:
http://agreenstory.de/like.jpg

A: The ideal thing would be to modify the javascript that is enforcing top: 0px to use values according to your case scenario.
But as I assume these are third party plugins, you can work-around it by applying  the following styles:
#osplugin-header-sticky .header-fixed {
    padding-top: 65px;
}

.fusion-header-wrapper {
    z-index: 200001;
}

Please let me know if that gives you the desired result. The black header still sticky-top right on the top edge, while the buy product call to action appears (when you scroll back) below it.

A: It is better to remove the fixed top position first:
<header class="oss-header-sticky  " style="top: 0px;">

Then you can move the div child element of this tag to a desire place , after closed of following tag:
<div class="fusion-header-v1 fusion-logo-left fusion-sticky-menu- fusion-sticky-logo-1 fusion-mobile-logo- fusion-mobile-menu-design-modern ">


text:
Q: Include referenced project's .config file Rather than excluding a file from the referenced output of an assembly, I want to add one!
I have a console application project (BuildTest1) that references a second class library project (ClassLibrary1). The Visual Studio solution looks like this:

I have a class library project that has an app.config. I want this .config file copied to the referring project's output, just like the .dll and .pdb files are. The config file for the class library is copied to the class library output directory as 'ClassLibrary1.dll.config'
I've tried adding this to the .exe project's .csproj file but it doesn't seem to make any difference:
  <PropertyGroup>
    <AllowedReferenceRelatedFileExtensions>
        .pdb;
        .xml;
        .config
    </AllowedReferenceRelatedFileExtensions>
  </PropertyGroup>

A: I was so close... I tracked this down to the MSBuild ResolveAssemblyReference task that is called from the ResolveAssemblyReferences target in Microsoft.Common.targets. This is what populates the ReferenceCopyLocalPaths item.
So looking at the pattern of files it was matching I discovered that the file extension .dll.config (rather than just .config) did the trick:
<PropertyGroup>
    <AllowedReferenceRelatedFileExtensions>
        .pdb;
        .xml;
        .dll.config
    </AllowedReferenceRelatedFileExtensions>
</PropertyGroup>


text:
Q: Connection failure - AWS RDS and mySQL Workbench I have setup numerous databases on AWS RDS SQL, however mySQL workbench fails to connect to the databases. I have read online that my machine IP address must be added to the security group of the database. However that option is not available.
If anyone can provide an insight into whether the security group can only be accessed with the premium plan with AWS RDS as i'm currently using the free tier
Thanks in advance

A:
Yes, you can access AWS RDS in workbench free tier also.

you need to fix some issue before connecting via workbench.
For access AWS RDS to the remote machine, you need to give Public Accessibility 'Yes' when you create AWS RDS instance.

Also, you need to add your public IP address in AWS RDS security group with port 3306 in inbound rule.

For more details click here: https://www.serverkaka.com/2018/09/connect-aws-rds-mysql-instance-with-phpmyadmin.html


text:
Q: Photos trim tool reducing the clip's fps Whenever I use the Photos app on Windows 10 to trim a .mp4 video, it seems that the output trimmed video is of a substantially lower framerate. Is there any workaround or fix for this?

A: You don't have much control over the Photos app, nor are you the only one to complain
about its generated video quality.
The only solution is to use a better software.
If trimming is the only operation, you may use for example
Lossless Cut,
advertising itself as "The swiss army knife of lossless video/audio editing".
Or see the article
Best Free Video Cutter and Joiner.

A: FIX: INSTEAD OF SELECT "TRIM", SELECT "SLOW MOTION", TRIM THE VIDEO IN THAT OPTION AND MOVE THE SLOW MOTTION EFFECT TO 0 in the top, save and ready. 60fps or whatever you have.


text:
Q: PHP isset function for submit check not working I have just discovered that the isset function is no longer working on my login and register forms. Very strange I though, so I undid everything that I had recently done to see if it was causing it but no luck. If i remove the isset and replace with this;
if($_SERVER['REQUEST_METHOD'] == "POST"){

it works! But I have two forms on one page so I need to check which one is submitted.
Here's the isset function:
if (isset($_POST['submit_login'])) {

And the submit button just so you know it has the correct name;
<input type="submit" name="submit_login" value="Login" class="buttonClassic"/>

The one for the register form is exactly the same but with name submit_reg.
Form:
<form action="<?php echo htmlentities('Login'); ?>" method="post" id="login">

Already signed up? Log in

   Your email address <input type="email" required name="email" placeholder="Email" class="text" id="email">
   Your password <input type="password"  name="pass" required placeholder="Password" class="text" id="password">
   <input type="submit" name="submit_login" value="Login" class="buttonClassic"/>

Forgotten your password?

</form>

reg form:
<form action="<?php echo htmlentities('Login'); ?>" method="post" id="register" >

New to NBS? Sign up, it's free!

   What's your email address? <input type="email" name="email" required placeholder="Email" class="text" id="reg_email">
   Choose a password <input type="password" required name="pass" placeholder="Password" class="text" id="reg_password">
   Re-type password <input type="password" required name="pass2" placeholder="Re-type password" class="text" id="reg_password2">
   <input type="checkbox" name="subscribed" value="subscribed" id="subscribed">Yes, send me email updates from NewBorn Sounds.

   <input type="checkbox" required="flag" name="terms" value="ticked" id="terms">I agree to the terms & conditions.

   <input type="submit" name="submit_reg" value="Sign Up" class="buttonClassic">
</form>

If you need anything more just shout!
Oh and I know I could just submit the form to an external PHP script but I don't particularly want to do that as I would like the user input errors to be outputted to the same page. I know I could just use ajax, which I do, but I am trying to keep javascript as an add-on and not reduce the user experience for no js.
Full HTML:

<form action="Login" method="post" id="login" novalidate="novalidate">

Already signed up? Log in

   Your email address <input type="email" required="" name="email" placeholder="Email" class="text" id="email">
   Your password <input type="password" name="pass" required="" placeholder="Password" class="text" id="password">
   <input type="submit" name="submit_login" value="Login" class="buttonClassic">

Forgotten your password?

</form>

<form action="Login" method="post" id="register" novalidate="novalidate">

New to NBS? Sign up, it's free!

   What's your email address? <input type="email" name="email" required="" placeholder="Email" class="text" id="reg_email">
   Choose a password <input type="password" required="" name="pass" placeholder="Password" class="text" id="reg_password">
   Re-type password <input type="password" required="" name="pass2" placeholder="Re-type password" class="text" id="reg_password2">
   <input type="checkbox" name="subscribed" value="subscribed" id="subscribed">Yes, send me email updates from NewBorn Sounds.

   <input type="checkbox" required="flag" name="terms" value="ticked" id="terms">I agree to the terms & conditions.

   <input type="submit" name="submit_reg" value="Sign Up" class="buttonClassic">
</form>

A: maybe you could do something like this :
if($_SERVER['REQUEST_METHOD'] == "POST"){
 if (isset($_POST['submit_login'])) {
    //do something
 } else {
   //do something else
 }

}

A: Form action needs to be a valid url, e.g. "/login.php".
Checkboxes have either the value given (once checked), or they do not appear at all. Best is to double check them: "isset($_POST['mycheckbox']) && 'value' ==$_POST['mycheckbox']".
Show us the php you use to evaluate the form.

A: How this?
<input type="submit" name="submit_reg" value="Sign Up" class="buttonClassic">
<?php
if($_POST['submit'] == 'Sign Up'){
  //do something
}
?>


text:
Q: If electrons lack internal structure, how are there also positrons? How is charge "stored" if there is no internal structure?

A: The thing we describe as charge is a coupling constant between two quantum fields. All elementary particles are described by a quantum field, and for a quantum field the charge is the strength of the interaction with the photon quantum field. So it is a fundamental property of the field, not some variable that needs storing.
I suspect the confusion has arisen because electrons and positrons are described by different quantum fields and those fields have different values for the charge. It is not the case that there is one single field and we have to somehow store the value of the charge differently for particles and antiparticles.

A:
How is charge "stored" if there is no internal structure?

One has to realize that physics is the tabulation of observations in nature using mathematical models, which are called theories, by imposing on the models extra axioms called laws , postulates, principles . The theories are validated if they can predict new observations. And these physics theories are valid in specific regions of the variables, not for all space and all time.
Electrons and positrons belong to the quantum mechanical frame , which,  present day mainstream physics postulates is the underlying frame from which all other theories emerge in the appropriate limits.
Observations and data since last century, have solidified at present to the standard model of particle physics where it is axiomatically assumed that the elementary particles (and corresponding antiparticles) are point particles with the assigned charge in the table.
Axiomatic means that "there can be no question", the theory hangs together assuming the axioms are true. If it is a bad theory, it will fail in predicting new data and observations, BUT the standard model is continually validated by new data.

If electrons lack internal structure, how are there also positrons?

All elementary particles in the table lack internal structure and all charged ones have an antiparticle with the same mass and the negative charge. It is an observationally validated fact .
It may be that in the future , people working on deterministic theories that attempt to fit the same data as the quantum mechanical theories, but give internal structure to what are considered point particles now, may succeed. BUT the new theories must embed the successes of quantum mechanics in modelling nature, and either use similar axioms for charge for elementary internal constituents, or  have in the theory a mechanism for generating charge. At present the charge of elementary particles is assigned axiomatically, in order to fit data and observations. That is why the positron has the opposite charge of the electron.


text:
Q: Is there javascript equivalent to R's use of ":" for returning a string of numbers between the numbers on either side of the colon? I am currently learning javascript, but I come completely from an R background (primarily coded for multivariable statistics). I was wondering if there was some equivalent to R's use of : in javascript.
For example, in R Studio, I can simply type 2:6 in order to get a string of numbers from 2 to 6 (ie: R Studio would output [2, 3, 4, 5, 6]).
Currently, I've had to create a whole function that does it, which isn't very efficient, nor would it be convenient when coding for larger projects. Also, if there IS a javascript equivalent, I'm hoping that it would work with functions/functions of objects, and not just integers.
Ex of what I mean: In R, typing Data2 = table(myData[2:4,(1:ncol(myData)),]) would create a table "Data2" using not ONLY rows 2, 3, 4 of myData, but ALSO use the columns from 1 THROUGH the end of the number of columns in myData. So basically, I'm hoping that it'd be able to use other functions within it.
I really hope that makes sense! If not, please don't hesitate to ask me to clarify!


text:
Q: jQuery Get Class Name I'm trying to get the class name from an selection of images when clicked.
The code below retrieves the first images class name but when I click on my other images with different class values they display the first images class.
How can I get each images class value?
HTML

jQuery Code
    $(".bg").click(function(){
        var1 = $('.bg img').attr('class');

A: Try this instead:
$(".bg").click(function(){
    var1 = $(this).children('img').attr('class');

A: Try:
$(".bg").click(function(){
    var1 = $(this).attr('class');
});

The above might, on reflection, not be quite what you're after. I'd suggest trying:
$('.bg img').click(  // attaches the 'click' to the image
    function(){
        var1 = $(this).attr('class');
    });

Or:
$(".bg").click(function(){
    var1 = $(this).find('img').attr('class'); // finds the 'img' inside the 'a'
});


text:
Q: Issue with docker image websphere9, console not work when expose others ports I'm build the docker image from 135353539817.dkr.ecr.sa-east-1.amazonaws.com/websphere:9.0.0.11, and the console only works when I expose the default ports 9080/9043, when a try mapping the default 9043 to 9143 for example by compose or docker run, its not works.
I'm tried change the serverindex.xml and virtualhosts.xml, but din't  works too!
Someone had this issue or something like this?
Thanks.

A: This is a limitation of WebSphere. The admin console port will have to be exposed on 9043 only. In general, you shouldn't be using the admin console very much when using WebSphere in a container, because none of the settings you change will be saved if the container needs to restart for some reason since the original image the container was created from remains unchanged.
Have a look at the recommended best practices for using the WebSphere image. This will help you use it in a way that works more smoothly for containers.


text:
Q: Disable enumeration of properties in JavaScript without ECMAScript 5 With ECMAScript 5 we have Object.defineProperty, which allows us to describe how a property should respond to some actions. One of the possibilites from this is to disable enumeration of properties, so they won't show up in for...in loops. For example the length property of arrays is not enumerable.
Is it possible to do something similar without ECMAScript 5?

A: It's not possibel to create non-enumerable properties in ECMA-262 ed 3, but you can emulate private members.


text:
Q: Nuxt.js - retrieving and storing bearer token server side I'm working on a Nuxt project (for the first time) where the API that I'm consuming requires us to authenticate via client oAuth2. The application holds the client ID & client secret but I don't want to expose this data to the user.
My plan is to retrieve the generated bearer token on the server side using the oAuth token endpoint. Then I can locally store the generated token on the filesystem and push it through to the user.
The problem I'm having is that I can't work out how best to store the bearer token. I've created a serverMiddleware that I'm trying to use FS to write the generated token to file. The problem with this is that I can't actually seem to use FS as it throws an error when being required in. I thought the idea of serverMiddleware is that it always runs on the server side?
I'm getting -
[HMR] bundle 'client' has 1 warnings
client.js?1b93:196 ./middleware/server/bearerToken.tsModule not found: Error: Can't resolve 'fs' in '/middleware/server'

Here's the middleware I've created -
const myServerMiddleware = (req, res, next) => {

    try {
        const fs = require('fs');

        // ToDo: read and/or generate bearer token

    } catch (e) {
        console.log('No FS available', e);
    }

    next();
};

export default {
    path: '/',
    handler: myServerMiddleware,
    mode: 'server'
};

And this is being loaded within my configuration using -
{
  serverMiddleware: [
    '@/middleware/server/bearerToken.ts'
  ],
}

I hope someone can point me in the right direction here!

A: For anyone in the same boat...
Server middleware didn't seem to cut it but normal middleware did. Thought this could be useful to someone...
Within my nuxt.config.js I've defined the API's authentication parameters and set the middleware that the router should use. These actually load from .env file at runtime:
    // Public variables
    publicRuntimeConfig: {
        apiUrl: process.env.API_URL,
        name: process.env.APP_NAME
    },

    // Private variables
    privateRuntimeConfig: {
        apiClientId: process.env.API_CLIENT,
        apiClientSecret: process.env.API_SECRET,
    },

    // Apply global middleware to our routing.
    router: {
        middleware: [
            'bearer-token'
        ],
    },

Now for the middleware. I've created a file called bearer-token.ts within the middleware folder which automatically enables it using the config above. It turns out at this stage of execution you can actually check whether we are at the server or client level by checking that process.server is truthy. As long as we are at the server level, we can manipulate the filesystem using node's fs package.
Here is my 'completed' middleware (in typescript)... Notice that I'm using the Vuex to store my generated key, this allows me to push the generated bearer token through to the user. I'm also updating the modification time of the generated file based on the token expiry so I can easily check when the token needs regenerating, saving excessive calls to the oAuth server.
import {Context} from '@nuxt/types';

const getToken = (context: Context) => {
    const axios = require('axios');

    return axios.post('/oauth/token', {
        grant_type: 'client_credentials',
        client_id: context.$config.apiClientId,
        client_secret: context.$config.apiClientSecret,
        scope: ''
    }, {
        baseURL: context.$config.apiUrl,
        headers: {'Accept': 'application/json'}
    });
}

export default function (context: Context) {

    // only perform this at the server level.
    if (process.server) {

        // set parameters needed.
        const fileName = './.apiToken',
            timestamp = Date.now(),
            fs = require('fs'),
            promise = new Promise(async (resolve, reject) => {

                try {
                    // get our stored files timestamps.
                    const data = fs.statSync(fileName);

                    // is our file timestamp in the future?
                    if (Date.now() < data.mtimeMs) {

                        // resolve our token from our file.
                        resolve(fs.readFileSync(fileName).toString());
                        return;
                    }
                } catch (err) {
                    // ignore this error (file not found)
                }

                try {
                    // grab our token from the oAuth server,
                    // we'll reduce the expiry timestamp by 10 mins
                    // to reduce near expiring tokens.
                    const res = await getToken(context),
                        expiryTime = timestamp + (res.data.expires_in - (60 * 10));

                    // write our file and sync the times.
                    fs.writeFileSync(fileName, res.data.access_token);
                    fs.utimesSync(fileName, new Date(expiryTime), new Date(expiryTime));

                    // resolve our promise with our generated token.
                    resolve(res.data.access_token);

                } catch (err) {

                    // ToDo: handle token retrieval failure...
                    console.log(err);
                }

            });

        // once our promise is resolved, set it against our store.
        promise.then(
            (token) => context.store.commit('bearerToken/setToken', token),
            // ToDo: better handling of errors...
            (err) => console.log(err)
        );
    }
}

This allows me to generate a bearer token at the server level and cache it, which I can then use with SSR or on the client-side.


text:
Q: Use the zeroes of T3 to construct an interpolating polynomial Use the zeroes of T3 to construct an interpolating polynomial of degree two for the function x^3 on the interval [-1,1]
Okay, so I have been looking at Finding the zeroes using Chebyshev polynomials which is similar, but not the same type of question.
The zeroes of T3(x)=4x3−3x are 0,±3√2.
Here is what I have tried.
$$\frac{(-\frac{\sqrt{3}}2)^3(x-0)(x-\frac{\sqrt{3}}2)}{(\frac{\sqrt{3}}2)(\frac{\sqrt{3}}2 + \frac{\sqrt{3}}2)} + (0)^3(other stuff) + \frac{(\frac{\sqrt{3}}2)^3(x-0)(x+\frac{\sqrt{3}}2)}{(\frac{\sqrt{3}}2)(\frac{\sqrt{3}}2 + \frac{\sqrt{3}}2)}$$
Am I doing this correctly? When I solve through this, it comes down to $\frac{0}{1.5}$

A: We have:
$$f(x) = x^3, ~x \in [-1,1]$$
No translation of the range is required here.
Using the zeros of Chebyshev polynomials for $T_3(x)$, we have:
$$T_3(x) = 4x^3 - 3x = x(4x^2 - 3) = 0 \implies x_0 = -\dfrac{\sqrt{3}}{2} , x_1 = 0, x_3 = \dfrac{\sqrt{3}}{2}$$
We now evaluate our function, $f(x) = x^3$ at those zero values and have:

*

*$f(x_0) = f\left(-\dfrac{\sqrt{3}}{2}\right) = -3 \dfrac{\sqrt{3}}{8}$

*$f(x_1) = f(0) = 0$

*$f(x_2) = f\left(\dfrac{\sqrt{3}}{2}\right) = 3 \dfrac{\sqrt{3}}{8}$

We can now set up and solve for the interpolating polynomial $q(x) = ax^2 + b x + c$ using the Vandermonde matrix as:
$$\begin{bmatrix}x_0^2 & x_0 & 1\\ x_1^2 & x_1 & 1\\ x_2^2 & x_2 & 1\end{bmatrix} \begin{bmatrix}a\\b\\c\end{bmatrix} = \begin{bmatrix}f(x_0) \\ f(x_1) \\ f(x_2)\end{bmatrix}$$
This gives us:
$$\begin{bmatrix}-\dfrac{\sqrt{3}}{2}^2 & -\dfrac{\sqrt{3}}{2} & 1\\ 0 & 0 & 1\\ \dfrac{\sqrt{3}}{2}^2 & \dfrac{\sqrt{3}}{2} & 1\end{bmatrix} \begin{bmatrix}a\\b\\c\end{bmatrix} = \begin{bmatrix}-3\dfrac{\sqrt{3}}{8} \\ 0 \\ 3\dfrac{\sqrt{3}}{8}\end{bmatrix}$$
This yields:
$$a = 0, b = \dfrac{3}{4}, c = 0$$
So, our interpolating polynomial is:
$$q(x) = \dfrac{3}{4} x$$
We can plot the original and interpolating function and have:


text:
Q: Trying to get current Timestamp with the following format YYYY-MM-DDTHH:MM:SS.MSSZ So i am trying to get the current Discord Webhooks's embedded Timestamp with the following format YYYY-MM-DDTHH:MM:SS.MSSZ(PHP) which will result in 2015-12-31T12:00:00.000Z
What I have done:
$timestamp = date('Y-m-d') . 'T' . date("H:i:s") . '.';
But really I couldn't complete that format MSSZ which results in 000Z

A: You can display milliseconds (added in PHP 7.0.0) like this.
echo date('Y-m-d').'T'.date("H:i:s").'.'.date("v").'Z';

wich will output the following:
2018-03-08T06:57:24.000Z

A: Another code to display milliseconds if using DateTime
(new DateTime())->format('Y-m-d\TH:i:s\.v\Z');


text:
Q: Paypal REST SDK - Billing Plans no longer retrievable after being made ACTIVE So I'm using the Paypal PHP SDK on Github, http://paypal.github.io/PayPal-PHP-SDK/ . Some strange behavior I've noticed which I'm not sure what's going on.
So let's say I create a billing plan, but don't touch it after creation, so that the state is simple CREATED. Everything is good, I can retrieve it from the list of plans. However, the moment I change the state to ACTIVE via a patch, I can see that it is in fact active, but only just once.  Any subsequent attempts to see the list of plans no longer shows that plan.  What's going on?  I'm literally copy pasting the example source they give.
Edit - just to expand, I know the plan still exists, because I can subscribe users to it.  Weirdly the paypal page where you click ok to subscribe is extremely non verbose... doesn't even say what the price is, just to approve paying my store.  And yet the Agreement object that is returned by PayPal, which includes the approval url, has all this info.  Weird.

A: If you are using the PayPal-PHP-SDK, you could assign more parameters to Plan::all() method.
As shown in the List Plan sample code, you could pass parameter 'status' as :
try {
    // Get the list of all plans
    // You can modify different params to change the return list.
    // The explanation about each pagination information could be found here
    // at https://developer.paypal.com/webapps/developer/docs/api/#list-plans
    $params = array('page_size' => '20', 'page' => '98', 'status' => 'ACTIVE');
    $planList = Plan::all($params, $apiContext);
} catch (Exception $ex) {
    ResultPrinter::printError("List of Plans", "Plan", null, $params, $ex);
    exit(1);
}

As in the case, you could change the status, and page along with page_size. This will help you get the active list of plans.
Actually, by default the list plan status is defaulted to CREATED.


text:
Q: Prestashop add product error : Property Product->link_rewrite is empty hello i'm tring to add new product to my prestashop store using REST api , but when i send my xml request i have this response: Validation error: "Property Product->link_rewrite is empty" !!!
this is my xml request :
xml=<?xml version="1.0" encoding="UTF-8"?>
<prestashop xmlns:xlink="http://www.w3.org/1999/xlink">
<product>
    <id/>
    <id_manufacturer/>
    <id_supplier/>
    <id_category_default/>
    <new/>
    <cache_default_attribute/>
    <id_default_image/>
    <id_default_combination/>
    <id_tax_rules_group/>
    <type/>
    <id_shop_default/>
    <reference/>
    <supplier_reference/>
    <location/>
    <width/>
    <height/>
    <depth/>
    <weight/>
    <quantity_discount/>
    <ean13/>
    <upc/>
    <cache_is_pack/>
    <cache_has_attachments/>
    <is_virtual/>
    <on_sale/>
    <online_only/>
    <ecotax/>
    <minimal_quantity/>
    <price>1000</price>
    <wholesale_price/>
    <unity/>
    <unit_price_ratio/>
    <additional_shipping_cost/>
    <customizable/>
    <text_fields/>
    <uploadable_files/>
    <active>1</active>
    <redirect_type/>
    <id_product_redirected/>
    <available_for_order/>
    <available_date/>
    <condition/>
    <show_price/>
    <indexed/>
    <visibility/>
    <advanced_stock_management/>
    <date_add/>
    <date_upd/>
    <meta_description><language id="1"/><language id="2"/></meta_description>
    <meta_keywords><language id="1"/><language id="2"/></meta_keywords>
    <meta_title><language id="1"/><language id="2"/></meta_title>
    <link_rewrite>hello</link_rewrite>
    <name>test name</name>
    <description>test description</description>

    <available_now><language id="1"/><language id="2"/></available_now>
    <available_later><language id="1"/><language id="2"/></available_later>
<associations></associations>
</product>
</prestashop>

please i'm waiting for any help

A: I got the solution. Go to classes >> controller >> AdminController.php
See the function copyFromPost
Find,
$languages = Language::getLanguages(false);
$class = get_class($object);
    $fields = $class->$definition['fields'];

    foreach ($fields as $field => $params) {
        if (array_key_exists('lang', $params) && $params['lang']) {
            foreach ($languages as $language) {
                if (isset($_POST[$field.'_'.(int)$language['id_lang']])) {
                    $object->{$field}[(int)$language['id_lang']] = $_POST[$field.'_'.(int)$language['id_lang']];
                }
            }
        }
    }

Replace with,
$rules = call_user_func(array(get_class($object), 'getValidationRules'), get_class($object));
    if (count($rules['validateLang']))
    {
        $languages = Language::getLanguages(false);
        foreach ($languages as $language)
            foreach (array_keys($rules['validateLang']) as $field)
                if (isset($_POST[$field.'_'.(int)$language['id_lang']]))
                    $object->{$field}[(int)$language['id_lang']] = $_POST[$field.'_'.(int)$language['id_lang']];
    }

A:
The link_rewrite element is also language dependent. Try replacing:
<link_rewrite>hello</link_rewrite>

with:
<link_rewrite>
    <language id="1">hello</language>
    <language id="2">hello</language>
</link_rewrite>


text:
Q: undefined reference to `__gcov_flush' I am trying same,
http://www.linuxforums.org/forum/suse-linux/135465-gcov-g.html
Code from the link,
#include <iostream>

using namespace std;

void one(void);
void two(void);
void __gcov_flush(void);

int main(void)
{
  int i;

  while(true)
  {
        __gcov_flush();
        cout <<  "Enter a number(1-2), 0 to exit " << endl;
        cin >> i;

        if ( i == 1 )
           one();
        else if ( i == 2 )
           two();
        else if ( i == 0 )
           break;
        else
          continue;
  }
  return 0;
}

void one(void)
{ cout << "One is called" << endl; }

void two(void)
{ cout << "Two is called" << endl; }

but for me also it gives,
test.cpp:(.text+0x1d9): undefined reference to `__gcov_flush()'
collect2: ld returned 1 exit status

Tried the followings,
g++ -fprofile-arcs test.cpp
g++ -fprofile-arcs -g test.cpp
g++ -fprofile-arcs -ftest-coverage -g test.cpp
g++ -fprofile-arcs -ftest-coverage -g test.cpp -lgcov

I have also tried the "-lgcov" & "extern void __gcov_flush(void)" as mentioned in link above. I am currently on Ubuntu12.04 and g++ 4.6
So, I want to know if there is solution for this or gcov_flush doesnt work anymore.

A: I fixed this issue changing the settings.
Test Project --> Build Settings
Instrument Program Flow  = Yes

A: void __gcov_flush();

Since the code is compiled as C++, this declares the existence of a C++ function of that name. C++ functions are subject to name mangling, so the (C++) symbol is not found in the (C) link library, and the linker (rightfully) complains about it.
If you declare the function, declare it as a function with C linkage:
extern "C" void __gcov_flush();

This should do the trick.

Note the commend by Paweł Bylica -- __gcov_flush() has been removed in GCC 11, you should use __gcov_dump().


text:
Q: Need a Generic way to Create SEO friendly URL I have searched a lot and implemented many many Regular Expressions in my .htaccess file but can not succeed. How to find a generic way to make my URL SEO friendly?
Currently this is in my .htaccess file:
   RewriteEngine On
   RewriteCond %{REQUEST_FILENAME} !-f
   RewriteCond %{REQUEST_FILENAME} !-d
   RewriteRule ^(.*)$ index.php?page=$1 [L,QSA]

What I need to do is to change a URL like this:
http://localhost/abc/index.php?page=boats_for_sale

to this:
http://localhost/abc/boats_for_sale

Similarly, I want to hide all query strings in my URL.
How would I achieve that?

A: With something like that it work :
URL rewriting module activation
# Avoids problems with mod_rewrite
    Options +FollowSymlinks
# Activate rewriting module
    RewriteEngine on
# Set base URL directory rewrites
    RewriteBase /

Rewriting url parameters
RewriteRule ^abc/([a-zA-Z0-9_-]+)$ abc/index.php?page=$1

Plz read the rewrite mod bible :
http://httpd.apache.org/docs/2.0/mod/mod_rewrite.html


text:
Q: Is there a concise way to include php variables in HTML? All of the text on my page has to come from a translation file, so my markup is littered with stuff like <?php echo $translation; ?>.
For just one or two calls, it's fine, but when it's all over the page, it makes things awfully verbose. Is there a more concise way to include PHP variables in the markup? I can echo a heredoc, but then it removes all the IDE features for HTML editing like automatic indentation and highlighting.
Is there a way to just do something like {$translation} instead of <?php echo $translation ?>?

A: You can do
<?=$translation?>

If you have activated short_open_tag in your php.ini

A: You could use a template engine like smarty or twig. Smarty for example is supported in an IDE like netbeans.

A: Use a template language, like twig, it has builtin support for internatiolzation with a simple syntax.

A: If you want to keep "pure" PHP, you can use <?=$translation?>, or you can use a template engine, like Smarty. There are tons of those, just find one that suits you.

A: This should help you http://en.wikipedia.org/wiki/Template_engine_%28web%29


text:
Q: Why is cmake Visual Studio 2013 project not finding headers? I am using to build my project for Visual Studio 2013. It uses CUDA.
In order to add the headers to the project's path I am using cuda_include_directories(), however, VS intelliSense is not recognizing it. Why is that?
I can compile and I know this is not a big problem but it bugs me that intelliSense is marking the include red-underlined.
Any idea?


text:
Q: How to get method name in method decorator I have this decorator:
export function foo(prop: string = '') {
    return function (target, propertyKey: string, descriptor: PropertyDescriptor) {
        Reflect.defineMetadata(some-key, prop, target.constructor, descriptor.value.name)
    }
};

@foo('foofoo')
async someFunction() :Promise<number> {
}

when i run it in node all fine, but when i trying to run in the browser, the descriptor.value.name is empty.(Instead of 'someFunction')
So, there is  another way to get the method name in the browser?


text:
Q: script address in master page i use this code in master page:
<script src="Scripts/jquery.min.js" type="text/javascript"></script>
<script src="Scripts/jquery.cycle.all.js" type="text/javascript"></script>

<script type="text/javascript">
    $(document).ready(function () {
        $('#zome').cycle({
            fx: 'zoom',
            sync: false,
            delay: -2000
        });
     })
</script>

and i have default page and admin page: Default.aspx and Admin/Admin.aspx
javascript working in Default page but this code not working in admin page. plaes help me for path address in script.
i check this address, but is not ok!
/Scripts/jquery.min.js
And
~/Scripts/jquery.min.js

A: Try with:
<script language="javascript" src='<%# ResolveClientUrl("~/Scripts/MyScript.js")' type="text/javascript"/>

Replacing the path with and file names with your own files/folder names.

A: You can use ResolveUrl in the master page as follows
 <script type="text/javascript" src='<%= ResolveUrl("~/Scripts/jquery.min.js")%>'></script>

<script src='<%= ResolveUrl("~/Scripts/jquery.cycle.all.js")%>' type="text/javascript"></script>


text:
Q: PrimeNG add custom header text How i can here add my custom header text with icons and more?
<p-accordion>
<p-accordionTab header="Header 1">
   Content 1
</p-accordionTab>
<p-accordionTab header="Header 2">
    Content 2
</p-accordionTab>
<p-accordionTab header="Header 3">
    Content 3
</p-accordionTab>

A: Use
<p-accordionTab>
    <ng-template pTemplate="header">Header Content</ng-template>
    <ng-template pTemplate="content">Body Content</ng-template>
</p-accordionTab>

You can change the content


text:
Q: VBA add a number before a variable if matches certain conditions I am trying to update a weekly report. However for the calendar weeks between 1 and 9 i wish to attached 0 in-front.  So it shows "CW1- 14" instead of "CW1- 14" for example   I am trying to do it with if statesmen - so far unsuccessfully.
Dim week1 As String
week1 = Format(Date - 7, "ww")
'If week1 <= 9 Then
'week1 = Format(0, Date - 7, "ww")
'ElseIf week1 > 9 Then
'week1 = Format(Date - 7, "ww")
 'End If

 Dim long1 As String
long1 = Format(Date - 10, "yyyy")
Dim week2 As String
week2 = week1 - 4
Dim nameweek As String
nameweek = "CW" & week2 & " - " & "CW" & week1 & " " & long1

A: You can use the Format() twice.
Dim week1 As String
week1 = Format(Format(Date - 7, "ww"), "00")
' That would produce week1 = "01" or "09"


text:
Q: Cannot compare HTML string in karma/jasmine/PhantomJS test because of icon I have test which (should) checks if element html rendered by my factory is correct. However, this element contains material icon and it seems to be impossible to compare its HTML in this test.
Simplified test case:
describe( 'Compile: ', function () {
  it( 'compare two html strings and should be equal', function () {
    var mockEl = $( '' )
      ;
    expect( mockEl[0].outerHTML ).toBe(
      ''
    );
  } );
} );

In result I test throws error:
Expected ' to be ''.

This is how icon jQuery object text looks like in Chrome console:

A: Try comparing it using the unicode value like the following
expect( mockEl[0].outerHTML ).toBe(
  '\ue24b'
);


text:
Q: Access Ubuntu share from Windows 10 and Windows Server 2016 I've got problems with accessing shares of my Ubuntu machine from my Windows 10 PC.
I already tried to edit smb.conf:

min protocol = SMB2
max protocol = SMB2
client min protocol = SMB2
client max protocol = SMB2

Access still not working.
I tried to enable SMBv1 on my Windows 10 PC: Access still not working
The same trouble I got on Windows Server 2016.
I can access without problems from Windows 7 PCs, Windows Server 2012 R2 and Windows Server 2008 R2.
Which settings do I have to change on my Windows 10/Server 2016 machines?


text:
Q: Passing Button name between pages windows phone 8 I need a little help passing a button name/value to another page. Example
Page one has a button with name "Button 1".
Page two has a public string called "Passed-button-name".
When a user press a button one in page one, The string value in page will be same as the button name.
How will i go about creating this??
thanks in advance

A: You can use query string parameter for string variable like below :
NavigationService.Navigate(new Uri("/SecondPage.xaml?key=value", Urikind.Relative));
To get it on the target page:
protected override void OnNavigatedTo(NavigationEventArgs e)
{
    if (NavigationContext.QueryString.ContainsKey("key"))
    {
         string val = NavigationContext.QueryString["key"];
    }
}


text:
Q: Smooth damp or tween algorithm I would like to know an algorithm for smooth damp or as some people call it, tween. I would like it in Lua preferably but anything will help.
I have tried watching unity tutorials but can't transfer the code without a algorithm to substitute for the smooth damp function.

A: If I understand the question correctly, you're looking for an easing function. There is a Lua library that provides a set of easing functions on GitHub: https://github.com/EmmanuelOga/easing
An example would be:
local function inOutQuad(t, b, c, d)
  t = t / d * 2
  if t < 1 then
    return c / 2 * pow(t, 2) + b
  else
    return -c / 2 * ((t - 1) * (t - 3) - 1) + b
  end
end

Where t = time, b = begin value, c = change in value, and d = duration.
More information on these easing functions is available directly from Robert Penner here (this is where the function above is derived from): http://www.robertpenner.com/easing/


text:
Q: What is a U2E1 socket? I have a 2011 MacBook Air running Ubuntu 14.04 and would like to find out the CPU socket through software methods. To do so, I'm running sudo dmidecode -t 4, which yields, among other things, this:
Handle 0x000A, DMI type 4, 35 bytes
Processor Information
    Socket Designation: U2E1
    Type: Central Processor
    Family: Other
    Manufacturer: Intel(R) Corporation
    ID: A7 06 02 00 FF FB EB BF
    Version: Intel(R) Core(TM) i5-2467M CPU @ 1.60GHz
    Voltage: 0.0 V
    External Clock: Unknown
    Max Speed: 1600 MHz
    Current Speed: 1625 MHz
    Status: Populated, Enabled
    Upgrade: ZIF Socket
    L1 Cache Handle: 0x000C
    L2 Cache Handle: 0x000D
    L3 Cache Handle: 0x000E
    Serial Number: Not Specified
    Asset Tag: Intel(R) Core(TM) i5-2467M CPU @ 1.60GHz
    Part Number: Not Specified

I did find out something about ZIF sockets, and apparently they relate to the insertion technology (so it's not really the answer I'm looking for). I could not find any information about U2E1 sockets. I believe I'm dealing with either a Sandy Bridge or an Arrandale microarchitecture, but I'd still like to confirm it through the Terminal.

A: Honestly? I think that the information you're getting is incorrect.

*

*Officially intel only sells this processor in one socket type - the FCBGA1023 or BGA1023, which is soldered on, and its a sandy bridge based model.

*All macbook airs have soldered on processors -including the 2011 models. Even the core 2 based ones had a custom, soldered on processor

*The contemporary socket was the socket G2, and intel didn't seem to use any other socket types in that era.
I'd also add nearly every modern, post slot processor is probably ZIF - with older ones you had PGA with a locking lever, with modern ones you have LGA with the cage. In short, DMIdecode isn't really giving you accurate information in any sense.  As a soldered in chip, while there may be zero insertation force from the pick and place machine, removal and replacement may require considerably more force.
I suspect the U2E1 socket is roughly as mythical as a daylight loving grue, riding a unicorn into battle.
Interestingly dmidecode identifies my atom 230 as a core 2 solo family, so clearly there's issues with implimentation  (hell, no, its an in order design!)
Edit: Turns out that there's a marking saying U1PR next to the processor (thanks breakthrough!) - so it does designate the physical location of the processor, though it dosen't give you any clue to what it is, socketwise. Nonetheless some of the other data is still incorrect, and its quite useless for your specific needs


text:
Q: Autocompletar con PHP y MySQL muchas gracias por haberme ayudado con mis anteriores preguntas, me ha servido mucho su conocimiento, como he dicho en mis preguntas estoy aprendiendo sobre sistemas web y ahora me surge otra pregunta:
Resulta que tengo una base de datos de empleados en MySQL, y estoy registrando una información que hace referencia a incapacidades, ahora, en un campo donde se registra el nombre del empleado hago una consulta con el nombre completo del empleado y se autocompleta como lo necesito, pero, me gustaría que en otros campos como por ejemplo cédula o número de identificación se autocomplete de acuerdo con el nombre del empleado, para ser mas exactos si yo coloco en nombres Pepito Pérez el campo de cédula se llene automaticamente con la cédula de Pepito Pérez, todo esto ya almacenado en la base de datos de empleados.
la sentencia con la cual hago el input del nombre esta ligada a un script que me ayuda a autocompletar que es este:
<input name="nombres" id="nombres" class=" form-control span8 tip" type="text" required/>

Y el Script que según el id de ese input me autocompleta con busqueda es este:

Y tengo un archivo de colsulta.php donde realizo la consulta al respecto:
<?php
include("conn.php");
$palabraclave = strval($_POST['busqueda']);
$busqueda = "{$palabraclave}%";
$consultaDB = $conn->prepare("SELECT * FROM clientes WHERE nombres LIKE ?");
$consultaDB->bind_param("s",$busqueda);
$consultaDB->execute();
$resultado = $consultaDB->get_result();
if ($resultado->num_rows > 0) {
    while($registros = $resultado->fetch_assoc()) {
    $nombres[] = $registros["nombres"];
    }
    echo json_encode($nombres);
    }
$consultaDB->close();
?>

Entonces, no sé que podrían sugerirme para que los input que necesito que se llenen automaticamente lo hagan y el registro de estas incapacidades sea mucho más fácil y que se eviten errores al digitar.
Cualquier idea o ayuda será bienvenida, como también si necesitan algo mas del código pueden decirme.
Muchas gracias a todos y que tengan un buen día.

A: Creo que la mejor opción es recibir desde PHP todos los datos necesarios para administrar el usuario y debes configurar algunas opciones de Typeahead:

*

*display - Para especificar la propiedad que se mostrará y donde se realizarán las búsquedas

*template - Para crear el formato con el que se mostrarán los resultados, usando atributos de datos para guardar temporalmente la información adicional que requieras y se pueden acceder con $(elemento).data('nombre-de-atributo')

*callback -> onClickAfter - Para detectar cuando se seleccione una opción y poder actualizar otros elementos

En este fragmento de código no es necesario acceder a los atributos de datos, porque Typeahead usa el objeto del arreglo al ejecutar la función onClickAfter; de cualquier forma, lo dejo como referencia.

let data = [
    {nombres: 'Juan Pérez', cedula: 'abc123456789' },
    {nombres: 'José Gómez', cedula: 'xyz987654321' },
];
$(document).ready(function() {
    $('#nombres').typeahead({
        minLength: 1,
        maxItem: 10,
        // Definir propiedades que se van a mostrar y donde se hará la búsqueda
        display: ['nombres'],
        // Formato de resultados
        template: `<span data-cedula="{{cedula}}">{{nombres}}</span>`,
        // Origen de datos
        source: {data: data},
        callback: {
            // "Escuchar" clics en elementos de resultados
            onClickAfter: function (node, a, item, event) {
                // Actualizar valor de cédula
                $('#cedula').val(item.cedula);
            }
        }
    });
});
<link href="https://cdnjs.cloudflare.com/ajax/libs/jquery-typeahead/2.11.0/jquery.typeahead.min.css" rel="stylesheet"/>

<form id="form-country_v2" name="form-country_v2">

                Nombre: <input type="text" id="nombres" placeholder="Buscar">

                <button type="submit">

                </button>

        Cédula: <input type="text" id="cedula">

</form>

¿Qué necesitas cambiar?
Debes actualizar el código PHP para generar el arreglo con la información que vayas a usar para actualizar otros campos:
<?php
include("conn.php");
// Evita posibles errores definiendo antes el arreglo
$nombres = [];

$palabraclave = strval($_POST['busqueda']);
$busqueda = "{$palabraclave}%";
// En lugar de SELECT *, solicita solo los campos necesarios
$consultaDB = $conn->prepare("SELECT nombres, cedula FROM clientes WHERE nombres LIKE ?");
$consultaDB->bind_param("s",$busqueda);
$consultaDB->execute();
$resultado = $consultaDB->get_result();
if ($resultado->num_rows > 0) {
    while($registros = $resultado->fetch_assoc()) {
        // Agrega todo el registro, solo contiene los campos seleccionados en la consulta
        $nombres[] = $registros;
    }
}
// Siempre debes devolver un JSON, aunque sea arreglo vacío si no hay resultados
echo json_encode($nombres);
$consultaDB->close();

El resultado va a ser como el arreglo data del fragmento de código. Ahora, solo necesitas adaptar tu Javascript, dejando que Typeahead ejecute la petición AJAX y se configura de la misma forma que las peticiones de jQuery. Referencia: Typeahead -> opciones -> source:
        $(document).ready(function () {
            $('#nombres').typeahead({
                minLength: 1,
                maxItem: 10,
                display: ['nombres'],
                template: `<span data-cedula="{{cedula}}">{{nombres}}</span>`,
                source: { data: {
                    // Propiedad, no función, Typeahead hará la petición
                    ajax: {
                        // Misma configuración que $.ajax()
                        url: 'consulta.php',
                        data: 'busqueda=' + busqueda,
                        dataType: 'json',
                        type: 'POST'
                        // No es necesario "success:", a menos que quieras cambiar algo
                    }
                }},
                callback: {
                    onClickAfter: function (node, a, item, event) {
                        $('#cedula').val(item.cedula);
                    }
                }
            });
        });

Probablemente vayas a necesitar agregar algún otro campo de la tabla, tal vez ID, pero eso ya queda a tu criterio.


text:
Q: Prove metacyclic group is generated by two elements. Let $G$ be a metacyclic group. If we have a short exact sequence $1\to C_m\to G\to C_n\to 1 $ with $m,n\in \mathbb{N}$, then we have an epimorphism $\pi:G\to C_n$ but how can we conclude that $G=\langle a,b \rangle$ where $a$ is a generator of $\ker\pi$, a normal cyclic subgroup of order $m$ of $G$. Also, what about $b$, where will it come from? We know that $G/\ker\pi \cong C_n$, but why does kernel has to be cyclic and isomorphic to $C_m$.
Also, if $H\le G$, then why does there exist $c,d\in H$ with $H\cap\ \langle a \rangle=\langle c \rangle$ and $H=\langle c,d \rangle$.

A: Exactness at $G$ implies that the kernel of $\pi$ is equal to the image of the map $\psi : C_m\to G$. Exactness at $C_m$ implies that the kernel of $\psi$ is $1$, so $\psi$ is injective, and hence, $\ker\pi$ is isomorphic to $C_m$. Therefore, $\ker\pi=\langle a\rangle$, with $a\in G$ of order $m$.  Since $\langle a\rangle$ is normal in $G$, we have $C_n\simeq G/\langle a\rangle$. In other words, the quotient group $G/\langle a\rangle$ is cyclic of order $n$. Choose a generator $b\langle a\rangle\in G/\langle a\rangle$.  Every element of the quotient $G/\langle a\rangle$ is some power $b^k\langle a\rangle$ of the generator $b\langle a\rangle$, with $0\leq k<n$.  And so $G$ is the (disjoint) union of the cosets $b^k\langle a\rangle$ of $\langle a\rangle$.  But, for each such $k$, the coset $b^k\langle a\rangle$ is the set $\{ b^ka^i\mid 0\leq i < m\}$. In other words, every element of $G$ has the form $b^ka^i$, for some $i$ and $k$, which means that $G$ is generated by $a$ and $b$.


text:
Q: How to extract an attribute from an HTML element with Ant? I have an ANT configuration file which is becoming complicated, and now I'm stuck with an issue. One of the tasks retrieves a page from a website and saves it to a file. I need to load such file and extract from it the href attribute of a specific element. HTML is reasonably well formed, but I can't guarantee it.
I was thinking of a RegEx, but the element's attributes are not guaranteed to always appear in the same order (e.g. its class name, or id). Besides, I haven't found out how to just return the value of the href attribute, without the attribute itself.
I'm trying to limit the amount of addons to be added to ANT, therefore a "self-contained" solution would be welcome. Thanks.

A: I'm not sure how you're going to find the specific HTML element that has the href you're looking for (I'd assume by checking an id attribute, but you did not say so). I put together this chain of regex's to filter the HTML down to candidate anchor tags and then ultimately strip out just the href's.  I used the source of this page as my sample input and since I couldn't find any id attributes associated to anchors (that also had hrefs), I filtered down to anchors with the class="question-hyperlink" -- I'm hopeful this could be a good starting point for you (and note: as you stipulated, it does not contain any dependencies on additional modules, etc, regardless of how easy they are to install):
<?xml version="1.0" encoding="UTF-8"?>
<project name="Test Html attribute" default="test" basedir=".">
   <target name="test">

      <loadfile srcFile="ant.htm" property="html">
         <filterchain>
            <linecontainsregexp>
              <regexp pattern="<a.*href[^>]*>"/>
              <regexp pattern="<a.*class=["']question-hyperlink["'][^>]*>"/>
            </linecontainsregexp>
            <tokenfilter>
               <replaceregex pattern=".*<a.*href=["']?([^>"']*).*>[^<]*" replace="\1" flags="gi"/>
            </tokenfilter>
         </filterchain>
      </loadfile>

      <echo>${html}</echo>
   </target>
</project>


text:
Q: Sharepoint 2010 workflow failes with "0x80070057" I have created a simple Sharepoint 2010 site workflow that creates and manipulates tasks in a list.
All my activities execute properly, but when the workflow is about to get to the end (the red point in the diagram :)) some nasty exception happens.
Even with the exception the workflow is marked as complete.
I have tried to remove the last activities from the workflow because I thought they are causing the trouble, but the problem persists (this is the reason I think the problem is the finalization of the workflow itself and not my activities).
Have you encountered such problem and if you had how can I solve it?
Here are exception details:
Exception: System.Workflow.Runtime.Hosting.PersistenceException
InnerException: System.ArgumentException
InnerExceptionMessage:     <nativehr>0x80070057</nativehr><nativestack></nativestack>
Message: <nativehr>0x80070057</nativehr><nativestack></nativestack>
Stack Trace:

    at System.Workflow.Runtime.WorkflowExecutor.Persist(Activity dynamicActivity, Boolean unlock, Boolean needsCompensation)
    at System.Workflow.Runtime.WorkflowExecutor.System.Workflow.ComponentModel.IWorkflowCoreRuntime.PersistInstanceState(Activity activity)
    at System.Workflow.ComponentModel.Activity.MarkClosed()
    at System.Workflow.ComponentModel.Activity.ReleaseLockOnStatusChange(IActivityEventListener\`1 eventListener)
    at System.Workflow.ComponentModel.FaultAndCancellationHandlingFilter.SafeReleaseLockOnStatusChange(ActivityExecutionContext context)
    at System.Workflow.ComponentModel.FaultAndCancellationHandlingFilter.OnEvent(Object sender, ActivityExecutionStatusChangedEventArgs e)
    at System.Workflow.ComponentModel.ActivityExecutorDelegateInfo\`1.ActivityExecutorDelegateOperation.Run(IWorkflowCoreRuntime workflowCoreRuntime)
    at System.Workflow.Runtime.Scheduler.Run()


text:
Q: Not able to load partial view as modal when called from _Layout In my Core 2.0 project I am trying to load a partial view to modal div when called from _Layout.cshtml but nothing happens. On click of Create New User I am trying to load partial view on modal popup. Below is code-
//_Layout.cshtml

Home

About

Contact

Create New User

//Index.cshtml of Home

                <button type="button" class="close" data-dismiss="modal" aria-label="Close">
                    ×
                </button>

//Javascript
function CreateUser() {
            var url = appSetting + "Home/CreateUser";
            $.ajax({
                type: "GET",
                contentType: "application/json",
                url: url,
                data: null,
                dataType: "html",
                async: false,
                success: function (data) {
                    $("#ScheduleAppointment").html('');
                    $("#ScheduleAppointment").html(data);
                    $("#AppointmentSchedule").modal('show');
                },
                error: function (result) {
                    $("#divScheduleAppointment").html('');
                }
            })
        }

//Home Controller
  public ActionResult CreateUser()
      {
        return PartialView("_CreateUserHome");
      }

On debugging I realize that after Ajax success it calls Index action method of Home controller(that should not be) and may be it is causes page refresh and popup may get close. But what is it's solution.

A: With your current code, when user clicks on the anchor tag,  the browser do a normal link click behavior, which is navigating to the href attribute value of the clicked link element. If you want show the modal dialog instead of that, you should prevent this default behavior.
You may pass an event object to the CreateUser method
Create New User

and in your method, call the preventDefault method, which will stop the normal link click behavior(navigating to to the href value)
function CreateUser(e)
{
    e.preventDefault();

    var url = appSetting + "Home/CreateUser";
    $.ajax({
        type: "GET",
        url: url,
        success: function (data)
        {
            $("#ScheduleAppointment").html(data);
            $("#AppointmentSchedule").modal('show');
        },
        error: function (result)
        {
            $("#divScheduleAppointment").html('');
        }
    })
}

A suggestion: If it is not a navigational link, Consider using a button instead of an anchor tag.

A: Quick solution is to add return false to your event handler:

Create New User

This will suppress default behavior.


text:
Q: parse to JSON in node.js I have this Java code
DefaultHttpClient httpclient = new DefaultHttpClient();
        HttpPost httpPostRequest = new HttpPost(URL);
        StringEntity se;
        se = new StringEntity(jsonObjSend.toString());
        // Set HTTP parameters
        httpPostRequest.setEntity(se);
        httpPostRequest.setHeader("Accept", "application/json");
        httpPostRequest.setHeader("Content-type", "application/json");
        //httpPostRequest.setHeader("Accept-Encoding", "gzip");
        // only set this parameter if you would like to use gzip compression
        long t = System.currentTimeMillis();
        HttpResponse response = (HttpResponse) httpclient.execute(httpPostRequest);

and this in node.js
var http = require('http');
// Configure our HTTP server to respond with Hello World to all requests.
var server = http.createServer(function (request, response) {
console.log("Entering");

if ( request.method === 'POST' ) {

     // the body of the POST is JSON payload.
     request.pipe(process.stdout);
     }

});

// Listen on port 8000, IP defaults to 127.0.0.1
server.listen(8000);

// Put a friendly message on the terminal
console.log("Server running at http://127.0.0.1:8000/");

Im using the pipe to write everything in the console to be sure that i receive the data.
What i actually want is to parse the data back to JSON and then save it in a array.
How do i get the data from the request?
Does anyone have an code example?
Thanks

A: var http = require('http');
// Configure our HTTP server to respond with Hello World to all requests.
var server = http.createServer(function (request, response) {
console.log("Entering");

if ( request.method === 'POST' ) {

        // the body of the POST is JSON payload.
        request.pipe(process.stdout);

        var data = '';
        request.on('data', function(chunk) {
            data += chunk;
        });

        request.on('end', function() {
            try {
                data = JSON.parse(data);
            } catch (e) {
                console.log(e);
            }
        });
    }

});

// Listen on port 8000, IP defaults to 127.0.0.1
server.listen(8000);

// Put a friendly message on the terminal
console.log("Server running at http://127.0.0.1:8000/");

A: try to use the following concept in your code
        response.on('data', function (chunk)
        {
                var data = chunk.toString();
                var data_val = JSON.parse(data)
          });


text:
Q: Passing an ArrayList to a method in a separate class as argument ArrayList I don't know the best way to phrase my question, but I'm having trouble passing an ArrayList<class_that_implements_comparable> to a method in a different class as an argument ArrayList<Comparable>.
Let's say I have two ArrayLists in a driver class:
ArrayList<Person> peopleList;
ArrayList<Place> placeList;

Both the Person class and the Place class implement Comparable.
Then, in a class called Sorts, I have two methods:
public static void sort(ArrayList list){
  sortList(list);
}
public static void sortList(ArrayList<Comparable> list)
{
   //Code here
}

With this setup, I am able to call Sorts.sort(peopleList) and Sorts.sort(placeList) without any issue. It works perfectly.
However, if I change the signature of the sort method to have an argument of ArrayList<Comparable>...
public static void sort(ArrayList<Comparable> list){
  sortList(list);
}

I get the following error in my driver class:
Error:(59, 14) java: method sort in class Sorts cannot be applied to given types;
  required: java.util.ArrayList<java.lang.Comparable>
  found: java.util.ArrayList<Passenger>
  reason: actual argument java.util.ArrayList<Passenger> cannot be converted to java.util.ArrayList<java.lang.Comparable> by method invocation conversion

Why does java allow me to pass a generic ArrayList<> to another class using a non-generic ArrayList argument and then pass that ArrayList to another method using an ArrayList<Comparable> argument, yet it won't let me pass a generic ArrayList<> straight to an ArrayList<Comparable>?
And is there a way that I can convert it directly instead of having to use an extra method?
Thank you so much for your time and any insight you can provide!

A: You need pass something that implement Comparable itself or in superclass(or superclasses).
public static <T extends Comparable<? super T>> void sort(ArrayList<T> list)

When your method has signature static void sort(ArrayList list) it accept only instance of ArrayList.
If Person implement Comparable, it does not mean that List<Person> is subclass of List<Comparable>. So you need some extra moves to improve your method:

*

*allow all types that implemented Comparable T extends Comparable

*allow all types that inherited Comparable after superclasses Comparable<? super T>


text:
Q: Using ServiceStack Mini Profiler in self-hosted console application Is it possible to use ServiceStack Mini Profiler in self-hosted console application? If it is, where should I put profiler enable/disable code? In ASP.NET hosted ServiceStack it's usually in Application_BeginRequest and Application_EndRequest methods.

A: You could do it like this:
namespace ConsoleApplication1 {
  class Program {
    static void Main(string[] args) {
      // enable here

      // your code

      // disable here
    }
  }
}

or in the constructor and destructor like this:
namespace ConsoleApplication1 {
  class Program {
    Program() {
      // enable here
    }

    ~Program(){
      // disable here
    }

    static void Main(string[] args) {
      // your code
    }
  }
}

A: public abstract class MyHostBase : AppSelfHostBase
{
    this.GlobalRequestFilters.Add(OnBeginOfRequest);
    this.GlobalResponseFilters.Add(OnEnfOfRequest);
}


text:
Q: How to create cxf endpoint in camel without soapaction header validation? I'm trying to create service bus using camel and cxf component. Cxf endpoint should receive any soap  requests.
I have following snippet:
context.addRoutes(new RouteBuilder() {
  override def configure(): Unit = {
    from("cxf://http://localhost:7778?dataFormat=PAYLOAD&properties.mtom-enabled=true")
      .process(new Processor {
        override def process(exchange: Exchange): Unit = {
          // do something here
        }
      })
  }
})
context.start

But during requests I get following error:
org.apache.cxf.interceptor.Fault: The given SOAPAction queryINNFL does not match an operation
What can I do to make my endpoint receive all kind of soapaction headers?

A: You could try to implement CXF Interceptor and connect it to the interceptor inbound chain to the proper place in the endpoint. The individual phases and examples are described there. Your interceptor implementation could then imitate the required SoapAction value, to match the wsdl.


text:
Q: fetching document from iCloud giving me 3/4 content of that document not the full content I'm new to iPhone Development.
I have integrated iCloud storage in my application. I am successful in uploading documents on iCloud.
My document's size is around 126799 bytes. During uploading on iCloud I have made sure that a proper document is uploaded on iCloud by printing its length and content on the console. But when I am fetching document from iCloud it only gives me 3/4 of the content of that document. I have also checked this on console by printing its length and content.
/////====== variables are declared in interface file

- (BOOL)application:(UIApplication *)application didFinishLaunchingWithOptions:(NSDictionary *)launchOptions {

    NSURL *ubiq = [[NSFileManager defaultManager]
               URLForUbiquityContainerIdentifier:nil];
    if (ubiq)
    {
        NSLog(@"iCloud access at %@", ubiq);
        // TODO: Load document...
        [self loadDocument];
    }
    else
    {
        NSLog(@"No iCloud access");
    }
}

- (void)loadDocument{

     NSMetadataQuery *query = [[NSMetadataQuery alloc] init];
     _query = query;
    [query setSearchScopes:[NSArray arrayWithObject:NSMetadataQueryUbiquitousDocumentsScope]];

    NSString *filename = @"supplimentlistdescription.txt";
    NSPredicate *pred = [NSPredicate predicateWithFormat:@"%K like '%@'",filename,NSMetadataItemFSNameKey];
    [query setPredicate:pred];
    [[NSNotificationCenter defaultCenter]
        addObserver:self
        selector:@selector(queryDidFinishGathering:)
        name:NSMetadataQueryDidFinishGatheringNotification
        object:query];

    [query startQuery];
}

- (void)queryDidFinishGathering:(NSNotification *)notification {

    NSMetadataQuery *query = [notification object];
    [query disableUpdates];
    [query stopQuery];

    [[NSNotificationCenter defaultCenter] removeObserver:self
        name:NSMetadataQueryDidFinishGatheringNotification
        object:query];

    _query = nil;

    [self loadData:query];
}

- (void)loadData:(NSMetadataQuery *)query {

    if ([query resultCount] == 1)
    {

        NSMetadataItem *item = [query resultAtIndex:0];
        NSURL *url = [item valueForAttribute:NSMetadataItemURLKey];
        Note *doc = [[Note alloc] initWithFileURL:url];
        self.doc = doc;
        [self.doc openWithCompletionHandler:^(BOOL success)
            {
                if (success)
                {
                    NSLog(@"iCloud document opened");
                }
                else
                {
                    NSLog(@"failed opening document from iCloud");
                }
            }
        ];
    }
    else
    {

        NSFileManager *filemgr = [NSFileManager defaultManager];
        NSString *fileurlstring = [NSString stringWithFormat:@"Documents/Federal Rules of Civil Procedure"];
        NSLog(@"fileurlstring:%@",fileurlstring);
        ubiquityURL = [[filemgr URLForUbiquityContainerIdentifier:nil]
            URLByAppendingPathComponent:fileurlstring];
        [ubiquityURL retain];
        NSLog(@"ubiquityURL1:%@",ubiquityURL);

        if ([filemgr fileExistsAtPath:[ubiquityURL path]] == NO)
        {
            [ubiquityURL retain];

            [filemgr createDirectoryAtURL:ubiquityURL withIntermediateDirectories:YES attributes:nil error:nil];
            [ubiquityURL retain];

        }

        ubiquityURL = [ubiquityURL URLByAppendingPathComponent:@"supplimentlistdescription.txt"];
        [ubiquityURL retain];
        NSLog(@"ubiquityURL:%@",ubiquityURL);

        Note *doc = [[Note alloc] initWithFileURL:ubiquityURL];
        self.doc = doc;

        [doc saveToURL:[doc fileURL]
            forSaveOperation:UIDocumentSaveForCreating
            completionHandler:^(BOOL success)
            {
                if (success) {
                    [doc openWithCompletionHandler:^(BOOL success)
                        {
                            NSLog(@"new document opened from iCloud");
                        }
                    ];
                }
            }
        ];
    }
}

-
///Note.h
#import <UIKit/UIKit.h>
@interface Note : UIDocument

@property (strong) NSString * noteContent;
@end

-
#import "Note.h"
@implementation Note
@synthesize noteContent;

- (BOOL)loadFromContents:(id)contents ofType:(NSString *)typeName
    error:(NSError **)outError
{

    if ([contents length] > 0)
    {
        self.noteContent = [[NSString alloc]
                            initWithBytes:[contents bytes]
                            length:[contents length]
                            encoding:NSUTF8StringEncoding];
        NSLog(@"loadFromContents1");
        NSLog(@"noteContent:%@",noteContent);
        NSLog(@"noteContent.length:%d",noteContent.length);
    }
    else
    {
        // When the note is first created, assign some default content
        self.noteContent = @"Empty";
    }

    return YES;
}

- (id)contentsForType:(NSString *)typeName error:(NSError **)outError
{
    if ([self.noteContent length] == 0)
    {
        //self.noteContent = @"Empty";

        NSString *FolderName = @"Federal Rules of Civil Procedure";
        NSString *fileName = @"supplimentlistdescription.txt";

        NSArray *paths = NSSearchPathForDirectoriesInDomains(NSDocumentDirectory, NSUserDomainMask, YES);
        NSString *documentsDirectory = [paths objectAtIndex:0];
        [FolderName retain];
        NSString *fileName1 = [NSString stringWithFormat:@"%@/%@/%@",documentsDirectory,FolderName, fileName];
        NSLog(@"fileName1:%@",fileName1);

        NSData *data = [[NSData alloc]initWithContentsOfFile:fileName1];
        noteContent =[[NSString alloc]initWithData:data encoding:NSMacOSRomanStringEncoding];
        NSLog(@"noteContent:%@",noteContent);
        NSLog(@"noteContent.length:%d",noteContent.length);
    }

    return [NSData dataWithBytes:[self.noteContent UTF8String]
                      length:[self.noteContent length]];
}

@end

Can you please tell me whats can be the problem? Any suggestion will be appreciated. Thanks

A: I got a same problem like your before.
You should use
for writing
[self.noteContent dataUsingEncoding:NSUTF8StringEncoding];

for reading
self.noteContent = [[NSString alloc] initWithData:contents encoding:NSUTF8StringEncoding];

Example :
- (BOOL)loadFromContents:(id)contents ofType:(NSString *)typeName error:(NSError **)outError
{

    if ([contents length] > 0) {
        self.noteContent = [[NSString alloc] initWithData:contents encoding:NSUTF8StringEncoding];
    } else {
        self.noteContent = @""; // When the note is created we assign some default content
    }

    [[NSNotificationCenter defaultCenter] postNotificationName:@"noteModified"
                                                        object:self];

    return YES;

}

// Called whenever the application (auto)saves the content of a note
- (id)contentsForType:(NSString *)typeName error:(NSError **)outError
{

    if ([self.noteContent length] == 0) {
        self.noteContent = @"";
    }

    return [self.noteContent dataUsingEncoding:NSUTF8StringEncoding];

}


text:
Q: WPF ListView Style Borders Today i started teaching my self how to create a wpf application (finally)
So i am starting to get used to it but i have hit a bit of a snag with styling a listview.
In this top picture you can see it working perfectly (no border around the selection)

However in the second picture you can see a small border around the selection.. It seems this only happens when i use the keyboard to go to the next item in the list.
Is there something i am missing in the styles so i can get rid of this border?
Code: (remember i only started learning today so it is probably messy)
Listview Styles
<Style TargetType="{x:Type ListView}">
    <Setter Property="BorderThickness" Value="0" />
    <Style.Triggers>
        <Trigger Property="IsMouseOver" Value="True">
            <Setter Property="BorderThickness" Value="0" />
        </Trigger>
        <Trigger Property="IsSelected" Value="True">
            <Setter Property="BorderThickness" Value="0" />
        </Trigger>
    </Style.Triggers>
</Style>

<Style TargetType="{x:Type ListViewItem}">
    <Setter Property="BorderThickness" Value="0" />
    <Setter Property="Foreground" Value="#4b0037" />

    <Setter Property="Template">
        <Setter.Value>
            <ControlTemplate TargetType="{x:Type ListViewItem}">
                <Border
                     BorderBrush="Transparent"
                     BorderThickness="0"
                     Background="{TemplateBinding Background}">
                    <GridViewRowPresenter HorizontalAlignment="Stretch" VerticalAlignment="{TemplateBinding VerticalContentAlignment}" Width="Auto" Margin="0" Content="{TemplateBinding Content}"/>
                </Border>
            </ControlTemplate>
        </Setter.Value>
    </Setter>

    <Style.Triggers>
        <Trigger Property="IsMouseOver" Value="True">
            <Setter Property="Background">
                <Setter.Value>
                    <ImageBrush ImageSource="images/selection.png"/>
                </Setter.Value>
            </Setter>
            <Setter Property="BorderThickness" Value="0" />
        </Trigger>
        <Trigger Property="IsSelected" Value="True">
            <Setter Property="Background">
                <Setter.Value>
                    <ImageBrush ImageSource="images/selection.png"/>
                </Setter.Value>
            </Setter>
            <Setter Property="BorderThickness" Value="0" />
            <Setter Property="Foreground" Value="#FFFFFF" />
        </Trigger>
    </Style.Triggers>
</Style>

Listview XAML
            <ListView Background="transparent" Margin="10 10 10 10" x:Name="Mylist" HorizontalAlignment="Stretch" VerticalContentAlignment="center" VerticalAlignment="Stretch" BorderBrush="Transparent">
            <ListView.View>
                <GridView>
                    <GridViewColumn Header="img" Width="150" DisplayMemberBinding="{Binding img}" />
                    <GridViewColumn Header="name" Width="150" DisplayMemberBinding="{Binding name}" />
                    <GridViewColumn Header="path" Width="150" DisplayMemberBinding="{Binding path}" />
                </GridView>
            </ListView.View>
        </ListView>

A: Sorry, this would be easier if I had a grid view working somewhere.
My second idea is this: ListViewItems have a FocusVisualStyle. You can set it like this in your style:
<Setter Property="ListViewItem.FocusVisualStyle" Value="{DynamicResource ListViewItemFocusVisualStyle}" />

(Or you set it to null as it is done here: WPF ListView in GridView mode Highlighting problem)
The style could look like this:
<Style.Resources>
    <Style x:Key="ListViewItemFocusVisualStyle">
        <Setter Property="Control.Template">
            <Setter.Value>
                <ControlTemplate>
                    <Rectangle Margin="4, 1" StrokeThickness="1"
                               Stroke="{DynamicResource {x:Static SystemColors.ControlTextBrushKey}}"
                               StrokeDashArray="1 2"
                               SnapsToDevicePixels="True" />
                </ControlTemplate>
            </Setter.Value>
        </Setter>
    </Style>
</Style.Resources>

A: Please try <Setter Property="Control.Padding" Value="0" /> in your style for the ListViewItem


text:
Q: Prevent webpage zoom/resize in IE on Windows 8 snapping I am design a responsive layout webpage
I use jquery to update divs according to the change in window width
But when you snap IE modern ui to one side of the screen, it zooms out on the page making everything smaller, and this is totally screwing up the display of the page.
How can I stop IE from changing the zoom level on snap?

A: sorry, wrote too soon.
the answer for me is this...
@media screen {
    @-ms-viewport { width: device-width; }
}


text:
Q: fetch gmail calendar events in mvc 4 application I am working on mvc 4 web application. I want to implement a functionality wherein the scenario is as follows-
There will be gmail id as input for ex: abc@gmail.com. When user will enter this, application should fetch all the calendar events of that respective email id and display them.
I have gone through this-
http://msdn.microsoft.com/en-us/library/live/hh826523.aspx#cal_rest
https://developers.google.com/google-apps/calendar/v2/developers_guide_protocol
I am new to this and i have searched a lot but not got any solution. Please help! Thanks in advance!

A: Got the solution . Just refer this.
https://github.com/nanovazquez/google-calendar-sample

A: Please check the steps below.

*

*Add Google Data API SDK.

*Try this code.. I wrote this code for one project but I removed some codes that are not related to Google Calender. If you don't want to use SDK, you can simply do http-get or http-post to your calender link based on spec.
        CalendarService service = new CalendarService("A.Name");
        const string GOOGLE_CALENDAR_FEED = "https://www.google.com/calendar/feeds/";
        const string GOOGLE_CALENDAR_DEFAULT_ALL_CALENDAR_FULL = "default/allcalendars/full";
        const string GOOGLE_CALENDAR_ALL_PRIVATE_FULL = "private/full";

        private void SetUserCredentials() {
            var userName = ConfigurationManager.AppSettings["GoogleUserName"];
            var passWord = Security.DecryptString(ConfigurationManager.AppSettings["GooglePasswrod"]).ToInsecureString();
            if (userName != null && userName.Length > 0) {
                service.setUserCredentials(userName, passWord);
            }
        }

        private CalendarFeed GetCalendarsFeed() {
            CalendarQuery calendarQuery = new CalendarQuery();
            calendarQuery.Uri = new Uri(GOOGLE_CALENDAR_FEED + GOOGLE_CALENDAR_DEFAULT_ALL_CALENDAR_FULL);

            CalendarFeed resultFeed = (CalendarFeed)service.Query(calendarQuery);
            return resultFeed;
        }

    private TherapistTimeSlots GetTimeSlots(CalendarEntry entry2) {

    string feedstring = entry2.Id.AbsoluteUri.Substring(63);
    var postUristring = string.Format("{0}{1}/{2}", GOOGLE_CALENDAR_FEED, feedstring, GOOGLE_CALENDAR_ALL_PRIVATE_FULL);

    EventFeed eventFeed = GetEventFeed(postUristring);
    slot.Events = new List<Event>();

    if (eventFeed != null) {
        var orderEventList = (from entity in eventFeed.Entries
                              from timeslot in ((EventEntry)entity).Times
                              orderby timeslot.StartTime
                              select entity).ToList();

    }
    return slot;
}

private EventFeed GetEventFeed(string postUristring) {

    var eventQuery = new EventQuery();
    eventQuery.Uri = new Uri(postUristring);
    var h = Convert.ToInt32(DateTime.Now.ToString("HH", System.Globalization.DateTimeFormatInfo.InvariantInfo));
    eventQuery.StartTime = new DateTime(DateTime.Now.Year, DateTime.Now.Month, DateTime.Now.Day, h, 0, 0);
    eventQuery.EndTime = new DateTime(DateTime.Now.Year, DateTime.Now.Month, DateTime.Now.Day, h + 2, 0, 0);
    try {
        EventFeed eventFeed = service.Query(eventQuery) as EventFeed;
        return eventFeed;
    }
    catch (Exception ex) {
        /*
         * http://groups.google.com/group/google-calendar-help-dataapi/browse_thread/thread/1c1309d9e6bd9be7
         *
         *  Unfortunately, the calendar API will always issue a redirect to give you a
            gsessionid that will optimize your subsequent requests on our servers.
            Using the GData client library should be transparent for you as it is taking
            care of handling those redirect; but there might some times where this error
            occurs as you may have noticed.
            The best way to work around this is to catche the Exception and re-send the
            request as there is nothing else you can do on your part.
         */
        return null;
    }
}


text:
Q: How does the CFS Scheduler select which task group/cgroup to run next? This post gave a very nice summary of how scheduling is done on a per task basis, but it doesn't really go into how tasks groups are ordered on the RB tree.
I couldn't really find other resources that spoke about this either; all of them said something along the lines of:

The pick_next_task_fair() function keeps picking the left most scheduling entity as long as the current scheduling entity is a CFS RQ (RB Tree with leftmost node having smallest vruntime).

But how exactly does CFS prioritise one task group over another task group on the RB Tree? Is it done on the basis of the min_vruntime of the tasks inside it? Is it done based on the CPU shares given to that task group?
Any insights on this would be much appreciated! Thanks in advance!

A:
But how exactly do you place a task group on the RB Tree?

Take pick_next_task_fair() for instance, task groups are inserted into RB Tree via following codes. More specifically, put_prev_entity().
if (prev != p) {
        struct sched_entity *pse = &prev->se;

        while (!(cfs_rq = is_same_group(se, pse))) {
                int se_depth = se->depth;
                int pse_depth = pse->depth;

                if (se_depth <= pse_depth) {
                        put_prev_entity(cfs_rq_of(pse), pse);
                        pse = parent_entity(pse);
                }
                if (se_depth >= pse_depth) {
                        set_next_entity(cfs_rq_of(se), se);
                        se = parent_entity(se);
                }
        }

        put_prev_entity(cfs_rq, pse);
        set_next_entity(cfs_rq, se);
}

Is it done on the basis of the min_vruntime of the tasks inside it? Is
it done based on the CPU shares given to that task group?

Not the whole CPU shares given to that task group. Only a fragment1 of that shares. See calc_group_shares() and update_curr() for more details.