问:
C# MVC5 Present string url in view
I am beginning developer in asp.Net MVC5.

In my MVC project i use with web service that return me a string URL the URL is from another domain.

I want to move to the URL.

For clear myself:
The client fill form home page and press submit, in the server side i send a request web
service with parameters from the form and get URL with another domain and this URL i need to present as second page to the client

```<code>public class HomeController : Controller
{
    public ActionResult Home()
    {
        return View("~/Views/Home/home.cshtml");
    }

    [HttpPost]
    [ValidateAntiForgeryToken]
    public ActionResult doSomething(Something obj)
    {
        //use web service and get string URL
        string urlString = ;// get from the web service response.
        return View();// want write in the ();
    }
}
</code>```

答:
Also this is usefull for navigation in MVC.</p>

```<code>[HttpPost]
[ValidateAntiForgeryToken]
public ActionResult doSomething(Something obj)
{
    //use web service and get string URL
    string urlString = ;// get from the web service response.

    if (!string.IsNullOrEmpty(urlString))
    {
        //if the url is from within the domain.
        return RedirectToAction(urlString);
      //if the url is from other domain use this
      //return Redirect(urlString);
    }

    //If the urlString is empty Return to a error page
    return View("Error");
}
</code>```

Title: C# MVC5 Present string url in view

Body:
I am beginning developer in asp.Net MVC5.

In my MVC project i use with web service that return me a string URL the URL is from another domain.

I want to move to the URL.

For clear myself:
The client fill form home page and press submit, in the server side i send a request web
service with parameters from the form and get URL with another domain and this URL i need to present as second page to the client

public class HomeController : Controller
{
    public ActionResult Home()
    {
        return View("~/Views/Home/home.cshtml");
    }

    [HttpPost]
    [ValidateAntiForgeryToken]
    public ActionResult doSomething(Something obj)
    {
        //use web service and get string URL
        string urlString = ;// get from the web service response.
        return View();// want write in the ();
    }
}

Body:
Also this is usefull for navigation in MVC.

[HttpPost]
[ValidateAntiForgeryToken]
public ActionResult doSomething(Something obj)
{
    //use web service and get string URL
    string urlString = ;// get from the web service response.

    if (!string.IsNullOrEmpty(urlString))
    {
        //if the url is from within the domain.
        return RedirectToAction(urlString);
      //if the url is from other domain use this
      //return Redirect(urlString);
    }

    //If the urlString is empty Return to a error page
    return View("Error");
}


来源: stackexchange

问:
Add a comma to the version of the program
I was trying to change the version of a program, but I'm having difficulties I should add a number, for example: "5.50.1"
Currently it turns out to be 5.50</p>

```<code>    #define SOFTWARE_VERSION        0x0F
    #define SOFTWARE_VERSION_BCD    0x0550

#if defined(SOFTWARE)
#define IS_SOFTWARE         1
#else
#define IS_SOFTWARE         0
#endif

#define MAKE_VERSION(aldebaran, fw, type) ((aldebarab&0xFF) | ((fw&0xffff)<<8) | ((type&0x1)<<24))
</code>```

答: If your using visual studio as the compiler, then the resource file (.rc) can be accessed by the resource id which is defined in resource.h. The version number can be retrieved/modified/saved as a string resource (std::string, TCHAR, CString etc).    </p>

ContentLicense: CC BY-SA 3.0

Body:
I was trying to change the version of a program, but I'm having difficulties I should add a number, for example: "5.50.1"
Currently it turns out to be 5.50

    #define SOFTWARE_VERSION        0x0F
    #define SOFTWARE_VERSION_BCD    0x0550

#if defined(SOFTWARE)
#define IS_SOFTWARE         1
#else
#define IS_SOFTWARE         0
#endif

#define MAKE_VERSION(aldebaran, fw, type) ((aldebarab&0xFF) | ((fw&0xffff)<<8) | ((type&0x1)<<24))


问:
Can not cast context into activity Xamarin
I have an issue in xamarin, and I need some help, please

From xamarin tutorial, I wish to launch a phone call thanks to a DependencyService.

Here is the service implementation for Android part:

```<code> public bool Dial(string number)
    {
        var context = Android.App.Application.Context;

        if (context == null)
            return false;

        var intent = new Intent(Intent.ActionCall);
        intent.SetData(Uri.Parse("tel:" + number));
        try
        {
            var activity = (Activity)context;
            ActivityCompat.RequestPermissions(activity,
             new String[] { Android.Manifest.Permission.CallPhone }, 1);
        }
        catch (Exception e)
        {
            Console.WriteLine(e);
            throw;
        }

        if (IsIntentAvailable(context, intent))
        {
            try
            {
                context.StartActivity(intent);

            }
            catch (Exception e)
            {
                Console.WriteLine(e);
                throw;
            }
            return true;
        }

        return false;
    }
</code>```

The main issue is: I have a revoked permission

android.permission.CALL_PHONE

. I precise that I have given the permission in the manifest. I have read that I need to register in runtime the permission. It's what I'm trying with

```<code>ActivityCompat.RequestPermissions(activity,
             new String[] { Android.Manifest.Permission.CallPhone }, 1);
</code>```

But I need the curent Activity as parameter and I can't cast the current Context into Activity.

Please help me to find where I have done a mistake.

Thank you

答:
Try this

```<code>(YourActivityName)Forms.Context;
</code>```

for example:

```<code>var activity = (YourActivityName)Forms.Context;
</code>```

Body:
I have an issue in xamarin, and I need some help, please

From xamarin tutorial, I wish to launch a phone call thanks to a DependencyService.

Here is the service implementation for Android part:

 public bool Dial(string number)
    {
        var context = Android.App.Application.Context;

        if (context == null)
            return false;

        var intent = new Intent(Intent.ActionCall);
        intent.SetData(Uri.Parse("tel:" + number));
        try
        {
            var activity = (Activity)context;
            ActivityCompat.RequestPermissions(activity,
             new String[] { Android.Manifest.Permission.CallPhone }, 1);
        }
        catch (Exception e)
        {
            Console.WriteLine(e);
            throw;
        }

        if (IsIntentAvailable(context, intent))
        {
            try
            {
                context.StartActivity(intent);

            }
            catch (Exception e)
            {
                Console.WriteLine(e);
                throw;
            }
            return true;
        }

        return false;
    }

The main issue is: I have a revoked permission

android.permission.CALL_PHONE

. I precise that I have given the permission in the manifest. I have read that I need to register in runtime the permission. It's what I'm trying with

ActivityCompat.RequestPermissions(activity,
             new String[] { Android.Manifest.Permission.CallPhone }, 1);

But I need the curent Activity as parameter and I can't cast the current Context into Activity.

Please help me to find where I have done a mistake.

Thank you

Body:
Try this

(YourActivityName)Forms.Context;

for example:

var activity = (YourActivityName)Forms.Context;


问:
VS2010 C++ variadic template example
I have a class template and I can't seem to figure out how to perform a Variadic Template style instantiation.

Here is the "code" so far of what I'm looking for:

```<code>template<typename _Classname, typename... Args>
class CFunctorStartExT
{
  friend class CXXFactory;
protected:
  template<typename U>
  CFunctorStartExT(typename U& _functor, Args&... args) :
    m_Functor(_functor),
    m_args(args)
  {
  }
  virtual bool ProcessLoop(CSomeClass* pThread)
  {
    return m_Functor(pThread, m_args);
  }

protected:
  _Classname& m_Functor;
  Args... m_args;
};
</code>```

Obviously this won't compile :). The idea is to create a class that can store the values passed in (if any.. it might just have _Classname/U defined) on the constructor so they can be retrieved later to pass to m_Functor in another function.

First: can Variadic Template even be done in VS2010? I am getting compile problems just with the template declaration error C2143: syntax error : missing ',' before '...' from the line template<typename _Classname, typename... Args>

Second, can what I am trying to accomplish be done? Thanks!

答:
I believe the following will do what you want.  First you need a utility:

```<code>// make_tuple_indices

template <size_t...> struct tuple_indices {};

template <size_t _Sp, class _IntTuple, size_t _Ep>
struct make_indices_imp;

template <size_t _Sp, size_t ..._Indices, size_t _Ep>
struct make_indices_imp<_Sp, tuple_indices<_Indices...>, _Ep>
{
    typedef typename make_indices_imp<_Sp+1, tuple_indices<_Indices..., _Sp>, _Ep>::type type;
};

template <size_t _Ep, size_t ..._Indices>
struct make_indices_imp<_Ep, tuple_indices<_Indices...>, _Ep>
{
    typedef tuple_indices<_Indices...> type;
};

template <size_t _Ep, size_t _Sp = 0>
struct make_tuple_indices
{
    static_assert(_Sp <= _Ep, "make_tuple_indices input error");
    typedef typename make_indices_imp<_Sp, tuple_indices<>, _Ep>::type type;
};
</code>```

Then you can use this to help you expand a tuple holding your arguments:

```<code>template<typename _Classname, typename... Args>
class CFunctorStartExT
{
  friend class CXXFactory;
protected:
  template<typename U>
  CFunctorStartExT(U& _functor, Args&... args) :
    m_Functor(_functor),
    m_args(args...)
  {
  }

  virtual bool ProcessLoop(CSomeClass* pThread)
  {
    return ProcessLoop(pThread,
                       typename make_tuple_indices<sizeof...(Args)>::type());
  }

protected:
  _Classname& m_Functor;
  std::tuple<Args...> m_args;

private:
    template <std::size_t ...Indx>
    bool ProcessLoop(CSomeClass* pThread, tuple_indices<Indx...>)
    {
        return m_Functor(pThread, std::get<Indx>(m_args)...);
    }
};
</code>```

As far as VS2010 variadic template support: I have no idea.

ContentLicense: CC BY-SA 2.5

Title: VS2010 C++ variadic template example

Body:
I have a class template and I can't seem to figure out how to perform a Variadic Template style instantiation.

Here is the "code" so far of what I'm looking for:

template<typename _Classname, typename... Args>
class CFunctorStartExT
{
  friend class CXXFactory;
protected:
  template<typename U>
  CFunctorStartExT(typename U& _functor, Args&... args) :
    m_Functor(_functor),
    m_args(args)
  {
  }
  virtual bool ProcessLoop(CSomeClass* pThread)
  {
    return m_Functor(pThread, m_args);
  }

protected:
  _Classname& m_Functor;
  Args... m_args;
};

Obviously this won't compile :). The idea is to create a class that can store the values passed in (if any.. it might just have _Classname/U defined) on the constructor so they can be retrieved later to pass to m_Functor in another function.

First: can Variadic Template even be done in VS2010? I am getting compile problems just with the template declaration error C2143: syntax error : missing ',' before '...' from the line template<typename _Classname, typename... Args>

Second, can what I am trying to accomplish be done? Thanks!

Body:
I believe the following will do what you want.  First you need a utility:

// make_tuple_indices

template <size_t...> struct tuple_indices {};

template <size_t _Sp, class _IntTuple, size_t _Ep>
struct make_indices_imp;

template <size_t _Sp, size_t ..._Indices, size_t _Ep>
struct make_indices_imp<_Sp, tuple_indices<_Indices...>, _Ep>
{
    typedef typename make_indices_imp<_Sp+1, tuple_indices<_Indices..., _Sp>, _Ep>::type type;
};

template <size_t _Ep, size_t ..._Indices>
struct make_indices_imp<_Ep, tuple_indices<_Indices...>, _Ep>
{
    typedef tuple_indices<_Indices...> type;
};

template <size_t _Ep, size_t _Sp = 0>
struct make_tuple_indices
{
    static_assert(_Sp <= _Ep, "make_tuple_indices input error");
    typedef typename make_indices_imp<_Sp, tuple_indices<>, _Ep>::type type;
};

Then you can use this to help you expand a tuple holding your arguments:

template<typename _Classname, typename... Args>
class CFunctorStartExT
{
  friend class CXXFactory;
protected:
  template<typename U>
  CFunctorStartExT(U& _functor, Args&... args) :
    m_Functor(_functor),
    m_args(args...)
  {
  }

  virtual bool ProcessLoop(CSomeClass* pThread)
  {
    return ProcessLoop(pThread,
                       typename make_tuple_indices<sizeof...(Args)>::type());
  }

protected:
  _Classname& m_Functor;
  std::tuple<Args...> m_args;

private:
    template <std::size_t ...Indx>
    bool ProcessLoop(CSomeClass* pThread, tuple_indices<Indx...>)
    {
        return m_Functor(pThread, std::get<Indx>(m_args)...);
    }
};

As far as VS2010 variadic template support: I have no idea.


问:
sending one by one message through python over tcp protocol?
Hi I am trying to send same message 10 times through python over tcp protocol.
here is python code.

```<code>import socket
import sys
import random

HOST = '192.168.1.29'   # Symbolic name meaning all available interfaces
PORT = 55555 # Arbitrary non-privileged port

s = socket.socket(socket.AF_INET, socket.SOCK_STREAM)
print 'Socket created'

#Bind socket to local host and port
try:
    s.bind((HOST, PORT))
except socket.error as msg:
    print 'Bind failed. Error Code : ' + str(msg[0]) + ' Message ' + msg[1]
    sys.exit()

print 'Socket bind complete'

#Start listening on socket
s.listen(1)
print 'Socket now listening at',HOST, PORT
conn, addr = s.accept()
print 'Connected with ' + addr[0] + ':' + str(addr[1])
count = 0;
while 1:
    if (count > 9):
        break
    else:
        count = count + 1
        data  = ("hello world....!")
        conn.send(data)
        print "",data
    if data == "exit":
        break

conn.close()
s.close()
</code>```

As per code, Here i am trying to send "hello world" 10 times to far end as a separate message. In short each packet should contain only one time "hello world". but in my surprise, First packet contains one hello world message,but second packet contains 9 times hello world message. will you please let me know why it is happening? Is there any bug in code? if its not the way then how to send 10 different packets each containing one time hello world through python over tcp ?

答:
If i understand, you want to send data trough TCP. I use this code to send string via sockets

Send

```<code>import socket

UDP_IP = "192.168.1.2" #IP of the sender
UDP_PORT = 5005

sock = socket.socket(socket.AF_INET,socket.SOCK_DGRAM)

sock.bind((UDP_IP,UDP_PORT))

while True:
    data, addr = sock.recvfrom(1024)
    print "MSG:" + data
</code>```

Receive

```<code>import socket
UDP_IP = "192.168.1.1" #IP of the receiver
UDP_PORT = 5005

sock = socket.socket(socket.AF_INET, # Internet
                 socket.SOCK_DGRAM) # UDP
while True:
    try:
            data = str("Hello World!")
            print len(data)
            sock.sendto(data, (UDP_IP, UDP_PORT))
    except (KeyboardInterrupt, SystemExit):
            raise
</code>```

Body:
Hi I am trying to send same message 10 times through python over tcp protocol.
here is python code.

import socket
import sys
import random

HOST = '192.168.1.29'   # Symbolic name meaning all available interfaces
PORT = 55555 # Arbitrary non-privileged port

s = socket.socket(socket.AF_INET, socket.SOCK_STREAM)
print 'Socket created'

#Bind socket to local host and port
try:
    s.bind((HOST, PORT))
except socket.error as msg:
    print 'Bind failed. Error Code : ' + str(msg[0]) + ' Message ' + msg[1]
    sys.exit()

print 'Socket bind complete'

#Start listening on socket
s.listen(1)
print 'Socket now listening at',HOST, PORT
conn, addr = s.accept()
print 'Connected with ' + addr[0] + ':' + str(addr[1])
count = 0;
while 1:
    if (count > 9):
        break
    else:
        count = count + 1
        data  = ("hello world....!")
        conn.send(data)
        print "",data
    if data == "exit":
        break

conn.close()
s.close()

As per code, Here i am trying to send "hello world" 10 times to far end as a separate message. In short each packet should contain only one time "hello world". but in my surprise, First packet contains one hello world message,but second packet contains 9 times hello world message. will you please let me know why it is happening? Is there any bug in code? if its not the way then how to send 10 different packets each containing one time hello world through python over tcp ?

Body:
If i understand, you want to send data trough TCP. I use this code to send string via sockets

Send

import socket

UDP_IP = "192.168.1.2" #IP of the sender
UDP_PORT = 5005

sock = socket.socket(socket.AF_INET,socket.SOCK_DGRAM)

sock.bind((UDP_IP,UDP_PORT))

while True:
    data, addr = sock.recvfrom(1024)
    print "MSG:" + data

Receive

import socket
UDP_IP = "192.168.1.1" #IP of the receiver
UDP_PORT = 5005

sock = socket.socket(socket.AF_INET, # Internet
                 socket.SOCK_DGRAM) # UDP
while True:
    try:
            data = str("Hello World!")
            print len(data)
            sock.sendto(data, (UDP_IP, UDP_PORT))
    except (KeyboardInterrupt, SystemExit):
            raise


问:
How to drop timestamps that return zero if there is no data in InfluxDB
My InfluxDB query is:

```<code>select count(quantity) from test group by time(1d)
</code>```

Ouput

How do we drop zero?

答:
From the InfluxDB docs:

fill() changes the value reported for time intervals that have no data.

To return no timestamp for intervals with no data, use fill(none):

```<code>select count(quantity) from test where time > now()-10d group by time(1d) fill(none)
</code>```

Body:
My InfluxDB query is:

select count(quantity) from test group by time(1d)

Ouput

How do we drop zero?

Body:
From the InfluxDB docs:

fill() changes the value reported for time intervals that have no data.

To return no timestamp for intervals with no data, use fill(none):

select count(quantity) from test where time > now()-10d group by time(1d) fill(none)


问:
Spring Boot JPA Bulk insert
I have 3 Entities Parent,Child,SubChild. Parent is a parent of Child and Child is a parent of SubChild. I need to insert around 700 objects of Parent. Parent can have 50 Objects of Child. Child can have 50 objects of SubChild.
I tried normal repository.save(ListOfObjects) it takes approx 4mins.

Then I tried using entity manager's persist, flush and clear based on batch size(500). This also took approx 4 mins.
There wasn't much difference in performance. Please suggest a best way to insert such a high amount of data efficiently.

Parent

```<code>@Entity
public class Parent {
@Id @GeneratedValue(strategy= GenerationType.AUTO)
private Long parentId;
private String aaa;
private String bbb;
private String ccc;
@Version
private Long version;
@OneToMany(cascade = CascadeType.ALL, orphanRemoval = true, mappedBy = "parent", fetch = FetchType.LAZY)
@JoinColumnsOrFormulas({
@JoinColumnOrFormula(column=@JoinColumn(name="parentId",referencedColumnName="parentId",nullable=false))})
private List<Child> childs = new ArrayList<>();
public Long getParentId() {
    return parentId;
}
public void setParentId(Long parentId) {
    this.parentId = parentId;
}
public String getAaa() {
    return aaa;
}
public void setAaa(String aaa) {
    this.aaa = aaa;
}
public String getBbb() {
    return bbb;
}
public void setBbb(String bbb) {
    this.bbb = bbb;
}
public String getCcc() {
    return ccc;
}
public void setCcc(String ccc) {
    this.ccc = ccc;
}
public Long getVersion() {
    return version;
}
public void setVersion(Long version) {
    this.version = version;
}
public List<Child> getChilds() {
    return childs;
}
public void setChilds(List<Child> childs) {
    this.childs = childs;
}
}
</code>```

Child

```<code>@Entity
public class Child {
@Id @GeneratedValue(strategy= GenerationType.AUTO)
private Long childId;
private String ddd;
private String ccc;
private Integer eee;
@OneToMany(cascade = CascadeType.ALL,orphanRemoval = true, mappedBy = "child", fetch = FetchType.LAZY)
@JoinColumnsOrFormulas({
        @JoinColumnOrFormula(column = @JoinColumn(name = "childId", referencedColumnName = "childId", nullable = false)) })
private List<SubChild> subChilds = new ArrayList<>();
@ManyToOne(fetch = FetchType.LAZY)
@JoinColumnsOrFormulas({
    @JoinColumnOrFormula(column= @JoinColumn( name="parentId",referencedColumnName="parentId",nullable=false))
})
private Parent parent;

public Long getChildId() {
    return childId;
}
public void setChildId(Long childId) {
    this.childId = childId;
}
public String getDdd() {
    return ddd;
}
public void setDdd(String ddd) {
    this.ddd = ddd;
}
public String getCcc() {
    return ccc;
}
public void setCcc(String ccc) {
    this.ccc = ccc;
}
public Integer getEee() {
    return eee;
}
public void setEee(Integer eee) {
    this.eee = eee;
}
public List<SubChild> getSubChilds() {
    return subChilds;
}
public void setSubChilds(List<SubChild> subChilds) {
    this.subChilds = subChilds;
}
public Parent getParent() {
    return parent;
}
public void setParent(Parent parent) {
    this.parent = parent;
}
}
</code>```

SubChild

```<code>@Entity
public class SubChild {
@Id @GeneratedValue(strategy= GenerationType.AUTO)
private Long subChildId;
private String fff;
private String ggg;
private Integer hhh;

@ManyToOne(fetch = FetchType.LAZY)
@JoinColumnsOrFormulas({
    @JoinColumnOrFormula(column= @JoinColumn( name="childId",referencedColumnName="childId",nullable=false))
})
private Child child;

public Long getSubChildId() {
    return subChildId;
}
public void setSubChildId(Long subChildId) {
    this.subChildId = subChildId;
}
public String getFff() {
    return fff;
}
public void setFff(String fff) {
    this.fff = fff;
}
public String getGgg() {
    return ggg;
}
public void setGgg(String ggg) {
    this.ggg = ggg;
}
public Integer getHhh() {
    return hhh;
}
public void setHhh(Integer hhh) {
    this.hhh = hhh;
}
public Child getChild() {
    return child;
}
public void setChild(Child child) {
    this.child = child;
}
}
</code>```

Repository method used for persisting the list of Parent Entity

```<code>@Value("${spring.jpa.hibernate.jdbc.batch_size}")
private int batchSize;

public <T extends Parent> Collection<T> bulkSave(Collection<T> entities) {
    final List<T> savedEntities = new ArrayList<T>(entities.size());
    int i = 0;
    for (T t : entities) {
        savedEntities.add(persistOrMerge(t));
        i++;
        if (i % batchSize == 0) {
            // Flush a batch of inserts and release memory.
            entityManager.flush();
            entityManager.clear();
        }
    }
    return savedEntities;
}
private <T extends Parent> T persistOrMerge(T t) {
    if (t.getTimeSlotId() == null) {
        entityManager.persist(t);
        return t;
    } else {
        return entityManager.merge(t);
    }
}
</code>```

application.yml

```<code>spring:
  application:
    name: sample-service
  jpa:
    database: MYSQL
    show-sql: true
    hibernate:
      ddl-auto: update
      dialect: org.hibernate.dialect.MySQL5Dialect
      naming_strategy: org.hibernate.cfg.ImprovedNamingStrategy
      jdbc:
        batch_size: 100
  jackson:
    date-format: dd/MM/yyyy
  thymeleaf:
    cache: false
spring.datasource.url : jdbc:mysql://${dbhost}/sample?createDatabaseIfNotExist=true
spring.datasource.username : root
spring.datasource.password : root
spring.datasource.driver-class-name : com.mysql.cj.jdbc.Driver
</code>```

答:
To enable batch insert you need the batch_size property which you have in your configuration.

Also since a jdbc batch can target one table only you need the spring.jpa.hibernate.order_inserts=true property to order the insert between parent and child or else the statement are unordered and you will see a partial batch (new batch anytime an insert in a different table is called)

Title: Spring Boot JPA Bulk insert

Body:
I have 3 Entities Parent,Child,SubChild. Parent is a parent of Child and Child is a parent of SubChild. I need to insert around 700 objects of Parent. Parent can have 50 Objects of Child. Child can have 50 objects of SubChild.
I tried normal repository.save(ListOfObjects) it takes approx 4mins.

Then I tried using entity manager's persist, flush and clear based on batch size(500). This also took approx 4 mins.
There wasn't much difference in performance. Please suggest a best way to insert such a high amount of data efficiently.

Parent

@Entity
public class Parent {
@Id @GeneratedValue(strategy= GenerationType.AUTO)
private Long parentId;
private String aaa;
private String bbb;
private String ccc;
@Version
private Long version;
@OneToMany(cascade = CascadeType.ALL, orphanRemoval = true, mappedBy = "parent", fetch = FetchType.LAZY)
@JoinColumnsOrFormulas({
@JoinColumnOrFormula(column=@JoinColumn(name="parentId",referencedColumnName="parentId",nullable=false))})
private List<Child> childs = new ArrayList<>();
public Long getParentId() {
    return parentId;
}
public void setParentId(Long parentId) {
    this.parentId = parentId;
}
public String getAaa() {
    return aaa;
}
public void setAaa(String aaa) {
    this.aaa = aaa;
}
public String getBbb() {
    return bbb;
}
public void setBbb(String bbb) {
    this.bbb = bbb;
}
public String getCcc() {
    return ccc;
}
public void setCcc(String ccc) {
    this.ccc = ccc;
}
public Long getVersion() {
    return version;
}
public void setVersion(Long version) {
    this.version = version;
}
public List<Child> getChilds() {
    return childs;
}
public void setChilds(List<Child> childs) {
    this.childs = childs;
}
}

Child

@Entity
public class Child {
@Id @GeneratedValue(strategy= GenerationType.AUTO)
private Long childId;
private String ddd;
private String ccc;
private Integer eee;
@OneToMany(cascade = CascadeType.ALL,orphanRemoval = true, mappedBy = "child", fetch = FetchType.LAZY)
@JoinColumnsOrFormulas({
        @JoinColumnOrFormula(column = @JoinColumn(name = "childId", referencedColumnName = "childId", nullable = false)) })
private List<SubChild> subChilds = new ArrayList<>();
@ManyToOne(fetch = FetchType.LAZY)
@JoinColumnsOrFormulas({
    @JoinColumnOrFormula(column= @JoinColumn( name="parentId",referencedColumnName="parentId",nullable=false))
})
private Parent parent;

public Long getChildId() {
    return childId;
}
public void setChildId(Long childId) {
    this.childId = childId;
}
public String getDdd() {
    return ddd;
}
public void setDdd(String ddd) {
    this.ddd = ddd;
}
public String getCcc() {
    return ccc;
}
public void setCcc(String ccc) {
    this.ccc = ccc;
}
public Integer getEee() {
    return eee;
}
public void setEee(Integer eee) {
    this.eee = eee;
}
public List<SubChild> getSubChilds() {
    return subChilds;
}
public void setSubChilds(List<SubChild> subChilds) {
    this.subChilds = subChilds;
}
public Parent getParent() {
    return parent;
}
public void setParent(Parent parent) {
    this.parent = parent;
}
}

SubChild

@Entity
public class SubChild {
@Id @GeneratedValue(strategy= GenerationType.AUTO)
private Long subChildId;
private String fff;
private String ggg;
private Integer hhh;

@ManyToOne(fetch = FetchType.LAZY)
@JoinColumnsOrFormulas({
    @JoinColumnOrFormula(column= @JoinColumn( name="childId",referencedColumnName="childId",nullable=false))
})
private Child child;

public Long getSubChildId() {
    return subChildId;
}
public void setSubChildId(Long subChildId) {
    this.subChildId = subChildId;
}
public String getFff() {
    return fff;
}
public void setFff(String fff) {
    this.fff = fff;
}
public String getGgg() {
    return ggg;
}
public void setGgg(String ggg) {
    this.ggg = ggg;
}
public Integer getHhh() {
    return hhh;
}
public void setHhh(Integer hhh) {
    this.hhh = hhh;
}
public Child getChild() {
    return child;
}
public void setChild(Child child) {
    this.child = child;
}
}

Repository method used for persisting the list of Parent Entity

@Value("${spring.jpa.hibernate.jdbc.batch_size}")
private int batchSize;

public <T extends Parent> Collection<T> bulkSave(Collection<T> entities) {
    final List<T> savedEntities = new ArrayList<T>(entities.size());
    int i = 0;
    for (T t : entities) {
        savedEntities.add(persistOrMerge(t));
        i++;
        if (i % batchSize == 0) {
            // Flush a batch of inserts and release memory.
            entityManager.flush();
            entityManager.clear();
        }
    }
    return savedEntities;
}
private <T extends Parent> T persistOrMerge(T t) {
    if (t.getTimeSlotId() == null) {
        entityManager.persist(t);
        return t;
    } else {
        return entityManager.merge(t);
    }
}

application.yml

spring:
  application:
    name: sample-service
  jpa:
    database: MYSQL
    show-sql: true
    hibernate:
      ddl-auto: update
      dialect: org.hibernate.dialect.MySQL5Dialect
      naming_strategy: org.hibernate.cfg.ImprovedNamingStrategy
      jdbc:
        batch_size: 100
  jackson:
    date-format: dd/MM/yyyy
  thymeleaf:
    cache: false
spring.datasource.url : jdbc:mysql://${dbhost}/sample?createDatabaseIfNotExist=true
spring.datasource.username : root
spring.datasource.password : root
spring.datasource.driver-class-name : com.mysql.cj.jdbc.Driver


问:
LeaseExpiredException: No lease error on HDFS
I am trying to load large data to HDFS and I sometimes get the error below. any idea why?

The error:

```<code>org.apache.hadoop.ipc.RemoteException: org.apache.hadoop.hdfs.server.namenode.LeaseExpiredException: No lease on /data/work/20110926-134514/_temporary/_attempt_201109110407_0167_r_000026_0/hbase/site=3815120/day=20110925/107-107-3815120-20110926-134514-r-00026 File does not exist. Holder DFSClient_attempt_201109110407_0167_r_000026_0 does not have any open files.
at org.apache.hadoop.hdfs.server.namenode.FSNamesystem.checkLease(FSNamesystem.java:1557)
at org.apache.hadoop.hdfs.server.namenode.FSNamesystem.checkLease(FSNamesystem.java:1548)
at org.apache.hadoop.hdfs.server.namenode.FSNamesystem.completeFileInternal(FSNamesystem.java:1603)
at org.apache.hadoop.hdfs.server.namenode.FSNamesystem.completeFile(FSNamesystem.java:1591)
at org.apache.hadoop.hdfs.server.namenode.NameNode.complete(NameNode.java:675)
at sun.reflect.GeneratedMethodAccessor16.invoke(Unknown Source)
at sun.reflect.DelegatingMethodAccessorImpl.invoke(DelegatingMethodAccessorImpl.java:25)
at java.lang.reflect.Method.invoke(Method.java:597)
at org.apache.hadoop.ipc.RPC$Server.call(RPC.java:557)
at org.apache.hadoop.ipc.Server$Handler$1.run(Server.java:1434)
at org.apache.hadoop.ipc.Server$Handler$1.run(Server.java:1430)
at java.security.AccessController.doPrivileged(Native Method)
at javax.security.auth.Subject.doAs(Subject.java:396)
at org.apache.hadoop.security.UserGroupInformation.doAs(UserGroupInformation.java:1127)
at org.apache.hadoop.ipc.Server$Handler.run(Server.java:1428)

at org.apache.hadoop.ipc.Client.call(Client.java:1107)
at org.apache.hadoop.ipc.RPC$Invoker.invoke(RPC.java:226)
at $Proxy1.complete(Unknown Source)
at sun.reflect.NativeMethodAccessorImpl.invoke0(Native Method)
at sun.reflect.NativeMethodAccessorImpl.invoke(NativeMethodAccessorImpl.java:39)
at sun.reflect.DelegatingMethodAccessorImpl.invoke(DelegatingMethodAccessorImpl.java:25)
at java.lang.reflect.Method.invoke(Method.java:597)
at org.apache.hadoop.io.retry.RetryInvocationHandler.invokeMethod(RetryInvocationHandler.java:82)
at org.apache.hadoop.io.retry.RetryInvocationHandler.invoke(RetryInvocationHandler.java:59)
at $Proxy1.complete(Unknown Source)
at org.apache.hadoop.hdfs.DFSClient$DFSOutputStream.closeInternal(DFSClient.java:3566)
at org.apache.hadoop.hdfs.DFSClient$DFSOutputStream.close(DFSClient.java:3481)
at org.apache.hadoop.fs.FSDataOutputStream$PositionCache.close(FSDataOutputStream.java:61)
at org.apache.hadoop.fs.FSDataOutputStream.close(FSDataOutputStream.java:86)
at org.apache.hadoop.io.SequenceFile$Writer.close(SequenceFile.java:966)
at org.apache.hadoop.io.SequenceFile$BlockCompressWriter.close(SequenceFile.java:1297)
at org.apache.hadoop.mapreduce.lib.output.SequenceFileOutputFormat$1.close(SequenceFileOutputFormat.java:78)
at org.apache.hadoop.mapreduce.lib.output.MultipleOutputs$RecordWriterWithCounter.close(MultipleOutputs.java:303)
at org.apache.hadoop.mapreduce.lib.output.MultipleOutputs.close(MultipleOutputs.java:456)
at com.my.hadoop.platform.sortmerger.MergeSortHBaseReducer.cleanup(MergeSortHBaseReducer.java:145)
at org.apache.hadoop.mapreduce.Reducer.run(Reducer.java:178)
at org.apache.hadoop.mapred.ReduceTask.runNewReducer(ReduceTask.java:572)
at org.apache.hadoop.mapred.ReduceTask.run(ReduceTask.java:414)
at org.apache.hadoop.mapred.Child$4.run(Child.java:270)
at java.security.AccessController.doPrivileged(Native Method)
at javax.security.auth.Subject.doAs(Subject.java:396)
at org.apache.hadoop.security.UserGroupInformation.doAs(UserGroupInformation.java:1127)
at org.apache.hadoop.mapred.Child.main(Child.java:264)
</code>```

答:
I encountered this problem when I changed my program to use saveAsHadoopFile method to improve performance, in which scenario I can't make use of DataFrame API directly. see the problem

The reason why this would happen is basically what Zohar said, the saveAsHadoopFile method with MultipleTextOutputFormat actually doesn't allow multiple programs concurrently running to save files to the same directory. Once a program finished, it would delete the common _temporary directory the others still need, I am not sure if it's a bug in M/R API. (2.6.0-cdh5.12.1)

You can try this solution below if you can't redesign your program:

This is the source code of FileOutputCommitter in M/R API: (you must download an according version)

```<code>package org.apache.hadoop.mapreduce.lib.output;
public class FileOutputCommitter extends OutputCommitter {
private static final Log LOG = LogFactory.getLog(FileOutputCommitter.class);
/**
 * Name of directory where pending data is placed.  Data that has not been
 * committed yet.
 */
public static final String PENDING_DIR_NAME = "_temporary";
</code>```

Changes:

```<code>"_temporary"
</code>```

To:

```<code>System.getProperty("[the property name you like]")
</code>```

Compiles the single Class with all required dependencies, then creates a jar with the three output class files and places the jar to you classpath. (make it before the original jar)

Or, you can simply put the source file to your project.

Now, you can config the temp directory for each program by setting a different system property.

Hope it can help you.

Body:
I am trying to load large data to HDFS and I sometimes get the error below. any idea why?

The error:

org.apache.hadoop.ipc.RemoteException: org.apache.hadoop.hdfs.server.namenode.LeaseExpiredException: No lease on /data/work/20110926-134514/_temporary/_attempt_201109110407_0167_r_000026_0/hbase/site=3815120/day=20110925/107-107-3815120-20110926-134514-r-00026 File does not exist. Holder DFSClient_attempt_201109110407_0167_r_000026_0 does not have any open files.
at org.apache.hadoop.hdfs.server.namenode.FSNamesystem.checkLease(FSNamesystem.java:1557)
at org.apache.hadoop.hdfs.server.namenode.FSNamesystem.checkLease(FSNamesystem.java:1548)
at org.apache.hadoop.hdfs.server.namenode.FSNamesystem.completeFileInternal(FSNamesystem.java:1603)
at org.apache.hadoop.hdfs.server.namenode.FSNamesystem.completeFile(FSNamesystem.java:1591)
at org.apache.hadoop.hdfs.server.namenode.NameNode.complete(NameNode.java:675)
at sun.reflect.GeneratedMethodAccessor16.invoke(Unknown Source)
at sun.reflect.DelegatingMethodAccessorImpl.invoke(DelegatingMethodAccessorImpl.java:25)
at java.lang.reflect.Method.invoke(Method.java:597)
at org.apache.hadoop.ipc.RPC$Server.call(RPC.java:557)
at org.apache.hadoop.ipc.Server$Handler$1.run(Server.java:1434)
at org.apache.hadoop.ipc.Server$Handler$1.run(Server.java:1430)
at java.security.AccessController.doPrivileged(Native Method)
at javax.security.auth.Subject.doAs(Subject.java:396)
at org.apache.hadoop.security.UserGroupInformation.doAs(UserGroupInformation.java:1127)
at org.apache.hadoop.ipc.Server$Handler.run(Server.java:1428)

at org.apache.hadoop.ipc.Client.call(Client.java:1107)
at org.apache.hadoop.ipc.RPC$Invoker.invoke(RPC.java:226)
at $Proxy1.complete(Unknown Source)
at sun.reflect.NativeMethodAccessorImpl.invoke0(Native Method)
at sun.reflect.NativeMethodAccessorImpl.invoke(NativeMethodAccessorImpl.java:39)
at sun.reflect.DelegatingMethodAccessorImpl.invoke(DelegatingMethodAccessorImpl.java:25)
at java.lang.reflect.Method.invoke(Method.java:597)
at org.apache.hadoop.io.retry.RetryInvocationHandler.invokeMethod(RetryInvocationHandler.java:82)
at org.apache.hadoop.io.retry.RetryInvocationHandler.invoke(RetryInvocationHandler.java:59)
at $Proxy1.complete(Unknown Source)
at org.apache.hadoop.hdfs.DFSClient$DFSOutputStream.closeInternal(DFSClient.java:3566)
at org.apache.hadoop.hdfs.DFSClient$DFSOutputStream.close(DFSClient.java:3481)
at org.apache.hadoop.fs.FSDataOutputStream$PositionCache.close(FSDataOutputStream.java:61)
at org.apache.hadoop.fs.FSDataOutputStream.close(FSDataOutputStream.java:86)
at org.apache.hadoop.io.SequenceFile$Writer.close(SequenceFile.java:966)
at org.apache.hadoop.io.SequenceFile$BlockCompressWriter.close(SequenceFile.java:1297)
at org.apache.hadoop.mapreduce.lib.output.SequenceFileOutputFormat$1.close(SequenceFileOutputFormat.java:78)
at org.apache.hadoop.mapreduce.lib.output.MultipleOutputs$RecordWriterWithCounter.close(MultipleOutputs.java:303)
at org.apache.hadoop.mapreduce.lib.output.MultipleOutputs.close(MultipleOutputs.java:456)
at com.my.hadoop.platform.sortmerger.MergeSortHBaseReducer.cleanup(MergeSortHBaseReducer.java:145)
at org.apache.hadoop.mapreduce.Reducer.run(Reducer.java:178)
at org.apache.hadoop.mapred.ReduceTask.runNewReducer(ReduceTask.java:572)
at org.apache.hadoop.mapred.ReduceTask.run(ReduceTask.java:414)
at org.apache.hadoop.mapred.Child$4.run(Child.java:270)
at java.security.AccessController.doPrivileged(Native Method)
at javax.security.auth.Subject.doAs(Subject.java:396)
at org.apache.hadoop.security.UserGroupInformation.doAs(UserGroupInformation.java:1127)
at org.apache.hadoop.mapred.Child.main(Child.java:264)

Body:
I encountered this problem when I changed my program to use saveAsHadoopFile method to improve performance, in which scenario I can't make use of DataFrame API directly. see the problem

The reason why this would happen is basically what Zohar said, the saveAsHadoopFile method with MultipleTextOutputFormat actually doesn't allow multiple programs concurrently running to save files to the same directory. Once a program finished, it would delete the common _temporary directory the others still need, I am not sure if it's a bug in M/R API. (2.6.0-cdh5.12.1)

You can try this solution below if you can't redesign your program:

This is the source code of FileOutputCommitter in M/R API: (you must download an according version)

package org.apache.hadoop.mapreduce.lib.output;
public class FileOutputCommitter extends OutputCommitter {
private static final Log LOG = LogFactory.getLog(FileOutputCommitter.class);
/**
 * Name of directory where pending data is placed.  Data that has not been
 * committed yet.
 */
public static final String PENDING_DIR_NAME = "_temporary";

Changes:

"_temporary"

To:

System.getProperty("[the property name you like]")

Compiles the single Class with all required dependencies, then creates a jar with the three output class files and places the jar to you classpath. (make it before the original jar)

Or, you can simply put the source file to your project.

Now, you can config the temp directory for each program by setting a different system property.

Hope it can help you.


问:
How can I display this nested json object neatly and structured for the results object in django?
Here is my view.py:

```<code>def dublinbus(request):

    template = loader.get_template('park_at_dcu/dublinbus.html')
    busstop = request.GET.get('busstop', '')
    busstop_url = 'https://data.dublinked.ie/cgi-bin/rtpi/realtimebusinformation?stopid='+busstop+'&format=json'
    bus_time_info = requests.get(busstop_url)
    return HttpResponse(template.render(bus_time_info.json(), request))
</code>```

Here is the JSON data:

```<code>{"errorcode": "0",
 "errormessage": "",
 "numberofresults": 1,
 "stopid": "1644",
 "timestamp": "05\/12\/2017 12:22:09",
 "results":[{"arrivaldatetime": "05\/12\/2017 13:11:49",
             "duetime": "49",
             "departuredatetime": "05\/12\/2017 13:11:49",
             "departureduetime": "49",
             "scheduledarrivaldatetime": "05\/12\/2017 13:12:00",
             "scheduleddeparturedatetime": "05\/12\/2017 13:12:00",
             "destination": "Clontarf Road ",
             "destinationlocalized": " ",
             "origin": "DCU",
             "originlocalized": "DCU",
             "direction": "Inbound",
             "operator": "bac",
             "additionalinformation": "",
             "lowfloorstatus": "no",
             "route": "104",
             "sourcetimestamp": "05\/12\/2017 12:15:24",
             "monitored": "true"}]
}
</code>```

答:
you can use json.dumps for it.</p>

```<code>json.dumps(parsed, indent=4, sort_keys=True)

def dublinbus(request):

    template = loader.get_template('park_at_dcu/dublinbus.html')
    busstop = request.GET.get('busstop', '')
    busstop_url = 'https://data.dublinked.ie/cgi-bin/rtpi/realtimebusinformation?stopid='+busstop+'&format=json'
    bus_time_info = requests.get(busstop_url)
    pretty_bus_info = json.dumps(bus_time_info.json(), indent=4, sort_keys=True)
    return HttpResponse(template.render(pretty_bus_info, request))
</code>```

Body:
Here is my view.py:

def dublinbus(request):

    template = loader.get_template('park_at_dcu/dublinbus.html')
    busstop = request.GET.get('busstop', '')
    busstop_url = 'https://data.dublinked.ie/cgi-bin/rtpi/realtimebusinformation?stopid='+busstop+'&format=json'
    bus_time_info = requests.get(busstop_url)
    return HttpResponse(template.render(bus_time_info.json(), request))

Here is the JSON data:

{"errorcode": "0",
 "errormessage": "",
 "numberofresults": 1,
 "stopid": "1644",
 "timestamp": "05\/12\/2017 12:22:09",
 "results":[{"arrivaldatetime": "05\/12\/2017 13:11:49",
             "duetime": "49",
             "departuredatetime": "05\/12\/2017 13:11:49",
             "departureduetime": "49",
             "scheduledarrivaldatetime": "05\/12\/2017 13:12:00",
             "scheduleddeparturedatetime": "05\/12\/2017 13:12:00",
             "destination": "Clontarf Road ",
             "destinationlocalized": " ",
             "origin": "DCU",
             "originlocalized": "DCU",
             "direction": "Inbound",
             "operator": "bac",
             "additionalinformation": "",
             "lowfloorstatus": "no",
             "route": "104",
             "sourcetimestamp": "05\/12\/2017 12:15:24",
             "monitored": "true"}]
}

Body:
you can use json.dumps for it.

json.dumps(parsed, indent=4, sort_keys=True)

def dublinbus(request):

    template = loader.get_template('park_at_dcu/dublinbus.html')
    busstop = request.GET.get('busstop', '')
    busstop_url = 'https://data.dublinked.ie/cgi-bin/rtpi/realtimebusinformation?stopid='+busstop+'&format=json'
    bus_time_info = requests.get(busstop_url)
    pretty_bus_info = json.dumps(bus_time_info.json(), indent=4, sort_keys=True)
    return HttpResponse(template.render(pretty_bus_info, request))


问:
Clearing the screen in IPython
Is there a command in IPython to clear the screen?

EDIT: As @Saher mentions below, I can clean the screen using import os; os.system('CLS'), but is there a way to do this without having to import all of os?

答:
In macOS 10.13.1, Terminal 2.8, press command-k for Clear to Start.

clear resulted in "NameError: name 'clear' is not defined."

Caution: As a noob I may not fully understand what I did, but command-k seemed to do what I intended.

Title: Clearing the screen in IPython


问:
Convert column into object in R
I wanna convert first column into object in R so if the input looks like:

```<code>#name of df - KPIF
    namePill KPIPill
1: pill_tech     0.3
2:  pill_EUX     0.2
3:  pill_Bus     0.3
</code>```

the output should looks like:

```<code>#name of df - KPIF
           KPIPill
pill_tech    0.3
pill_EUX     0.2
pill_Bus     0.3
</code>```

Anyone could help ?
Regards,
Aleksandra

答:
First create the data frame:

```<code>KPIF <- data.frame(namePill=c('pill_tech','pill_EUX','pill_Bus'),
                   KPIPill=c(0.3,0.2,0.3))
KPIF
</code>```

Then apply the rownames:

```<code>> rownames(KPIF) <- KPIF[,'namePill']
> KPIF
           namePill KPIPill
pill_tech pill_tech     0.3
pill_EUX   pill_EUX     0.2
pill_Bus   pill_Bus     0.3
</code>```

Then drop the unnecessary column, suggesting that your data frame is a larger one having more columns:

```<code>> KPIF <- KPIF[!(colnames(KPIF) %in% 'namePill')]
> KPIF
          KPIPill
pill_tech     0.3
pill_EUX      0.2
pill_Bus      0.3
</code>```

Title: Convert column into object in R

Body:
I wanna convert first column into object in R so if the input looks like:

#name of df - KPIF
    namePill KPIPill
1: pill_tech     0.3
2:  pill_EUX     0.2
3:  pill_Bus     0.3

the output should looks like:

#name of df - KPIF
           KPIPill
pill_tech    0.3
pill_EUX     0.2
pill_Bus     0.3

Anyone could help ?
Regards,
Aleksandra

Body:
First create the data frame:

KPIF <- data.frame(namePill=c('pill_tech','pill_EUX','pill_Bus'),
                   KPIPill=c(0.3,0.2,0.3))
KPIF

Then apply the rownames:

> rownames(KPIF) <- KPIF[,'namePill']
> KPIF
           namePill KPIPill
pill_tech pill_tech     0.3
pill_EUX   pill_EUX     0.2
pill_Bus   pill_Bus     0.3

Then drop the unnecessary column, suggesting that your data frame is a larger one having more columns:

> KPIF <- KPIF[!(colnames(KPIF) %in% 'namePill')]
> KPIF
          KPIPill
pill_tech     0.3
pill_EUX      0.2
pill_Bus      0.3


问:
In Angular JS change in Model value is not reflected in directive's template
I'm new to AngularJS. I'm creating a directive with a template search-result. and using the directive inside main.html. which corresponds to mainController. Index.html binds model value handle with the textbox. Changing the text in textbox changes $scope.handle value but why the change is not reflected in main.html using the directive's template

In index.html in

```<code><div ng-controller="mainController">
    <h1>Its the second Controller</h1>
    <input type="text" ng-model ="handle" name= "myField"/>
</div>
</code>```

In app.js

```<code>myApp.directive("searchResult", function(){
    return {
        restrict:"AECM",
        templateUrl:'Directives/search-result.html',
        replace:true
    }
})
</code>```

In main.html

```<code><div class="container">
      <search-result></search-result>
</div>
</code>```

In search-result.html

```<code><a href="#" class="list-group-item">
    <p class="list-group-item-text">{{handle}}</p>
</a>
</code>```

答:
Directives inherit their parent's controller scope by default. But it seems you are placing the searchResult directive outside the mainController, so the directive will not have access to the $scope.handle value.

Place the search result inside the main controller to be able to access it's scope from the directive.

Body:
I'm new to AngularJS. I'm creating a directive with a template search-result. and using the directive inside main.html. which corresponds to mainController. Index.html binds model value handle with the textbox. Changing the text in textbox changes $scope.handle value but why the change is not reflected in main.html using the directive's template

In index.html in

Its the second Controller

    <input type="text" ng-model ="handle" name= "myField"/>

In app.js

myApp.directive("searchResult", function(){
    return {
        restrict:"AECM",
        templateUrl:'Directives/search-result.html',
        replace:true
    }
})

In main.html

      <search-result></search-result>

In search-result.html

{{handle}}


问:
Github commits from different PC's
Quick question, if i have different PC's which share the same/different projects which I would like to make commits to.

How can I make sure that all the commits will be made from my GitHub account owner? Right now, it commits with the PC username instead of my GitHub account.

答:
You can set your Git username the following way:

Open Git Bash.

Set a Git username:

$ git config --global user.name "Mona Lisa"

Confirm that you have set the Git username correctly:

$ git config --global user.name

Will output Mona Lisa

Reference: https://help.github.com/articles/setting-your-username-in-git/

Title: Github commits from different PC's


问:
how to reorder an string xml in c#
I have an XML-string and a unique tag value. Based on that tag value, how can I reorder the below XML? I want the specific tag value to be on the top.

<DataSet>
  <Row>
    <APPROVER>DSQF</APPROVER>
    <LEVEL>3</LEVEL>
    <LEVELDECODE>Supervisor</LEVELDECODE>
  </Row>
  <Row>
    <APPROVER>ASDQD</APPROVER>
    <LEVEL>3</LEVEL>
    <LEVELDECODE>Supervisor</LEVELDECODE>
  </Row>
  <Row>
    <APPROVER>ASDQTH</APPROVER>
    <LEVEL>3</LEVEL>
    <LEVELDECODE>Supervisor</LEVELDECODE>
  </Row>
</DataSet>
```

I want the row  with approver = ASDQD to be on the top (approver is selected by user).

答:
I use the page to create a c# class http://xmltocsharp.azurewebsites.net/

Generated class:

```<code>using System;
using System.Xml.Serialization;
using System.Collections.Generic;
namespace Xml2CSharp
{
    [XmlRoot(ElementName="Row")]
    public class Row {
        [XmlElement(ElementName="APPROVER")]
        public string APPROVER { get; set; }
        [XmlElement(ElementName="LEVEL")]
        public string LEVEL { get; set; }
        [XmlElement(ElementName="LEVELDECODE")]
        public string LEVELDECODE { get; set; }
    }

    [XmlRoot(ElementName="DataSet")]
    public class DataSet {
        [XmlElement(ElementName="Row")]
        public List<Row> Row { get; set; }
    }

}
</code>```

Afterwards use XMLSerialzer and then lambda expression to order by approver.

Title: how to reorder an string xml in c#

Body:
I have an XML-string and a unique tag value. Based on that tag value, how can I reorder the below XML? I want the specific tag value to be on the top.

<DataSet>
  <Row>
    <APPROVER>DSQF</APPROVER>
    <LEVEL>3</LEVEL>
    <LEVELDECODE>Supervisor</LEVELDECODE>
  </Row>
  <Row>
    <APPROVER>ASDQD</APPROVER>
    <LEVEL>3</LEVEL>
    <LEVELDECODE>Supervisor</LEVELDECODE>
  </Row>
  <Row>
    <APPROVER>ASDQTH</APPROVER>
    <LEVEL>3</LEVEL>
    <LEVELDECODE>Supervisor</LEVELDECODE>
  </Row>
</DataSet>

I want the row  with approver = ASDQD to be on the top (approver is selected by user).

Body:
I use the page to create a c# class http://xmltocsharp.azurewebsites.net/

Generated class:

using System;
using System.Xml.Serialization;
using System.Collections.Generic;
namespace Xml2CSharp
{
    [XmlRoot(ElementName="Row")]
    public class Row {
        [XmlElement(ElementName="APPROVER")]
        public string APPROVER { get; set; }
        [XmlElement(ElementName="LEVEL")]
        public string LEVEL { get; set; }
        [XmlElement(ElementName="LEVELDECODE")]
        public string LEVELDECODE { get; set; }
    }

    [XmlRoot(ElementName="DataSet")]
    public class DataSet {
        [XmlElement(ElementName="Row")]
        public List<Row> Row { get; set; }
    }

}

Afterwards use XMLSerialzer and then lambda expression to order by approver.


问:
function remove a word depending of a number - c programming
I have been stuck with this problem over 4 days:

Write a function skipWords() that takes a string named sentence and an integer named words as arguments. The function should return a pointer
  to a substring of sentence. The function should skip the number of words indicated by the parameter words.

If words is, for instance, 0, then a pointer to the beginning of the string sentence should be returned (that is, no words are skipped). If words is 1, then a pointer to the second word of sentence should be returned (i.e., one word is skipped), etc
 . To see how it should work, see the example below. The function may not print anything on the screen or take any input from the user. If words is greater or equal to the number of words in sentence, then the pointer NULL should be returned.

Example: char *ptr1, *ptr2, *ptr3, *ptr4;
 ptr1 = skipWords(“there you go”, 1); /* ptr1 points to “you go” */
ptr2 = skipWords(“there you go”, 2); /* ptr2 points to “go” */
ptr3 = skipWords(“a string”, 0); /* ptr3 points to “a string” */
ptr4 = skipWords(“a word”, 2); /* ptr4 is NULL */

got the code :

```<code>int skipWords(char sentence[], int words)
{
    int i;
    int len;

    len =strlen(sentence);

    if(words == 0)
    {
        sentence[i];
    }

    if(words == 1 && words<len)
    {

    *newsentence[i]=sentence[i];
    while (isalpha(newsentence[i])) //checking for the first blank space
    {
        i++;
    }
    newsentence[i] = '\0';

    *sentence[i]= newsentence[i]-i++;   //new string without the first word
    }

    if(words == 2 && len<words)
    {

    *newsentence[i]=sentence[i];
    // and i am lost

    else if (words>=len)
        *sentence=NULL;

}

int main()
{

    char *ptr1, *ptr2, *ptr3, *ptr4;
    ptr1= skipWords("there you go", 1);
    ptr2=skipWords("there you go", 2);
    ptr3=skipWords("a string", 0);
    ptr4=skipWords("a word",2);

    printf("%s\n", ptr1);
    printf("%s\n", ptr2);
    printf("%s\n", ptr3);
    printf("%s\n", ptr4);

    return 0;
}
</code>```

but I am completely lost.

答:
We beginners should help each other.:)

Here you are

```<code>#include <stdio.h>
#include <ctype.h>

char * skipWords( const char *s, size_t n )
{
    if ( n )
    {
        while ( isblank( ( unsigned char )*s ) ) ++s;

        do
        {
            while ( *s && !isblank( ( unsigned char )*s ) ) ++s;
            while ( isblank( ( unsigned char )*s ) ) ++s;
        } while ( *s && --n );
    }

    return ( char * ) ( *s ? s : NULL );
}

int main(void)
{
    char *ptr1, *ptr2, *ptr3, *ptr4;

    ptr1 = skipWords( "there you go", 1);

    if ( ptr1 ) puts( ptr1 );
    else puts( "NULL" );

    ptr2 = skipWords( "there you go", 2 );

    if ( ptr2 ) puts( ptr2 );
    else puts( "NULL" );

    ptr3 = skipWords( "a string", 0 );

    if ( ptr3 ) puts( ptr3 );
    else puts( "NULL" );

    ptr4 = skipWords( "a word", 2);

    if ( ptr4 ) puts( ptr4 );
    else puts( "NULL" );

    return 0;
}
</code>```

The program output is

```<code>you go
go
a string
NULL
</code>```

As for your code then for starters the function should be declared at least like

```<code>char * skipWords(char sentence[], int words);
^^^^^^
</code>```

instead of

```<code>int skipWords(char sentence[], int words);
^^^
</code>```

and even in the very beginning of the code there is used uninitialized variable i  that produces undefined behavior of the program.

```<code>int i;
int len;

len =strlen(sentence);

if(words == 0)
{
    sentence[i];
            ^^^^
}
// ...
</code>```

Body:
I have been stuck with this problem over 4 days:

Write a function skipWords() that takes a string named sentence and an integer named words as arguments. The function should return a pointer
  to a substring of sentence. The function should skip the number of words indicated by the parameter words.

If words is, for instance, 0, then a pointer to the beginning of the string sentence should be returned (that is, no words are skipped). If words is 1, then a pointer to the second word of sentence should be returned (i.e., one word is skipped), etc
 . To see how it should work, see the example below. The function may not print anything on the screen or take any input from the user. If words is greater or equal to the number of words in sentence, then the pointer NULL should be returned.

Example: char *ptr1, *ptr2, *ptr3, *ptr4;
 ptr1 = skipWords(“there you go”, 1); /* ptr1 points to “you go” */
ptr2 = skipWords(“there you go”, 2); /* ptr2 points to “go” */
ptr3 = skipWords(“a string”, 0); /* ptr3 points to “a string” */
ptr4 = skipWords(“a word”, 2); /* ptr4 is NULL */

got the code :

int skipWords(char sentence[], int words)
{
    int i;
    int len;

    len =strlen(sentence);

    if(words == 0)
    {
        sentence[i];
    }

    if(words == 1 && words<len)
    {

    *newsentence[i]=sentence[i];
    while (isalpha(newsentence[i])) //checking for the first blank space
    {
        i++;
    }
    newsentence[i] = '\0';

    *sentence[i]= newsentence[i]-i++;   //new string without the first word
    }

    if(words == 2 && len<words)
    {

    *newsentence[i]=sentence[i];
    // and i am lost

    else if (words>=len)
        *sentence=NULL;

}

int main()
{

    char *ptr1, *ptr2, *ptr3, *ptr4;
    ptr1= skipWords("there you go", 1);
    ptr2=skipWords("there you go", 2);
    ptr3=skipWords("a string", 0);
    ptr4=skipWords("a word",2);

    printf("%s\n", ptr1);
    printf("%s\n", ptr2);
    printf("%s\n", ptr3);
    printf("%s\n", ptr4);

    return 0;
}

but I am completely lost.

Body:
We beginners should help each other.:)

Here you are

#include <stdio.h>
#include <ctype.h>

char * skipWords( const char *s, size_t n )
{
    if ( n )
    {
        while ( isblank( ( unsigned char )*s ) ) ++s;

        do
        {
            while ( *s && !isblank( ( unsigned char )*s ) ) ++s;
            while ( isblank( ( unsigned char )*s ) ) ++s;
        } while ( *s && --n );
    }

    return ( char * ) ( *s ? s : NULL );
}

int main(void)
{
    char *ptr1, *ptr2, *ptr3, *ptr4;

    ptr1 = skipWords( "there you go", 1);

    if ( ptr1 ) puts( ptr1 );
    else puts( "NULL" );

    ptr2 = skipWords( "there you go", 2 );

    if ( ptr2 ) puts( ptr2 );
    else puts( "NULL" );

    ptr3 = skipWords( "a string", 0 );

    if ( ptr3 ) puts( ptr3 );
    else puts( "NULL" );

    ptr4 = skipWords( "a word", 2);

    if ( ptr4 ) puts( ptr4 );
    else puts( "NULL" );

    return 0;
}

The program output is

you go
go
a string
NULL

As for your code then for starters the function should be declared at least like

char * skipWords(char sentence[], int words);
^^^^^^

instead of

int skipWords(char sentence[], int words);
^^^

and even in the very beginning of the code there is used uninitialized variable i  that produces undefined behavior of the program.

int i;
int len;

len =strlen(sentence);

if(words == 0)
{
    sentence[i];
            ^^^^
}
// ...


问:
How to convert local time to UTC time same date but time set to midnight
I have this time

```<code>Tue Dec 05 2017 17:05:51 GMT+0530 (IST)
</code>```

I want to convert this into

```<code>Tue Dec 05 2017 00:00:00 GMT
</code>```

答:
Because you're asking for UTC I think this one is the easiest:

var input = "Tue Dec 05 2017 17:05:51 GMT+0530 (IST)"
var date = new Date(input);
date.setHours(1);
date.setMinutes(0);
date.setSeconds(0);
date.setMilliseconds(0);
console.log(date.toUTCString());```

Body:
I have this time

Tue Dec 05 2017 17:05:51 GMT+0530 (IST)

I want to convert this into

Tue Dec 05 2017 00:00:00 GMT


问:
How to get all headers in array
I tried to get all headers in handler and faced some difficulties.

valyala/fasthttp has the needed methods and I can get headlines one by one, but I don`t see the obvious way to get all of the headers.

So, How can I get all of the headers into an array?

答:
Use request.Header.VisitAll. See related doc.

```<code>r.Header.VisitAll(func (key, value []byte) {
    log.Printf("%v: %v", key, value)
})
</code>```

ContentLicense: CC BY-SA 4.0

Title: How to get all headers in array

Body:
Use request.Header.VisitAll. See related doc.

r.Header.VisitAll(func (key, value []byte) {
    log.Printf("%v: %v", key, value)
})


问:
python pandas dataframe to matlab struct using scipy.io
I am trying to save a pandas dataframe to a matlab .mat file using scipy.io.

I have the following:

```<code>array1 = np.array([1,2,3])
array2 = np.array(['a','b','c'])
array3 = np.array([1.01,2.02,3.03])
df = DataFrame({1:array1, 2:array2,3:array3}, index=('array1','array2','array3'))
recarray_ = df.to_records()
## Produces:
# rec.array([('array1', 1, 'a', 1.01), ('array2', 2, 'b', 2.02),
#   ('array3', 3, 'c', 3.03)],
#  dtype=[('index', 'O'), ('1', '<i4'), ('2', 'O'), ('3', '<f8')])
scipy.io.savemat('test_recarray_struct.mat', {'struct':df.to_records()})
</code>```

In Matlab, I would expect this to produce a struct containing three arrays (one int, one char, one float) but it actually produces is a struct containing 3 more structs, each containing four variables; 'index', 1, '2', 3. When trying to select 1, '2' or 3 I get the error 'The variable struct(1, 1).# does not exist.'

Can anyone explain the expected behaviour and how best to save DataFrames to .mat files?

答:
I think what you need is to create the dataframe like this:

```<code>df = DataFrame({'array1':array1, 'array2':array2,'array3':array3})
</code>```

and save it like this:

```<code>scipy.io.savemat('test_recarray_struct.mat', {'struct':df.to_dict("list")})
</code>```

So the code should be something like:

```<code># ... import appropritely
array1 = np.array([1,2,3])
array2 = np.array(['a','b','c'])
array3 = np.array([1.01,2.02,3.03])
df = DataFrame({'array1':array1, 'array2':array2,'array3':array3})
scipy.io.savemat('test_recarray_struct.mat', {'struct':df.to_dict("list")})
</code>```

Body:
I am trying to save a pandas dataframe to a matlab .mat file using scipy.io.

I have the following:

array1 = np.array([1,2,3])
array2 = np.array(['a','b','c'])
array3 = np.array([1.01,2.02,3.03])
df = DataFrame({1:array1, 2:array2,3:array3}, index=('array1','array2','array3'))
recarray_ = df.to_records()
## Produces:
# rec.array([('array1', 1, 'a', 1.01), ('array2', 2, 'b', 2.02),
#   ('array3', 3, 'c', 3.03)],
#  dtype=[('index', 'O'), ('1', '<i4'), ('2', 'O'), ('3', '<f8')])
scipy.io.savemat('test_recarray_struct.mat', {'struct':df.to_records()})

In Matlab, I would expect this to produce a struct containing three arrays (one int, one char, one float) but it actually produces is a struct containing 3 more structs, each containing four variables; 'index', 1, '2', 3. When trying to select 1, '2' or 3 I get the error 'The variable struct(1, 1).# does not exist.'

Can anyone explain the expected behaviour and how best to save DataFrames to .mat files?

Body:
I think what you need is to create the dataframe like this:

df = DataFrame({'array1':array1, 'array2':array2,'array3':array3})

and save it like this:

scipy.io.savemat('test_recarray_struct.mat', {'struct':df.to_dict("list")})

So the code should be something like:

# ... import appropritely
array1 = np.array([1,2,3])
array2 = np.array(['a','b','c'])
array3 = np.array([1.01,2.02,3.03])
df = DataFrame({'array1':array1, 'array2':array2,'array3':array3})
scipy.io.savemat('test_recarray_struct.mat', {'struct':df.to_dict("list")})


问:
CSS3 Flexbox row wrap is not working in iOS 8.3
CSS3 Flexbox row wrap is not working in iOS version 8.3 only. As per the suggestion on the link, I have updated my code. But still, it is not wrapping as expected.

`

```<code>.case-study-list {
        display: flex;
        justify-content: space-between;
        margin: 0 auto;
        padding: 0 0 30px;
        -webkit-flex-direction: row;
        flex-direction: row;
        -webkit-flex-wrap: wrap;
        flex-wrap: wrap;
        .case-study-item {
            list-style-type: none;
            min-width: 180px;
            padding: 30px 20px 0;
            -webkit-flex: 1 1 180px;
            -ms-flex: 1 1 180px;
            flex: 1 1 180px;
   }
}
</code>```

`

Please find the link to my fiddle.
I'm really stuck with this. Any help is much appreciated.

答:
Seems you missed to add prefix on display property. Safari 9 supports all standard flex properties, with Safari 8 and older you'll need to use vendor prefixes.

```<code>.case-study-list {
    display: -webkit-flex;
    display: flex;
}
</code>```

Here are some link's that might help you
CSS Autoprefixer
 FLEXBOX CHEAT SHEET

Body:
CSS3 Flexbox row wrap is not working in iOS version 8.3 only. As per the suggestion on the link, I have updated my code. But still, it is not wrapping as expected.

`

.case-study-list {
        display: flex;
        justify-content: space-between;
        margin: 0 auto;
        padding: 0 0 30px;
        -webkit-flex-direction: row;
        flex-direction: row;
        -webkit-flex-wrap: wrap;
        flex-wrap: wrap;
        .case-study-item {
            list-style-type: none;
            min-width: 180px;
            padding: 30px 20px 0;
            -webkit-flex: 1 1 180px;
            -ms-flex: 1 1 180px;
            flex: 1 1 180px;
   }
}

`

Please find the link to my fiddle.
I'm really stuck with this. Any help is much appreciated.

Body:
Seems you missed to add prefix on display property. Safari 9 supports all standard flex properties, with Safari 8 and older you'll need to use vendor prefixes.

.case-study-list {
    display: -webkit-flex;
    display: flex;
}

Here are some link's that might help you
CSS Autoprefixer
 FLEXBOX CHEAT SHEET