text:
Q: Which collection type is best to create poco classes in entity framework? We have following Two tables, which collection type is the  best for this situation , and how do we choose in other scenarios.
public class Employee{
public int Id {get;Set;}
public string Name{get;set;}
}
public class Comapany{
public int Id {get;set;}
public string Name {get;set;}
public virtual ICollection<Employee>employees{get;set;} or
public virtual list<Employee>employees{get;set;}
}

A: The general recommendation is to use the least specific type/interface, i.e. ICollection<T>, unless you want to enforce specific requirements.
The reason is that you have the freedom to use specific types appropriate to any situation. Let me give an example.
Suppose you have a method by which Employees are added to a new Company but you want to guarantee that these employees will be unique by name. If Company.Employees is an ICollection<T> you can now use a HashSet<Employee> that you initialize by the constructor taking an IEqualityComparer<Employee> comparing Employees by name, and assign it to Company.Employees.
For other sceneario's you may want to use List<Employee> because AddRange comes in handy.
The Visual Studio tools for reverse-engineering code-first from database create POCO classes that initialize their collections by HashSets, because they provide high-performance set operations.

A: In this situation it doesn't matter, EF will use List<T> in place on ICollection<T> by default. Collection type doesn't affect LINQ queries too. In other situations, you should choose what collection is more suited for your application logic. Common choices are List<T> and HashSet<T>.


text:
Q: Calculate the limit: I need to calculate:
$$\lim_{x\rightarrow \frac{\pi }{4}}\frac{\sin2x-\cos^{2}2x-1}{\cos^{2}2x+2\cos^{2}x-1}$$
I replaced $2\cos^{2}x-1=\cos2x$ and $\cos^{2}2x=1-\sin^{2}2x$, so this limit equals $\lim_{x\rightarrow \frac{\pi }{4}}(tg2x\frac{\sin2x+1}{\cos2x+1}-\frac{2}{\cos2x(\cos2x+1)})$ but we still have $\infty-\infty$. Any ideas?

A: Hint Replace $y=2x-{\pi\over 2}$, so $y\to0$ as $x\to{\pi\over 4}$

A: Since user64494 gave you the answer and the different steps, I shall just tell that the expression you work can be simplified to
(Sin[x] + Sec[x]) (Tan[x]-1) / (Sin[x] + Cos[x])
which does not make any problem.

redpajama_set_name: RedPajamaStackExchange


text:
Q: is it possible to set alarm for 7 days exactly at same time? I working on alarm application. I tried to implement alarm notification and got notifications for every day but I need to set alarm for 7 days, after that it has to cancel. I cancelled it in broadcast receiver whenever seven days out, but still I'm getting notifications after seven days also.
public class MyTest extends AppCompatActivity {

    AlarmManager alarmManager;
    SharedPreferences preferences;

    SharedPreferences.Editor editor;
    PendingIntent pendingIntent;
    int RequestCode =777;

    protected void onCreate(Bundle savedInstanceState) {
        super.onCreate(savedInstanceState);
        setContentView(R.layout.activity_my_test);
        Toolbar toolbar = (Toolbar) findViewById(R.id.toolbar);
        setSupportActionBar(toolbar);
        AlarmReciever alarm = new AlarmReciever();
        //  alarm.setAlarm(this);
        int alarmId = 0;
        alarmManager = (AlarmManager) getSystemService(ALARM_SERVICE);

        Intent alarmIntent = new Intent(MyTest.this, AlarmReciever.class); // AlarmReceiver1 = broadcast receiver
        alarmIntent.putExtra("alarmId", alarmId);
        pendingIntent = PendingIntent.getBroadcast(MyTest.this, RequestCode, alarmIntent, PendingIntent.FLAG_UPDATE_CURRENT);
        // alarmIntent.setData((Uri.parse("custom://" + System.currentTimeMillis())));

        Calendar alarmStartTime = Calendar.getInstance();
        Calendar now = Calendar.getInstance();
        alarmStartTime.set(Calendar.HOUR_OF_DAY, 00);
        alarmStartTime.set(Calendar.MINUTE, 00);
        alarmStartTime.set(Calendar.SECOND, 0);

        Log.d("Alarm", now.toString());
        /// int count= 0;
        // last i added for comparision
        if (now.after(alarmStartTime)) {
            //second
            Log.d("Alarm", "Added a day");
            alarmStartTime.add(Calendar.DATE, 1);
            // count++;

        }
        /*  System.out.println(count);
        if(count==7){
            alarmManager.cancel(pendingIntent);

        }*/

        // for(int i=0;i<7;i ++) {
            //  alarmManager.set(AlarmManager.RTC_WAKEUP, alarmStartTime.getTimeInMillis() + 1000 * 60 * 60 * 24 /*AlarmManager.INTERVAL_DAY*/, pendingIntent);
             alarmManager.setInexactRepeating(AlarmManager.RTC_WAKEUP, alarmStartTime.getTimeInMillis() , AlarmManager.INTERVAL_DAY, pendingIntent);

            Log.d("Alarm", "Alarms set for everyday 8 am.");

        //  }
    }
}

Broadcast Receiver
public class AlarmReciever extends BroadcastReceiver {
    SharedPreferences preferences;
    SharedPreferences.Editor editor;
    int count=0;
    AlarmManager alarmManager;
    PendingIntent pendingIntent;
    int RequestCode =777;
    @Override
    public void onReceive(Context context, Intent intent) {
          // String rec = intent.getDataString();
       // Log.d("Alarm",rec);

        Intent service1 = new Intent(context, NotificationService.class);
       // service1.setData((Uri.parse("custom://" + System.currentTimeMillis())));
        context.startService(service1);
           count++;
        preferences = context.getSharedPreferences("MyCount", Context.MODE_PRIVATE);
        editor=preferences.edit();
        editor.putInt("COUNT", count);
        editor.commit();
          incrementSum(context);

    }

 public void  incrementSum(Context context){

    int cou = preferences.getInt("COUNT",0);
    //  System.out.println(cou);
    // int c=0;
    //  int cou = preferences.getInt("COUNT",0);
    int co = preferences.getInt("C",0);
    if(cou==1){
        cou=co+1;
        editor = preferences.edit();
        editor.putInt("C",cou);
        editor.commit();
    }

    int c = preferences.getInt("C",0);
    // System.out.println("count"+cou);
    // int count = preferences.getInt("COUNT",0);
    // System.out.println("last"+count);
    System.out.println("sum" + c);
    if(c>=7) {

        Intent alarmIntent = new Intent(context, AlarmReciever.class);
        pendingIntent = PendingIntent.getBroadcast(context, RequestCode, alarmIntent,  PendingIntent.FLAG_UPDATE_CURRENT);
        alarmManager = (AlarmManager) context.getSystemService(Context.ALARM_SERVICE);
        if (alarmManager!= null) {
            alarmManager.cancel(pendingIntent);
        }
        // alarmManager.cancel(pendingIntent);
    }
    // AlarmManager   alarmManager = (AlarmManager) context.getSystemService(Context.ALARM_SERVICE);
}

Notification service
public class NotificationService extends IntentService {

    private NotificationManager notificationManager;
    private PendingIntent pendingIntent;
    private static int NOTIFICATION_ID = 1;
    Notification notification;

    public NotificationService() {
        super("testing.amaze.com.mytest");
    }

    @Override
    protected void onHandleIntent(Intent intent) {
        Context context = this.getApplicationContext();
        notificationManager = (NotificationManager)context.getSystemService(Context.NOTIFICATION_SERVICE);
        Intent mIntent = new Intent(this, ActivityTwo.class);
        Bundle bundle = new Bundle();
        bundle.putString("test", "test");
        mIntent.putExtras(bundle);
        pendingIntent = PendingIntent.getActivity(context, 0, mIntent, PendingIntent.FLAG_UPDATE_CURRENT);

        Resources res = this.getResources();
        NotificationCompat.Builder builder = new NotificationCompat.Builder(this);
        //   Uri soundUri = RingtoneManager.getDefaultUri(RingtoneManager.TYPE_ALARM);
        notification = new NotificationCompat.Builder(this)
                .setContentIntent(pendingIntent)
                //.setSmallIcon(R.drawable.ic_launcher)
                //.setLargeIcon(BitmapFactory.decodeResource(res, R.drawable.ic_launcher))
                .setTicker("ticker value")
                .setAutoCancel(true)
                .setPriority(8)
              //  .setSound(soundUri)
                .setContentTitle("Notif title")
                .setContentText("Text").build();
        notification.flags |= Notification.FLAG_AUTO_CANCEL | Notification.FLAG_SHOW_LIGHTS;
        notification.defaults |= Notification.DEFAULT_SOUND | Notification.DEFAULT_VIBRATE;
        notification.ledARGB = 0xFFFFA500;
        notification.ledOnMS = 800;
        notification.ledOffMS = 1000;
        notificationManager = (NotificationManager)getSystemService(NOTIFICATION_SERVICE);
        notificationManager.notify(NOTIFICATION_ID, notification);
        Log.i("notif", "Notifications sent.");

    }

A: For set Alarm
public void setAlarm(Context context,int alarm_id) {
        int u_id = alarm_id;

        Intent intent1 = new Intent(context, AlarmBrodcastReceiver.class);
        PendingIntent pendingIntent = PendingIntent.getBroadcast(
                context, u_id, intent1, PendingIntent.FLAG_UPDATE_CURRENT);
        AlarmManager am = (AlarmManager) context
                .getSystemService(context.ALARM_SERVICE);
        am.setRepeating(AlarmManager.RTC_WAKEUP, timetoSet,
                AlarmManager.INTERVAL_DAY, pendingIntent);
    }

for Cancel Alarm
public void cancelAarm(Context context,int alarm_id) {
        int u_id = alarm_id;
        Intent intent1 = new Intent(context, AlarmBrodcastReceiver.class);
        PendingIntent pendingIntent = PendingIntent.getBroadcast(
                context, u_id, intent1, PendingIntent.FLAG_UPDATE_CURRENT);
        AlarmManager am = (AlarmManager) context
                .getSystemService(context.ALARM_SERVICE);
        am.cancel(pendingIntent);
    }

A: To cancel the alarm you previously scheduled you need to use Same PendingIntent.  to simplify this create a method to get the PendingIntent with some request code. like
private PendingIntent getPendingIntent(int requestCode) {
    Intent intent = new Intent(context,YourAlarmssReceiver.class);
    return PendingIntent.getBroadcast(context, requestCode,intent,0);
}

and use
((AlarmManager) context.getSystemService(Context.ALARM_SERVICE)).cancel(getPendingIntent(yourRequestCode));

keep your request code in share preferences to get it after 7 days.
EDIT :
in your BroadcastReciever , after starting NotificationService just call incrementSum method.
    public void  incrementSum(Context context){

      int cou = preferences.getInt("COUNT",0);
        cou++;
        editor = preferences.edit();
        editor.putInt("COUNT",cou);
        editor.commit();

    if(COUNT>=7) {

        Intent alarmIntent = new Intent(context, AlarmReciever.class);
        pendingIntent = PendingIntent.getBroadcast(context, RequestCode, alarmIntent,  PendingIntent.FLAG_UPDATE_CURRENT);
        alarmManager = (AlarmManager) context.getSystemService(Context.ALARM_SERVICE);
        if (alarmManager!= null) {
            alarmManager.cancel(pendingIntent);
        }
        // alarmManager.cancel(pendingIntent);
    }
  }


text:
Q: ChartJS: Get value from another another Chart I have two charts, First chart shows the breakup of Shirt sales.
Second is the comparison of Blue Shirt vs Blue Trouser sales.
I want to import the Blue Shirt value from the first Chart to Second chart.
Here is the Code with two charts:
var ctx = document.getElementById("myChart1").getContext('2d');
var myChart = new Chart(ctx, {
type: 'bar',
data: {
labels: ["Red", "Blue", "Yellow", "Green", "Purple", "Orange"],
datasets: [{
    label: 'Shirts',
    data: [10, 10, 15, 5, 2, 3],
    backgroundColor: [
        'rgba(255, 99, 132, 0.2)',
        'rgba(54, 162, 235, 0.2)',
        'rgba(255, 206, 86, 0.2)',
        'rgba(75, 192, 192, 0.2)',
        'rgba(153, 102, 255, 0.2)',
        'rgba(255, 159, 64, 0.2)'
    ],
    borderColor: [
        'rgba(255,99,132,1)',
        'rgba(54, 162, 235, 1)',
        'rgba(255, 206, 86, 1)',
        'rgba(75, 192, 192, 1)',
        'rgba(153, 102, 255, 1)',
        'rgba(255, 159, 64, 1)'
    ],
    borderWidth: 1
}]
},
options: {
scales: {
    yAxes: [{
        ticks: {
            beginAtZero:true
        }
    }]
},
}
});

var ctx = document.getElementById("myChart2").getContext('2d');
var myChart = new Chart(ctx, {
type: 'bar',
data: {
labels: ["Blue Shirts", "Blue Trousers"],
datasets: [{
    label: 'Sales',
    data: [10, 8],
    backgroundColor: [
        'rgba(255, 99, 132, 0.2)',
        'rgba(54, 162, 235, 0.2)',
     ],
    borderColor: [
        'rgba(255,99,132,1)',
        'rgba(54, 162, 235, 1)',
    ],
    borderWidth: 1
}]
},
options: {
scales: {
    yAxes: [{
        ticks: {
            beginAtZero:true
        }
    }]
},
}
});

Here is the JSFiddle (https://jsfiddle.net/kingBethal/L8x790fn/15/).

A: I found this thread describing getting data from click events: Click events on Pie Charts in Chart.js
I made also made a new fiddle here where it logs a chart object containing the chart data on chart click: https://jsfiddle.net/btnL9d2a/16/
 myChart1Canvas.onclick = function(evt) {
   var activePoints = myChart.getElementsAtEvent(evt);
   if (activePoints[0]) {
   var chartData = activePoints[0]['_chart'].config.data;
   // `chartData` will be an object in the format {'Labels' : Array, 'datasets' : Array}.
   console.log(chartData);
 }
};

chartData.datasets[0].data is an array of the clicked-on chart's data.


text:
Q: PPTP VPN problem in Ubuntu 22.04 I use Ubuntu 22.04 LTS and I have a problem with connecting to VPN using the PPTP.
Running tail -f /var/log/syslog | grep NetworkManager
Jul  9 14:15:33 ThinkPad NetworkManager[1093]: <info>  [1657359933.2202] vpn[0x556e82738460,b8d91891-159c-4b46-8a71-32d0ab50313f,"KerioMaker | VPK-1"]: starting pptp
Jul  9 14:15:33 ThinkPad NetworkManager[1093]: <info>  [1657359933.2239] audit: op="connection-activate" uuid="b8d91891-159c-4b46-8a71-32d0ab50313f" name="KerioMaker | VPK-1" pid=2162 uid=1000 result="success"
Jul  9 14:15:33 ThinkPad NetworkManager[14951]: Plugin /usr/lib/pppd/2.4.9/nm-pptp-pppd-plugin.so loaded.
Jul  9 14:15:33 ThinkPad NetworkManager[14951]: Using interface ppp0
Jul  9 14:15:33 ThinkPad NetworkManager[14951]: Connect: ppp0 <--> /dev/pts/1
Jul  9 14:15:33 ThinkPad NetworkManager[1093]: <info>  [1657359933.5647] manager: (ppp0): new Ppp device (/org/freedesktop/NetworkManager/Devices/12)
Jul  9 14:16:04 ThinkPad NetworkManager[14951]: LCP: timeout sending Config-Requests
Jul  9 14:16:04 ThinkPad NetworkManager[14951]: Connection terminated.
Jul  9 14:16:04 ThinkPad NetworkManager[14951]: Terminating on signal 15
Jul  9 14:16:04 ThinkPad NetworkManager[14951]: Child process /sbin/pptp 49.12.218.89 --nolaunchpppd --loglevel 0 --logstring nm-pptp-service-14945 (pid 14954) terminated with signal 15
Jul  9 14:16:04 ThinkPad NetworkManager[14951]: Modem hangup

Any help would be highly appreciated.


text:
Q: How should I send information from a database to my App? Android Studio Basically, I am creating a very simple app, that will pop questions in the interface whenever the app receives a question, and then store the answer in the database (Yes, no, don't know) something like this:
App layout
What I have done so far:
I created my database using MySQL.
I created a script to get the information out of the database. (php script)
I created a very simple android studio user interface.
My questions:
1)  Just from reading on android.developer I can see that they use databases managed by SQLite, is there going to be a problem with my database being MySQL? Should I really consider redoing my database on SQLite?
2)  My biggest issue and what I am most ignorant about is how to send the information to the app. I have read and gotten feedback that I might want to use MQTT Mosquito as an open source to do this. Others say doing a REST Api, but I have also read about google firebase, and I want to know what is the simplest/easiest to learn method. Are there any recommended sample/methods from google that make this easy?
-Extra note on this point: have in mind that this is a simple app and I will have users registered to my app. (What I mean to registered to my app: I will have the phone numbers of the registered recipients in my database)
Here is a sample of how the information coming from the database looks so far:
Database sample
3)  To send the data back to the database (Yes, no, don't know) I started using the following code:
NOTE: obviuslly the if statements need to be filled, but I wanted to have some feedback on if I am implementing a good method.
public void onRadioButtonClicked(View view) {
    // Is the button now checked?
    boolean checked = ((RadioButton) view).isChecked();

    // Check which radio button was clicked
    switch(view.getId()) {
        case R.id.radioButtonYes:
            if (checked)
                findViewById(R.id.buttonNEXT).setEnabled(true);
            break;
        case R.id.radioButtonNo:
            if (checked)
                findViewById(R.id.buttonNEXT).setEnabled(true);
                break;
        case R.id.radioButtonDontknow:
            if (checked)
                findViewById(R.id.buttonNEXT).setEnabled(true);
                break;
    }
}

Thank you for anyone that would take the time to give me their opinion, I appreciate it.


text:
Q: Mathematical formulation for maximum sum of edge weights For my academic research purposes, I have a situation as below.
The initial problem looks as in below figure.
I need to find one match for each of P1,P2,P3 from the right side such that the sum of edge weights is maximized. If we look at a solution for the below query, the solution can be as below.

If we consider the sum of edge weights now, it is

*

*P1 -> A1 (1.5)

*P2 -> A2 (1.9)

*P3 -> A3 (2)

And the total would be 5.4 which is the maximum. How can I represent the above problem in the form of a mathematical equation?

A: Given the two sets $P$ and $A$ indexed with $i$ and $j$, respectively, I would use a binary variable $x_{ij}$ which is equal to 1 iff I select the edge from $i \in P$ to $j \in A$.
I want to maximize the sum of the edges' weights, subject to the constraints that there are no two edges incident to the same node. As I understand, all nodes in $P$ must have a match, while some nodes in $A$ may not have a match (of course, the cardinality of $P$ must be smaller or equal to the cardinality of $A$):
$$ \max \sum_{i \in P}\sum_{j \in A} x_{ij} \cdot w_{ij} \;\;s.t.$$
$$\sum_{j \in A} x_{ij} = 1\;\;\;\forall i\in P$$
$$\sum_{i \in P} x_{ij} \leq 1\;\;\;\forall j\in A$$
$$x_{ij} \in \{0,1\}$$
where $w_{ij}$ is the weight of the edge from $i$ to $j$.
The first constraint ensures that the degree of each node in $P$ is exactly 1 (all nodes in $P$ have only one incident edge), while the second constraint ensures that each node in $A$ has at most one incident edge.
Hope I correctly understood the question.


text:
Q: 404 Error When Accessing URL through AJAX Not sure why, everything seems formatted fine, but I get the HTTP 404 error when attempting to access a function in my controller. Here's the aspx:
function CheckIfPacked() {
  if ($("#OrderNumber").val() != "") {
    var url = "/Packing/PackageTracking/CheckIfPacked";
    $.ajax({
      url: url,
      cache: false,
      data: "orderNumber=" + $("#OrderNumber").val() + "&actionyes=GetSalesOrder()",
      success: function (data) {
      var domElement = $(data);
      if (data != "") {
        $('#MessageDiv').append(domElement);
      }
    });
  }
}

And here's the controller:
public Result CheckIfPacked(string orderNumber) {
   var mesEntity = new MESEntities();
   var packh = from packhead in mesEntity.Packing_Transaction_Headers
               where packhead.Order_No_ == orderNumber
               select packhead.Completed_by_Packer;
   if (packh.First() == 0)
   {
      return new Result { Success = true, Message = string.Format("You have not finished packing order {0}, are you sure you want to navigate away from this page?", orderNumber) };
   }
   else
   {
      return null;
   }
}

I think I've just stared at this too long. Thanks.

A: your method should be static and you should use webmethod attribute for your function :
[WebMethod]
public static Result CheckIfPacked(string orderNumber) {
   var mesEntity = new MESEntities();
   var packh = from packhead in mesEntity.Packing_Transaction_Headers
               where packhead.Order_No_ == orderNumber
               select packhead.Completed_by_Packer;
   if (packh.First() == 0)
   {
      return new Result { Success = true, Message = string.Format("You have not finished packing order {0}, are you sure you want to navigate away from this page?", orderNumber) };
   }
   else
   {
      return null;
   }
}


text:
Q: RuntimeError while ploting data from loop using pygtgr I need to plot data generated in a loop using pyqtgraph, but every time I get the following error:

RuntimeError: wrapped C/C++ object of type PlotDataItem has been
deleted

This is a minimal example that generates this error. Basically, I want to create two figures and update them with new data, as the data comes in. Does anybody know what I am doing wrong?
import random
import pyqtgraph as pg
from pyqtgraph.Qt import QtGui, QtCore

class test():
    def __init__(self):

        self.win = pg.GraphicsWindow()
        self. win.resize(800, 800)

        # Create layout to hold multiple subplots
        pg_layout = pg.GraphicsLayoutWidget()

        # Add subplots
        plot1 = pg_layout.addPlot(pen=None, symbol='x', row=0, col=0, title="Sim. vs. Ml.")
        plot2 = pg_layout.addPlot(pen=None, symbol='x', row=0, col=1, title="Area")

        self.p1 = plot1.plot()                        # create an empty "plot" (a curve to plot)
        self.p2 = plot2.plot()                        # create an empty "plot" (a curve to plot)

        # Show our layout holding multiple subplots
        pg_layout.show()

    def update_plot(self,data):
        self.p1.setData(data)
        QtGui.QApplication.processEvents()

    def run(self):
        while True:
            x = random.sample(range(1, 100), 20)
            self.update_plot(x)

t = test()
t.run()

A: pg_layout, plot1 and plot2 are local variables. As such, they will be destroyed once class initialization has been done, unless they're stored in some other living object: plot1 and plot2 are referenced by pg_layout, but, conversely, this latter (pg_layout) is not attached to (referenced by) any other objects.
As soon as the __init__ function returns, pg_layout becomes an orphan object: self.p1 and self.p2 are PlotDataItem objects, they live in class test object, they are children of pg_layout but they most likely do not store their parent, and this makes pg_layout not attached to any living object.
By the way, GraphicsWindow is both deprecated and useless in this example and QApplication is a class in QtWidgets package
import random

from PyQt5 import QtGui, QtCore, QtWidgets
import pyqtgraph as pg

class test():
    def __init__(self):
        # Create layout to hold multiple subplots
       self.pg_layout = pg.GraphicsLayoutWidget()

        # Add subplots
       plot1 = self.pg_layout.addPlot(pen=None, symbol='x', row=0, col=0, title="Sim. vs. Ml.")
       plot2 = self.pg_layout.addPlot(pen=None, symbol='x', row=0, col=1, title="Area")

       self.p1 = plot1.plot()                        # create an empty "plot" (a curve to plot)
       self.p2 = plot2.plot()                        # create an empty "plot" (a curve to plot)

        # Show our layout holding multiple subplots
       self.pg_layout.show()

    def update_plot(self,data):
        self.p1.setData(data)
        QtWidgets.QApplication.processEvents()

    def run(self):
        while True:
            x = random.sample(range(1, 100), 20)
            self.update_plot(x)

t = test()
t.run()

To prove what inferred above, let us create  (for didactic purpose only) a new custom attribute for self.p1 and self.p2 plots to store their parent (pg_layout) that this time is not a class object but remains a local variable. All the rest remains the same.
class test():
    def __init__(self):
        # Create layout to hold multiple subplots
       pg_layout = pg.GraphicsLayoutWidget()

        # Add subplots
       plot1 = pg_layout.addPlot(pen=None, symbol='x', row=0, col=0, title="Sim. vs. Ml.")
       plot2 = pg_layout.addPlot(pen=None, symbol='x', row=0, col=1, title="Area")

       self.p1 = plot1.plot()                        # create an empty "plot" (a curve to plot)
       self.p2 = plot2.plot()                        # create an empty "plot" (a curve to plot)

       setattr(self.p1, 'myparent', pg_layout)
       setattr(self.p2, 'myparent', pg_layout)

        # Show our layout holding multiple subplots
       pg_layout.show()

As you can see, the code runs fine: the fact pg_layout has been forced to be attached to its child (and not vice versa!) self.p1 that is a class attribute,  let it remain alive after the test object initialization.


text:
Q: Failed to load property source from location 'classpath:/application.yml' I'm using variables in application.yml to parameterise between environments, these variables are set by a tag in pom.xml and when I run JUnit tests in IntelliJ Idea, the application throw error while load application.yml
Caused by: while scanning for the next token
found character '@' that cannot start any token. (Do not use @ for indentation)
 in 'reader', line 4, column 15:
        auth-url: @auth.url@

I tried to edit IDE run configurations and also put the variable inside quotes but without success. Running through the terminal always works, only in IntelliJ IDEA does not work
application.yml
spring:
  application:
    name: Application
    auth-url: @auth.url@
  profiles:
    active: @activatedProperties@
  data:
    mongo:
      host: @app.datasource.host@
      port: @app.datasource.port@
      database: @app.datasource.database@
      password: @app.datasource.password@
      username: @app.datasource.user@

Full Stacktrace
java.lang.IllegalStateException: Failed to load ApplicationContext

    at org.springframework.test.context.cache.DefaultCacheAwareContextLoaderDelegate.loadContext(DefaultCacheAwareContextLoaderDelegate.java:125)
    at org.springframework.test.context.support.DefaultTestContext.getApplicationContext(DefaultTestContext.java:108)
    at org.springframework.test.context.web.ServletTestExecutionListener.setUpRequestContextIfNecessary(ServletTestExecutionListener.java:190)
    at org.springframework.test.context.web.ServletTestExecutionListener.prepareTestInstance(ServletTestExecutionListener.java:132)
    at org.springframework.test.context.TestContextManager.prepareTestInstance(TestContextManager.java:246)
    at org.springframework.test.context.junit.jupiter.SpringExtension.postProcessTestInstance(SpringExtension.java:97)
    at org.junit.jupiter.engine.descriptor.ClassTestDescriptor.lambda$invokeTestInstancePostProcessors$5(ClassTestDescriptor.java:349)
    at org.junit.jupiter.engine.descriptor.JupiterTestDescriptor.executeAndMaskThrowable(JupiterTestDescriptor.java:215)
    at org.junit.jupiter.engine.descriptor.ClassTestDescriptor.lambda$invokeTestInstancePostProcessors$6(ClassTestDescriptor.java:349)
    at java.base/java.util.stream.ReferencePipeline$3$1.accept(ReferencePipeline.java:195)
    at java.base/java.util.stream.ReferencePipeline$2$1.accept(ReferencePipeline.java:177)
    at java.base/java.util.ArrayList$ArrayListSpliterator.forEachRemaining(ArrayList.java:1654)
    at java.base/java.util.stream.AbstractPipeline.copyInto(AbstractPipeline.java:484)
    at java.base/java.util.stream.AbstractPipeline.wrapAndCopyInto(AbstractPipeline.java:474)
    at java.base/java.util.stream.StreamSpliterators$WrappingSpliterator.forEachRemaining(StreamSpliterators.java:312)
    at java.base/java.util.stream.Streams$ConcatSpliterator.forEachRemaining(Streams.java:735)
    at java.base/java.util.stream.Streams$ConcatSpliterator.forEachRemaining(Streams.java:734)
    at java.base/java.util.stream.ReferencePipeline$Head.forEach(ReferencePipeline.java:658)
    at org.junit.jupiter.engine.descriptor.ClassTestDescriptor.invokeTestInstancePostProcessors(ClassTestDescriptor.java:348)
    at org.junit.jupiter.engine.descriptor.ClassTestDescriptor.instantiateAndPostProcessTestInstance(ClassTestDescriptor.java:270)
    at org.junit.jupiter.engine.descriptor.ClassTestDescriptor.lambda$testInstanceProvider$2(ClassTestDescriptor.java:259)
    at org.junit.jupiter.engine.descriptor.ClassTestDescriptor.lambda$testInstanceProvider$3(ClassTestDescriptor.java:263)
    at java.base/java.util.Optional.orElseGet(Optional.java:369)
    at org.junit.jupiter.engine.descriptor.ClassTestDescriptor.lambda$testInstanceProvider$4(ClassTestDescriptor.java:262)
    at org.junit.jupiter.engine.descriptor.TestMethodTestDescriptor.prepare(TestMethodTestDescriptor.java:82)
    at org.junit.jupiter.engine.descriptor.TestMethodTestDescriptor.prepare(TestMethodTestDescriptor.java:59)
    at org.junit.platform.engine.support.hierarchical.NodeTestTask.lambda$prepare$0(NodeTestTask.java:83)
    at org.junit.platform.engine.support.hierarchical.ThrowableCollector.execute(ThrowableCollector.java:72)
    at org.junit.platform.engine.support.hierarchical.NodeTestTask.prepare(NodeTestTask.java:83)
    at org.junit.platform.engine.support.hierarchical.NodeTestTask.execute(NodeTestTask.java:69)
    at java.base/java.util.ArrayList.forEach(ArrayList.java:1540)
    at org.junit.platform.engine.support.hierarchical.SameThreadHierarchicalTestExecutorService.invokeAll(SameThreadHierarchicalTestExecutorService.java:38)
    at org.junit.platform.engine.support.hierarchical.NodeTestTask.lambda$executeRecursively$4(NodeTestTask.java:112)
    at org.junit.platform.engine.support.hierarchical.ThrowableCollector.execute(ThrowableCollector.java:72)
    at org.junit.platform.engine.support.hierarchical.NodeTestTask.executeRecursively(NodeTestTask.java:98)
    at org.junit.platform.engine.support.hierarchical.NodeTestTask.execute(NodeTestTask.java:74)
    at java.base/java.util.ArrayList.forEach(ArrayList.java:1540)
    at org.junit.platform.engine.support.hierarchical.SameThreadHierarchicalTestExecutorService.invokeAll(SameThreadHierarchicalTestExecutorService.java:38)
    at org.junit.platform.engine.support.hierarchical.NodeTestTask.lambda$executeRecursively$4(NodeTestTask.java:112)
    at org.junit.platform.engine.support.hierarchical.ThrowableCollector.execute(ThrowableCollector.java:72)
    at org.junit.platform.engine.support.hierarchical.NodeTestTask.executeRecursively(NodeTestTask.java:98)
    at org.junit.platform.engine.support.hierarchical.NodeTestTask.execute(NodeTestTask.java:74)
    at org.junit.platform.engine.support.hierarchical.SameThreadHierarchicalTestExecutorService.submit(SameThreadHierarchicalTestExecutorService.java:32)
    at org.junit.platform.engine.support.hierarchical.HierarchicalTestExecutor.execute(HierarchicalTestExecutor.java:57)
    at org.junit.platform.engine.support.hierarchical.HierarchicalTestEngine.execute(HierarchicalTestEngine.java:51)
    at org.junit.platform.launcher.core.DefaultLauncher.execute(DefaultLauncher.java:220)
    at org.junit.platform.launcher.core.DefaultLauncher.lambda$execute$6(DefaultLauncher.java:188)
    at org.junit.platform.launcher.core.DefaultLauncher.withInterceptedStreams(DefaultLauncher.java:202)
    at org.junit.platform.launcher.core.DefaultLauncher.execute(DefaultLauncher.java:181)
    at org.junit.platform.launcher.core.DefaultLauncher.execute(DefaultLauncher.java:128)
    at com.intellij.junit5.JUnit5IdeaTestRunner.startRunnerWithArgs(JUnit5IdeaTestRunner.java:69)
    at com.intellij.rt.execution.junit.IdeaTestRunner$Repeater.startRunnerWithArgs(IdeaTestRunner.java:47)
    at com.intellij.rt.execution.junit.JUnitStarter.prepareStreamsAndStart(JUnitStarter.java:242)
    at com.intellij.rt.execution.junit.JUnitStarter.main(JUnitStarter.java:70)
Caused by: java.lang.IllegalStateException: Failed to load property source from location 'classpath:/application.yml'
    at org.springframework.boot.context.config.ConfigFileApplicationListener$Loader.load(ConfigFileApplicationListener.java:524)
    at org.springframework.boot.context.config.ConfigFileApplicationListener$Loader.loadForFileExtension(ConfigFileApplicationListener.java:473)
    at org.springframework.boot.context.config.ConfigFileApplicationListener$Loader.load(ConfigFileApplicationListener.java:443)
    at org.springframework.boot.context.config.ConfigFileApplicationListener$Loader.lambda$null$6(ConfigFileApplicationListener.java:425)
    at java.base/java.lang.Iterable.forEach(Iterable.java:75)
    at org.springframework.boot.context.config.ConfigFileApplicationListener$Loader.lambda$load$7(ConfigFileApplicationListener.java:425)
    at java.base/java.lang.Iterable.forEach(Iterable.java:75)
    at org.springframework.boot.context.config.ConfigFileApplicationListener$Loader.load(ConfigFileApplicationListener.java:422)
    at org.springframework.boot.context.config.ConfigFileApplicationListener$Loader.load(ConfigFileApplicationListener.java:321)
    at org.springframework.boot.context.config.ConfigFileApplicationListener.addPropertySources(ConfigFileApplicationListener.java:202)
    at org.springframework.boot.context.config.ConfigFileApplicationListener.postProcessEnvironment(ConfigFileApplicationListener.java:186)
    at org.springframework.boot.context.config.ConfigFileApplicationListener.onApplicationEnvironmentPreparedEvent(ConfigFileApplicationListener.java:176)
    at org.springframework.boot.context.config.ConfigFileApplicationListener.onApplicationEvent(ConfigFileApplicationListener.java:164)
    at org.springframework.context.event.SimpleApplicationEventMulticaster.doInvokeListener(SimpleApplicationEventMulticaster.java:172)
    at org.springframework.context.event.SimpleApplicationEventMulticaster.invokeListener(SimpleApplicationEventMulticaster.java:165)
    at org.springframework.context.event.SimpleApplicationEventMulticaster.multicastEvent(SimpleApplicationEventMulticaster.java:139)
    at org.springframework.context.event.SimpleApplicationEventMulticaster.multicastEvent(SimpleApplicationEventMulticaster.java:127)
    at org.springframework.boot.context.event.EventPublishingRunListener.environmentPrepared(EventPublishingRunListener.java:75)
    at org.springframework.boot.SpringApplicationRunListeners.environmentPrepared(SpringApplicationRunListeners.java:53)
    at org.springframework.boot.SpringApplication.prepareEnvironment(SpringApplication.java:340)
    at org.springframework.boot.SpringApplication.run(SpringApplication.java:304)
    at org.springframework.boot.test.context.SpringBootContextLoader.loadContext(SpringBootContextLoader.java:119)
    at org.springframework.test.context.cache.DefaultCacheAwareContextLoaderDelegate.loadContextInternal(DefaultCacheAwareContextLoaderDelegate.java:99)
    at org.springframework.test.context.cache.DefaultCacheAwareContextLoaderDelegate.loadContext(DefaultCacheAwareContextLoaderDelegate.java:117)
    ... 53 more
Caused by: while scanning for the next token
found character '@' that cannot start any token. (Do not use @ for indentation)
 in 'reader', line 4, column 15:
        auth-url: @auth.url@
                  ^

    at org.yaml.snakeyaml.scanner.ScannerImpl.fetchMoreTokens(ScannerImpl.java:419)
    at org.yaml.snakeyaml.scanner.ScannerImpl.checkToken(ScannerImpl.java:227)
    at org.yaml.snakeyaml.parser.ParserImpl$ParseBlockMappingValue.produce(ParserImpl.java:586)
    at org.yaml.snakeyaml.parser.ParserImpl.peekEvent(ParserImpl.java:158)
    at org.yaml.snakeyaml.parser.ParserImpl.checkEvent(ParserImpl.java:148)
    at org.yaml.snakeyaml.composer.Composer.composeNode(Composer.java:124)
    at org.yaml.snakeyaml.composer.Composer.composeValueNode(Composer.java:236)
    at org.yaml.snakeyaml.composer.Composer.composeMappingChildren(Composer.java:227)
    at org.yaml.snakeyaml.composer.Composer.composeMappingNode(Composer.java:215)
    at org.yaml.snakeyaml.composer.Composer.composeNode(Composer.java:144)
    at org.yaml.snakeyaml.composer.Composer.composeValueNode(Composer.java:236)
    at org.yaml.snakeyaml.composer.Composer.composeMappingChildren(Composer.java:227)
    at org.yaml.snakeyaml.composer.Composer.composeMappingNode(Composer.java:215)
    at org.yaml.snakeyaml.composer.Composer.composeNode(Composer.java:144)
    at org.yaml.snakeyaml.composer.Composer.composeValueNode(Composer.java:236)
    at org.yaml.snakeyaml.composer.Composer.composeMappingChildren(Composer.java:227)
    at org.yaml.snakeyaml.composer.Composer.composeMappingNode(Composer.java:215)
    at org.yaml.snakeyaml.composer.Composer.composeNode(Composer.java:144)
    at org.yaml.snakeyaml.composer.Composer.getNode(Composer.java:85)
    at org.yaml.snakeyaml.constructor.BaseConstructor.getData(BaseConstructor.java:123)
    at org.yaml.snakeyaml.Yaml$1.next(Yaml.java:547)
    at org.springframework.beans.factory.config.YamlProcessor.process(YamlProcessor.java:160)
    at org.springframework.beans.factory.config.YamlProcessor.process(YamlProcessor.java:134)
    at org.springframework.boot.env.OriginTrackedYamlLoader.load(OriginTrackedYamlLoader.java:75)
    at org.springframework.boot.env.YamlPropertySourceLoader.load(YamlPropertySourceLoader.java:49)
    at org.springframework.boot.context.config.ConfigFileApplicationListener$Loader.loadDocuments(ConfigFileApplicationListener.java:542)
    at org.springframework.boot.context.config.ConfigFileApplicationListener$Loader.load(ConfigFileApplicationListener.java:497)
    ... 76 more

A: Do you have all your maven dependencies installed?,
can you run?,...
mvn clean install

then on the Maven tab do a Reload project and try Build Project again


text:
Q: The best way to config server mixed with wordpress and laravel Hi I have one question to ask for help. I need to setup project that mix between Laravel and Wordpress.
The URL structure is like...
www.domain.com/   -> wordpress
www.domain.com/blog   -> wordpress
www.domain.com/blog/{post_id}   -> wordpress
www.domain.com/project -> laravel
www.domain.com/search -> laravel
www.domain.com/user/{user_id} -> laravel
app.domain.com -> laravel

for welcome page,  I will use wordpress but in some path such as /project or /user/{user_id}, I will use controller in Laravel.
Please give me any idea how to setup the hosting/server that meet my requirement.
BEST Regards.


text:
Q: Uncaught TypeError: Cannot read property 'X' of undefined (array) I know, this is probably the most asked error about JavaScipt! But I've read, at least 20 articles about this error on StackOverflow and none gave me the information that I needed. So, sorry in advance for any stupid question! ;)
I am starting a basic battleship game with JavaScript. For now, I have two functions: boats (generates boats) and table (generates table and interacts with the user. These are the complete functions:
Table:
function table (){
     const DIM = parseInt(prompt("Insert the size:"));
     var arr = [];
     for (var i = 0; i < DIM; i++){
         arr[i] = [];
         for (var j = 0; j < DIM; j++){
             arr[i][j] = parseInt(0);
         }
     }
     arr = boats(5, 1, DIM, arr); //1 Carrier
     arr = boats(4, 1, DIM, arr); //1 Battleship
     arr = boats(3, 2, DIM, arr); //2 Cruiser
     arr = boats(2, 3, DIM, arr); //3 Destroyer
     arr = boats(1, 4, DIM, arr); //4 Submarines
     console.log(arr);
}

Boats:
function boats (siz, numb,  DIM, arr){
    console.log(arr);
    var size = siz;
    var nrboats = numb;
    var step = 0;
    while (step < nrboats) {
        var random_column = parseInt(Math.floor((Math.random() * DIM)));
        console.log(random_column);
        var random_line = parseInt(Math.floor((Math.random() * DIM)));
        console.log(random_line);
        var verification = true;
        var orientation = "";
        while (verification && orientation === "") {
            for(var k = 0; k < size; k++) {
                if (arr[random_line][Math.min((random_column) + k, DIM-1)] === 0 && arr[random_line][((random_column) + 1 + k)] === 0 && arr[random_line][((random_column) - 1 + k)] === 0 && arr[((random_line) + 1)][(random_column + k)] === 0 && arr[((random_line) - 1)][(random_column + k)] === 0) {
                     verification = true;
                     orientation = "horizontal";
                 } else if (arr[Math.min((random_line) + k,DIM-1)][random_column] === 0 && arr[((random_line) + k)][((random_column) + 1)] === 0 && arr[((random_line) + k)][((random_column) - 1)] === 0 && arr[((random_line) + 1 + k)][random_column] === 0 && arr[((random_line) - 1 + k)][random_column] === 0) {
                     verification = true;
                     orientation = "vertical";
                 } else {
                     verification = false;
                 }
        }
        if (verification && orientation === "horizontal") {
            for(var i = 0; i < size; i++){
                arr[random_line][random_column+i] = 1;
            }
            step++;
        } else if (verification && orientation === "vertical") {
            for(var j = 0; j < size; j++){
                arr[random_line+j][random_column] = 1;
            }
            step++;
        }
    }
    return arr;
}

This may be a simple issue but I just can't figure out what's happening! Any help would be great!
Thanks,
mikeysantana

A: You random_line variable in cases such as arr[((random_line) + k)][random_column] gets values larger than length-1 of your array arr so you are doing undefined[random_column].
For every random_line variable you see in there you need to make sure they do not exceed the array's lastIndex, I did one line:
...else if (arr[Math.min((random_line) + k,DIM-1)][random_column] === 0 && arr[((random_line) + k)][((random_column) + 1)] === 0 && arr[((random_line) + k)][((random_column) - 1)] === 0 && arr[((random_line) + 1 + k)][random_column] === 0 && arr[((random_line) - 1 + k)][random_column] === 0){....

Make sure it is coherent with your game logic. In certain cases the size of the battleship is too large to fit to your grid especially when your random variable is towards the near of the array but you have a large ship to fit in.


text:
Q: Unable to evaluate brickhouse.udf.json.JsonSplitUDF I have tried to create a json_split function(UDF) using brickhouse.udf.json.JsonSplitUDF which was successful at beeline. But when I am trying to use the same function in my queries, it fails due to "unable to evaluate brickhouse.udf.json.JsonSplitUDF"! I have used the same class at Hive by adding explicitly it is working.
additional info: I have added the jars at hive.reloadable.aux.jars.path and did the reload at beeline. we are using Kerberos and Sentry authentication.
I would be glad to provide if any additional information required in order to assist me further.
I would greatly appreciate your time and earliest response.
Thanks
Jagath


text:
Q: Optimization problem: Find the point on the line $−x + 2y − 1 = 0$ that is closest to the point $(1, 2)$.
Find the point on the line  $−x + 2y − 1 = 0$  that is closest to the point $(1, 2)$.

I solved the optimization and got $x=14/10$ and $y = 1.7$ but my $y$ coordinate is not correct. can anyone explain why it's wrong. I used $x$ coordinate and solved for $y$ using $y=(x+1)/2$.

A: Any point on the line $(2k-1,k)$
Now the point will be on the perpendicular line as well
So, the product of the gradients
$$\dfrac12\cdot\dfrac{k-2}{2k-1-1}=-1$$
Alternatively, if $d$ is the distance,
$d^2=(2k-1-1)^2+(k-2)^2=5k^2-12k+20=5(k-6/5)^2+20-5(6/5)^2$
The equality occurs if $k-6/5=0$

A: A point on that line is given by $\left(x,y\right)=\left(x,\frac{x+1}{2}\right)$. Using the equation for the distance between two points, the distance between a point on this line and $\left(1,2\right)$ is given by $\sqrt{\left(x-1\right)^{2}+\left(\frac{x+1}{2}-2\right)^{2}}$. You already know this is an optimization problem, so you just need to solve the equation
$$\frac{\text{d}}{\text{d}x}\sqrt{\left(x-1\right)^{2}+\left(\frac{x+1}{2}-2\right)^{2}}=0.$$


text:
Q: How to check if the row is first on each page? I have list of data to print. I want to know if there is any way to find if the row is the first row in JasperReports's report for every page?

A: There is a built in variable name $V{PAGE_COUNT}

PAGE_COUNT - Built-in variable containing the number of records that were processed when generating the current page.

This variable starts at 1 for first record on page and counts to end of page, it will reset to 1 when new page is created.
This means that the first record on a page will have this variable ==1, you can for example use a printWhenExpression if you like to add something on first row.
<printWhenExpression><![CDATA[$V{PAGE_COUNT}.intValue()==1]]></printWhenExpression>

A: This task can be solved with in several ways in addition of using JasperReports engine built-in variable PAGE_COUNT.
Using variable
We can create the variable with resetType="Page" for counting number of rows at page.
<variable name="counterOnPage" class="java.lang.Integer" resetType="Page" calculation="Sum">
    <variableExpression><![CDATA[1]]></variableExpression>
    <initialValueExpression><![CDATA[0]]></initialValueExpression>
</variable>

Datasource
The simple csv datasource will be good for samples.
First page. Row 1
First page. Row 2
First page. Row 3
First page. Row 4
First page. Row 5
Second page. Row 1
Second page. Row 2
Second page. Row 3
Second page. Row 4
Second page. Row 5
Third page. Row 1
Third page. Row 2
Third page. Row 3
Third page. Row 4
Third page. Row 5

The name of data adapter for this datasource in the example below is rows.csv. The name of a field is name
Sample report template
The height of report is enough for showing only 5 rows per page.
<?xml version="1.0" encoding="UTF-8"?>
<jasperReport xmlns="http://jasperreports.sourceforge.net/jasperreports" xmlns:xsi="http://www.w3.org/2001/XMLSchema-instance" xsi:schemaLocation="http://jasperreports.sourceforge.net/jasperreports http://jasperreports.sourceforge.net/xsd/jasperreport.xsd" name="Using variable" pageWidth="250" pageHeight="75" whenNoDataType="AllSectionsNoDetail" columnWidth="210" leftMargin="20" rightMargin="20" topMargin="0" bottomMargin="0">
    <property name="com.jaspersoft.studio.data.defaultdataadapter" value="rows.csv"/>
    <field name="name" class="java.lang.String"/>
    <variable name="counterOnPage" class="java.lang.Integer" resetType="Page" calculation="Sum">
        <variableExpression><![CDATA[1]]></variableExpression>
        <initialValueExpression><![CDATA[0]]></initialValueExpression>
    </variable>
    <detail>
        <band height="15">
            <textField>
                <reportElement x="0" y="0" width="180" height="15" uuid="1b535a7e-7a8e-4e44-91ff-c0b8415afcf1"/>
                <textFieldExpression><![CDATA[($V{counterOnPage} == 1) ? $F{name} + "!" : $F{name}]]></textFieldExpression>
            </textField>
        </band>
    </detail>
</jasperReport>

For first row we will add the symbol "!" to the end of a string.
Output result
The result (pdf file) will be:

Using report's parameters map
Here is a little hack using parameters map ($P{REPORT_PARAMETERS_MAP}).
We can set some "flag" (instead of using variable) for marking the first row at page. We can put textField at pageHeader for setting value isFirst at report's Map, for example.
<textField>
    <reportElement x="0" y="0" width="100" height="1"/>
    <textFieldExpression><![CDATA[$P{REPORT_PARAMETERS_MAP}.put("isFirst", true)]]></textFieldExpression>
</textField>

-- we are initializing the value of our flag.
We should add check for isFirst value and change the value of this flag after first use. The fake textField will do this job
<textField>
    <reportElement x="180" y="0" width="0" height="15"/>
    <textFieldExpression><![CDATA[((Boolean) $P{REPORT_PARAMETERS_MAP}.put("isFirst", false)) ? "" : ""]]></textFieldExpression>
</textField>

-- we are reseting the value of our flag.
Sample report template
The datasource will be the same.
<?xml version="1.0" encoding="UTF-8"?>
<jasperReport xmlns="http://jasperreports.sourceforge.net/jasperreports" xmlns:xsi="http://www.w3.org/2001/XMLSchema-instance" xsi:schemaLocation="http://jasperreports.sourceforge.net/jasperreports http://jasperreports.sourceforge.net/xsd/jasperreport.xsd" name="Using Map" pageWidth="250" pageHeight="76" whenNoDataType="AllSectionsNoDetail" columnWidth="210" leftMargin="20" rightMargin="20" topMargin="0" bottomMargin="0">
    <property name="com.jaspersoft.studio.data.defaultdataadapter" value="rows.csv"/>
    <field name="name" class="java.lang.String"/>
    <pageHeader>
        <band height="1">
            <textField>
                <reportElement x="0" y="0" width="100" height="1"/>
                <textFieldExpression><![CDATA[$P{REPORT_PARAMETERS_MAP}.put("isFirst", true)]]></textFieldExpression>
            </textField>
        </band>
    </pageHeader>
    <detail>
        <band height="15">
            <textField>
                <reportElement x="0" y="0" width="180" height="15">
                </reportElement>
                <textFieldExpression><![CDATA[($P{REPORT_PARAMETERS_MAP}.get("isFirst") != null && ((Boolean) $P{REPORT_PARAMETERS_MAP}.get("isFirst")) == true) ? "! " + $F{name} + "!" : $F{name}]]></textFieldExpression>
            </textField>
            <textField>
                <reportElement x="180" y="0" width="0" height="15"/>
                <textFieldExpression><![CDATA[((Boolean) $P{REPORT_PARAMETERS_MAP}.put("isFirst", false)) ? "" : ""]]></textFieldExpression>
            </textField>
        </band>
    </detail>
</jasperReport>

For the first row we will add the symbol "!" to the begin and the end of a string.
Output result
The result (pdf file) will be:


text:
Q: ''Boolean value of Tensor with more than one value is ambiguous'' when broadcasting torch Tensor My objective is to extract the dimensions of a pytorch Tensor, whose indices are not in a given list. I want to use broadcasting to do that like follows:
Sim = torch.rand((5, 5))
samples_idx = [0]  # the index of dim that I don't want to extract
a = torch.arange(Sim.size(0)) not in samples_idx
result = Sim[a]

I assume a would be a Tensor with True/Flase with the dimension of 5.But I get the error RuntimeError: Boolean value of Tensor with more than one value is ambiguous. Anyone can help me to point out where it goes wrong? Thanks.

A: You could create a set containing the desired indices by substracting samples_idx from a set containing all indices:
>>> Sim = torch.rand(5, 5)
tensor([[0.9069, 0.3323, 0.8358, 0.3738, 0.3516],
        [0.1894, 0.5747, 0.0763, 0.8526, 0.2351],
        [0.0304, 0.7631, 0.3799, 0.9968, 0.6143],
        [0.0647, 0.2307, 0.4061, 0.9648, 0.0212],
        [0.8479, 0.6400, 0.0195, 0.2901, 0.4026]])

>>> samples_idx = [0]

The following essentially acts as your torch.arange not in sample_idx:
>>> idx = set(range(len(Sim))) - set(samples_idx)
{1, 2, 3, 4}

Then perform the indexing with idx:
>>> Sim[tuple(idx),:]
tensor([[0.1894, 0.5747, 0.0763, 0.8526, 0.2351],
        [0.0304, 0.7631, 0.3799, 0.9968, 0.6143],
        [0.0647, 0.2307, 0.4061, 0.9648, 0.0212],
        [0.8479, 0.6400, 0.0195, 0.2901, 0.4026]])

A: There is a misunderstanding between the concept of "dimension" and "indices". What you want is to filter Sim and keep only rows (the 0th dimension) which indices match a given rule.
Here is how you could do that:
Sim = torch.rand((5, 5))
samples_idx = [0]  # the index of dim that I don't want to extract
a = [v for v in range(Sim.size(0)) if v not in samples_idx]
result = Sim[a]

a is not a boolean Tensor but a list of indices to keep. You then use it to index Sim on the 0th dimension (the rows).
not in is not an operation that can be broadcasted, you should use a regular Python comprehension list for it.

A: Maybe this is a bit out of focus, but you could also try using boolean indexing.
>>> Sim = torch.rand((5, 5))
tensor([[0.8128, 0.2024, 0.3673, 0.2038, 0.3549],
        [0.4652, 0.4304, 0.4987, 0.2378, 0.2803],
        [0.2227, 0.1466, 0.6736, 0.0929, 0.3635],
        [0.2218, 0.9078, 0.2633, 0.3935, 0.2199],
        [0.7007, 0.9650, 0.4192, 0.4781, 0.9864]])

>>> samples_idx = [0]
>>> a = torch.ones(Sim.size(0))
>>> a[samples_idx] = 0
>>> result = Sim[a.bool(), :]
tensor([[0.4652, 0.4304, 0.4987, 0.2378, 0.2803],
        [0.2227, 0.1466, 0.6736, 0.0929, 0.3635],
        [0.2218, 0.9078, 0.2633, 0.3935, 0.2199],
        [0.7007, 0.9650, 0.4192, 0.4781, 0.9864]])

This way you don't have to iterate all the samples_idx list checking the inclusion.


text:
Q: Polyline on user walking I'm trying to make a polyline in map from Android while the user walks Below is my code.But I just get a straight line from my current location to somewhere else.
public class Map extends MapActivity {

private MapController mapController;
private MapView mapView;
private LocationManager locationManager;

private MyLocationOverlay myLocationOverlay;
 GeoPoint geoPoint = null;
 GeoPoint despoint = null;
 int latitude;
 int longitude;
 GeoPoint srcGeoPoint;
 public HelloItemizedOverlay routeOverlay;

public void onCreate(Bundle bundle) {
    super.onCreate(bundle);
    setContentView(R.layout.main2); // bind the layout to the activity
    mapView = (MapView) findViewById(R.id.mapview);
    mapView.setBuiltInZoomControls(true);
    mapView.setSatellite(false);
    mapController = mapView.getController();
    mapController.setZoom(14); // Zoon 1 is world view
    locationManager = (LocationManager) getSystemService(Context.LOCATION_SERVICE);
    locationManager.requestLocationUpdates(LocationManager.GPS_PROVIDER, 2000,
            2, new GeoUpdateHandler());
    Location location = locationManager.getLastKnownLocation(LocationManager.GPS_PROVIDER);
     if(location != null)
        {
             latitude = (int) (location.getLatitude() * 1E6);
            longitude = (int) (location.getLongitude() * 1E6);
        }
      srcGeoPoint = new GeoPoint(latitude, latitude);
      geoPoint = srcGeoPoint;
    myLocationOverlay = new MyLocationOverlay(this, mapView);
    mapView.getOverlays().add(myLocationOverlay);
    mapView.getController().setZoom(15);
    //mapController.setCenter(geoPoint);
    //mapView.getOverlays().add(new HelloItemizedOverlay(srcGeoPoint, srcGeoPoint));

}

@Override
protected boolean isRouteDisplayed() {
    return false;
}

public class GeoUpdateHandler implements LocationListener {

    @Override
    public void onLocationChanged(Location location) {

        int lat = (int) (location.getLatitude() * 1E6);
        int lng = (int) (location.getLongitude() * 1E6);
        GeoPoint changepoint = new GeoPoint(lat, lng);

        mapView.getOverlays().add(new HelloItemizedOverlay(srcGeoPoint,changepoint));

    }

    @Override
    public void onProviderDisabled(String provider) {
    }

    @Override
    public void onProviderEnabled(String provider) {
    }

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

@Override
protected void onResume() {
    super.onResume();
    myLocationOverlay.enableMyLocation();
    myLocationOverlay.enableCompass();
}

@Override
protected void onPause() {
    super.onResume();
    myLocationOverlay.disableMyLocation();
    myLocationOverlay.disableCompass();
}}

Overlay class
public class HelloItemizedOverlay extends Overlay {

 private GeoPoint gp1;
    private GeoPoint gp2;

public HelloItemizedOverlay(GeoPoint gp1, GeoPoint gp2) {
    this.gp1 = gp1;
    this.gp2 = gp2;
}
@Override
public boolean draw(Canvas canvas, MapView mapView, boolean shadow,
        long when) {
     Projection projection = mapView.getProjection();
        if (shadow == false) {

            Paint paint = new Paint();
            paint.setAntiAlias(true);
            Point point = new Point();
            projection.toPixels(gp1, point);
            paint.setColor(Color.BLUE);
            Point point2 = new Point();
            projection.toPixels(gp2, point2);
            paint.setStrokeWidth(2);
            canvas.drawLine((float) point.x, (float) point.y, (float) point2.x,
                    (float) point2.y, paint);
        }
        return super.draw(canvas, mapView, shadow, when);
    } }

Can anyone pls help me out to draw a line on user walks.The above just draw a line from current loc to some where

A: i tried to create a method that:
-get a new GeoPoint
-add it to the road
-delete the previous road and show the new one
 then invoke it every 10 seconds
and this is how i code it :
 public void scheduleReceiveLocation(final GeoPoint newPosition) {
             final int TEN_SECONDS = 10000;
            handler.postDelayed(new Runnable() {
                public void run () {
//remove previous point
                    waypoints.remove(1);
//delete the previous road
                    map.getOverlays().remove(0);
//add the new GeoPoint
                    waypoints.add(1,newPosition);
                    // draw the new road with the new position
                    new UpdateRoadTask().execute(waypoints);

                 // this method will contain your almost-finished HTTP calls
                    handler.postDelayed(this, TEN_SECONDS);
                }
            }, TEN_SECONDS);
        }

then just call handler.removeCallbacksAndMessages(null); to stop
hope it help


text:
Q: Job doing Stop-Job on self Just looking for verification here. Can a job Stop-Job itself? I have a script that creates a job that suppresses a service for as long as the main script is running (by way of passed $PID) and I am currently using this
Start-Job -name:'SuppressAdAppMgrSvc' -argumentList $id -scriptBlock {
    param (
        $id
    )

    do {
        if ((Get-Service AdAppMgrSvc -errorAction:silentlyContinue).Status -eq 'Running') {
            Stop-Service AdAppMgrSvc -force -warningAction:silentlyContinue -errorAction:silentlyContinue
        }

        Start-Sleep -s 5
        $powershellProcess = Get-Process -id:$id -errorAction:silentlyContinue
    } while ($powershellProcess)

    Stop-Job 'SuppressAdAppMgrSvc' -warningAction:silentlyContinue -errorAction:silentlyContinue
    Remove-Job 'SuppressAdAppMgrSvc' -warningAction:silentlyContinue -errorAction:silentlyContinue

My thinking is the job will run, and when $PowershellProcess is no longer, then the Stop-Job would run. But I suspect the Remove-Job would not, since this is the very job that just got stopped. In general it probably isn't a problem, as 99% of the time I do a reboot when my script completes, but I am curious if there is a pattern for dealing with this? Or is it something of an edge case?

A: How do you expect Remove-Job to run inside a stopped job? And why would you want to do that from inside the job in the first place?
The job will automatically enter the Stopped state when the code in the scriptblock terminates, so all you need to do is to wait for that to happen and then remove the job:
Start-Job -Name 'SuppressAdAppMgrSvc' -ArgumentList $id -ScriptBlock {
  ...
} | Wait-Job | Remove-Job


text:
Q: How can I adjust Textmate syntax highlighting in Smarty literal tags So I have the Smarty TM bundle installed and active in Textmate, but I have a problem with the way it treats stuff inside of Smarty's literal tags.
As seen in this example: http://pastie.textmate.org/private/v3amipi5ukpg7vlcivixw
If I put Smarty literal tags inside of my HTML script tags, TM sees the stuff within the script tags as JS and highlights it appropriately. If I move those literal tags such that they are around my script, Textmate loses track of the fact that the script tags contain javascript--or even that the script tags are HTML--neither are highlighted.
I hate putting my literal tags inside the script because everything that deals with JS in the editor (for example, I have a TM command to run my JS through JSHint) gets mad at them being there unless I prefix them with JS comments (like in my pasted example). But prefixing them with comments is extra work I don't feel like doing, and causes lots of empty comments in my outputted source.
I have looked at the various lang definitions involved, and just cannot figure out what the heck to do to fix it. Any thoughts?
Thanks,
Jim


text:
Q: YUI Rich Editor + invalidHTML + style I am trying to insert an inline style tag into the editor content. When I call saveHTML it strips out the style block when I'm in rich editor view. I have tried changing the style property of invalidHTML to false, but it still seems to strip the style block out.
Any pointers to the API or suggestions would be helpful at this stage!
Thanks,
Col.

A: I hope I understand your question properly. You just want to be able to insert something like this in your textarea?
<style>
    .className { font-weight: bold;}
</style>

If so this is how I have it working using what is specified in the YUI API documentation. In particular this part on invalidHTML
Before I initialize the editor I specify all the invalid tags I want stripped out:
var invalidTags = {"abbr":{ "keepContents":true },
    "acronym":{ "keepContents":true }, "address":{ "keepContents":true },
    "applet":"", "area":"", "base":"", "basefont":"", "bdo":"", "big":"",
    "blockquote":{ "keepContents":true }, "body":{ "keepContents":true }}

Mine's a rather long list (basically all html tags) as I exclude everything except p, style, br, ul, ol, li.  So in your case you'd leave out the style tag.
Then I set up the editor and then pass in the invalidTags as the invalidHTML for the editor before rendering.
So this is what everything looks like after all is said and done.
var invalidTags = {"abbr":{ "keepContents":true },
    "acronym":{ "keepContents":true }, "address":{ "keepContents":true },
    "applet":"", "area":"", "base":"", "basefont":"", "bdo":"", "big":"",
    "blockquote":{ "keepContents":true }, "body":{ "keepContents":true }}

var editor = new YAHOO.widget.Editor('myeditor', {
    height: '300px',
    width: '500px',
    dompath: true,
    filterWord: true
}

editor.invalidHTML = invalidTags;
editor.render();

YAHOO.util.Event.on('Update', 'click', function() {
    editor.saveHTML();
}

So that's that for how I get it to preserve the tags I want. eg. style.
Hope that helps you out.


text:
Q: How to evaluate if $\int_2^\infty {\frac{1}{\log(x)\cdot \sqrt{x^2+1}}}dx$ converges? I am asked to evaluate if $$\int_2^\infty {\frac{1}{\log(x)\cdot \sqrt{x^2+1}}}dx$$
converges.
How can that be done? Even Wolframalpha/Mathematica 8.0 does not return a value.
Can this be done with improper integral convergence tests I,II or III?
EDIT:
Improper integral convergence test I (I guess it is also called comparison test I, at least in my native language):
If there exists $g(x)$ such that $0\leq f(x)\leq g(x)\quad \forall x \in [a;=\infty)$
and  $\int_a^\infty{g(x)dx}$ converges, then $\int_a^\infty{f(x)dx}$ also converges.
Improper integral convergence test II would be the ratio test.

A: Hint.  First investigate
$$\int_2^\infty \frac{dx}{x\log x}\ .$$

A: Since
$$\int_{2}^{M}\frac{dx}{x\log x}=\int_{\log 2}^{\log M}\frac{dt}{t}=\log\log M-\log\log 2$$
and for any $x\geq 2$:
$$\frac{1}{\log(x)\cdot\sqrt{x^2+1}}\geq\frac{1}{x\log x\cdot\sqrt{\frac{5}{4}}}=\frac{2}{\sqrt{5}}\cdot\frac{1}{x\log x}$$
the integral is divergent.


text:
Q: How to get the norm of of the functional? Let $\frac{1}{r}=\frac{1}{p}+\frac{1}{q},\ r,p,q>0.\ \alpha=(\alpha_{n})\in L^{q}$. Define $T:L^{p}\rightarrow L^{r}$ by $(Tx)(t)=\alpha(t)x(t)$ for every $x\in L^{p}$. Then $\lVert T\rVert=$?
I have done the first part. That is for $x\in L^{p},\ \lVert Tx\rVert_{r}\leq\lVert\alpha\rVert_{q}\lVert x\rVert_{p}$. Then$$\lVert T\rVert=\sup_{x\neq0}\dfrac{\lVert Tx\rVert_{r}}{\lVert x\rVert_{p}}\leq\lVert\alpha\rVert_{q}.$$But I can't choose a specific $x$ such that  $\frac{\lVert Tx\rVert_{r}}{\lVert x\rVert_{p}}=\lVert\alpha\rVert_{q}$. Any help would be appreciated.


text:
Q: Popup Box with Link to other google Document in Google Document I have a script that I run from the menu of a google document. It essentially functions like this one: https://webapps.stackexchange.com/questions/47173/how-to-automatically-open-a-created-text-document-after-it-being-created/47649#47649.
I want a function that is similar the one in the link above except that the popup with the link is shown in a google doc rather than a google spreadsheet. That part of my script looks like this (title and url are defined above that part):
var docnew = DocumentApp.getActiveDocument();

var app = UiApp.createApplication().setTitle("Open Doc")
.setHeight(50).setWidth(400);
var vPanel = app.createVerticalPanel().add(app.createAnchor(title, url));

app.add(vPanel);
docnew.show(app);

I then get the following error. "TypeError: Funktion show in Objekt Document nicht gefunden", which is German and means  "TypeError: Function show not found in object Document".
Can somebody help me with this?
Thanks a lot in advance.
Best,
Phil

A: The show method works only in spreadsheets, in Google Documents (and also in the new version of spreadsheets) you can use this code :
SpreadsheetApp.getUi().showModalDialog(argument);

The documentation shows some examples.
Your code snippet would be like this :
function showUi(){
  var docnew = DocumentApp.getActiveDocument();
  var app = UiApp.createApplication()
  .setHeight(50).setWidth(400);
  var vPanel = app.createVerticalPanel().add(app.createAnchor(title, url));
  app.add(vPanel);
  DocumentApp.getUi().showModelessDialog(app,"Open Doc");
}


text:
Q: Independence of $X$ and $X^2$ If I have a random variable $X$ where the pdf is always positive, are $X$ and $X^2$ independent? Never, sometimes, or always?
I was thinking to either find the pdf of $X^2$ or the cdf. Then find the joint pdf/cdf. But without the actual value of the pdf for $X$ I'm not sure how to do that. Is there another way?
Any help would be appreciated!
Edit: pdf is positive for any real value of X
Edit 2: X is a continuous random variable

A: Surely $X $ and $X^2$ are not independent! As soon as you know the value of one, the value of the other becomes determined!

A: Given that $X^2\in A^2$ for some set $A$ in the Borel σ-algebra of $\mathbb R$, then you know that $X\in \pm A$. Take $A$ such that $0<P(X\in \pm A)<1$ (this $A$ exists due to your assumption that $f(x)>0$ for all $x\in \mathbb R$), then $$P(X\in \pm A\mid X^2\in A^2)=1\neq P(X\in \pm A)$$ hence $X$ and $X^2$ are always dependent under this assumption. Otherwise, (see the comment in the other answer) you can create a degenerate random variable for which $X$ and $X^2$ are independent.

A: If $X$ is a non-negative RV and not constant, then $X$ and $X^2$ are positively correlated, and hence not independent.  Here's why: The covariance between $X$ and $X^2$ is by definition the expectation of
$$
(X-EX)\left(X^2 - E(X^2)\right).\tag1
$$
Rewrite (1) as
$$
(X-EX)\left(X^2-(EX)^2\right) + (X-EX)\left((EX)^2-E(X^2)\right).\tag2
$$
The second term of (2) has expectation zero. Meanwhile, the first term of (2) can be rewritten
$$
(X-EX)^2(X + EX),\tag3
$$
which shows that (3) is a nonnegative and non-constant RV. Therefore (3) has positive expectation, so so does (1), which means the required covariance is positive.
(Assuming all required expectations exist.) Geometrically, the random pair ($X$, $X^2$) lives on the right half of the curve $y=x^2$, so the correlation is positive if $X$ is not constant.


text:
Q: jQuery ON method sub tag issue I have found inserting issue in Chrome and IE in FF working well
I have next code that change classes name
 jQuery(document).on("mouseout", ".buttonStyleOver", { className: "buttonStyle" }, ChangeClass);
    jQuery(document).on("mouseover", ".buttonStyle", { className: "buttonStyleOver" }, ChangeClass);

    function ChangeClass(e) {
            var el = e.srcElement || e.target;
            jQuery(el).attr("class", e.data.className);
    }

and I have next HTML part (please don't critic it I know this is bad style)
<button id="RunItButton" class="buttonStyle" type="button" style="vertical-align:middle;padding-right:5px;height:25px">
Run It
</button>

in IE and Chrome event also change class="cmRunIt" to buttonStyleOver how to fix it ?
thanks.

A: To make you understand your problem, add a console.log :
var el = e.srcElement || e.target;
console.log(el);

You will see that some times el is not your button but the div ! Why do you use e.srcElement ?
Try with :
function ChangeClass(e) {
  jQuery(this).attr("class", e.data.className);
}

And marius is right, unless you need live events, you should use hover.

A: can't you just do something like this?
$("#RunItButton").hover(function(){
  $(this).addClass("buttonStyleOver");
}, function(){
  $(this).removeClass("buttonStyleOver");
});

or:
$("#RunItButton").mouseover(function(){
  $(this).addClass("buttonStyleOver");
}).mouseout(function(){
  $(this).removeClass("buttonStyleOver");
});


text:
Q: Can a Table of Contents be generated in Publisher? I have a decent amount of content already typed up with headers on most pages.  I would like to create a generated Table of Contents based off of these headers.  Is this possible, and if so how can I do this?

A: I would like to create a generated Table of Contents based off of these headers
You cannot automatically create a table of contents - this feature is not available in Publisher.
The following instructions show you how to manually create a TOC. It looks like you will have to copy and paste your headings ...

Insert a table of contents in Publisher
For a little extra work—and a big payoff—you can create a table of
  contents in Publisher. Begin by adding a text box and use
  right-aligned tabs with leaders. Leaders are the dots, dashes, or
  lines that follow the chapter or section titles in a table of contents
  and that line up those titles with page numbers.

*

*Click Home > Draw Text Box.

*In your publication, click where you want one corner of the text to appear, and then drag diagonally until you have the box size that
  you want.

*Type the title of your table of contents, and then press ENTER.

*Double-click the horizontal ruler where you want the page number to appear.

*In the Tabs dialog box, click Right, choose your Leader style, and then click OK.

*Now type your TOC entry; for example: Chapter 1, press TAB to insert the leader and type the page number.

Source Insert a table of contents in Publisher

A: Came here looking for a quick fix for a colleagues problem couldn't find a solution elsewhere, so posting my own solution to simulate TOC using script with PowerShell Version 5 on Win7 with Publisher 2010.
TOC added in between page 2 and 3 where page 1 was a title cover page and 2 a welcome page. The title was always text box shape 1. to keep alignment style a monospaced font was used for TOC.
If you are using Standard Publisher Page Part Headings then the following could be substituted variable $TOCAdd
$Heading_Geometric_Title_Text = $Publisher.ActiveDocument.Pages($pge).Shapes(1).GroupItems[3].TextFrame.TextRange.Text
$Heading_Geometric_Subtitle_Text = $Publisher.ActiveDocument.Pages($pge).Shapes(1).GroupItems[2].TextFrame.TextRange.Text

$Heading_Brackets_Title_Text = $Publisher.ActiveDocument.Pages($pge).Shapes(1).GroupItems[2].TextFrame.TextRange.Text
$Heading_Brackets_Subtitle_Text = $Publisher.ActiveDocument.Pages($pge).Shapes(1).GroupItems[5].TextFrame.TextRange.Text

$Heading_Pure_Title_Text = $Publisher.ActiveDocument.Pages($pge).Shapes(1).GroupItems[3].TextFrame.TextRange.Text
$Heading_Pure_Subtitle_Text = $Publisher.ActiveDocument.Pages($pge).Shapes(1).GroupItems[2].TextFrame.TextRange.Text

#
# Path to Publisher document
$FileName = "$env:USERPROFILE\Documents\Publication_1.pub"
$Publisher=NEW-Object –comobject Publisher.Application

# Following line sets whether file is opened visible or not.
$Publisher.ActiveWindow.visible = 1

# Open Publisher Document
$Publisher.open($FileName)

# Check how Many Pages in document
$count = $Publisher.ActiveDocument.Pages.Count

# How Many TOC Pages required in document for the amount of titles (assume 17 per page)
    $TOCPages = [math]::Round($count/17)

# New Page Count including TOC required in document
    $countINC = $count += $TOCPages

# Add TOC pages required insert Page(s) after last Pre page
    $Pre = 2
    IF ($TOCPages -ge 1) {
    ForEach ( $n in 1..$TOCPages){
    $Publisher.ActiveDocument.Pages.Add(1,$Pre)
    }

# Add table on TOC Pages
    ForEach ( $n In 1..$TOCPages){
# Insert New Toc from this page No
    $n += $Pre

# Insert table on the new TOC page with  NumRows:=17, NumColumns:=3, Left:=50, Top:=70, Width:=600, Height:=300
    $TOCPage = $Publisher.ActiveDocument.Pages($n).Shapes.AddTable( 17, 3, 50, 75, 600, 300)
# Adjust column widths for table (shape)
    $TOCPage.Table.Columns(1).width = 30  #Item No
    $TOCPage.Table.Columns(2).width = 450 #Item
    $TOCPage.Table.Columns(3).width = 70  #Page No

    #Add Text Box Standard Text (type 1) adjust font size then make it Bold
    $TOCTitle = $Publisher.ActiveDocument.Pages($n).Shapes.AddTextbox(1, 360,  26, 150, 25)
    $TOCIndex = ($n -= ($Pre))
    $TOCTitle.TextFrame.TextRange.Text = "Table of Contents $TOCIndex"
    $TOCTitle.TextFrame.TextRange.Font.Size = 14
    $TOCTitle.TextFrame.TextRange.Font.Bold = 1
    }
    }
# Identify first page after TOC
    $start = $TOCPages += ($Pre += 1)
# Create TOC Array (Fixed Content First) append to fixed length Char 46 (period)
    $TOCROW1 = 'Title Page'
    $TOCROW2 = 'Welcome to the Catalogue'
    $TOCROW3 = 'Table of Contents'
    $TOCArray = @()
    $TOCRow = "" | Select 'Table of Contents','PageNo'
    $TOCRow.'Table of Contents' = $TOCROW1.PadRight(60,[char]46)
    $TOCRow.PageNo = 1
    $TOCArray = $TOCArray + $TOCRow
    $TOCRow = "" | Select 'Table of Contents','PageNo'
    $TOCRow.'Table of Contents' = $TOCROW2.PadRight(60,[char]46)
    $TOCRow.PageNo = 2
    $TOCArray = $TOCArray + $TOCRow
    $TOCRow = "" | Select 'Table of Contents','PageNo'
    $TOCRow.'Table of Contents' = $TOCROW3.PadRight(60,[char]46)
    $TOCRow.PageNo = 3
    $TOCArray = $TOCArray + $TOCRow

# Use try / catch for page shapes returning error
    try {
    ForEach ($pge in $Start..$countINC){
    IF ($pge -eq "" ){ Write-Host "Debug"}
    Else{ # Add TOC Array Entries

    $TOCAdd = $Publisher.ActiveDocument.Pages($pge).Shapes(1).TextFrame.TextRange.Text
    $TOCRow = "" | Select 'Table of Contents','PageNo';
    $TOCRow.'Table of Contents' = $TOCAdd.PadRight(60,[char]46)
    $TOCRow.PageNo = $pge
    $TOCArray = $TOCArray + $TOCRow
    }
 }
}

    catch { }

# Debug uncomment following line to View Output of 'Table of Contents' based on the data added in Array variable 'TOCArray'
#    $TOCArray | Format-Table -Wrap -Property 'Table of Contents','PageNo'

# Add TOC entries to TOC (uses monospaced font to get alignment)
    $n = 2
    $q = -1
    $Item =0
    ForEach ($TOC in 1..$TOCPages) {
     $n++
     $q++
     $Row = 0
     $Offset = ($q * $Range)
     $Range  = 17
     $TOCArray | Select-Object -Skip $Offset -First $Range -Property 'Table of Contents','PageNo'|
    ForEach-Object {
      $Row++
      $Item++
      $TOCEntry = $Publisher.ActiveDocument.Pages($n).Shapes(1).Table.Rows($Row).Cells(1);
      $TOCEntry.TextRange.Text = "$Item";
      $TOCEntry.TextRange.Font.Size = 12;
      $TOCEntry.TextRange.Font.Bold = 1;
      $TOCEntry.TextRange.Font.Name = 'Consolas';
      $TOCEntry = $Publisher.ActiveDocument.Pages($n).Shapes(1).Table.Rows($Row).Cells(2);
      $TOCEntry.TextRange.Text = $_.'Table of Contents'.replace("`r","").ToString()
      $TOCEntry.TextRange.Font.Size = 12;
      $TOCEntry.TextRange.Font.Bold = 1;
      $TOCEntry.TextRange.Font.Name = 'Consolas';
      $TOCEntry = $Publisher.ActiveDocument.Pages($n).Shapes(1).Table.Rows($Row).Cells(3);
      #Need to Convert PageNo stored as System.Int32 to String
      $TOCEntry.TextRange.Text = $_.PageNo.ToString()
      $TOCEntry.TextRange.Font.Size = 12;
      $TOCEntry.TextRange.Font.Bold = 1;
      $TOCEntry.TextRange.Font.Name = 'Consolas';
     }
    }
# Save File (and increment versions), then close.
    $v++
    $file = $Publisher.ActiveDocument.Name
    $BaseName = $file.Substring(0, $file.LastIndexOf('.'))
    $strFileName = $BaseName + "_v1" + $v
    $Publisher.ActiveDocument.SaveAs($strFileName)
    $Publisher.ActiveDocument.Close()
    $Publisher.quit()
    [System.Runtime.Interopservices.Marshal]::ReleaseComObject($Publisher)


text:
Q: webpack/babel transpile to system.register I can successfully transpile es6 modules -> System.Register format using babel cli.
I would like to be able to transpile to System.Register format using babel from Webpack.
.babelrc
{
    "presets": ["es2015"],
    "plugins": ["transform-es2015-modules-systemjs"]
}

webpack.config.js
.....
.....
loaders: [ {
        test   : /.js$/,
        exclude : /node_modules/,
        loader : 'babel-loader',
        query: {
            presets: ['es2015']
        }
    }
]
.....
.....

After running 'webpack', a warning is returned System.register is not supported by webpack.
I know this is self explanatory, my question is (which i have been unable to find the answer to after searching / investigating) -
Is this something that is going to be supported by webpack? Or if it is supported, what am i doing wrong?
Thanks,

A: Pretty out-of-date answer, but you could try "commonjs". It gets worked for me.


text:
Q: Several count aggregation output in Mongo So I have a collection like this:
{
 'region': '1',
 'status': 'a',
 'sum': 100
}
{
 'region': '1',
 'status': 'b',
 'sum': 80
}
{
 'region': '2',
 'status': 'a',
 'sum': 20
}
{
 'region': '2',
 'status': 'a',
 'sum': 30
}

And the desired result must be like this:
[
  {
    'region': '1',
    'status_a': 1,
    'status_b': 1,
    'sum': 180
  },
  {
    'region': '2',
    'status_a': 2,
    'sum': 50
  }
]

Any suggestions? The number of regions as well as the number of statuses can vary and I need to always output the sum for the entire region despite statuses
P.S if you wanna be super specific with your answer, then region and status fields are ObjectId's, thanks in advice!

A: *

*$group by both region and status and count status and sum

*$group by only region and $concat status_ and its value after converting object id to string using $toString

*construct the array of status and statusCount in key-value format

*$arrayToObject convert above converted array to object

*$mergeObjects to merge required fields and status object

*$replaceRoot to replace above merged document in root

db.collection.aggregate([
  {
    $group: {
      _id: { region: "$region", status: "$status" },
      statusCount: { $sum: 1 },
      sum: { $sum: "$sum" }
    }
  },
  {
    $group: {
      _id: "$_id.region",
      status: {
        $push: {
          k: { $concat: ["status_", { $toString: "$_id.status" }] },
          v: "$statusCount"
        }
      },
      sum: { $sum: "$sum" }
    }
  },
  {
    $replaceRoot: {
      newRoot: {
        $mergeObjects: [
          { $arrayToObject: "$status" },
          {
            resion: "$_id",
            sum: "$sum"
          }
        ]
      }
    }
  }
])

Playground


text:
Q: Entity Framework doesn't update bit datatype I have added a new column IsForceLogOff (datatype = Bit). When I update the table in the usual way, everything updates except the newly added bool column.
public static UserErrorStatus UserUpdate(User user, Company company)
{
    UserErrorStatus status = UserErrorStatus.Error;

    using (OAPDataLayerEntities DbEntity = GetDBContext())
    {
        try
        {
            using (TransactionScope transaction = new TransactionScope())
            {
                user.IsForceLogOff = true;
                DbEntity.Users.Attach(user);
                DbEntity.ObjectStateManager.ChangeObjectState(user, EntityState.Modified);

                DbEntity.SaveChanges();
                transaction.Complete();

                DbEntity.AcceptAllChanges();
                status = UserErrorStatus.Success;
            }
        }
    }
}

Create table statement:
CREATE TABLE [dbo].[User]
(
    [UserID] [int] IDENTITY(1,1) NOT NULL,
    [AddressID] [int] NULL,
    [AccountTypeID] [int] NOT NULL,
    [StaffID] [int] NULL,
    [SalutationID] [int] NULL,
    [FirstName] [nvarchar](50) NOT NULL,
    [LastName] [nvarchar](50) NOT NULL,
    [EmailAddress] [nvarchar](100) NOT NULL,
    [Password] [nvarchar](50) NOT NULL,
    [SecurityQuestionID] [int] NOT NULL,
    [SecurityAnswer] [nvarchar](50) NOT NULL,
    [PhoneNumber1] [nvarchar](50) NULL,
    [PhoneNumber2] [nvarchar](50) NULL,
    [Fax] [nvarchar](50) NULL,
    [CompanyID] [int] NULL,
    [DateCreated] [smalldatetime] NOT NULL,
    [DateModified] [smalldatetime] NOT NULL,
    [DateLastLogin] [smalldatetime] NOT NULL,
    [UserIDModified] [int] NULL,
    [StatusID] [int] NOT NULL,
    [Notes] [ntext] NULL,
    [IsForceLogOff] [bit] NOT NULL
)

Refer to the above sql

A: The typical suspect is that at runtime the application is using a different database instance than the one you are checking. With a breakpoint verify the connection string used /w var conn = DbEntity.Database.Connection.ConnectionString (EF6) or DbEntity.Database.GetDbConnection().ConnectionString for pre-EFCore 5, or DbEntity.Database.ConnectionString for EF Core 5. (thank you Microsoft...)
In your example, the use of the TransactionScope is completely unnecessary, and in cases where a TransactionScope would be practical, you have them the wrong way around. TransactionScope should be the outer-most boundary, with the using (var DbEntity = ... being declared inside the scope.
TransactionScopes add an additional cost to processing and would be used to coordinate transactions between the DbContext operations and other external operations, such as operations with other DbContexts or other services etc. that comply with transaction commit/rollback strategies. DbContexts inherently operate with a Transaction internally so it doesn't matter how many entities you update within the scope of a DbContext and it's SaveChanges call, they will be saved within a single transaction.


text:
Q: SSIS On Error Event Handler sending multiple emails on error I have set up a Script Email task as part of the OnError Event Handler in a SSIS package. But on error the event handler sends multiple emails. Understanding the reason of that I tried to implement the solution suggested in the following thread but that is not working for me. I am having an issue similar to one of the commentators where condition @[System::SourceID]== @[System::PackageID] always evaluates to False so no email is being sent out at all now instead of multiple ones. I am using SQL Server 2012.
SSIS send email on error sending multiple errors
PS: I could not add comment to this thread due to lack of reputation points, so I had to start a new one.
Thanks,
KK

A: The way I have resolved the multiple exception issue in the past is

*

*Only raise email / log errors from master packages

*Add ErrorCounter variable and set to zero

*Inside the OnError handler increase the on error count by 1

*Add a precedence constraint expression @[User::ErrorCounter]<=1

*Send email or log error from that precedence constraint

that way you will only record one error per set of parent / child package failures

A: I always use @[System::SourceName] ==  @[System::PackageName]

Enlarge


text:
Q: How to set proxy without credentials to WebClient c.net I have a proxy and port number but don't have credentials .how can iset the webclient to go through that proxy ,the below code is giving error
string proxyserver = "http://10.0.0.127:8080/";
    IWebProxy proxy = new WebProxy(proxyserver);
    proxy.Credentials = CredentialCache.DefaultCredentials;
    WebClient.Proxy = proxy;
     byte[] rawResponse = WebClient.UploadFile(url, filename);

If i use CredentialCache i don't have authenticationtype and networkcredential. Is there any other way to assign my proxy to the WebClient
thanks,
michaled

A: Unless the code you have supplied is only a portion of your actual code, you will need to associate the proxy created with the WebClient object using the Proxy property (See documentation below):
WebClient.Proxy Property
If you are already doing so then disregard this.


text:
Q: Does Scala have a statement equivalent to ML's "as" construct? In ML, one can assign names for each element of a matched pattern:
fun findPair n nil = NONE
| findPair n (head as (n1, _))::rest =
    if n = n1 then (SOME head) else (findPair n rest)

In this code, I defined an alias for the first pair of the list and matched the contents of the pair. Is there an equivalent construct in Scala?

A: You can do variable binding with the @ symbol, e.g.:
scala> val wholeList @ List(x, _*) = List(1,2,3)
wholeList: List[Int] = List(1, 2, 3)
x: Int = 1

A: I'm sure you'll get a more complete answer later as I'm not sure how to write it recursively like your example, but maybe this variation would work for you:
scala> val pairs = List((1, "a"), (2, "b"), (3, "c"))
pairs: List[(Int, String)] = List((1,a), (2,b), (3,c))

scala> val n = 2
n: Int = 2

scala> pairs find {e => e._1 == n}
res0: Option[(Int, String)] = Some((2,b))

OK, next attempt at direct translation. How about this?
scala> def findPair[A, B](n: A, p: List[Tuple2[A, B]]): Option[Tuple2[A, B]] = p match {
     | case Nil => None
     | case head::rest if head._1 == n => Some(head)
     | case _::rest => findPair(n, rest)
     | }
findPair: [A, B](n: A, p: List[(A, B)])Option[(A, B)]


text:
Q: How to set current sequence while converting primary key serial(integer) to bigserial(bigint) The table already has few thousands of rows and I want to convert the primary key from Integer to BigInteger. How to change the sequence for biginteger?
--Create new temp sequence (sequence-name1) for bigint
CREATE SEQUENCE public.case_audit_case_audit_uid_seq1
    INCREMENT 1
    START 5542
    MINVALUE 1
    MAXVALUE 9223372036854775807
    CACHE 1;
ALTER SEQUENCE public.case_audit_case_audit_uid_seq1  OWNER TO postgres;
--Alter column to bigint
ALTER TABLE public.case_audit ALTER COLUMN case_audit_uid TYPE bigint;
--Alter pk column with temp Sequence
ALTER TABLE public.case_audit ALTER COLUMN case_audit_uid SET DEFAULT     nextval('indsolv.case_audit_case_audit_uid_seq1'::regclass);
--Drop original sequence
DROP SEQUENCE public.case_audit_case_audit_uid_seq;
--Create new sequence for bigint with original sequence name
CREATE SEQUENCE public.case_audit_case_audit_uid_seq
    INCREMENT 1
    START 5542
    MINVALUE 1
    MAXVALUE 9223372036854775807
    CACHE 1;
ALTER SEQUENCE public.case_audit_case_audit_uid_seq OWNER TO postgres;
---Set original sequence
ALTER TABLE public.case_audit ALTER COLUMN case_audit_uid SET DEFAULT nextval('public.case_audit_case_audit_uid_seq'::regclass);
---Drop temp sequence
DROP SEQUENCE public.case_audit_case_audit_uid_seq1;

Is there any simple solution compare to this?

A: PgAdmin4 has no option to modify graphically but as per PostgreSQL Document, we can alter the sequence data type to smallint, integer, and bigint
Alter table column & sequence data type and set max value for the sequence
ALTER SEQUENCE public.case_audit_case_audit_uid_seq AS bigint;
ALTER SEQUENCE public.case_audit_case_audit_uid_seq MAXVALUE 9223372036854775807;
ALTER TABLE public.case_audit ALTER COLUMN case_audit_uid TYPE bigint;


text:
Q: Azure AD Intranet Login Portal I'm trying to make an Intranet page for staff they authenticate into to see personalized information.
I'm currently trying to use Azure AD App registrations and PHP. I have the following code so far then I become stuck:
LOGIN

Then:
$get_code = $_GET['code'];

$ch = curl_init();
curl_setopt_array($ch, array(
    CURLOPT_URL => 'https://login.microsoftonline.com/website.co.uk/oauth2/token',
    CURLOPT_POST => 1,
    CURLOPT_POSTFIELDS => array(
        "grant_type" => "authorization_code",
        "client_id" => "xyzxyzyxzxyzxyzyxzxyzxyzyxzxyzxyzyxz",
        "code" => $get_code,
        "redirect_uri" => "https://website2.com/login/authentication",
        "client_secret" => "hgdfyuieshafguirhuiqagfhuirehguirej",
        "resource" => "Microsoft.Azure.ActiveDirectory"
    )
));
$result = curl_exec($ch);
curl_close($ch);

This all seem to work and I get an Access token back.
In the Required permissions on Azure AD it just has the default:
"Windows Azure Active Directory (Microsoft.Azure.ActiveDirectory) /
Sign in and read user profile"
I'm also requesting the "resource" as "Microsoft.Azure.ActiveDirectory". Is this resource correct and how do I now read the users profile? Thanks


text:
Q: How to get the decision tree built at an iteration of the Ada boosting package in R? I have built a boosting model with 50 decision trees using the "ada" package in R. How can I print the decision tree built at a iteration of "ada"?
I can use the "print" function to display the detail of a "rpart" object, is there any similar function to print the decision trees built in an "ada" object?
Thank you very much!
My sample code is like below:
    library(ada)
    data("soldat")
    model <- ada(y ~ .
               , data=soldat
               , loss="e"
               , type="discrete"
               , iter=50
               , control=rpart.control(cp=-1, maxdepth=2))

A: The trees are stored in the list model$model$trees
These are rpart objects so you can use print, plot etc., just as when calling rpart.
So, for instance to plot the 5th tree:
plot(model$model$trees[[5]])
text(model$model$trees[[5]])


text:
Q: TypeError: bodyParser.urlencoded is not a function app.use(bodyParser.urlencoded({extended: true}));

this always show the above problem in the console. If anybody has face it before, then help me. thank you!

A: If you are using Express version below 4.16,
npm i body-parser

Now in your main app.js or server.js or index.js file, require body-parser as shown below,
const bodyParser = require('body-parser')

This should resolve your error.
If you are using Express above v4.16 you don't need to add an additional body-parser package to your application
Replace
app.use(bodyParser.urlencoded({extended: true}))

with
app.use(express.urlencoded()); //Parse URL-encoded bodies

References:

*

*https://medium.com/@mmajdanski/express-body-parser-and-why-may-not-need-it-335803cd048c

*https://github.com/expressjs/body-parser


text:
Q: Create a war file including external jars using command prompt I have two projects - Project1 and Project2. Project1 contains all the java classes. And project2 contains all the jar files required in project1. Means, Project1 depends on Project1 (for jars).
I am using Glassfish server. While creating the war file of Project1, I included all the jar files from project2.
Example:
Project2 conatins 2 packages - POI and web-services.
POI package contains: poi-examples-3.6-20091214.jar,poi-contrib-3.6-20091214.jar, poi-ooxml-3.6-20091214.jar, poi-ooxml-schemas-3.6-20091214.jar, poi-scratchpad-3.6-20091214.jar.
web-services package contains: javax.servlet-3.0.jar, javax.servlet-api.jar, jersey-bundle-1.10.jar, jersey-client-1.12.jar, jersey-core-1.12.jar, jersey-multipart-1.4.jar.
Now for creating the war file for Project1 from command prompt, I used the following command:
jar cvf Project1.war D:\JavaProject\Project2\lib\external\poi\poi-examples-3.6-20091214.jar D:\JavaProject\Project2\lib\external\poi\poi-contrib-3.6-20091214.jar D:\JavaProject\Project2\lib\external\poi\poi-ooxml-3.6-20091214.jar D:\JavaProject\Project2\lib\external\poi\poi-ooxml-schemas-3.6-20091214.jar D:\JavaProject\Project2\lib\external\poi\poi-scratchpad-3.6-20091214.jar D:\JavaProject\Project2\lib\external\web-services\javax.servlet-3.0.jar D:\JavaProject\Project2\lib\external\web-services\javax.servlet-api.jar D:\JavaProject\Project2\lib\external\web-services\jersey-bundle-1.10.jar D:\JavaProject\Project2\lib\external\web-services\jersey-client-1.12.jar D:\JavaProject\Project2\lib\external\web-services\jersey-core-1.12.jar D:\JavaProject\Project2\lib\external\web-services\jersey-multipart-1.4.jar

Project1.war file created in the current directory.
But, when I tried to deploy the Project1.war on Glassfish server, I encountered this error:
C:\glassfish3\glassfish\domains\domain1\applications\Project1\D:\JavaProject\Project2\lib\external\poi\poi-contrib-3.6-20091214.jar

(C:\glassfish3\glassfish\domains\domain1\applications\ is the directory where '.war' files are copied after deployment)
I could not understand the problem. Is something wrong with the command, I executed for creating war file? How are external jars included while creating war file using command line prompt?
Please help.. Thanks in advance!

A: A WAR file has to have a specific file structure.
/
    META-INF/
    WEB-INF/
        classes/
             classes and other classpath resources go here
        lib/
             jar files go here
        web.xml
    other webapp stuff; e.g. HTML, JSPs, CSS ...

If you just throw stuff into a JAR file at random, it won't be recognizable as a webapp when it is unpacked by the webapp container.

A: You should be using the WAR exploded layout, in other words, project2 should be included at $PROJECT1_DEPLOYMENT_DIR/WEB-INF/lib and so on. Then your jar command will result in a deployable file to Glassfish or any other servlet container.


text:
Q: Longest increasing sequence of nodes in a graph Recently attended a MSFT interview for SDET position.. The 2nd round interviewer asked me this question:
Given a graph which has a number in the node value, find the set of all increasing sequence of vertices which are connected. Not able to recall the exact question.. The guy seemed very hostile and was refuting each of my solutions.. Any one knowing any such question.. Finally the solution was to have an adjacency matrix..
Still not sure how this will work..

A: The first step is to turn the bidirectional edges into directional edges, only going from the smaller to the larger numbered node for each one. Note that the resulting graph will be a directed acyclic graph (DAG), since we can't go from a small-high-small number in a path. From here on we can ignore the node numbering.
We have now reduced the problem to the longest path problem. The solution (described in detail in the link) is to perform a topological sort on the graph and then use dynamic programming to find the longest path.
All of this can be achieved in linear time.


text:
Q: Uglifying Template Strings Webpack I'm using node-fetch to send over GraphQL requests in a lambda function. The requests are written as template strings; they therefore naturally are formatted and displayed "beautifully" by my IDE.
Just to save bandwidth, is there any way I can use Webpack to "uglify" these strings, for instance to remove the \n characters when compiling my Typescript file?
Thank you!

A: This depends on how you're loading the files in webpack. The babel plugin doesn't have a minify option. Neither does the loader from graphql-tag. Other loaders, like this one, do.


text:
Q: How to dynamically update the record in DynamoDB in Python? I am trying to update records in dynamodb table dynamically.
table structure is like this:
host_name, host_id hostClass column1 column2 column3 column4 .... column10

my function is like this:
def update_column_info(host_name, host_id, column_name):
    table = self.client.Table(my_test_table)
    try:
        response = table.update_item(
           Key={PARTITION_KEY: str(host_name),
             SORT_KEY: str(host_id)},
             UpdateExpression='SET hostClass=:hostClass',
             ExpressionAttributeValues={':hostClass': column_value}
    except Exception as e:
        print("failed", e)

This worked to update column hostClass.
But I am trying to update it dynamically in which I don't need to pass the column name separately and trying to do similar thing which is mentioned in this post for javascript.
but I am trying it for python and couldn't figure out the proper syntax.


text:
Q: Find string from a list and see if partially in an another list So im trying to loop in the list A to find the elements from the list D and get something like this in the result:
Result="F10,12 ;FR300,157-159; FR300,161-162; FR300,183-184; FR300,185-186; FR300,187-188; FR300,191-192"

List<String> D= ("D","F10","FR300","FR300" )
List<String> A=("F10,12  | FR600,191-192 | FR400,191-192  | FR300,191-192  | FR300,187-188  | FR300,185-186  | FR300,183-184  | 3D  | FR300,157-159  | 1D  | FR300,161-162  | 300D")

String[] split_A = A.split("[|]")
String[] split_D = D.split("[,]")
for (s in split_A){
    for (item in split_D){
       if (item in s){
          println "Result"+ s
       }
    }
}

So my question is how to find the matches and be able to get somthing like the Result i have tried to use contains() but it didnt work correcly and i can't really add a variable with the specefic value like var=FR300,F10 cause i need to find somthening that will work if i run the script on a table that contain more than 400 records and the value from the column D can change ...
Thank you for your tips !

A: Okay Finaly i did it like this .. i know it's not the best way
String[] split_A = A.split("[|]")
Set<String> myset = new HashSet<>();
String [] split_D = D.split("[,]");
for(int i=0;i<split_D.length;i++){
        myset.add(split_D[i]);
}
for (String elem1: myset){
    for (elem2 in split_A){
        if( elem2.contains(elem1)){
            if (elem1!="D"){
                println elem2+"Found match"
            }
        }
    }
}

A: Another alternative will be as follow :
for (String elem1: myset){
    for (elem2 in split_A){
        if( elem2.contains(elem1)){
            if (elem1!="D"){
//              println elem2+"Found match"
                Result.add([elem2])
            }
        }
    }
}
println Result