text:
Q: sed and remove string between two patterns I've got problem with removing part of string between two patterns with sed. I've always got last PATTERN-2 in line:
test.txt:
PATTERN-1xxxxPATTERN-2aaa
PATTERN-1xxxxPATTERN-2fffPATTERN-1zzzzPATTERN-2gggPATTERN-1zzzzPATTERN-2
PATTERN-1xxxxPATTERN-2bbb

cmd
sed 's/PATTERN-1.*PATTERN-2//g' test.txt

the result of above is
aaa

bbb

but I would like to have
aaa
fffggg
bbb

Is possible to find PATTERN-2 which is closest to PATTERN-1?

A: As @steeldriver points out, it is easy if you have non-greedy regexps. If not, you can do it with a loop, like this:
sed ':a;s/PATTERN-2/\n/;s/PATTERN-1.*\n//;ta' test.txt

This works because we know there are no newlines in the middle of any line. It would also work with any other character that does not occur in any line, e.g. §.

A: If you want to use only sed try like below
sed 's/PATTERN-1[^P]*PATTERN-2//g' test.txt

A: In your example, the .* matches stuff that you want to keep.
You can capture that stuff and replace it back by using:
sed 's/PATTERN-1\(.*\)PATTERN-2/\1/g' test.txt

Everything between the brackets gets stored in the first capture buffer and \1 substitute in the value of that buffer.

A: It's easy in a regex implementations that support a non-greedy qualifier, such as perl's ? For example:
perl -pe 's/PATTERN-1.*?PATTERN-2//g' test.txt

A: "Closest" is not really a sed term. But if there is a reasonable limit to the number of repeats of the sequence PATTERN-1.*PATTERN-2 you can hardcode for that number as follows:
     $ sed -E 's/(PATTERN-1).*(PATTERN-2)(.*)\1.*\2/\3/g;s/PATTERN-1.*PATTERN-2//g' <<"end"
     PATTERN-1xxxxPATTERN-2aaa
     PATTERN-1xxxxPATTERN-2fffPATTERN-1zzzzPATTERN-2gggPATTERN-1zzzzPATTERN-2
     PATTERN-1xxxxPATTERN-2bbb
     end

     aaa
     ggg
     bbb

Note that I use the -E option for extended regex syntax. Also note that in the search expression I use backreferences for the PATTERN-1 and -2 strings, just for your comfort.


text:
Q: html doc not using external css style sheet I am starting to learn CSS and after trying to implement an external stylesheet, i found I was unable to change the color of my html document. I am using Visual Studio Code and my html templates are using Djangos inheritance.
I have tried double checking that everything is saved, I have checked spelling for the href, and i even restarted VSC. So far nothing.
Here is the base html sheet
<!DOCTYPE html>

      <meta charset="utf-8">
        {% block style %}
        {% endblock %}
     <title>
         {% block title %}
         {% endblock %}
     </title>

  {% block content %}
  {% endblock %}

Here is an html sheet that should use the styling:
{% extends 'student_view_base.html' %}

{% block title %}
    Socrates Home Page
{% endblock %}

{% block style %}
<link rel="stylesheet" type="text/css"
 href="css/sidebar.css">
{% endblock %}

{% block content %}

Socrates Home Page

        Login

    Admin Login
{% endblock %}

Here is the css sheet:
h1{
    color: blue;
}

As you can tell, I am pretty new to Web Dev in general and this was mostly to experiment and make sure I could implement it properly.
As far as I can tell the h1 tags text should be turning blue. Currently it remains black.
EDIT: I can confirm that the href is linked to the proper document, ctrl clicking takes me to the right document.

A: You are better off placing your html code on templates and your css on static when you use django. Create a templates and static folders on your project as here. enter image description here
Then edit settings.py'DIRS': [os.path.join(BASE_DIR, 'templates')], inside TEMPLATES. Also add the following code to your settings.py :
STATIC_URL = '/static/'

STATIC_DIRS = [
    os.path.join(BASE_DIR, 'static'),
]

STATIC_ROOT = os.path.join(BASE_DIR, 'static')

MEDIA_URL = '/media/'

MEDIA_ROOT = os.path.join(BASE_DIR, 'media')

You should be good to go.

redpajama_set_name: RedPajamaStackExchange


text:
Q: status : 500 Internal Server Error postman only posts empty curly brackets when enter the data on the body and this is my code (index.js), (auth.js)

const express = require("express");
const dotenv = require("dotenv");
const mongoose = require("mongoose");
const authRoute = require("./routes/auth");
const app = express();

dotenv.config();
app.use(express.json());

mongoose.connect(process.env.MONGO_URL, {
    useNewUrlParser: true,
    useUnifiedTopology: true,
    useCreateIndex: true,
  }).then(console.log("Connected to MongoDB"))
  .catch((err) => console.log("err"));
app.use("/api/auth",authRoute );

app.use("/api/auth",authRoute);

app.listen("3000", () => {
  console.log("Backend is running.");
});

const router = require("express").Router();
const User = require("../models/User");

//REGISTER
router.post("/register", async (req, res) => {
  try {
    const newUser = new User({
      username: req.body.username,
      email: req.body.email,
      password: req.body.password,
    });

    const user = await newUser.save();
    res.status(200).json(user);
  } catch (err) {
    res.status(500).json(err);
  }
});

//LOGIN

module.exports = router;
and image of the postman result

when I  send the request postman posts empty curly brackets. I want to get the post data on the down of the body at the postman
screenshot of the postman
and this is what terminal logs
result on the terminal

A: You should check what receives in user object at  const user = await newUser.save();
data would be in user.data
or use json instead,
 const user = await newUser.save();
    res.status(200).jsonp(user);

A: .env file must be inside the root folder, not the outside

A: I got that error in postman and my problem was that I was adding a str data in an int field in pgAdmin


text:
Q: I'm using django and beautiful soup trying to get the links but it's not working Im trying to scrape data using beautiful soup and django. I'm using B.S. In conjunction with requests. There are 38 links on the page but when I try to output them only one shows. Heres my code in views.py
def sewp(request):
r = requests.get("http://www.vladtv.com/")

soup = BeautifulSoup(r.content, 'html.parser')

content = soup.find_all("a")

for link in soup.find_all("a"):
    link = link.get("href")

ella = "ella"
context = {
    "link": link,
    "ella": ella,
}
return render(request, "posts/display_soup.html", context)

but if I do this
def sewp(request):
r = requests.get("http://www.vladtv.com/")

soup = BeautifulSoup(r.content, 'html.parser')

content = soup.find_all("a")

ella = "ella"
context = {
    "content": content,
    "ella": ella,
}
return render(request, "posts/display_soup.html", context)

all the links show
How can I correct my code to make this work? Any guidance is welcomed. there really is no documentation or tutorials that explain how to use B.S. and Django.
I've been using Django less than a month and have started using B.S. and Requests 12 hours ago. Thanks in advance

A: The problem lies in the loop of your code. The value of link gets replaced after every iteration. Hence, at the end of the loop only one link is printed (the last link).
You need to initialize a list and then append the links into it. Then pass that list to the context.
links = []
for link in soup.find_all('a'):
    links.append(link.get("href"))

# Or you could simplify that loop using list comprehension:
# links = [link.get("href") for link in soup.find_all('a')]

context = {
    "links": links
}


text:
Q: How do I hide posts across all loops based on the value of a custom field? I'm trying to dynamically hide posts across my entire site if the value of a custom field called distribution is "1".
I've set up a meta box on the post editor screen to set the value of the field, but, especially on older posts, the field will not always be set.
Note that I'm doing this in a plugin, so the easy way of directly editing loops and WP_queries in the theme isn't an option for me.
It seems like pre_get_posts or posts_where will do what I want.
function hide_custom_filter( $where = '') {
  global $wpdb;
  if (!is_single() && !is_admin()) {
    $where .= " AND (($wpdb->postmeta.distribution = '1')) ";
  }
  return $where;
}
add_filter( 'posts_where', 'hide_custom_filter' );

The above code gives me an error: WordPress database error: [Unknown column 'wp_postmeta.distribution' in 'where clause'].
What's going on here?

A: This should do it, using pre_get_posts:
function wpse_275546_hide_distribution_post( $query ) {
    /* Don't filter posts in admin, or the current post when viewing a single post. */
    if ( ! is_admin() && ! ( $query->is_main_query() && is_single() ) ) {
        /**
         * Get current meta query if it exists, otherwise an empty array.
         * This is to modifiy, so that we don't override any existing meta queries.
         */
        $meta_query = $query->get( 'meta_query' ) ?: array();

        /* Add meta query to find posts that do not have distribitions set to 1. */
        $meta_query[] = array(
            'key'     => 'distribution',
            'value'   => '1',
            'compare' => '!=',
        );

        /* Apply meta query. */
        $query->set( 'meta_query', $meta_query );
    }
}
add_action( 'pre_get_posts', 'wpse_275546_hide_distribution_post' );

One thing I wasn't sure about was your use of is_single(). Do you still want to allow people to view the single post? If so, do you still want to hide it from any other possible loops, like widgets?
If you're ok showing the posts everywhere when viewing a single post, then you can remove the $query->is_main_query() && part. I added that to ensure that the main post appeared on single post views, but still kept them hidden from secondary posts.


text:
Q: Pausing a Downloading File in Google Chrome and Hibernate the System, will it resume? I'm downloading a large .rar file in GOOGLE CHROME but I don't want to leave my system powered on over night. I'm planning to pause and hibernate the system so that when I switch it back on, I can resume the file download in my queue. Is this possible with this method, will it resume the file download where it left off?

A: By default Chrome will not resume downloads when your system is suspended / hibernated. You could try the Chrono Download Manager extension which does support pause/resume/resync of downloads.
Google Chrome - Chrono Download Manager
EDIT: There is a new flag you can set in chrome. If you go to the URL below in your address bar:
chrome://flags/#enable-download-resumption
and enable that, it should work to resume a download.


text:
Q: Reading Config File in Python2.7 I have a file named .env in my code directory
.env has different configs
Eg : username = "xyz"
     password = "abcd"

In my code directory I have a folder called scripts
Inside scripts I have a script named "control.py" which needs to read the config from .env
How can I achieve this?
The structure is something as below
/var/www/html/code/.env
/var/www/html/code/scripts/control.py

.env has all the config stuffs and control.py needs to read these config.

A: It would be better if you use decouple module for this purpose. You can do pip install python-decouple.


text:
Q: Excel formula to return value based on header and two columns I'm trying to write an Excel formula that will place an "X" in a cell if the value in the header row occurs anywhere in column A while the values in Column B are unchanged. I envision the result looking like this:

A: use COUTNIFS:
=IF(COUNTIFS($A:$A,C$1,$B:$B,$B2),"X","")

It will count if the header if found in A where B matches what is in B2.  If it returns anything but 0 it will return X otherwise an empty string.


text:
Q: Jfreechart make a dynamic scrollable chart I am trying to create a XYLineChart using JfreeChart. It is a dynamic chart and I receive data every 2 seconds upto a minute. I want to make the chart scrollable so that I can visit the older data points plotted.
I tried adding the chartPanel to a JScrollPane. Did not work. It only makes the entire window scrollable, but not the actual chart.
Can someone help me?
I need to scroll back real time in order to see the previously plotted points.
Here's my code:
class DynamicData extends JFrame {
private TimeSeries series;
private TimeSeries series2;
public DynamicData(String title) {
    super(title);
    this.setDefaultCloseOperation(JFrame.EXIT_ON_CLOSE);
    this.series = new TimeSeries("Time", Millisecond.class);
    this.series2 = new TimeSeries("Time", Millisecond.class);
    final TimeSeriesCollection dataset = new     TimeSeriesCollection(this.series);
    DateAxis domainAxis = new DateAxis("Time");
    NumberAxis rangeAxis = new NumberAxis("Packet Size");
    XYBarRenderer renderer = new XYBarRenderer(0.1);

    Day d1 = new Day();
    domainAxis.setAutoRange(true);
    //domainAxis.setRange(new DateRange(d1.getFirstMillisecond(), d1.getLastMillisecond()));

    XYPlot mainPlot = new XYPlot(dataset, domainAxis, rangeAxis, renderer);

    mainPlot.setDomainGridlinesVisible(true);
    domainAxis.setTickMarkPosition(DateTickMarkPosition.MIDDLE);
    JFreeChart chart = new JFreeChart(null, null, mainPlot, true);
    ChartPanel chartPanel = new ChartPanel(chart);
    chartPanel.setPreferredSize(new Dimension(600, 600));

    this.add(chartPanel);
    this.add(getScrollBar(domainAxis), BorderLayout.SOUTH);
    this.pack();
 }

 private JScrollBar getScrollBar(final DateAxis domainAxis){
    final double r1 = domainAxis.getLowerBound();
    final double r2 = domainAxis.getUpperBound();
    JScrollBar scrollBar = new JScrollBar(JScrollBar.HORIZONTAL, 0, 100, 0, 400);
    scrollBar.addAdjustmentListener( new AdjustmentListener() {
        public void adjustmentValueChanged(AdjustmentEvent e) {
            double x = e.getValue();
            domainAxis.setRange(r1+x, r2+x);
        }
    });
    return scrollBar;
}
public void plotGraph(long value)
{
     try
    {
        this.series.addOrUpdate(new Millisecond(), value);
    }
    catch(Exception e)
    {
        e.printStackTrace();
    }
}
}


text:
Q: iis hosting. Could not load file or assembly 'Newtonsoft.Json, Version=4.5.0.0 I have an asp.net MVC 4 web application which is running fine on developer machine(i have hosted it in IIS). But after hosting in to another machine which doesn't have mvc framework installed and .net framework installed, i ended up with the following
Could not load file or assembly 'Newtonsoft.Json, Version=4.5.0.0, Culture=neutral, PublicKeyToken=30ad4fe6b2a6aeed' or one of its dependencies. The system cannot find the file specified

i came know to know that mvc framework is not required to host, from the below link
Do I need to install MVC 3/4 on web server to run mvc application

A: Nope its not a default one, verify once in your project references, it must be referenced.
Newtonsoft is third parth library, so its no by default in project, go through all your project's references and look for Newtongsoft.Json, once you find remove it or If you're using packages then go to your package.config file and lookfor Newtonsoft.Json and remove it

A: Try to remove the Newtonsoft Json Nuget (uninstall-Package Newtonsoft.Json)   package or
install The Newtonsoft Json (Install-Package Newtonsoft.Json) then Uninstall it, it may works


text:
Q: Unexplained overflow x on page I'm wondering if anyone can help me. I am working on a website and one of the pages has a weird overflow to the right of the page. I honestly cannot work out what is causing it after inspecting all of the elements. Would anyone mind taking a look to see if you can see what's causing this as I am stuck. Very grateful for any help! The url is: https://diabetesand.me/recipes/quick-and-easy-tacos

A: You problem:

The quick solution is:


text:
Q: How to store selected date from jquery datepicker in a variable using c#? I have a jquery calender on my aspx page as

and following is the JS:
var array = ["23/08/2013", "24/08/2013", "25/08/2013"];
    $("#selectDate").datepicker({
        onSelect: function(dateText,inst){
        $('#selectDate').submit();},
        defaultDate: "+1w",
        changeMonth: true,
        dateFormat: "dd/mm/yy",
        minDate: 0,
        maxDate: '+1y +0m -1d',
        numberOfMonths: 2,
        beforeShowDay: function (date) {
            var string = jQuery.datepicker.formatDate('yy-mm-dd', date);
            return [array.indexOf(string) == -1];
        }
    });

Now, i need to store the selected date from the datepicker into the variable on .cs page,I know i have to use onSelect function, but I don't know how to do it, any help will be appreciated.
I am using Asp.net and C#.

A: You can get the date, put it in a asp.net hidden field using js and then when you post it back you can put it in a C# variable, something like this:
Add hidden field to your markup:
<asp:HiddenField Id="myDate" runat="server"></asp:HiddenField>

Get the date and set it to the hiddenfield before postback:
var currentDate = $( "#selectDate" ).datepicker( "getDate" );
$('#<% myDate.ClientID %'>).val(currentDate);

And when you post it you can use this in your code behind:
var selectedDate = DateTime.Parse(myDate.Value);


text:
Q: Linking 2 Mongoose collections I am trying to build a simple website, where authenticated users (authors) can write and post stories.
I have an Author collection and a Story collection and I'm trying to create links between both collections. I am using mongoose and the populate/ref method. I can successfully display a story or list of stories that contain information about their author but I'm really struggling to attach a list of stories to their author when displaying the author profile. What I want is to make sure that when visiting an author profile page, users can see the list of their stories.
I'm trying to use the populate/ref method to fulfill the array that would display the authors list of stories (storyList) but the array remains tirelessly empty. When displaying an author profile page I first used the findById function but understood this doesn't seem to work with populate. So I'm now using the findOne function but with the same results.
Here is my Author collection:
const mongoose = require('mongoose');

const authorSchema = mongoose.Schema({
  userName: {
    type: String,
    required: true
  },
  firstName: String,
  lastName: String,
  authorImage: {
    type: String
  },
  emailAddress: {
    type: String,
    required: true,
    unique: true,
    match: /^(([^<>()\[\]\\.,;:\s@"]+(\.[^<>()\[\]\\.,;:\s@"]+)*)|(".+"))@((\[[0-9]{1,3}\.[0-9]{1,3}\.[0-9]{1,3}\.[0-9]{1,3}])|(([a-zA-Z\-0-9]+\.)+[a-zA-Z]{2,}))$/
  },
  password: {
    type: String,
    required: true
  },
  storyList: [{
    type: mongoose.Schema.Types.ObjectId,
    ref: 'Story'
  }]
});

module.exports = mongoose.model('Author', authorSchema, 'authors');

Here is my route to display an author profile page:
const mongoose = require('mongoose');
const bcrypt = require('bcrypt');
const jwt = require('jsonwebtoken');

const Author = require('../models/author');

exports.authors_get_one = (req, res, next) => {
  const username = req.params.userName;
  Author.findOne(username)
    .select("_id userName firstName lastName emailAddress password authorImage storyList")
    .populate('storyList')
    .exec()
    .then(doc => {
      console.log("From database", doc);
      if (doc) {
        res.status(200).json({
          author: doc,
        });
      } else {
        res.status(404).json({
          message: 'No valid entry found for provided ID'
        });
      }
    })
    .catch(err => {
      console.log(err);
      res.status(500).json({
        error: err
      });
    });
}

Here is my Story schema
const mongoose = require('mongoose');

const storySchema = mongoose.Schema({
  author: {
    type: mongoose.Schema.Types.ObjectId,
    ref: 'Author',
  },
  title: {
    type: String,
  },
  text: {
    type: String,
  },
  language: {
    type: String,
  },
  published: {
    type: Boolean,
    default: false
  }
});

module.exports = mongoose.model('Story', storySchema, 'stories');

And here is my route to create a story:
const mongoose = require('mongoose');
const Story = require('../models/story');
const Author = require('../models/author');

exports.stories_createOne = (req, res, next) => {
  const story = new Story({
    title: req.body.title,
    text: req.body.text,
    language: req.body.language,
    author: req.body.author
  });
  story
    .save()
    .then(result => {
      console.log(result);
      res.status(201).json({
        message: "Story publiée !",
        createdStory: {
          _id: result._id,
          title: result.title,
          text: result.text,
          language: result.language,
          author: result.author,
        }
      });
    })
    .catch(err => {
      console.log(err);
      res.status(500).json({
        error: err
      });
    });
}

From the documentation I found, I can not see what I'm doing wrong. Am I missing something here? Is the populate method not enough to fulfill my list of stories (storyList)? Should I even do something somewhere else in my code and what?

A: The reason your storyList array remains empty is because you are not pushing the stories ref into the author.storyList array after creating the stories. Source.
The easy fix to this would be to do something like this in the route to create a story:
exports.stories_createOne = (req, res, next) => {
  const story = new Story({
    title: req.body.title,
    text: req.body.text,
    language: req.body.language,
    author: req.body.author
  });
  story
    .save()
    .then(result => {
      console.log(result);
      // Push the story id into the author.storyList array
      Author
        .update(
          { _id: req.body.author },
          { $push: { storyList: result.toJSON()._id } }
         )
        .then(() => {
          // send response here
        })
    })
    .catch(err => {
      // Handle Error
    });
}


text:
Q: A filter method in React isn't working while a map is I am using a ternary check in React. If an item exists, it triggers a .map method, and if it doesn't it triggers a .filter method. The map is working fine, but the filter is not. It is throwing an error saying that an object is not a valid React child, and to use an array. However, to my understanding, it IS an array...
 {test.searchTerm === ""
            ? test.users.map((item, index) => (
                <>

                    {index + 1}
                    {item.name.first + " " + item.name.last}
                    {item.email}
                    {item.gender}
                    {item.phone}

                </>
              ))
            : test.users.filter((item, index) => {
              //console.log(test.users)
                if (
                  test.searchTerm === item.name.first ||
                  test.searchTerm === item.name.last ||
                  test.searchTerm === item.name.first + " " + item.name.last
                ) {

                  return (
                    <>

                        {index + 1}
                        {item.name.first + " " + item.name.last}
                        {item.email}
                        {item.gender}
                        {item.phone}

                    </>
                  );
                }
              })}

A: In JavaScript filter is used to create a new array base on the condition. Your filter method should return true for matching element and false other wise. After that you have to map the resulting filtered array. After filter you still have an array of objects.
{test.searchTerm === ""
            ? test.users.map((item, index) => (
                <>

                    {index + 1}
                    {item.name.first + " " + item.name.last}
                    {item.email}
                    {item.gender}
                    {item.phone}

                </>
              ))
            : test.users.filter((item, index) => {
              //console.log(test.users)
                if (
                  test.searchTerm === item.name.first ||
                  test.searchTerm === item.name.last ||
                  test.searchTerm === item.name.first + " " + item.name.last
                ) {

                  return true;
                }
                return false
              }).map(item => (
                    <>

                        {index + 1}
                        {item.name.first + " " + item.name.last}
                        {item.email}
                        {item.gender}
                        {item.phone}

                    </>
              ))}


text:
Q: Highlight text feature in browser (Chrome) which looks like highlighting in android I want to implement feature (for chrome extension) which allows the user to select some text from webpage in browser with mouse and I want to add ability for the user to edit selection boundaries (like it can be done in android application) with small controls below the selected line which can be moved with the mouse:

May be there is existing library to achieve similar behaviour in browser in easy way?

A: i think this might help..
var divs = document.getElementsByTagName("p");

for(var d in divs) {
  // highlight a part of a
 tag
    divs[d].addEventListener('mouseup',function(){var str= document.getSelection()    ;alert(str);
    this.innerHTML =this.innerHTML.replace(str,''+str+'');
    });
}

And more of it can be found in here


text:
Q: Android Market: Making my app "free" The help text on the publishing section says that once I make my app free I can no longer make it a commercial product. Is this true? Can I simply delete everything and re-publish my app to get around this?

A: Yes, its true that if you make your app free, you can't make it paid anymore. If you do want to make a paid version while you have a free version, you'll have to upload a new app with a different package name. You probably can't just delete everything and republish.


text:
Q: Pre-populating Django Forms I'm trying to have a Django Form from a query, but I keep doing it the wrong way. Checked out a few examples, but I'm doing it a bit different. Here's my code,
Le Form
class ItemForm(ModelForm):

    class Meta:
        model = Item
        exclude = ('deleted')

And part of the view
def index(request):
    user = User
    try:
        last_modified_list = ShoppingList.objects.filter(deleted='0').filter(owner=user).latest('date_modified')
        items = Item.objects.filter(shopping_list=last_modified_list).filter(deleted='0')
    except ObjectDoesNotExist:
        items = Item.objects.filter(deleted='0')

    last_used_currency = ExtendedUser.objects.filter(owner=user)

    #currency = forms.CharField(initial=last_used_currency.last_currency)
    try:
        last_used_shoppinglist = ShoppingList.objects.filter(deleted='0').filter(owner=user).latest('date_modified')
    except ObjectDoesNotExist:
        last_used_shoppinglist = datetime.datetime.now()

    item_form = ItemForm (request.POST or None)
    item_form.fields["shopping_list"]=last_used_shoppinglist

    if item_form.is_valid():
        name =  item_form.cleaned_data['name']
        bought =  item_form.cleaned_data['bought']
        currency = item_form.cleaned_data['currency']
        price = item_form.cleaned_data['price']
        date_added = item_form.cleaned_data['date_added']
        date_modified = item_form.cleaned_data['date_modified']
        date_bought = item_form.cleaned_data['date_bought']
        shopping_list = item_form.cleaned_data['shopping_list']
        quantity = item_form.cleaned_data['quantity']
        deleted = item_form.cleaned_data['deleted']

    return render_to_response ('base.html',{'user':user,'items':items,'item_form':item_form}, context_instance=RequestContext(request))

The shopping_list line is really leading to many errors.

A: You want to pass the object into the form as "instance". If I understand your code correctly and you had a single Item named "item":
ItemForm(request.POST or None, instance=item)

In this case though, it looks like you want a model formset so you can edit multiple items at once. Then you would pass your items variable in as the "queryset" parameter.
EDIT: Actual solution is for a different problem,
item_form.fields["shopping_list"].initial = last_used_shoppinglist


text:
Q: How to auto refresh data in android studio every second? I am new to android studio, I am making an app that gets the json of a field in thingspeak, but I don't know how can I make an auto refresh to the data I get every second. Can you please help me?

public class MainActivity extends AppCompatActivity {
    private TextView mTextViewResult;

    @Override
    protected void onCreate(Bundle savedInstanceState) {
        super.onCreate(savedInstanceState);
        setContentView(R.layout.activity_main);
        mTextViewResult = findViewById(R.id.text_view_result);

        OkHttpClient client = new OkHttpClient();

        // Read field url from thingspeak
        String url = "https://api.thingspeak.com/channels/XXXXXXX/fields/1.json?api_key=XXXXXXXXXXXXX&results=2";

        Request request = new Request.Builder()
                .url(url)
                .build();

        client.newCall(request).enqueue(new Callback() {
            @Override
            public void onResponse(@NonNull okhttp3.Call call, @NonNull Response response) throws IOException {
                if (response.isSuccessful()) {

                       // this is what I want to refresh every second

                        final String myResponse = response.body().string();

                        MainActivity.this.runOnUiThread(new Runnable() {
                            @Override
                            public void run() {
                                mTextViewResult.setText(myResponse);
                            }
                        });
                    }
                }

        });
    }
}

A: I found a solution finally, I placed the data request inside the following code and it worked perfectly:
final Handler handler = new Handler();
Runnable refresh = new Runnable() {
        @Override
        public void run() {
            // data request
            handler.postDelayed(this, 5000);
        }
    };
handler.postDelayed(refresh, 5000);

A: Use a CountDown Timer . Set the timer for 1 second and  in onFinish method call request data .
       new CountDownTimer(1000, 1000) {
            public void onTick(long millisUntilFinished) {

            }
            public void onFinish() {
               //Request Data
            }
        }.start();


text:
Q: event dispatch thread in Java SWING program I am totally a newbie in Java. And I want to create an animation. But I did not succeed. mouseClicked() will be executed in the event dispatching thread. Why doesn't it work? Will the event dispatching be occupied by other threads, what other threads?
public class DemoThreadGUI {

    public static void main(String [] args) {
        DemoThreadGUI app = new DemoThreadGUI();
        app.go();
    }

    public void go() {
        SwingUtilities.invokeLater(new Runnable() {
            public void run() {
                generateGUI();
            }
        });
    }
    public void generateGUI() {
        JFrame frame = new JFrame("Demo");
        frame.add(new MyPanel());
        frame.pack();
        frame.setDefaultCloseOperation(JFrame.EXIT_ON_CLOSE);
        frame.setVisible(true);
    }

    class MyPanel extends JPanel implements MouseListener {
        private int x,y;
        private int r;
        public MyPanel() {
            this.setPreferredSize(new Dimension(100,100));
            this.addMouseListener(this);
            x = 50;
            y = 50;
            r = 25;
        }
        public void paintComponent(Graphics g) {
            super.paintComponent(g);
            g.fillOval(x-r,y-r,r*2,r*2);
        }

        public void mouseClicked(MouseEvent event) {
            int targetX = event.getX();
            int targetY = event.getY();
            for(int i=0;i<10;++i) {
                x = (x+targetX)/2;
                y = (y+targetY)/2;
                repaint();
                try {
                    Thread.sleep(100);
                } catch (InterruptedException e) { }
            }
        }

        public void mouseEntered(MouseEvent event) {}
        public void mouseExited(MouseEvent event) {}
        public void mousePressed(MouseEvent event) {}
        public void mouseReleased(MouseEvent event) {}

    }

}

A: In your mouseClicked() start a new Thread and place the code in the thread
       for(int i=0;i<10;++i) {
            x = (x+targetX)/2;
            y = (y+targetY)/2;
            repaint();
            try {
                Thread.sleep(100);
            } catch (InterruptedException e) { }
        }

The repaint() call should be wrapped into SwingUtilities.invokeAndWait() to pass control to EDT

A: As Holger said, You can't expect a thread to paint your UI when you told it to sleep.
Use this instead:

*

*Make targetX and targetY global variables, and make a new java.util.Thread object t.
private int x,y;
private int r;
Thread t;
int targetX, targetY;

*modify your mouseClicked method as:
public void mouseClicked(final MouseEvent event) {
    targetX = event.getX();
    targetY = event.getY();
    t = new Thread(new Runnable(){public void run(){anim();}});
    t.start();
}

*Put your code of the mouseClicked method into the anim method as:
public void anim()
{
    for(int i=0;i<10;++i) {
        try{
            x = (x+targetX)/2;
            y = (y+targetY)/2;
            repaint();
            Thread.sleep(100);
        }catch(Exception e){}
    }
    t.stop();
}

This works perfectly.


text:
Q: .htaccess subdomain to folder I've recently made some minor changes to my website's folder structure, and now one of my rewriterules seems broken.
in the past I had a /mydomain.com/ folder in public_html in which a wiki was set up. In the same folder were some folders that I used for subdomain access, like members and files.
The old setup:
#www to main website
RewriteCond %{HTTP_HOST} ^www.mydomain.com$
RewriteRule ^(.*)$ mydomain.com/$1 [L]

#subdomain to folder (members. => /members/, files. => /files/, etc)
RewriteCond %{HTTP_HOST} ^(.*).mydomain.com$
RewriteCond %{HTTP_HOST} !^www.mydomain.com$
RewriteRule ^(.*)$ mydomain.com/%1/$1 [L]

Fairly easy, and when I typed in files.mydomain.com/myfile.zip it worked without any problems.
Recently I installed several languages of my wiki (which is in fact irrelevant to the question, but just to elaborate the situation) and I made the following rule:
#to the right language folder (www = en)
RewriteCond %{HTTP_HOST} ^(www|nl|es).mydomain.com$
RewriteRule ^(.*)$ mydomain.com/%1/$1 [L]

#subdomain to folder (members. => /members/, files. => /files/, etc)
RewriteCond %{HTTP_HOST} ^(.*).mydomain.com$
RewriteCond %{HTTP_HOST} !^www.mydomain.com$
RewriteRule ^(.*)$ mydomain.com/misc/%1/$1 [L]

Obviously, the different language wikis are set up in mydomain.com/www/, mydomain.com/es/, etc. This works perfectly fine.
The problem lies in the second part, the subfolders. In the same mydomain.com/ folder I created a misc/ folder to store all the misc stuff (including the subdomain folders). I figured just adding the /misc/ in the path (like I added the language folder name in the first rule) would make it work.. but it gives me a 500 error.
Neither the old setup nor the new setup have any .htaccess lines in any folders that could conflict with the second rule.
Can anyone spot the error, or tell me how to systematically check this setup for bugs?

A: The easiest way to prevent the redirection loop I believe is happening is to just check if you've already rewritten the URL to where you intended it to go. We can do this a few different ways; if you know that the file will exist once you've rewritten it, you can condition on %{REQUEST_FILENAME} !-f, for instance.
In your case, since you're rewriting everything to a common folder within your /public_html directory, we can just check if that's already been done:
#to the right language folder (www = en)
RewriteCond %{HTTP_HOST} ^(www|nl|es)\.example\.com$
RewriteCond %{REQUEST_URI} !^/example\.com
RewriteRule ^(.*)$ example.com/%1/$1 [L]

#subdomain to folder (members. => /members/, files. => /files/, etc)
RewriteCond %{HTTP_HOST} ^(.*)\.example\.com$
RewriteCond %{HTTP_HOST} !^www\.example\.com$
RewriteCond %{REQUEST_URI} !^/example\.com
RewriteRule ^(.*)$ example.com/misc/%1/$1 [L]

Admittedly, I'm not sure why you're experiencing issues now, but weren't before. I ran your original rule set on my test server and ended up with an internal server error due to too many internal redirections, so there must be differences in our setup. In any case though, hopefully this will get things working for you.


text:
Q: RANKX issues using DAX I was working on the conversion of a sql request into a dax one :
    >;WITH cte
    >AS
    >(
    >       SELECT uc.idU_Email
    >              ,uc.id_Type
    >              ,uc.dRecueil
    >              ,valeur
    >              ,ROW_NUMBER() OVER(PARTITION BY idU_Email,id_Type ORDER BY dRecueil DESC, valeur ASC) AS rang
    >       FROM   vUE uc
    >       WHERE uc.Id_Type=1  AND uc.dRecueil<=(DATEADD(month, -1, GETDATE()))
    >)
    >SELECT COUNT(idU_Email)
    >    FROM   cte
    >    WHERE  rang = 1
    >    and valeur = 1

If i understood well, the equivalent of the rownumber function in sql in the RANKX Function in DAX.
So basically, to achieve the conversion i created a new calculated colum with the following expression :
Ranking on partition
To resume it,  it makes a ranking on every parition of idU_Email order by dRecueil and then by valeur.
Thus, the only thing left to do was to add a condition on the date (like in my SQL request), but i guess i don't really know how (or where?), and an error occurred when i tried, which i haven't achieved to solved yet :
Ranking on partition with filter on date
I hope someone would find a way to solve that issue (or even to propose me a better way to have the equivalent of my SQL request).
Thanks by advance ! Smiley Happy
[UPDATE]
I've achieved to partition as I wanted to do and to apply a date filter like that :
RANK_OnDate = IF(vUE[dRecueil] <= DATE(YEAR(TODAY()); MONTH(TODAY())-1; DAY(TODAY()))
            ;RANKX(FILTER(vUE; vUE[idU_Email] = EARLIER(vUE[idU_Email]) && vUE[id_Type] = EARLIER(vUE[id_Type]))
                ;RANKX(ALL(vUE); vUE[dRecueil]; ;ASC)
                +
                DIVIDE(
                    RANKX(ALL(vUE); vUE[valeur]; ; DESC; Skip)
                    ;COUNTROWS(ALL(vUE)) + 1
                )
            )
        )

But, actually, i would like it to filter dynamically... Thus i don't know if it would be better to use that directly in a measure (according that i want to count distinctly the lower/higher rank for each idU_email).
Additionally my filter just apply blank when the date isn't ok with the filter but the ranking stay the same...
I tried to do directly the distinct count in a measure but can't save the different issues encountered... Have you got some ideas ?
(and thanks for your answers) :)

A: I think you're pretty close, try this
Rank = IF(vUE[dRecueil] <= DATE(YEAR(TODAY()), MONTH(TODAY())-1, DAY(TODAY())),
           RANKX(FILTER(vUE, vUE[idU_Email] = EARLIER(vUE[idU_Email])),
               RANKX(ALL(vUE), vUE[dRecueil], ,ASC) +
               DIVIDE(
                   RANKX(ALL(vUE), vUE[valeur], , DESC, Skip),
                   COUNTROWS(ALL(vUE)) + 1)))


text:
Q: How Do I Add SSL/TLS Connection Security Option to Evolution Mail? As the title indicates, I am having trouble moving one of my mail accounts from Thunderbird to Evolution Mail because the mail server where my email is located will only accept a SSL connection.  Thunderbird's 'SSL/TLS' default connection security option works perfectly, but Evolution Mail only provides 'STARTTLS after connecting' and 'TLS on a dedicated port' as connection security options.  Can someone dummy-proof instructions on how to get my Evolution mail to support SSL connections?
Ubuntu 18.04
Evolution 3.28.5
Can't find a single thing explaining why SSL support is NOT by default built into Evolution.  Even Evolution's own help docs say that SSL is supported, but the actual option for SSL connection simply is not there.
I uninstalled evolution, installed the PPA, and re-installed.  There is no option for SSL connection security... banging head on wall... now.
This is what I see:

NOTE: I have tried all three Security Encryption Methods, but none work.
Thanx

A: You already have that option, it's just named differently between Thunderbird and Evolution.
Thunderbird's "SSL/TLS" option is equivalent to Evolution's "TLS on a dedicated port".
Use the port and "TLS on a dedicated port" options to emulate Thunderbird's "SSL/TLS" options.
Under the hood they both say that it's a dedicated port that only accepts TLS connections by default, rather than StartTLS which starts on a plaintext connection and then upgrades to TLS Encrypted automatically after the initial connection is established.

But, why is "SSL" not listed?
"SSL" and "TLS" are two protocols that do encrypted connectivity but with different handshake mechanisms, etc.  "SSL" died effectively when SSLv3 was effectively killed by the POODLE vulnerability in 2014, and is effectively considered "dead" now.  TLS is now the protocol that is supported for encrypted connections.
However, "SSL" itself has such a known history in terms of being discussed as the "encryption mechanism" and "SSL Certificates" and such that "SSL" and "TLS" are synonymous for "TLS" nowadays in the average person's vocabulary and such.  Whenever we say "SSL" we usually mean "TLS" nowadays though.
(And since OpenSSL versions in 18.04 and later have SSLv2 and SSLv3 disabled by default, SSL is effectively dead, but TLS lives on)


text:
Q: Print all the VM's in XenServer using Java API I have been trying to play around with Xenserver by printing the VM's present by using the following code
Connection conn = new Connection(new URL("http://"));
Session.loginWithPassword(conn, "xyz", "xyz", "");
Object type //parameter)
**"int size = VM.getAll(conn).size();//how many objects in XCP"**
Object objArr[] = VM.getAll( conn ).toArray();//Trandfer <Set>VM to Object array
VM a = Types.toVM( objArr[0] );
System.out.println( a.getUuid( conn ) );

But failed to get the desired result as it throws an exception for the quoted line. Can someone tell me where the hell am I going wrong?


text:
Q: ldapjs - write after end error I have created an authentication service using the following code in Node.js and ldapjs.
var when = require ('when');
var AuthenticationError = require('../errors/AuthenticationError');
var SessionManagerService = require('./SessionManagerService');

var ldap = require('ldapjs');

var client = ldap.createClient({
    url: 'ldaps://ad.mycompany.com:636',
    tlsOptions: {'rejectUnauthorized': false}
});

module.exports = {

    signIn: function (email, password) {
        return this.ldapBind(email, password).then(
            function () {
                return SessionManagerService.createSessionHash({email: email});
            }
        );
    },

    ldapBind: function (email, password) {
        var deferred = when.defer();
        client.bind(email, password, function(err) {
            if (err) {
                deferred.reject (new AuthenticationError('Invalid username and/or password!', 'Authentication.signIn.error'));
            } else {
                client.unbind();
                deferred.resolve(true);
            }
        });
        return deferred.promise;
    },

};

When I authenticate my user for the first time, it works perfectly but it fails starting from the second attempt.
The error message is: 'write after end'.
When I restart the node server it works again for the first attempt.
It looks like something is hanging but I don't know what. Any idea?

A: I solved this problem a few days ago for creating ldap-client every time in ldapBind function (in your case).


text:
Q: How to pass parameters in Angular between pages My Node.js backend returns the AWS Cognito tokens as JSON which are received in my Angular login Component.
I wish to open my dashboard and pass the received tokens
in my login.component.ts function I do: this.router.navigate(['/dashboard', { tokens: data }]); before sending the data I print it to the console and it looks fine
in my dashboard.component.ts I'm not sure why the tokens are not reachable
import { Component, OnInit } from '@angular/core';
import { ActivatedRoute, Router } from '@angular/router';

constructor(private route: ActivatedRoute, private router: Router) {}

ngOnInit() {

this.route.queryParams.subscribe(params => {
            console.log('params = ' + params);
            var data = params['tokens'];
            console.log('data = ' + data);
            for(let key in data){
                console.log('key = ' + key + ' data= ' + data[key]);
            }
        });
}

this is the 'console.log' output params = [object Object] data = undefined
What am I doing wrong?

A: You are sending params not query params, so your code should be :-
this.route.params.subscribe(params => {
            console.log('params = ' + params);
            var data = params['tokens'];
            console.log('data = ' + data);
            for(let key in data){
                console.log('key = ' + key + ' data= ' + data[key]);
            }
        });


text:
Q: Suddenly Java process (JVM) got disconnected I started my application in tomcat server with the following properties,

-Dcom.sun.management.jmxremote.port=1502 -Dcom.sun.management.jmxremote.ssl=false -Dcom.sun.management.jmxremote.password.file=../jmxremote.password -DinstanceName=$INSTANCE -Xms256m -Xmx2g -Dtomcat.appserver.instance=$INSTANCE -Dcontainer.port=$PORT -Dcontainer.host=../hostname -DappLogLevel=INFO -DappLogDir=/logs/ -DUseCustomErrorPage=false -Dfile.encoding=UTF-8 -XX:+HeapDumpOnOutOfMemoryError -XX:-PrintGCDetails -XX:-PrintGCTimeStamps -XX:MaxMetaspaceSize=1028m -XX:+UseConcMarkSweepGC -XX:+CMSClassUnloadingEnabled -XX:+CMSPermGenSweepingEnabled -XX:HeapDumpPath=/dumps/ -Dsun.net.inetaddr.ttl=300 -DUseCustomErrorPage=false

I have started the jconsole and suddenly

I don't know for some reason JVM has stopped with no error.
Using Tomcat for deployment and JDK 8
Java: jdk1.8.0_11_32bit
Tomcat: apache-tomcat-7.0.35
please let me know if we can make any modifications to the environment settings.


text:
Q: VMware Fault Tolerance possible Tests I have been thinking about how I can test my Fault Tolerance machines.
But I can't seem to come with a proper test.
How can I possibly calculate the time it took for VMware to switch from the primary virtual machine to the secondary one?

A: Ping the VM and kill the host where the primary runs, how many pings do you loose? This should give you a feeling for the time it takes vSphere to switch from the primary virtual machine to the secondary.


text:
Q: How to make a timed reward system in php and mysql How can I make a reward system in PHP that has a timer and sets a timer for a certain amount of time after they click on it and mysql inserts a random value into the table?
I am making a project and I want users to accumulate the in-game currency as if they were using a Bitcoin faucet.

A: A simple way to do this would be to keep track of the users "currency" using a table that has both amounts and datetimes. The user's balance would only show the entries that have datetimes before the current time. That way, you can insert the entry right away and then it only goes live when you need it.
rowid |  user_id   |  amount  |      activetime       |
-------------------------------------------------------
90000 |     1      |  0.01    |   12:13:12 01-16-15   |
90001 |     1      |  0.01    |   12:13:12 02-16-15   |

On inserts you can set the active time to something like DATE_ADD(NOW(), INTERVAL 2 HOUR) so it will show up 2 hours later.
Example of adding a row:
INSERT INTO transactions
    (user_id, amount, activetime)
VALUES
    (1, 0.01, DATE_ADD(NOW(), INTERVAL 2 HOUR))

Example of getting current balance for a user:
SELECT SUM(amount) AS balance FROM transactions WHERE activetime <= NOW()

Also, if you want to rate limit the user, it is easy now to check if they have already clicked the button because there will be an entry greater than the current time. You could query quickly like this:
SELECT 1 FROM transactions WHERE activetime > NOW() LIMIT 1

Then in php, if num_rows() is 1, they have already clicked the button and are waiting for payment. Otherwise it will return 0.
Hopefully this helps. Let me know if you have any other questions on this topic, or if you need some clarification.


text:
Q: Doctrine 2 configuration settings in zend 2 Following a tutorial on an IBM page I managed to get doctrine 2 working with zend 2.
The problem however is when I follow the tutorial, the configuration is set using an array based configuration. When I wanted more info about doctrine 2 configuration I ended up in this page which is not an array based configuration!
What I want to do is to disable the generation of proxy classes in production mode, but I can't figure out what settings I can use in the array approach. How can I for example do something like this:
return array(
    // ...
    'doctrine' => array(
        'connection' => array(
         //I already know how to do this!
        ),

        //THIS IS JUST A WILD GUESS, IT DOESN'T WORK:
        'configuration' => array(
            'orm_default' => array(
                'auto_generate_proxy_classes' => false,
            ),
        ),
    ),
);

A: Right settings is:
'doctrine' => array(
    'configuration' => array(
        'orm_default' => array(
            'generate_proxies' => false,
        ),
    ),
),

as you can see in DoctrineOrmModule documentation:
https://github.com/doctrine/DoctrineORMModule/blob/master/docs/configuration.md
or directly in default configuration:
https://github.com/doctrine/DoctrineORMModule/blob/master/config/module.config.php#L72


text:
Q: Querying GraphQL Microservice with API key? I have developed two Netflix DGS GraphQL Microservices and Apollo Gateway on top of these two microservices to make them as an federated graphql.
I have a client application that is trying to query both the graphql microservices. And both microservices have a unique API key. How do we assign API key for multiple microservices either from client or Apollo server ?
When client queries for more than one microservices with API key, there is a chance of ignoring API key by server. Is there any best practices to handle API key management?

A: Apollo Gateway has buildService property which you can use to modify request behavior using standard callbacks like willSendRequest.
Using willSendRequest you can match service url and append API key accordingly:
class RequestHander extends RemoteGraphQLDataSource {
    willSendRequest({ request }: { request: GraphQLRequest }) {
        // if request.http.url matches url of a service which you
        // use, add api-key to headers, e.g.
        if (request.http.url === 'http://localhost:3001') {
            request.http.headers.set('api-key', <API_KEY>)
        }
    }
}

const main = () => {
    const gateway = new ApolloGateway({
        buildService: ({ url }) => new RequestHander({ url }),
        serviceList: [
            { name: 'service1', url: 'http://localhost:3001' },
            { name: 'service2', url: 'http://localhost:3002' },
        ],
    })

    const server = new ApolloServer({ gateway })

    void server.listen({ port: 3000 }).then(({ url }) => {
        logger.info(`Apollo Gateway ready at ${url}`)
    })
}

main()

This way you can create some map where you'll have all services with its api keys listed, and then you'll be able to match url and api key in willSendRequest callback in a simple way.


text:
Q: load coordinates from database that are within the bounds of the map I need to return a set of filtered records from the database which coordinates are within the current maps bounds (map.getBounds())
According to Google Maps API v3 this is possible to do client side using their api and the function "containsLatLng(latlng:GLatLng)", but I want to do this implementation in the server side and then just returned the records that are within this coordinates.
My current implementation works if map is centered in the Africa, but if the map is showing China and Canada in the same view, then my implementation doesn't work because the longitude flips from positive to negative in the Pacific.
Any suggestions on how to implement this accurately?

A: In Google Maps, the LatLngBounds object constructor takes the southwest and northeast corners of the rectangular bounds.
Knowing that one point is the southwest corner and not the southeast corner is crucial to solving the problem.
If you know that one point is the southwest corner and the other the northeast corner, then compare the two corners' longitudes.  Your algorithm will work like this:

*

*If the longitude of the southwest corner is less than the longitude of the northeast corner, than a point is within the bounds if it has a longitude between those two longitudes and a latitude between the two latitudes of the corners.  (This is probably what you're doing for everything which is why it works in Africa where the condition is true, but not in something that spans the Pacific Ocean.)

*If the longitude of the southwest corner is more than the longitude of the northeast corner, than your bounds crosses 0 longitude and you need to reverse the condition:  A point iswithin the bounds if it has a longitude that is not numerically between the longitude of the southwest corner and the longitude of the northeast corner.
For simplicity and because it is almost certainly true, I am assuming that you will never have a bounds that covers the North Pole or the South Pole.  (In Google Maps, I don't even know if you can have such a bounds.)


text:
Q: Is a ring generated by an irreducible polynomial a PID?
If $p(x)$ is an irreducible polynomial in $\mathbb R[X]$ (the set of polynomials with real coeffs), is the (sub)ring generated by $p(x)$ a PID?

My guess is yes, at least if I have an ideal generated by a finite number of elements then every generator must divide $p(x)$ so must be $p(x)$ itself or $1$ which gives that the ideal will be generated by a multiple of $p(x)$.   However, of course, I have no reason to assume that any ideal is finitely generated.
Thank you in advance.

A: You can prove that for $p\in\Bbb R[X]$ with $\deg p\ge 1$ we have $\Bbb R[p(X)]\simeq\Bbb R[T]$ (by sending $T$ to $p(X)$), that is, $\Bbb R[p(X)]$ is isomorphic to a polynomial ring over $\Bbb R$ in one variable. Then automatically $\Bbb R[p(X)]$ is a PID.


text:
Q: Executing SSIS package using command prompt I am trying to execute an SSIS package using command prompt.
I have visual studio 2019 community edition installed and have selected 'Data storage and processing' during the installation.
Also installed SQL server integration services projects from visual studio extensions.
I looked for Dtexec.exe and found it at the below mentioned locations.
C:\Program Files (x86)\Microsoft SQL Server\110\DTS\Binn
C:\Program Files (x86)\Microsoft SQL Server\120\DTS\Binn
C:\Program Files (x86)\Microsoft SQL Server\130\DTS\Binn
I couldn't find a 64bit Dtexec.exe under C:\Program Files
I have created an SSIS package using visual studio 2019.
I tried executing the package from command line using a batch file.
"C:\Program Files (x86)\Microsoft SQL Server\120\DTS\Binn\dtexec.exe" /FILE "C:\Users\Ash\source\repos\DR Activity 1\DR Activity 1\Package.dtsx" /MAXCONCURRENT " -1 " /CHECKPOINTING OFF  /REPORTING EWCDI
pause
I get an error message stating
There was an exception while loading Script Task from XML: System.Exception: The Script Task "ST_07a17c9047774ce7ad850af7a94a9ca5" uses version 15.0 script that is not supported in this release of Integration Services


text:
Q: What's the meaning of "ceid" in Google News url I am recently working on web scraping of Google News and dealing with the URL format. I have same question of this post about the meaning of ceid.
For example the link from the post: https://news.google.com/rss/search?q=studie&hl=de&gl=DE&ceid=DE:de
I know hl = host language, gl = for the search results whose country of origin matches the parameter value, but I can't find what ceid for. If I cut that part of the search link, it is unable to show the result, so obviously it is a must part.
So what's the meaning and the purpose of the "ceid"?
Many thanks.

A: It might mean the country name and show the results according to the common language of the country.
For example:  'ceid=IN:en' means the country as "India", and hence the result should show up in English.


text:
Q: ignore or close zabbix problem for a period of time I have both zabbix 3 and zabbix 5. I have a template that monitors Database statistics. there is a trigger that is important, but sometimes when we are operating on Database the trigger is not needed because we caused that situation. sometimes i don't want this trigger on my dashboard so i attend to close it. but the interval for its item is 60s and after a minute it appears again. so is there any way to close or ignore a trigger for a period of time?
i don't want to put the machine in maintenance mode because operation may take a week. i can't disable the item, we need its data and history. i can't change it's interval since it is in template.
in this question Q1 someone explained about closing the problem but it's not what i want.

A: Since Zabbix 4, you can put a single item in maintenance using Tags.

If maintenance tags are specified, maintenance for the selected hosts will still be activated, but problems will only be suppressed (i.e. no actions will be taken) if their tags are a match.

https://www.zabbix.com/documentation/current/manual/maintenance
So:

*

*tag the trigger in the template

*create a maintenace for that host/tag and activate it when needed


text:
Q: How do I check if a variable contains a letter/phrase in batch? So I'm making, like, a fake messenger thing in batch to mess with people and I want to make it seem more realistic. Basically, I need to be able to search a variable to see if it contains a word? if that makes sense. Everyone that I've asked has said to use the findstr function, but I can't really do that because it's not a separate text file.
I was wondering if there was a way to do, like,
set /p input=thing (a variable for user input)
if %thing% contains "o" echo yes

I don't know if that makes sense. Sorry. I'm a beginner.
Thank you so much for reading this. I've been looking at stuff for this for like 3 hours

A: findstr works, but you have to consider everything. For instance:
findstr /irc:"hi"

will find the word Hi any string, but it will also find high, which etc. So it will take a lot of time and effort to get the responses close to 100%.. anyway, all just for fun. Give this a try.
@echo off
cls
set /p "you=What is your name? "
@echo off & setlocal enabledelayedexpansion
set "cn=0"
for %%i in (Mary Catlin John Steve Emma Candice) do (
    set /a cn+=1
    set "name[!cn!]=%%i"
    echo !cn!. %%i
)
for /l %%a in (1,1,!cn!) do set "ucount=!ucount!%%a"
choice /c !ucount! /m "Hi %you%, Who'd you like to chat to?"
set name=!name[%errorlevel%]!
echo Please wait for !name! to join.. & timeout /t 6 /nobreak>nul 2>&1 & echo !name! is online.

for /F %%a in ('echo prompt $E ^| cmd') do set "ESC=%%a"
:chat
set /p "string=%you%: %ESC%[91m"
(timeout /t 1)>nul 2>&1
call :strings
goto :chat

:hi
echo %ESC%[92m!name!: What's up?%ESC%[0m
goto :eof

:doing
echo %ESC%[92m!name!: I am well, thank you%ESC%[0m
goto :eof

:time
echo %ESC%[92m!name!: It is now %time%%ESC%[0m
goto :eof

:date
echo %ESC%[92m!name!: The current date is %date%%ESC%[0m
goto :eof

:ben_jerry
echo %ESC%[92m!name!: I love Ben ^& Jerry's!!%ESC%[0m
goto :eof

:dude
echo %ESC%[92m!name!: DUDE!!%ESC%[0m
goto :eof

:not_love
echo %ESC%[92m!name!: WOAH!!! You're going to fast, I'm out%ESC%[0m
goto :eof

:strings
echo "%string%" | findstr /irc:"\<hi\>">nul 2>&1 && call :hi
echo "%string%" | findstr /irc:"\<how\>">nul 2>&1 && call :doing
echo "%string%" | findstr /irc:"\<time\>">nul 2>&1 && call :time
echo "%string%" | findstr /irc:"\<date\>">nul 2>&1 && call :date
echo "%string%" | findstr /irc:"\<love\>">nul 2>&1 && call :not_love
echo "%string%" | findstr /irc:"\<ben & jerry's\>">nul 2>&1 && call :ben_jerry
echo "%string%" | findstr /irc:"ice cream">nul 2>&1 && call :dude && call :ben_jerry
if "%string%" == "/exit" color & cls & exit
goto :eof

Result, where me: would be what I typed and `Bot: being the responses.

A: You can do it within external commands, using CMD's set replace.
set /p "thing=thing (a variable for user input) "

if not "%thing%"=="%thing:o=_%"  echo Contains 'o'

With that, you are replacing the content of %thing% temporary to _ and then check if both strings are equal.
If the replace matches 0 results, then strings will be equal and it will not show anything. If some string is replaced, strings will not match so it will contain the character.


text:
Q: Getting the proper event.data from onWrite in Cloud Functions with Firebase I feel like I'm just missing something silly here because all the examples including codelab show that accessing the event data is straightforward. But I can't get it to work.
I have a straightforward chat/conversation structure that looks like:
    conversations/uniqueconversationId/uniquemessageId/
and inside the unique message I store text, user, etc. Every time a new message is posted in the app, I push a new message to the conversation.
In Cloud Functions, I want to know when a new message is posted and send a notification. This is almost 100% the same as the codelab example.
exports.sendNotification = functions.database.ref('/conversations/{conversationId}').onWrite(event => {
  const snapshot = event.data;
  // Only send a notification when a new message has been created.
  if (snapshot.previous.val()) {
    return;
  }

  console.log(snapshot);
  ...

All the examples show accessing the snapshot value is as simple as
const text = snapshot.val().text;

But that doesn't work for me.  When I attempt to access it, it says it is undefined. When I keep the check of snapshot.previous.val() which I pulled straight from codelab, it just returns, even though I'm posting a new message.  (And even if I take this out so I can log the snapshot, it still doesn't work.)
When I look in the console, the DeltaSnapshot is huge and contains all the message objects in the conversation.  I cannot directly access the new message values as expected.
Here is the chunk of code that writes to the DB (this is from React, BTW). This write works perfectly.
var messageData = {
    user: {
       _id: user.uid,
        name: user.fullName
    },
    text: messageText,
    createdAt:firebase.database.ServerValue.TIMESTAMP,
    sentToUser: conversation.recipientUid
};

this.getRef().child('conversations').child(conversation.conversationId).push(messageData)

Here is the JSON for an example message:
{
    "-Km9qFcNClX3uQXX51D1" : {
      "createdAt" : 1496978098834,
      "text" : "Test message sent",
      "user" : {
        "_id" : "cKFnsNkYSyNXm5duUy",
        "name" : "Test User"
      }
    }
}

Ideally, based on the examples I would expect to be able to just use snapshot.val().text and get "Test message sent."
Any direction you can point me in will be appreciated. Thanks.

A: You're triggering on writes one level too high.  You want writes to the message ID:
functions.database.ref('/conversations/{conversationId}/{messageId}').onWrite(...)

Then the snapshot will be for the messageData under messageId and not the list of all the messages in the conversation.


text:
Q: I am not able to start MongoDB ON WINDOWS 10 Mongod is not starting on windows 10 it shows 'access control is not enabled for the database. Read and write access to data and configuration is unrestr 10.

A: Mongo is started and is running. This message is simply a notice, not an error. It says that your Mongo database is insecure because anyone is able to read and write. This is fine for your development purposes on your computer, but you should change the settings if you use Mongo for a production, customer-facing website.


text:
Q: ol-ext Control Bar and function in the Controller I have an extjs app in which I am using an ol-ext control bar. The control bar is in the file MyApp.js and the function that I want to call clicking on the button belonging the control bar is in the relative controller MyAppController.
In MyApp.js:

var testFuction = function(){
   return this.getController().updateImages;
};

var mainbar = new ol.control.Bar();
var first = new ol.control.Button (
 {
       html: '1',
       //handler: 'updateImages',
       //reference: 'locationShowImageButton',
        handleClick: testFuction,
 });

//Standard Controls
mainbar.addControl (first);
mainbar.setPosition('bottom-right');
this.map.addControl(mainbar);

In MyAppController:

updateImages: function (obj) {
            var self = this;
            this.getView().cleanImageLayers();
            var selectedFloors = ; //it should be the value of the  ol.control.Button, so 1
            if (this.lookupReference('locationShowImageButton').pressed) {
               .....

A: First check if this.getController() in MyApp.js refer to MyAppController.

You can't use ol.control.Button like sencha component.

You should use this in your MyApp.js scope.
var mainbar = new ol.control.Bar();
var me = this;
var first = new ol.control.Button (
 {
        html: '1',
        handleClick: function () {
            me.getController().updateImages();
        }
 });

//Standard Controls
mainbar.addControl (first);
mainbar.setPosition('bottom-right');
this.map.addControl(mainbar);


text:
Q: OneNote API (REST) -- How to maintain the line breaks and spacing of the OneNote page while updating the content of page using PATCH service? I am getting the HTML of the OneNote page using GET pages REST API of OneNote. Here is the dummy code --

<title>Sales meeting III</title>
<meta http-equiv="Content-Type" content="text/html; charset=utf-8" /> <meta name="created" content="2017-03-14T17:30:00.0000000" />

Sales Meeting

donderdag 9 maart 2017

20:00

Send draft press release to marketing team

Schedule briefing

Jack is the greatest

This is Testing

Now, I am updating only "p" (paragraph) tag using their unique id by "replace" method in PATCH API. This action is not at all related to rest of the HTML of the page as per my knowledge. Content is getting updated properly and I am getting successfull response from the API but it is removing br tags as well. Which disturbs the indentation of the page.
How can I maintain the indentation of page or how to avoid the removal of br tags or line breaks of the page, I want them as it is on the page.
Thanks in advance.

A: Hi AnupamHow are you creating your OneNote page?I've just tried creating a page both programmatically and by direct editing in OneNote Online and the br tags are confined to paragraph tags and survive patching.

A: Here are the answers to your 2 questions -

*

*How to maintain line breaks

*

*To maintain line breaks 'br' you can replace the entire 'div' instead of the specific item in the page

*How to maintain indentation

*

*Except for the 'pre' tag, OneNote Api does not support indentation at present.


text:
Q: Defining injective functions in Z3 My goal is to define an injective function f: Int -> Term, where Term is some new sort. Having referred to the definition of the injective function, I wrote the following:
(declare-sort Term)
(declare-fun f (Int) Term)
(assert (forall ((x Int) (y Int))
                (=> (= (f x) (f y)) (= x y))))
(check-sat)

This causes a timeout. I suspect that this is because the solver tries to validate the assertion for all values in the Int domain, which is infinite.
I also checked that the model described above works for some custom sort instead of Int:
(declare-sort Term)
(declare-sort A)
(declare-fun f (A) Term)
(assert (forall ((x A) (y A))
                (=> (= (f x) (f y)) (= x y))))
(declare-const x A)
(declare-const y A)
(assert (and (not (= x y)) (= (f x) (f y))))
(check-sat)
(get-model)

The first question is how to implement the same model for Int sort instead of A. Can solver do this?
I also found the injective function example in the tutorial in multi-patterns section. I don't quite get why :pattern annotation is helpful. So the second question is why :pattern is used and what does it brings to this example particularly.

A: I am trying this
(declare-sort Term)
(declare-const x Int)
(declare-const y Int)
(declare-fun f (Int) Term)
(define-fun biyect () Bool
    (=> (= (f x) (f y)) (= x y)))
(assert (not biyect))
(check-sat)
(get-model)

and I am obtaining this
sat
(model
  ;; universe for Term:
  ;; Term!val!0
  ;; -----------
  ;; definitions for universe elements:
  (declare-fun Term!val!0 () Term)
  ;; cardinality constraint:
  (forall ((x Term)) (= x Term!val !0))
  ;; -----------
  (define-fun y () Int
    1)
  (define-fun x () Int
    0)
  (define-fun f ((x!1 Int)) Term
    (ite (= x!1 0) Term!val!0
    (ite (= x!1 1) Term!val!0
      Term!val!0)))
  )

A: What do you think about this
(declare-sort Term)
(declare-fun f (Int) Term)
(define-fun biyect () Bool
    (forall ((x Int) (y Int))
            (=> (= (f x) (f y)) (= x y))))
(assert (not biyect))
(check-sat)
(get-model)

and the output is
sat
(model
;; universe for Term:
;; Term!val!0
;; -----------
;; definitions for universe elements:
(declare-fun Term!val!0 () Term)
;; cardinality constraint:
(forall ((x Term)) (= x Term!val!0))
;; -----------
(define-fun x!1 () Int 0)
(define-fun y!0 () Int 1)
(define-fun f ((x!1 Int)) Term
 (ite (= x!1 0) Term!val!0
 (ite (= x!1 1) Term!val!0
   Term!val!0)))
)


text:
Q: Podcast feed in Android app I am working on an android app for my church and would like to put our sermons on it. The company we upload our sermons to automatically makes a podcast feed for it. Basically I am looking for a way to list podcasts inside of the app. I would like it to be hardcoded to one podcast. I have looked online but cannot really find anything about. I am not sure how to code the podcast part. More than likely the actual playing can be handed off to a secondary app.

A: there two steps i recommend.
A) Use the Aquery lib to parse the xml or json returned by the podcast feed link.
Check it out https://code.google.com/p/android-query/. Doesnt matter what layout you use to display the podcast items.
B) Then you can Streaming the audio from A URL using MediaPlayer. http://www.tutorialspoint.com/android/android_mediaplayer.htm
Good luck


text:
Q: Iterate over all bits of byte in C# I am working on a C# application. I have a byte variable, i want to iterate over all bits of it.
byte var = 3;
System.Collections.BitArray bits = new System.Collections.BitArray(var);
Console.WriteLine("Length of collection : " + bits.Length);
for (int i = 0; i < bits.Length; i++)
{
    Console.WriteLine(bits[i]);
}

This code gives me the following output:
Length of collection : 3
False
False
False

But as the binary representation of 3 is 00000011 so i expect the following output
False
False
False
False
False
False
True
True

What am i doing wrong ? How can i achieve the required output

A: You're calling the BitArray(int length) constructor:

Initializes a new instance of the BitArray class that can hold the specified number of bit values, which are initially set to false.

So you're creating a BitArray of length 3, not a BitArray which contains the bits from the integer value 3.
You want the BitArray(byte[] bytes) constructor:

Initializes a new instance of the BitArray class that contains bit values copied from the specified array of bytes.

byte var = 3;
BitArray bits = new BitArray(new byte[] { var });
Console.WriteLine("Length of collection : " + bits.Length);
for (int i = 0; i < bits.Length; i++)
{
    Console.WriteLine(bits[i]);
}

Outputs:
Length of collection : 8
True
True
False
False
False
False
False
False


text:
Q: Configure log4j org.apache.log4j.rolling.RollingFileAppender so that compressed logs are removed once the number of logs passes a set index amount I am using the org.apache.log4j.rolling.RollingFileAppender in the apache-log4j-extras package to compress the log once they are no longer the active log. Here is an example appender:

<appender name="TRACELOG" class="org.apache.log4j.rolling.RollingFileAppender">
    <param name="file" value="logFileName.log" />

    <rollingPolicy class="org.apache.log4j.rolling.TimeBasedRollingPolicy">
        <param name="FileNamePattern" value="logFileName.%d.log.gz" />
    </rollingPolicy>

    <layout class="org.apache.log4j.PatternLayout">
        <param name="ConversionPattern" value="%d %-5p [%t] %C{2} (%F:%L) - %m%n" />
    </layout>

    <filter class="org.apache.log4j.varia.LevelMatchFilter">
        <param name="LevelToMatch" value="trace" />
        <param name="AcceptOnMatch" value="true" />
    </filter>
    <filter class="org.apache.log4j.varia.DenyAllFilter" />
</appender>

What I would like to do is add something like <param name="MaxBackupIndex" value="14" /> so that it will essentially only keep 14 days worth of compressed logs, but when I try and use it, I get the following warning:

log4j:WARN No such property [maxBackupIndex] in org.apache.log4j.rolling.RollingFileAppender.

A: in extra rolling file appender (not the standard) there is no way to specify the rolling policy directly in the appender, cause it's specified in the rolling policy field.
The problem is that you're using a TimeBasedRollingPolicy that doesn't support maxBackupIndex, maxBackupIndex is only supported in FixedWindowRollingPolicy

A: You can write your custom file appender, which extends RollingFileAppender.
Here is an example: http://www.javaworld.com/community/node/6148


text:
Q: A column in a table is referred to by multiple physical column names I have a spring boot project using JPA, So I am trying to map two tables into a third one using their Id :
for example I have a coupon class, I have a customer class I want to take customer id and coupon id into a third table.
I have coupons:
@Entity
@Table(name = "coupons")
public class Coupon {

    @Id
    @GeneratedValue(strategy = GenerationType.IDENTITY)

    private long coup_id;
    private String title;
    private String start;
    private String end;
    private int amount;
    private String type;
    private String message;
    private double price;
    private String image;

    @ManyToMany(mappedBy = "coupons")
    private List<Customer> customers;

I have customers:
@Entity
@Table(name="customers")
public class Customer {

    @Id
    @GeneratedValue(strategy=GenerationType.IDENTITY)

    private int cust_id;

    @Size(min=1,message="is required")
    private String cust_name;

    @Size(min = 1, message = "is required")
    private String password;
     @ManyToMany(cascade = { CascadeType.ALL })
        @JoinTable(
            name = "customer_coupon",
            joinColumns = { @JoinColumn(name = "cust_id") },
            inverseJoinColumns = { @JoinColumn(name = "coup_id") }
        )
    private List<Coupon> coupons;

and I have the connecting table customer_coupon:

This is the error I am getting when starting the project:
Caused by: org.hibernate.DuplicateMappingException: Table [coupons] contains physical column name [coup_id] referred to by multiple physical column names: [coupId], [coup_id]

I have no idea where it comes from, would love if someone could help me !

A: Found the problem...sorry.
Had another class Company that was referring to coupId as well:
     @OneToMany(
            cascade = CascadeType.ALL,
            orphanRemoval = true
        )
 @JoinColumn(name = "coupId")
private List<Coupon> coupons = new ArrayList();

This is from the Company class.

A: I had same problem.
@Column(name = "coup_id") private long coupId;
and column in db table called coup_id.
I removed @Column annotation, and workin! Thats all.
Hibernate convert xX to x_x itself.

A: To remove ambiguity use the @Column annotation:
@Column(name = "coup_id")
private long coupId;

This way you can name your Java attributes as you like and don't let JPA alone for interpreting them.

A: Another situation where I had this problem is due to case sensitivity. I mentioned a column name as ownerid and ownerId in two classes. As per Error: Table [] contains logical column name [ownerid] referring to multiple physical column names [ownerid] and [owner_id]. I ended up spending a lot of time searching for owner_id.

A: I have join table, that is also entity and have ManyToOne relationships to two tables, so it is not exactly this issue, but could help someone.
Adding @MapsId(property name) to @ManyToOne property worked for me.

A: it might be because of miss the mapped by
i was have the issue in this code
@OneToMany
@JsonManagedReference
private List<TweetsEntity> userTweets;

but after make it this way (add the mappedBy)
@OneToMany(mappedBy = "user")
@JsonManagedReference
private List<TweetsEntity> userTweets;

its solved for me


text:
Q: Command-line tool for converting PLIST to JSON? Is there a command line tool available for converting .plist files to JSON?
If not, what would be the approach for creating one using Objective-C or C on a Mac? For instance, there is JSONKit, for Objective-C. How would one go about opening a .plist file, pass it to JSONKit, and serialize that as JSON?

A: The following gets the job done—
// convertPlistToJSON.m
#import <Foundation/Foundation.h>
#import "JSONKit.h"

int main(int argc, char *argv[]) {
  NSAutoreleasePool *pool = [[NSAutoreleasePool alloc] init];

  if(argc != 3) { fprintf(stderr, "usage: %s FILE_PLIST FILE_JSON\n", argv[0]); exit(5); }

  NSString *plistFileNameString = [NSString stringWithUTF8String:argv[1]];
  NSString *jsonFileNameString  = [NSString stringWithUTF8String:argv[2]];

  NSError *error = NULL;

  NSData *plistFileData = [NSData dataWithContentsOfFile:plistFileNameString options:0UL error:&error];
  if(plistFileData == NULL) {
    NSLog(@"Unable to read plist file.  Error: %@, info: %@", error, [error userInfo]);
    exit(1);
  }

  id plist = [NSPropertyListSerialization propertyListWithData:plistFileData options:NSPropertyListImmutable format:NULL error:&error];
  if(plist == NULL) {
    NSLog(@"Unable to deserialize property list.  Error: %@, info: %@", error, [error userInfo]);
    exit(1);
  }

  NSData *jsonData = [plist JSONDataWithOptions:JKSerializeOptionPretty error:&error];
  if(jsonData == NULL) {
    NSLog(@"Unable to serialize plist to JSON.  Error: %@, info: %@", error, [error userInfo]);
    exit(1);
  }

  if([jsonData writeToFile:jsonFileNameString options:NSDataWritingAtomic error:&error] == NO) {
    NSLog(@"Unable to write JSON to file.  Error: %@, info: %@", error, [error userInfo]);
    exit(1);
  }

  [pool release]; pool = NULL;
  return(0);
}

It does some reasonable error checking, but it's not bullet proof.  Use at your own risk.
You'll need JSONKit to build the tool.  Place JSONKit.m and JSONKit.h in the same directory as convertPlistToJSON.m, and then compile with:
shell% gcc -o convertPlistToJSON convertPlistToJSON.m JSONKit.m -framework Foundation

Usage:
shell% convertPlistTOJSON
usage: convertPlistToJSON FILE_PLIST FILE_JSON

shell% convertPlistTOJSON input.plist output.json

Reads in input.plist, and writes the pretty printed JSON to output.json.

A: Using mac utils
Convert plist to json
plutil -convert json -o output.json input.plist

Convert json to plist
plutil -convert xml1 input.json -o output.plist

A: The code is fairly simple to do this:
NSArray* array = [[NSArray arrayWithContentsOfFile:[@"~/input.plist" stringByExpandingTildeInPath]]retain];
SBJsonWriter* writer = [[SBJsonWriter alloc] init];
NSString* s = [[writer stringWithObject:array] retain];
[s writeToFile:[@"~/output.json" stringByExpandingTildeInPath] atomically:YES];
[array release];

I never got around to making it accept arguments as I only needed to do 3 files.

A: I wrote a tool in python to do this. See here:
http://sourceforge.net/projects/plist2json
Works from command line on os x or linux distros, batch converts a directory. It's short and simple so it should be easy to modify for your own purposes.

A: There is a native way, to convert plist's to json. It's called NSJSONSerialization.
Here is an example on how to use it, and convert a plist file to a json file:
NSDictionary *plistDict = [NSDictionary dictionaryWithContentsOfFile:@"input.plist"];

NSError *error;
NSData *jsonData = [NSJSONSerialization dataWithJSONObject:plistDict options:NSJSONWritingPrettyPrinted error:&error];
NSString *jsonString = [[NSString alloc] initWithData:jsonData encoding:NSUTF8StringEncoding];
[jsonString writeToFile:@"output.json" atomically:NO encoding:NSUTF8StringEncoding error:&error];

A: Converts Filename.plist to Filename.json:
plutil -convert json -r -e json Filename.plist

-convert indicates format, -r makes the output more human-readable, -e specifies an extension

A: If you run into issues with "invalid object in plist for destination format", you probably have bytes-like data in the plist, which plutil does not consider serializable to json.
Python has built-in plist support, and we can specify a custom default function to specify what to do when serialization fails (e.g. on bytes). If you don't care about the bytes fields, we can just serialize them as '<not serializable>' with the following python one-liner:
python -c 'import plistlib,sys,json; print(json.dumps(plistlib.loads(sys.stdin.read().encode("utf-8")), default=lambda o:"<not serializable>"))'
This takes the stdin, parses the plist, then dumps it to json. For example, to get current power information for your Mac, you can run:
ioreg -rw0 -c AppleSmartBattery -a | python -c 'import plistlib,sys,json; print(json.dumps(plistlib.loads(sys.stdin.read().encode("utf-8")), default=lambda o:"<not serializable>"))'
and if you wanted to just get the current charging wattage, you could pipe that into jq '.[0].AdapterDetails.Watts'

A: If you are on a Mac you can use the plutil tool on the command line (this comes with the developer tools I believe):
plutil -convert json Data.plist

as mentioned in the comments, this will overwrite the existing data. To output to a new file
plutil -convert json -o Data.json Data.plist


text:
Q: Prove that $L^{\infty} [0,1]$ is not separable.
Prove that $L^{\infty} [0,1]$ is not separable.

I know that $\ell^{\infty} = L^{\infty} (\Bbb N, \mathcal P (\Bbb N), \mu_c)$ is not separable where $\mu_c$ is the counting measure on $\mathcal P (\Bbb N).$ The way I proved that is to construct sequences in $\ell^{\infty}$ whose range set is contained in $\{0,1\}.$ Then such collection is uncountable and any two sequences are $1$ unit apart with respect to $\ell^{\infty}$-norm and then if we consider open balls of radius $\frac {1} {2}$ around each of the sequences then they are all disjoint and hence any dense subset of $\ell^{\infty}$ has to contain at least one element from each of these disjoint open balls. Since the number of such open balls is uncountable it follows that any dense subset of $\ell^{\infty}$ contains uncountably many elements and hence $\ell^{\infty}$ cannot be separable. How do I argue the same for $L^{\infty} [0,1]\ $?
I think of a collection of functions $\{f_{\alpha}\}_{\alpha \in I},$ for some indexing set $I$ such that $f_{\alpha} \left (\frac {1} {n} \right ) = 0\ \text {or}\ 1$ and $f_{\alpha} (x) = 0,$ for $x \not\in \left \{\frac {1} {n}\ \big |\ n \in \Bbb N \right \}.$ Then I think this collection will work here. Am I right?

A: Functions in $L^{\infty}$ are defined only up to a set of measure $0$. The value at $\frac 1  n$ is not well defined. So your argument does not work.
Define $T:\ell^{\infty} \to L^{\infty} ([0,1])$ by $T(a_n)=\sum a_n \chi_{(\frac 1{n+1}, \frac 1n)}$ Check that $T$ is an isometric isomoprphism. Can you finish?


text:
Q: How to add sql "BETWEEN" conditions inside CASE within WHERE CLAUSE in SQL I have a sql query where I need to add different statements(between statements) in where clause based on one condition.  If TX.APPLICATION_ID is 'CONV' then I need to add filter date range on SYS_CREATION_DATE and if APPLICATION_ID is not 'CONV' then I need to add filter date range on TRANS_DATE. Here is what i'm trying and getting 'missing keyword' error. please suggest
WHERE TX.TRANS_TYPE IN ('CREDIT', 'CREDITR','CREDITR9', 'DSPJUS')
  AND
    CASE
    WHEN TRIM(TX.APPLICATION_ID) = 'CONV'
    THEN
      TX.SYS_CREATION_DATE  BETWEEN  TO_DATE('20200831', 'YYYYMMDD')  AND  TO_DATE('20200831', 'YYYYMMDD')
    ELSE
       TX.TRANS_DATE BETWEEN TO_DATE('20200831', 'YYYYMMDD') AND TO_DATE('20200831', 'YYYYMMDD')
    END

A: You should remove the CASE expression logic, which generally never belongs in the WHERE clause.  Instead, use vanilla AND/OR:
WHERE
    TX.TRANS_TYPE IN ('CREDIT', 'CREDITR','CREDITR9', 'DSPJUS') AND (
    (
        TRIM(TX.APPLICATION_ID) = 'CONV' AND
        TX.SYS_CREATION_DATE >= date '20200831' AND
        TX.SYS_CREATION_DATE < date '20200901'
    )
    OR
    (
        TRIM(TX.APPLICATION_ID) <> 'CONV' AND
        TX.TRANS_DATE >= date '20200831' AND
        TX.TRANS_DATE < date '20200901'
    ))


text:
Q: Help with substitutions in multiple integrals I am in the middle of a homework problem and can't find out what I am doing wrong. The question asks:

Use the transformation in Exercise 2 (given as $u=x+2y$, $v=x-y$) to evaluate the integral $\int_{0}^{\frac{2}{3}}\int_{y}^{2-2y}(x+2y)e^{y-x}dxdy$ by first writing the integral over a region G in the $u v$-plane.

My work is as follows:
Finding x and y in terms of u and v: I found that $x=\frac{u}{3}+\frac{2}{3}v$ and that $y=\frac{u}{3}-\frac{v}{3}$

My work for the above: $v=x-y$   ->   $y=x-v$
$v=x+2y$ -> $x=u-2y$
$x=u-2(x-v) = u-2x+2v \equiv 3x=u+2v = \frac{u}{3} + \frac{2}{3}$
$y=u-2y-v\equiv3y=u-v=\frac{u}{3}-\frac{v}{3}$

Then finding the Jacobian using the coefficients of the aforementioned x and y equivalents: \begin{bmatrix} \frac{1}{3} & \frac{2}{3} \\[0.3em]
\frac{1}{3} &-\frac{1}{3}
\end{bmatrix} $=-\frac{7}{9}$
Solving for the bounds and equation in terms of $u$ and $v$: $\int_{0}^{\frac{2}{3}}\int_{0}^{2}(u)e^{-v}(-\frac{7}{9})dudv$
The answer I get is $-\frac{14}{9}(1-\frac{1}{e^\frac{2}{3}})$, which is not what the answer is supposed to be: $\frac{1}{3}(1+\frac{3}{e^2})$

A: First of all, your computation of $u$ and  $v$ in terms of  $x$ and  $y$ is correct. However your the determinant of your Jacobian is  $- \frac{1}{3}$  so  its absolute value is  $ \frac{1}{3}$   (Easy to check that) .
Now for your boundaries . In the first integral you have  $$  0 \leq y \leq  2/3 $$  and  $$ y \leq x\leq  2-2y$$ so in terms of  $u$ and  $v$ we get  $$  0 \leq \frac{u-v}{3} \leq  2/3 $$  and  $$ \frac{u-v}{3}   \leq \frac{u+2v}{3} \leq  2-2\frac{u-v}{3} $$
The first one implies $$ v \leq  u \leq 2+v $$ qnd the second implies  $$  u-v \leq  u+2v  \text{ and } u+2v \leq 6-2u+2v$$  and so  treating these last two inequalities we get  $$  -v \leq  2v  \text{ and } u\leq 6-2u $$  i.e.   $$  3v \geq 0  \text{ and } 3u\leq 6 $$ so that   $$  v \geq 0  \text{ and } u\leq 2 $$ plotting this region we get
so you integral  should be  $$\frac{1}{3 } \int_0^2 \int_0^u u e^{-v}dvdu$$
Try to compute it, and you will find the desired result. Hope this helps you.


text:
Q: Compiler complains about possible undefined in nested objects I have the following sample code: sample on typescriptlang.org (activate strictNullChecks)
 1. let boolVar: number | undefined;
 2.
 3. if (boolVar) {
 4.     boolVar.toString; // all fine
 5. }
 6.
 7. let objectVar: { [key: string]: number | undefined } = {a: 1};
 8.
 9. const selector = "a";
10. if (objectVar[selector]) {
11.     objectVar[selector].toFixed; // Object is possible undefined? o0
12. }

Why does the compiler complains about line 11.: Object is possible undefined when I explicitly check for this object in line 10.?

A: Type guards (which is what you are using when you write if (objectVar[selector]) and expect the type to change based on the check) do not work with index access. This is documented in this and this issues. The reason for this is (as stated by @RyanCavanaugh in comments to the issue)

Declined due to performance reasons. Since it should almost always be possible to write const j = list[i] instead, this shouldn't be too burdensome.

As is stated above the recommendation is to use a local variable :
let objectVar: { [key: string]: number | undefined } = {a: 1};

const selector = "a";
const objectVar_selector = objectVar[selector];
if (objectVar_selector) {
    objectVar_selector.toFixed; // Object is possible undefined? o0
}


text:
Q: Force compilation error on missing static member variable in derived classes Assuming the following class hierarchy:
//file base.h
class IBase
{
public:
    virtual ~IBase() = default;

    //a static member identifying IBase (e.g. "iid.base")
    static const char* const IID;  //initialize in implementation file
//[...]
};//class IBase

class IDerived : public IBase
{
public:
    virtual ~IDerived() = default;

    //a static member identifying IDerived (e.g. "iid.derived")
    static const char* const IID;  //initialize in implementation file
//[...]
};//class IDerived

class IEvenMoreDerived : public IDerived
{
public:
    virtual ~IEvenMoreDerived() = default;

    //missing static const member IID!
//[...]
};//class IEvenMoreDerived

Every class in this hierarchy must have its own static const tChar* const iid which can be used to identify the object without instantiating it. In IEvenMoreDerived this information is missing.
Now, somewhere in the code, I have a function template where the IID is accessed:
//file main.cpp
#include "base.h"

template<typename T>
void queryIID()
{
    std::cout << T::IID << std::endl;
}

int main(int argc, char* argv[])
{
    queryIID<IBase>();             //prints "iid.base"
    queryIID<IDerived>();          //prints "iid.derived"
    queryIID<IEvenMoreDerived>();  //probably prints "iid.derived"
    return 0;
}

My intention is to get a compile time error when using queryIID<IEvenMoreDerived>(); as IEvenMoreDerived doesn't have a static member iid. I assume it might be possible using some template magic inside function template queryIID(), but everything I tried didn't solve the issue.
Some additional points:

*

*Using constexpr char* instead of static const char* const unfortunately seems not possible as according to The MS VS2015 Feature Preview even in VS2015 it won't be supported.

*After some digging I came across the C++ Templates FAQ. According to this, member hiding is a "feature" of class templates. I just couldn't figure out how I might use this to solve my problem. Furthermore I don't want the class hierarchy as presented above to be changed to class.

*Among other questions, I found this somewhat similar question on SO, but it didn't entirely match my problem.

A: As a workaround, you may delegate Id in an external structure, something like:
template <typename T>
struct IdName
{
    static const char* const IID;
};

// instead of `const char* const IBase::IID = "IBase";`
// you have to use the following
template <> const char* const IdName<IBase>::IID = "IBase";
// Same for IDerived
template <> const char* const IdName<IDerived>::IID = "IDerived";

And you got linking error when trying to use IdName<IEvenMoreDerived>::IID.
Live example


text:
Q: How to get array of path points or linear interpolation (lerp) on a hyperbolic plane? The gist of it is, how do you animate between two points on a hyperbolic plane?
So we have basic linear interpolation (lerp) through tweening libraries such as GSAP's TweenMax, where you can specify a start and end position and a duration, and it will call your lerp function with the percentage (from 0 to 1) of completion of the duration (i.e. the percent of time passed), along with the start and end values:
const lerp = (v0, v1, t) => v0 * (1 - t) + v1 * t

You can customize the animation flow with easing functions in this situation, like:
x = lerp(startX, endX, easeInOutSine(t))

function easeInOutSine(x) {
  return -(cos(PI * x) - 1) / 2
}

In the end, you can compose a dynamic animation like this, by just specifying a few key states, and then tweening between them:

But how can you do this for the hyperbolic plane? I am thinking like the game HyperRogue but where you click on an outer tile, and it tweens you around to that tile. That is, I think it moves along the hyperbolic geodesic (the visibly curved path from start to end state).
I have these functions I'm working with from the MagicTile project, which I ported to TypeScript:
// The pure translation (i.e. moves the origin straight in some direction) that takes p1 to p2.
// I borrowed this from Don's hyperbolic applet.

PureTranslation(g: Geometry, p1: Complex, p2: Complex) {
  let A: Complex = p2.Subtract(p1)
  let B: Complex = p2.Multiply(p1)

  let denom: number =
    1 - (B.Real * B.Real + B.Imaginary * B.Imaginary)

  let P: Complex = new Complex(
    (A.Real * (1 + B.Real) + A.Imaginary * B.Imaginary) / denom,
    (A.Imaginary * (1 - B.Real) + A.Real * B.Imaginary) / denom,
  )

  this.Isometry(g, 0, P)
  this.Normalize()
}

// Move from a point p1 -> p2 along a geodesic.
// Also somewhat from Don.

Geodesic(g: Geometry, p1: Complex, p2: Complex) {
  let t: Mobius = Mobius.construct()
  t.Isometry(g, 0, p1.Negate())

  let p2t: Complex = t.ApplyComplex(p2)
  let m2: Mobius = Mobius.construct()
  let m1: Mobius = Mobius.construct()
  m1.Isometry(g, 0, p1.Negate())
  m2.Isometry(g, 0, p2t)

  let m3: Mobius = m1.Inverse()
  this.Merge(m3.Multiply(m2.Multiply(m1)))
}

This is defined on a Mobius class which calculates a Mobius transform. You don't need to know about Mobius transforms (I don't know much), but they have 4 complex number fields. They are then attached to an "Isometry", which is used to compute the transform for each polygon in a hyperbolic tessellation, like this:
Polygon p = tile.Polygon.Clone();
p.Transform( isometry );
Color color = getColor()
GLUtils.DrawConcavePolygon( p, color, GrabModelTransform() );

Given that, I would think about potentially calling the Geodesic function like this:
Geodesic(Geometry.Hyperbolic, currentPosition, desiredPosition)

That would, I think, compute the final transformation on the Mobius object on the Isometry. So that gives me the final position (I think so far).
My question is, given we have the final position, how do we do a lerp sort of function to animate to it? At a high level, how might you accomplish that?
I would think that one approach is to generate a hundred points between here and there, like path segment points (breaking down the curved path into small segments), and then tweening from one point to the next. That wouldn't be ideal though, so maybe there is an equation like the lerp function that would work. Either way, I don't see how I could accomplish it with either of these approaches. How do you take the difference between two points on the hyperbolic plane, get the arc'd path between them, and then animate along those arcs?


text:
Q: Can I downgrade the version of k8s docker desktop uses without modifying the version of docker desktop? I use an older version of k8s in prod and want the same version locally.
I don't want to roll back my entire docker desktop version though.
Also, ideally I would be able to switch between different versions of k8s locally or run several clusters of different versions simultaneously for testing migrations, etc. Is this possible?


text:
Q: View Controller value passing I have an iOS application that has Controller A, which uses a tableview that adopts the 3D touch protocol. Each cell actually adopts this 3D touch so when selecting a cell, it will bring a modal view controller (Controller B).
This controller B is basically used to fill information that is then added to the tableview on Controller A.
So in applying the DRY principle, I am reusing Controller B for adding and editing data.
Problem:
Controller B has a property
var didPresentVia3dTouch : Bool = false

and a method:
public func setPreference(editMode: Bool) {
   self.didPresentVia3dTouch = editMode
}

So this method is supposed to set the value of didPresentVia3dTouch to true from false when the tablecell in Controller A is forced touch, rather than being presented thru the navigation item button as a general 'Add' call.
in Controller A, i've kept a reference to Controller B like so:
var controllerBref = AddEditViewController()

so in the method
func previewingContext(previewingContext: UIViewControllerPreviewing, commitViewController viewControllerToCommit: UIViewController)
I call the method setPreference from Controller B like so:
controllerBRef.setPreference(true)

in order to invoke Controller B to act as an Edit view for data on that cell.
One issue that i've noticed is that when I print the value of Controller B's method setPreference(editMode: Bool), the editMode constant, it prints out true, but in the viewWillAppear, viewDidAppear, viewDidLoad, and all other methods, the value for didPresentVia3dTouch still reads false, so therefore not allowing me to change the title of the navigation bar whether its on Edit mode or Add new mode.
Is there something I am missing or not understanding here? I tried delegation but could not figure it out.

A: You need to set the property on the view controller instance that will be presented, not some random instance that you have instantiated and stored in a property.
Use:
func previewingContext(previewingContext: UIViewControllerPreviewing, commitViewController viewControllerToCommit: UIViewController) {
    if let destVC = viewControllerToCommit as? AddEditViewController {
        destVC.setPreference(editMode:true)
    }
}

A: The problem is that this line
var controllerBref = AddEditViewController()

has no relation  the currently presented VC , i mean it's a separate instance  , so when you present B set it to controllerBref