text:
Q: What process does professional website building follow? I've searched for a while, but I can't find anything related on Google or here.
Me and some friends were debating starting a company, so I figure it might be good to do a quick pilot project to see how well we can work together. We have a designer who can do HTML, CSS and Flash, enjoys doing art, but doesn't like to do HTML and CSS... And 2 programmers that are willing to do anything.
My question is, from an experienced site builder's perspective, what steps do we do - in chronological order - to properly handle a website? Does the designer design the look and feel of the site, then the programmers fill in the gaps with functionality? Or do the programmers create a "mock-up" of the site with most of the functionality, then the designer spices it up? Or is it more of a back-and-forth process?
I just want to know how a professional normally handles it.
Update:
   A recap taking some of the notes from each post.

Step 1: Define requirements. What will your site/application do?
Step 2: Use cases. Who will use the application, and what will they do with it? This doesn't have to be done with a bunch of crazy UML diagrams, just use whatever visual aids you think work best for you. Find a CMS vendor, or a search vendor, or both. While planning, maybe do some competitor analysis, and see how those in similar fields have done theirs.
Step 3: Visual proof-of-concept. This is done by your designer, NOT your programmers... Programmers are notoriously bad at UI. Use an image program like Photoshop, not an HTML editor. Leave it fluid and simple at first. Select the three-color theme for the site (two primaries and an accent.) Get a sense of how you want to lay things out, keeping in mind the chosen CMS and/or search functionality. Focus hard on usability, add pizzaz later. Turn the created concept into JPEG mock-ups, or create a staging site to allow the client to view the work. A staging site will allow for future releases to be tested prior to moving it to production.
Step 4: Once the site is conceptualized by your designers, have your HTML/CSS developer turn it into markup. He/she should shoot for XHTML compliance and test on as many major browsers as you can. Also a good time to set up versioning/bug tracking/management systems, to keep track of changes, bugs, and feedback.
Step 5: Have your programmers start turning your requirements into software. This can and should be done in parallel with Step 4- there's no reason they can't be coding up the major pieces and writing tests while the UI is designed and developed.
Step 6: Marry up the final UI design with the code. Test, Test, Test!!
Step 7: Display end result to client, and get client sign-off.
Step 8: Deploy the site to production.
Rinse, Repeat...

A: Step 1: Define requirements.  What will your site/application do?
Step 2: Use cases.  Who will use the application, and what will they do with it?  This doesn't have to be done with a bunch of crazy UML diagrams, just use whatever visual aids you think work best for you.
Step 3:  Visual proof-of-concept. This is done by your designer, NOT your programmers.  Use an image program like Photoshop, not an HTML editor.  Leave it fluid and simple at first.  Select the three-color theme for the site (two primaries and an accent.)  Get a sense of how you want to lay things out.  Focus hard on usability, add pizzaz later.
Step 4: Once the site is conceptualized by your designers, have your HTML/CSS developer turn it into markup.  He/she should shoot for XHTML compliance and test on as many major browsers as you can.
Step 5:  Have your programmers start turning your requirements into software.  This can and should be done in parallel with Step 4- there's no reason they can't be coding up the major pieces and writing tests while the UI is designed and developed.
Step 6:  Marry up the final UI design with the code.  Test, Test, Test!!
Rinse, Repeat...

A: As a first step, I'd recommend doing a bit of up-front design using an approach such as paper prototyping, to lock down what it is you want your website to do, and roughly how you want it to look.
Next up, read up on the Agile approach to software development and see if you like the sound of what it suggests. It tends to work best with smaller, well-motivated teams.
Figure out the minimum amount of functionality you can create that you can deliver as a product so that you can get user feedback as soon as possibly. Then expect to iteratively add functionality to the product over time.

A: There is no one universal way. Every shop does it differently. Hence, a warning: gross generalizations follow.
Web development typically consists of much shorter release cycles, because it's so simple to push out a release, compared to client-side software. Thus the more "agile" methods are more frequently used than the "waterfall" models encountered in developing client software.

A: *

*Figure out what, exactly, you're building.

*Take care of all the legal stuff (e.g. what business entity you'll be forming, how will each team member be compensated for their work, will there be health benefits, etc).

*Mockups. I suggest having the designers do the mockups since programmers are notoriously bad at UI design.

*Set up some sort of bug tracking / case management system so that you have a centralized place for all your feature requests and bug reports.

*Start coding.

*Once you have a simple version of your app, get some people to test it out to make sure you're on the right path.

*???

*Profit!

A: The Web Style Guide provides a pretty detailed overview of the process.

A: Just to give something on the other side of the coin.  Where I work, we have for the past couple of years, worked on a redesign of the company's website.  Here are some highlights of the process:

*

*Identify vendors for various functions that will be needed.  In this case that meant finding a Content Management System vendor as well as a Search vendor.

*Get a new design for the site that can be applied to what was selected in the first step.

*Using system integrators and in-house developers, start to build some of the functionality for the site and take the flexible, customizable software in 1 and make it useful for the organization.  Note that this is where a couple of years have been spent getting this working and some business decisions ironed out.

*Release a preview site to verify functionality and fix bugs, add enhancements as needed.
Note that in your case you may not have the same budget but there are various CMS frameworks out there to select as well as how much integration do you want to have for the site?  Does it have to talk to a half-dozen different systems?  In the case I mentioned above there are CRM integrations, ESB integrations, search integrations, and translation integrations to give a few examples of where things had to be wired up correctly.

In response to the comment, be sure you and the client know what is meant by "simple" as if there is any e-commerce functionality, forums, or personalization these are examples where it can be important to know what is needed now and have an idea of what is needed down the road as there can likely be a ton of things that customers may want but you have to figure out some of the nitty-gritty details at points in the future.  For example, some people may think that Google is simple, and from an end-user perspective it is though how many computers does Google have running how many different applications doing how much processing 24/7?  Quite a bit, I'd imagine.  Simple is good, but sometimes making something look simple can be incredibly hard to do.

A: You should mix and match the lists provided here for your needs.
I just want to make sure you know one thing...
Customers are "stoopid" when it comes to web design.
You will have to claw, scrape, drag, gnash, rip, and extricate every requirement from their naive little souls.  If you fail to do so? Guess who gets the blame?
The road you now look down is a hard one filled with competition, stress, and risk.  It requires endurance, faith, patience, and the ability to eat ramen 5 of 7 days a week.

A: To add (or repeat) Dave Swersky's list.

*

*Gather requirements from clients

*Do some competitor analysis.  Gather
screen shots of competitor sites.

*Build a sitemap /wireframe - What is
the structure/content of the site?

*Get designers to create JPG mockups.
They may use the screen shots for
"inspiration"

*Get feedback from
clients based on JPEG's

*Create HTML
mockups from JPEG's

*Get feedback
from clients.  Go back to step 4 if
necessary

*Implement HTML using
technology of choice

*Unit test the site

*UAT and obtain sign off.

*Deploy to live
client feedback is critical, they should be involved in every step to ensure a successful implementation.
Hope this helps

A: In addition to the steps outlined in other answers, I'd add this (to be added somewhere near the end of the "cycle"):
x. Once you have a more or less end to end solution, set up a staging site.
y. Get client sign off on staging site.
z. Deploy to production site.
Celebrate! But not too hard, there's almost always going to be a few iterations of changes, because users rarely know exactly what they really want the first time around.
So, when (not if), the client asks for changes, you can work on the changes and promote them to the staging site first! This is important because a) it gives clients a chance to preview changes before the whole world sees them b) if the integrity of the data on the production site is important, you can hopefully weed out any issues on the staging site before they impact production data.


text:
Q: N number of prior business days to extract I need to get the nth previous business date
BEGIN
    SELECT holiday_ind
      INTO v_holiday_ind
      FROM holiday_calendar
       AND bus_date = L_bus_dt;
EXCEPTION
    WHEN OTHERS THEN
          V_holiday_ind='N'
END;

Now the user will input one date and an integer say n
I have to subtract n business days from the input date and give the output
For example if the user inputs May 26 2015 and 2 , the output should be May 20 2015 because may 25 2015 is memorial day and may 23 2015 sat and may 24 2015 sun
I tried following
FOR i IN 1..n
LOOP
BEGIN
   SELECT holiday_ind
     INTO v_holiday_ind
     FROM holiday_calendar
      AND bus_date = L_bus_dt;
    EXCEPTION
        WHEN OTHERS THEN
          V_holiday_ind='N'
    END;
    L_bus_date := L_bus_date - n;
END LOOP;

But not working
Please help

A: There is syntax error in your code snippet and I think usage of FOR LOOP might not be that appropriate.
Here I assume that holiday_calendar contain information for weekends also.
The code will be something like this
begin
    while n > 0
    loop
        if l_bus_dt is holiday / weekend then
            l_bus_dt = l_bus_dt - 1
        otherwise
            l_bus_dt = l_bus_dt - 1
            n = n - 1
        end if
    end loop
end

hope this helps.

redpajama_set_name: RedPajamaStackExchange


text:
Q: Why I have this black screen running flutter Making this app calendar, shows me this black screen when I run the application, this is what I mean:

As you can see, I can't see the numbers either the days of the week, so how to solve this issue, to change background color black to white, I don't know if I have to change some properties colors, but in my understanding the default color is white with blue
This is my code:
(in the puspec.yaml, I'm using sync_fusion_calendar)
import 'dart:math';

import 'package:flutter/material.dart';
import 'package:syncfusion_flutter_calendar/calendar.dart';

void main() {
  runApp(MyApp());
}

class MyApp extends StatelessWidget {
  // This widget is the root of your application.
  @override
  Widget build(BuildContext context) {
    return MaterialApp(
      title: 'Flutter Demo',
      debugShowCheckedModeBanner: false,
      theme: ThemeData(
        // This is the theme of your application.
        //
        // Try running your application with "flutter run". You'll see the
        // application has a blue toolbar. Then, without quitting the app, try
        // changing the primarySwatch below to Colors.green and then invoke
        // "hot reload" (press "r" in the console where you ran "flutter run",
        // or simply save your changes to "hot reload" in a Flutter IDE).
        // Notice that the counter didn't reset back to zero; the application
        // is not restarted.
        primarySwatch: Colors.blue,
      ),
      home: MyHomePage(title: 'Flutter Demo Home Page'),
    );
  }
}

class MyHomePage extends StatefulWidget {
  MyHomePage({Key? key, required this.title}) : super(key: key);

  // This widget is the home page of your application. It is stateful, meaning
  // that it has a State object (defined below) that contains fields that affect
  // how it looks.

  // This class is the configuration for the state. It holds the values (in this
  // case the title) provided by the parent (in this case the App widget) and
  // used by the build method of the State. Fields in a Widget subclass are
  // always marked "final".

  final String title;

  @override
  _MyHomePageState createState() => _MyHomePageState();
}

late Map<DateTime, List<Appointment>> _dataCollection;

class _MyHomePageState extends State<MyHomePage> {
  late var _calendarDataSource;

  @override
  void initState() {
    _dataCollection = getAppointments();
    _calendarDataSource = MeetingDataSource(<Appointment>[]);
    super.initState();
  }

  @override
  Widget build(BuildContext context) {
    return SfCalendar(
      view: CalendarView.month,
      monthViewSettings: MonthViewSettings(
          appointmentDisplayMode: MonthAppointmentDisplayMode.appointment),
      dataSource: _calendarDataSource,
      loadMoreWidgetBuilder:
          (BuildContext context, LoadMoreCallback loadMoreAppointments) {
        return FutureBuilder(
          future: loadMoreAppointments(),
          builder: (context, snapShot) {
            return Container(
              alignment: Alignment.center,
              child: CircularProgressIndicator(
                valueColor: AlwaysStoppedAnimation(Colors.blue),
              ),
            );
          },
        );
      },
    );
  }

  Map<DateTime, List<Appointment>> getAppointments() {
    final List<String> _subjectCollection = <String>[];
    _subjectCollection.add('General Meeting');
    _subjectCollection.add('Plan Execution');
    _subjectCollection.add('Project Plan');
    _subjectCollection.add('Consulting');
    _subjectCollection.add('Support');
    _subjectCollection.add('Development Meeting');
    _subjectCollection.add('Scrum');
    _subjectCollection.add('Project Completion');
    _subjectCollection.add('Release updates');
    _subjectCollection.add('Performance Check');

    final List<Color> _colorCollection = <Color>[];
    _colorCollection.add(const Color(0xFF0F8644));
    _colorCollection.add(const Color(0xFF8B1FA9));
    _colorCollection.add(const Color(0xFFD20100));
    _colorCollection.add(const Color(0xFFFC571D));
    _colorCollection.add(const Color(0xFF36B37B));
    _colorCollection.add(const Color(0xFF01A1EF));
    _colorCollection.add(const Color(0xFF3D4FB5));
    _colorCollection.add(const Color(0xFFE47C73));
    _colorCollection.add(const Color(0xFF636363));
    _colorCollection.add(const Color(0xFF0A8043));

    final Random random = Random();
    var _dataCollection = <DateTime, List<Appointment>>{};
    final DateTime today = DateTime.now();
    final DateTime rangeStartDate = DateTime(today.year, today.month, today.day)
        .add(const Duration(days: -1000));
    final DateTime rangeEndDate = DateTime(today.year, today.month, today.day)
        .add(const Duration(days: 1000));
    for (DateTime i = rangeStartDate;
    i.isBefore(rangeEndDate);
    i = i.add(Duration(days: 1 + random.nextInt(2)))) {
      final DateTime date = i;
      final int count = 1 + random.nextInt(3);
      for (int j = 0; j < count; j++) {
        final DateTime startDate = DateTime(
            date.year, date.month, date.day, 8 + random.nextInt(8), 0, 0);
        final int duration = random.nextInt(3);
        final Appointment meeting = Appointment(
            subject: _subjectCollection[random.nextInt(7)],
            startTime: startDate,
            endTime:
            startDate.add(Duration(hours: duration == 0 ? 1 : duration)),
            color: _colorCollection[random.nextInt(9)],
            isAllDay: false);

        if (_dataCollection.containsKey(date)) {
          final List<Appointment> meetings = _dataCollection[date]!;
          meetings.add(meeting);
          _dataCollection[date] = meetings;
        } else {
          _dataCollection[date] = [meeting];
        }
      }
    }
    return _dataCollection;
  }
}

class MeetingDataSource extends CalendarDataSource {
  MeetingDataSource(List<Appointment> source) {
    appointments = source;
  }

  @override
  Future<void> handleLoadMore(DateTime startDate, DateTime endDate) async {
    await Future.delayed(Duration(seconds: 1));
    final List<Appointment> meetings = <Appointment>[];
    DateTime appStartDate = startDate;
    DateTime appEndDate = endDate;

    while (appStartDate.isBefore(appEndDate)) {
      final List<Appointment>? data = _dataCollection[appStartDate];
      if (data == null) {
        appStartDate = appStartDate.add(Duration(days: 1));
        continue;
      }
      for (final Appointment meeting in data) {
        if (appointments!.contains(meeting)) {
          continue;
        }
        meetings.add(meeting);
      }
      appStartDate = appStartDate.add(Duration(days: 1));
    }
    appointments!.addAll(meetings);
    notifyListeners(CalendarDataSourceAction.add, meetings);
  }
}

Thank you in advance

A: Wrap the sfcalendar with a scaffold. And give sfcalendar as the body of the scaffold
Scaffold(
body: SFCalendar()
)


text:
Q: Setting height of image view in android I want to add a background image to my linear layout containg 2 text views.. I did that using a frame layout.. But the image is not scaling according to the size of my linear layout.. can anyone help ? The following is my layout file
    <FrameLayout xmlns:android="http://schemas.android.com/apk/res/android"
    xmlns:tools="http://schemas.android.com/tools"
    android:id="@+id/FrameLayout1"
    android:layout_width="match_parent"
    android:layout_height="match_parent"
    >

    <ImageView
        android:id="@+id/imageView1"
        android:layout_width="match_parent"
        android:layout_height="wrap_content"
        android:src="@drawable/button_update_normal" />

    <LinearLayout
        android:layout_width="match_parent"
        android:layout_height="match_parent"
        android:orientation="vertical" >

        <TextView
            android:layout_width="wrap_content"
            android:layout_height="wrap_content"
            android:text="@string/hello_world" />

        <TextView
            android:id="@+id/textView1"
            android:layout_width="wrap_content"
            android:layout_height="wrap_content"
            android:text="TextView" />

    </LinearLayout>

</FrameLayout>

A: You can set background of linear layout by
android:background="imagename"

A: You can use android:background attribute of your LinearLayoutr. Set image as linear layout background.

A: In your ImageView, change android:layout_height="wrap_content" to android:layout_height="fill_parent"

A: I'll suggest you a simpler way. U don't actually need a framelayout to do wat you are trying to do. U can set your background image in your linearlayout itself. See the following code.
<LinearLayout
    android:layout_width="match_parent"
    android:layout_height="match_parent"
    android:orientation="vertical"
    android:background= "@drawable/yourBackgroundImage >

    <TextView
        android:layout_width="wrap_content"
        android:layout_height="wrap_content"
        android:text="@string/hello_world" />

    <TextView
        android:id="@+id/textView1"
        android:layout_width="wrap_content"
        android:layout_height="wrap_content"
        android:text="TextView" />

</LinearLayout>

A: android:background should work but this is another way to fit image acco
<RelativeLayout xmlns:android="http://schemas.android.com/apk/res/android"
xmlns:tools="http://schemas.android.com/tools"
android:id="@+id/FrameLayout1"
android:layout_width="match_parent"
android:layout_height="match_parent" >

<ImageView
    android:id="@+id/imageView1"
    android:layout_width="wrap_content"
    android:layout_height="wrap_content"
    android:layout_alignBottom="@+id/linearLayout1"
    android:layout_alignLeft="@+id/linearLayout1"
    android:layout_alignRight="@+id/linearLayout1"
    android:layout_alignTop="@+id/linearLayout1"
    android:scaleType="fitXY"
    android:src="@drawable/button_update_normal" />

<LinearLayout
    android:id="@+id/linearLayout1"
    android:layout_width="match_parent"
    android:layout_height="match_parent"
    android:orientation="vertical" >

    <TextView
        android:layout_width="wrap_content"
        android:layout_height="wrap_content"
        android:text="@string/hello_world" />

    <TextView
        android:id="@+id/textView1"
        android:layout_width="wrap_content"
        android:layout_height="wrap_content"
        android:text="TextView" />
</LinearLayout>


text:
Q: How do I copy an inherited class properties to another class that inherits the same class? I have three classes:

*

*Base

*Primary

*Secondary

Primary and Secondary inherit from Base. Base has several properties.
In one of the Primary methods, I will create a new Secondary class instance. Is there a way to copy the Base properties from Primary to Secondary w/o having to do it one by one?
If I do it one by one, it will be like:
Secondary.Property1 = Primary.Property1
Secondary.Property2 = Primary.Proprety2
I'm pretty sure there is a better way to do this.

A: You could use a library like AutoMapper. If it were my code I'd most likely simply map by hand, unless the sheer number of mappings made that unwieldy.


text:
Q: WPF problems refreshing textblock bound to console.stdout I am building a small wpf app in C#. When a button gets clicked a third
party dll function constructs a tree like object. This object is bound
to a treeview. This works fine but takes a bit of time to load. As the
dll function constructs the object it prints progress info to the
console. I want to redirect this into a TextBlock so that the user
gets to see the progress messages.
My window ctor looks like this:

InitializeComponent();
StringRedir s = new StringRedir(ref ProgressTextBlock);
Console.SetOut(s);
Console.SetError(s);
this.DataContext = s;

xaml:
<TextBlock Text="{Binding Path=Text}" Width="244"
x:Name="ProgressTextBlock" TextWrapping="Wrap"  />
<TreeView >...</TreeView>

The StringRedir class is shown below. The problem is the TextBlock for
some reason does not get updated with the messages until the TreeView
gets loaded. Stepping through I see the Text property being updated
but the TextBlock is not getting refreshed. I added a MessageBox.Show
() at the point where Text gets updated and this seems to cause the
window to refresh each time and I am able to see each message. So I
guess I need some way to explicitly refresh the screen...but this
doesnt make sense I thought the databinding would cause a visual
refresh when the property changed. What am I missing here? How do I
get it to refresh? Any advice is appreciated!
public class StringRedir : StringWriter , INotifyPropertyChanged
{
    private string text;
    private TextBlock local;

    public string Text {
        get{ return text;}
        set{
            text = text + value;
            OnPropertyChanged("Text");
        }
    }

    public event PropertyChangedEventHandler PropertyChanged;
    protected void OnPropertyChanged(string name)
    {
        PropertyChangedEventHandler handler = PropertyChanged;
        if (handler != null)
        {
            handler(this, new PropertyChangedEventArgs(name));
        }
    }

    public StringRedir(ref TextBlock t)
    {
        local = t;
        Text = "";
    }

    public override void WriteLine(string x)
    {
        Text = x +"\n";
        //MessageBox.Show("hello");
    }

}

A: You haven't included the code that is loading the data for the TreeView, but I'm guessing it's being done on the UI thread. If so, this will block any UI updates (including changes to the TextBlock) until it has completed.

A: So after doing some reading on the WPF threading model ( http://msdn.microsoft.com/en-us/library/ms741870.aspx ) I finally got it to refresh by calling Dispatcher Invoke() with Dispatch priority set to Render. As Kent suggested above UI updates in the dispatcher queue were probably low priority. I ended up doing something like this.
XAML
<TextBox VerticalScrollBarVisibility="Auto"
         Text="{Binding Path=Text, NotifyOnTargetUpdated=True}"
         x:Name="test" TextWrapping="Wrap" AcceptsReturn="True"
         TargetUpdated="test_TargetUpdated"/>

C# target updated handler code

private void test_TargetUpdated(object sender, DataTransferEventArgs e)
{
    TextBox t = sender as TextBox;
    t.ScrollToEnd();
    t.Dispatcher.Invoke(new EmptyDelegate(() => { }), System.Windows.Threading.DispatcherPriority.Render);
}

Note: Earlier I was using a TextBlock but I changed to a TextBox as it comes with scrolling
I still feel uneasy about the whole flow though. Is there a better way to do this?
Thanks to Matt and Kent for their comments. If I had points would mark their answers as helpful.

A: I believe the problem is in the constructor of your StringRedir class. You're passing in ProgessTextBlock, and you're doing this to it:
local.Text = "";

This is effectively overwriting the previously set value for ProgressTextBlock.Text, which was this:
{Binding Text}

See what I mean? By explicitly setting a value to the TextBlock's Text property, you've cancelled the binding.
If I'm reading right, it looks like the idea of passing a TextBlock into the StringRedir's ctor is a hangover from before you tried binding directly. I'd ditch that and stick with the binding idea as it's more in the "spirit" of WPF.


text:
Q: $I = \int_{c^{-a}}^{\infty} \left(1-\left(1-\frac{b}{1+x^{1/a}}\right)^{t}\right)\mathrm{d}x$, as $t \to \infty$ How to to find a closed-form expression for the following integral as $t \to \infty$:
$$I = \int_{c^{-a}}^{\infty} \left(1-\left(1-\frac{b}{1+x^{1/a}}\right)^{t}\right)\mathrm{d}x,$$
where $a \in (0, 1)$, $b \in (0, 1]$, $c > 0$, and $t > 0$?
My attempt: I tried using binomial expansion as $\left(1-\frac{b}{1+x^{1/a}}\right)^{t} = \sum_{k = 0}^{\infty}\binom{t}{k}\left(-\frac{b}{1+x^{1/a}}\right)^{k}$. Then
$$I = \int_{c^{-a}}^{\infty} \sum_{k = 1}^{\infty}\binom{t}{k}\left(-\frac{b}{1+x^{1/a}}\right)^{k}\mathrm{d}x.$$
I could not proceed from here.

A: $$
I(t) = \int_{c^{-a}}^{\infty} \left(1-\left(1-\frac{b}{1+x^{1/a}}\right)^{t}\right)\mathrm{d}x
 = a\int_{c^{-1}}^{\infty}y^{a-1} \left(1-\left(1-\frac{b}{1+y}\right)^{t}\right)\mathrm{d}y \\
= y^{a} \left(1-\left(1-\frac{b}{1+y}\right)^{t}\right)\Bigg|_{y=c^{-1}}^\infty  + {tb}\int_{c^{-1}}^{\infty}\frac{y^a}{(1+y)^2} \left(1-\frac{b}{1+y}\right)^{t-1}\mathrm{d}y\\  = K(t) + tb \int_0^{(1+c^{-1})^{-1}} \left(\frac{1-z}z\right)^a (1-bz)^{t-1} dz =: K(t) + J(t).
$$
Then, obviously, $K(t) = -c^{-a}+o(t^{-1})$, $t\to\infty$. The last integral can be analysed in a standard manner. Denote $d = (1+c^{-1})^{-1}$, and let $C$ be a large number. Rewrite the integral as
$$
\int_0^{C/(t-1)} \left(\frac{1-z}z\right)^a e^{(t-1)\log(1-bz)} dz + \int_{C/(t-1)}^d \left(\frac{1-z}z\right)^a e^{(t-1)\log(1-bz)} dz.
$$
Observe that $$\int_{C/(t-1)}^d \left(\frac{1-z}z\right)^a e^{(t-1)\log(1-bz)} dz\le \int_0^{d} z^{-a} e^{-Cb}dz = e^{-Cb}d^{1-a}/(1-a).$$
Further,
$$
\int_0^{C/(t-1)} \left(\frac{1-z}z\right)^a e^{(t-1)\log(1-bz)} dz\\
 = (t-1)^{a-1}\int_0^C u^{-a} \left(1-\frac{u}{t-1}\right)\exp\left\{(t-1)\log\left(1-\frac{bu}{t-1}\right)\right\}du \\
\sim t^{a-1}\int_0^C u^{-a}e^{-bu}du = (tb)^{a-1} \Gamma(1-a,C), t\to \infty.
$$
By letting $C\to\infty$ (I leave technicalities for you), we get
$$
J(t) \sim (tb)^a\Gamma(1-a), t\to\infty;
$$
the error seems to be $O(t^{a-1})$. As a result,
$I(t) = (tb)^a\Gamma(1-a) - c^{-a} + O(t^{a-1})$, $t\to\infty$.


text:
Q: RAISERROR on a trigger. What will happen? Will we get informed? What will happen if a trigger on a table hits the part of the trigger that includes the RAISERROR code below?
RAISERROR('Attempt to modify supposedly immutable number.',16,1)

How will we know this code was executed?

A: The errors generated by RAISERROR operate the same as errors generated by the Database Engine code. The values specified by RAISERROR are reported by the ERROR_LINE, ERROR_MESSAGE, ERROR_NUMBER, ERROR_PROCEDURE, ERROR_SEVERITY, ERROR_STATE, and @@ERROR system functions. When RAISERROR is run with a severity of 11 or higher in a TRY block, it transfers control to the associated CATCH block. The error is returned to the caller if RAISERROR is run:
Outside the scope of any TRY block.
With a severity of 10 or lower in a TRY block.
With a severity of 20 or higher that terminates the database connection.
If you are in trigger context, all errors terminate the batch and roll back the transaction on the spot.
When it comes to error handling in SQL Server, no rule is valid without an exception. Errors you raise yourself with RAISERROR do not abort the batch, not even in trigger context
There is one more way that a trigger can terminate the batch. This happens if @@trancount is 0 when the trigger exits. A trigger always executes in the context of a transaction, since even if there is no multi-statement transaction in progress each INSERT, UPDATE and DELETE statement is its own transaction in SQL Server, and the trigger is part of that transaction.
Doc


text:
Q: PHP round & ceiling not correctly parsing data The numbers that are being pulled from an xml file and then assigned to a variable but are outputted incorrectly. I'm not quite sure why or how to get around it.  An example is this.
$pricing_high = 1.15;
echo $pricing_high;

This displays 1.15 obviously. But when I assign this like so:
$price = ceil($pricing_high / 0.05) * 0.05;
echo $price;

This displays 2.
$price = round($pricing_high / 0.05) * 0.05;
echo $price;

This displays 1.
How do I get numbers to correctly round up to the nearest 5 cents when passing it like this?

A: As of PHP documentation for round function:
http://php.net/manual/en/function.round.php
You can specify precision as second parameter:
$pricing_high = 1.15;
$price = round($pricing_high / 0.05, 2) * 0.05;
echo $price;

Note value of second parameter 2

A: Is 1.15 = 1 dollar and 15 cents? If so:
echo sprintf('%.2f', round($price / 0.05) * 0.05); // Rounds to nearest
echo sprintf('%.2f', ceil($price / 0.05) * 0.05); // Rounds up

Tests:
$price = 1.13;

echo sprintf('%.2f', round($price / 0.05) * 0.05); // Outputs: 1.15
echo sprintf('%.2f', ceil($price / 0.05) * 0.05); // Outputs: 1.15

$price = 1.12;

echo sprintf('%.2f', round($price / 0.05) * 0.05); // Outputs: 1.10
echo sprintf('%.2f', ceil($price / 0.05) * 0.05); // Outputs: 1.15

If 1.15 = 1.15 cents then replace 0.05 with 5.

A: As ceil() and floor() don't have this precision, you might multiply your results and divide it after.


text:
Q: building a Qt application outside the Qt sourcetree I made a simple Qt application that's based on an Qt example application and builds fine from within the "examples" directory of the Qt sourcetree.
Now I want to move my project files to a different location but qmake fails to create a Makefile that can find the Qt header files.
The project files have been moved from ~/qt-everywhere-opensource-src-4.7.2/examples/webkit/fullscreenbrowser to  ~/cvswork/fullscreenbrowser/
So the .pro file is now ~/cvswork/fullscreenbrowser/fullscreenbrowser.pro
And the Qt sources are still at ~/qt-everywhere-opensource-src-4.7.2
qmake itself runs fine, but make fails to load some includes:
$ make
g++ -c -pipe -O2 -Wall -W -D_REENTRANT -DQT_NO_DEBUG -DQT_WEBKIT_LIB
-DQT_GUI_LIB -DQT_NETWORK_LIB -DQT_CORE_LIB
-I/usr/share/qt4/mkspecs/linux-g++
-I. -I/usr/include/qt4/QtCore -I/usr/include/qt4/QtNetwork
-I/usr/include/qt4/QtGui
-I/usr/include/qt4/QtWebKit
-I/usr/include/qt4
-I.
-o main.o main.cpp
main.cpp:41:17: error: QtGui: No such file or directory

For comparison, when building under the ...examples... directory, the first g++ call is much different:
$ make
g++ -c -pipe -fno-exceptions -O2 -Wall -W -D_REENTRANT -DQT_NO_DEBUG
-DQT_WEBKIT_LIB -DQT_GUI_LIB -DQT_NETWORK_LIB -DQT_CORE_LIB -DQT_HAVE_MMX
-DQT_HAVE_3DNOW -DQT_HAVE_SSE -DQT_HAVE_MMXEXT -DQT_HAVE_SSE2 -DQT_HAVE_SSE3
-DQT_HAVE_SSSE3 -DQT_HAVE_SSE4_1 -DQT_HAVE_SSE4_2 -DQT_HAVE_AVX -DQT_SHARED
-I../../../mkspecs/qws/linux-x86-g++
-I.
-I../../../include/QtCore
-I../../../include/QtNetwork
-I../../../include/QtGui
-I../../../include/QtWebKit
-I../../../include
-I.moc/release-shared-emb-x86
-o .obj/release-shared-emb-x86/main.o main.cpp

What do i have to configure so that the Qt source directory is found?

EDIT: The fullscreenbrowser.pro file can be seen here: http://pastebin.com/jUPJiWBC
EDIT2: I get the same behavior in the examples directory when adding -nocache to the qmake call.

A: The example probably attempts to include a file from elsewhere in the hierarchy. For simple cases you can often generate a new project file as follows:
qmake -project # generate a project file using defaults
qmake          # generate a makefile from the project file
make           # build using the makefile

qmake will go through your directory recursively examining and including files. It's not smart enough to figure out everything, like every module you may need, but it does a good job on simple test projects. I usually do the above for all my spikes.

A: That's actually more or less by design I think. Building inside the source folder needs to be a bit different than building against an installed tree, just to be able to do upgrades sanely for instance (prebuild everything in-place without referencing any existing build).
I believe that "trick" is done with a specific .qmake.cache file in the toplevel source folder (~/qt-everywhere-opensource-src-4.7.2 in your case) that is created when you configure the source tree (which happens to build qmake in there).
Try copying that file to your new build location (~/cvswork/fullscreenbrowser/ or ~/cvswork if you have other projects, it should look there too), and re-run qmake (making sure you use the one inside the Qt source directory).
This should work if you've simply configured the source tree.
Here's the first lines of that .qmake.cache file on my machine after having unpacked and configured an old Qt archive:
CONFIG +=  release shared dll largefile stl precompile_header mmx 3dnow sse sse2 sse3 ssse3 sse4_1 sse4_2 avx dylib create_prl link_prl depend_includepath fix_output_dirs QTDIR_build
QT_SOURCE_TREE = $$quote(/home/foo/src/qt-everywhere-opensource-src-4.7.3)
QT_BUILD_TREE = $$quote(/home/foo/src/qt-everywhere-opensource-src-4.7.3)
QT_BUILD_PARTS = libs tools examples demos docs translations
QMAKE_ABSOLUTE_SOURCE_ROOT = $$QT_SOURCE_TREE
QMAKE_MOC_SRC    = $$QT_BUILD_TREE/src/moc

#local paths that cannot be queried from the QT_INSTALL_* properties while building QTDIR
QMAKE_MOC        = $$QT_BUILD_TREE/bin/moc
QMAKE_UIC        = $$QT_BUILD_TREE/bin/uic
QMAKE_UIC3       = $$QT_BUILD_TREE/bin/uic3
QMAKE_RCC        = $$QT_BUILD_TREE/bin/rcc
QMAKE_QDBUSXML2CPP = $$QT_BUILD_TREE/bin/qdbusxml2cpp
QMAKE_INCDIR_QT  = $$QT_BUILD_TREE/include
QMAKE_LIBDIR_QT  = $$QT_BUILD_TREE/lib

QMAKE_LFLAGS    = -Wl,-rpath-link,$$QT_BUILD_TREE/lib $$QMAKE_LFLAGS
QT_CFLAGS_PSQL   = -I/usr/include/postgresql-8.4
QT_LFLAGS_PSQL   = -L/usr/lib64/postgresql-8.4/lib64
QT_CFLAGS_MYSQL   = -I/usr/include/mysql
QT_LFLAGS_MYSQL   = -Wl,-O1 -Wl,--as-needed -rdynamic -L/usr/lib64/mysql -lmysqlclient_r -L/usr//lib64 -lz -lpthread -lcrypt -lnsl -lm -lpthread -L/usr/lib64/ -lssl -lcrypto
Q    T_LFLAGS_ODBC   = -lodbc
QMAKESPEC = $$QT_BUILD_TREE/mkspecs/linux-g++-64
...

As you can see, a lot of the fundamental qmake variables are overridden with that build tree prefix.
(Not sure why you don't simply install Qt somewhere in your home directory. You wouldn't have any of this pain, and you don't need root for that I think as long as the prefix is your own - haven't tried that in ages though, so YMMV.)


text:
Q: Log without Exception stack trace in Serilog I am using Serilog and Serilog.Exceptions for structured logging purposes in my MVC5 application.
I want to remove the stack trace from the value of the "Exception" field in the log. I understand that I am using the new JsonFormatter() in the RollingFile sink, hence the exception object, say, ex, gets formatted as ex.ToString() and the entire object gets written as it is.
I am using new DestructuringOptionsBuilder().WithDefaultDestructurers() to show stack trace in "ExceptionDetails" section which looks much better as a separate field.
Is it possible to see only the name of the exception as a value of the "Exception" field in the log rather than the entire stack trace and other details as ex.ToString() while writing to a JSON file sink?
Here is my exception log:
{
  "Timestamp": "2021-09-02T15:04:02.4469999+05:00",
  "Level": "Error",
  "MessageTemplate": "Unhandled Exception",
  "Exception": "System.NullReferenceException: Object reference not set to an instance of an object.\r\n   at AppV2.Controllers.BaseController.Initialize(RequestContext requestContext) in E:\\Workspace\\AppV2\\AppV2\\Controllers\\BaseController.cs:line 115\r\n   at System.Web.Mvc.Controller.BeginExecute(RequestContext requestContext, AsyncCallback callback, Object state)\r\n   at System.Web.Mvc.Controller.System.Web.Mvc.Async.IAsyncController.BeginExecute(RequestContext requestContext, AsyncCallback callback, Object state)\r\n   at System.Web.Mvc.MvcHandler.<BeginProcessRequest>b__4(AsyncCallback asyncCallback, Object asyncState, ProcessRequestState innerState)\r\n   at System.Web.Mvc.Async.AsyncResultWrapper.WrappedAsyncVoid`1.CallBeginDelegate(AsyncCallback callback, Object callbackState)\r\n   at System.Web.Mvc.Async.AsyncResultWrapper.WrappedAsyncResultBase`1.Begin(AsyncCallback callback, Object state, Int32 timeout)\r\n   at System.Web.Mvc.MvcHandler.BeginProcessRequest(HttpContextBase httpContext, AsyncCallback callback, Object state)\r\n   at System.Web.Mvc.MvcHandler.BeginProcessRequest(HttpContext httpContext, AsyncCallback callback, Object state)\r\n   at System.Web.Mvc.MvcHandler.System.Web.IHttpAsyncHandler.BeginProcessRequest(HttpContext context, AsyncCallback cb, Object extraData)\r\n   at System.Web.HttpApplication.CallHandlerExecutionStep.System.Web.HttpApplication.IExecutionStep.Execute()\r\n   at System.Web.HttpApplication.ExecuteStepImpl(IExecutionStep step)\r\n   at System.Web.HttpApplication.ExecuteStep(IExecutionStep step, Boolean& completedSynchronously)",
  "Properties": {
    "UserName": "adminuser@mail.com",
    "ThreadId": 5,
    "Caller": "AppV2.Extensions.Logger.LogError(System.Exception, System.String, System.Object[])",
    "MachineName": "DESKTOP-GHV3V41",
    "HttpRequestId": "e9922caf-7e25-47f8-9941-263ba1ec4278",
    "HttpRequestNumber": 1,
    "HttpRequestClientHostIP": "::1",
    "HttpRequestType": "GET",
    "HttpRequestRawUrl": "/",
    "ExceptionDetails": {
      "Type": "System.NullReferenceException",
      "HResult": -2147467261,
      "Message": "Object reference not set to an instance of an object.",
      "Source": "Boilerplate.Web.Mvc5.Sample",
      "StackTrace": "   at AppV2.Controllers.BaseController.Initialize(RequestContext requestContext) in E:\\Workspace\\AppV2\\AppV2\\Controllers\\BaseController.cs:line 115\r\n   at System.Web.Mvc.Controller.BeginExecute(RequestContext requestContext, AsyncCallback callback, Object state)\r\n   at System.Web.Mvc.Controller.System.Web.Mvc.Async.IAsyncController.BeginExecute(RequestContext requestContext, AsyncCallback callback, Object state)\r\n   at System.Web.Mvc.MvcHandler.<BeginProcessRequest>b__4(AsyncCallback asyncCallback, Object asyncState, ProcessRequestState innerState)\r\n   at System.Web.Mvc.Async.AsyncResultWrapper.WrappedAsyncVoid`1.CallBeginDelegate(AsyncCallback callback, Object callbackState)\r\n   at System.Web.Mvc.Async.AsyncResultWrapper.WrappedAsyncResultBase`1.Begin(AsyncCallback callback, Object state, Int32 timeout)\r\n   at System.Web.Mvc.MvcHandler.BeginProcessRequest(HttpContextBase httpContext, AsyncCallback callback, Object state)\r\n   at System.Web.Mvc.MvcHandler.BeginProcessRequest(HttpContext httpContext, AsyncCallback callback, Object state)\r\n   at System.Web.Mvc.MvcHandler.System.Web.IHttpAsyncHandler.BeginProcessRequest(HttpContext context, AsyncCallback cb, Object extraData)\r\n   at System.Web.HttpApplication.CallHandlerExecutionStep.System.Web.HttpApplication.IExecutionStep.Execute()\r\n   at System.Web.HttpApplication.ExecuteStepImpl(IExecutionStep step)\r\n   at System.Web.HttpApplication.ExecuteStep(IExecutionStep step, Boolean& completedSynchronously)",
      "TargetSite": "Void Initialize(System.Web.Routing.RequestContext)"
    }
  }
}

Here is my Logger class:
public class Logger
{
    private static readonly ILogger logger;

    static Logger()
    {
        logger = new LoggerConfiguration()
            .Enrich.WithUserName(anonymousUsername: "Not Authenticated")
            .Enrich.FromLogContext()
            .Enrich.With(new ThreadEnrich())
            .Enrich.WithCaller()
            .Enrich.WithMachineName()
            .Enrich.WithHttpRequestId()
            .Enrich.WithHttpRequestNumber()
            .Enrich.WithHttpRequestClientHostIP()
            .Enrich.WithHttpRequestType()
            .Enrich.WithHttpRequestRawUrl()
            .Enrich.WithMvcRouteData()
            .Enrich.WithExceptionDetails(
                new DestructuringOptionsBuilder()
                .WithDefaultDestructurers())
            .Enrich.WithDemystifiedStackTraces()
            .WriteTo.RollingFile(new JsonFormatter(),
                HttpContext.Current.Server.MapPath($"~/logs/log-.json"),
                LogEventLevel.Debug,
                fileSizeLimitBytes: 655360)
            .CreateLogger();
    }

    public static void LogInformation(string info, object[] data = null)
    {
        logger.Information(info, data);
    }

    public static void LogDebug(string debug, object[] data = null)
    {
        logger.Debug(debug, data);
    }

    public static void LogWarning(string warning, object[] data = null, Exception e = null)
    {
        logger.Warning(e, warning, data);
    }

    public static void LogError(Exception e, string error, object[] data = null)
    {
        logger.Error(e, error, data);
    }
}

Any suggestions regarding my Logger class are also welcome.

A: Regardless of what log properties exist, "formatters" are how Serilog transforms standard log information (including exceptions) into text.
To get rid of the redundancy, you'll need to use a something other than JsonFormatter.
If you use Serilog.Expressions, this is easily done with an ExpressionTemplate. Example usage with Serilog.Sinks.File (other sinks are similar):
const string logTemplate = "{ { Timestamp: @t, Message: @m, Level: @l, Exception: ExceptionDetail, ..Rest() } }\n";

Log.Logger = new LoggerConfiguration()
  .Enrich.WithExceptionDetails()
  .WriteTo.File(new ExpressionTemplate(logTemplate), "app.log")
  .CreateLogger();

OLD ANSWER (without Serilog.Expressions):
Here's a formatter that I use that simply moves "ExceptionDetails" in place of the top-level "Exception."
namespace Serilog.Exceptions.Formatting;

using System.IO;
using Serilog.Events;
using Serilog.Exceptions.Core;
using Serilog.Formatting;
using Serilog.Formatting.Json;

/// <summary>
/// A JSON text formatter using structured properties for exceptions.
/// </summary>
/// <remarks>
/// Avoids the redundancy of <see cref="JsonFormatter"/> when used with <see cref="ExceptionEnricher"/>.
/// </remarks>
public class StructuredExceptionFormatter : ITextFormatter
{
    private readonly string rootName;
    private readonly JsonValueFormatter valueFormatter = new(typeTagName: null);

    /// <summary>
    /// Initializes a new instance of the <see cref="StructuredExceptionFormatter"/> class.
    /// </summary>
    /// <param name="rootName">The root name used by the enricher, if different from the default.</param>
    public StructuredExceptionFormatter(string? rootName = null)
    {
        this.rootName = rootName ?? new DestructuringOptionsBuilder().RootName;
    }

    public void Format(LogEvent logEvent, TextWriter output)
    {
        output.Write("{\"Timestamp\":\"");
        output.Write(logEvent.Timestamp.UtcDateTime.ToString("O"));

        output.Write("\",\"Message\":");
        var message = logEvent.MessageTemplate.Render(logEvent.Properties);
        JsonValueFormatter.WriteQuotedJsonString(message, output);

        output.Write(",\"Level\":\"");
        output.Write(logEvent.Level);
        output.Write('\"');

        var propCount = logEvent.Properties.Count;

        if (logEvent.Properties.TryGetValue(this.rootName, out var exceptionProperty))
        {
            output.Write(",\"Exception\":");
            this.valueFormatter.Format(exceptionProperty, output);
            propCount--;
        }

        if (propCount > 0)
        {
            output.Write(",\"Properties\":{");
            var comma = false;

            foreach (var property in logEvent.Properties)
            {
                if (property.Key == this.rootName)
                {
                    continue;
                }

                if (comma)
                {
                    output.Write(',');
                }
                else
                {
                    comma = true;
                }

                JsonValueFormatter.WriteQuotedJsonString(property.Key, output);
                output.Write(':');
                this.valueFormatter.Format(property.Value, output);
            }

            output.Write("}");
        }

        output.WriteLine('}');
    }
}

It would render your exception as follows:
{
  "Timestamp": "2021-09-02T15:04:02.4469999+05:00",
  "Level": "Error",
  "Message": "Unhandled Exception",
  "Exception": {
    "Type": "System.NullReferenceException",
    "HResult": -2147467261,
    "Message": "Object reference not set to an instance of an object.",
    "Source": "Boilerplate.Web.Mvc5.Sample",
    "StackTrace": "   at AppV2.Controllers.BaseController.Initialize(RequestContext requestContext) in E:\\Workspace\\AppV2\\AppV2\\Controllers\\BaseController.cs:line 115\r\n   at System.Web.Mvc.Controller.BeginExecute(RequestContext requestContext, AsyncCallback callback, Object state)\r\n   at System.Web.Mvc.Controller.System.Web.Mvc.Async.IAsyncController.BeginExecute(RequestContext requestContext, AsyncCallback callback, Object state)\r\n   at System.Web.Mvc.MvcHandler.<BeginProcessRequest>b__4(AsyncCallback asyncCallback, Object asyncState, ProcessRequestState innerState)\r\n   at System.Web.Mvc.Async.AsyncResultWrapper.WrappedAsyncVoid`1.CallBeginDelegate(AsyncCallback callback, Object callbackState)\r\n   at System.Web.Mvc.Async.AsyncResultWrapper.WrappedAsyncResultBase`1.Begin(AsyncCallback callback, Object state, Int32 timeout)\r\n   at System.Web.Mvc.MvcHandler.BeginProcessRequest(HttpContextBase httpContext, AsyncCallback callback, Object state)\r\n   at System.Web.Mvc.MvcHandler.BeginProcessRequest(HttpContext httpContext, AsyncCallback callback, Object state)\r\n   at System.Web.Mvc.MvcHandler.System.Web.IHttpAsyncHandler.BeginProcessRequest(HttpContext context, AsyncCallback cb, Object extraData)\r\n   at System.Web.HttpApplication.CallHandlerExecutionStep.System.Web.HttpApplication.IExecutionStep.Execute()\r\n   at System.Web.HttpApplication.ExecuteStepImpl(IExecutionStep step)\r\n   at System.Web.HttpApplication.ExecuteStep(IExecutionStep step, Boolean& completedSynchronously)",
    "TargetSite": "Void Initialize(System.Web.Routing.RequestContext)"
  },
  "Properties": {
    "UserName": "adminuser@mail.com",
    "ThreadId": 5,
    "Caller": "AppV2.Extensions.Logger.LogError(System.Exception, System.String, System.Object[])",
    "MachineName": "DESKTOP-GHV3V41",
    "HttpRequestId": "e9922caf-7e25-47f8-9941-263ba1ec4278",
    "HttpRequestNumber": 1,
    "HttpRequestClientHostIP": "::1",
    "HttpRequestType": "GET",
    "HttpRequestRawUrl": "/"
  }
}

A: I researched and I think you should check the Serilog filters. You can filter event fields, sources or even filter data if they have a certain value, for example. You can do this by configuring the respective filters in your logger configuration on code or in the JSON file.
Refer to this link for more information https://github.com/serilog/serilog-filters-expressions


text:
Q: Contextual menu without autofocus I would like to open a "contextual menu" when a user touches a button.
I have searched with no success for a solution to have the default android context menu without autofocus. To me the default autofocus is a pain in the neck as it forces extra taps for the user (out of the menu window) to select another item on the main window.
My activity offers a gridview with items g1, g2,... and the contextual menu would display a list of textareas t1, t2... Here is what I need:

*

*when user taps g1, a menu shows up at the bottom of the screen (I need to be able to customize the menu layout basically)

*when user taps g1, the rest of the window does not fade away i.e. he should still be able to view normally the main window except for the space taken by the menu at the bottom

*when user taps g1, he does not loose the focus of the current window i.e. if he taps g2 after the menu has open, g2 will act normally without requiring an extra tap

*let's say user taps g1, then taps g2: the current contextual menu should close and a new one opens, refreshed for b2

*i need to do that for apps starting from minsdkversion=8 (seems i cannot use "action bar")

Hope this makes sense, let me know if it doesn't.
I guess that would be too much hassle to hack the default context menu to customize it this way? It's totally ok to create my own. But I don't know where to start.
So could you point me toward the direction of achieving what I want ?
Thanks for your time

A: Two suggestions how to do that with self-defined context menus.
Variant A: Maybe it is an option for you to wrap your current Layout into a RelativeLayout, and add a LinearLayout (containing your self-defined context menu) to that RelativeLayout as soon as the user clicks an g1. When g2 is clicked, remove that old LinearLayout and add a new one with relativeLayout.addView(contextMenuLayout). To have your LinearLayout placed on the bottom, make sure to use contextMenuLayout.setLayoutParams(...) on it and pass an instance of RelativeLayout.LayoutParams, and set Align Parent Bottom and Center Horizontal. Because your contextMenuLayout is the last element of the RelativeLayout, it will be drawn on top. Focus will act as you wish.
Variant B: Wrap your current Layout into a LinearLayout with vertical orientation. The first cell contains your current layout. The second cell may contain your self-defined context menu, you add and remove just like in Variant A. Two advantages: first, your original layout is not covered by the context view, and in that way everything is always visible. Secondly, you can set the 'LinearLayout' to "animateLayoutChanges", which makes the context menu fade in smoothly with Android API11+ (ignored in earlier versions).
Variant A and B as Pseudocode (both work similar):
class YourActivity extends Activity implements OnItemClickListener {

    View contextMenu = null;

    public void onItemClick(AdapterView<?> parent, View view, int position, long id) {

        // this could be RelativeLayout (Variant A) or LinearLayout (Variant B) which in turn contains your Layout
        Layout rootLayout = (Layout)findViewById(R.id.root_layout);

        // in case there is a context menu open, remove it
        if(contextMenu!=null)
            rootLayout.removeView(contextMenu);

        // add new self-defined context menu
        contextMenu = getContextMenuView();
        rootLayout.addView(contextMenu);
    }

    private View getContextMenuView() {
        Layout contextMenuView = new LinearLayout(...);
        .... add contents ...
        return contextMenuView;
    }

    ....
}

Note you need to cast rootLayout to either LinearLayout or RelativeLayout, since Layout itself has no addView(...) method.


text:
Q: Automatically Detect the Dongle Port Number C# My client wants a simple C# WinForms application to send SMS messages over the Huawei E303 dongle. I used the below code and it works successfully.
public class SMSSender
{
    SerialPort sp = new SerialPort();

    public bool SendMessage(string PhoneNumber, string Message, int port)
    {
        string selectedPort = String.Concat("COM", port);

        sp.PortName = selectedPort;
        sp.Open();

        PhoneNumber = char.ConvertFromUtf32(34) + PhoneNumber + char.ConvertFromUtf32(34);
        sp.Write("AT+CMGF=1" + char.ConvertFromUtf32(13));
        sp.Write("AT+CMGS=" + PhoneNumber + char.ConvertFromUtf32(13));

        sp.Write(Message + char.ConvertFromUtf32(26) + char.ConvertFromUtf32(13));
        sp.Close();
    }
}

But the problem is, this code does not detect the dongle port number automatically. I cannot hard code the port number because when he connect the dongle to a different USB port, then port number changes. As a simple solution, I added a text box to enter the port number manually.
Can anyone help me to improve this code to automatically detect the dongle port number?


text:
Q: MongoDB cannot create UUID String in aggregation pipeline Currently i have reports collection like below in database (simplified for clarity);
{
    "_id": "33b4c208-4807-4004-ae55-d482266ee790",
    "reportTypeId": "RPT-100",
    "created": "2021-02-23T23:54:28.376+00:00",
    "userId": "cc278c75-9399-451e-a40d-64eb0d14625a",
    "rows": [
        {
            "row_field_1": "x",
            "row_field_2": "y",
            "row_field_3": "z"
        }
    ]
}

But we decide to seperate reports from rows so i created reportRows collection.
I write aggregate to transfer every rows of inside the report object to newly created reportRows collection.
But you already notice i dont have any _id field in report rows items so before i insert, i want to create an _id field with UUID String value.
I found documentation for UUID.
https://docs.mongodb.com/manual/reference/method/UUID/
The documentation says i can create random UUID using UUID() function but when i add _id field in the aggregation pipeline using $set or $addFields stages, MongoDB gives below error.
"MongoshInvalidInputError: Missing required argument."
And MongoDB Compass tool gives below warning for same pipeline.
"Stage must be properly formatted document"
// $set stage for adding (or setting) _id field for row
{
    "$set": {
        "_id": UUID()
    }
}

How can i create or set _id field with random UUID String in aggregation pipeline?
Thank you.


text:
Q: SQLite in operator in query() I'm calling SQLite like this
String[] args = new String[]{"(A,B)"}
Cursor cur = db.query("tab1", null, "name in ?", args, null, null, null);

and receiving Exception:
android.database.sqlite.SQLiteException: near "?": syntax error: , while compiling: SELECT * FROM tab1 WHERE name in ?

How to use in operator in query() ?
I already tried
String[] args = new String[]{"('A','B')"}

A: String[] args = new String[]{A,B} // if A, B are variables
String[] args = new String[]{"A","B"}
Cursor cur = db.query("tab1", null, "name in (?,?)", args, null, null, null);

A: While working on a project and struggling with this very same question I found these other questions (and answers) helpful:

*

*Sqlite Query for multiple values in one columm

*Android/SQLite IN clause and placeholders
Here is what I've found works:
String[] args = new String[] {"A", "B"};
Cursor cur = db.query("tab1", null, "name in(?,?)", args, null, null, null);

As will:
String args = "A, B";
Cursor cur = db.query("tab1", null, "name in(" + args + ")", null, null, null, null);

So you can either use multiple ? with the IN() statement and match each with an element in selectionArgs array (like the first example).  If you have multiple conditions in your WHERE clause, make sure to match the ? with the correct element in selectionArgs:
String[] args = new String[] {"Current", "A", "B"};
Cursor cur = db.query("tab1", null, "IsCurrent=? AND name in(?,?)", args, null, null, null);

Or you can just use a string made up of comma-delineated arguments directly in the IN() statement in the selection string itself (like the second example).

The referenced questions seemed to indicate that you could use a single ? in the IN() and somehow expand the associated parameter(s), but I was not able to get that to work.

A: If I am not mistaken, arg parsing does not work with IN clause. So you can't use '?' in your WHERE clause.
You should do something like this :
String args = "A, B";
Cursor cur = db.query("tab1", null, "name in (" + args + ")", null, null, null, null);

and construct your args with a loop if needed.

A: If i understand right, you can solve your problem like this:
List<String> exercise =  new ArrayList<>();
exercise.add(parameter1);
exercise.add(parameter2);
exercise.add(parameter3);

Cursor cursor = sqLiteDatabase.rawQuery("SELECT * FROM exersisesenglish WHERE sex " + "
=?" + " AND level" + "=?" + " AND wish" + "=?" + " AND place" + "=?" + " AND lang" +
"=?" +" AND stay_exersise IN (" + exercise.get(0) + "," + exercise.get(1) + "," +
exercise.get(2) + "," + exercise.get(3) + ")", new String[]{String.valueOf(sex),
String.valueOf(level), String.valueOf(wish), String.valueOf(place),
String.valueOf(loc)});


text:
Q: A function $f:\mathbb{R}\to\mathbb{R}$ such that $f^{-1}(x)=\frac{1}{f(x)}$ Does there exist a non trivial function $f:\mathbb{R}\to\mathbb{R}$ such that $f^{-1}(x)=\frac{1}{f(x)}$ ?

A: At least the functional equation can't hold for every $x \in \mathbb{R}$. Note that plugging in $x = 0$ implies
$$
f^{-1}(0) = \frac{1}{f(0)} \Rightarrow 0 = f\left(\frac{1}{f(0)}\right)
$$
so in particular $f$ attains value $0$ for some $c \in \mathbb{R}$. But now
$$
f^{-1}(c) = \frac{1}{f(c)} = \frac{1}{0},
$$
so there is no such function.

A: Suppose $f$ continuous. Then $f$, being invertible, is increasing or decreasing. If it is increasing, $f^{-1}(x)$ is increasing, while $[f(x)]^{-1}$ is decreasing. If it is decreasing, $f^{-1}(x)$ is decreasing, while $[f(x)]^{-1}$ is increasing. So there exists no solution among continuous functions. In fact, any solution would have to be everywhere discontinuous, or continuous at only a finite set of points.


text:
Q: Python: What's wrong with this Python Code? # Define a procedure, median, that takes three
# numbers as its inputs, and returns the median
# of the three numbers.

# Make sure your procedure has a return statement.

def bigger(b,c):
    if b > c:
        return b
    else:
        return c
# if b is returned, then b >c
# if c is returned, then c > b

def biggest(a,b,c):
    return bigger(a,bigger(b,c))

def median(a,b,c):
    if biggest(a,b,c) == c and bigger(a,b) ==a:
        # c > b and c > a
        # a > b
        return a
    elif biggest(a,b,c) == c and bigger(a,b)==b:
        #
        return b
    else:
        return c

print(median(1,2,3))
#>>> 2    (correct)

print(median(9,3,6))
#>>> 6    (correct)

print(median(7,8,7))
#>>> 7    (correct)

print(median(3,2,1)
#>>> 1    (incorrect)

It works perfectly fine when I run it with those three prints above, but when trying different prints the output is incorrect. For example when I tried print median(3,2,1)
the output was 1 which is an incorrect answer. What's the problem with this code, and how can I fix it?

A: If c isn't the biggest, you always return c. That includes when it's the smallest.
To fix it? Well, I'd just do
return sorted([a, b, c])[1]

but since this looks like homework, that answer probably relies too much on the library and too little on your own critical thinking. Instead, what if you found the biggest input, then returned the bigger of the other two?

A: Yes, I know this is your homework but I couldn't resist. This is one method that does not use sorting (and it works I believe).
def median(a, b, c):

    if (a >= b and b >= c) or (c >= b and b >= a):
        return b
    elif (a >= c and c >= b) or (b >= c and c >= a):
        return c
    else:
        return a


text:
Q: How to integrate an App Secret into your Adjust SDK? According to the document of AdjustSDK. This is code to integrate
config.setAppSecret(secretId, info1, info2, info3, info4);

Please explain me the parameters inside it.

A: An App Secret is a set of five integers. Adjust uses this value to hash key data points when sending SDK traffic to Adjust's servers, where Adjust can verify the legitimacy of the installs based on this hash value. The App Secret is so instrumental in computing the SDK Signature that only the plain text format (as exported from your Adjust Dashboard) can be used to derive it.
9.2 What is an App Secret?


text:
Q: execution terminated in middle when the API is Called concurrently using HttpClient I am having a problem while calling a webService using HttpClient from my another webservice hosted in the same server.
The Scenario is, There is a REST webService, Lets Say "WebService1" that receives the request from multiple clients to create the PDF.
The WebService1 further calls the another webservice "BackendWebService" to create the PDF Doument. This backend WebService references the third party Library to create the PDF.
What is happening now is if a single user calls the WebService1 with 10 requests, then there is no problem. All the requests are processed successfully.
But if there are involvement of multiple users and sends the request to WebService1 simultaneously, then only few records are processed successfully, some of the records are
terminated in middle. It seems the code is not executed completely and the application is terminated without completing the whole process.
Why this is happening ? Please help. I have already created only one static instance of HttpClient, but still no Luck.
WebService1 calls the BackendWebService as below:
for each number of PDF request from client:
This is how WebService calls the BackendWebService

A: Finally i got the reason of this issue.
There was an concurrency issue in the library (a custom library called processhandler.dll ) referenced in BackendWebService while writing log in to the txt file by multiple processes. And when there is an exception in this referenced library, the process was terminating without any information in IIS or in application level logs as well.


text:
Q: Print UTF8 characets to windows console using a source file with a UTF8 encoding i'm trying to print a UTF8 character like ê to the Windows Console with a c++ console application, i'm using SetConsoleOutputCP(CP_UTF8); and i'm getting the result like expected, but, my source file needs to have the following encoding: UTF8 without Signature, yeah that's necessary because i'm getting the UTF8 Hex value of a string, so my problem is, how to print to the console a character like ê with a source file like that and not print what i am getting (ê)

A: With u8 you can specify that a string is always encoded as UTF8, regardless of the source file's actual encoding.


text:
Q: Proving the set of irrational numbers in $\mathbb{R}$ has the same cardinality as $\mathbb{R}$ Not going to show my whole proof here, but this logic work?
We are showing |R-Q| = |R| => |I| = |R|
Since I is a subset of R, |I| must be less than or equal to |R|.
So all we have to show is |I| is not less than |R|.
So started by proving R is uncountable using diagonalization and a contradiction.
Then proved I is uncountable using a contradiction and the fact that I union Q = R.
Then concluded that since I is uncountable and R is uncountable, then|I| cannot be < |R| => |I| = |R|.
Does that make sense?

A: Just show that there are injective functions from one set to another and vice versa. For one, just take the inclusion. For the other send R\Q in (0,1)\Q and Q to (1,2)\Q for example. ( I'm using the fact the the open interval has a bijection with R and that injections preserve cardinality). Then the result follows by the Cantor-Bernstein-Schroeder theorem.

A: You need a bijection from $\mathbb R$ to $\mathbb I$ so the image has to skip $\mathbb Q$. So, force the issue:  enumerate the rationals $\{r_n\}$ in some way and fix an irrational number $\alpha$. Now define
$f(x) = \begin{cases}
          r_{2n}+\alpha& x=r_n \\
          r_{2n+1}+\alpha & x=r_n+\alpha \\
          x & \text{otherwise}
       \end{cases}$.
$f$ is clearly injective, so if you know the Schroeder-Bernstein theorem, you're done. If not, then we can prove $f$ is onto: suppose $y=r_n+\alpha.$ If $n=0$, then $f(r_0)=r_0+\alpha.$ If $n$ is even, then $f\left(r_{\frac{n}{2}}\right)=r_n+\alpha$ and if $n$ is odd then $f\left(r_{\frac{n-1}{2}}+\alpha\right)=r_n+\alpha.$ Otherwise, $f(y)=y$ so $f$ is onto.

A: Your approach seem futile. The problem is that you prove that $\mathbb I$ and $\mathbb R$ are both uncountable or in other words that $|\mathbb I|>|\mathbb N|$ and $\mathbb R > \mathbb N$, but like ordinary order relation this does not imply any relation between $\mathbb I$ and $\mathbb R$.
What you would like to do is to prove the existence of a bijection between $\mathbb I$ and $\mathbb R$. However constructing such a function is quite elaborate, instead one can use the Schröder-Bernstein theorem which says that it's enough to show that there exists an injection (or surjection) both ways. An injection from $\mathbb I$ to $\mathbb R$ is trivial to construct (ie the identity mapping).
The other way you can do it by for example take the decimal expansion of the number and interleave it with the decimal expansion of a arbitrary irrational number. Ie say you interleave with $\sqrt{2}=1.4142\dots$ it would map $1.0000\dots$ to $1.04010402\dots$ (the zeroes are from $1.000\dots$ and the other decimals are from $1.4142\dots$).


text:
Q: Does Barcode/Magswipe Track data contains photo/image information on Driving License? In the US does the PDF417 format for identification cards store image/photo information in the barcode/magswipe tracks?
Can we extract that information if it is available?

A: The photo is going to take many kilobytes to have any decent resolution. A single PDF417 can hold a little over 1.5k. A magstripe even less.
There isn't a photo in either data store.


text:
Q: Pretty urls and trailing slashes The question is about trailing slashes in URLs.
When we have a directory structure, then it is obvious - / means directory, no slash means resource.
However many sites are dynamic and use pretty urls that do not directly reflect their directory structure. And in this case most urls are actually requesting resources rather than directories, so a trailing slash is not needed.
My questions is: is it fine to have pretty urls not ending in a trailing slash, and if access to a trailing slash version is attempted to use a 301 redirect to the non-slash version?
And a counter question - is it fine to have all pretty urls end with a slash even though they are not directories?

A: Google says it's ok (for indexing and searching and all that)
However, they do mention that behavior like this is treated as duplicate content. So it's probably better that only one of those schemes actually refer to the content. You'd want one of the schemes to redirect to the other. Whether it should be the one with the trailing slash or not depends on your choice.
This article talks about this issue as well : http://www.standardzilla.com/2007/07/09/dont-forget-your-trailing-slash/ It recommends that you end with a trailing slash. But I think this is dependent more on how your server is setup than anything else.


text:
Q: Replication Hung - Seconds_Behind_Master Increasing One of my slave is no longer replicating. The seconds_behind_master continue to increase, Exec_Master_Log_Pos does not increase, and Relay_Log_Space does increase. Slave_IO_Running and Slave_SQL_Running are yes (unless I stop it, or encounter the 1205).
I've tried the solutions on this thread which sounded similar but haven't had any luck, Slave SQL thread got hanged. I also tried a RESET SLAVE which still produce the same behavior.
Additionally when I run:
stop slave;

on my instance it takes +30 seconds to execute.

Query OK, 0 rows affected (33.97 sec)

show slave status\G

returns:
               Slave_IO_State: Waiting for master to send event
                  Master_Host: 10.0.40.203
                  Master_User: replicant
                  Master_Port: 3306
                Connect_Retry: 60
              Master_Log_File: mysql-bin.000779
          Read_Master_Log_Pos: 881930813
               Relay_Log_File: mysqld-relay-bin.000002
                Relay_Log_Pos: 283
        Relay_Master_Log_File: mysql-bin.000779
             Slave_IO_Running: Yes
            Slave_SQL_Running: Yes
              Replicate_Do_DB:
          Replicate_Ignore_DB: test
           Replicate_Do_Table: Users,corporations,dates,systemspecs,test_replication,domains,test,ips,deleteddate,percona_checksum,accesslevels,status,collectionsdata,orders,email_to_user,requests,userprops,percona_checksum,useremails,requests_site,sections,ordertosection,UserToGroup,validkeys
       Replicate_Ignore_Table:
      Replicate_Wild_Do_Table: percona.%
  Replicate_Wild_Ignore_Table: test.%
                   Last_Errno: 0
                   Last_Error:
                 Skip_Counter: 0
          Exec_Master_Log_Pos: 771399898
              Relay_Log_Space: 110531372
              Until_Condition: None
               Until_Log_File:
                Until_Log_Pos: 0
           Master_SSL_Allowed: No
           Master_SSL_CA_File:
           Master_SSL_CA_Path:
              Master_SSL_Cert:
            Master_SSL_Cipher:
               Master_SSL_Key:
        Seconds_Behind_Master: 4784
Master_SSL_Verify_Server_Cert: No
                Last_IO_Errno: 0
                Last_IO_Error:
               Last_SQL_Errno: 0
               Last_SQL_Error:
  Replicate_Ignore_Server_Ids:
             Master_Server_Id: 2222
                  Master_UUID: example
             Master_Info_File: /mnt/mysql/master.info
                    SQL_Delay: 0
          SQL_Remaining_Delay: NULL
      Slave_SQL_Running_State: updating
           Master_Retry_Count: 86400
                  Master_Bind:
      Last_IO_Error_Timestamp:
     Last_SQL_Error_Timestamp:
               Master_SSL_Crl:
           Master_SSL_Crlpath:
           Retrieved_Gtid_Set:
            Executed_Gtid_Set:
                Auto_Position: 0

I have four other slaves of the master that all are functional so I know the master logs aren't corrupt.
If I leave the replication running I end up with a 1205 error:

Slave SQL thread retried transaction 10 time(s) in vain, giving up. Consider raising the value of the slave_transaction_retries variable.

UPDATE:
Running SHOW PROCESSLIST brought back:
348 | replicant  | serverDNS | NULL  | Binlog Dump | 1107340 | Master has sent all binlog to slave; waiting for binlog to be updated

After finding this we altered innodb_lock_wait_timeout from 50, its default value, to 14400. This allowed the replication to process again. However it is unclear why the 50 timeout would occur on only one of 5 slaves. All slaves are m5.2xlarge AWS instances so they have the same number of resources.
Additionally, should I stop at 14400 or should I just set this to the max 1073741824?
Update 2:
If I issue a restart for the mysql service replication processes as expected for about a day then the issue reproduces.
Additionally this slave is also a master of another system if that makes a difference. The slave of this master is running fine.
Current relevant (or in my eyes) slave output lines:
         Master_Log_File: mysql-bin.000786
      Read_Master_Log_Pos: 131895019
           Relay_Log_File: mysqld-relay-bin.000025
            Relay_Log_Pos: 52668949
    Relay_Master_Log_File: mysql-bin.000786
        Exec_Master_Log_Pos: 91692081
          Relay_Log_Space: 131895472
             Seconds_Behind_Master: 12163

The 91692081 is the value it currently is stuck at.
Update 3:
Looking into it further OS file reads, OS file writes, and OS fsyncs are consistently increasing. I also have found a warning being logged:

Warning: difficult to find free blocks in the buffer pool (324 search iterations)! 0 failed attempts to flush a page! Consider increasing the buffer pool size. It is also possible that in your Unix version fsync is very slow, or completely frozen inside the OS kernel. Then upgrading to a newer version of your operating system may help. Look at the number of fsyncs in diagnostic info below.

A: Since your other slaves are running fine, this is possibly caused by user error. Some row was probably changed on this slave manually, which was meant to be changed on the master. The slave then encounters something like duplicate key constraint 10 times and fails. If the transaction causing this error is slow or it effects a lot of rows combined with ROW based replication, it can take a long time before the replication fails. See MySQL replication slave hangs after encountering SET @@SESSION.GTID_NEXT= 'ANONYMOUS';
Try to issue SHOW BINLOG EVENTS IN 'mysql-bin.000779' FROM 771399898 LIMIT 500; to find the offending query.
These values are from your SHOW SLAVE STATUS output. I put the LIMIT at 500 as a starting point, but increase it if it doesn't give you enough data.
It may be faster to set up the replication again (using a non-locking tool like Innobackupex) than to troubleshoot the root cause and solution of this problem.


text:
Q: DbUpdateException error trying to use EF core code first I have a simple Web API and I am trying to use entity framework core code first, with an external sql server database hosted on AWS RDS. My aim is for EF to create my model database/tables automatically, based on my context and models,  the first time I use Swagger to create an object. Although when I try to post an object to my API with Swagger, tables do not get created and instead I get the following error: Microsoft.EntityFrameworkCore.DbUpdateException: An error occurred while updating the entries. See the inner exception for details.
 ---> Microsoft.Data.SqlClient.SqlException (0x80131904): Invalid object name 'Users'.
Did I set up EF incorrectly?
Db Context:
namespace FitnessTrackerAPI.Data
{
    public class FitnessTrackerAPIContext : DbContext
    {
        public FitnessTrackerAPIContext (DbContextOptions<FitnessTrackerAPIContext> options)
            : base(options)
        {
        }

        public DbSet<FitnessTracker.UserData> Users { get; set; }

        public DbSet<FitnessTracker.WorkoutData> Workouts { get; set; }
    }
}

I also added the following to Startup.cs:
    public void ConfigureServices(IServiceCollection services)
    {
         services.AddDbContext<FitnessTrackerAPIContext>(options =>
         options.UseSqlServer(Configuration.GetConnectionString("FitnessTrackerAPIContext")));
         ....

    private void InitializeDatabase(IApplicationBuilder app)
    {
         using (var serviceScope = app.ApplicationServices.GetService<IServiceScopeFactory>().CreateScope())
         {
                var context = serviceScope.ServiceProvider.GetRequiredService<FitnessTrackerAPIContext>();
                context.Database.Migrate();
         }
    }

    // This method gets called by the runtime. Use this method to configure the HTTP request pipeline.
    public void Configure(IApplicationBuilder app, IWebHostEnvironment env)
    {
        //Apply pending migrations
        InitializeDatabase(app);
        ....

Connection String in appsettings.json: "ConnectionStrings": {
    "FitnessTrackerAPIContext": "Server=fitnessapi.clxnbxbuoxx1.eu-west-1.rds.amazonaws.com,1433;User ID=XXXXX;Password=XXXXX; Initial Catalog=fitnessapi; Database=fitnessapi; Connect Timeout=30;Encrypt=False;TrustServerCertificate=False;ApplicationIntent=ReadWrite;MultiSubnetFailover=False"

A: You need to call context.Database.EnsureCreated(); to "ensure" the tables are created. More about this method here.


text:
Q: Get ID DLR in Kannel I developed an application that uses the Kannel to send SMS to a SMSC via SMPP. I send for Kannel sendSms using http and get a status update and sms responses via DLR-URL. But I'm not knowing capture an ID for this message, I can not identify it on my system.
Is there any parameter that Kannel send the DLR-URL that identifies the message? Or, you could spend a parameter customized by sendSms and then capture it in DLR-URL?

A: You can add a parameter to your DLR URL with the value %F - that will be set to the SMSC's ID. However, that only gets you the SMSC ID but doesn't solve the problem of finding the message on your side.
Another thing you can do is to create a unique DLR URL for each message you send - you can include the respective message ID from your database directly in the URL. For example, if the message has an ID of 123456789 in your database, and it will have an ID of 987654321 on the SMSC, it would look like this:

*

*you set the dlr-url to the message with the ID 123456789:
http://example.com/dlr-url/?my_id=123456789&smsc_id=%F&dlr=%d

*when the time comes, you receive a request similar to this:
http://example.com/dlr-url/?my_id=123456789&smsc_id=987654321&dlr=1


text:
Q: Data is not loaded in to Datatable using Jsp Ajex crud i am creating simple crud system.i am beginner of jsp.i can add data into the database using ajax in JSP record added successfully.after add the record i tried to load the data on datatable but data is not loading on datatable
i written code below. what i tried so far
Table

  ********JQuery********

this is the Jsp code
all_project.jsp JSP CODE
    <% Class.forName("com.mysql.jdbc.Driver"); %>
    <%@page contentType="text/html" pageEncoding="UTF-8"%>
    <%@page import="java.sql.*" %>
     <%
                Connection con;
                PreparedStatement pst;
                ResultSet rs;
                Class.forName("com.mysql.jdbc.Driver");
                con = DriverManager.getConnection("jdbc:mysql://localhost/studcrud", "root","");
                String query="select * from record";
                Statement stmt=con.createStatement();
                 rs=stmt.executeQuery(query);
                while(rs.next())
                          {
                    String id   =rs.getString("id");
                    String name   =rs.getString("name");
                    String course   =rs.getString("course");
                    String fee   =rs.getString("fee");

                 out.println(id);
                out.println(name);
                out.println(course);
                out.println(fee);

}
     %>

data displayed on the console look like this
**1
john
java
10000
2
Raja
C#
7000
3
sad
asd
2323
4
Nishan
Jsp
12000**

but but display on the datatable
Add the data into the database code JSP Ajax
function addProject()
    {
        if($("#frmProject").valid())
        {
            var url= '';
            var dat = '';
            var method = '';
            if(isNew == true)
            {
                url = 'add.jsp';
                data = $('#frmProject').serialize();
                method = 'POST';
            }

            else
            {
                url = 'update_project.jsp';
                data = $('#frmProject').serialize() + "&project_id=" + project_id;
                method = 'POST';
            }

            $.ajax({

                type : method,
                url : url,
                dataType : 'JSON',

                success : function (data)
                {
                    $('#frmProject')[0].reset();

                    $('#save').html('');
                    $('#save').append('Add');

                    var msg;
                    get_all();
                    if(isNew)
                    {
                        msg = "Course Created";
                    }
                    else
                    {
                        msg = "Course Updated";
                    }

                    isNew = true;
                },
                error: function (xhr, status, error) {
                    alert(xhr);
                    console.log(xhr.responseText);

                    $.alert({
                        title: 'Fail!',
                        //            content: xhr.responseJSON.errors.product_code + '
' + xhr.responseJSON.msg,
                        type: 'red',
                        autoClose: 'ok|2000'

                    });
                    $('#save').prop('disabled', false);
                    $('#save').html('');
                    $('#save').append('Save');
                }

            });

        }
    }

add.jsp
<%@page import="java.sql.*" %>

<% Class.forName("com.mysql.jdbc.Driver"); %>
<%@page contentType="text/html" pageEncoding="UTF-8"%>

         <%
            String studname = request.getParameter("studname");
             String course = request.getParameter("course");
             String fee = request.getParameter("fee");

            Connection con;
            PreparedStatement pst;
            ResultSet rs;

            Class.forName("com.mysql.jdbc.Driver");
            con = DriverManager.getConnection("jdbc:mysql://localhost/studcrud", "root","");

            pst = con.prepareStatement("insert into records(name,course,fee)values(?,?,?)");
        pst.setString(1,studname);
        pst.setString(2,course);
            pst.setString(3,fee);

            pst.executeUpdate();

        %>

A: With version 1.10.0 of DataTables, it is built-in and easy:
var table = $('#example').DataTable();
table.ajax.reload();

Or may be :
$('#example').DataTable().ajax.reload();


text:
Q: Can I monitor changes on an HTML DIV? I am working on a complex web app.
In it, there is a div which gets updated.
It prints something like:

[1/4]
[2/4]
[3/4]
[4/4]

Probably some JavaScript somewhere is updating with something like:
div.innerHTML = "[2/4]";

My question is:
Can I somehow intercept/(listen to) innerHTML changes so that I could monitor how long they take?
I am in a position where I could inject any JavaScript and I would like to collect something like:
console.log("1/4 has been called at timestamp");
console.log("2/4 has been called at timestamp");
console.log("3/4 has been called at timestamp");
...

A: You might be able to use Mutation Events to do this if the browsers you are targeting support them. Here is a small jsFiddle demo that should work in a browser that supports the Mutation Events. I tested this in Chrome 23
JavaScript:
var observable = document.getElementById('observable');

observable.addEventListener('DOMSubtreeModified', function(ev) {
  console.log(ev.target.nodeValue, ev.timeStamp);
}, false);

var i = 0;

observable.addEventListener('click', function(ev) {
    observable.innerHTML = ++i;
    return false;
}, false);

HTML:

click me and look at the console

CSS:
#observable {
    background-color:lightblue;
    height:42px;
}


text:
Q: How do I train a model using two loss functions? I have a TensorFlow graph with two loss functions. I want to train my model alternatively:

*

*Train the model using the first loss function.

*Train the model using the second loss function.

*Repeat one and two until convergence.

Do I have to create two graphs then load, train and save the weights for every step? Or Is it possible to achieve that with a single graph?

A: Yes, this is possible:
import tensorflow as tf

x = tf.get_variable('x', initializer=42.)
y = tf.square(x)

optimizer = tf.train.GradientDescentOptimizer(0.1)

train_min = optimizer.minimize(y)  # minimize x*x
train_max = optimizer.minimize(-y) # maximize x*x

with tf.Session() as sess:
    sess.run(tf.global_variables_initializer())

    for _ in range(20):
        cost, _ = sess.run([y, train_min])
        print(cost)
        cost, _ = sess.run([y, train_max])
        print(cost)

If you don't mind to minimize both cost function on exactly the same batch, you can even write
import tensorflow as tf

x = tf.get_variable('x', initializer=42.)
y = tf.square(x)

optimizer = tf.train.GradientDescentOptimizer(0.1)

train_min = optimizer.minimize(y)

with tf.control_dependencies([train_min]):
    train_min_then_max = optimizer.minimize(-y)

with tf.Session() as sess:
    sess.run(tf.global_variables_initializer())

    for _ in range(20):
        cost, _ = sess.run([y, train_min_then_max])
        print(cost)

which does the optimization with a single sess.run call.


text:
Q: CUDA PTX code %envreg<32> special registers I tried to run a PTX assembly code generated by a .cl kernel with the CUDA driver API. The steps i took were these ( standard opencl procedure ):
1) Load .cl kernel
2) JIT compile it
3) Get the compiled ptx code and save it.
So far so good.
I noticed some special registers inside ptx assembly, %envreg3, %envreg6 etc. The problem is that these registers are not set ( according to ptx_isa these registers are set by the driver before the kernel launch ) when i try to execute the code with the driver API. So the code is falling into an infinite loop, and fails to run corectly. But if i manually set the values ( nore exactly i replace %envreg6 with the blocksize inside ptx ), the code is executing and i get the correct results ( correct compared with the cpu results ).
Does anyone know how we can set values to these registers, or maybee if i am missing something? i.e. a flag on cuLaunchKernel, that sets values to these registers?

A: You are trying to compile an OpenCL kernel and run it using the CUDA driver API. The NVIDIA driver/compiler interface is different between OpenCL and CUDA, so what you want to do is not supported and fundamentally cannot work.
Presumably, the only workaround would be the one you found: to patch the PTX code. But I'm afraid this might not work in the general case.
Edit:
Specifically, OpenCL supports larger grids than most NVIDIA GPUs support, so grid sizes need to be virtualized by dividing across multiple actual grid launches, and so offsets are necessary. Also in OpenCL, indices do not necessarily start from (0, 0, 0), the user can specify offsets which the driver must pass to the kernel.  Therefore the registers initialized for OpenCL and CUDA C launches are different.


text:
Q: How do I differ the shortcut name of my app from its "real" name? I would like a shortened name for the icon that is displayed in launcher, and when the user makes a shortcut on his home screen, that differs from the name displayed in manage applications and the default title bar that shows up in the app itself.
I feel like this is simple, and should be some short code in the manifest, but I am having a hard time finding a solution as most results in google point to end users renaming apps themselves. Thanks for any help!

A: Changing the following parameter in the launcher intent filter or activity or the application tag in the manifest file will give you the desired result.
android:label="Any String !!"

Android Manifest Guide.
I hope it helps..


text:
Q: How to remove elements from array on the basis of subarray I have two arrays in following format:
Arr1: [{name: 'TenG', id: 'd7cf4b5c-42ec-40fc-9b4e-b1600963ff37', group: 'add'}, ....]
Arr2: [{name: 'TenG, id: 'd7cf4b5c-42ec-40fc-9b4e-b1600963ff37', group: 'selected', category: undefined}, .....]
I want to keep all the elements of Arr1 which are not part of Arr2... I am shortlisting the data on the basis of group but seems the condition not coming right. please help on condition.
Sharing my code snippet for reference:
var tmpArr = [];
interfaces.filter((item) =>{
    selectedInterfaces.some((key=> (item.group!==key.group && tmpArr.push(item))))
})

console.log(tmpArr);

The result is coming as empty array in JSX. Thank you in advance for help !!

A: Try this:
const tmpArr = interfaces.filter(item1 => {
  return selectedInterfaces.every(item2 => item1.group !== item2.group)
})

You can also use lodash.differenceBy for that:
import differenceBy from 'lodash/differenceBy'

const tmpArr = differenceBy(interfaces, selectedInterfaces, 'group')


text:
Q: How do "Suspended" and "Not Running" states look like for the user? I'm trying to work out the lifecycle of an application, but I can't imagine what some of the states look like.
The program goes into a suspended state when there is no code to run in the background, right? It's still in the background (memory) but can't do anything. Now the question arises, how does it look to the average user? It can still be seen in the app switcher, but will the app restart if I want to open it?
But what happens if that app runs out of memory and goes into the "Not Running" state? Is it still visible in the App Switcher, but will the app restart if I try to open it again? What is the difference in Suspended and Not running state to a user?
Could you help me with this question?
Documentation: https://developer.apple.com/documentation/uikit/app_and_environment/managing_your_app_s_life_cycle

A: They don't look different to the user at the time. The app is listed in the app switcher regardless of whether it is suspended or not running. The app switcher makes no distinction between "it is suspended" and "it is not running but it was running recently".
However, if the user taps the app in the app switcher, what happens next is different. If the app was suspended, it simply resumes right where it was when it was suspended. But if the app is not running, it launches from a cold start, the same as if the user had killed the app and then tapped its icon in the springboard.
For some apps, this difference is quite noticeable. Apple's Books app is a good example; if it resumes from suspension, the user is instantly still reading the same page of the same book, but if it launches from a cold start, it does an involved dance that takes quite a long time, passing thru the library and visibly opening that book, to eventually get the user back to the same book and the same page.
Apple has said that ideally you should write your app in such a way that both situations look identical to the user, by saving state when you go into the background so that you can quickly restore that state the next time the app is cold-launched; but as I've just demonstrated, Apple itself does not always meet that goal.
Another goal is to try to prevent the app from being killed while suspended in the first place. You can't prevent the user from killing the app from the app switcher, but you can try at least to discourage the system from killing the app while suspended. You can't guarantee this but you can try, by not using very much memory for instance, to fly under the radar so that the system will let your app live when it is looking for apps to kill in order to free up resources. Apple has an interesting video on this topic (which would have answered your question), https://developer.apple.com/videos/play/wwdc2020/10078/.


text:
Q: Python 3 name tuple position If I have the coordinate tuple (10.1, 15.2), how can I make it so that I can call 10.1 as simply x instead of coordinates[0], and y instead of coordinates[1]?
I want to do this so that I can pass a tuple from function to function while still being able to call x and y easily. I could just:
x = coordinates[0]
y = coordinated[1]

but that seems like a bad idea -- lengthy and I'd have to repeat it for each function.

A: Use namedtuple:
   > from collections import namedtuple
   > c = namedtuple('Coords',['x','y'])
   > xy = c(5,6)
   > xy
   => Coords(x=5, y=6)
   > xy.x
   => 5
   > xy.y
   => 6


text:
Q: Can you concatenate two strings to create dynamic column names in PostgreSQL? I have a form where people can type in a start and end date, as well as a column name prefix.
In the backend, I want to do something along the lines of
SELECT *, CAST('{{startDate}}' AS TIMESTAMP) AS ({{prefix}} + '_startDate')

Is this possible? Basically, I want to dynamically create the name of the new column. The table is immediately returned to the user, so I don't want to mutate the underlying table itself. Thanks!

A: You can execute dynamic query that you have prepared by using EXECUTE keyword, otherwise it is not possible to have dynamic structure of SQL.
Since you are preparing your SQL outside database, you can use something like:
SELECT *, CAST('{{startDate}}' AS TIMESTAMP) AS {{prefix}}_startDate
Assuming that {{prefix}} is replaced with some string by your template before it is sent to database.


text:
Q: How get the list of cities on facebook API with a region param I want get a list of cities passing a state region param.
I got make this facebook webservice that i get the list of states from a country
https://graph.facebook.com/v3.1/search?country_code=BR&limit=1000&location_types%5B0%5D=region&type=adgeolocation&access_token=XXXX
Response code with this url:
{
   "data": [
      {
          "key": "438",
          "name": "Acre",
          "type": "region",
          "country_code": "BR",
          "country_name": "Brazil",
          "supports_region": true,
          "supports_city": true
      },
      {
          "key": "439",
          "name": "Alagoas",
          "type": "region",
          "country_code": "BR",
          "country_name": "Brazil",
          "supports_region": true,
          "supports_city": true
      }
    ]
}

Someone can help me ? Thanks!

A: You can get a list of cities only with a non-empty value of q parameter, containing the value of the city name substring. I think for queries with region_id this is an unnecessary restriction.


text:
Q: Is there a packaging method to reduce the capacity after building next.js? Execute the following command in next.js to create an image by copying all used files to docker , including the next.js built file.
npm install
npm run build

During this process, the file size becomes large during build, so it takes too long to copy.
So, I want to make a docker image by copying it after reducing the capacity in a way such as packaging.
I tried using the method of exporting only ssg and uploading it only to the out folder, but it does not turn into ssr.


text:
Q: Why is Yii2 rest controller giving response in XML format? Currently I am using the following initialization code on my api module
public function init()
{
    parent::init();
    Yii::$app->response->format = Response::FORMAT_JSON;
}

My api gives back response in XML format in the following example.
public function actionTest()
{
    $items = ['one', 'two', 'three' => ['a', 'b', 'c']];
    return $items;
}

This is the response:
<response>
  <item>one</item>
  <item>two</item>
   <three>
    <item>a</item>
    <item>b</item>
    <item>c</item>
   </three>
</response>

The only way I can get it to work is by adding this line to each of the controller behaviors. I have read the documentation which says I can initalize this on the module class so I do not need to do it in every controller. I do not know why it gives XML though. Also just in case the only way is to add it to my behaviors, do I have to write code to handle name, code, status, type, previous and code or does Yii provide yii\rest\Controller and yii\rest\ActiveController which automatically handle this. Clearly they are being output automatically when there is an error.
{"name":"Not Found"
 "message":"Page not found.",
 "code":0,
 "status":404
 "type":"yii\\web\\NotFoundHttpException"
 "previous":{"name":"Invalid Route","message":"Unable to resolve the request: api/home/",
 "code":0,"type":"yii\\base\\InvalidRouteException"
 }
}

A: After three painful days, I have found the solutions. It is sometimes quite difficult to explain this problem when you are coming from a whole JSON world of ExpressJS and NodeJS. Logically what Yii2 does is perfectly fine, on the other hand 90%  RESTful APIs expect the output to be in JSON hence you do not explicitly want to set request headers every time you make an API call.
Browsers by default add request headers as "Application/XML" hence what you see on screen is XML instead of JSON.
Yii2's content negotiator upon receipt of headers as application/xml formats your output in XML. If you make a same request using CURL or PostMan with headers as "Application/JSON" you will get the desired output.
If you wish to override this behaviour then just add the below function in your controller and include the following:-
use yii\web\Response;
use yii\helpers\ArrayHelper;

public function behaviors()
  {
      return ArrayHelper::merge(parent::behaviors(), [
          [
              'class' => 'yii\filters\ContentNegotiator',
              'only' => ['view', 'index'],  // in a controller
              // if in a module, use the following IDs for user actions
              // 'only' => ['user/view', 'user/index']
              'formats' => [
                  'application/json' => Response::FORMAT_JSON,
              ],
              'languages' => [
                  'en',
                  'de',
              ],
          ],
      ]);
  }

A: I test Your code and it's work perfectly
my controller this :
<?php

namespace backend\controllers;

use yii\rest\Controller;
use yii;
use yii\web\Response;

class TestController extends Controller{

    public function init()
    {
        parent::init();
        Yii::$app->response->format = Response::FORMAT_JSON;
    }

    public function actionTest(){
        $items = ['one', 'two', 'three' => ['a', 'b', 'c']];
        return $items;
    }
}

Output  :
{"0":"one","1":"two","three":["a","b","c"]}

check your namespace OR send your code !

A: In Yii2 applications default response type is XML (and I guess it's default for REST too). During HTTP connection both sides declares what type of data are able to send and/or receive. If this information is not passed to server default data type is send(even if you specified that it should be JSON in your app) to guarantee proper communication. If you want to receive JSON data you must add Accept: application/json header to your request. And probably you don't have to specify it in php code because Yii2 should deduct it from request headers.
You can find more explanation how it works here.