Q: Bypassing Controller in Rails Im using Rails 2.3.5 and I have a model, let's call it Post. I used named scopes to apply different kinds of sorts on Post. For example, in the Post model I have possibility to rank posts by its scores:
named_scope :order_by_acception_rate_desc,
Proc.new { |limit| { :limit => limit, :order => "acception_rate desc" } }

In the Post Controller I have:
def best
    @best_posts = Post.order_by_acception_rate_desc(10)
end

In the view I just render this collection @best_posts:
<%= render :partial => "post", :collection => @best_posts

Currently my application is working like that, but actually I do not need to have the method "best" in the Controller, and I could move it to the Model Post doing like:
def self.best
    self.order_by_acception_rate_desc(10)
end

and then in the view I would render the collection like:
<%= render :partial => "post", :collection => Post.best

I do not know which approach is better, but using the ranking methods in the Model, I could avoid to create routes for each one of ranking methods. What approach is better, is there any better approach than these?

A: with according to Rails conventions the logic should be separated,

*

*controllers handle permissions, auth/authorization, assign instance/class variables

*helpers handle html logic what to show/hide to user

*views should not provide any logic, permissions check. think about it from designer's point of view

*models handle data collection/manipulation over ORM

I'd like to ask you to try:
#helper
def self.best(limit)
  all(:limit => limit, :order => "acception_rate desc")
end

#controller
@best_posts = Post.best

#view
<%= render :partial => "post", :collection => @best_posts %>

A: You should not bypass the controller and include much logic in your view.
You could keep a single route and filter the Post model depending on one of the params.
You don't tell enough here to answer more clearly but you have the big picture.

A: You can leave just the view file and it should work.


Q: SQL Server Reporting Services 2008 R2 Express Edition "Report Builder" Button How do I enable the "Report Builder" button on SQL Server Reporting Services (Report Manager Web View).
I am using the 2008 R2 Express Edition.
Is this available in this edition ??
Thanks.

A: I don't believe that it's possible. If you compare Express to Standard, expand the Reporting node, you will see Model Support is unchecked for Express. Report Builder 1.0 only worked on prebuilt models so by extension, I'm assuming that bullet continues to address models and the report builder.
I never install Express so I can't dig around and verify it.
If the Report Builder button is not showing, verify the accessing account has Report Builder role or better.  Predefined SSRS Roles in 2008 R2

A: I can confirm that this feature is not available in the express edition - you will also not be able to create a report model.


Q: Using Formula Language to return column values I'm trying to return all values stored in the tNames variable.
Values exists in the field. The show multivalues as separate entries have been selected already but none of the names is returned.
Below is the sample code:
tNames := "";
@For(n := 0; n <= QuestionCount - 1; n := n + 1;
tNames := tNames + ", " + @Implode(@GetField("ChecklistContact_" +
  @Text(n));",")
);
@Trim(tNames)

I dont know why its not returning anything, will appreciate your help.
The below returns only the contact with index 0, but I want to return all contacts in each document.
tCount := 0;
@For(n := 0; n <= QuestionCount - 1; n := n + 1;
 tCount := tCount + @If(@GetField("ChecklistContact_" + @Text(n)) = ""; 0; 1)
);
@GetField("ChecklistContact_" + @Text(tCount))

Following comments from Richard the below return the required values, but will prefer not to hard code field name.
Is there any way of using for loop to return field names and values?
tNames := "";
tNames:= @GetField("ChecklistContact_1") : @GetField("ChecklistContact_2") : ... @GetField("ChecklistContact_7");
@Trim(tNames)

A: I don't believe that IBM's documentation says this explicitly, but I don't think @GetField works in column value formulas. The doc says that it works in the "current document", and there is no current document when the formula is executing in a view.
Assuming you know what the maximum number for N is, the way to do this is with a simple list:
ChecklistContact_1 : ChecklistContact_2 : ChecklistContact_3 : ... : ChecklistContact_N

If N is large, this will be a lot of typing, but you'll only have to do it once and copying and pasting and editing the numbers will make it go pretty quickly.

A: It might sound inelegant but, if you can, create a new computed field with your column formula in your form and then use that new field in your column. Also, from a performance standpoint you will be better off.

A: Maybe use your loop to create the list of fieldnames as Richard suggested, then display tNames


Q: Scala: expression's type is not compatible with formal parameter type trait Ingredient{}

case class Papperoni() extends Ingredient{}
case class Mushroom() extends Ingredient{}

trait ToppingDef[T] {
}

object PepperoniDef extends Serializable with ToppingDef[Papperoni] {
}

object MushroomDef extends Serializable with ToppingDef[Mushroom] {
}

class Oven[T <: Ingredient](val topping:ToppingDef[T]) {
}

class Pizza {
  def cook = {
    val topping =
      if(someCondition()) { PepperoniDef }
      else { MushroomDef}

    new Oven(topping) // <-- build error here
  }
}

I am using Scala 2.11.  This example is somewhat contrived but I’ve stripped out everything unrelated to the problem to provide a concise example.
The error I get on the last line is:
Error:(26, 5) no type parameters for constructor Oven: (topping: ToppingDef[T])Oven[T] exist so that it can be applied to arguments (Serializable with ToppingDef[_ >: Papperoni with Mushroom <: Product with Serializable with Ingredient])
 --- because ---
argument expression's type is not compatible with formal parameter type;
 found   : Serializable with ToppingDef[_ >: Papperoni with Mushroom <: Product with Serializable with Ingredient]
 required: ToppingDef[?T]
    new Oven(topping)

However changing the last line to this for example:
new Oven(PepperoniDef)

builds fine.  So the compiler has no problem finding the type when the parameter is passed explicitly like this.
Also, removing the Serializable trait from PepperoniDef and MushroomDef like this:
object PepperoniDef extends ToppingDef[Papperoni] {
}

object MushroomDef extends ToppingDef[Mushroom] {
}

also builds. However in my case I need the Serializable.
I think I can probably restructure the code to work around this if necessary but I would like to understand what's going on, I don't know why the type is ambiguous in the first case, or why the presence of the Serializable trait has any effect.  Thanks in advance for any insights.
EDIT: Thank you for the replies, very helpful.  I think the most concise fix is to change this:
val topping =

to this:
val topping:ToppingDef[_ <: Ingredient] =

Which cures the build error and does not require a change to the generic classes, which I would like to keep as simple an unannotated as possible so as to have Scala infer as much type information as possible.
This doesn't answer the question of why the presence of Serializable has any effect on this.

A: It seems that helping the compiler out with type annotation makes this compile:
val topping: ToppingDef[
    _ >: Papperoni with Mushroom <: Ingredient with Product with Serializable] =
    if (true) {
      PepperoniDef
    } else {
      MushroomDef
    }

I don't think this has to do with the Serializable class specifically, it seems like a compiler quirk to me since the produced type has a mixed in type including Product with Serializable anyway.
You can also "relax" the type signature by making T covariant, meaning Topping[Ingredient] will be inferred. This happens because the "is subtype of" relation Papperoni <: Ingredient on a covariant ToppingDef[+T] means ToppingDef[Papperoni] <: ToppingDef[Ingredient], thus allowing the common supertype for T:
trait ToppingDef[+T]
val topping: ToppingDef[Ingredient with Product with Serializable] =
  if (true) {
    PepperoniDef
  } else {
    MushroomDef
  }

And this also compiles without type annotation.
Edit:
Making Ovens type parameter an existential instead of a universally quantified type seems to work as well with the Serializable trait:
class Oven[_ <: Ingredient](val topping: ToppingDef[_])

val topping: Serializable with ToppingDef[_ <: Ingredient] =
  if (true) {
    PepperoniDef
  } else {
    MushroomDef
  }

new Oven(topping)

A: You need to add some type information to your trait:
trait ToppingDef[+T <: Ingredient] {}

Right now the topping variable is not able to figure out that T is supposed to be an Ingredient so you need to tell it.


Q: Pass string array to PHP script as POST I am trying to pass a string array to a PHP script as POST data in an Android app but i have an issue.
this is my client side code:
ArrayList<NameValuePair> querySend = new ArrayList<NameValuePair>();
for (Stop s : stops) {
                querySend.add(new BasicNameValuePair("stop_data[]", s.getNumber()));
            }
HttpClient httpclient = new DefaultHttpClient();
                HttpPost httppost = new HttpPost("http://www.myURL/myPHPScript.php");
                httppost.setEntity(new UrlEncodedFormEntity(querySend));
                HttpResponse response = httpclient.execute(httppost);

and this is my PHP script code:
foreach($_GET['stop_data'] as $stop) {
  // do something
}

If i run my java code i will get this response error from php script:
Warning: Invalid argument supplied for foreach() in /web/htdocs/www.myURL/myPHPScript.php on line 6
null

otherwise if i will put the request on my browser manully in this way:
http://www.myURL/myPHPScript.php?stop_data[]=768&stop_data[]=1283

i will give the correct answer!
if i try the same code, but if i POST not an array but a single string passing and receiving stop_data variables without [] it works!
I can't understand where is the mistake!! It is possible that the [] in BasicNameValuePair String name are doing some codification mistaken? I need to pass an array, how i have to do?

A: you use POST method and in php code you should use $_POST
try this
foreach($_POST['stop_data'] as $stop) {
  // do something
}

this way is using GET method
http://www.myURL/myPHPScript.php?stop_data[]=768&stop_data[]=1283


Q: Create a .htaccess file with the code for clean url I want to create clean url, so I tried many configurations.  I also created an .htaccess file but it does not work.  Anyone can help me?
My .htaccess code
Options +FollowSymLinks
RewriteEngine on
RewriteRule single-post/id/(.*)/title/(.*)/ single-post.php?id=$1&title=$2
RewriteRule single-post/id/(.*)/title/(.*) single-post.php?id=$1&title=$2

Present url
http://localhost/just2minute/story/single-post/id/2590/title/%E0%A4%95%E0%A5%87%E0%A4%B0%E0%A4%B2%20%E0%A4%AE%E0%A5%87%E0%A4%82%20%E0%A4%AC%E0%A4%BE%E0%A4%B0%E0%A4%BF%E0%A4%B6%20%E0%A4%94%E0%A4%B0%20%E0%A4%B2%E0%A5%88%E0%A4%82%E0%A4%A1%E0%A4%B8%E0%A4%B2%E0%A4%BE%E0%A4%87%E0%A4%A1%20%E0%A4%B8%E0%A5%87%2018%20%E0%A4%B2%E0%A5%8B%E0%A4%97%E0%A5%8B%E0%A4%82%20%E0%A4%95%E0%A5%80%20%E0%A4%AE%E0%A5%8C%E0%A4%A4/

I want to create"
http://localhost/just2minute/story/single-post/id/(Any Value)/title/(Any Value)/

A: You do not need two rules. You can achieve the goal using one rewrite rule, for example,
RewriteRule ^story/single-post/id/([0-9]+)/title/([0-9a-zA-Z-]+)/?$ single-post.php?id=$1&title=$2

After that you can access with the URL like this
https://localhost/just2minute/story/single-post/id/51835322/title/create-a-htaccess-file-with-the-code-for-clean-url

Then you want to do something like explained in this article:
https://www.tinywebhut.com/remove-duplicate-urls-from-your-website-38


Q: Modify path name when saving with PIL I am extracting RGB channels  from images and saving them as grayscale png files, but I have trouble saving them. Here is my code:
listing = os.listdir(path1)
for f in listing:
    im = Image.open(path1 + f)
    red, green, blue = im.split()
    red = red.convert('LA')
    green = green.convert('LA')
    blue = blue.convert('LA')
    red.save(path2 + f + 'r', 'png')
    green.save(path2 + f + 'g', 'png')
    blue.save(path2 + f + 'b','png')

Where path1 and path2 are image folder and save destinations respectively. What I want to do is to save the b&w version of color channel of img.png to
imgr.png, imgg.png, imgb.png, but what I get with this code is img.pngr, img.pngg, img.pngb. Any help would be appreciated.

A: You first need to split the filename from the extension.
import os
filename = path2 + f # Consider using os.path.join(path2, f) instead
root, ext = os.path.splitext(filename)

Then you can combine them correctly again doing:
filename = root + "r" + ext

Now filename would be imgr.png instead of img.pngr.

A: You could do this as follows:
import os

listing = os.listdir(path1)

for f in listing:
    im = Image.open(os.path.join(path1, f))

    red, green, blue = im.split()
    red = red.convert('LA')
    green = green.convert('LA')
    blue = blue.convert('LA')

    file_name, file_ext = os.path.splitext(f)

    red.save(os.path.join(path2, "{}r.png".format(file_name))
    green.save(os.path.join(path2, "{}g.png".format(file_name))
    blue.save(os.path.join(path2, "{}b.png".format(file_name))

I would recommend you make use of the os.path.split() and os.path.join() functions when working with paths and filenames.


Q: Putting $scope in Cytoscape click event I have created a network graph using Cytoscapejs. I am trying to unhide a div, and load more things after the user click on edge of the graph.
I have the following in my controller:
CytoscapeService.getGraph().on('tap', 'edge[id = "123"]', function (event) {

console.log("Hi")
//Above console printout works.

  //The below does not work on index.html
  $scope.testMessage = "Hello World";
  $scope.showMe = function () {
    $scope.show = true;
  }

  $scope.showMe();

});

// This works though.
//$scope.testMessage = "Hi from outside";

And in Index.html:

  {{testMessage}}

The console.log does get print out but the $scope.showMe with function inside isn't being called. However, if I move the scope outside of this clause, into the main clause of the Controller, it works.
Any there alternatives on how I can achieve this?

A: This is common with angular when you are  using jquery events to update a $scope value. You will have to manually triger a $scope apply:
$scope.$apply(function(){
    $scope.show = true;
});

Another solution would be to use Angular's $timeout
$timeout(function () {
    $scope.show = true;
});

See the documentation for $scope.apply() and more scope information.


Q: SSL self-signed certificate on client side When I create a SSL self-signed certificate.

*

*If I don't add the .crt on the client side,  the browser (Chrome/Firefox) seems to download implicitly the .crt. Is it possible to prevent this ?

*If I add the .crt within Chrome Trusted root store, I get the so-called "Your connection is not private" page. Is it normal ? Is there a way to avoid it ?


Q: Ошибка при добавлении в массив Vue подскажите почему ошибка this is undefined ?
<template>

    <button class="btn btn-success" @click="addRow">Добавить в новый массив</button>

{{ newRole }}

</template>

A: Дело в контексте. Используйте стрелочную функцию в качестве callback для forEach, чтобы использовать в нем this для экземпляра vue.
addRow() {
  this.role.forEach((value, key) => {
    this.newRole.push(value.id);
  });
}

Стрелочные функции особенные: у них нет своего «собственного» this.
  Если мы используем this внутри стрелочной функции, то его значение
  берётся из внешней «нормальной» функции. Это является особенностью стрелочных функций. Они полезны, когда мы на самом деле не хотим иметь отдельное значение this, а хотим брать его из внешнего контекста.

new Vue({
  el: '#app',
  data() {
    return {
      role: [{
          name: 'Alex',
          id: '1'
        },
        {
          name: 'Sveta',
          id: '2'
        },
      ],
      newRole: []
    }
  },
  methods: {
    addRow() {
      this.role.forEach((value, key) => {
        this.newRole.push(value.id);
      });
    }
  }
})

  <button class="btn btn-success" @click="addRow">Добавить в новый массив</button>

{{ newRole }}


Q: Non-isomorphic covering spaces with same domain and range Suppose $X$ is a connected topological space and $p,q:\tilde X\to X$ are covering spaces of $X$. That is, for all $x\in X$ there exists an open $U\subseteq X$ containing $x$ such that $p^{-1}[U],q^{-1}[U]$ are disjoint unions of open sets in $\tilde X$ which are homeomorphic to $U$. Is there always a pair of homeomorphisms $\tilde h:\tilde X\to\tilde X$ and $h:X\to X$ such that $p\tilde h=hq$? I can see how this would not have to be the case if $X$ were disconnected, but I can't think of a counterexample where $X$ is connected.


Q: Flex how to format a date string when it could be two different formats I have a date field in flex and have the format set to YYYY-MM-DD.  As long as the user clicks the calendar pop-up it set's it that way.
However, I need to allow the field to be human enter-able so they can type in a date.
The problem is, most users want to type the format  MM/DD/YYYY.   I have a tool tip that shows the format, but how can I check the format and change it to the YYYY-MM-DD format, or do something else appropriate (alert?)?

A: Easy enough:
DateFormatter.parseDate(yourString);

As long as your string is somewhat of a standard format, it should work.


Q: how to use for loop in a JButton  public void init(GUI gui){
    // the class extends Jframe
   gui.setSize(1024, 700);
   gui.setPreferredSize(new Dimension(1024, 700));
   gui.setResizable(false);
   gui.setLocationRelativeTo(null);
   gui.setTitle("Student Management System");
   gui.setDefaultCloseOperation(EXIT_ON_CLOSE);
   Admin_AllStudents_pnl=new JLayeredPane();
   Admin_AllStudents_pnl.setSize(1024,700);
   Admin_AllStudents_pnl.setLayout(null);
   Admin_AllStudents_pnl.setVisible(false);
   Admin_AllStudents_pnl.setOpaque(true);
  // Admin_AllStudents_pnl.setBackground(Color.white);

   String col[]={"ID","Name","Password","Cell","Adress"};
   DefaultTableModel tablemodel=new DefaultTableModel(col,0);
   All_Students=new JTable(tablemodel);

   view_all=new JButton("View_All");
   Admin_AllStudents_pnl.add(view_all);
   view_all.setBorder(null);
   view_all.setBounds(10,10,view_all.getPreferredSize().width,view_all.getPreferredSize().height);

   view_all.addActionListener(new ActionListener(){
       @Override

// Student and admin are both classes s gets an array list from the admin of all //the students.
//i need to display them in a table format so using for loop.
       public void actionPerformed(ActionEvent ae) {
        ArrayList<Student> s=new ArrayList<>();
        s=admin.AllStudent();
        System.out.println("size of s arraylist"+s.size());

       for(int i=0;i<s.size();i++)
       {
       String Ids=s.get(i).getId();
       String names=s.get(i).getName();
       String passwords=s.get(i).getPass();
       String cells=s.get(i).getCell();
       String adresss=s.get(i).getAdress();
       Object[] data={Ids,names,passwords,cells,adresss};
       tablemodel.addRow(data);
       }
       }

   });

  Admin_AllStudents_pnl.add(All_Students);

   gui.add(Admin_AllStudents_pnl);

only the for loop is not working whole code works fine without for loop every variable is already declared the code is about of 1000 lines so i cant upload all of it.


Q: How to apply a rule to only one component in altium? I would leave the insulation of copper with 0.35 mm across the board except in a microcontroller. It requires that the insulation allowed is 0.2 mm because of the distances between the pad. How to make a rule unique to this component?

A: As this problem regards with the footprint itself, instead of being a problem of a whole net or component, you can proceed making a rule just for the footprint.
I've done this with success:

*

*Design > Rules > Clearance > New Rule

*Change the new rule priority to the highest, or if you have plenty rules, arrange it correctly to make it work.

*Enter the new rule properties with double click

*In "Where The First Object Matches", select "Custom Query"

*Write "HasFootprint('NameOfYourFootprint')

*Set the desired values in the Constraints tab, then accept.

Now we are going to re run the design rule checker.

*Tools > Reset Error Markers

*Tools > Design Rule Checker > Run Design Rule Check

Hope this works for you too.

A: Draw a room, then use the "WithinRoom" query.

A: I think you can put a directive via a box around the MCU on the schematic to assign a net class to the nets associated with the MCU using a Blanket Directive and then apply the rule to that net class, however it will relax the clearance rules for all parts of those nets anywhere on the PCB.
If you are willing to be a little less automated, you can run DRC for the board, confirm that the only errors are those associated with the footprint, then relax the rule. If editing happens subsequently, traces will be allowed to be closer anywhere on the PCB of course.


Q: System.Net.WebException on YoutubeExtractor when downloading a video Environment

*

*Windows 8.1

*Visual Studio 2017 Community

*C#

*WPF application

Issue

*

*YoutubeExtractor throws System.Net.WebException when downloading a video.

I got YoutubeExtractor by Nuget and it doesn't work. The VideoInfo object isn't null. I tried several videos on Youtube and the same exceptions popped up. I googled the issue and it didn't give me much help.
Here's the code.
var videos = DownloadUrlResolver.GetDownloadUrls(@"https://www.youtube.com/watch?v=M1wLtAXDgqg");
VideoInfo video = videos
    .First(info => info.VideoType == VideoType.Mp4 && info.Resolution == 360);

if (video.RequiresDecryption)
    DownloadUrlResolver.DecryptDownloadUrl(video);

var videoDownloader = new VideoDownloader(video, System.IO.Path.Combine("D:", video.Title + video.VideoExtension));

videoDownloader.DownloadProgressChanged += (sender_, args) => Console.WriteLine(args.ProgressPercentage);

videoDownloader.Execute(); // I got the exception here.

How can I solve this issue? Thanks.
EDIT : 2017/10/26 13:42 GMT
Alexey 'Tyrrrz' Golub's answer helped so much! I corrected his original code and here it is.
using YoutubeExplode;
using YoutubeExplode.Models.MediaStreams;

var client = new YoutubeClient();
var video = await client.GetVideoAsync("bHzHlSLhtmM");
// double equal signs after s.VideoQuality instead of one
var streamInfo = video.MuxedStreamInfos.First(s => s.Container == Container.Mp4 && s.VideoQuality == VideoQuality.Medium360);
// "D:\\" instead of "D:"
var pathWithoutExtension = System.IO.Path.Combine("D:\\", video.Title);
// streamInfo.Container.GetFileExtension() instead of video.VideoExtension (video doesn't have the property)
var path = System.IO.Path.ChangeExtension(pathWithoutExtension, streamInfo.Container.GetFileExtension());
// new Progress<double>() instead of new Progress()
await client.DownloadMediaStreamAsync(streamInfo, path, new Progress<double>(d => Console.WriteLine(d.ToString("p2"))));


Q: kotlin whereNotEqualTo doesn't work for a field that has null value in firestore

BJ document has a null value of the capital field which should have not taken by  whereNotEqualTo
 val citiesRef = db.collection("cities").whereNotEqualTo("capital", true)
    try {
        val documents = citiesRef.get().await()
        for (document in documents){
            Log.d(TAG,"${document.data}")
        }
    }catch (e:Throwable){
        Log.d(TAG,e.message.toString())
    }

This code is not working despite the documentation saying that

Note that null field values do not match != clauses, because x != null evaluates to undefined.

but after I altered the null value with true or false doesn't matter which one is chosen, the code works well. can somebody explain to me what is the problem I encountered?

A: When you are using the following query:
val citiesRef = db.collection("cities").whereNotEqualTo("capital", true)

It means that you are trying to get all documents in the cities collection where the capital field holds the opposite value of the Boolean true, which is false. So you'll only get the documents where the capital field holds the value of false. The above query is the same with:
val citiesRef = db.collection("cities").whereEqualTo("capital", false)

Since null, is not the negation of true, the documents that have the capital field set to null, won't be returned. And it makes sense since null is not a boolean type, not a string type, nor any other supported data types. Null represents "none" or "undefined" and it's a distinct data type and cannot be considered "not equal" to any other data type.
That's the same as the docs states:

Note that null field values do not match != clauses


Q: How to create mobile, tablet, desktop viewable web template I want to create same category two templates. First one for tablet, laptop and desktop viewable to any screen size and second one for mobile viewable to any screen size.
How can I create all device (mobile, tablet, laptop and desktop any screen size) viewable template?
I searched last two week in google to find out the above question answer but I unfortunately I don’t find any useful link. So please, anyone can help me giving above question answer (any useful link or details description). Thanks

A: Those kind of templates are really hard to find unless u pay fo them.
Just have a look on this :
http://mobile.smashingmagazine.com/2010/07/19/how-to-use-css3-media-queries-to-create-a-mobile-version-of-your-website/


Q: $y'=4-x^2y^2$ and slope field Differential equation :
$y'=4-x^2y^2$.
Write slope field of this equation, and answer T/F:
$(a)$ The solution which includes $(x,y)=(0,0)$ has a local minima.
$(b)$ The solution which includes $(x,y)=(0,0)$ has a local maxima.
$(c)$ The solution which includes $(x,y)=(0,0)$ has at least one inflection point.
I can't get some things :
First of all, I used the slope field generator of desmos and get :
$y'=4-x^2y^2$" />
How am I supposed to draw my solutions with this slope field ?
For $(a),(b),(c)$ the answer is yes but I can't get why.
If $(x,y)=(0,0) \implies y'=4-0=4$, then how there is local minima, maxima, and inflection point?
I'd be grateful for your help!

A: If your function has a positive slope at $(0,0)$, it must certainly turn around at some point by looking at the slope field. First, notice that your solution is continuous. Recall that solutions of a slope field cannot intersect.

*

*If you start at the origin, and move down and to the left, which is what you would do with a positive slope, you will eventually hit a point on your slope field where the slope is negative. Hence, your solution must transition from negative to positive somewhere in between that, i.e. your solution has a local minimum.

*The same logic applies here. Move up and to the right and you will hit a point where the slope changes to negative, so you have a local max somewhere between that.

*A solution that contains a local max and local min must have an inflection point somewhere.


Q: control system - is the gain positive or negative? If the phase of a control system at high frequencies approaches to 0º then its gain K is negative. And if it approaches to -180º it gain is positive? Why is that? And how it works for low frequencies? Does anybody here know where can I find information about it?
The transfer function of the control system:

Phase result (request by @AJN):

A: It all depends on the numerator phase angle. This is either \$\small\phi =atan\:(\frac{-\omega}{\omega_{1}})=-90^o\$, or \$\small \phi =atan\:(\frac{\omega}{-\omega_{1}})=90^o\$, as \$\small\omega\rightarrow \infty \$. The denominator phase angle will always be \$\small -270^o\$, as \$\small\omega\rightarrow \infty \$.

A: Given
Phase approaches \$\Phi\$ at high frequencies (or 0 frequency);
And a transfer function which you can rewrite in the form
$$
H(s) = \frac{N(s)}{D(s)} = K \cdot \frac{\prod_{i=1}^{n} (s-z_i)}{\prod_{j=1}^{m} (s-p_j)}
$$
Finding the relation between angle and K
At high frequencies, \$s \rightarrow \jmath\infty\$ ans so \$s-c_i \approx s\$. So,
$$
\begin{align}
H(s)|_{s\rightarrow \jmath\infty} &{}\approx{}
K \cdot \frac{\prod_{i=1}^{n} s}{\prod_{j=1}^{m} s}
= K \cdot s^{n-m}\\
%
\angle H(s)_{s\rightarrow \jmath\infty} &{}\approx{}
\angle K + \angle(\jmath \omega)^{n-m}
= \angle K + \angle(\jmath)^{n-m} = \color{blue}{\angle K + (n-m) \times 90\deg}
\end{align}
$$
\$\angle K = 0\$ if \$K \ge 0\$  and \$\angle K = 180\$ if \$K < 0\$.
At low frequencies, \$s \rightarrow \jmath 0\$ ans so \$s-c_i \approx -c_i\$. Similar derivation for the angle can be done for this case also.
Your example
$$
H(s)|_{s\rightarrow \jmath\infty} {}\approx{}
K \frac{s}{s^3} \\
\angle H(s)|_{s\rightarrow \jmath\infty} {}\approx{}
\angle K + (1-3) \times 90 \deg = \angle K - 180 \deg
$$
So, if it was given that the angle approached -180 deg at high frequencies, then K would have been positive, so that it contributed 0 deg in the blue equation above.
But, your handwritten results show the reverse. I think it is because you have not taken the correct quadrant for the angle while taking \$\tan^{-1}\$ for the middle term \$\tan^{-1}(-100000/(8000\pi))\$.
See the below difference when taking arctan:
>> atan2d(-100000, 8000)
ans = -85.426
>> atan2d(100000, -8000)
ans =  94.574


Q: Get all changed files in a changest I want to get all the changed file in a changeset but without having the letter that specify the change type.
I know this command
hg status --change changeset

However, this return result like,
A /path/to/file
M /path/to/file

I want the result to be
/path/to/file

without "A" or "M". I tried to do it with regular expression and it used to work but I don't know it didn't work in one scenario.
The regular expression,
/(?<=[MA]\s).+/

This the scenario that did not work
arwa/Documents/Projects/firefox/M db << notice M here.

Any thought?

A: You should add ^ (start of line) to your regex:
/(?<=^[MA]\s).+/

If you don't do that, (?<=[MA]\s) will lookabehind the M part and .+ will catch db.

A: As of Mercurial 3.5, you can use templates (still an experimental feature, you can see it with hg help status -v). Namely:
hg status --change <rev> --template '{path}\n'

A: Why not use log with template?
hg log -r CSET -T "{files % '{file}\n'}"

will produce clean output
lang/UTF-8/serendipity_lang_ru.inc.php
plugins/serendipity_event_bbcode/UTF-8/lang_ru.inc.php
plugins/serendipity_event_emoticate/UTF-8/lang_ru.inc.php
plugins/serendipity_event_karma/UTF-8/lang_ru.inc.php
plugins/serendipity_event_s9ymarkup/UTF-8/lang_ru.inc.php
plugins/serendipity_plugin_shoutbox/UTF-8/lang_ru.inc.php

contrary to templated status
'lang\UTF-8\serendipity_lang_ru.inc.php
''plugins\serendipity_event_bbcode\UTF-8\lang_ru.inc.php
''plugins\serendipity_event_emoticate\UTF-8\lang_ru.inc.php
''plugins\serendipity_event_karma\UTF-8\lang_ru.inc.php
''plugins\serendipity_event_s9ymarkup\UTF-8\lang_ru.inc.php
''plugins\serendipity_plugin_shoutbox\UTF-8\lang_ru.inc.php
'


Q: App closes upon using BACKSPACE or SHIFT button in an EditText view When using the BACKSPACE or SHIFT of the onscreen keyboard to edit text in EditText views, my app closes (didn't have this problem before). It is possible to type in text, but as soon as I use BACKSPACE or SHIFT, the app closes.
Logcat gives the following alerts:
at android.os.Handler.dispatchMessage(Handler.java:106)
at android.os.Looper.loop(Looper.java:214)

Line 106 of Handler.java reads as follows;
handleMessage(msg);

Line 214 of Looper.java reads as follows;
if (logSlowDispatch) {
     showSlowLog(slowDispatchThresholdMs, dispatchStart,
     dispatchEnd, "dispatch", msg);
}

What action should I take to remedy this? Here is the full Logcat
    2019-09-09 16:46:12.416 13560-13560/? E/Zygote: isWhitelistProcess - Process is Whitelisted
2019-09-09 16:46:12.417 13560-13560/? E/Zygote: accessInfo : 1
2019-09-09 16:46:23.608 13560-13560/com.commonsense.android.doorway E/AndroidRuntime: FATAL EXCEPTION: main
    Process: com.commonsense.android.doorway, PID: 13560
    java.lang.NoSuchMethodError: No static method dispatchUnhandledKeyEventPre(Landroid/view/View;Landroid/view/KeyEvent;)Z in class Landroid/support/v4/view/ViewCompat; or its super classes (declaration of 'android.support.v4.view.ViewCompat' appears in /data/app/com.commonsense.android.doorway-4nmhQXtmyOPwFjuoPHsunQ==/base.apk)
        at android.support.v7.app.AppCompatDelegateImpl.dispatchKeyEvent(AppCompatDelegateImpl.java:1162)
        at android.support.v7.app.AppCompatDelegateImpl$AppCompatWindowCallback.dispatchKeyEvent(AppCompatDelegateImpl.java:2529)
        at com.android.internal.policy.DecorView.dispatchKeyEvent(DecorView.java:590)
        at android.view.ViewRootImpl$ViewPostImeInputStage.processKeyEvent(ViewRootImpl.java:6094)
        at android.view.ViewRootImpl$ViewPostImeInputStage.onProcess(ViewRootImpl.java:5949)
        at android.view.ViewRootImpl$InputStage.deliver(ViewRootImpl.java:5402)
        at android.view.ViewRootImpl$InputStage.onDeliverToNext(ViewRootImpl.java:5455)
        at android.view.ViewRootImpl$InputStage.forward(ViewRootImpl.java:5421)
        at android.view.ViewRootImpl$AsyncInputStage.forward(ViewRootImpl.java:5580)
        at android.view.ViewRootImpl$InputStage.apply(ViewRootImpl.java:5429)
        at android.view.ViewRootImpl$AsyncInputStage.apply(ViewRootImpl.java:5637)
        at android.view.ViewRootImpl$InputStage.deliver(ViewRootImpl.java:5402)
        at android.view.ViewRootImpl$InputStage.onDeliverToNext(ViewRootImpl.java:5455)
        at android.view.ViewRootImpl$InputStage.forward(ViewRootImpl.java:5421)
        at android.view.ViewRootImpl$InputStage.apply(ViewRootImpl.java:5429)
        at android.view.ViewRootImpl$InputStage.deliver(ViewRootImpl.java:5402)
        at android.view.ViewRootImpl.deliverInputEvent(ViewRootImpl.java:8467)
        at android.view.ViewRootImpl.doProcessInputEvents(ViewRootImpl.java:8387)
        at android.view.ViewRootImpl.enqueueInputEvent(ViewRootImpl.java:8340)
        at android.view.ViewRootImpl$ViewRootHandler.handleMessage(ViewRootImpl.java:5039)
        at android.os.Handler.dispatchMessage(Handler.java:106)
        at android.os.Looper.loop(Looper.java:214)
        at android.app.ActivityThread.main(ActivityThread.java:7094)
        at java.lang.reflect.Method.invoke(Native Method)
        at com.android.internal.os.RuntimeInit$MethodAndArgsCaller.run(RuntimeInit.java:494)
        at com.android.internal.os.ZygoteInit.main(ZygoteInit.java:975)

And this is the build.gradle file. Android Studio says that mixing versions (like 28.0.0) in the dependencies can lead to bugs. Apparently they schould all be the same version. Could this be the problem source?
apply plugin: 'com.android.application'

android {
    compileSdkVersion 28
    defaultConfig {
        applicationId "com.commonsense.android.doorway"
        minSdkVersion 25
        targetSdkVersion 28
        versionCode 1
        versionName "1.0"
        testInstrumentationRunner "android.support.test.runner.AndroidJUnitRunner"
    }
    buildTypes {
        release {
            minifyEnabled false
            proguardFiles getDefaultProguardFile('proguard-android.txt'), 'proguard-rules.pro'
        }
    }
    productFlavors {
    }
}

dependencies {
    implementation fileTree(include: ['*.jar'], dir: 'libs')
    implementation 'com.android.support:appcompat-v7:28.0.0-alpha3'
    implementation 'com.google.code.gson:gson:2.8.2'
    implementation 'com.android.support.constraint:constraint-layout:1.1.2'
    implementation 'com.android.support:wear:28.0.0'
    testImplementation 'junit:junit:4.12'
    androidTestImplementation 'com.android.support.test:runner:1.0.2'
    androidTestImplementation 'com.android.support.test.espresso:espresso-core:3.0.2'
    implementation 'com.android.support:design:28.0.0-alpha3'
    compileOnly 'com.google.android.wearable:wearable:2.4.0'
}

When I detach the EditText views from their editText = findViewBy(R.id.editText), the error stops. But then of course the EditText views have become useless.

A: In the build.gradle file, I deleted implementation 'com.android.support:appcompat-v7:28.0.0-alpha3'. Android Studio had warned in uncertain terms (as usual) that putting different versions in the dependencies "might produce some bugs". The said dependency was the first that could be deleted without causing any compile errors. And waddayou know, the backspace/shift bug disappeared immediately...


Q: Default Value Containing Special Characters in HTML Form I was trying to get a symbol like ® to be a default value for a text field,
I am trying to set the default by a javascript , but all i get is ® or &® in the text box, i am doing this from script as i am using drupal , so i dont have html files , i even trie ddefault value option in hook_form()

A: I'm not clear on what exactly you're trying to do; maybe something like this?
// set the default value of yourTextField
yourTextField.defaultValue = '\u00AE';

// or set the actual value of yourTextField
yourTextField.Value = '\u00AE';


Q: Como hacer que la clase base conozca qué clase derivada está actuando Veamos. Tengo una clase base derivada de QTableView, en la que defino la mayoría de los métodos, entre ellos uno llamado Copiar()
De esa clase me derivan dos, obteniendo dos tablas con algunas diferencias entre ellas. Cada una de ellas tiene una acción para copiar el contenido, con implementaciones diferentes.
Una forma de hacerlo, es que cada clase derivada tenga su propia función Copiar(), la cual llamará al modelo que las sirve y ahí se implementará la función.
Pero me pregunto si yo puedo definir un solo método Copiar() en la tabla base, y que -sabiendo de qué tipo es la tabla que llama a la función- haga un casting o una selección a esa tabla derivada de forma que llame al modelo que le corresponde.
Algo como:
void TablaBase::Copiar()
{
    if (me ha enviado la señal la tabladerivada1)
    {
         tabladerivada1->model()->Copiar();
    }
    else
    {
         tabladerivada2->model()->Copiar();
    }
}

Edito:
Puesto que a esta función de la tabla base se la llama mediante una señal, acabo de ver que puedo acceder al emisor mediante el método sender(), en concreto sender()->parent() ya que el emisor es una QAccion, pero el tipo que me da es el de la tabla base, cuando lo está emitiendo una tabla derivada (si bien mediante una función virtual)
Esta sería la tabla base (pongo la parte representativa):
class Filter;

class TablaBase : public QTableView
{
    Q_OBJECT

public:
    TablaBase(int nColumnas, QWidget *parent=nullptr);
    bool columnaBloqueada(int columna);
    virtual void MostrarMenuCabecera(QPoint pos)=0;
    virtual void MostrarMenuTabla(QPoint pos)=0;//me centro en este
    QHeaderView* CabeceraDeTabla();
    ~TablaBase();

    int limiteIzquierdo;
    int limiteDerecho;

private slots:
    void Bloquear(int columna);
    void Copiar();
    void Pegar();

public slots:
    void customHeaderMenuRequested(QPoint pos);
    void customTableMenuRequested(QPoint pos);
-------------------

Ahora una de las tablas derivadas:
class TablaMedCert : public TablaBase
{
public:
    explicit TablaMedCert(int nColumnas, QWidget *parent=nullptr);
    void MostrarMenuCabecera(QPoint pos);
    void MostrarMenuTabla(QPoint pos);

private:
    DelegadosParcialesSubtotales* dlgPS;
    DelegadoMedicionesEstandar* dlgME;
};

La implementación de MostrarMenuTabla()
void TablaMedCert::MostrarMenuTabla(QPoint pos)
{
    QMenu *menu=new QMenu(this);
    QAction *AccionCopiar = new QAction("Copiar lineas de medición", this);
    QAction *AccionPegar = new QAction("Pegar lineas de medición", this);
    menu->addAction(AccionCopiar);
    menu->addAction(AccionPegar);
    /*copiar*/
    QObject::connect(AccionCopiar, SIGNAL(triggered()), this, SLOT(Copiar()));
    /*pegar*/
    QObject::connect(AccionPegar, SIGNAL(triggered()), this, SLOT(Pegar()));
    menu->popup(cabeceraVertical->viewport()->mapToGlobal(pos));
}

Y por último la implementación de Copiar() en la tabla base (bueno, realmente no hay tal). Pensaba que el sender()->parent() sería TablaMedCert, con lo que podría hacer un dynamic_cast para que llamase al modelo adecuado, pero veo que realmente el sender()->parent() es la tabla base
void TablaBase::Copiar()
{
    QObject* obj = sender();
    qDebug()<<obj->parent();
}

A: Se me ocurre una posible solución, muy fácil de implementar: utiliza un campo en la clase base para indicar desde que derivada estás llamando:
class Base {
private:
  int mDerived;

protected:
  Base( int d ) : mDerived( d ) { }

public:
  virtual algo( );
};

class Hija: public Base {
public:
  // Cambiamos el número según la clase hija que seamos.
  Hija( ) : Base( 1 ) { }
};

void Base::algo( ) {
  ...
  if( mDerived == ... ) {
    // Codigo dependiendo de la clase hija.
  } else if( mDerived == ... ) {
    ...
  }
}

También podrías utilizar typeid( *this ) si tus clases tienen métodos virtuales.

A: En C++ puedes hacer que una función se comporte de forma diferente según el tipo concreto de objeto que estés utilizando y esto se consigue con la palabra virtual:
struct A
{
  virtual void func() // Solo es necesario en la classe base
  { std::cout << "A\n"; }
};

struct B : A
{
  void func()
  { std::cout << "B\n"; }
};

struct C : B
{
  void func()
  { std::cout << "C\n"; }
};

struct D : B
{
  void func()
  { std::cout << "D\n"; }
};

int main()
{
  std::vector<A*> lista;
  lista.push_back(new A);
  lista.push_back(new B);
  lista.push_back(new C);
  lista.push_back(new D);

  for( int i=0; i<lista.size(); i++ )
  {
    A* puntero = lista[i];
    puntero->func();
  }
}

Salida:
A
B
C
D

En Qt esto funciona también con los slots. Aplicado a tu caso el código podría lucir más o menos así:
class TablaBase : public QTableView
{
private slots:
    virtual void Copiar();
};

class TablaMedCert : public TablaBase
{

private slots:
  // En la clase base esta funcion es virtual
  // En esta implementacion pones el comportamiento especifico para TablaMedCert
  void Copiar();
};

A: Bueno, al final lo he implementado como sigue.
La tabla base tiene una función bool Copiar() que será a la que llamen las tablas derivadas. Por otro lado, el problema lo estaba teniendo (y no sé por qué, la verdad) en el modelo que alimenta a las tablas derivadas, ya que si no se hace casting lo toma como un AbstractItemModel
Entonces, mi solución pasa por capturar el sender, haciendo un casting a la clase de la Tabla Base. Y luego ver qué modelo (MedicionesModel o PrincipalModel) tiene esa tabla haciendo de nuevo un casting a cada uno de los posibles. He cambiado el tipo a bool
El código es el siguiente, espero que esté bien y sirva:
bool TablaBase::Copiar()
{
    TablaBase* tabla = qobject_cast<TablaBase*>(sender()->parent());
    if (MedicionesModel* mod = qobject_cast<MedicionesModel*>(tabla->model()))
    {
        return mod->Copiar();
    }
    else if (PrincipalModel* mod = qobject_cast<PrincipalModel*>(tabla->model()))
    {
        return mod->Copiar();
    }
    else return false;
}

A: Bajo la asumpción que no quieres que tu método "copiar" sea virtual (tus objetos ya son polimórficos así que... no sé por qué no ir hacia la solución de eferion, más eficiente que la tuya), si no te importa que la clase base sea paramétrica:
template<class derivada>
class TablaBase : public QTableView
{ ... };

class TablaDerivada1 : public TablaBase<TablaDerivada>
{ ... };

Dentro de TablaBase, ya tienes el tipo de la derivada. Tu función copiar sería:
if (std::is_same<derivada, TablaDerivada1>::value)
    un_metodo();
else
    el_otro();

Si no quieres que sea paramétrica, entonces vete a una solución virtual:
if (dynamic_cast<TablaDerivada1*>(this) != nullptr)
     un_metodo();
else
     el_otro();

Como posibilidad adicional, también podrías trabajar con typeid o type_index, etc...


Q: Circular chemical reaction cascade I am trying to use tikz-cd package to draw circular chemical reaction cascade. Here is what I have tried so far
\documentclass{article}
\usepackage{graphicx, tikz-cd}
\begin{figure}[h]
    \centering
    \begin{tikzpicture}[node distance=3cm]
    % nodes
    \node (origin) at (0,0) {};
    \node (a) at (4,0) {A};
    \node (b) at (2.828,2.828) {B};
    \node (c) at (0,4) {C};
    \node (d) at (-2.828,2.828) {D};
    \node (e) at (-4, 0) {E};
    \node (f) at (-2.828,-2.828) {F};
    \node (g) at (0,-4) {G};
    \node (h) at (2.828, -2.828) {H};

    \draw (0, 0) circle [radius = 4cm]; %This element for illustration
    \draw [->] (a) to[bend right=45]  (b);
    \draw [->] (b) to[bend right=45]  (c);
    \draw [->] (c) to[bend right=45]  (d);
    \draw [->] (d) to[bend right=45]  (e);
    \draw [->] (e) to[bend right=45]  (f);
    \draw [->] (f) to[bend right=45]  (g);
    \draw [->] (g) to[bend right=45]  (h);
    \draw [->] (h) to[bend right=45]  (a);

    \end{tikzpicture}
    \caption{Caption}
\end{figure}

Which results into something like following,

However, I want arrows to be in circular manner. (Aligned to circle which I have drawn for illustration purpose). Also finally I am trying to get reaction cascade like this,

Any help will be appreciated ! I tried looking at this post but wasn't sure how to implement here.


Q: Make a table in ebook file I wanna make a book with parallel translation. It supposed to have table with to columns - one have text on source language, the other on target language.
I found, that I can do it easy with fb2, just write a xml code by python script. But my ebook read it ugly - the first column much wider than the second. (see picture)
Code example:

         Lang1
         Lang2

       ... the same ...

I don't work with web design, and maybe dont understand some simple thing. How can I set size of columns? Or maybe I should use some other format (epub)
It essential, that I need format, which I can read on ebook comfortable. Books in PDF format are bad for this, cause I can't change font and don't want zoom.
Thanks for you answers!

A: FB2 Supports reflow by design which is the reason for poor table support in many ebook readers as two column is contra the basic reflow principle.
Thus HTML can support tables but are not always "expected" nor supported well in many ebook readers.
Daisy epubtest "basic" did not include tables ! But they are tested in Accessibility: Non-visual Reading. Adobe fails the visual display by not adjusting the 4 cell contents to fit device, and fails on navigation.
MuPDF show the table as one column with cells reflowing to fit the page width, Calibre uses varying width columns but can also have issues.

If you need a fixed layout, then PDF was designed to maintain page layout, Thus the answer is probably use PDF with a page column and font size targeted to suit a pocket book such as A6, two column, no margins, 6pt.
If it is for your own use only, then ebook format targeted for your device, may well work if the columns are fixed to half screen width.


Q: Make an SD card to boot the distribution image created with Yocto I have managed to build images for my own compiled Linux kernel source code using Yocto.
Yocto has produced image files according to:
http://www.crashcourse.ca/wiki/index.php/Yocto_Project_Quick_Start
Example from above link:
$ ls -F
core-image-minimal-beagleboard-20121120113536.rootfs.jffs2
core-image-minimal-beagleboard-20121120113536.rootfs.tar.bz2
core-image-minimal-beagleboard.jffs2@
core-image-minimal-beagleboard.tar.bz2@
MLO-beagleboard@
MLO-beagleboard-1.5.0+git1+9f94c6577e3a018b6b75cbe39f32bb331871f915-r0*
modules-3.4.11-yocto-standard-r4.3-beagleboard.tgz
README_-_DO_NOT_DELETE_FILES_IN_THIS_DIRECTORY.txt
u-boot-beagleboard.bin@
u-boot-beagleboard-v2011.06+git6+b1af6f532e0d348b153d5c148369229d24af361a-r3.bin*
u-boot.bin@
uImage@
uImage-3.4.11+git1+a201268353c030d9fafe00f2041976f7437d9386_1+449f7f520350700858f21a555  4b81cc8ad23267d-r4.3-beagleboard-20121120113536.bin
uImage-beagleboard.bin@
x-load-beagleboard-1.5.0+git1+9f94c6577e3a018b6b75cbe39f32bb331871f915-r0.bin.ift*
x-load-beagleboard.bin.ift@
$

How do I use these Images to produce an SD card that can boot the Linux dist Yocto has produced? Partioning etc? How do I use my Yocto images?

A: See:
http://android.serverbox.ch/?p=1273
Although I had to copy the uImage-xxx and rename it to uImage and put it into boot.
Also see:
https://groups.google.com/forum/#!topic/beagleboard/jqReCTG_L44
To make an image work for BeagleBone.


Q: Java Enumeration vs Iterator Enumeration doesn't throw ConcurrentModificationException , why?
See below code .
public static void main(String[] args) {

    Vector<String> v=new Vector<String>();
    v.add("Amit");
    v.add("Raj");
    v.add("Pathak");
    v.add("Sumit");
    v.add("Aron");
    v.add("Trek");

    Enumeration<String> en=v.elements();

    while(en.hasMoreElements())
    {
        String value=(String) en.nextElement();
        System.out.println(value);
        v.remove(value);

    }

}

It only prints :

Amit
Pathak
Aron

Why is this such behavior . Can we say that Enumerator is thread safe.
Edit: When working with Iterator it throws ConcurrentModificationException in single thread application.
public static void main(String[] args) {

    Vector<String> v=new Vector<String>();
    v.add("Amit");
    v.add("Raj");
    v.add("Pathak");
    v.add("Sumit");
    v.add("Aron");
    v.add("Trek");

    Iterator<String> it=v.iterator();
    while(it.hasNext())
    {
        String value=(String) it.next();
        System.out.println(value);
        v.remove(value);
    }
}

Please check.

A:
Enumeration doesn't throw ConcurrentModificationException , why?

Because there is no path in the code being invoked which throws this exception. Edit: I am referring to the implementation provided by the Vector class, not about the Enumeration interface in general.

Why is this such behavior . Can we say that Enumerator is thread safe.

It is thread-safe in a sense that the code executed is properly synchronized. However, I don't think the result your loop yields is what you would except.
The reason for your output is that the Enumeration object maintains a counter, which is incremented after every invokation of nextElement(). This counter is not aware of your invokation of remove().

A: the fail-fast behaviour which throws the ConcurrentModificationException is only implemented for the Iterator as you can read in
http://docs.oracle.com/javase/6/docs/api/java/util/Vector.html

A: Concurrent modification here has nothing to do with threads.
Concurrency here simply means that you are modifying the collection while you are iterating over it. (In your example this happens in the same thread.)
Iterators and enumerations of collections can throw ConcurrentModificationException in this case, but don't have to. The ones that do exhibit fail-fast behaviour. Apparently, the enumeration of Vector isn't fail-fast.
Thread-safety obviously involves multiple threads somehow. Vector is thread-safe only in the sense that its operations (like add, get, etc.) are synchronized. This is to avoid non-deterministic behaviour when one thread is adding an element while at the same time another thread is trying to remove one for example.
Now, when one thread is structurally modifying your collection while another thread is iterating over it, you have to deal with both thread-safety and concurrent modification issues. In this case, and probably in general, it is safest not to rely on ConcurrentModificationException being thrown. It is best to choose the appropriate collection implementation (a thread-safe one for example) and avoid/disallow concurrent modification yourself.
Some iterators allow adding/setting/removing elements through the iterator itself. This can be a good alternative if you really need concurrent modification.

A: Note that ConcurrentModificationException has nothing to do with concurrency in the sense of multithreading or thread safety. Some collections allow concurrent modifications, some don't. Normally you can find the answer in the docs. But concurrent doesn't mean concurrently by different threads. It means you can modify the collection while you iterate.
ConcurrentHashMap is a special case, as it is explicitly defined to be thread-safe AND editable while iterated (which I think is true for all thread-safe collections).
Anyway, as long as you're using a single thread to iterate and modify the collection, ConcurrentHashMap is the wrong solution to your problem. You are using the API wrongly. You should use Iterator.remove() to remove items. Alternatively, you can make a copy of the collection before you iterate and modify the original.
EDIT:
I don't know of any Enumeration that throws a ConcurrentModificationException. However, the behavior in case of a concurrent modification might not be what you expect it to be. As you see in you example, the enumeration skips every second element in the list. This is due to it's internal index being incremented regardless of removes. So this is what happens:

*

*en.nextElement() - returns first element from Vector, increments index to 1

*v.remove(value) - removes first element from Vector, shifts all elements left

*en.nextElement() - returns second element from Vector, which now is "Pathak"

The fail-fast behavior of Iterator protects you from this kind of things, which is why it is generally preferable to Enumberation. Instead, you should do the following:
Iterator<String> it=v.iterator();
while(it.hasNext())
{
    String value=(String) it.next();
    System.out.println(value);
    it.remove(); // not v.remove(value); !!
}

Alternatively:
for(String value : new Vector<String>(v)) // make a copy
{
    String value=(String) it.next();
    System.out.println(value);
    v.remove(value);
}

The first one is certainly preferable, as you don't really need the copy as long as you use the API as it is intended.

A: Short answer: It's a bonus feature that was invented after enumeration was already there, so the fact that the enumerator does not throw it does not suggest anything particular.
Long answer:
From wikipedia:

Collection implementations in pre-JDK 1.2 [...] did not contain a
  collections framework. The standard methods for grouping Java
  objects were via the array, the Vector, and the Hashtable classes,
  which unfortunately were not easy to extend, and did not implement a
  standard member interface. To address the need for reusable
  collection data structures [...] The
  collections framework was designed and developed primarily by Joshua
  Bloch, and was introduced in JDK 1.2.

When the Bloch team did that, they thought it was a good idea to put in a new mechanism that sends out an alarm (ConcurrentModificationException) when their collections were not synchronized properly in a multi-threaded program. There are two important things to note about this mechanism: 1) it's not guaranteed to catch concurrency bugs -- the exception is only thrown if you are lucky. 2) The exception is also thrown if you misuse the collection using a single thread (as in your example).
So, a collection not throwing an  ConcurrentModificationException when accessed by multiple threads does not imply it's thread-safe either.

A: It depends on how you get the Enumeration. See the following example, it does throw ConcurrentModificationException:
import java.util.*;

public class ConcurrencyTest {
    public static void main(String[] args) {

        Vector<String> v=new Vector<String>();
        v.add("Amit");
        v.add("Raj");
        v.add("Pathak");
        v.add("Sumit");
        v.add("Aron");
        v.add("Trek");

        Enumeration<String> en=Collections.enumeration(v);//v.elements();

        while(en.hasMoreElements())
        {
            String value=(String) en.nextElement();
            System.out.println(value);
            v.remove(value);
        }

        System.out.println("************************************");

        Iterator<String> iter = v.iterator();
           while(iter.hasNext()){
              System.out.println(iter.next());
              iter.remove();
              System.out.println(v.size());
        }
    }
}

Enumeration is just an interface, it's actual behavior is implementation-dependent. The Enumeration from the Collections.enumeration() call wraps the iterator in someway, so it's indeed fail-fast, but the Enumeration obtained from calling the Vector.elements() is not.
The not-fail-fast Enumeration could introduce arbitrary, non-deterministic behavior at an undetermined time in the future. For example: if you write the main method as this, it will throw java.util.NoSuchElementException after the first iteration.
public static void main(String[] args) {

        Vector<String> v=new Vector<String>();
        v.add("Amit");
        v.add("Raj");
        v.add("Pathak");

        Enumeration<String> en = v.elements(); //Collections.enumeration(v);

        while(en.hasMoreElements())
        {
            v.remove(0);
            String value=(String) en.nextElement();
            System.out.println(value);
        }
    }

A: remove the v.remove(value) and everything will work as expected
Edit: sorry, misread the question there
This has nothing to do with threadsafety though. You're not even multithreading so there is no reason Java would throw an exception for this.
If you want exceptions when you are changing the vector make it Unmodifiable


Q: Access DataGridTemplateColumn content I have a WPF DataGrid templatecolumn that has a DataTemplate for an AutoCompleteBox from the wpf toolkit.  During RowEditEnding event and validation procedures, I am not able to see the content in the templatecolumn.
<DataGridTemplateColumn Header="Account Type" >
    <DataGridTemplateColumn.CellTemplate>
        <DataTemplate>
            <toolkit:AutoCompleteBox Text="{Binding Path='Account Type'}" Populating="PopulateAccountTypesACB" IsTextCompletionEnabled="True" BorderThickness="0" />
        </DataTemplate>
    </DataGridTemplateColumn.CellTemplate>
</DataGridTemplateColumn>

public override ValidationResult Validate(object value, System.Globalization.CultureInfo cultureInfo)
    {
        if ((value as BindingGroup).Items.Count == 0)
            return new ValidationResult(true, null);

        DataRowView row = (value as BindingGroup).Items[0] as DataRowView;

        if (row != null)
        {
            if (ValidateAccountName(row.Row.ItemArray[0].ToString()))
            {
                return new ValidationResult(true, null);
            }
            else
            {
                return new ValidationResult(false,
                    "Account Name must be between 1 and 100 Characters.");
            }
        }
        else
            return new ValidationResult(true, null);
    }

When I put a break point in my validation function after I create the DataRowView, the template column is empty.  How would I get its content?

A: For a start you have a space in the Path of your Binding for the AutoCompleteBox.Text property which I don't think is allowed.

A: After looking into this, it seems like it doesn't have anything to do with the DataGridTemplateColumn, but rather with the AutoCompleteBox from the Wpf Toolkit.  The AutoCompleteBox has been nothing but trouble for me ever since I started using it.  As a result, I decided to scrap it and use an Editable ComboBox instead.  The combobox is much cleaner and more simple to implement. Here is how my code now looks and the datarowview is able to see what the user types in the box:
<DataGridTemplateColumn Header="Account Type">
    <DataGridTemplateColumn.CellTemplate>
        <DataTemplate>
            <TextBlock Text="{Binding Path='Account Type'}" />
        </DataTemplate>
    </DataGridTemplateColumn.CellTemplate>
    <DataGridTemplateColumn.CellEditingTemplate>
        <DataTemplate>
            <ComboBox IsEditable="True" LostFocus="LostFocusAccountTypes" ItemsSource="{DynamicResource types}" Height="23" IsTextSearchEnabled="True"/>
        </DataTemplate>
    </DataGridTemplateColumn.CellEditingTemplate>
</DataGridTemplateColumn>

Code Behind (this.Types is an observable collection of strings)
    private void PopulateAccountTypes()
    {
        try
        {
            string accountQuery = "SELECT AccountType FROM AccountType WHERE UserID = " + MyAccountant.DbProperties.currentUserID + "";

            SqlDataReader accountType = null;
            SqlCommand query = new SqlCommand(accountQuery, MyAccountant.DbProperties.dbConnection);

            accountType = query.ExecuteReader();

            while (accountType.Read())
            {
                this.Types.Add(accountType["AccountType"].ToString());
            }

            accountType.Close();
            Resources["types"] = this.Types;
        }
        catch (Exception ex)
        {
            MessageBox.Show(ex.Message);
        }
    }


Q: Wait for nested async calls to finish I have a series of nested async calls that need to finish before my code continues. Function save_part1 calls the sqlite database and returns the rows of interest. For each of those rows, I make an ajax call to a save them remotely.
From what I have read about promises and deferred, I have only seen them being used in the context of ajax calls. And on top of that, it makes my brain hurt.
Question: how do I wait until all the ajax calls have completed before starting save_part2?
function save()
{
    save_part1();
    //this should only happen after all the ajax calls from save_part1 are complete
    save_part2();
}
function save_part1()
{
    db.transaction(function (tx) {
        tx.executeSql("SELECT * FROM TABLE1", [],
            function (transaction, results) {
                for (var i = 0; i < results.rows.length; i++)
                {
                    var row = results.rows.item(i);

                    ajaxCall_item1(row);

                }
            }, errorHandler)
    });
}

function save_part2()
{
    db.transaction(function (tx) {
        tx.executeSql("SELECT * FROM TABLE2", [],
            function (transaction, results) {
                for (var i = 0; i < results.rows.length; i++)
                {
                    var row = results.rows.item(i);

                    ajaxCall_item2(row);

                }
            }, errorHandler)
    });
}

A: As long as you have ajaxCall_item returning the jQuery deferred object, you can have save_part1 return a deferred object, collect the returned promises into an array, call them with $.when and resolve the "promise" once all of the requests have completed. Then you will be able to write: save_part1().then(save_part2);. Here is an untested example:
function save() {
    save_part1().then(save_part2).fail(function(err) {
      // ohno
    });
}

function ajaxCall_item1(row) {
  return $.ajax({ ... });
}

function save_part1()
{
  var dfd = jQuery.Deferred();
  var promises = [];
  db.transaction(function (tx) {
    tx.executeSql("SELECT * FROM TABLE1", [],
      function (transaction, results) {
        for (var i = 0; i < results.rows.length; i++) {
            var row = results.rows.item(i);
            promises.push(ajaxCall_item1(row));
        }

        $.when.apply($, promises).then(function() {
          dfd.resolve.apply(dfd, arguments);
        });
      }, function(err) {
        dfd.reject(err);
      });
  });
  return dfd;
}


Q: Java Installation in Ubuntu 20.4 This is my first time of using Ubuntu. I am trying to install java jdk-15 in my lap.I applied following steps.

*

*sudo update-alternatives --install /usr/bin/java java /usr/lib/jvm/jdk-15/bin/java 1

*sudo update-alternatives --config java

*sudo gedit /etc/environment => I saved the path (JAVA_HOME = "/usr/lib/jvm/jdk-15" )

*source /etc/environment ==> this step outputs "JAVA_HOME: command not found"

Why do I get this? Pls help me.

A: Check your JDK install
First, ensure your desired JDK version is indeed installed:
javac -version should output some information.
To get an overview of the different JDK versions installed on your computer, you can use sudo update-alternatives --config javac. This command should display at least the JDK version you target.
Install JDK if needed
If no Java is installed, or if you don't have the version you wish, you will have to install it.
From Ubuntu repositories (easiest, best secured and supported)
openjdk-15 is available in Ubuntu repository for Groovy. Here are the different openjdk versions available per Ubuntu version :
https://packages.ubuntu.com/search?suite=default&section=all&arch=any&keywords=openjdk-&searchon=names
Once you've made your version choice, install it with sudo apt install open-jdk-VERSION-jdk.
From third party providers (more options available but more steps required)
If you really want openjdk-15 but run in another version than Groovy, you'll have two options:

*

*take JDK 15 from Openjdk website and install it manually : https://openjdk.java.net/install/. You will have to download a tar.gz file, decompress it, and then move it into a folder that is part of your PATH. I would not recommend this option as it will require you to perform future JDK update manually.

*there is also a nice alternative that consists in using AdoptOpenJDK PPA:
https://adoptopenjdk.net/installation.html?variant=openjdk15&jvmVariant=hotspot#linux-pkg. If you go for it, you'll install JDK 15 with sudo apt install adoptopenjdk-15-hotspot. I would definitely recommend this option as it is easier to setup and you'll get updates when running sudo apt upgrade.

Once Java is installed, run sudo update-alternatives --config java and sudo update-alternatives --config javac to use this version by default, and check that javac -version now gives you the right version.
Define JAVA_HOME
In the /etc/environment file, you can follow this syntax (adapting it to your effective path):
JAVA_HOME=/usr/lib/jvm/adoptopenjdk-15-hotspot-amd64/bin/java
Notice that there's no space around "=" sign and the path can be unquoted.
Once done, use source /etc/environment or reboot your computer to take the change into account.
Now, if you enter echo $JAVA_HOME, it should display the path to your Java executable.


Q: How to find the list of indices of NaN values of a given column of a dataframe in python Say I have the following dataframe and I want to get the indices of NaN values in Column 'b'.
Input:
df = pd.DataFrame(np.array([[1, 2, 3 ], [ np.nan, 5, 6], [7, np.nan, 9], [7, np.nan, 9]]),
                   columns=['a', 'b', 'c'])

Output:
[2,3]

How can I do this? I would like to get the indices as a list.


Q: Show ActionBar with Centred Logo In ListActivity Trying to show an ActionBar with the app logo to the left, title of the screen centred and  menu icons to the right. The class below extends a ListActivity how can i go about doing this:
The method i have created was centerlogo(); See code extract below:
public class NewsActivity extends ListActivity {

    @Override
    protected void onCreate(Bundle savedInstanceState) {
        // TODO Auto-generated method stub
        super.onCreate(savedInstanceState);
        ListView list;
        String[] itemname = { "Bafana crash out of Afcon",
                "Mali and Guinea face ultimate lottery",
                "Orlando Pirates eye cup glory",
                "Ivory Coast advance to Afcon quarters",
                "Algeria qualify for Afcon quarter-finals",
                "Reflect on Afcon lessons - Mbalula",
                "Tovey preaches patience with Bafana",
                "SuperSport's Brockie harbours lofty goals" };
        Integer[] imgid = { R.drawable.bafana, R.drawable.mailguinea,
                R.drawable.orlando, R.drawable.ivorycoast, R.drawable.algeria,
                R.drawable.reflection, R.drawable.tovey, R.drawable.supersport, };

        CustomListAdapter adapter = new CustomListAdapter(this, itemname, imgid);
        setListAdapter(adapter);

         centreLogo();
    }

    private void centreLogo() {
        // TODO Auto-generated method stub
                 Drawable d = getResources().getDrawable(R.drawable.banner);
     android.app.ActionBar bar = getActionBar();
     bar.setBackgroundDrawable(d);
     bar.setDisplayShowTitleEnabled(false);
     bar.setDisplayShowCustomEnabled(true);
     // getSupportActionBar().setDisplayHomeAsUpEnabled(true);
     bar.setCustomView(R.layout.news_view);
     bar.setDisplayShowHomeEnabled(true);
     bar.setIcon(R.drawable.icon);
    }

    @Override
    public boolean onCreateOptionsMenu(Menu menu) {
        // Inflate the menu items for use in the action bar
        MenuInflater inflater = getMenuInflater();
        inflater.inflate(R.menu.main, menu);
        return super.onCreateOptionsMenu(menu);
    }

    public void readMore(View view) {
        Intent read = new Intent(NewsActivity.this, ReadMoreActivity.class);
        startActivity(read);
    }

}

I get the following error:
01-29 13:45:40.093: E/AndroidRuntime(15402): FATAL EXCEPTION: main
01-29 13:45:40.093: E/AndroidRuntime(15402): java.lang.RuntimeException: Unable to start activity ComponentInfo{platinum.platinumstars/platinumnews.NewsActivity}: java.lang.NullPointerException
01-29 13:45:40.093: E/AndroidRuntime(15402):    at android.app.ActivityThread.performLaunchActivity(ActivityThread.java:2245)
01-29 13:45:40.093: E/AndroidRuntime(15402):    at android.app.ActivityThread.handleLaunchActivity(ActivityThread.java:2295)
01-29 13:45:40.093: E/AndroidRuntime(15402):    at android.app.ActivityThread.access$700(ActivityThread.java:150)
01-29 13:45:40.093: E/AndroidRuntime(15402):    at android.app.ActivityThread$H.handleMessage(ActivityThread.java:1280)
01-29 13:45:40.093: E/AndroidRuntime(15402):    at android.os.Handler.dispatchMessage(Handler.java:99)
01-29 13:45:40.093: E/AndroidRuntime(15402):    at android.os.Looper.loop(Looper.java:176)
01-29 13:45:40.093: E/AndroidRuntime(15402):    at android.app.ActivityThread.main(ActivityThread.java:5279)
01-29 13:45:40.093: E/AndroidRuntime(15402):    at java.lang.reflect.Method.invokeNative(Native Method)
01-29 13:45:40.093: E/AndroidRuntime(15402):    at java.lang.reflect.Method.invoke(Method.java:511)

A: I decided to go with  GareginSargsyan suggestion. The main problem was that i was trying to inflate the default android list, so i instantiated a new ListView ,
set the ContentView of the list view and the rest is history.
public class NewsActivity extends ActionBarActivity {
        ListView list;
        @Override
        protected void onCreate(Bundle savedInstanceState) {
            // TODO Auto-generated method stub
            super.onCreate(savedInstanceState);
            setContentView(R.layout.activity_platinum_news_list);
            String[] itemname = { "Bafana crash out of Afcon",
                    "Mali and Guinea face ultimate lottery",
                    "Orlando Pirates eye cup glory",
                    "Ivory Coast advance to Afcon quarters",
                    "Algeria qualify for Afcon quarter-finals",
                    "Reflect on Afcon lessons - Mbalula",
                    "Tovey preaches patience with Bafana",
                    "SuperSport's Brockie harbours lofty goals" };
            Integer[] imgid = { R.drawable.bafana, R.drawable.mailguinea,
                    R.drawable.orlando, R.drawable.ivorycoast, R.drawable.algeria,
                    R.drawable.reflection, R.drawable.tovey, R.drawable.supersport, };

    //      CustomListAdapter adapter = new CustomListAdapter(this, itemname, imgid);
    //      setListAdapter(adapter);
            CustomListAdapter test = new CustomListAdapter(this, itemname, imgid);
            list = (ListView) findViewById(R.id.list);
            list.setAdapter(test);

             centreLogo();
        }

        private void centreLogo() {
            // TODO Auto-generated method stub
            Drawable d = getResources().getDrawable(R.drawable.banner);
            getSupportActionBar().setBackgroundDrawable(d);
            getSupportActionBar().setDisplayShowTitleEnabled(false);
            getSupportActionBar().setDisplayShowCustomEnabled(true);
            // getSupportActionBar().setDisplayHomeAsUpEnabled(true);
            getSupportActionBar().setCustomView(R.layout.news_view);
            getSupportActionBar().setDisplayShowHomeEnabled(true);
            getSupportActionBar().setIcon(R.drawable.icon);
        }

        @Override
        public boolean onCreateOptionsMenu(Menu menu) {
            // Inflate the menu items for use in the action bar

             getMenuInflater().inflate(R.menu.newsmenu, menu);
                return true;
        }

        public void readMore(View view) {
            Intent read = new Intent(NewsActivity.this, ReadMoreActivity.class);
            startActivity(read);
        }

    }

A: Most likely, getActionBar() is causing the exception. Try using getSupportActionBar() instead.


Q: Does "toric" conflict with "Calabi-Yau" in the projective case? Let $X$ be a Calabi-Yau complex algebraic variety. If it is projective, we can talk about its geometric genus $p_g=h^{\dim X, 0}$, and the Calabi-Yau condition says that $p_g=1$.
Now, one might be interested in the so-called "local" Calabi-Yau varieties, which are not projective. Some of them are of greatest interest because they are toric. So my question is:

Q. Is it impossible for a smooth toric Calabi-Yau variety to be
  projective?

Put in another way: is the genus of a smooth projective toric variety always different from $1$?
Thank you for your time and your help!

A: Yes, it is impossible. Toric varities are rational; a smooth projective rational variety has $p_g=0.$


Q: Prove device enrollment with MDM from an iOS App We want to make an iOS enterprise app that communicates with a server A - we also have our own MDM server as a separate solution which could communicate with the A server if needed. Q: How can the app securely prove to its server, with every request, that it is coming from a device that is enrolled with the MDM?
I thought there would be some UUID that the app could send together with a signed challenge to A. A would then comunicate with MDM server to validate. But seems impossible.

A: The MDM is supposed to handle this. You should not be required to check every request in the API to make sure it is secure. Airwatch, for instance, makes all of your applications downloadable only through their catalog and the agent or vpn system connects when the application is opened. If the user were to attempt to circumvent these limits it unenrolls their device and disallows access until a new enrollment code is issued by your tech department.


Q: 'the love of nature' (1. nature can love or 2. can be loved?)
'the love of nature'

*

*nature can love or 2. can be loved? or 3. both?

The phrase above is confusing.
the love of your country : country is loved here (passive)
the love of God : God is not loved here (God is the subject who gives love)

A: In the phrase the love of nature, it is nature that is loved.
I can't think of a context where nature itself can love.
As to the love of God, God can be either the subject or object of the verb love.


Q: Can I split compressed sql file using split linux command? If not, then any other method to do? I have a 30 GB compressed sql file (with extension .sql.bz2) and if I unzip it will become 300 GB. However due to disk space issue, I can't do the same.
Could I split the compressed sql file something like using split linux command?
I tried but with no success. Any other approach?
Thanks!

A: You might take a look at this question: split-files-using-tar-gz-zip-or-bzip2
I assume the reason you want to split it is to move it? And that you know you probably wont be able to import a small slice of the file into a database?


Q: how to switch image on slidepanellayout in android how to use image to show more & less in slidepanellayout in android.i am using demo application from this link,check this layout.xml
https://github.com/umano/AndroidSlidingUpPanel/blob/master/demo/res/layout/activity_demo.xml
if data hidden it has to show down icon & and when it expanded it has to show up icon


Q: How to write a base class for DRY in this situation without DI in Kotlin? I got 2 cases for a class, one is like this:
class User {
    private val name:Name = NameGenerator()

    fun sayName() {
        println(this.name.fakeName)
    }
}

The other one is:
class User(suggestion:String) {
    private val name:Name = NameGenerator(suggestion)

    fun sayName() {
        println(this.name.fakeName)
    }
}

Now you see the differences, it's all about that name, it has 2 different ways to initialize.
How could I write a base class to DRY in this case?
I end up with something like this:
abstract class BaseUser {
    protected val name:Name = MockName()

    fun sayName() {
        println(this.name.fakeName)
    }
}

Then I can use it like:
class UserCaseOne():BaseUser() {

}

class UserCaseTwo(suggestion:String):BaseUser() {
    init {
        this.name = NameGenerator(suggestion)
    }
}

This is pretty lame considering that I have to use a mock object to initialize.
Are there better ways to do this? Without injecting the implementation? I don't want to force the UserCaseTwo to have a redundant constructor.

A: If your goal is essentially two combine your first two User classes into a single class, you could do this:
class User(suggestion: String? = null) {
    private val name: NameGenerator = suggestion?.let { NameGenerator(it) } ?: NameGenerator()

    fun sayName() {
        println(this.name.fakeName)
    }
}

A: Would it be acceptable to make the name provisioning part of the constructor signature by taking a function as a parameter? The following approach enables the desired abstraction imho:
class User(private val nameProvider: () -> Name) {
    private val name: Name by lazy(nameProvider)

    fun sayName() {
        println(this.name.fakeName)
    }
}

You can create Users with any nameProvider such as:
User { MockName() }
User { NameGenerator("blah") }


Q: How to force postfix to use ip that is configured for domain? I want to confirm to SPF and DKIM, this requires me to send email using the IP written in the DNS record of the domain
I have two domains example1.com and example2.com with two IPs 100.0.0.1 and 100.0.0.2 respectively.
How can I configure postfix to always use IP 100.0.0.1 when the send from address is xx@example1.com and the same to be true for the other domain.
When connecting to the SMTP transport I am using localhost, I know I can configure two postfix instances for each IP and then just connect to the right IP when sending depending on the domain, I would like to see if this can be avoided.
How can this be done?

A: May take some fiddling, but i think you can achieve this in the following way:

*

*configure your original smtpd listener in master.cf to route mail where sender is from each respective domain to two new, local smtpd listeners

*setup 2 additional smtpd listeners in master.cf that have their own main.cf files (eg. example1.main.cf and example2.main.cf) :http://www.postfix.org/master.5.html (in said master.cf file, you can override various settings for main.cf via the -o name=value mechanism)

*configure the new main.cf files with appropriate outbound interface configurations and other related main.cf configs

A: You can specify sender as user@example1.com and user@example2.com to send mails from an Ip/Host by using sender dependent sasl authentication. Follow these links. http://www.postfix.org/SASL_README.html#client_sasl_sender And in other terms. http://www.cyberciti.biz/faq/postfix-multiple-isp-accounts-smarthost-smtp-client/


Q: Class library project build error, broken references The class library project in Visual Studio is throwing an error when I try building it. The error says:

"Your project is not referencing the ".NETFramework,Version=v4.5.2" framework. Add a reference to ".NETFramework,Version=v4.5.2" in the "frameworks" section of your project.json, and then re-run NuGet restore."

This project is under source control and builds perfectly on other machines with the same Visual Studio version installed. The projects's target network is 4.5.2 as specified in project file.

project.json file looks like this:
{
  "version": "1.0.0-*",
  "description": "Test Class Library",
  "authors": [ "author" ],
  "tags": [ "" ],
  "projectUrl": "",
  "licenseUrl": "",

  "dependencies": {
    "System.Collections": "4.0.10-beta-23019",
    "System.Linq": "4.0.0-beta-23019",
    "System.Threading": "4.0.10-beta-23019",
    "System.Runtime": "4.0.10-beta-23019",
    "Microsoft.CSharp": "4.0.0-beta-23019"
  },

  "frameworks": {
    "dotnet": { }
  }
}

I noticed when I build the project, the file project.lock.json gets generated in the project folder, and in it .NETPlatform verision is set to be ".NETPlatform,Version=v5.0". Not sure if this is what causing this problem. It if does, why would project.lock.json set the version to 5.0?
Can anyone suggest a solution to this problem? So far, I am unable to build this project on my machine.

A: Hit this issue with VS2017, what it happened is we converted a dotnet core project back to use .Net frameworks. The old project.assets.json was left in obj folder. And it caused this error. When the file or the obj folder is removed, it builds fine.

A: I resolved this by not using NuGet for this project anymore.

*

*Removed all NuGet packages from the project.

*

*Right-click the project in Visual Studio

*Manage NuGet Packages...

*Uninstall packages one by one until there are none

*Deleted project.json file in the root directory of the project.

*Restarted the Visual Studio. This step might not be necessary, but sometimes when you remove project.json file, you get the NuGet related error when building the project. If this happens, restart the Visual Studio.


Q: Add link to this JavaScript code I have the following javascript code for a rotating image. Those images are in a separate folder from the javascript. I want to link the rotation itself to another page. All images will go to the same link. The current code works great but I just don't know where I add the a href code or its syntax.
// JavaScript Document
//
// Type the number of images you are rotating.
NumberOfImagesToRotate = 3;
FirstPart = '';

function printImage() {
var r = Math.ceil(Math.random() * NumberOfImagesToRotate);
document.write(FirstPart + r + LastPart);
}

A: Try this format

It is up to you if you want to define the target attribute in  tag.

A: // JavaScript Document
//
// Type the number of images you are rotating.
var numberOfImagesToRotate = 3;
// Edit the destination URl here
var linkUrl = 'example.html';
// HTML-partials
var imgFirstPart = '';
var anchorFirstPart = '';
var anchorLastPart = '';

function printImage() {
  var r = Math.ceil(Math.random() * numberOfImagesToRotate);
  document.write(anchorFirstPart + linkUrl + anchorSecondPart + imgFirstPart + r + imgLastPart + anchorLastPart);
}


Q: A question on text classification with more than one level of category I am trying to produce a series of product classifiers based on the text description that each product has. The data frame I have is similar to the following but is more complicated. Python and the sklearn library are used.
data = {'description':['orange', 'apple', 'bean', 'carrot','pork','fish','beef'],
        'level1':['plant', 'plant', 'plant', 'plant','animal','animal','animal'],
         'level2:['fruit','fruit','vegatable','vegatable','livestock', 'seafood','livestock'}

# Create DataFrame
df = pd.DataFrame(data)

"Description" is the textual data. Now it is only a word. But the real one is a longer sentence.
"Level1" is the top category.
"Level2" is a sub-category.
I know how to train a classification model to classify the products into Level 1 categories by using the sklearn library.
Below is what I did:
import pandas as pd
import numpy as np
import nltk
from sklearn.model_selection import train_test_split
from sklearn.feature_extraction.text import TfidfVectorizer
from sklearn.feature_extraction.text import CountVectorizer
from sklearn.naive_bayes import MultinomialNB
from sklearn.metrics import classification_report, f1_score, accuracy_score, confusion_matrix
from sklearn.metrics import roc_curve, auc, roc_auc_score
import pickle

# Train/Test split
X_train, X_test, y_train, y_test = train_test_split(df['description'],
                                                 df[['Level1','Level2']], test_size = 0.4, shuffle=True)

#use the TF-IDF Vectorizer
tfidf_vectorizer = TfidfVectorizer(use_idf=True)

#transforming the training data into tf-idf matrix
X_train_vectors_tfidf = tfidf_vectorizer.fit_transform(X_train)

#transforming testing data into tf-idf matrix
X_test_vectors_tfidf = tfidf_vectorizer.transform(X_test)

#Create and save model for level 1
naive_bayes_classifier = MultinomialNB()
model_level1 = naive_bayes_classifier.fit(X_train_vectors_tfidf, y_train['Level1'])
with open('model_level_1.pkl','wb') as f:
    pickle.dump(model_level1, f)

What I don't know how to do is to build a classification model for each Level 1 category that can predict the products' Level 2 category. For example, based on the above dataset, there should be one classification model for 'plant' (to predict fruit or vegetable) and another model for 'animal' (to predict seafood or livestock). Do you have any ideas to do it and save the models by using loops?

A: Assuming you will be able to get all the columns of the dataset then it would be a mix of features with Levels being the class labels. Formulating on the same lines:
cols = ["abc", "Level1", "Level2", "Level3"]

From this now let's take only levels because that is what we are interested in.
level_cols = [val for val in levels if "Lev" in val]

The above just check for the presence of "Lev" starts with these three characters.
Now, with level cols in place. I think you could do the following as a starting point:
1. Iterate only the level cols.
2. Take only the numbers 1,2,3,4....n
3. If step-2 is divisible by 2 then I do the prediction using the saved level model. Ideally, all the even ones.
4. Else train on other levels.

for level in level_cols:
    if int(level[-1]) % 2 == 0:
      #  open the saved model at int(level[-1]) - 1
      #  Perform my prediction
    else:
        level_idx = int(level[-1])
        model = naive_bayes_classifier.fit(x_train, y_train[level])
        mf = open("model-x-"+level_idx, "wb")
        pickle.dump(model, mf)


Q: Check if the entire substring is contained in a string Taking for example two var: $a="bar/var1" and $b="var" I want to check if the content of $b is in $a, but not just each character of $b, its exact content.
I tried:

*

*if [[ $a =~ .*$b*. ]]

*if [[ "$a" =~ .*"$b"*. ]]

*if [[ "$a" = *"$b"* ]]

*if [[ "$a" = *$b* ]]

*if [[ "$a" == *$b* ]]
but the problem is always the same
if $b is "rav" or "var" the result is the same,
but I want true only if it's "var".

A: #!/bin/bash

a="bar/var1"
b="var"

if [[ "$a" == *"$b"* ]]; then
  echo "Got it"
fi

b="rav"

if [[ "$a" == *"$b"* ]]; then
  echo "Got it"
fi

You have this in your list of attempts:
if [[ "$a" = *"$b"* ]]

You were on the right track, but you need two = symbols, not one.


Q: Witnesses in the Henkin construction and the canonical model See the images below, from Model theory: An Introduction, by David Marker: In the proof of Lemma 2.1.7 the canonical model is defined using equivalence classes of constant symbols of $\mathcal{L}$, where the relation $\sim$ is defined by $c\sim d$ iff $T\vDash (c=d)$.
I am trying to understand why on page 36, the witness property is actually needed to demonstrate that $f^{\mathcal{M}}$ is well defined (and similarly a paragraph below regarding terms).
Focusing on functions, I wonder why he does not define $f^{\mathcal{M}}(c_{1}^{*},\ldots,c_{n}^{*})=(f(c_{1},\ldots,c_{n}))^{*}$, as it is clear this would be well definied because if $(c_{1}=d_{1}),\ldots,(c_{n}=d_{n})\in T$ then $(f(c_{1},\ldots,c_{n})=f(d_{1},\ldots,d_{n}))\in T$. (A similar argument can be made for the paragraph below regarding terms)
I have two questions:

*

*Am I missing something? I.e. is the witness property really needed?

*If instead of using the constants symbols of $\mathcal{L}$ to define the canonical model we use the variable-free terms of $\mathcal{L}$ (the relation $\sim$ being defined the same as above, but for variable-free terms), is there any advantage? In An Introduction to mathematical Logic, by R. Hodel, the canonical model is defined this way.

A: For question 1: $f(c_1,\dots,c_n)$ is not a constant symbol, so $(f(c_1,\dots,c_n))^*$ is meaningless.
As you suggest in question 2, you could instead define an equivalence relation on the set of all terms with no free variables and define the elements of the model to be equivalence classes of terms. Then you would not need to use the witnessing property to define the interpretations of the function symbols: $f(t_1^*,\dots,t_n^*) = (f(t_1,\dots,t_n))^*$ works just fine.
Is there any other advantage? Not really: the point is that the witnessing property ensures that every equivalence class of terms contains a constant symbol. Indeed, the model built on constants is isomorphic to the model built on terms. It's really a matter of taste whether you find it conceptually simpler to work with constants or arbitrary terms.

A: There are many ways to perform this construction. As the author states :

The main idea of the construction is that we will add enough constants to the
language so that every element of our model will be named by a constant symbol

This is why, for every $c_{1},\ldots,c_{n}$, the author needs to introduce a new constant $d$ satisfying $T \vdash f(c_{1},\ldots,c_{n}) = d$, for otherwise he'd miss that constant later on.


Q: Respect negative conditions for advanced collection associations I was trying to use this functionality introduced in #645 with conditional 2nd degree has_many ... through relationships with little success.
In my case:

*

*a Course has_many :user_assigned_content_skills, -> { where(source: 'user') }, class_name: "ContentSkill"

*and a ContentSkill belongs_to :skill and belongs_to :course
Then Course.ransack({user_assigned_content_skills_skill_name_not_cont: 'ruby'}).result.to_sql returns the following:
"SELECT courses.* FROM courses LEFT OUTER JOIN content_skills ON content_skills.course_id = courses.id AND content_skills.source = 'user' LEFT OUTER JOIN skills ON skills.id = content_skills.skill_id WHERE (skills.name NOT ILIKE '%ruby%')"
This means false positives again if a course has multiple content_skills. Any ideas how to retrieve all courses not being associated with a given skill name?
Many thanks for any insights!

A: You can get ids of courses associated with a given skill name, and then get a list of courses with ids that don't match the previous found. You can even make it as one composite SQL query.
Course.where.not(id: Course.ransack({user_assigned_content_skills_skill_name_cont: 'ruby'}).result)

This will generate an SQL like this:
SELECT courses.*
FROM courses
WHERE courses.id NOT IN (
  SELECT courses.id FROM courses
  LEFT OUTER JOIN content_skills ON content_skills.course_id = courses.id AND content_skills.source = 'user'
  LEFT OUTER JOIN skills ON skills.id = content_skills.skill_id
  WHERE (skills.name ILIKE '%ruby%')
)


Q: Error: Call to a possibly undefined method I have the simplest code ever. Main class:
package
{
import field.Field;
import flash.display.Sprite;
import flash.events.Event;

public class Main extends Sprite
{

    public function Main():void
    {
        if (stage) init();
        else addEventListener(Event.ADDED_TO_STAGE, init);
    }

    private function init(e:Event = null):void
    {
        removeEventListener(Event.ADDED_TO_STAGE, init);

        var field:Field = new Field();
        addChild(field);
        field.test();
    }
}
}

and a Field class:
package field
{
import flash.display.Sprite;

public class Field extends Sprite
{

    public function Field()
    {
        super();

    }

    public function test():void
    {

    }

}
}

test method is presented.
But when I try to compile I get this:
Main.as(26): col: 10 Error: Call to a possibly undefined method test.
field.test();
How could this be happening?

A: field is your package, that's why you can not do field.test(). So you have to choose another name of your Field instance. You can do like this :
var _field:Field = new Field();
addChild(_field);
_field.test();

Hope that can help.


Q: Reading specific number of bytes from a buffered reader in golang I am aware of the specific function in golang from the bufio package.
func (b *Reader) Peek(n int) ([]byte, error)

Peek returns the next n bytes without advancing the reader. The bytes
  stop being valid at the next read call. If Peek returns fewer than n
  bytes, it also returns an error explaining why the read is short. The
  error is ErrBufferFull if n is larger than b's buffer size.

I need to be able to read a specific number of bytes from a Reader that will advance the reader.  Basically, identical to the function above, but it advances the reader.  Does anybody know how to accomplish this?

A: TLDR:
my42bytes, err := ioutil.ReadAll(io.LimitReader(myReader, 42))

Full answer:
@monicuta mentioned io.ReadFull which works great. Here I provide another method. It works by chaining ioutil.ReadAll and io.LimitReader together. Let's read the doc first:

$ go doc ioutil.ReadAll
func ReadAll(r io.Reader) ([]byte, error)
     ReadAll reads from r until an error or EOF and returns the data it read. A
     successful call returns err == nil, not err == EOF. Because ReadAll is
     defined to read from src until EOF, it does not treat an EOF from Read as an
     error to be reported.

$ go doc io.LimitReader
func LimitReader(r Reader, n int64) Reader
     LimitReader returns a Reader that reads from r but stops with EOF after n
     bytes. The underlying implementation is a *LimitedReader.

So if you want to get 42 bytes from myReader, you do this
import (
        "io"
        "io/ioutil"
)

func main() {
        // myReader := ...
        my42bytes, err := ioutil.ReadAll(io.LimitReader(myReader, 42))
        if err != nil {
                panic(err)
        }
        //...
}

Here is the equivalent code with io.ReadFull

$ go doc io.ReadFull
func ReadFull(r Reader, buf []byte) (n int, err error)
    ReadFull reads exactly len(buf) bytes from r into buf. It returns the number
    of bytes copied and an error if fewer bytes were read. The error is EOF only
    if no bytes were read. If an EOF happens after reading some but not all the
    bytes, ReadFull returns ErrUnexpectedEOF. On return, n == len(buf) if and
    only if err == nil. If r returns an error having read at least len(buf)
    bytes, the error is dropped.

import (
        "io"
)

func main() {
        // myReader := ...
        buf := make([]byte, 42)
        _, err := io.ReadFull(myReader, buf)
        if err != nil {
                panic(err)
        }
        //...
}

Compared to io.ReadFull, an advantage is that you don't need to manually make a buf, where len(buf) is the number of bytes you want to read, then pass buf as an argument when you Read
Instead you simply tell io.LimitReader you want at most 42 bytes from myReader, and call ioutil.ReadAll to read them all, returning the result as a slice of bytes. If successful, the returned slice is guaranteed to be of length 42.

A: Note that the bufio.Read method calls the underlying io.Read at most once, meaning that it can return n < len(p), without reaching EOF. If you want to read exactly len(p) bytes or fail with an error, you can use io.ReadFull like this:
n, err := io.ReadFull(reader, p)

This works even if the reader is buffered.

A: I am prefering Read() especially if you are going to read any type of files and it could be also useful in sending data in chunks, below is an example to show how it is used
fs, err := os.Open("fileName");

if err != nil{
    fmt.Println("error reading file")
    return
}

defer fs.Close()

reader := bufio.NewReader(fs)

buf := make([]byte, 1024)

for{
    v, _ := reader.Read(buf) //ReadString and ReadLine() also applicable or alternative

    if v == 0{
        return
    }
    //in case it is a string file, you could check its content here...
    fmt.Print(string(buf))
}

A: func (b *Reader) Read(p []byte) (n int, err error)

http://golang.org/pkg/bufio/#Reader.Read
The number of bytes read will be limited to len(p)

A: Pass a n-bytes sized buffer to the reader.

A: If you want to read the bytes from an io.Reader and into an io.Writer, then you can use io.CopyN

CopyN copies n bytes (or until an error) from src to dst. It returns the number of bytes copied and the earliest error encountered while copying.
On return, written == n if and only if err == nil.

written, err := io.CopyN(dst, src, n)
if err != nil {
    // We didn't read the desired number of bytes
} else {
   // We can proceed successfully
}

A: To do this you just need to create a byte slice and read the data into this slice with
n := 512
buff := make([]byte, n)
fs.Read(buff)  // fs is your reader. Can be like this fs, _ := os.Open('file')

func (b *Reader) Read(p []byte) (n int, err error)

Read reads data into p. It returns the number of bytes read into p.
  The bytes are taken from at most one Read on the underlying Reader,
  hence n may be less than len(p)


Q: Determining bar width, with a 3d matrix I have my data as follows:
var data = [[-5,7,10],[10,15,25],[-18,-14,-6]];

var margin = {top: 0, right: 30, bottom: 80, left: 30},
        width = 180 - margin.left - margin.right,
        height = 295 - margin.top - margin.bottom;

var x0 = Math.max(-d3.min(data[0]), d3.max(data[2]));
var x = d3.scale.linear()
        .domain([-x0, x0])
        .range([0, width]);

var y = d3.scale.ordinal()
.domain(d3.range(data.length))
.rangeRoundBands([0, height], .2);

var svg = d3.select("body").append("svg")
    .attr("width", width + margin.left + margin.right)
    .attr("height", height + margin.top + margin.bottom)
  .append("g")
.attr("transform", "translate(" + margin.left + "," + margin.top + ")");

svg.selectAll(".bar")
        .data(data)
      .enter().append("rect")
        .style("fill", "steelblue")
        .attr("x", function(d, i) { return x(Math.min(0, d[0])); })
        .attr("y", function(d, i) { return y(i); })
        .attr("width", function(d, i) { return Math.abs(x(d[2]) - x(d[0])); })
        .attr("height", y.rangeBand())
        .append("rect");

//y axis
svg.append("g")
.attr("class", "y axis")
.append("line")
.attr("x1", x(0))
.attr("x2", x(0))
.attr("y1", 0)
.attr("y2", height+10);

What I want to do is create a bar chart where data[0] is the starting point, data[1] has a vertical line bisecting the bar and data[2] is the max value of the bar. So far, I think I'm covering the first two use cases correctly, but the third one fails. Any ideas?
http://jsfiddle.net/NPqEm/