text:
Q: Convert drupal 7 content type into code automatically. Content type generator code? I already have a content type in my drupal project.
I am currently working on my own module and would like to create a built in content type.
Is there a way to convert a content type that I built directly in drupal into code ?
A kind of Content Type Code Generator ?.
I want to generate this code automatically if it's possible.
$t = get_t();

  // Define the node type.
  $slider = array(
    'type' => 'slider',
    'name' => $t('Slider Content'),
    'base' => 'node_content',
    'description' => $t('This is an example node type with a few fields.'),
    'body_label' => $t('Example Description')
  );

  // Complete the node type definition by setting any defaults not explicitly
  // declared above.
  // http://api.drupal.org/api/function/node_type_set_defaults/7
  $content_type = node_type_set_defaults($slider);
  node_add_body_field($content_type);

  // Save the content type
  node_type_save($content_type);

Thanks a lot.

A: Maybe you should have a look at Features module. Using Features should allow you to export your content type along with added fields into a module you can install to another site later.
Check this documentation link.

A: maybe this can help you.
add hook_install():
please check: http://yaremchuk.ru/blog/how-create-content-type-drupal-7-programmatically


text:
Q: Defining holomorphic function as an integral in $\mathbb{R}^n$ Let $U$ be a bounded connected subset of $\mathbb{R}^n$. Let $f:\mathbb{C} \times U \to \mathbb{C}$ such that
1) for all $(u_1,\ldots,u_n) \in U$ the function $z \mapsto f(z,u_1,\ldots,u_n)$ is holomorphic
2) for all $z\in \mathbb{C}$ the function
$(u_1,\ldots,u_n) \mapsto f(z,u_1,\ldots,u_n)$ is continuous
Can we conclude
$F(z) = \int_U f(z,u_1,\ldots,u_n) \;du_1 \cdots du_n$
is holomorphic on $\mathbb{C}$ ?

A: The answer is NO! The function
$$
f:\mathbb{C}\times(0,1) \to \mathbb{C},\ f(z,u)=\exp\left(\frac{z}{u}\right)
$$
satisfies all the conditions. However the function $(0,1) \to \mathbb{C}, z \mapsto f(z,u)$ is not integrable. In particular the function $F: \mathbb{C} \to \mathbb{C},\ F(z)=\int_0^1f(z,u)\,du$ is not well defined, and therefore it cannot be holomorphic.

redpajama_set_name: RedPajamaStackExchange


text:
Q: How can I add and remove notification observers when a UIViewController is pushed/pulled by a navigation controller? I usually add the UINotification observer in the init method and I remove them in dealloc.
However if I have a chain of UIViewControllers pushed by a UINavigationController, they are not deallocated when the next UIViewController is pushed. Consequently they all observe for the notification, and this is not what I want.
How can I add and remove notification observers when a UIViewController is pushed/pulled by a navigation controller ?

A: In order to get notified, you can set the delegate of the UINavigationController. This is quite cumbersome though, since the navigation controller only has one delegate. So in this case, I would have used viewDidAppear:animated, viewDidDisappear:animated and so on. These methods will be called on your view controllers as the navigation controller hides and shows them, and will also be called if you present a modal view controller in which case you probably also want to unregister notifications.

A: Adding a second answer with an example on how to achieve this with a UINavigationControllerDelegate.
Somewhere, set the delegate to the root view controller. Either with code or by connecting it in a nib. Make your root view controller a UINavigationControllerDelegate.
@interface MyViewController : UIViewController <UINavigationControllerDelegate>
    // ...
@end

Do this in the implementation of the root view controller
@implementation MyViewController
- (void)navigationController:(UINavigationController *)navigationController
      willShowViewController:(UIViewController *)viewController
                    animated:(BOOL)animated
{
    [viewController
        performSelector:@selector(willBeShownViaNavigationController)];

    [navigationController.visibleViewController
        performSelector:@selector(willBeHiddenViaNavigationController)];
}
@end

Make sure all the view controllers being used in that navigation controller implements those two methods.
Note: this code is untested, there may be some errors. But you should get the idea.

A: You need to subclass UINavigationController to keep track of whether it is pushing or popping.  Then in your viewWillAppear you can check to see if you're being pushed or popped.  I have a subclass for that Here


text:
Q: Continuously update state variable price from API call I have two state variables
const [cartList, setCartList] = useState([]);
const [tabledata, setTabledata] = useState(localStorage.getItem("items"))

tableData is initiated from local storage
cartList will be an array of objects with complete list and an example will be like
[
   {id: 1, name: pen, sku: 1001, price: 5},
   {id: 2, name: a4-book, sku: 1005, price: 2},
   {id: 3, name: usb-16gb, sku: 1010, price: 15},
   {id: 4, name: usb-32gb, sku: 1021, price: 28}
]

tableData is also an object array and will have some items and an example will be like
[
   {id: 2, name: a4-book, sku: 1005, price: 1.5},
   {id: 4, name: usb-32gb, sku: 1021, price: 22}
]

cartList has my latest price for each item, i want to update the tabledata to get the price for corresponding items (by id) from cartList every 5 minutes.
what is the best way to achieve this continuously ? so the tabledata element price is up to date with cartList price for corresponding items?

A: You can fetch cartList and update tableData and localStorage right away. However for doing this every 5 minutes, simply wrap the fetch call in a setInterval() call.
const FIVE_MINUTES_MS = 5 * 60 * 1000;
useEffect(() => {
  const interval = setInterval(() => fetch("/api/cartlist")
    .then(res => res.json())
    .then(list => {
      setCartList(list);
      const tableDataNew = tableData.map(item => ({
        ...item,
        price: list.find(cartItem => cartItem.name === item.name).price
      }));
      setTableData(tableDataNew);
      localStorage.setItem("items", JSON.stringify(tableDataNew));
    })
    .catch(err => console.error(err)), FIVE_MINUTES_MS);
  return () => clearInterval(interval);
}, []);

The important bit to understand here is that I copy the updated prices from cartList after it is fetched and then update tableData while also storing it in localStorage.
The return statement is to stop this process e.g. when the component unmounts.
I haven't tested this but I hope this gives an idea of the flow.


text:
Q: Embedding a Google Chart with iframe So basically I am trying to either use the googleViz package and/or just embed a published google chart within a tabPaenl as an iframe and then have it automatically adjust to fit within the tabPanel embedded within the respective tabPanel in an R Shiny Web App. Any thoughts and/or suggestions would be awesome.
so I tried just using googleVis package and it stops the r-shiny app from loading because googleVis wants to open a graph in a separate webpage.
Basically I have a fluidRow that has to tabBoxes
                  fluidRow(
                    tabBox(
                      title = "Visualization Trends",
                      # The id lets us use input$tabset1 on the server to find the current tab
                      id = "tabset1", height = "500px",
                      tabPanel("First Response",
                               "First Tab Content 1",
              I WANT TO EMBED THE CHART HERE
                               ),
                      tabPanel("Case Closure", "First Tab Content 2"),
                      tabPanel("SLA Met", "First Tab Content 3"),
                      tabPanel("SLA Missed", "Insert SLA Misses Content"),
                      tabPanel("Overall CR & MW", "Insert Google Chart")

The actual results have not been useful, and I am kind of stuck so I really just need some direction more than anything else.

A: So, this wasn't as hard as I thought it would be.
In order to embed the chart you have to publish it first and then select the embed option. You then copy all of the content with
<iframe>some_embedded_content<iframe>

After you copy this you can then embed it within a tabBox Panel as such:
                      fluidRow(
                    tabBox(
                      title = "Visualization Trends",
                      # The id lets us use input$tabset1 on the server to find the current tab
                      id = "tabset1", height = "500px",
                      tabPanel("First Response",
                               HTML('<iframe width="600" height="371" seamless frameborder="0" scrolling="no" src="https://docs.google.com/spreadsheets/d/e/2PACX-1vRNxLt1gp1TRc7sB83xjGpXLcLLUq8xH0B9iv1/pubchart?oid=1201606802&format=interactive"></iframe>')

                               )


text:
Q: parent_id получить дочерние категория или продукт
Например, я хочу показать/перечислить все продукты или дочерние категория под parent_id = 1

Структура таблицы моей базы данных

    CREATE TABLE `categories` (
  `category_id` int(10) NOT NULL,
  `parent_id` int(10) DEFAULT '0',
  `title` varchar(255) NOT NULL
) ENGINE=InnoDB DEFAULT CHARSET=latin1;

    CREATE TABLE `products` (
  `id` int(10) NOT NULL,
  `product` varchar(255) DEFAULT NULL,
  `description` longtext,
  `category` int(10) DEFAULT NULL
) ENGINE=InnoDB DEFAULT CHARSET=latin1;

category.php

    $parent_id = 3;

$query=mysqli_query($conn,"
SELECT * FROM products
LEFT JOIN categories
ON products.category = categories.category_id
GROUP BY (SELECT parent_id
          FROM categories
          WHERE parent_id = $parent_id
          GROUP BY parent_id)");

while ($row=mysqli_fetch_array($query))
{
    echo "
{$row['title']}
";
}


text:
Q: SQL (HSQLDB) query to create a pivot table equivalent in LibreOffice Base I'm working on a database in LibreOffice Base and trying to output the equivalent of a pivot table. Base uses HSQL which, I understand, doesn't support pivot, but the reports you can make with it are perfect for me so I want to stick with it.
There are three columns I want to involve in my pivot: Rotation, Modality and Number.
Here is an example of how the data looks at present:
Rotation    |   Modality    |   Number
1           |   1           |   5
1           |   2           |   3
1           |   3           |   4
2           |   1           |   6
2           |   1           |   5
2           |   3           |   2
3           |   1           |   1
3           |   2           |   4

As you can see, there are three modalities. You can have any number of modalities - zero or more per rotation.
And what I'm after (the sum of each modality per rotation):
Rotation    |   Modality 1  |   Modality 2  |   Modality 3
1           |   5           |   3           |   4
2           |   11          |   0           |   2
3           |   1           |   4           |   0

(I'd be equally happy with Modality and Rotation the other way around.) I've searched around a lot and have come up with two ways I think I should be able to achieve this: using CASE WHEN and using subqueries.
Trying CASE WHEN
Here is what I've tried:
SELECT   "Rotation"
   ,CASE "Modality" WHEN 1 THEN SUM( "Number" ) END
   ,CASE "Modality" WHEN 2 THEN SUM( "Number" ) END
   ,CASE "Modality" WHEN 3 THEN SUM( "Number" ) END
FROM     "my database"
GROUP BY "Rotation"
ORDER BY "Rotation"

This query returns a table that looks like the one above except instead of showing the sum of each modality, it shows the sum for all modalities in that rotation in one (seemingly) random column, like this:
Rotation    |   Modality 1  |   Modality 2  |   Modality 3
1           |               |               |   12
2           |               |               |   13
3           |   5           |               |

So something is wrong with the SUM() component of the query, I just can't figure out what.
Trying subqueries
SELECT  "Modality"
   ,( SELECT SUM( "Number" ) FROM "my database" WHERE "Rotation" = 1 AND "Modality" = 1 )
   ,( SELECT SUM( "Number" ) FROM "my database" WHERE "Rotation" = 2 AND "Modality" = 1 )
   ,( SELECT SUM( "Number" ) FROM "my database" WHERE "Rotation" = 3 AND "Modality" = 1 )
FROM "my database"
WHERE "Modality" = 1
GROUP BY "Modality"

That produces:
Modality    |   Rotation 1  |   Rotation 2  |   Rotation 3
1           |   5           |   11          |   1

Now obviously it only returns modality 1 due to the 'WHERE' clauses, but I can't figure out how to get all modalities displayed this subquery way. The subquery code also runs way slower than the CASE WHEN, which makes me wonder if it's the wrong way to go about this.

A: Your query was close, you just need to put the case statement inside of the sum statement to perform conditional aggregation:
SELECT   Rotation
   , SUM(CASE WHEN Modality = 1 THEN Number END )
   , SUM(CASE WHEN Modality = 2 THEN Number END )
   , SUM(CASE WHEN Modality = 3 THEN Number END )
FROM     yourtable
GROUP BY Rotation
ORDER BY Rotation


text:
Q: memory leak in iphone I m having leaks at this particular variable:
item = [[NSMutableDictionary alloc] init];

since i m using @property(nonatomic,retain) to synthesize the item. It's obvious to have leaks. I tried autorelease:
item = [[[NSMutableDictionary alloc] init] autorelease];

since I'm storing all the array content in items. The app crashes. I've tried releasing the memory content in dealloc, but there still are leaks. Could you guys help me out?

A: If you're synthesizing accessors, why aren't you using them?
Change this:
item = [[[NSMutableDictionary alloc] init] autorelease];

To this:
self.item = [NSMutableDictionary dictionary];


text:
Q: Regex pattern where matches img tags Using MVC, look at this example where we have the following HTML code:

Duma

Duma

I would like that print only the content of the tags, as:
Duma [IMAGE] Duma

Removing the image (showing [IMAGE]) tags and showing only the text (as innerText)
I decided to create an extension where until this moment, shows only
Duma Duma

public static class StringExtensions
{
    public static string StripHtml (this string inputString)
    {
       return Regex.Replace
         (inputString, "<.*?>", string.Empty);
    }
}

How can I do to add [IMAGE] everytime the regex matches with img tags

A: You can try this out:
public static class StringExtensions
{
    public static string StripHtml (this string inputString)
    {
       return Regex.Replace(
       Regex.Replace(inputString, "", "[IMAGE]"), "<.*?>", string.Empty);
    }
}

It actually calls two Reges.Replace() one inside other. !st one replaces the  tag to [IMAGE] followed by replacing rest of string leaving only the content inside
 tag.


text:
Q: Run Jar file with more than one argument I am building an optimization into a JPEG-Encoder written in Java. To do my benchmark i want to extract the orginal code and the optimized code into separated jars. Each jar has to take two arguments. The first on for the file name and the secound for the repeat of the compression of the jpeg.
public static void main(String[] args) {
    String filepath = args[0];
    try {
        int times = Integer.getInteger(args[1]);
        runBenchmark(filepath, times);
    } catch(IOException | NumberFormatException ioe) {
        System.out.println("Your arguments are Wrong! Use the follow order!");
        System.out.println("1. Argument must be the filename of the image.");
        System.out.println("2. Argument must be a number to repeat the compression.");
    }
}

This is my main, witch handle my args. I cant run the arguments on IntellJ . Even if I compile it the a jar, i cant pass my arg2.

I passed two arguments via configuration in intellj and i get a NullPointerException. So i tried to figure out if my java can take two arguments. I wrote a simple main in vim and compiled ran it with two args and worked. I repeated this in a new Project in intellj.
This is working. But why?

A: You have to check if the parameter is a int or not.
Use Integer.parseInt() and a try-catch block to inform the user if a failure happen.
int times = 0;
try {
  times = Integer.parseInt(args[1]);
} catch (Exception e) {
  System.out.println("failure with a parameter");
}

A: I changed the method to Integer.parseInt(string) and now it works. It was the Integer.getInt() it . I thought i had now 2. arg because I get the NullPointerException.
Now it work with this code.
public static void main(String[] args) {
    try {
        String filepath = args[0];
        int times = Integer.parseInt(args[1]);
        runBenchmark(filepath, times);
    } catch (NumberFormatException nfe) {
        System.out.println("2. Arg must be an number");
    } catch (IOException ioe) {
        System.out.println("File not found.");
    } catch(Exception e) {
        System.out.println("Your arguments are Wrong! Use the follow order!");
        System.out.println("1. Argument must be the filename of the image.");
        System.out.println("2. Argument must be a number to repeat the compression.");
    }
}


text:
Q: How to dynamically add MaximumValue for RangeValidator in GridView using c#? I have this RangeValidator
    <asp:RangeValidator ID="MarksValidation" runat="server" ErrorMessage="Invalid marks" ValidationGroup="Validation" Type="Integer" ControlToValidate="subject_marks" MinimumValue="-1" MaximumValue='' ></asp:RangeValidator>
<asp:TextBox ID="subject_marks" ControlStyle-CssClass="wide" runat="server" Text='<%# Eval("subject") %>' />

Now i want calculate max marks in c# in then assign that to MaximumValue of the RangeValidator.
How can I do this?

A: You can set the MaximumValue property in code behind with the expression you want.
MarksValidation.MaximumValue = expression;

Example:
MarksValidation.MaximumValue = 50*SomeValue;

Edit, based on comments, as validator is in GridView
protected void gvUserInfo_RowDataBound(object sender, GridViewRowEventArgs e)
{
   if (e.Row.RowType == DataControlRowType.DataRow)
   {
       RangeValidator rv = (RangeValidator)e.Row.FindControl("MarksValidation");
       rv.MaximumValue = 50*Convert.ToInt32(DataBinder.Eval(e.Row.DataItem, "ColumnFromDatabase"));;

   }
}


text:
Q: NHibernate Ordering more than 2 joined fields of a class I would like to ask on how you do ordering on an object with 2 properties that are basically joined from 2 entities.
Lets say "ClassA" has a property named ClassB and ClassC which are also classes themselves. ClassB has a property named Name and ClassC also has a property named Name. Now, since ClassB and ClassC are both properties of ClassA, how can i order a list of ClassAs using the Name properties of ClassB and ClassC. Below is the sample NHibernate criteria code in C#:
ICriteria criteria = m_Session.CreateCriteria<ClassA>()
     .AddOrder(Order.Asc("ClassB.Name"))
     .AddOrder(Order.Asc("ClassC.Name"));

But the above code throws an error saying that
 "could not resolve property: ClassB.Name of: ClassA". Any help would be appreciated. Thanks a lot.

A: You will need to alias the 2 associations (ClassB & ClassB) so that you can order by them.
ICriteria criteria = m_Session.CreateCriteria<ClassA>()
    .CreateAlias("ClassB", "b")
    .CreateAlias("ClassC", "c")
    .AddOrder(Order.Asc("b.Name"))
    .AddOrder(Order.Asc("c.Name"));


text:
Q: Laravel don't update DB model through XMLHttpRequest + Timeout For a few hours I am stuck on this problem.
I have a url
increase/1

and route
Route::get('increase/{id}', '***Controller@action***');

and controller
public function action***($id) {
    $model = ***::where***->first();
    $model->counter += 1;
    $model->save();
}

When I hit url in browser, counter is incremented -> DB updated.

When my template is rendered and I want to call this url through XMLHttpRequest. I have a script on the bottom of page (xhr.timeout is not important).
<script>
function pageViewIncrease() {
    var xhr = new XMLHttpRequest();
    xhr.open("GET", "{{ url() }}/increase/{{ id }}", true);
    xhr.timeout = 0;
    xhr.send(null);
}
    pageViewIncrease();
</script>

When template is rendered, counter is incremented -> DB updated.

But I want to call this "script" with delay.
setTimeout( pageViewIncrease, 290 );

With timeout, counter is sometimes incremented and sometimes not.
With bigger timeout (500,1000,...), Laravel not update model anymore.
I really don't know what am I doing wrong :(.
Thank you

A: I solved it.
I found out "delayed request content" is from cache.

Then I edit my code with help from "Problems with cached result when sending a XMLHttpRequest?".
xhr.open("GET", "{{ url() }}/increase/{{ id }}?t=" + Math.random(), true);

and my code is working even with
setTimeout( pageViewIncrease, 3000 );


text:
Q: Backbone router.navigate doesn't trigger I have a problem with my router not redirecting when i call navigate.
Im running a Rails setup with the 'backbone-on-rails' gem.
The problem seems to be related to how the app is initialised.
App
window.App =
  Models: {}
  Collections: {}
  Views: {}
  Routers: {}
  initialize: ->
    new App.Routers.Main()
    Backbone.history.start({pushState: true})

$ ->
  App.initialize()

Router
class App.Routers.Main extends Backbone.Router

  routes:
    '': 'index'
    'login': 'login'

  initialize: ->
    # Check login status
    @check_login_status()

  initialize_layout: ->
    # Default layout template
    layout        = new App.Views.Layout
    $('#main').html( layout.render().el )

    # Navigation template
    navigation  = new App.Views.Navigation(user: @current_user)
    $('#main nav[role="top"]').html( navigation.render().el )

    # Return this
    this

  index: ->
    @initialize_layout() unless @current_user.get('company_id') is null
    this

  login: ->
    layout        = new App.Views.Layout
    $('#main').html( layout.render().el )

    login       = new App.Views.Login
    $('#main .container-fluid').html(login.render().el)

  check_login_status: ->
    @current_user = new App.Models.CurrentUser
    @current_user.fetch({
      async: false
      success: (data, status, xhr) ->

        # If no user is logged in, and we arent on the login page, redirect to it
        if data.get('company_id') is null and window.location.pathname isnt '/login'
          # Navigate to login page
          window.location.href = '/login'

    })

In my router i have an initialise function that checks wether or not the user is logged in. I console.log a simple status to easily verify it, and indeed it logs out 'not logged in'.
Despite that, the navigate doesnt redirect to /login.
If i start backbone history before i start the router, then the navigate part works, but when i refresh the page (cmd+r) then the router doesn't run the index method.

A: The reason the navigation to /login doesn't trigger the route login is the leading forward slash. If you leave out the forward slash, it should work:
self.navigate('login', {trigger: true})

Forward slash -prefixed URL means that the route should be found at the domain's root, i.e. domain.com/login. To maintain the flexibility to run your application in a URL that's not in the application's root, say, domain.com/en/login, you should prefer the relative URL format.
You also say:

start backbone history before i start the router, then the navigate part works

This is probably not a good idea. I don't know exactly how it "works", but the Backbone documentation is quite clear on this topic:

During page load, after your application has finished creating all of its routers, be sure to call Backbone.history.start(), or Backbone.history.start({pushState: true}) to route the initial URL.


text:
Q: Android: requestLocationUpdates throws exception I'm trying to get periodically the user position via GPS in Android and send the data to a remote DB, but I get the exception: Can't create handler inside thread that has not called Looper.prepare().
The method that retrieves the position is in a remote service, and it's pretty basic:
private void dumpLocationLog() {
        LocationManager lm = (LocationManager) getSystemService(Context.LOCATION_SERVICE);
        Looper.myLooper().prepare();
        lm.requestLocationUpdates(LocationManager.GPS_PROVIDER, 1000L, 500.0f ,this);
        retrieveUserId();
        sendData(user_id);
    }

I tried calling Looper.myLooper().prepare(); but it still does not work.
I guess I have to implement a Looper here but I don't know how as I'm still pretty newbie with Android.
This is the full code of my service:
public class LocationLoggingService extends Service {
    String latString, lngString;
    Double latitude, longitude;
    Date durationDate;
    String user_id;
    public String username;

    private Handler serviceHandler;
    private Task myTask = new Task();

    @Override
    public IBinder onBind(Intent i) {
        Log.d(getClass().getSimpleName(), "onBind()");
        username = i.getStringExtra("username");
        return myRemoteLocationServiceStub;
    }

    private IMyRemoteLocationLoggingService.Stub myRemoteLocationServiceStub = new IMyRemoteLocationLoggingService.Stub() {
        public void dumpLocationLog() throws RemoteException {
            LocationLoggingService.this.dumpLocationLog();
        }
    };

    @Override
    public void onCreate() {
        super.onCreate();
        Log.d(getClass().getSimpleName(), "onCreate()");
    }

    @Override
    public void onDestroy() {
        super.onDestroy();
        serviceHandler.removeCallbacks(myTask);
        serviceHandler = null;
        Log.d(getClass().getSimpleName(), "onDestroy()");
    }

    @Override
    public void onStart(Intent intent, int startId) {
        username = intent.getStringExtra("username");
        super.onStart(intent, startId);
        serviceHandler = new Handler();
        serviceHandler.postDelayed(myTask, 1000L);
        Log.d(getClass().getSimpleName(), "onStart()");
    }

    class Task implements Runnable {
        public void run() {
            try {
                myRemoteLocationServiceStub.dumpLocationLog();
            } catch (RemoteException e) {
                e.printStackTrace();
            }
            serviceHandler.postDelayed(this, 5000L);
            Log.i(getClass().getSimpleName(), "Calling the dumpLocationLog");
        }
    }

    public void retrieveUserId() {
        ArrayList<NameValuePair> postParameters = new ArrayList<NameValuePair>();
        postParameters.add(new BasicNameValuePair("username", username));
        String response = null;
        try {
            response = CustomHttpClient.executeHttpPost(
                    "http://10.0.2.2/science/getUserId.php", postParameters);
            String res = response.toString();
            res = res.replaceAll("\\s+", "");
            if (!res.equals("0")) {
                Log.d(getClass().getSimpleName(),
                        "Successfully retrieved user_id");
                user_id = res;
            } else {
                Log.d(getClass().getSimpleName(), "Error retrieving user_id");
            }
        } catch (Exception e) {
        }
    }

    private void sendData(String user_id) {
        ArrayList<NameValuePair> postParameters = new ArrayList<NameValuePair>();
        postParameters.add(new BasicNameValuePair("user_id", user_id));
        postParameters.add(new BasicNameValuePair("latitude", latString));
        postParameters.add(new BasicNameValuePair("longitude", lngString));
        String response = null;
        try {
            response = CustomHttpClient.executeHttpPost(
                    "http://10.0.2.2/science/sendLocationData.php",
                    postParameters);
            String res = response.toString();
            res = res.replaceAll("\\s+", "");
            if (res.equals("1")) {
                Log.d(getClass().getSimpleName(), "Insertado en DB!");
            } else {
                Log.d(getClass().getSimpleName(), "Error insertando en la DB");
            }
        } catch (Exception e) {
        }
    }

    LocationListener myLocationListener = new LocationListener () {
        @Override
        public void onLocationChanged(Location location) {
            if (location != null) {
                android.os.Debug.waitForDebugger();
                latitude = location.getLatitude();
                longitude = location.getLongitude();
                latString = Double.toString(latitude);
                lngString = Double.toString(longitude);
                Log.d("Location: ", getClass().getSimpleName());
                Log.d(latString, getClass().getSimpleName());
                Log.d(lngString, getClass().getSimpleName());
            }
        }

        @Override
        public void onProviderDisabled(String provider) {
        }

        @Override
        public void onProviderEnabled(String provider) {
        }

        @Override
        public void onStatusChanged(String provider, int status, Bundle extras) {

        }
    };

    private void dumpLocationLog() {
        LocationManager lm = (LocationManager) getSystemService(Context.LOCATION_SERVICE);
        lm.requestLocationUpdates(LocationManager.GPS_PROVIDER, 1000L, 500.0f, myLocationListener);
        retrieveUserId();
        sendData(user_id);
    }

    public static String create_datestring(String timestring)
            throws java.text.ParseException {
        SimpleDateFormat sdf = new SimpleDateFormat("yyyy-MM-dd HH:mm:ss",
                Locale.US);
        Date dt = null;
        Calendar c = Calendar.getInstance();
        try {
            dt = sdf.parse("2011-03-01 17:55:15");
            c.setTime(dt);
            System.out.println(c.getTimeInMillis());
            System.out.println(dt.toString());
        } catch (ParseException e) {
            System.err.println("There's an error in the Date!");
        }
        return dt.toString();
    }
}

Thanks a lot in advance!

A: The proper way to use the message looper is described in its doc with a code sample here

A: Well finally the solution is:
Class LoggingService.java (this is my service):
private void dumpLocationLog() {
        new DumpLocationLog(context, latString, lngString).start();
        Log.d(latString, getClass().getSimpleName());
        Log.d(lngString, getClass().getSimpleName());
        retrieveUserId();
        sendData(user_id);
    }

Then in DumpLocationLog.java:
public class DumpLocationLog extends Thread {
    LocationManager lm;
    LocationHelper loc;
    String latString, lngString = null;

    public DumpLocationLog(Context context, String latString, String lngString) {
        loc = new LocationHelper();
        lm = (LocationManager)context.getSystemService(Context.LOCATION_SERVICE);
    }

    public void run() {
        Looper.prepare();
        lm.requestLocationUpdates(LocationManager.GPS_PROVIDER, 1000L, 500.0f, loc);
        Looper.loop();
    }
}

Then finally the LocationHelper for the LocationListener interface:
public class LocationHelper implements LocationListener {
    public String latString, lngString;
    public Double latitude, longitude;

    @Override
    public void onLocationChanged(Location location) {
        if (location != null) {
            latitude = location.getLatitude();
            longitude = location.getLongitude();
            LocationLoggingService.latString = Double.toString(latitude);
            LocationLoggingService.lngString = Double.toString(longitude);
        }
    }

    @Override
    public void onProviderDisabled(String provider) {
    }

    @Override
    public void onProviderEnabled(String provider) {
    }

    @Override
    public void onStatusChanged(String provider, int status, Bundle extras) {

    }
}

It works like a charm but I have realized, that when listening for locations, it's creating threads non-stop and never closing the former ones; I mean that every time it checks for location, it creates a new thread and after X minutes, there are hundreds of threads.
Anybody knows why?

A: What I was suggesting you do was
class DumpLocationLog extends Thread
{
    public void run()
    {
        LocationManager lm = (LocationManager) getSystemService(Context.LOCATION_SERVICE);
        lm.requestLocationUpdates(LocationManager.GPS_PROVIDER, 1000L, 500.0f ,/* FIXME this */);
        retrieveUserId();
        sendData(user_id);
    }
}

Then, from wherever you had been calling dumpLocationLog(), use runOnUiThread(new DumpLocationLog()) instead.

A: You can use this approach:

    class DumpLocationLog extends Thread
    {
    public void run()
    {
        Looper.prepare();
        mLooper = Looper.myLooper();
        lm.requestLocationUpdates(LocationManager.GPS_PROVIDER, 1000L, 500.0f ,mLooper);
        retrieveUserId();
        sendData(user_id);
        Looper.loop();
    }
    public void stop()
    {
       mLooper.quit();
    }
    }


text:
Q: Laurent Series of $\frac{e^z}{z(1+z^2)}$ [at z=0] How to get the Laurent Series of $$\frac{e^z}{z(1+z^2)}$$ at $z=0$?
I know the answer is
$$\frac{1}{z} + 1 - \frac{1}{2}z - \frac{5}{6}z^2 + \frac{13}{24}z^3 + \frac{101}{120}z^4 + O(z^5)$$
But I don't know how to do it, wanna know the step...

A: There is no simple formula for that. You know that$$\frac{e^z}{1+z^2}=\left(1+\frac z{1!}+\frac{z^2}{2!}+\frac{z^3}{3!}\cdots\right)\left(1-z^2+z^4-z^6+\cdots\right).$$You compute the first few terms and then you divide by $z$ to get the Laurent series.


text:
Q: How to auto terminate ProcessGroup output port? I have designed a process group with several output ports, but when I want to use them, I have to connect all output port to another processors, otherwise flowfiles accumulate in output port.
Is there any way to auto terminate output port for a process group like what we can do for processors by set Automatically Terminate Relationships?
I realized that flowfile expiration can be used to prevent accumulation of flowfile. But I am looking for better method.

A: If you have an output port then it is expected to be connected somewhere in order to be valid. If you aren't going to connect it somewhere, then you wouldn't have the port. You would just auto-terminate the processors before that, or send everything to a dead-end processor like UpdateAttribute that does nothing and is auto-terminated.


text:
Q: Prove that $10 | (n^a - n^b)$. $n$ is a positive integer. Prove that there exists positive integers $a$ and $b$, $(a > b)$ such that $10 | (n^a - n^b)$.
I have tried to prove this by induction on $n$, but I get stuck at the induction step trying to prove it for $n = k + 1$, not knowing how to expand $((k + 1)^a - (k + 1)^b)$. Is this the wrong approach to solving this problem, or am I missing something here?

A: As suggested in the comment by Akiva Weinberger, take $a=5$ and $b=1$.
Then $(k+1)^a-(k+1)^b=(k+1)^5-(k+1)=(k+1)[(k+1)^4-1]$
$=(k+1)(k^4+4k^3+6k^2+4k)=(k+1)k(k^3+4k^2+6k+4)$.
This is divisible by $2$ because  $(k+1)k$ is,
and modulo $5$ this is the same as $(k+1)k(k-1)(k^2+1)$, so it is divisible by $5$ too,
and therefore it is divisible by $10$.

A: We have $n^{a} - n^{b} \equiv 0\pmod 2$ since if $n \equiv 1 \pmod 2$ , then $ n^{a} - n^{b}\equiv 1-1 \equiv 0\pmod 2$ and if $n\equiv 0 \pmod 2, n^{a} - n^{b}\equiv0-0 \equiv 0\pmod 2$.
If $5|n$, then $n^{a}-n^{b}\equiv0-0\equiv 0 \pmod 5$ and so $10|n^{a}-n^{b}$.
If $5 \nmid n$, then $n^{4} \equiv 1 \pmod 5$ by Fermat's little theorem so that $n^{8} \equiv 1 \pmod 5 \implies$
$n^{8}-n^{4} \equiv 0 \pmod 5$ and altogether, in this case, $10|n^{a}-n^{b}$ as well where $a=8$ and $b=4$.


text:
Q: How to use nested forms with different relations using the cocoon gem? My dilemma has been around for a week now, I am trying to solve it but so far I have not been able to, so I am asking for help.
I have a Model Dealership and others nested (DealershipsSetting, Address, Machines, Operators, Cards) where the has_one relation only applies to DealershipsSetting, so the others are has_many.
I can only write some information in the database tables, when I call the build method for each model of the nested forms, for example:
  def new
    @dealership = Dealership.new
    @ dealership.build_dealerships_setting if @ dealership.dealerships_setting.blank?
    @ dealership.addresses.build if @ dealership.addresses.blank?
...
  end

  def edit
    @ dealership.build_dealerships_setting if @ dealership.dealerships_setting.blank?
    @ dealership.addresses.build if @ dealership.addresses.blank?
...
  end

I realize:
a) The first thing I notice in the log is that the forms are redirected several times. It makes sense since I'm forcing them to build through the builds call (at least that's what I understand about it). But this is not the default behavior when using the gem, I tested in another application just to know how to use the gem by following the documentation https://github.com/nathanvda/cocoon
b) Due to the call of the build method, the forms come open (ready to receive the data), I do not know if it is the default behavior.
c) When I call Action New or Edit, I can not record more than one record (type, 2 addresses, 3 cards or N operators)
d) In the documentation I did not notice any call to the build method, I found in the searches to try to solve my problem, for example, https://share.atelie.software/rails-nested-attributes-com-has-many-42ecf6179871
e) If I remove the calls from the builds, following the examples available in the documentation, the fields appear hidden until you call through the link_to_add_association, but no data, from the nested forms, is saved.
When I set my dealerships_controller like this, I can't add any register in the database:
def new
   @dealership = Dealership.new
end
...
def create
   @dealership = Dealership.new(dealership_params)

   respond_to do |format|
     if @dealership.save
        format.html { redirect_to users_backend_dealerships_path, notice: 'Dealership was successfully created.' }
        format.json { render :show, status: :created, location: @dealership }
     else
        format.html { render :new }
        format.json { render json: @dealership.errors, status: :unprocessable_entity }
     end
   end
 end
....

def dealership_params
  params.require(:dealership).permit(
:fantasy_name, :social_name, :cpf, :cnpj, :municipal_registration, :state_registration, :credit, :phone, :manager_email, :is_available, :credits_package_id, dealerships_setting_attributes: [:id, :credit_alert, :contract_validity, :franchise_for_rent, :due_date, :credit_value, :is_available, :_destroy],addresses_attributes: [:id, :place, :neighborhood, :cep, :state, :city, :is_available, :_destroy], machines_attributes: [:id, :name, :model, :serial_number, :mac_address, :calibration_counter, :is_available, :_destroy], operators_attributes: [:id, :name, :cpf, :card, :is_available, :_destroy ], cards_attributes: [:id, :serial, :category, :credit_package, :client, :machine, :operator, :is_available, :_destroy ])
end

Like this, I can add one register by model in the database.
dealerships_controller
class UsersBackend :: DealershipsController <UsersBackendController
  before_action: set_dealership, only: [: show,: edit,: update,: destroy]
  before_action: get_credit_packages, only: [: edit,: update,: new]

 def index
    @dealerships = Dealership.includes(:dealerships_setting, :addresses, :machines, :operators, :cards)
  end

  def show
  end

  def add_credits
  end

  def new
    @dealership = Dealership.new
    @dealership.build_dealerships_setting if @dealership.dealerships_setting.blank?
    @dealership.addresses.build if @dealership.addresses.blank?
    @dealership.machines.build if @dealership.machines.blank?
    @dealership.operators.build if @dealership.operators.blank?
    @dealership.cards.build if @dealership.cards.blank?
  end

  def edit
    @dealership.build_dealerships_setting if @dealership.dealerships_setting.blank?
    @dealership.addresses.build if @dealership.addresses.blank?
    @dealership.machines.build if @dealership.machines.blank?
    @dealership.operators.build if @dealership.operators.blank?
    @dealership.cards.build if @dealership.cards.blank?
  end

  def create
    @dealership = Dealership.new(dealership_params)

    respond_to do |format|
      if @dealership.save
        format.html { redirect_to users_backend_dealerships_path, notice: 'Dealership was successfully created.' }
        format.json { render :show, status: :created, location: @dealership }
      else
        format.html { render :new }
        format.json { render json: @dealership.errors, status: :unprocessable_entity }
      end
    end
  end

  def update
    respond_to do |format|
      if @dealership.update(dealership_params)
        format.html { redirect_to users_backend_dealerships_path, notice: 'Dealership was successfully updated.' }
        format.json { render :show, status: :ok, location: @dealership }
      else
        format.html { render :edit }
        format.json { render json: @dealership.errors, status: :unprocessable_entity }
      end
    end
  end

def destroy
    @dealership.destroy
    respond_to do |format|
      format.html { redirect_to users_backend_dealerships_path, notice: 'Dealership was successfully destroyed.' }
      format.json { head :no_content }
    end
  end

  private

    def set_dealership
      @dealership = Dealership.find(params[:id])
    end

    def dealership_params
      params.require(:dealership).permit(:fantasy_name, :social_name, :cpf, :cnpj, :municipal_registration, :state_registration, :credit, :phone, :manager_email, :is_available, :credits_package_id,
        dealerships_setting_attributes: [:id, :credit_alert, :contract_validity, :franchise_for_rent, :due_date, :credit_value, :is_available, :_destroy],
        addresses_attributes: [:id, :place, :neighborhood, :cep, :state, :city, :is_available, :_destroy],
        machines_attributes: [:id, :name, :model, :serial_number, :mac_address, :calibration_counter, :is_available, :_destroy],
        operators_attributes: [:id, :name, :cpf, :card, :is_available, :_destroy ],
        cards_attributes: [:id, :serial, :category, :credit_package, :client, :machine, :operator, :is_available, :_destroy ]
        )
    end

    def get_credit_packages
      @credit_packages = CreditsPackage.where(media_owner: 0)
    end
end

model  dealership.rb
class Dealership < ApplicationRecord

  has_many :credits_packages

  has_one :dealerships_setting, dependent: :destroy, inverse_of: :dealership

  has_many :addresses, dependent: :destroy, inverse_of: :dealership
  has_many :machines, dependent: :destroy, inverse_of: :dealership
  has_many :operators, dependent: :destroy, inverse_of: :dealership
  has_many :cards, dependent: :destroy, inverse_of: :dealership

  accepts_nested_attributes_for :dealerships_setting, reject_if: :all_blank, allow_destroy: true

  accepts_nested_attributes_for :addresses, reject_if: :all_blank, allow_destroy: true
  accepts_nested_attributes_for :machines, reject_if: :all_blank, allow_destroy: true
  accepts_nested_attributes_for :operators, reject_if: :all_blank, allow_destroy: true
  accepts_nested_attributes_for :cards, reject_if: :all_blank, allow_destroy: true

  accepts_nested_attributes_for :users, reject_if: :all_blank, allow_destroy: true
end

model dealerships_setting
class DealershipsSetting < ApplicationRecord
  belongs_to :dealership, inverse_of: :dealerships_setting
end

model address.rb
class Address < ApplicationRecord
  belongs_to :dealership
end

form.html.erb (dealership)
<%= form_with(model: [ :users_backend, @dealership], local: true) do |form| %>

          <%= form.label :fantasy_name %>
               <%= form.text_field :fantasy_name, autofocus: true, class:"text-uppercase form-control", placeholder:t('place_holders.fantasy_name') %>

...

<%= form.fields_for :dealerships_setting, @dealership.dealerships_setting do |dealerships_setting| %>
     <%= render partial: 'dealerships_setting_fields', locals: { f: dealerships_setting } %>
  <% end %>

    <%= form.fields_for :addresses do |address| %>
<%= render partial: 'address_fields', locals: { f: address } %>
    <% end %>
    <%= link_to_add_association('Add address', form, :addresses) %>

....others nested forms...

_dealerships_setting_fields.html.erb

    <%= f.label :contract_validity %>
    <%= f.text_field :contract_validity, class:"form-control ", placeholder:t('place_holders.contract_validity') %>

 ...another fields...

_address_fields.html.erb

    <%= f.label :place %>
    <%= f.text_field :place, class:"text-uppercase form-control", placeholder:t('place_holders.place') %>

 ...another fields...

What do I need?
A - Manage dealerships, where they must have one configuration and one or more addresses, machines, operators and cards.
I will be very grateful to anyone who can help me.

A: Ok, so there were two main errors I encountered:

*

*your form tag was inside a div, but your form content spanned multiple divs. It will look correct but will not post the correct info in all cases

*secondly: you did have validations blocking the save, in my case, and then two things happened:

*

*you did not set @credit_packages in your create action, giving an error when rerendering the form

*you did not show any validation-error (so no feedback as to why the save failed)

So I did two things. In your dealerships_controller I edited the following line
before_action :get_credit_packages, only: [:edit, :update, :new, :create]

(also set credit packages on create)
And your _form.html.erb I moved the form_with directly under the row div, and added some rudimentary display of the validation errors. The row div was never closed. Your full form:

<%= action_message %>

  <%= form_with(model: [ :users_backend, @dealership], local: true) do |form| %>

      <%= @dealership.errors.messages.inspect %>

<%= t('labels.dealership_information') %>

              <%= form.label :fantasy_name %>
              <%= form.text_field :fantasy_name, autofocus: true, class:"text-uppercase form-control", placeholder:t('place_holders.fantasy_name') %>

              <%= form.label :social_name %>
              <%= form.text_field :social_name, class:"text-uppercase form-control", placeholder:t('place_holders.social_name') %>

                <%= form.label :phone %>
                <%= form.text_field :phone, class:"form-control", placeholder:t('place_holders.phone') %>

                <%= form.label :manager_email %>
                <%= form.text_field :manager_email, class:"text-downcase form-control", placeholder:t('place_holders.manager_email') %>

                <%= form.label :cpf %>
                <%= form.text_field :cpf, class:"form-control", placeholder:t('place_holders.cpf') %>

                <%= form.label :cnpj %>
                <%= form.text_field :cnpj, class:"form-control", placeholder:t('place_holders.cnpj') %>

                <%= form.label :municipal_registration %>
                <%= form.text_field :municipal_registration, class:"form-control form-control-user", placeholder:t('place_holders.municipal_registration') %>

                <%= form.label :state_registration %>
                <%= form.text_field :state_registration, class:"form-control form-control-user", placeholder:t('place_holders.state_registration') %>

              <%= form.label :credits_package %>
              <%= form.collection_select(:credits_package_id, @credit_packages, :id, :name, {:prompt => t('prompt.credits_package')}, { class:"form-control" }) %>

              <%= form.check_box :is_available, class:"custom-control-input" %>
              <%= form.label :is_available, class:"custom-control-label" %>

<%= t('labels.financial_settings') %>

              <%= form.fields_for :dealerships_setting, @dealership.dealerships_setting do |dealerships_setting| %>
                <%= render partial: 'dealerships_setting_fields', locals: { f: dealerships_setting } %>
              <% end %>

<%= t('labels.addresses') %>

                <%= form.fields_for :addresses do |address| %>
                  <%= render partial: 'address_fields', locals: { f: address } %>
                <% end %>
                <%= link_to_add_association('Adicionar endereço', form, :addresses) %>

<%= t('labels.machines') %>

                <%= form.fields_for :machines do |machine| %>
                  <%= render partial: 'machine_fields', locals: { f: machine } %>
                <% end %>
                <%= link_to_add_association('Adicionar equipamento', form, :machines) %>

<%= t('labels.operators') %>

                <%= form.fields_for :operators do |operator| %>
                  <%= render partial: 'operator_fields', locals: { f: operator } %>
                <% end %>
                <%= link_to_add_association('Adicionar operador', form, :operators) %>

<%= t('labels.cards') %>

              <%= form.fields_for :cards do |c| %>
                <%= render partial: 'card_fields', locals: { f: c } %>
              <% end %>
              <%= link_to_add_association('Adicionar cartão', form, :cards) %>

        <%= form.submit t('buttons.save'), class:"btn btn-success btn-user"%>

  <% end %>

And then I was able to save a dealership. The layout is now broken for some reason I do not understand, but I will let you fix that (the css class does not behave how I expect it?).
Note: this is one of the reasons I prefer (or advice) to use a library like haml, slim, .. because your view-code will be easier to read/maintain and will be correct.


text:
Q: Frobenius theorem: a variant? In a physics article I am reading [1] the author uses the following result, which he named Frobenius theorem:
If a vector field $F: \mathbb{R}^3 \rightarrow \mathbb{R}^3$ satisfies
$$F \cdot (\nabla \times F) = 0,\ \ \ \ \ \ \text{(A)}$$
denoting scalar product and vector product in this order, then there exists scalar fields $\lambda$ and $V$ such that $F = -\lambda \nabla V$.
The only relevant Frobenius theorem I can think of is the one in differential calculus but it is about linear PDEs whereas the equation (A) is quadratic in $F$. Thus I failed to find the connection. Did I miss something? Or is there another Frobenius theorem?
[1] H Urbantke, Force fields in which all orbits are planar, European Journal of Physics 7 (1986), 157

A: There are indeed a lot of cosmetically different "Frobenius theorem"s around. You shouldn't be thinking of the $F \cdot \nabla \times F = 0$ as the first-order PDE here - rather, it is the involutivity condition.
One convenient formulation of Frobenius is the following:

If $\omega$ is a differential one-form satisfying $\omega \wedge d\omega = 0$, then locally we can find smooth functions $f,g$ such that $\omega = f\,d g$.

Letting $\omega = F^\flat$ be the one-form corresponding to $F$, we can translate from three-dimensional vector calculus to exterior calculus: we have $$F \cdot (\nabla \times F) dV = \langle \omega, \star\,d \omega \rangle dV = \omega \wedge d \omega = 0$$ and thus there exist $f,g$ such that $\omega = f\,dg$ and thus $F = f\nabla g$.


text:
Q: Orthophoto land use classification in QGIS I am using a CIR orthophoto and tried to make a land use classification with the use of Semi-Automatic Classification Plugin in QGIS.  I work in QGIS 3.2 but I get errors that my ROI are too small (error creating signature), but my these areas are quite large. Furthermore, the classification does not work at all.
I want to know the built-up area on the orthophoto, so if there is another methodology in QGIS, I would love to know.
You can find the orthophoto on this website: http://www.geopunt.be/download?container=omz15vl&title=Orthofotomoza%C3%AFek,%20middenschalig,%20zomeropnamen,%202015,%20Vlaanderen#


text:
Q: echo - Syntax error: Bad substitution A script with a problem:
  1 #!/bin/bash
  2
  3 skl="test"
  4 # get length
  5 leng=$(expr length $skl)
  6 # get desired length
  7 leng=$(expr 22 - $leng)
  8
  9 # get desired string
 10 str=$(printf "%${leng}s" "-")
 11
 12 # replace empty spaces
 13 str=$(echo "${str// /-}")
 14
 15 # output
 16 echo "$str  obd: $skl  $str"
 17

but it outputs:
name.sh: 13: Syntax error: Bad substitution

please help, thanks
I would be very grateful :)

A: Take out all unnecessary expr calls, using pure BASH features:
#!/bin/bash

skl="test"
# get length
leng=${#skl}
# get desired length
leng=$((22 - leng))

# get desired string
str=$(printf "%${leng}s" "-")

# replace empty spaces
str=$(echo "${str// /-}")

# output
echo "$str  obd: $skl  $str"

A: The following line:
str=$(echo "${str// /-}")

is resulting into Syntax error: Bad substitution because you are not executing your script using bash.  You are either executing your script using sh or dash which is causing the error.

EDIT: In order to fix your script to enable it to work with sh and dash in addition to bash, you could replace the following lines:
# get desired string
str=$(printf "%${leng}s" "-")

# replace empty spaces
str=$(echo "${str// /-}")

with
str=$(printf '=%.0s' $(seq $leng) | tr '=' '-')


text:
Q: How do I transfer my NoScript data to a new computer? I use the Firefox add-on NoScript and would like to transfer it's data to another Firefox installation so that I don't lose all the training I have put into it.  I don't want to copy my entire profile over because something is corrupt and certain add-ons aren't behaving properly.
How do I transfer NoScript data only?

A: Just go to options in NoScript and on the bottom there are buttons for export and import.


text:
Q: Create a new row with zeroes in wide Pandas DataFrame I'm trying to fill an empty array with one row of zeroes. This is apparently a lot harder said than done. This is my attempt:
Array = pd.DataFrame(columns=["curTime", "HC", "AC", "HG", "HF1", "HF2", "HF3", "HF4", "HF5", "HF6",
                            "HF7", "HF8", "HF9", "HF10", "HF11", "HF12", "HD1", "HD2", "HD3", "HD4", "HD5", "HD6",
                            "AG", "AF1", "AF2", "AF3", "AF4", "AF5", "AF6", "AF7", "AF8", "AF9", "AF10", "AF11", "AF12",
                            "AD1", "AD2", "AD3", "AD4", "AD5", "AD6"])
appendArray = [[0] * len(Array.columns)]
Array = Array.append(appendArray, ignore_index = True)

This however creates a row that stacks another 41 columns to the right of my existing 41 columns, and fills them with zeroes, while the original 41 columns get a "NaN" value.
How do I most easily do this?

A: You can using pd.Series within the append
Array.append(pd.Series(appendArray,index=Array.columns), ignore_index = True)
Out[780]:
   curTime  HC  AC  HG  HF1  HF2  HF3  HF4  HF5  HF6 ...   AF9  AF10  AF11  \
0        0   0   0   0    0    0    0    0    0    0 ...     0     0     0
1        0   0   0   0    0    0    0    0    0    0 ...     0     0     0
   AF12  AD1  AD2  AD3  AD4  AD5  AD6
0     0    0    0    0    0    0    0
1     0    0    0    0    0    0    0
[2 rows x 41 columns]


text:
Q: Proving that $\mathbb{Z}_{n}$ is cyclic It should be very basic, but I'm struggling to understand the solution. I'm trying to prove that to group $\mathbb{Z}_{n}$ is cyclic. Everywhere I tried to find a solution I came across of the saying

$\mathbb{Z}_{n}$ is cyclic because it has a generator $1$ (meaning $\mathbb{Z}_{n} = \langle 1 \rangle$).

I understand the meaning of generator, but I don't understand why the generator is $1$. Probably I'll feel stupid when I'll finally understand. Why $\mathbb{Z}_{n} = \langle 1 \rangle$ when $\mathbb{Z}_{n}$ is the Sum group of integers modulo $n$.

A: Take any $m\in\{1,2,...,n-1\}$. Then $m=1+1+...+1$ when you sum $m$ times. And if you take $m=0$ then $m=1+1+...+1$ when you sum $n$ times because $0\equiv n$(mod $n$). Hence any element of the group is generated by the set $\{1\}$.

A: Hint: $a \bmod n = a(1 \bmod n)$.


text:
Q: How do I change the default directory that pip installs to? When I run the commmand
pip install virtualenv

I get:
Installing virtualenv script to /usr/local/share/python

But my default virtualenv is in a different place:
which virtualenv
usr/local/bin/virtualenv

I'd like pip to install to the usr/local/bin directory by default. Any help would be greatly appreciated.

A: If you want to manually decide where you want packages to reside, you could always download the source distribution to a directory of your choice with the following:
pip install -d <path_to_my_directory>

But when you install, I think you probably want to put the executable console scripts (as defined in the package's setup.py file; like virtualenv for example) in a directory included in your $PATH environmental variable.
You can specify this manually by doing the following:
sudo python setup.py install --install-scripts /usr/bin/

orsudo python setup.py install --install-scripts /usr/local/bin/
Let me know if you have any other questions...

A: /usr/local/bin is for executable programs.  /usr/local/share is to store data that is independent of the architecture.
So, in your case, you are installing by default in /usr/local, where the executable programs live in /usr/local/bin, the arquitecture-independent data lives in /usr/local/share, configuration files live in /usr/local/etc, etc.
You can check Filesystem_Hierarchy_Standard to get an overview on the topic.


text:
Q: Limits Vary, Limit Varies Let's say each city has its own city-wide speed limit.

*

*The speed limit varies between cities.

*The speed limits vary between cities.

Definition 1 for "vary" of this dictionary reads:

to be different in different situations

which implies that only one single characteristic, without it belonging to a specific thing, is being talked about, so sentence 1 should be the correct one.
But, definition 1a of the same dictionary reads:

if two or more things vary, they are different from each other

which implies that two or more characteristics, each belonging to a separate thing, are being talked about, so sentence 2 seems to be the correct one.  What do native speakers think?

A: Nice question. In Br.E I'm leaning towards the single form: "The speed limit varies between cities". Why? Because I took your point about single characteristics. When I broke it down, a speed limit is only really one single thing/one concept; we're just referring to different instances of speed limit.
However, I don't think the plural form would sound out of place at all, and in fact, could be used pretty much equally (given that my previous point is a bit flimsy when you consider that each city likely has many different speed limits). Google searches of the exact two phrases confirm that both are possible.
Some tips I thought of:
If you're referring to one country for example, the singular option might be better.

The speed limit varies from town to town.

Yet, a global reference might read better with a plural:

Speed limits vary dramatically from continent to continent.

You might also consider using other words to see if you can resolve this type of doubt in future. For example, "temperature vs temperatures". "The average temperature in x country varies" vs "Temperatures in North America vary depending on..."

A: Hmm, very interesting question.
The easy way out is to say that a city could have multiple speed limits, like one speed limit for back roads and a higher speed limit for the main roads. So a collection of speed limits in one city is different from the collection of speed limits in another city, so, "The speed limits vary."
But suppose each city has only one speed limit, but the speed limit in, say, Detroit is 40 mph while the speed limit in Boston is 30 mph. Should you use the singular because each has only one speed limit, or the plural because, between the two, there are two speed limits.
I've heard people say it both ways, so I think the practical answer is, "either way is acceptable". But is one way arguably right and the other wrong? I don't know.


text:
Q: trying to understand Gundb (nodejs application) for my study For my study I'm trying to use Gun to store the date for my app.
I thought it would be useful to first use one location to host my data, get it up and running and then introduce the peer connectivity.
Now my first question would be: is this way of thinking correct?
Then, how would I go about deploying to something now now.sh
I'm not looking for a one line solution, more some more pointers in to change my way of thinking. Although I think I understand the appeal of decentralized data I would love to hear if I am correct/wrong.
Kind regards,
Daneel

A: @a-daneel yes, you are correct. You can start with 0, 1, or Many connections, then always add or subtract more later.
As for now I don't use it myself personally, but you should follow whatever instructions they provide on deploying.
If you want to find other like-minded people to chat with, do join our discussion chat room on http://chat.gun.eco ! :) Super super super friendly and helpful people there.


text:
Q: Code First with Enum properties Theoretical question here.
I have a property "Status" that can only accept 2 different values (open, closed) which i want to set as an enum type of property. in a codefirst mvc application, should the enum be defined in the data model, in the viewmodel or both?
I am leaning towards making the enum part of the viewmodel and the codefirst property for this model would just store the string value of the enum. Then, i would just map the 2 values back and forth using automapper. The enum property of the viewmodel would be displayed as a radiobutton.
Thoughts?

A: It depends.
1) If You have other code that can access Your data model (apart from Your views) than You probably want this Status property to be of enum type. So that this third party code will not break Your logic. Anyway, even if You don't have such code right now I suggest You to use enum for forward compatibility: mabby You or other developer will add it in the future. It's a best practice. IMHO, this is mandatory.
2) What about using enum in the view model? IMHO, this is optional. Because if You want to validate Your input You probably will do it on the server in Your controller action method. If You use radiobuttons than You even don't need to validate the input in controller. Just use this in Your view:
@model path.YourViewModel
@using YourEnumNamespace;  /* where You defined Your Status enum */

@using (Html.BeginForm("YourMethod", "YourController", FormMethod.Post, null))
{
<fieldset>

        @foreach (var enumValue in Enum.GetValues(typeof(Status)))
        {

                @Html.Label(enumValue.ToString())
                @Html.RadioButtonFor(model => model.Title, enumValue)

        }

    <input type="submit" value="Save"/>
</fieldset>
}

Just enumerate enum values as in the above code.
To summarize: there is no need to use enum type in viewmodel, but it is a good practice to think about forward compatibility and use enum type in datamodel.

A: I usually have them in both my domain models and ViewModels, Entity Framework will map them to integers in the database. I created some html helpers which create drop down lists for an enum in my ViewModel.


text:
Q: Actualizar activity con cambios en adapter Xamarin android Buenas.
Me gustaría saber si sería posible actualizar el activity padre que contiene un adapter cuando en éste se produzca un evento.
Explico con un poco más de detalle:
Tengo un activity que carga un adapter con una serie de información contenida en cada item y un botón para un cambio de estado (por cada uno de los items).
Necesitaría que cada vez que el usuario hace click en el botón de cambio de estado de los items actualizara el activity padre.
Os adjunto el código de mi adapter (he omitido algunas partes para dejar lo relevante)
Muchas gracias por la ayuda.
  class adapter_listview_pedidos_asignados_int :
    BaseAdapter<DetalleRutaAsignadaIntClass>    {

        ImageView btnEntregaRealizadaOK1;

        ImageView btnEntregaRealizadaConInci1;

        List<DetalleRutaAsignadaIntClass> items;
        Activity context;

        string _ok = "OK";

        View _view;

        public override int Count   {
            get { return items.Count; }
        }

        public override DetalleRutaAsignadaIntClass this[int position] {
            get { return items[position]; }
        }

        public adapter_listview_pedidos_asignados_int(Activity context, List<DetalleRutaAsignadaIntClass> items) : base() {
            this.context = context;
            this.items = items;
        }

        public override long GetItemId(int position)    {
            return position;
        }

        public override View GetView(int position, View convertView, ViewGroup parent)  {
            View view = null;
            DetalleRutaAsignadaIntClass item = items[position];
            if (convertView == null) {
                view = new View(context);
            }
            else {
                view = convertView;
            }

            if (view != null)       {
                view = context.LayoutInflater.Inflate(Resource.Layout.item_pedido_asign_ruta_int, null);
                _view = view;

                view.FindViewById<TextView>(Resource.Id.lblNombreLinea).Text = item.nombre_linea.ToString();
                view.FindViewById<TextView>(Resource.Id.lblDistancia).Text = item.distancia_aproximada.ToString();

                view.FindViewById<TextView>(Resource.Id.lblNombreLocalizacionOrigen).Text = item.nombre_localizacion_origen.ToString();
                view.FindViewById<TextView>(Resource.Id.lblNombreLocalizacionDestino).Text = item.nombre_localizacion_destino.ToString();

                view.FindViewById<ImageView>(Resource.Id.btnEntregaRealizadaOK1).Visibility = ViewStates.Gone;

                btnEntregaRealizadaOK1 = view.FindViewById<ImageView>(Resource.Id.btnEntregaRealizadaOK1);
                btnEntregaRealizadaOK1.Click += delegate    {
            bool res = actualiza_estado(string id_pedido, string resultado);
                //*** Aquí es donde quiero actualizar el activity padre ***//
                };

            }
            return view;
        }

        private bool actualiza_estado(string id_pedido, string resultado) {
            bool devolver = false;

            librerias.helpers.WebService consulta = new librerias.helpers.WebService(helper.helper.url_web_service, "cambia_estado_pedido_a_finalizado_int");
            try {
                consulta.AddParameter("id_pedido", id_pedido.ToString());
                consulta.AddParameter("resultado", resultado.ToString());

                consulta.Invoke();
            }
            finally { consulta.PosInvoke(); }

            devolver = Convert.ToBoolean(consulta.ResultString);
            consulta = null;

            return devolver;
        }

    }

A: yo lo resolví asi funciona pero nose si sea lo correcto
ListView listaTra;
    List<mantenimientoProsesado> listaTraItems;
    bool actualizacionesBandera = false;

    protected override void OnCreate(Bundle savedInstanceState)
    {
        base.OnCreate(savedInstanceState);

        // Create your application here

        SetContentView(Resource.Layout.ListaTrabajosPersonal);
        listaTra = FindViewById<ListView>(Resource.Id.ListaListaTrabajosPersonal);
        listasActualizar();
        listaTra.ItemClick += listaTra_ItemClick;
    }

    protected override void OnPostResume()
    {
        base.OnPostResume();
        if (actualizacionesBandera)
        {
            listasActualizar();
            actualizacionesBandera = false;
        }
    }

    public void listasActualizar()
    {
        listaTraItems = ;//cargas tu lista
        listaTra.Adapter = new ListaTrabajosPersonalAdaptador(this, listaTraItems);
    }

    void listaTra_ItemClick(object sender, AdapterView.ItemClickEventArgs e)
    {
        actualizacionesBandera = true;

        Toast.MakeText(this, listaTraItems[e.Position].ClienteAgencia, ToastLength.Short).Show();
        Intent Navegar = new Intent(this, typeof(Mantenimiento));
        StartActivity(Navegar);

    }

A: Acabo de dar con la solución y mira que llevaba un buen rato con esto. Relativamente sencillo pero lo dejo aquí para cualquier otra persona: justo después de la llamada a actualiza_estado he hecho lo siguiente:
Intent act_actualizado= new Intent(context.Intent);
act_actualizado.SetFlags(ActivityFlags.NewTask);
this.context.Finish();
Application.Context.StartActivity(act_actualizado);

Cualquier mejora o sugerencia es, por supuesto, apreciada.


text:
Q: Splitting a string which contains numerical digits in Perl I want to split a string(which has numerical digits). In the below example, I want to split the string at k and k1.
my @array1=("0","23","1","4","65","7");
$k=1;$k1=0;
my $j=join("",@array1);
my @ar=split(/($k|$k1)/,$j);
print join(";",@ar),"\n\n";

The output is ;0;23;1;4657
In the above output, extra semicolon ";" is printing
The expected output is 0;23;1;4657
When I try the above code for the below example, the output is correct: (0;5;123;4;6); the extra semicolon is not printing here.
my @array1=("0","5","1234","6");
$k=5;$k1=4;

I am not sure, for what reason the first example is printing extra semicolon ";"
Can some one help me in this?

A: The difference is when you split around the first character, you get an empty value at the beginning.  Hence the extra ; before the 0 (and after the "").  You'll similarly find ;; when splitting on two adjacent characters
So the absolute simplest fix would be to use grep to remove empty string:
my @ar=split(/($k|$k1)/,$j);
@ar = grep /./, @ar;

This removes the empty strings in @ar.
In the bigger picture, you might want to look at why you're joining strings just to split them back apart.  You're also splitting around a number in one place that could appear in another.  Like if $k=1 and @array1 = (11, 23, 1, 4);

A: This is a highly contrived example, has many issues (e.g. $k and $k1 need to be declared with "my", you should use strict etc.) and it's probably going to do something you don't want.
The bottom line, and the reason you see the leading semicolon, is that if you split by a delimiter that matches at the beginning of the string, split will return an empty list element for that.
print join ';', split /0/, '0123';

A: There's some interesting behaviour in this code which I was not aware of and that's not been brought out in the other answers.  What normally happens with a split on a regular expression is that the characters that you're splitting on are omitted from the result.  However, it seems that if you have capturing parentheses in the regex, then the captured material is kept in the result.
Script
#!/usr/bin/env perl

use strict;
use warnings;

my @array1 = ("0", "23", "1", "4", "65", "7");
my $j = join("", @array1);
my $k;
my $k1;
my @ar;
print "Join [$j]\n";

$k = 1;
$k1 = 0;
printf "%-25s", "Version 1 /($k|$k1)/:";
@ar = split(/($k|$k1)/, $j);
print "[", join(";", @ar), "]\n";

printf "%-25s", "Version 2 /($k|$k1)/:";
$k = "1";
$k1 = "0";
@ar = split(/($k|$k1)/, $j);
print "[", join(";", @ar), "]\n";

printf "%-25s", "Version 3 /[01]/:";
@ar = split(/[01]/, $j);
print "[", join(";", @ar), "]\n";

printf "%-25s", "Version 4 /(0|1)/:";
@ar = split(/(0|1)/, $j);
print "[", join(";", @ar), "]\n";

printf "%-25s", "Version 5 /0|1/:";
@ar = split(/0|1/, $j);
print "[", join(";", @ar), "]\n";

printf "%-25s", "Version 6 /([46])/:";
@ar = split(/([46])/, $j);
print "[", join(";", @ar), "]\n";

printf "%-25s", "Version 7 /(?:[46])/:";
@ar = split(/(?:[46])/, $j);
print "[", join(";", @ar), "]\n";

Output
Join [02314657]
Version 1 /(1|0)/:       [;0;23;1;4657]
Version 2 /(1|0)/:       [;0;23;1;4657]
Version 3 /[01]/:        [;23;4657]
Version 4 /(0|1)/:       [;0;23;1;4657]
Version 5 /0|1/:         [;23;4657]
Version 6 /([46])/:      [0231;4;;6;57]
Version 7 /(?:[46])/:    [0231;;57]

As you can see, when the capturing parentheses are present in the regex on which the string is split, the (captured) splitting characters are preserved. When the parentheses are missing or are explicitly non-capturing (Version 7), then the splitting characters are not preserved.
And, if you read the manual carefully, the split description does include the paragraph:

If the PATTERN contains capturing groups, then for each separator, an additional field is produced for each substring captured by a group (in the order in which the groups are specified, as per backreferences; if any group does not match, then it captures the undef value instead of a substring. Also, note that any such additional field is produced whenever there is a separator (that is, whenever a split occurs), and such an additional field does not count towards the LIMIT.

Followed by some examples.
Testing with Perl 5.16.0 on Mac OS X 10.7.5.

A: One option is to use a regex instead of split. This works for both data sets you've shown:
use strict;
use warnings;

my @array1 = ( "0", "23", "1", "4", "65", "7" );
my $k      = 1;
my $k1     = 0;

my $j      = join( '', @array1 );
my @ar = $j =~ /([$k$k1]|[^$k$k1]+)/g;
print join( ";", @ar );

Output:
0;23;1;4657

A: Perl provides a very powerful regex substitution construct which does away with the need to perform split-fu and join-fu in this case:
$string =~ s{(?:$k|$k1)\K}{;}g ;


text:
Q: Optimize a find and match code in Python I have a code which takes as input two files:
(1) a dictionary/lexicon
(2) a text file (one sentence per line)
The first part of my code reads the dictionary in tuples so outputs something like:
('mthy3lkw', 'weakBelief', 'U')

('mthy3lkm', 'firmBelief', 'B')

('mthy3lh', 'notBelief', 'A')

The second part of the code is to search each sentence in the text file for the words in position 0 in those tuples and then print out the sentence, the search word and it's type.
So given the sentence mthy3lkw ana mesh 3arif , desired output is:
["mthy3lkw ana mesh 3arif", 'mthy3lkw', 'weakBelief', 'U'] given that the highlighted word is found in the dictionary.
The second part of my code - the matching part - is TOO slow. How do I make it faster?
Here is my code
findings = []
for sentence in data:  # I open the sentences file with .readlines()
    for word in tuples:  # similar to the ones mentioned above
        p1 = re.compile('\\b%s\\b'%word[0])  # get the first word in every tuple
        if p1.findall(sentence) and word[1] == "firmBelief":
            findings.append([sentence, word[0], "firmBelief"])

print findings

A: Convert your list of tuples into a trie, and use that for searching.

A: Build a dict lookup structure so you can find the correct one from your tuples quickly. Then you can restructure your loops so that instead of going through your whole dictionary for each sentence, trying to match every entry up, you instead go over each word in the sentence and look it up in the dictionary dict:
# Create a lookup structure for words
word_dictionary = dict((entry[0], entry) for entry in tuples)

findings = []
word_re = re.compile(r'\b\S+\b') # only need to create the regexp once
for sentence in data:
    for word in word_re.findall(sentence): # Check every word in the sentence
        if word in word_dictionary: # A match was found
            entry = word_dictionary[word]
            findings.append([sentence, word, entry[1], entry[2]])


text:
Q: Simple TCP Client I'm trying to implement simple TCP Client in Haskell. But it gets closed as soon as it connects. I don't know what is causing it to close. How could I make it so that it would print lines from server into stdout and send lines from stdin to server forever until stdin receives line ":quit"?
import Control.Monad (forever)
import Network (withSocketsDo, PortID(..), connectTo)
import System.IO
import Control.Concurrent (forkFinally)
import Control.Concurrent.Async (race)

main :: IO ()
main = withSocketsDo $ do
  -- connect to my local tcp server
  handle <- connectTo "192.168.137.1" (PortNumber 44444)
  -- should close the connection using handle after everything is done
  _ <- forkFinally (talk handle) (\_ -> hClose handle)
  return ()

talk :: Handle -> IO ()
talk handle = do
    hSetNewlineMode handle universalNewlineMode
    hSetBuffering handle LineBuffering
    -- if either one of them terminates, other one will get terminated
    _ <- race (interactWithServer handle) (interactWithUser handle)
    return ()

interactWithServer :: Handle -> IO ()
interactWithServer handle = forever $ do
  line <- hGetLine handle
  print line          -- print a line that came from server into stdout

interactWithUser :: Handle -> IO ()
interactWithUser handle = do
  line <- getLine
  case line of
    ":quit" -> return ()            -- stop loop if user input is :quit
    _ -> do hPutStrLn handle line
            interactWithUser handle -- send, then continue looping

A: With Ørjan Johansen's help I figured it out. forkFinally was creating a thread then after that main thread was getting closed. That line was meant to wait until talk finished and then close the connection. It had to be (also shortened it)
main :: IO ()
main = withSocketsDo $ do
  handle <- connectTo "192.168.137.1" (PortNumber 44444)
  talk handle `finally` hClose handle

talk :: Handle -> IO ()
talk handle = do
    hSetNewlineMode handle universalNewlineMode
    hSetBuffering handle LineBuffering
    _ <- race fromServer toServer
    return ()
  where
    fromServer = forever $ do
      line <- hGetLine handle
      print line
    toServer = do
      line <- getLine
      case line of
-- server accepts /quit as disconnect command so better send it to the server
        ":quit" -> do hPutStrLn handle "/quit"; return "Quit"
        _ ->  do hPutStrLn handle line; toServer

I hope this code is safe :D


text:
Q: Jquery when do you use $.get(index) instead normal selector Just wondering when do you actually use $.get(index); I am a bit confused on when and where to use $.get(index), when u can straight get any element by getting the id or class name?
(note i am not talking about the $.get() ajax call) sorry i confused some of your guys

A: As the docs state, .get() retrieves the DOM object, not the jQuery object. So if you need the native DOM object, you'd use .get().
Why would you need the native DOM element? For example, you might want to access methods like .play() on an HTML5 video.
$('#myvideo').play() wouldn't work. $('#myvideo').get(0).play() would.

A: Say you had a list with no id's or classes but wanted to target the middle list item:

One

Two

Three

You could then use:
$('li').get(1)

to retrieve list item two (index is zero based)

A: The $.get function in jQuery is for making Ajax calls, not selecting elements. Please see this in the jQuery documentation: http://api.jquery.com/jQuery.get/


text:
Q: Word 2016: paragraph spacing not working - paragraph stuck to page top I have a title line sentence (1-line paragraph) "Chapter 2: Literature Review" that needs to have a 72 pt paragraph spacing before the line. The line starts on a new page following a page break from the end of Chapter 1.
The paragraph is Normal style: double spaced, no indent, 0 before spacing, 0 after spacing. When I try to add the 72 pt spacing before, the paragraph spacing dialog shows a 72 pt value in the before space box, but the paragraph is still glued to the top of the page.
How can I get this first chapter title to move down with 72 pt space before? Should I just create a new style? I can't figure out what's holding it at the top of the page.
Thanks

A: Without having access to your document, it is hard to tell if this answer will work for you. I suspect that the problem is you might have the "Don't add space to paragraphs of the same style" selected.
Right click your paragraph, select "Paragraph". Under the "Indents and Spacing" tab, deselect "Don't add space to paragraphs of the same style".
If this does not work, check the options within the "Lines ans Page Break" tab in the "Paragraph" window, and deselect unnecessary options.
If it still is not working, repeat both of these steps for the paragraphs above and below the paragraph you are working on.

A: You can accomplish this with a frame.

*

*Create or modify a paragraph style

*format (edit) the Paragraph settings for the style:

*

*set the amount of spacing you want before the paragraph (ex: 72pt)

*set a Page break before the paragraph (Line and Page Breaks > Pagination)

*format (edit) the Frame settings for the style:

*

*set the text wrapping to None

*Save the changes to your style (OK button)
The paragraph will now have the spacing above it within the frame.

A: Microsoft word veteran here. If you're using word 16-18, follow these instructions:

*

*Select all you text.

*Click on the Home tab.

*Then, to the right of paragraph, where there are squares that say AaBbCcDd, click the no spacing one.

*If you had centered text, make the text centered again as it will all go to the left.


text:
Q: What properties do the matrix $A^HA$ have? The matrix $\mathbf{A}$, written in the form of column vectors, is
$\mathbf{A}=(\mathbf{a}_1, \mathbf{a}_2,...\mathbf{a}_P)$
where $\mathbf{a}_k$ is an $M\times 1$ complex column vector that is given by
$\mathbf{a}_k = (1,e^{j\tau_k},e^{j2\tau_k},\cdots,e^{j(M-1)\tau_k})$,
$j=\sqrt{-1}$ and all real constants $\tau_k$, $k=1,2,\cdots,P$, are unequal.
Assume $M>P$, then what properties, such as positive definiteness, eigenvalue decomposition, matrix rank etc, do the matrix $\mathbf{A}^H\mathbf{A}$ have? And how to prove these properties?

A: The matrix $A^HA$ is positive-semidefinite, which is true even without extra assumptions on $A$. It's Hermitian, since
$$(A^HA)^H = A^H(A^H)^H = A^H A.$$
It's positive-semidefinite because, for any vector $v \in \Bbb{C}^P$,
$$v^H(A^HA)v = (Av)^H(Av) = \|Av\|_2^2 \ge 0.$$
In order for it to be positive-definite, whenever $v \neq 0$, we need $\|Av\|_2 > 0$. This happens if and only if the columns of $A$ are linearly independent.
When are the columns linearly independent? Note that a column of $A$ takes the form:
$$(1, \omega_k, \omega_k^2, \ldots, \omega_k^{M-1}),$$
where $\omega_k = e^{j\tau_k}$. This makes $A$ the transpose of a Vandermonde matrix, whose rows are linearly independent provided they are distinct, and do not outnumber the columns. So, your matrix will be positive-definite if and only if the $\omega_k$ numbers are pairwise distinct (proving this is usually done by extending the Vandermonde matrix to be square, and computing the determinant, which elegantly establishes the above claim).
Of course, you assume the $\tau_k$ numbers are pairwise distinct, but this is not quite sufficient, as the complex exponential is not injective. In fact, the complex exponential has a period of $2\pi$. So, your matrix will be positive-definite if and only if $\tau_k - \tau_l$ is only an integer multiple of $2\pi$ if $k = l$.
As for rank, the rank of $A$ and the rank of $A^HA$ agree (once again, without further assumption on $A$). This can most easily be seen by the rank-nullity theorem. The nullspace of $A^HA$ actually matches the nullspace of $A$, since
$$Av = 0 \implies A^HAv = 0 \implies v^HA^HAv = 0 \implies \|Av\|^2_2 = 0 \implies Av = 0,$$
so $Av = 0 \iff A^HAv = 0$. That is, the nullspaces agree. Since both matrices have $P$ columns, the ranks also agree.
The rank of $A$ will just be, once again, the number of distinct columns, due to the Vandermonde result. Thus, the rank of $A^H A$ will be the number of distinct $\omega_k$s. Equivalently, it will be the number of equivalence classes of the equivalence relation $x \sim y \iff (x - y)/(2\pi) \in \Bbb{Z}$ when applied to $\{\tau_1, \ldots, \tau_P\}$.
As for eigenvalues/eigenvectors, I greatly doubt that there will be a "nice" formulation for eigenvalues and eigenvectors. Obviously, if columns repeat, then we will get some $0$ eigenvalues. If $\omega_k = \omega_l$ for some $k \neq l$, then to get an eigenvector, we simply place a $1$ in the $k$th position, and $-1$ in the $l$th position, and $0$s elsewhere. For non-zero eigenvalues/eigenvectors, I don't think we'll get anything neat.


text:
Q: Load value from SQL table in HTML textarea I want to load the data of a table in my SQL database in a HTML textarea (PHP page):
   <form action="" method="post">
   <textarea id="styled" name="content"></textarea>

<input type="submit" name="Update">
   </form>

So, I would like to load the text in my table into this textarea when the page loads. The query is simple:
       "SELECT * FROM about WHERE id=20"
..but I have no idea how to load the result in a textarea.

A: Assuming you did mysqli_connect etc.
<?php
$res = mysqli_query("SELECT * FROM about WHERE id=20");
$row = mysqli_fetch_assoc($res);
$value = $row["the_column"];
?>
<form action="" method="post">
<textarea id="styled" name="content"><?php echo htmlentities($value);?></textarea>

<input type="submit" name="Update">
</form>

If you're not using mysqli substitute those functions.

A: From PDO tag wiki:
<?php
// connect. have to be moved into separate file to be included
$dsn = "mysql:host=localhost;dbname=test;charset=utf8";
$opt = array(
    PDO::ATTR_ERRMODE            => PDO::ERRMODE_EXCEPTION,
    PDO::ATTR_DEFAULT_FETCH_MODE => PDO::FETCH_ASSOC
);
$pdo = new PDO($dsn,'root','', $opt);

//getting data
$id  = 20;
$stm = $pdo->prepare("SELECT text FROM about WHERE id=?");
$stm->execute(array($id));
$text = $stm->fetchColumn();

//echoing out
?>
<form method="post">
    <textarea id="styled" name="content"><?=htmlspecialchars($text)?></textarea>

    <input type="submit" name="Update">
</form>

A: just put your php retrieval code between textarea


text:
Q: PS1 variable inheritance between scripts and programs using bash in AIX How can I ensure that PS1 variable in AIX bash is inherited between cross calling of scripts and programs ?
Suppose a program gives to the user a shell instance such as the shell command of vi. This can be used in two ways, in one of them it's launched by a script (see the 2nd case below):

*

*ksh prompt -> program -> "user asks for shell" -> ksh

*script -> program -> "user asks for shell" -> ksh
That works well with ksh. But when the bash is used (in AIX), we noticed in the 2nd case that the PS1 variable isn't inherited, so it has the default value.
You can test it just using vi, create a script, like: runvi.sh:
# blablabla
# vi $1

When we run the script and ask vi for the shell, the prompt is: sh-4.3$
Of course, when you run vi directly, and it asks for the shell, the prompt is your previously defined PS1.
The unique difference between the test above and the real program is that in the program the bash shows the PS1 with the value bash-4.3$, so the issue with PS1 inheritance seems the same. This C program can shows it:
#include <stdlib.h>
main() { system("$SHELL"); }

BASH VERSION:
bash-4.3$ bash -version
GNU bash, version 4.3.30(1)-release (powerpc-ibm-aix5.1.0.0)
Copyright (C) 2013 Free Software Foundation, Inc.
License GPLv3+: GNU GPL version 3 or later <http://gnu.org/licenses/gpl.html>
This is free software; you are free to change and redistribute it.
There is NO WARRANTY, to the extent permitted by law.

AIX VERSION
The same behavior between AIX 5.3 until 7.
OBS: In Ubuntu this doesn't happen.

A: An workaround:
// C code snippet
#define CMDPATTERN_PS1_PRESET "export PS1='%s';$SHELL"
#define CMDPATTERN_PS1_NOSET "$SHELL"

char* cmdpattern = (userPS1!=NULL && *userPS1 != NULL) ?CMDPATTERN_PS1_PRESET :CMDPATTERN_PS1_NOSET;
sprintf(shellcmd, cmdpattern, userPS1);
system(shellcmd);

So, if the user wants a custom PS1, in case it isn't inherited, it should be previsouly configured in the software. And can keep working in all shells and OSes.


text:
Q: Doctrine 2 Association Mapping (ManyToOne and OneToMany) I am new with Doctrine2 and need some help.
I have 2 Entities: LocationEntity and RatingEntity
RatingEntity
<?php

use Doctrine\ORM\Mapping as ORM;

/**
 * Rating
 *
 * @ORM\Entity
 * @ORM\Table(name="`RATING`")
 */
class RatingEntity {

    /**
     *
     * @var int
     * @ORM\Id
     * @ORM\Column(name="`ID`", type="integer", nullable=false)
     * @ORM\GeneratedValue(strategy="SEQUENCE")
     * @ORM\SequenceGenerator(sequenceName="RATING_ID_SEQ", initialValue=1, allocationSize=1)
     */
    protected $id;

    /**
     *
     * @var int
     * @ORM\Column(name="`LOCATION_ID`", type="integer")
     */
    protected $locationId;

    /**
     * @var LocationEntity
     * @ORM\ManyToOne(targetEntity="LocationEntity", inversedBy="ratings")
     * @ORM\JoinColumn(name="`LOCATION_ID`", referencedColumnName="`ID`")
     */
    protected $location;

    /**
     * @return the $location
     */
    public function getLocation() {
        return $this->location;
    }

    /**
     * @param field_type $location
     */
    public function setLocation($location) {
        $this->location = $location;
    }

and LocationEntity
<?php

use Doctrine\ORM\Mapping as ORM;
use Doctrine\Common\Collections\ArrayCollection;
use Doctrine\Common\Collections\Collection;

/**
 * Location
 *
 * @ORM\Entity
 * @ORM\Table(name="`LOCATION`")
 */
class LocationEntity {

    /**
     *
     * @var int
     * @ORM\Id
     * @ORM\Column(name="`ID`", type="integer", nullable=false)
     * @ORM\GeneratedValue(strategy="SEQUENCE")
     * @ORM\SequenceGenerator(sequenceName="LOCATION_ID_SEQ", initialValue=1, allocationSize=1)
     */
    protected $id;

    /**
     *
     * @var ArrayCollection
     * @ORM\OneToMany(targetEntity="RatingEntity", mappedBy="location", cascade={"persist"}, fetch="LAZY")
     */
    protected $ratings;

    /**
     * @return the $ratings
     */
    public function getRatings() {

        return $this->ratings;
    }

    /**
     * @param \Doctrine\Common\Collections\ArrayCollection $ratings
     */
    public function setRatings($ratings) {

        $this->ratings = $ratings;
    }

    /**
     * Never forget to initialize all your collections!
     */
    public function __construct() {
        $this->ratings = new ArrayCollection();
    }

If I get locations, i get ratings for location as Array,
but if I want to get Rating and Location for it, I get NULL only in getLocation().
Can somebody help?

A: I don't think that you need the locationId property in your Rating entity as the column is already mapped using the location property. Try removing the locationId section and see if it doesn't work as expected.


text:
Q: GnuPlot: Draw line per CSV line I just started to work with Gnu Plot and i created a few simple plots. But now i have a new problem.
The input is a csv-file like this:
name;n0;n1;n2
Benj;1;3;2
Silv;6;1;2
Steffi;3;2;2

The count of the columns and the count of the rows is dynamic. So this is also a valid input file:
name;n0;n1;n2;n3;n4
Benj;2;2;3;2;1

I like to have a graph like this (input is the first csv):

I played around with some Gnu Plot files which i created before, but i always just got something totally different.
Maybe someone has a hint or something to help me?
Thank you very much,
Best regards
Kevin

A: As noted by Christoph, you need to transpose the data before plotting, the answers here should be helpful with that. To determine the number of rows in the data, recent versions of Gnuplot can use the stats command (see comment by Christoph below), otherwise the number of lines needs to be counted by other means.
Here is how you could handle both issues with external programs:
dfile = "data.csv"
nrec  = system("wc -l < " . dfile)
set datafile separator ';'
plot for [i=2:nrec] '<transpose --fsep \; -t '.dfile using i:xtic(1) with lines title columnhead

I used wc from coreutils to count the number of lines and transpose as suggested by flyingsheep to handle the transposition.
Result:

Running the same script on data with more plots and data points:
data2.csv
name;n0;n1;n2;n3;n4
Benj;1;3;2;5;3
Silv;6;1;2;3;4
Steffi;3;2;2;4;2
Carl;2;4;5;3;2

A: That's the wrong data file format for gnuplot. Usually, for a single plot, gnuplot uses all rows for a single column. With a data file like
name;Benj;Silv;Steffi
n0;1;6;3
n1;3;1;2
n2;2;2;2

the plot becomes as easy as
set datafile separator ";"
set style data lines
set key autotitle columnhead
plot 'data.csv' using 2:xtic(1), '' using 3, '' using 4

with the result (using 4.6.3):

A: As mentioned already in the other answers, the most efficient way is certainly to transpose the data and use simple standard gnuplot plotting commands.
If you want a platform-independent gnuplot-only solution you could do the following:
If all rows have the same number of columns you can plot the data using the option matrix (check help matrix). There are a few examples here on SO. However, here, the additional difficulty is to get the xticlabels and the legend as well.
I tried a few script variations, but the one below was the only one I found which seems to work unchanged for both gnuplot4.6.0 (March, 2012) and gnuplot5.5.0 (July 2021).
I don't want to say the solution is beautiful, but it works with gnuplot-only.
Data: SO22438313.dat (taken from Thor's answer)
name;    n0; n1; n2; n3; n4
Benj;    1;  3;  2;  5;  3
Silv;    6;  1;  2;  3;  4
Steffi;  3;  2;  2;  4;  2
Carl;    2;  4;  5;  3;  2

Script: (works for gnuplot>=4.6.0, March 2012)
### plotting rows with xticlabels and legend
reset

FILE = "SO22438318.dat"

set datafile separator ';'
set yrange[0:]
set key noautotitle
# set colorsequence classic   # optional for gnuplot>=5.0

myTitles = ''

plot FILE matrix u (c=$1):3:(r=$2) every ::1:1 w l lw 2 lc var, \
        for [i=1:c]'' u (i):(i==1?myTitles=myTitles.' '.strcol(1):0,NaN): \
            xtic($0==0?xt=strcol(i+1):xt) w l lw 2, \
        for [i=1:r] '+' u 1:(NaN) every ::0::0 w l lc i lw 2 ti word(myTitles,i+1)
### end of script

Result:


text:
Q: error android SDK in class R I update my SDK, and now it is giving error in my whole project. Says that there is a class named R, which is where the layout call.
this with error in the line
import br.com.projeto_tcc.R;

A: R is the automatically generated with references to all your resources. It is used very frequently in android, so when it 'disappears', it seems to cause an error throughout the whole project.
As has been mentioned in comments above, a rebuild will sometimes solve the issue. However, if the issue is still persisting and the compiler is still unable to find the class 'R', then you need to start looking at your xml files (layouts, menus, etc).
When there is a syntax error in an android XML file, the error notification is not displayed as prominently as it is for errors in Java files (if you are using Eclipse with ADT plugin, as most android devs do). As such, it is pretty easy to miss a typo or other syntax error in one of these files unless you go through and look in each individual one (or check the errors tab in the window at the bottom of your screen if using eclipse/adt).
Syntax errors in these XML files prevent the generation of the R class; therefore, when the java compiler is looking at the references you make to the R class (for example, R.layout.foo or R.id.bar), it cannot find the class, and highlights those lines of code as errors.
So, make sure that your XML files are all well-formed, because this is a fairly common issue, especially if you are just learning your way around adt.


text:
Q: What's the straightforward, supported, stable way of using ES6 syntax and Javascript minification with Rails? I'm trying to use ES6 syntax in my Javascript files, in a Rails project. I also need to minify the Javascript files (mine, and the ones included by libraries like rails-ujs) for performance reasons.
When I first generated the project and ran it locally, it worked fine. However, this is because the environment configurations are different for development vs. production. In the development configuration, there is no minification. In the production configuration, Uglifier is used to minify Javascript.
Once I tried to deploy to production, Uglifier and ExecJS started throwing up all kinds of syntax errors, such as not recognizing the const keyword or not recognizing the > in the => operator of arrow functions.
After spending a few hours searching for a fix, I resorted to simply disabling Uglifier so that I could deploy successfully. However, now that my site is in production and working, I would like to make this optimization work.
I'm familiar with Babel and Webpack, and I've used them in other projects (along with some custom scripts) to generate browser-ready ES5 code (for Internet Explorer) and browser-ready ES6 code (for every other browser). If I wasn't using Rails, this would be trivial for me to solve.
However, since I'm using Rails, I need to figure out how to do this in the context of the Rails Asset Pipeline. Surprisingly, there doesn't seem to be any standard way to do this, despite ES6 being 4 years old and supported by every modern browser. It's really weird that Microsoft Edge is way ahead of Rails on this one.
Here's a few suggestions that I've seen, and the problems with them.

*

*https://github.com/babel/ruby-babel-transpiler

*

*Has no documentation indicating how it should be used in the Rails Asset Pipeline.

*https://www.rubydoc.info/gems/uglifier

*

*Included by default in Rails, but doesn't support ES6 syntax.

*Mentions "experimental ES6 syntax support", but it doesn't work, even when you enable "Harmony mode".

*It uses the word "experimental", and I'm trying to use this in a production app. Any serious Javascript tool should have stable support for ES6 by now.

*https://github.com/fnando/babel-schmooze-sprockets

*

*Unclear documentation, includes a lot of caveats about having to do weird nonstandard things like call .default() on all of your imports.

*https://nandovieira.com/using-es2015-with-asset-pipeline-on-ruby-on-rails

*

*Mentions having to use a "pre-release version" of Sprockets. I'm trying to use this in a production app, and I don't think that I'm being unreasonable by expecting to be able to do this with stable versions of libraries. The article is 3 years old, but I can't find a more recent version.

*How do I use ES6 (ES2015) in a ruby on rails app?

*

*Has a few suggestions, but none of them are self-contained solutions, and this is almost 3 years old. I expect that there's a specific, stable way to do it by now?

*https://revs.runtime-revolution.com/want-to-use-es6-with-rails-right-now-webpack-to-the-rescue-ebefb2004e9e

*

*This is pretty much what I'd do if I had to do all of my ES6 support outside of the Rails Asset Pipeline. Surely, there's a way to do this without stepping outside of Rails and compiling my Javascript code manually?

*https://github.com/babel/minify

*

*Still in beta. I'm trying to use this for a production site.