text:
Q: SQL Select list of last records with condition I have the following table
ID      Name        CodSituation
1       John 1
2       Mary 2
3       Mary 3
4       Mary 4
5       John 5
6       John 2
7 Mary 1
I want to select the Names, ID's and CodSituation for all users where their last entry is CodSituation=2
In these results I will get just the id 6 As Mary's last entry was CodeSituation=4
if more than one users have their latest CodSituation=2 I want them too.

A: [FINAL EDIT]
After seeing what was posted at the end of this answer I figured out that the user was asking the wrong question:
What they were asking was 'show me everyone who has CodSituation=2' when they meant 'Show me all the users who's last entry in CodSituation field=2'
Here is the correct query for that:
select a.ID, a.Name, a.CodSituation
from table_name a
inner join (
    select Name, max(ID) as MaxID
    from table_name
    group by Name
) b on a.Name = b.Name and a.ID = b.MaxID
where a.CodSituation = 2;

Here is the fiddle for that: http://sqlfiddle.com/#!2/a731d
[END]
[here are the previous queries, for reference]
Looks to me like you just need:
select * from table_name where CodSituation=2

To get all of the people with situation 2
To get only the last entry using mysql:
select * from table_name where CodSituation=2 order by id desc limit 1

To get the last entry using sql-server:
select top 1 * from table_name where CodSituation=2 order by ID desc;

See a working example here:
http://sqlfiddle.com/#!6/022fb/4
[edit]
OP supplied an actual dataset:
select Name from table_name where CodSituation=2 group by Name;

This shows all the unique users with a CodSituation of 2 (with one entry per person)
http://sqlfiddle.com/#!3/be404/2

A: Can be achieved like this, but may not be the best way to do this
Basically what I am doing is Create a temporary table and add the Name and Maximum row number.
Which then match again that the maximum row number row is associated with CodSituation=2
 Create Table #Temp2(Name Varchar(10),RowN int)

;WITH CTE AS (SELECT *,RN=ROW_NUMBER() OVER(PARTITION BY Name ORDER BY ID)
             FROM TableName)

insert into #Temp2
SELECT Name,MAX(RN)
FROM CTE
Group By Name

select TT.*
from
(
    SELECT *,RN=ROW_NUMBER() OVER(PARTITION BY Name ORDER BY ID)
             FROM TableName
)TT
cross apply (
            select Name
            from #Temp2 TB
            where TB.Name=TT.Name and TB.RowN= TT.RN
            ) Tab
Where CodSituation=2

Fiddle Sample

A: I found an easier way  concatenating fieds and using max solve this problem... Thanks!
SELECT
right(
max(
right(('0000000' + CONVERT(varchar,id) + '-'+ convert(varchar,codsituation)),4)),10),
name
FROM TABLE_NAME
GROUP BY name
HAVING
right(
max(
right(

  ('0000000' + CONVERT(varchar,id) + '-'+ convert(varchar,codsituation))
  ,4)),1) = 2

http://sqlfiddle.com/#!3/3dc1c/10


text:
Q: jQuery get index of certain child elements and ignore others I'm trying to get the index of a child element ol, but there is also some h2's in there which I don't need and are therefore polluting my results when using the jQuery index() function.
So I need the index of the ol, as if there weren't any h2's at all. So that if you click on the 3rd ol the index will be 2 and not 4.
The HTML looks like this:

Title

Item

Item

Item

Title

Item

Item

Item

Title

Item

Item

Item

Title

Item

Item

Item

And the jQuery:
$('ol li').click(function () {
    // get current index position of the ol
    var itemIndex   = $(this).parent('ol').index();

    alert(itemIndex);
});

A: If I well understood, try this code
var ol = $('ol');
ol.find('li').click(function () {
    var parentOl  = $(this).parent('ol');
    // get current index position of the ol
    var itemIndex = ol.index(parentOl);
    alert(itemIndex);
});

example jsbin : http://jsbin.com/enugex/1/edit

A: modify your code on jsfiddle
$('ol li').click(function (item,index) {
    // get current index position of the ol
      var itemIndex   = $(this).parents('div').children('ol').index($(this).parent('ol'));

    alert(itemIndex);
});

A: Try this
$(this).parent('ol').parent().children('ol').indexOf($(this).parent('ol'));

redpajama_set_name: RedPajamaStackExchange


text:
Q: NLog dll is not being copied over to consuming application from Class Library I am using class library as a reference to many applications. I have Nlog dll (4.5.3 for .Net Framework 4) being referenced in a class library through Hierarchy folder structure.
For example "D:\current\Bin\NLog.4.5.3\lib\net40-client". Somehow NLog dll is not being copied over to consuming application's bin folder and I am getting "System.IO.FileNotFoundException".
I made sure that Copy to Local is True(See attached NLog properties). I also applied false to it and again made it true as suggested in some other posts, but it did not work. Any suggestions on it?
Another thing which I don't understand is - I do have NLog 1.0.0.505(NLog for .Net 2) in "D:\current\Bin\" path. If I change NLog dll to 4.5.3 in mentioned path, Then it brings it over Nlog dll to consuming applications.
Though in my class library, there is no reference of parent path NLog dlls. But my class library dll files reside in "D:\current\Bin\" path and all applications are consuming it from here. Is there any possibilities that application is not going further down hierarchy for NLog dll and just keep checking limited to parent bin Hierarchy? Even though if I remove NLog dll(For .Net framework 2.0) from "D:\current\Bin\" path, it is not picking up NLog from Hierarchy path.
Class library and applications are both built on .Net framework 4.0

Exception - An unhandled exception of type 'System.IO.FileNotFoundException' occurred in class library.
Additional information: Could not load file or assembly 'NLog, Version=4.0.0.0, Culture=neutral, PublicKeyToken=5120e14c03d0593c' or one of its dependencies. The system cannot find the file specified.


text:
Q: Update not working in specific situation I am fetching a list of favourite skills for a user.
(userTable)->(user)->(favourite_skill)->(skills)
gun.get('userTable')
   .get(user.pk)
   .get('favorite_skill')
   .map()
   .on(
     (skill, pk) => {
       cb(skill, pk)
     }
   )

After editing one of those skills and updating, nothing happens.
The data remains the same on the gun server as well.
gun.get('skillTable').get(skill.pk).put(skill)

All works well when I fetch a complete skill list like this:
gun.get('skillTable').map().on(....)


text:
Q: Double Integral Over Region Common to Two Circles Evaluate $\iint\frac{(x^2+y^2)^2}{x^2y^2} dx dy$ over the region common to the circles $x^2+y^2=7x$ and $x^2+y^2=11y$.

A: You may use the Cylindrical coordinates to find the value of the integrals. This, as @Ron's Caesarian's approach, will get a bit messy but it works as well. We have two circles on $z=0$ intersected each other, so $$7r\cos\theta=7x=x^2+y^2=11y=11r\sin\theta\longrightarrow\theta_{0}=\tan^{-1}\left(\frac{7}{11}\right)\cong0.56$$ Now we have $$I=\int_{\theta=0}^{\theta_0}\int_{r=0}^{11\sin\theta}\frac{r^4}{r^4\cos^2\theta\sin^2\theta}rdrd\theta+\int_{\theta=\theta_0}^{\pi/2}\int_{r=7\cos\theta}^{0}\frac{r^4}{r^4\cos^2\theta\sin^2\theta}rdrd\theta$$

A: The intersection region is a football-shaped region symmetric about the line $y=7/11 x$.  When you do out the algebra to locate the circles' center and radii, you may derive the integration limits in Cartesians.  In this case, the integral takes the form
$$\int_0^{x_0} \frac{dx}{x^2} \, \int_{y_-(x)}^{y_+(x)} dy \frac{(x^2+y^2)^2}{y^2}$$
where $x_0$ is the rightmost intersection point $x$ coordinate, whch may be found to take the value
$$x_0=\frac{7 \cdot 11^2}{7^2+11^2} = \frac{847}{170}$$
$y_-$ and $y_+$ define the boundaries of the two circles:
$$y_-(x) = \frac{11}{2}-\sqrt{\frac{121}{4}-x^2}$$
$$y_+(x) = \sqrt{\frac{49}{4}-\left(\frac{7}{2}-x\right)^2}$$
Expanding the integrals, one gets a sum of three single integrals:
$$\int_0^{x_0} dx \, x^2 \left (\frac{1}{y_-(x)} - \frac{1}{y_+(x)}\right ) + 2\int_0^{x_0} dx \, [y_+(x)-y_-(x)] + \\\frac13 \int_0^{x_0} dx \frac{1}{x^2} \left [ y_+(x)^3-y_-(x)^3\right]$$
I will stop here, noting that the evaluation of these integrals, while messy, should be straightforward.  I should note that each of these integrals has been done in Wolfram Alpha (for example, here's one), and are doable through trig substitutions.


text:
Q: How can i read a .docx or .doc file directly from the URL link without downloading it to the local system in Python 3.7? I have built a resume parsing code in Python 3.7 but i want to read a .docx or .doc resume file directly from the URL link(e.g. http://13.234.163.240/storage/userData/phpjsK4iJ.docx) without downloading it to my local system.

A: How about Requests?
import requests
from io import BytesIO

r = requests.get('http://your.link/storage/file.docx')
fh = BytesIO(r.content)

your_resume_parser.parse_resume(fh)

More about Requests: https://2.python-requests.org/en/master/user/quickstart/


text:
Q: Missing operator in query expression with OleDb going into an Access database I am getting an error:
Syntax error (missing operator) in query expression.
Here is the SQL that is objected to:

I am guessing that Access feels it needs more parentheses somewhere. I have tried adding them in different places, with no luck so far.

A: Remove the ( at the after the from
      .....FROM ";
    sSQL += "[ComponentText] .....

instead of
    sSQL += "([ComponentText] ...

A: well, I am not sure what exactly was wrong, but I did revise the SQL and got it to work. The revision involved using a SELECT FROM (SELECT   ) AS Q  ... WHERE Component.Text IN (SELECT   ).
here is the sSQL that worked:
SELECT Q.[ComponentCounter] FROM (SELECT [ComponentText].[ComponentCounter],[ComponentText].[TextId],[ComponentText].[Text] FROM [ComponentText] WHERE [ComponentText].[TextId] = @bomgroupid AND [ComponentText].[Text] = @bomdevice) AS Q  INNER JOIN [Connection] as P ON Q.[ComponentCounter]=P.[CompCounter] WHERE  Q.[ComponentCounter] IN (SELECT [ComponentText].[ComponentCounter] FROM [ComponentText] WHERE [ComponentText].[TextId] = 160040 AND [ComponentText].[Text]= @type );
I am not in the habit of using Aliases, but it really helped simplify this SQL statement, both for myself and MS Access. I will have to remember that. Thanks everyone for the help.


text:
Q: Throw an aggregate exception from a task won't break all other tasks I have two tasks:
try
{
    List<Task> tasks = new List<Task>();

    Task task1 = Task.Factory.StartNew(() => func(param));
    tasks.Add(task1);
    if (someCondition)
    {
        Task task2 = Task.Factory.StartNew(() => func2(param2));
        tasks.Add(task2);
     }

     tasksArr = tasks.ToArray();

     Task.WaitAll(tasksArr);
 }
 catch (AggregateException e)
 {
     //handle
 }
 catch (Exception)
 {
     //handle
 }

If an exception occurs in one of the tasks, I'm throwing a new aggregation exception, but 'm reaching the catch statement only after the second task finishes. I want to catch it immediately, in order to stop unnecessary work in the second task.
I tried to use a cancellation token:
CancellationTokenSource cts = new CancellationTokenSource();

Task.WaitAll(tasksArr,cts.Token);

But this wasn't a good solution since it requires that the inner exception will be handled + the caught exception will be an OperationCanceledException
Any ideas?

A: To cancel waiting it is necessary to pass an instance of CancellationTokenSource class to Task.WaitAll Method (Task[], CancellationToken). Also, use a continuation on each task that runs when a task fails (faults, i.e. TaskStatus.Faulted).
var cancellationTokenSource = new CancellationTokenSource();

var tasks = new List<Task>();

var firstTask = new Task(FirstMethod);
firstTask.ContinueWith(t =>
    {
        Console.WriteLine("First task exception: {0}", t.Exception);
        cancellationTokenSource.Cancel();
    }, CancellationToken.None, TaskContinuationOptions.OnlyOnFaulted, TaskScheduler.Default);
tasks.Add(firstTask);
firstTask.Start();

var secondTask = new Task(SecondMethod);
secondTask.ContinueWith(t =>
    {
        Console.WriteLine("Second task exception: {0}", t.Exception);
        cancellationTokenSource.Cancel();
    }, CancellationToken.None, TaskContinuationOptions.OnlyOnFaulted, TaskScheduler.Default);
tasks.Add(secondTask);
secondTask.Start();

try
{
    var cancellationToken = cancellationTokenSource.Token;
    var tasksArray = tasks.ToArray();
    Task.WaitAll(tasksArray, cancellationToken);
}
catch (Exception e)
{
    // ...
}


text:
Q: Retrieve data from Redis and display them on the frontend I push and retrieve the data from the Redis list in the NodeJS(Express), but I cannot send them and display on the frontend (Angular).
I push the message with the lpush method and retrieve with lrange and I want to send these data to the frontend (with express -> app.get{}). On the frontend I use Angular with angular-socket-io factory.
Please take a look at the server.js file bellow.
var express = require('express');

var app = express();
app.use('/', express.static('../app/'));
app.use('/bower_components', express.static('../bower_components/'));

var server = require('http').createServer(app);
var io = require('socket.io').listen(server);

var bodyParser = require('body-parser');
var jsonParser = bodyParser.json();
var urlencodedParser = bodyParser.urlencoded({ extended: false });

var redis = require('redis')
var redisClient = redis.createClient();

/**
 *  Store a message in redis
 *
 *  @function storeMessage
 *  @param {String} name
 *  @param {Object} data
 */

function storeMessage (name, data) {
    var message = JSON.stringify({name:name, data:data});

    // store up to 10 messages
    redisClient.lpush('messages', message, function(error) {
        if (error) throw error;
        redisClient.ltrim('messages', 0, 10);
    });
};

io.sockets.on('connection', function (client) {

    /**
     *  When users join, set their nickname and broadcast they are here
     *  Add the user to redis
     */

    redisClient.lrange('messages', 0, -1, function( error, messages) {
        messages = messages.reverse();

        messages.forEach(function(message) {
            message = JSON.parse(message);
            client.emit('messages',message.name + ' : ' + message.data);
        });
    });
});

//!!TROUBLE HERE?? -> send data to the frontend
app.get('/messages', function (err, res) {
    'use strict';

    messages.forEach(function(res) {
        client.emit("messages", res.name + ": " + res.data);
    });
    res.send(messages);
});

server.listen(3000, function () {
    'use strict';
});


text:
Q: What is the class of arithmetic operations in python? I am currently making a simple calculator, and while I was trying to figure out what functions I should assign to tkinter buttons that represent arithmetic operations, this question hit me. So I tried to figure it out by using the type() but the output said it is an invalid syntax. They have meanings and certain functions so they can't just be nothing. What is their class?

A:
Do you mean operators like + and *? Those aren't objects, they can't be assigned to anything, it's not even meaningful to ask what class they are. (There are functions equivalent to all of the operators in the operator module, which may be of use in your program.)
- jasonharper


text:
Q: Writing comments in QGIS Graphical Modeler I want to explain my model step by step so anyone can easely understand what's going on.
So, is it possible to write comments in the QGIS's Graphical Modeler?

A: You can use the help text editor (button next to green "play" button) to edit informational metadata with your model:


text:
Q: Execution context was destroyed, most likely because of a navigation Puppeteer In my Puppeteer Node JS app I need to read localStorage and cookies from a browser web page, but for some reason I'm getting the following error:

UnhandledPromiseRejectionWarning: Error: Execution context was destroyed, most likely because of a navigation.

What am I doing wrong/missing from my JS:
const dayjs = require('dayjs');
const AdvancedFormat = require('dayjs/plugin/advancedFormat');
dayjs.extend(AdvancedFormat);

const puppeteer = require('puppeteer');
const { config } = require('./config');
const helpers = require('./helpers');
const logs = require('./logs');

const runEmulation = async (body) => {
  logs.debug('starting emulation');

  // vars
  const argOptions = [], journey = [];

  // sandbox config
  if ((config.puppeteer.run_in_sandbox === 'true')) {
    argOptions.push('--no-sandbox');
  }

  // initiate a Puppeteer instance with options and launch
  const browser = await puppeteer.launch({
    args: argOptions,
    headless: (config.puppeteer.run_in_headless === 'true') ? true : false
  });

  // launch a new page
  const page = await browser.newPage()

  // initiate a new CDP session
  const client = await page.target().createCDPSession();
  await client.send('Network.enable');
  await client.on('Network.requestWillBeSent', async (e) => {

    // if not a document, skip
    if (e.type !== "Document") return;

    const scrapablePageData = async () => {

      function getLocalStorage () {
        const values = [];
        const keys = Object.keys(localStorage);
        let index = keys.length;

        while (index--) {
          values.push({
            key: keys[index],
            value: localStorage.getItem(keys[index])
          });
        }

        return values ? values : [];
      }

      return {
        localStorage: getLocalStorage()
      }

    }

    const scrapable = await page.evaluate(scrapablePageData);
    const cookies = await page.cookies();

    // the data we want to log
    journey.push({
      url: e.documentURL,
      type: e.redirectResponse ? e.redirectResponse.status : 'JS Redirection',
      storage: {
        cookies: cookies ?? [],
        local: scrapable.localStorage ?? []
      },
      duration_in_ms: 0,
      duration_in_sec: 0,
      loaded_at: dayjs().valueOf()
    })
  })

  // set userAgent and go to the URL
  await page.setUserAgent(body.userAgent);
  await page.goto(body.url);
  await page.waitForNavigation();

  console.log(journey)
}

exports.runEmulation = runEmulation


text:
Q: Steam game positive/negative recommendations Is there a way to retrieve amount of positive/negative recommendations for a steam game?
I've found appdetails function, but it only returns total recommendations number:
"recommendations":{"total":5782}
E.g.
http://store.steampowered.com/api/appdetails?appids=57690

A: If this data doesn't exist in the JSON response you're getting from the api, not a chance mate :(


text:
Q: Inline PythonScript Azure Pipelines task in external file I am developing a Azure task template, and I have a large .py file that I want to be executed in one step
  - task: PythonScript@0
    displayName: 'Run a Python script'
    inputs:
      scriptSource: inline
      script: |
        ... really long python code

It's possible to store the code in another file, at the same level of the yml template, and consume it from there? Or what would be the best approach to keep the template clean?
I know that it's possible to use scriptSource
  - task: PythonScript@0
    displayName: 'Run a Python script'
    inputs:
      scriptSource: 'filePath'
      scriptPath: 'my_python.py'
      arguments: '${{ parameters.my_param }}'

But as the template is in another repository than the repository ran in the pipeline, I don't think that I can reach that my_python.py without downloading it with a wget, or cloning, or doing additional steps. I am right?
Regards!

A: To use a template from another repo you need to define repository source like here:
# Repo: Contoso/LinuxProduct
# File: azure-pipelines.yml
resources:
  repositories:
    - repository: templates
      type: github
      name: Contoso/BuildTemplates

steps:
- template: common.yml@templates  # Template reference

Once you have you need to just checkout this repo:
# Repo: Contoso/LinuxProduct
# File: azure-pipelines.yml
resources:
  repositories:
    - repository: templates
      type: github
      name: Contoso/BuildTemplates

steps:
- checkout: self
- checkout: templates #this download whole repo
- template: common.yml@templates  # Template reference

Now you need to figure out where it is downloaded ;)

Multiple repositories: If you have multiple checkout steps in your job, your source code is checked out into directories named after the repositories as a subfolder of s in (Agent.BuildDirectory). If (Agent.BuildDirectory) is C:\agent\_work\1 and your repositories are named tools and code, your code is checked out to C:\agent\_work\1\s\tools and C:\agent\_work\1\s\code.

So if you have script in scripts folder in templates repo you will find it in $(Agent.BuildDirectory)\templates\scripts\script.py.
So then you can use it like this:
  - task: PythonScript@0
    displayName: 'Run a Python script'
    inputs:
      scriptSource: 'filePath'
      scriptPath: '$(Agent.BuildDirectory)\templates\scripts\script.py'
      arguments: '${{ parameters.my_param }}'


text:
Q: Pass object to a new page I have some json which is being ng-repeated:
{
"title": "image title",
"description": "Lorem ipsum dolor sit amet, per ea ferri platonem voluptaria, ea eum ubique ornatus interpretaris. Dolore erroribus reprimique ex mea, mei soluta iisque cu, cu eam repudiare iracundia. Te cum populo molestie noluisse. Cu graece propriae eum, at qui erat oportere, ad wisi consequat persecuti pri. Ne usu partem discere, quas aliquam id cum. Tation numquam sensibus pri ne, his cibo noluisse scriptorem in.",
"imageUrl": "http://some.url.com",
"tags": "Apple, Orange, Banana, Pear, Grapes, Peach",
"owner": "some name",
"thumbnailUrl": "http://some.url.com"
},

On the index page it only shows the thumbnailUrl, if you click on the image it should pass that object to a new 'page'/template and display the description/author etc.
I've tried using various examples and none of which seem to work as I want. Quite confused and any help would be awesome.

A: If you are using some sort of router, you can pass this object to the new page, or like code90 said, you can use a service to maintain these objects between pages.
EDIT: Here is a link to the ui-router page
https://angular-ui.github.io/ui-router/site/#/api/ui.router


text:
Q: Grails and 3rd party tool use same database: how to update grails after 3rd party deletes? I'm writing a Service method (Grails 2.5.5) which deletes entities using a 3rd party rest API. Partway through my method, I call .refresh() on one of the entities, I get this exception:
org.springframework.orm.hibernate4.HibernateObjectRetrievalFailureException: No row with the given identifier exists: [MyEntity#7103]; nested exception is org.hibernate.UnresolvableObjectException: No row with the given identifier exists: [MyEntity#7103]

which is true since I just deleted it using the REST API. If it matters, the deleted MyEntity is in a hasMany on the entity I'm trying to refresh. I don't (think I) want to mark this as ignoreNotFound.
How do I tell Grails/Hibernate that it's ok that this record no longer exists?

A: I faced with same issue and found next solution.
So you have entity E that has list of entities A.
In case you need to delete entity A you need to do following:
 public void deleteA(List<Integer> ids) {
    if (!ids) {
        return
    }
    List<A> aToDelete = A.findAllByIdInList(ids)
    aToDelete.each { A a ->
        if(a.e) {
            E e = a.e
            e.a.remove(a)
        } else {
            a.delete()
        }
    }
}

So the idea is to check if A has any relation to E in case yes delete it via E otherwise delete it directly. For me works fine.


text:
Q: html source showing extra  tags here you will see  duration:50hrs.Now if you debug this using firebug, you will see extra

 tags after 50 hrs, whereas in actual html i made "duration:50 hrs" inside p tags
Please point out the reason.

A: It is not valid to have an
 (or any other block-level element) inside a
 tag. Consider using a
 tag with margins instead.

A: Upon inspecting the element I saw

The course offered by us cover complete and thorough knowledge of Search Engine Optimization, which is essential for the success of online business, Knowledge and understanding of the workings of search engines and the SEO skills that the course develops ensures clear understanding of Search Engine Optimization.
This course gives hands-on experience in the area of Search Engine Optimization and internet marketing.

Duration:
 50 Hrs

Pre-requisite:
 Basic Knowledge of computer & internet

This is not what you described, as the
 tags are placed in an order

Duration:
 50 Hrs

as you can see, on the second line there is a
 at the start, wich is in acordance to the ending

If the error is this neat then :)
To fix the error you will need to remove the
 tags aroung the text and simply add a
 wich will separate the two lines


text:
Q: Error on installation of ghc via homebrew hi im not sure what im doing and
basically i tried to get ghc and haskell-platform on to my mac via homebrew
however for reasons that i don't understand, ghc doesn't work hence neither does haskell-platform
according to brew doctor:
Warning: Unbrewed .pc files were found in /usr/local/lib/pkgconfig.
If you didn't put them there on purpose they could cause problems when
building Homebrew formulae, and may need to be deleted.

Unexpected .pc files:
    /usr/local/lib/pkgconfig/fuse.pc
its-fatbass:~ jellynom$ brew doctor
Warning: Unbrewed .pc files were found in /usr/local/lib/pkgconfig.
If you didn't put them there on purpose they could cause problems when
building Homebrew formulae, and may need to be deleted.

Unexpected .pc files:
    /usr/local/lib/pkgconfig/fuse.pc

but according to someone this can be ignore???
also i cannot seem to find the file to delete it (if i should delete it)
==> Downloading https://downloads.sf.net/project/machomebrew/Bottles/ghc-7.6.3.mo
######################################################################## 100.0%
==> Pouring ghc-7.6.3.mountain_lion.bottle.1.tar.gz
==> Caveats
This brew is for GHC only; you might also be interested in haskell-platform.
==> Summary
 /usr/local/Cellar/ghc/7.6.3: 5286 files, 776M
its-fatbass:~ jellynom$ brew install haskell-platform
==> Downloading http://lambda.haskell.org/platform/download/2013.2.0.0/haskell-pl
Already downloaded: /Library/Caches/Homebrew/haskell-platform-2013.2.0.0.tar.gz
==> ./configure --prefix=/usr/local/Cellar/haskell-platform/2013.2.0.0
configure: error: Your installation of ghc does not appear to work.
  It cannot compile a simple program (see config.log for the details).
  If you installed ghc from a generic binary tarball then it is worth
  checking that you have the 'gmp' C library and header files installed.
  (On Debian-based systems this package is called libgmp3-dev.)

READ THIS: https://github.com/mxcl/homebrew/wiki/troubleshooting

These open issues may also help:
    https://github.com/mxcl/homebrew/issues/20956

i don't know how to check for the gmp c library and header files
and the link they recommended is completely over my head too; something about hscolor missing.
Does this mean i have other things i should have installed prior to installing ghc??? (i have nothing else installed via homebrew other than ghc and haskell-platform)
if so, what should i have installed??


text:
Q: Maven Nested Modules - Naming Conventions/Best practices I just have I minor question where I did not find answers (or they were really old and I do not know if still accurate).
Lets assume I have something like a web application and I want to build it using maven.
Logically I might have something like the following structure:
application
    -client
        -theme
        -ui
    -server
        -service-1
        -service-2

Now how would the different groupIds and artifactIds look like?
And is it recommended/best practice that the root package name of a module is groupId.artifactId?
If yes, how do I handle a dash in my artifactId for the package name?
From my simple understanding I would have the following ids for the single modules (where application/client/server are just parent & aggregator poms):
my.domain:application
my.domain.application:client
my.domain.application.client:theme
my.domain.application.client:ui
my.domain.application:server
my.domain.application.server:service-1
my.domain.application.server:service-2

Or would it be better to prefix the non aggregating, non parent poms with the
application name (basically the "Leafs" of the hierarchy)? Or simply every artifactId? Again: how to handle the package name then?
So that, e.g. in a WAR the libraries are better distinguishable?
my.domain:application
my.domain.application:client
my.domain.application.client:application-theme
my.domain.application.client:application-ui
my.domain.application:server
my.domain.application.server:application-service-1
my.domain.application.server:application-service-2

This somehow is really confusing for me..
Thank you in advance for your help!


text:
Q: How to replace the last one or two characters of a file with unix tools I have a hanging comma at the end of a file that I would like to replace with a close square bracket.  There may or may not be a newline character at the end of the file as well.  How can I replace the one or two characters with the square bracket using common unix tools?

A: This will delete all trailing empty lines and then replace the last comma in the file with a ']'
cat origfile | sed -e :a -e '/^\n*$/{$d;N;ba' -e '}' | sed -e '$s/,$/]/'  > outputfile

A: Generally, text files should end with a newline.
One way to edit a file for replace trailing comma with close bracket on last line is:
ed - $file <<'!'
$s/,$/]/
w
q
!

This goes to the last line, replaces the trailing comma with close bracket, and writes and exits.  Alternatively, using sed:
sed '$s/,$/]/' $file > new.$file &&
mv new.$file $file

If you have GNU sed, there is an 'overwrite' option ('-i', IIRC).
If you need to deal with file names rather than file contents, then:
newname=$(echo "$oldname" | sed 's/,$/]/')

And no doubt there are other mechanisms too.  You could also use Perl or Python; they tend towards overkill for the example requested.

A: Sed can easily do a replace on the last line only:

sed '$ s/,/]/g' inputFile

The $ address selector indicates the last line.
If the file ended with a newline, this would not change that, however.  Is that really a desired behavior, or do you just want to replace the last , with ]?

A: perl -i -pe'BEGIN{undef$/}s/,\n?\Z/]/'

A: here's a faster method compared to use sed for big files, assuming last line is not a newline
head -n -1 file > temp;
s=$(tail -1 file)
echo ${s/%,/]} >> temp
echo mv temp file


text:
Q: Error in aspx page when using class inside of span tag Sorry about the ambiguous title but it is the best I could do.
I am getting the following error

Argument type 'object' is not assignable to parameter type 'int'

The line that is referenced is:
<span class = '<%#BindPageNumberClass(DataBinder.Eval(Container, "DataItem")) %>' onclick="dtpaging_Page_Selected('<%# DataBinder.Eval(Container, "DataItem")%>');">

This line produces the red squiggle that is indicative of an error in the first portion
<span class = '<%#BindPageNumberClass(DataBinder.Eval(Container, "DataItem")).....

So naturally I thought I should convert this line to Int32 but sadly enough it did not work and gave me almost the same error.  I searched the internet and tried many failed attempts at fixing this error.
Has anyone else ran into this issue?  What I find perplexing is that only the first part of the line is erroring out when the rest of the line (which appears to be the exact same code) is not erroring out?

A: The return value of DataBinder.Eval is an object. Assuming your BindPageNumberClass takes an int as it's parameter, you'll need to cast the return of the eval call to int using (int)DataBinder.Eval(Container, "DataItem"):
<span class='<%#BindPageNumberClass((int)DataBinder.Eval(Container, "DataItem")) %>'
    onclick="dtpaging_Page_Selected('<%# DataBinder.Eval(Container, "DataItem")%>');">


text:
Q: How to prevent noninsulated wires close together during manual wiring a PCB? Actually I have two problems, but this one is most annoying:
I have like 10 wires I want to solder to the pins of a pin header (2.54 mm distance apart).
Initially I kept like 5 mm of the end of each wire noninsulated, to be able to solder it to the pin. However, I found out it's quite a lot, since two adjecent wires may touch each other eventually.
Now I keep the noninsulated distance just a few mm, but I prefer not to redo the wires I already did (some of them are not on pin wires, but on components directly and it would get messy removing the solder).
How can I 'fix' this. What I could come up with:

*

*Of course making the non insulated ends very small.

*Putting heat shrink tube around the wire before soldering and slide it as much as possible to the end and heat it. Quite some extra work though. Never tried heat shrink tubing, so maybe even the solder might get ruined?

*Sticking tape in between/over it, but the tape might get off later.

I wonder if there are better solutions.
Another problem I have, is that I didn't make the most beautiful soldering joints from some wires to some components (Hi Link AC/DC converters). They have short pins only and I'm a bit weary to remove the solder. However, I had already twice that when I put 220-250V on it, the wire broke lose from the component. Probably a cold solder connection? And what to do (probably redo the soldering?)
(sorry for not having pictures, the 'project' is not next to me now).

A: You really need to practice your soldering technique before you start your next project. Having wires with 220VAC on them flapping around loose is no joke.
But, to save the current one, you can simply use adhesive (hot-melt glue, superglue, whatever) to fix the wires in place so that the exposed conductors don't short to each other.
When a wire breaks loose, there's no option other than resoldering it, and then providing some kind of strain relief so that it doesn't happen again.


text:
Q: Op-amp network topology to amplify positive (or negative) cycles only, keeping the complimentary cycles at unity gain Question
Does there exist an Op-Amp network topology to amplify only the positive, or negative cycles, whilst keeping the corresponding (negative, or positive) cycles at unity gain?
I want to send a small signal into an op-amp, amplify only the positive or negative cycles, then send the output into another op-amp to amplify the 'other cycle'.
Prototype

Avoid
I understating the the super diode/ precision half wave rectifier (Abbreviation: PHRF) allows for splitting of positive or negative cycles, but I am hesitant to split the incoming signal into two parallel routes, use two PHWRs to separate the positive and negative cycles and then use further stages to amplify the two routes, and then sum them with another op-amp for fear of incurring phase issues when recombining the signals.

This plan is to feed a clipping stage for asymmetric clipping. As long as the clipped (guitar) signal does not suffer too much phase difference upon recombination as per 2nd image, the audio signal will be recognisable to the user.
It is important to be able to vary the positive and negative cycle amplification independently as this will give the asymmetric clipping.
Regards
Daniel

A: Since you say you want asymmetric clipping, I'm going to present you with a circuit that does that.
It DOES NOT solve your stated problem of separate gains for the positive and negative halves of the signal - I think that is just your imagined way to get what you wanted.
I'm going to use a symmetric clipper, but make the signal asymmetric.  The result is an asymmetrically clipped signal.

simulate this circuit – Schematic created using CircuitLab
R1 and OA1 are used to add a DC offset to the signal.  Add more than half of V+, and the positive half gets clipped more.  Add less than half of V+ and the negative half of the signal gets clipped more.  Adjust the level of the signal going in to adjust how much clipping is done, adjust R1 for the asymmetry.
Much simpler than trying to split the signal into halves, fiddle with them, then add them back together.

A: And another asymmetrical clipping circuit (but with more precision): -

U2 and U3 perform the clipping/clamping. U2 prevents the output signal rising above V3 (can be set with a pot) and U3 prevents the output signal falling below V4 (can also be set with a pot). You can check what the output looks like courtesy of this website.

A: Your reticence to split the signal, process the two halves independently, and resassemble them pretty much rules out analog techniques.  The alternative is to sample, process using DSP, and then output the new signal with a DAC.
I'd say try it with precision half wave rectifiers.  More than likely, its good enough.  I don't anticipate phase issues at audio frequencies.


text:
Q: Haskell: Recursing in a `do` block I am trying to achieve loop-like functionality in a Haskell program, via recursion with main. The following code should print a * to STDOUT every 2 seconds, indefinitely:
import Control.Concurrent (threadDelay)   --(This function stalls the IO for given number of microseconds
main = do
        threadDelay 2000000
        Prelude.putChar '*'
        main

It compiles fine, but accumulates the output *s and only displays them when the program is aborted, rather than printing another * every 2 seconds (why?). Is this 'loop' like programming with main an accepted programming style, or is there a better way to achieve the desired behaviour?


text:
Q: Images in calculated columns I have a calculated column, formatted as number which is showing and image. Everything works fine on list views and in the web parts.
But when I view a specific item, the calculated column only shows me the HTML code and not the image.
What am I doin wrong?
This is my formula:
=IF(Area="HR";"

";IF(Area="IT";"

";IF(Area="KC";"

";IF(Area="PR";"

";IF(Area="BO";"

")))))

A: Note:
in June 2017, Microsoft disabled the use of JavaScript in a Calculated Column
That means given answers may not apply  for newer SharePoint versions
For long explanation and work arounds see:
June 13th 2017 Microsoft blocked handling HTML markup in SharePoint calculated fields - how to get the same functionality back

**Original answer:**
The Number trick to display HTML only works in Views, it shows the bare HTML on Forms and in Alerts.
#Full explanation and pros & cons at: https://www.365csi.nl/vm365com/#/How
For Forms you have to go for Client-Side-Rendering (CSR)
###BTW
Your Formula:
=IF(Area="HR"
;"

"
;IF(Area="IT"
    ;"

"
    ;IF(Area="KC";"

"
        ;IF(Area="PR"
            ;"

"
            ;IF(Area="BO"
                ;"

"
                )
            )
        )
    )
)

###Can be rewritten to
="

"

###Which can be shortened to:
=""

iCC

A: It is true that I need to go for CSR.

*

*I went into the edit mode on the DispForm view for one of my items.

*Go into the Web Part attributes -> Miscellaneous

*Enter the JSLink to your file (in my case it is ~sitecollection/SiteAssets/logo.js)

Sharepoint is showing my HTML code as a text string and for this I simply exchanged the innerHTML with my innerText.
The only trick is to use the Sharepoint OnLoad function.
_spBodyOnLoadFunctionNames.push("change");

function change() {
    var elem = document.getElementById("SPFieldCalculated")

    //innerText does not exist in FF
    if (typeof elem.textContent !== "undefined") {
        elem.innerHTML = elem.textContent;
    } else {
        elem.innerHTML = elem.innerText;
    }
}

A: Just an idea to accomplish your requirement in a different way is to use CSR.
I think the pro's of CSR are in your case:

*

*Only one column

*You can sort by column and get the real name instead of the html code

*Easy to use in different libraries

If you have questions about the tutorial, don't be afraIT to ask.


text:
Q: Arrange array of Data into Matrix Order in Javascript Am not able find logic, Here I need arrange the below data into multidimensional with matrix format,
var data = [
        {
            "matrixData":[8,0],
            "x":8,
            "y":0,
        },
        {
            "matrixData":[0,4],
            "x":0,
            "y":4,
        },
        {
            "matrixData":[4,0],
            "x":4,
            "y":0,
        },
        {
            "matrixData":[0,0],
            "x":0,
            "y":0,
        },
        {
            "matrixData":[4,4],
            "x":4,
            "y":4
        }
    ]

into following order based on row column wise,
Expected Result
var data = [
        [
            {
                "matrixData":[0,0],
                "x":0,
                "y":0,
            },
            {
                "matrixData":[4,0],
                "x":4,
                "y":0,
            },
            {
                "matrixData":[8,0],
                "x":8,
                "y":0,
            },
        ],
        [
            {
                "matrixData":[0,4],
                "x":0,
                "y":4,
            },
            {
                "matrixData":[4,4],
                "x":4,
                "y":4
            }
        ]
    ]

here x is row and y is column, is there any possible by using sort method or underscore.js

A: You could sort the array in advance and then group the objects.

var data = [{ matrixData: [8, 0], x: 8, y: 0 }, { matrixData: [0, 4], x: 0, y: 4 }, { matrixData: [4, 0], x: 4, y: 0 }, { matrixData: [0, 0], x: 0, y: 0 }, { matrixData: [4, 4], x: 4, y: 4 }],
    groups = data
        .sort(({ matrixData: a }, { matrixData: b }) => a[1] - b[1] || a[0] - b[0])
        .reduce((r, o, i, a) => {
            if (!i || a[i - 1].matrixData[1] !== o.matrixData[1]) {
                r.push([o]);
            } else{
                r[r.length - 1].push(o);
            }
            return r;
        }, [])

console.log(groups);
.as-console-wrapper { max-height: 100% !important; top: 0; }

A: Source javascript | Object grouping

var data = [
  {
    "matrixData":[8,0],
    "x":8,
    "y":0,
  },
  {
    "matrixData":[0,4],
    "x":0,
    "y":4,
  },
  {
    "matrixData":[4,0],
    "x":4,
    "y":0,
  },
  {
    "matrixData":[0,0],
    "x":0,
    "y":0,
  },
  {
    "matrixData":[4,4],
    "x":4,
    "y":4
  }
];
function groupBy(collection, property) {
  var i = 0, val, index,
      values = [], result = [];
  for (; i < collection.length; i++) {
    val = collection[i][property];
    index = values.indexOf(val);
    if (index > -1)
      result[index].push(collection[i]);
    else {
      values.push(val);
      result.push([collection[i]]);
    }
  }
  return result;
}

var obj = groupBy(data, "y");

console.log(obj);


text:
Q: Draw2D.js : How to get JSON from 'HorizontalLayout' with child labels and how to restore 'HorizontalLayout' with label from JSON I am newb to Draw2D.js, I have created 'HorizontalLayout' with three child label. and trying to get JSON for 'HorizontalLayout' with three child label.
My code as following:
HTML:

JS:
var canvas = new draw2d.Canvas("gfx_holder");
var label1 = new draw2d.shape.basic.Label({text: "TEST123"});
var label2 = new draw2d.shape.basic.Label({text: "Label 2"});
var label3 = new draw2d.shape.basic.Label({text: "Label 3"});

var container1 = new draw2d.shape.layout.HorizontalLayout();
container1.add(label1);
container1.add(label2);
container1.add(label3);
container1.setGap(10);
container1.setStroke(2);

canvas.add(container1, 50, 10);

canvas.getCommandStack().addEventListener(function (e) {
    if (e.isPostChangeEvent()) {
        displayJSON(canvas);
    }
});

function displayJSON(canvas) {
       var writer = new draw2d.io.json.Writer();

       writer.marshal(canvas, function (json) {
       $("#json").text(JSON.stringify(json, null, 2));
   });
}

Above code generated following output:

I am getting JSON by calling displayJSON(canvas) method. but I am just getting parent (HorizontalLayout) shape not getting child labels.
I am getting following JSON by calling displayJSON(canvas) method:
[
  {
    "type": "draw2d.shape.layout.HorizontalLayout",
    "id": "9c009d71-a2af-6c86-51c4-e9011c9a446d",
    "x": 198,
    "y": 122,
    "width": 184.390625,
    "height": 28,
    "alpha": 1,
    "angle": 0,
    "userData": {},
    "cssClass": "draw2d_shape_layout_HorizontalLayout",
    "ports": [],
    "bgColor": "none",
    "color": "#1B1B1B",
    "stroke": 2,
    "radius": 0,
    "dasharray": null,
    "gap": 10
  }
]

I want to get whole figure JSON with HorizontalLayout and child labels.
So, How can I get it? And After that How to display Draw2d graph from JSON?


text:
Q: How to mock a method call in Ruby I'm writing a test method for Class A, method called m().
m() calls f() on Class B through an instance of B called 'b', but I mock that method call using-
def test_m
@a = A.new
b_mock = MiniTest::Mock.new
b_mock.expect(:f, 'expected_output')
def b_mock.f()
return 'expected output'
end
@a.b = b_mock
end

Now A has another method m1(), how can a mock a call to it and get a constant output, using the above or a better approach with Minitest?
Error-
NoMethodError: unmocked method :get_group_by_name, expected one of [:]

A: You can use MiniTest Object#stub method, it redefines the method result for the duration of the block.
require 'minitest/mock'

class A
  def m1
    m2
    'the original result'
  end

  def m2
    'm2 result'
  end
end

@a = A.new
@a.stub :m1, "the stubbed result" do

  puts @a.m1  # will print 'the stubbed result'
  puts @a.m2

end

Read more: http://www.rubydoc.info/gems/minitest/4.2.0/Object:stub


text:
Q: Rails 4, Ruby 2.7.1 schema.rb shows "Could not dump table because of following FrozenError" After upgrading to Ruby 2.7.1 my schema.rb is peppered with the following warnings for multiple tables:
# Could not dump table "pages" because of following FrozenError
#   can't modify frozen String: "false"

# Could not dump table "proxies" because of following FrozenError
#   can't modify frozen String: "true"

I've searched high and low for a solution and have checked (as far as I'm able) the migrations, of which there are many.
Downgrading Ruby at this staging isn't an option.
Anyone has a similar situation and managed to resolve it?

A: If someone is still looking for this.
The error is because in the old version of rails the schema dumper used the to_s to convert database default column value to string and then perform operations on that string. But in ruby 2.7 the to_s method for nil, true and false return a frozen string and hence the FrozenError, so if upgrading rails version is not an option you can just put this in an initializer to override the schema dumper method to use the dup instead of actual string.
module ActiveRecord
  module ConnectionAdapters
    module ColumnDumper
      def prepare_column_options(column, types)
        spec = {}
        spec[:name]      = column.name.inspect
        spec[:type]      = column.type.to_s
        spec[:null]      = 'false' unless column.null

        limit = column.limit || types[column.type][:limit]
        spec[:limit]     = limit.inspect if limit
        spec[:precision] = column.precision.inspect if column.precision
        spec[:scale]     = column.scale.inspect if column.scale

        default = schema_default(column).dup if column.has_default?
        spec[:default]   = default unless default.nil?

        spec
      end
    end
  end
end

A: I know you mentioned that downgrading RUby isn't an option for you.
But if you are able to downgrade Ruby here's what worked for me.
This is a Ruby 2.7 issue as noted by rmlockerd.
I ended up downgrading my Ruby version to '2.6.6'.
After downgrading my Ruby, I ran db:schema:load and was able regenerate the schema file without the above errors.


text:
Q: Nested resource missing _url I am trying to write a simple api using ruby and rails and have almost got it working, I am just having one issue. When I try and create a nested resource, I receive an "undefined method" error.
I have two models, one is a user model and one is a record model. They are setup in the routes.rb as such:
resources :users, :except => [:new,:edit] do
  resources :records, :except => [:new,:edit]
end

My records controller contains the following:
def show
  respond_with @user.records.find(params[:id])
end

def create
  respond_with @user.records.create(params[:record])
end

When I call show with a parameter, it works and returns the model. When I post a create I get the following error:
NoMethodError: undefined method `record_url' for #<RecordsController:0x007fea3682a5c8>

I am not sure why this is occuring but if anyone has any ideas I would be grateful. Also, if any more code is required to help, tell me so that I can add it.
Forgot to add my rake routes:
user_records GET    /users/:user_id/records(.:format)     records#index
             POST   /users/:user_id/records(.:format)     records#create
 user_record GET    /users/:user_id/records/:id(.:format) records#show
             PUT    /users/:user_id/records/:id(.:format) records#update
             DELETE /users/:user_id/records/:id(.:format) records#destroy
       users GET    /users(.:format)                      users#index
             POST   /users(.:format)                      users#create
        user GET    /users/:id(.:format)                  users#show
             PUT    /users/:id(.:format)                  users#update
             DELETE /users/:id(.:format)                  users#destroy

A: @record =  @user.records.create(params[:record])
respond_with(@user, @record)


text:
Q: Pandas date conversion assuming wrong date format I am trying to convert a pandas date column to YYYY-MM-DD and then restrict the date based of a parameter min_date.
The problem is when trying to covert dd/mm/yyyy from the df to the required format, pandas assumes the date is us style, i.e. 06/07/2020 is converted to 2020-06-07
I scoured stackoverflow but cannot find someone with a similar issue, the usual answers are just to use strftime, but this does not work for my use case.
Snippet of code:
import pandas as pd
from datetime import datetime

#date restriction
min_date = datetime.strptime(str("2020-06-01"),"%Y-%m-%d").date()

#convert html from website to DF
df = pd.read_html("https://webgate.ec.europa.eu/rasff-window/portal/index.cfm?event=notificationsList")[0]

#only use certain columns
df = df[["Subject","Date of case"]]
df.rename(columns={"Subject": "Description", "Date of case": "Date" }, inplace=True)

#adding another date column to easily compare the old vs new date
df["Date1"] = pd.to_datetime(df["Date"]).dt.strftime('%Y-%m-%d')
df = df[df["Date1"] > min_date.strftime('%Y-%m-%d')]

print(df[["Date","Date1","Description"]])

Thanks in advance for any help.

A: I think you need compare datetimes, not strings repr of datetimes, also is added dayfirst=True parameter in to_datetime and changed format to DD/MM/YYYY in Series.dt.strftime:
#date restriction
min_date = datetime.strptime(str("2020-06-01"),"%Y-%m-%d")

#convert html from website to DF
u = "https://webgate.ec.europa.eu/rasff-window/portal/index.cfm?event=notificationsList"
df = pd.read_html(u)[0]

#only use certain columns
df = df[["Subject","Date of case"]]
df.rename(columns={"Subject": "Description", "Date of case": "Date" }, inplace=True)

#adding another date column to easily compare the old vs new date

#converted to datetimes
df["Date1"] = pd.to_datetime(df["Date"], dayfirst=True)
#compare
df = df[df["Date1"] > min_date].copy()
#or compare by string
#df = df[df["Date1"] > "2020-06-01"].copy()
#change to custom format
df["Date1"] = df["Date1"].dt.strftime('%d/%m/%Y')

print(df[["Date","Date1","Description"]])
          Date       Date1                                        Description
0   06/07/2020  06/07/2020  presence of lactose (>1 250 mg/kg - ppm) in la...
1   06/07/2020  06/07/2020  high content of vitamin B9 - folic acid (1388 ...
2   06/07/2020  06/07/2020  high content of vitamin B9 - folic acid (1189 ...
3   06/07/2020  06/07/2020  aflatoxins (B1 = 25.4 µg/kg - ppb) in groundnu...
4   06/07/2020  06/07/2020  poor temperature control (-10.2 °C) of frozen ...
..         ...         ...                                                ...
95  24/06/2020  24/06/2020  unauthorised genetically modified micro-organi...
96  24/06/2020  24/06/2020  Salmonella (in 2 out of 5 samples /25g) in pro...
97  24/06/2020  24/06/2020  horse which has not undergone sufficient withd...
98  24/06/2020  24/06/2020  unauthorised genetically modified (positive fo...
99  24/06/2020  24/06/2020    2,4-dinitrophenol (DNP) offered online for sale

[100 rows x 3 columns]


text:
Q: Stream stories are restricted for this application I am getting the following error whilst publishing to Facebook via my iPhone application

Stream stories are restricted for this application.

And I am pretty sure i am not posting any thing to user's wall without notifying him first.Can any suggest what might have caused this issue?
Thank you for your support

A: This means that your application has lost its ability to publish to the users by Facebook.  This is usually due to too many people reporting your application as spam or deleting your posts or revoking your application or other spam measures implemented by Facebook.  To appeal to have your app reinstated, contact Facebook.  Another option is to create another application but you may run into the same issue if you dont fix the root cause (people viewing your app as spam).


text:
Q: Regex - match a pattern (from capture) before a capture group I have to match text with this scheme:

*

*capture [\w-/]* which are not ['] (\1)

*capture [']+ which follow (\2)

*and replace \2\1\2 with \1

Example:
my input text is: l''''text'''
the right output is: l'text
I've tried with:
re.sub(r"(\5)(?=((([\w\-\/](?<!'))+)('+)))", r"\2", text)

A: You could match the previously matched quotes after the string:
('+)([\w/-]+)\1

The \1 matches the exact same text group 1 matched.
Online demo at https://regex101.com/r/zQ0hM2/2.
Python session demo:
>>> import re
>>> text = "l''''text'''"
>>> re.sub(r'''('+)([\w/-]+)\1''', r'\2', text)
"l'text"


text:
Q: Converting to UTC is giving NaN error in Javascript I have below code which is giving NaN error when i am trying to convert it into Date.UTC format.
 let sDate = "2019, 10, 19";
 let min = Date.UTC(sDate);

whereas below code is giving me correct result
let min = Date.UTC(2019, 10, 19);

but as per my need, sDate is supposed to be passed as parameter because it may vary. How to correct this?

A: If you refer docs, Date.UTC does not take date string as an argument. It takes individual parts.

Date.UTC(year[, month[, day[, hour[, minute[, second[, millisecond]]]]]])

So when you pass Date.UTC('2019, 10, 19'), you are just passing year's value and not other values. Year's value is also not number. Hence NaN.
If you wish to create UTC date using date string, you will have to split values.

The date arguments are not a string:

let sDate = "2019, 10, 19";
 let min = Date.UTC(...sDate.split(', '));
 console.log(new Date(min));

A: You can use String.split (with destructuring) to convert a known date string format into year, month, day. You have do subtract 1 from the month value when passing to the Date.UTC function since this accepts a month value from 0 to 11 (January to December).
If you want to do more sophisticated Date parsing I strongly recommend you use a library such as Moment.js. This is well tested and has a very flexible API.

const sDate = "2019, 10, 19";
const [year, month, day] = sDate.split(",");
console.log("Date components:", {year, month, day});
// Date constructor takes a month from 0: January to 11: December
const utcDate = Date.UTC(year, month - 1, day);
console.log("Date (ISO):", new Date(utcDate).toISOString());
console.log("Date (toLocaleString):", new Date(utcDate).toLocaleString("en", { timeZone: "UTC"}));

A: The Date.UTC() method accepts parameters similar to the Date constructor but treats them as UTC
Date.UTC(year[, month[, day[, hour[, minute[, second[, millisecond]]]]]])

you can't use string directly

getData=(d)=>{
            return [d.getFullYear(),d.getMonth(),d.getDate(), d.getHours(),d.getMinutes()];
        };

        let splited = getData(new Date('2019, 10, 19'))

        console.log(new Date(Date.UTC(...splited)));


text:
Q: Is my solution of group theory question correct? The following question appeared in my examination.

Let $G$ be the symmetric group $S_5$ of permutations of five symbols. Consider the set $\mathscr{S}$ of subgroups of $G$ that are isomorphic to the non-cyclic group of order $4$. Let us call these two subgroups $H$ and $K$ belonging to $\mathscr{S}$ as equivalent if they are conjugate (that is, there exists $g \in G$ such that $gHg^{-1}=K$). How many equivalence classes are there in $\mathscr{S}$?

I thought for constructing non cyclic subgroup we would need three elements of order $2$ and order two elements in $S_5$ either would be transposition or it would be product of two transpositions. Because two permutations are conjugate iff they have same cycle representations and thus we would get $2$ equivalence classes. Is this correct? What are other ways to solve this question?

A: Your reasoning is not correct/complete, but you're on the right track.
You say an order 2 element in $S_5$ "would be transposition or it would be product of two permutations". Presumably you meant "two transpositions" in the sense that their cycle decomposition would be the product of two transpositions.
In any case, this just says that any subgroup of order 4 must consist of elements from two conjugacy classes (together with the identity). It says nothing about the conjugacy classes of such subgroups themselves. You may as well replace the number 4 with the number 2 up to this point--clearly you're missing something.

Edit: Some more discussion was requested. Let's consider $(12)(34)$. Which copies of the non-cyclic group of order 4 can it participate in, if any? Well, $\{e, (12), (34), (12)(34)\}$ comes to mind immediately. Try playing around and seeing if there are any others (hint: there are). Then consider which of them are conjugate (if any). My suggestion is essentially to classify the subgroups first and then ask about their conjugacy afterwards.


text:
Q: Como obtengo el subtotal a pagar de mis elementos HTML en JavaScript como estan?
estoy tratando de obtener el precio final de ciertos productos seleccionados de mi HTML pero no lo consigo de ninguna forma, estoy probando todos los metodos que me encuentro por internet, les comparto mi una parte de mi codigo HTML y JS

Featured shop

Cajas de madera

Avellana Cajas & Souvenirs

$650

                    Agregar al carrito

Cajas de madera personalizada

Avellana Cajas & Souvenirs

$650

                    Agregar al carrito

Tazas

Avellana Cajas & Souvenirs

$650

                    Agregar al carrito

Listado de productos seleccionados

    Vaciar carrito
    Procesar compra

asd

Aqui les dejo algunas partes del codigo JS, tambien tengo mas eventos que son para vaciar el carrito, eliminar productos
function cargarEventListeners(){
    // Muestra los cursos de localStorage
    document.addEventListener('DOMContentLoaded', () =>{
        articulosCarrito = JSON.parse(localStorage.getItem('carrito')) || [];
        carritoHTML();
    })
}
function leerDatosProducto(producto){
    // Creamos un objeto con los datos del producto
    const infoProducto = {
        imagen: producto.querySelector('img').src,
        titulo: producto.querySelector('h3').textContent,
        precio: producto.querySelector('.card_precio p').textContent,
        id: producto.querySelector('a').getAttribute('data-id'),
        cantidad: 1
    }

// Revisamos si un producto ya existe en nuestro carrito
const existe = articulosCarrito.some( producto => producto.id === infoProducto.id)
if(existe){
    // Actualizamos la cantidad
    const productos = articulosCarrito.map( producto =>{
        if(producto.id === infoProducto.id){
            let precioProducto = Number(infoProducto.precio.slice(1,
            infoProducto.precio.length))

            producto.cantidad++;

            producto.precio = `$${precioProducto * producto.cantidad}`;

            return producto; // retorna el objeto actualizado
            }else{
                return producto;
            }

        })
        articulosCarrito = [...productos]
    }else{
        // Agregamos los elementos al carrito
        articulosCarrito = [...articulosCarrito, infoProducto]
    }
    carritoHTML();
}

function carritoHTML(){
limpiarHTML()

// Recorre el carrito y genera el HTML
articulosCarrito.forEach( (producto) =>{
    const {imagen, titulo, precio, cantidad, id} = producto
    /* const row = document.createElement('span'); */
    compra.innerHTML += `

Nombre producto: ${titulo}

Precio: ${precio}

Cantidad: ${cantidad}

                 Eliminar producto

    `;
})
    // Agregar el carrito al LocalStorage
    sincronizarStorage()
    totalPrecio()

}

La funcion de aqui probe llamandola en diferentes partes de mi codigo y siempre obtuve el mismo resultado en el html cuando selecciono los productos y los agrego correctamente al carrito, el parrafo de subtotal me muestra los precios de cada producto por seperado pero no hace la suma total, lo que si me funciona es cuando agrego X cantidad de un producto se me actuliza el precio bien, pero el subtotal no logro conseguirlo.
function totalPrecio(){
    const precioTotal = articulosCarrito.reduce( (total, producto) => total +
    producto.precio,0);
    const precioTexto = `$${precioTotal}`

    precio.innerHTML = `Total a pagar: ${precioTexto}`
}

function sincronizarStorage(){
    localStorage.setItem('carrito', JSON.stringify(articulosCarrito))
}


text:
Q: Google Apps Script fails to copy bullets from one document to other document Following this code, I am using Google Apps Script to append a document template to another document. The template has bullets lists, however these will be lost upon copy, while indentation will be retained correctly.
Link to the template
Code:
     var newDoc = DocumentApp.openById('anotherGoogleID');
      var newDocBody = newDoc.getBody();
      var templateBody = DocumentApp.openById('aGoogleID').getActiveSection();
 // has bullets
          var totalElements = templateBody.getNumChildren();
          newDocBody.appendPageBreak();
          for( var j = 0; j < totalElements; ++j ) {
            var element = otherBody.getChild(j).copy();
            var type = element.getType();
            if( type == DocumentApp.ElementType.PARAGRAPH )
              newDocBody.appendParagraph(element);
            else if( type == DocumentApp.ElementType.TABLE )
              newDocBody.appendTable(element);
            else if( type == DocumentApp.ElementType.LIST_ITEM )
              newDocBody.appendListItem(element);
            else
              throw new Error("Unknown element type: "+type);
          }
    newDocBody.saveAndClose()

A: I found I could get it to work with
newDocBody.appendListItem(listItem.getText()).setAttributes(element.getAttributes());

To put it in context: (based of https://www.labnol.org/code/19892-merge-multiple-google-documents)
for( var j = 0; j < totalElements; ++j ) {
    var element = otherBody.getChild(j).copy();
    var type = element.getType();
    if( type == DocumentApp.ElementType.PARAGRAPH )
      body.appendParagraph(element).setAttributes(element.getAttributes());
    else if( type == DocumentApp.ElementType.TABLE )
      body.appendTable(element).setAttributes(element.getAttributes());
    else if( type == DocumentApp.ElementType.LIST_ITEM ){
      var listItem = element.asListItem();
    body.appendListItem(listItem.getText()).setAttributes(element.getAttributes());
}

A: Following this sample, I have modified the code this way:
var newDoc = DocumentApp.openById('anotherGoogleID');
      var newDocBody = newDoc.getBody();
      var templateBody = DocumentApp.openById('aGoogleID').getActiveSection();
 // has bullets
          var totalElements = templateBody.getNumChildren();
          newDocBody.appendPageBreak();
          for( var j = 0; j < totalElements; ++j ) {
            var element = otherBody.getChild(j).copy();
            var type = element.getType();
            if( type == DocumentApp.ElementType.PARAGRAPH )
              newDocBody.appendParagraph(element);
            else if( type == DocumentApp.ElementType.TABLE )
              newDocBody.appendTable(element);
            else if( type == DocumentApp.ElementType.LIST_ITEM )
               { newDocBody.appendListItem(element);
                 var glyphType = element.getGlyphType();
                 element.setGlyphType(glyphType);
                 }
            else
              throw new Error("Unknown element type: "+type);
          }
    newDocBody.saveAndClose()

Now some bullets are being created, but circles bullets instead of letters....


text:
Q: Error when trying to create and mount a new HFS volume (in order to test filter scheme driver) I am trying to test a IO kit sample app that implements a filter scheme. See section 10.7.10 here for context. As the source there is hard to cut and paste (and when I tried I got errors), I am using the source from here which builds.
In the last figure on that page (1038) it has a series of steps for creating and mounting a new HFS volume. The idea is to see that the KEXT is working and doing encryption. I have built the sample KEXT and tested with it, but I always get "No mountable file systems" error when I make the "open" call. I have verified the KEXT is properly loaded.
If I remove the "-partitionType" I am able to manipulate the volume normally (though this doesn't involve the KEXT).
Can someone please suggest what might be going wrong here?
Part of my confusion in figure 1038's script is the "detach" command that is run before the open. It fails for me, but I am not sure if that is what is causing the "open" after it to fail, or is unrelated.
$ sudo kextload /System/Library/Extensions/IOKitDriverTestApp.kext/
$ hdiutil create -size 32m -partitionType osxbook_HFS /tmp/crypto.dmg
created: /tmp/crypto.dmg
$ hdiutil attach -nomount /tmp/crypto.dmg
/dev/disk2              Apple_partition_scheme
/dev/disk2s1            Apple_partition_map
/dev/disk2s2            osxbook_HFS
$ diskutil list
/dev/disk0 (internal, physical):
[cut]
/dev/disk1 (synthesized):
[cut]
/dev/disk2 (disk image):
   #:                       TYPE NAME                    SIZE       IDENTIFIER
   0:     Apple_partition_scheme                        +33.6 MB    disk2
   1:        Apple_partition_map                         32.3 KB    disk2s1
   2:                osxbook_HFS                         33.5 MB    disk2s2
$ newfs_hfs -v Crypto /dev/rdisk2s2
Initialized /dev/rdisk2s2 as a 32 MB case-insensitive HFS Plus volume
$ hdiutil detach /dev/disk2
hdiutil: detach failed - No such file or directory
$ open /tmp/crypto.dmg
==> Get popup window with error "crypto.dmg" "No mountable file systems"

UPDATE: the question originally targeted the case when the KEXT was not loaded. Since I got that to work I changed it to reflect the case with the KEXT, which is more important anyway.
UPDATE2: It seems that eventually the kext is getting unloaded (possibly crashing). Sometimes it seems around the time of the "open", sometimes after. I tried adding statements like IOLog("CSD: init"), but none of them show up in the system log or console log. Looking for how else I can triage this (without needing a separate machine).
UPDATE3: Below is the output of when I try to start the KEXT. There are a bunch of warnings but since I have the signing check disabled I think it is still loading. Also I see it loaded via kextstat.
The other strange thing is I don't see any signs of this KEXT in the output of "ioreg", nor do I see any of the print statements from IOLog().
My-MacBook-Pro:Extensions myuser$ sudo kextutil -v /System/Library/Extensions/IOKitDriverTestApp.kext/
Defaulting to kernel file '/System/Library/Kernels/kernel'
Kext with invalid signatured (-67050) allowed: <OSKext 0x7fa53703ec70 [0x7fff8fe6faf0]> { URL = "file:///System/Library/Extensions/IOKitDriverTestApp.kext/", ID = "com.osxbook.driver.IOKitDriverTestApp" }
Code Signing Failure: code signature is invalid
Warnings:
    Personality CFBundleIdentifier differs from containing kext's (not necessarily a mistake, but rarely done):
        SimpleCryptoDisk
    Personality CFBundleIdentifier names a kext that can't be found:
        'SimpleCryptoDisk' -> 'com.osxbook.driver.SimpleCryptoDisk'

Warnings:
    Personality CFBundleIdentifier differs from containing kext's (not necessarily a mistake, but rarely done):
        SimpleCryptoDisk
    Personality CFBundleIdentifier names a kext that can't be found:
        'SimpleCryptoDisk' -> 'com.osxbook.driver.SimpleCryptoDisk'

/System/Library/Extensions/IOKitDriverTestApp.kext appears to be loadable (not including linkage for on-disk libraries).
Loading /System/Library/Extensions/IOKitDriverTestApp.kext.
/System/Library/Extensions/IOKitDriverTestApp.kext successfully loaded (or already loaded).
Invalid signature -67050 for kext <OSKext 0x7fa53703ec70 [0x7fff8fe6faf0]> { URL = "file:///System/Library/Extensions/IOKitDriverTestApp.kext/", ID = "com.osxbook.driver.IOKitDriverTestApp" }

UPDATE4: I adjusted the bundle ID in the plist so it matches, and now it is not giving the "names a kext that can't be found" error:
My-MacBook-Pro:Debug myuser$ sudo kextutil -v /System/Library/Extensions/IOKitDriverTestApp.kext/
Password:
Defaulting to kernel file '/System/Library/Kernels/kernel'
Kext with invalid signatured (-67050) allowed: <OSKext 0x7f8be663ecf0 [0x7fff866bcaf0]> { URL = "file:///System/Library/Extensions/IOKitDriverTestApp.kext/", ID = "com.osxbook.driver.IOKitDriverTestApp" }
Code Signing Failure: code signature is invalid
/System/Library/Extensions/IOKitDriverTestApp.kext appears to be loadable (not including linkage for on-disk libraries).
Loading /System/Library/Extensions/IOKitDriverTestApp.kext.
/System/Library/Extensions/IOKitDriverTestApp.kext successfully loaded (or already loaded).
Invalid signature -67050 for kext <OSKext 0x7f8be663ecf0 [0x7fff866bcaf0]> { URL = "file:///System/Library/Extensions/IOKitDriverTestApp.kext/", ID = "com.osxbook.driver.IOKitDriverTestApp" }

UPDATE5:
Now my OS consistently crashes every time I load the KEXT and then execute "hdiutil attach -nomount /tmp/crypto.dmg" (after creating /tmp/crypto.dmg).
It seems clear my KEXT is running now, but for some reason I still don't see the IOLog() statements anywhere. Will have to look through the system logs and see if there is any indication why it is crashing.
UPDATE6: I have been able to get a symbolicated kernel panic, but it is pointing to a different KEXT (which I don't think I have the source too). Below is the relevant part of it.
I tried using another version of the same test KEXT (here) without any changes (I have removed the IOLog() statements for now since they weren't showing up).
I see a note this was tested on Mac OS 10.6, but has anyone gotten this sample to work on 10.13.16 (High Sierra)?
...
0xffffff800c94f540 : 0xffffff800cb8776f mach_kernel : _kernel_trap + 0x70f
0xffffff800c94f6b0 : 0xffffff800ca1e1e0 mach_kernel : _return_from_trap + 0xe0
0xffffff800c94f6d0 : 0xffffff7f8d527251 com.apple.iokit.IOStorageFamily : __ZN9IOStorage8completeEP19IOStorageCompletioniy + 0x27
0xffffff81f7a4b980 : 0xffffff7f8d51a0c4 com.apple.iokit.IOStorageFamily : __ZN20IOBlockStorageDriver24prepareRequestCompletionEPvS0_iy + 0xc2
0xffffff81f7a4b9e0 : 0xffffff7f903afa7a com.apple.driver.DiskImages : __ZN13IOHDIXCommand8completeEiy + 0x26
0xffffff81f7a4ba00 : 0xffffff7f903adbfe com.apple.driver.DiskImages : __ZN22IOHDIXHDDriveOutKernel12processReplyEPK13HDIReplyOOL64P18IOMemoryDescriptor + 0x2be
0xffffff81f7a4ba60 : 0xffffff7f903aee9b com.apple.driver.DiskImages : __ZN32IOHDIXHDDriveOutKernelUserClient14processReply64EPK13HDIReplyOOL64 + 0xd3
0xffffff81f7a4bac0 : 0xffffff800d0c3959 mach_kernel : _shim_io_connect_method_structureI_structureO + 0x1c9
0xffffff81f7a4bb20 : 0xffffff800d0c1ae0 mach_kernel : __ZN12IOUserClient14externalMethodEjP25IOExternalMethodArgumentsP24IOExternalMethodDispatchP8OSObjectPv + 0x340
0xffffff81f7a4bb70 : 0xffffff800d0ca567 mach_kernel : _is_io_connect_method + 0x217
...

UPDATE7: I gave up on trying to use the SimpleCryptoDisk.cpp test app and started from scratch, adding a little bit of code at a time. I've had some success (the driver starts and I can see logging), though I don't really have anything working yet.
If I get stuck on this I may post another question, but I'll go ahead and mark pmdj's answer as correct since he answered my original question.
If anyone knows of a modified version of SimpleCryptoDisk that works on High Sierra I'd still like to know, however.

A: To answer your original questions:

[Why "No mountable file systems" when not loading the kext and using partition type "osxbook_HFS"]

As you can see, the Apple Partition Scheme uses arbitrary text strings for identifying partition type. macOS uses this string verbatim as the "content hint" which selects which file system type to attempt to automount on that volume. The HFS+ file system is only looking for Apple_HFS (and Apple_HFSX for case-sensitive)
The idea behind the kext is that it itself matches the newly defined content hint and publishes a new storage nub object which in turn has the HFS+ content hint for the filesystem to pick up.
Why hdiutil detach was failing

$ hdiutil detach /dev/disk2
hdiutil: detach failed - No such file or directory

On current versions of macOS, you need to rewrite the command as either:
$ hdiutil detach disk2

or

$ hdiutil detach /Volumes/VOLUMENAME

I can't immediately answer your current question of why it's not working with the kext, but I can suggest you look at whether your kext is behaving as expected with regard to the IO Registry. Check with IORegistryExplorer or ioreg whether it's matching the volume with the special partition type, and whether it's creating and registering the virtual (decrypted) volume with the Apple_HFS content hint. Add the ioreg output (ioreg -w 0 -lirc YOUR_DRIVERS_CLASSNAME) to your question if unsure.


text:
Q: No thumbnail shows on facebook, when I post a link to my site I just published a new website. When someone tries to publish the link on Facebook, no thumbnail-options shows up, even though there are plenty of image-files to choose from.
When I post the link to the "gallery" section though, I get the option to choose a thumbnail from the images in the gallery only.
The url to the website: http://www.ridderhest.no

A: According to the debug tool: https://developers.facebook.com/tools/debug/og/object?q=http%3A%2F%2Fwww.ridderhest.no the image is being detected correctly from your tags and it appears to meet the size requirements, does it work it you change the image to be slightly larger? the minimum supported size is 50x50 and that's exactly the size of the image, maybe a 51x51 image works?


text:
Q: systemd Exec format error I have a java file which I'm trying to install as a service. But I'm getting errors. Below is the contents of my file and errors. I'm running Debian 8.
[Unit]
Description=App1Manager
After=syslog.target

[Service]
ExecStart=/usr/bin/jsvc -user root -cp /usr/share/java/commons-daemon.jar:/usr/local/myapp/bin/Manager.jar -pidfile /var/run/app1manager.pid

Type=forking

[Install]
WantedBy=multi-user.target

With either the below I get the following error:
SYSTEMD_LOG_LEVEL=debug /lib/systemd/system/myapp1
SYSTEMD_LOG_LEVEL=debug /etc/init.d/myapp1

/etc/init.d/myapp1: line 1: [Unit]: command not found
/etc/init.d/myapp1: line 6: [Service]: command not found
/etc/init.d/myapp1: line 7: -user: command not found
/etc/init.d/myapp1: line 10: [Install]: command not found

Aug 12 12:04:39 debian systemd[3903]: Failed at step EXEC spawning /etc/init.d/myapp1: Exec format error
-- Subject: Process /etc/init.d/myapp1 could not be executed
-- Defined-By: systemd
-- Support: http://lists.freedesktop.org/mailman/listinfo/systemd-devel
--
-- The process /etc/init.d/myapp1 could not be executed and failed.
--
-- The error number returned while executing this process is 8.
Aug 12 12:04:39 debian systemd[1]: myapp1.service: control process exited, code=exited status=203
Aug 12 12:04:39 debian systemd[1]: Failed to start (null).
-- Subject: Unit myapp1.service has failed
-- Defined-By: systemd
-- Support: http://lists.freedesktop.org/mailman/listinfo/systemd-devel
--
-- Unit myapp1.service has failed.
--
-- The result is failed.
Aug 12 12:04:39 debian systemd[1]: Unit myapp1.service entered failed state.

A: Install to systemd/system with a .service file extension; the executable bit does not need to be set.  Do not install systemd-format service files to /etc/init.d/; this is for legacy SysVinit style service scripts.
To start services, use systemctl start myapp1.  When you're not sure whether the service is implemented as systemd or SysV, use service myapp1 start.
To enable on boot [given an appropriate Install section] use systemctl enable myapp1.


text:
Q: Laravel 5.2 - Updating multiple rows with one query So I do a lot of calculations and at the end I have rates that need to be saved to existing rows in a table.
The array I have will be similar to the following:
[
    <model_id> => [
        'rate' => <some rate>
    ]
    <model_id_2> => [
        'rate' => <some other rate>
    ]
    .....
]

Now obviously I could foreach through this array and do an update for each and every item in the array but I could end up with 100 update calls. Is there a way (through laravel's eloquent OR even a raw sql query) to do all these updates through one call?

A: You may try with Eloquent update() for multiple records update. Here is some code which I am using for update multiple records into the my table.
\App\Notification::where('to_id', '=', 0)
                ->update(['is_read' => 1]);

A: If you are worried about the request spent time you can handle this by firing an event and then queueing your listener/job, who will save your model, so it can be processed asynchronously. For examples, go to Laravel Docs for Queues
As long as I know you cannot update multiple rows on Laravel.


text:
Q: Principal ideal of an integrally closed domain
Let $R$ be an integrally closed domain and $S$ be an integral domain that contains $R$. Assume that $a\in S$ is integral over $R$. Prove that $I=\left\{ f\left(x\right)\in R\left[x\right]\mid f\left(a\right)=0\right\} $ is a principal ideal of $R[x].$

I only know that $R[x]$ is also an integrally closed integral domain and $a$ is a root of a monic polynomial of $R[x]$. So if $g(x)$ is a monic polynomial of $R[x]$ then $g(a)=0$.
Help me a hint.
Thank for any insight.

A: Let $p$ be the minimal polynomial of $a$ over $K$, the field of fractions of $R$, and $f\in I$ monic. We should have $p\mid f$ in $K[x]$, and by Gauss' lemma $p\mid f$ in $R[x]$. Now it's easy to show that $I=(p)$.


text:
Q: Angular2 - interpolated object is 'undefined' but console.log() works I'm working on a very simple Angular2 app, but I'm running into an issue where an interpolated component object is evaluated by the browser as undefined, though I am able to console.log(this) in the component and see the values, albeit with the 'Value below was evaluated just now' note.
For context, I've initiated my app with the Angular2 command line tool, but I am loosely following the Angular2 'Tour of Heroes' tutorial (which uses a zipped quickstart package to assemble the basic files)...
The template that is causing the issue is person-detail.component.html, where I very simply have:

Welcome, {{ person.name }}

Here is the associated person-detail.component.ts
import { Component, Input, OnInit } from '@angular/core';
import { ActivatedRoute, Params }   from '@angular/router';
import { Location }                 from '@angular/common';
import 'rxjs/add/operator/switchMap';
import { PersonService } from './person.service';
import { Person } from './person';

@Component({
  selector: 'person-details',
  templateUrl: './person-details.component.html'
})

export class PersonDetailsComponent implements OnInit {

  @Input() person: Person;
   constructor(
    private personService: PersonService,
    private route: ActivatedRoute,
    private location: Location
  ) {};

  ngOnInit(): void {
    this.route.params
      .switchMap((params: Params) => this.personService.getPerson(+params['id']))
      .subscribe(person => this.person = person);

      console.log(this) //THIS LOGS THE COMPLETE OBJECT AS I WANT IT, BUT WITH THE 'Value below...' NOTE
  };
}

and person.service.ts
import { Injectable } from '@angular/core';
import { Http, Headers, RequestOptions, Response } from '@angular/http';
import 'rxjs/add/operator/map';
import { Observable } from "rxjs/Observable";
import { Person } from './person';
import 'rxjs/add/operator/toPromise';

@Injectable()
export class PersonService {
    private apiUrl = 'http://localhost:4000/api/';

    constructor(private http: Http) {
        console.log('Service ready...');
    }

  getPeople(): Promise<Person[]> {
    let headers = new Headers({ 'Content-Type': 'application/json' });
    let options = new RequestOptions({ headers: headers });
    return this.http
      .get(this.apiUrl + 'people', options)
      .toPromise()
      .then(response => response.json().data as Person[])
  }

  getPerson(id: number): Promise<Person> {
    return this.getPeople()
      .then(people => people.find(person => person.id === id));
  }
}

But when I navigate to the page, I get the error inline template:0:5 caused by: Cannot read property 'name' of undefined, though the data returned by console.log() looks good.
Conceptually, I understand what's happening... the section of the page is rendering before the  object is fully-formed. But I'm confused, because as far as I can tell, I put things together in exactly the same way as the 'Tour of Heroes' tutorial, which worked just fine - except for the fact that I initiated my project with the command line tools (which builds the project slightly differently) and I'm connecting to my own API with some header options, etc...
How can I set it so that the section of the page will wait until the object is fully-formed before trying to render it?
Note - if I try to interpolate {{ person }}, the browser displays  [object Object]

A: The console.log is giving you the wrong impression because person is still undefined by the time you try to access it in the template, although you don't have time to appreciate the change in the console if the response from the server is fast enough. So you need to use the safe navigation operator.

Welcome, {{ person?.name }}

A: In some cases you might want to consider using typescript getters. They will allow you to have a default value for your property.
export class PersonDetailsComponent implements OnInit {
  @Input() personInput: Person;
  get person(){
    return personInput || {};
  }

Call it like:
<person-details [personInput]="details"></person-details>

And then in your PersonDetailsComponent, you can use it without any change:

Welcome, {{ person.name }}


text:
Q: adjust webpage to facebook tab with jQuery I am trying to adjust webpage to facebook tab, I created new page for the tab and load the content from the targeted webpage, all go well the issue is that I can't re-size this content to fit 810px.
HTML:
<html>
    <head>
        <meta charset='utf-8'>
        <link rel="stylesheet" type="text/css" href="css/style.css">
        <script type="text/javascript" src="js/jquery.js"></script>
        <script type="text/javascript" src="js/facebook-tab.js"></script>
    </head>

    <body>
        <div id="facebook-contant">
        </div>

    </body>
</html>

jQuery:
$(document).ready(function(){
    $( "#facebook-contant" ).load('recommendations.html #rec-board-holder');
});

any advice how to change the load content size?

A: You can try canvas setSize method to adjust tab page height and width, reference:
https://developers.facebook.com/docs/reference/javascript/
Method called
FB.Canvas.setSize

It takes arguments in json object like
FB.Canvas.setSize({ width: 640, height: 480 });

You can specify width and height here. You need to call javascript sdk of facebook to call this method.

A: You should use heigh / width in percentage(%) rather px / em. change the css file.

A: I'm not sure I understand the question, but here's my thoughts anyway. If you're trying to change elements in the loaded content, you could just add a function that fires after the content is loaded and make the adjustments.
$(document).ready(function(){
    $( "#facebook-contant" ).load('recommendations.html #rec-board-holder',function(){
        //access and make adjustments here
    });
});


text:
Q: could not find schema information for the element 'specflow' Visual Studio Professional 2013 I am compiling my webdriver C# code in Visual Studio professional 2013
I have installed Specflow
I get the following error
could not find schema information for the element 'specflow'
My AppConfig file has the following settings:
<?xml version="1.0" encoding="utf-8"?>
<configuration>
  <configSections>
    <section name="specFlow" type="TechTalk.SpecFlow.Configuration.ConfigurationSectionHandler, TechTalk.SpecFlow" />
  </configSections>
  <specFlow>
    <!-- For additional details on SpecFlow configuration options see http://go.specflow.org/doc- config -->
  </specFlow>
  <appSettings>
    ...
  </appSettings>
</configuration>

Why is it complaining about could not find schema info for specflow?
In my step definition file i have included at the top of the class
using NUnit.Framework;
using OpenQA.Selenium;
using System;
using System.Collections.Generic;
using System.Linq;
using System.Text;
using TechTalk.SpecFlow;
using G.Selenium;

namespace WebdriverBdd
{
    [Binding]
    public class SearchSteps : SeleniumWebDriver
    {
        [Given(@"user is on g search page")]
        public void UserIsOnGSearchPage()
        {
            SeleniumWebDriver selenium_driver = new SeleniumWebDriver();
        }
    }

A: Note: Since your specFlow config section is empty, you can just delete it. SpecFlow will use defaults for everything in either case.

Could not find schema information for the element 'specFlow'.

The message(s) are informational only. Many configSections don't have schemas because they are very simple, very complex or have plugin options that aren't kept up with.
You can always create an XML schema from documentation or using an XML file as an example. To create one from an example (which of course, might be overfit to the example), open the XML file (app.config) and select the menu command XML » Create Schema.
In the case of an App.config, the schema will be for the whole configuration. Simply pare it down to the specflow config section. I did this with mine, which directs code generation for MS Test instead of NUnit. I then jazzed it up a bit by creating an enumeration for the name of the unitTestProvider.
<?xml version="1.0" encoding="utf-8"?>
<xs:schema attributeFormDefault="unqualified" elementFormDefault="qualified" xmlns:xs="http://www.w3.org/2001/XMLSchema">
  <xs:element name="specFlow">
    <xs:annotation>
      <xs:documentation>
        Customizes SpecFlow code generation. This unofficial schema is hand-crafted based on actual use.
        For additional details on SpecFlow configuration options see http://go.specflow.org/doc-config.

        Should occur zero or one times in an app.config.
      </xs:documentation>
    </xs:annotation>
    <xs:complexType>
      <xs:sequence>
        <xs:choice minOccurs="0" maxOccurs="1">
          <xs:element name="unitTestProvider">
            <xs:complexType>
              <xs:attribute name="name" type="SpecFlowUnitTestProvider" use="required" />
            </xs:complexType>
          </xs:element>
        </xs:choice>
      </xs:sequence>
    </xs:complexType>
  </xs:element>
  <xs:simpleType name="SpecFlowUnitTestProvider">
    <xs:restriction base="xs:string">
      <xs:enumeration value="MsTest" />
      <xs:enumeration value="NUnit" />
    </xs:restriction>
  </xs:simpleType>
</xs:schema>


text:
Q: Iterating sublists without using the list length I have a list of things, and I need to apply some processing on successive (and overlapping) groups of 3 elements:
I can do it with:
for i in range(len(things)-2):
    process(things[i:i+3])

So for instance:
things=[0, 1, 2, 3, 4, 5, 6, 7]

And I want to process:
[0, 1, 2], [1, 2, 3], [2, 3, 4], [3, 4, 5], [4, 5, 6], [5, 6, 7]

But is there a clever (but readable) way to do it without explicitly using len(things)?

A: Yes, what you're looking for is called a sliding/moving window. There are different ways to achieve this but the easiest is to use tee() and islice() functions from itertools. Using this you can define a window() function like below with default window size of 2.
import itertools

def window(iterable, n=2):
    iters = itertools.tee(iterable, n)
    for i, it in enumerate(iters):
        next(itertools.islice(it, i, i), None)
    return zip(*iters)

Then you can use it as
>>> things=[0, 1, 2, 3, 4, 5, 6, 7]
>>> list(window(things, n = 3))
[(0, 1, 2), (1, 2, 3), (2, 3, 4), (3, 4, 5), (4, 5, 6), (5, 6, 7)]
>>> for elem in window(things, n = 3):
...     print(elem)
...
(0, 1, 2)
(1, 2, 3)
(2, 3, 4)
(3, 4, 5)
(4, 5, 6)
(5, 6, 7)

Edit: For one time use a more simpler option may be
>>> list(zip(things, things[1:], things[2:]))
[(0, 1, 2), (1, 2, 3), (2, 3, 4), (3, 4, 5), (4, 5, 6), (5, 6, 7)]

A: Another way of doing it could be:
for i in things[0:-2]:
    a=things.index(i)
    process(things[a:a+3])

A: Let's try using enumerate, Here len(things[i : i+len_]) == len_ is to drop uneven sized list that get's accumulated at the end iterations.
len_ = 3

[things[i : i+len_] for i, j in enumerate(things) if len(things[i : i+len_]) == len_]

[[0, 1, 2], [1, 2, 3], [2, 3, 4], [3, 4, 5], [4, 5, 6], [5, 6, 7]]

len_ = 4

[things[i : i+len_] for i, j in enumerate(things) if len(things[i : i+len_]) == len_]

[[0, 1, 2, 3], [1, 2, 3, 4], [2, 3, 4, 5], [3, 4, 5, 6], [4, 5, 6, 7]]


text:
Q: Git fetch: How to keep on my local branch? I was reading this post: What is the difference between 'git pull' and 'git fetch'?
and it said that once you do a "git fetch", you actually update your "remote-tracking branches under refs/remotes//".
If so, let's say that I have a branch named 'dev_branch' and it exists both on my local machine and on the remote server. If I do "git fetch", can I say that:

*

*No change will be made to local branch 'dev_branch' ?

*The branch 'origin/dev_branch' will be updated as the branch in remote server?

*If I do "git pull", I understand that it merges my local branch with the remote one. If I just opened a local branch that doesn't have a correspondent branch in remote server (let's call it my_branch), how will "git pull" affect it? Is it correct to say that it will not cause any change?

A: For question 1 and 2. Yes, you are right. In case of

git fetch

There will be no change in your local dev_branch, git will only synchronize origin/dev_branch in your local computer with its counterpart in remote repository. This behaviour of git fetch is described clearly here. One way to verify this behaviour is by comparing:

git diff origin/dev_branch dev_branch

For question 3, if there is no origin/my_branch in remote repository and you invoke

git pull

Git will prompt error:

fatal: No remote repository specified.  Please, specify either a URL or a
  remote name from which new revisions should be fetched.

You can specify the remote branch, you'd like to merge change with you local my_branch by:

git pull remote_repository remote_branch_name

And run git log to see the effect:

Merge branch 'remote_branch_name' of git_on_the_cloud_service/remote_repository


text:
Q: writing arrays and strings to file using '%' operator I'm trying to export data in a certain format (.cube file); the file type isn't the main issue.
Now I have to print different line formats based on their line number. So far so good, I'm able to do it using the following:
 if line_num == 0 or line_num == 1:
     # comment line
     output_file.write("%s\n" % (self.comments[line_num]))
     continue
 if line_num == 2:
     # number of total atoms, and the origin coordinates
     output_file.write("%4d %.6f %.6f %.6f\n" % (self.num_atoms, self.origin[0], self.origin[1], self.origin[2]))
     continue

The above work, but I've wanted to use the '%' operator in the following manner:
if line_num == 2:
     # number of total atoms, and the origin coordinates
     output_file.write("%4d %.6f %.6f %.6f\n" % (self.num_atoms, self.origin)

because self.origin is a Numpy Array size 1X3.
When doing so, I get the following error:
Traceback (most recent call last):
File "<stdin>", line 1, in <module>
TypeError: only size-1 arrays can be converted to Python scalars

is there a way to do what I wanted instead of give every element in the array.
Thanks.

A: Use *self.origin to unroll the array.
>>> "%4d %.6f %.6f %.6f\n" % (num_atoms, *origin)
' 199 1.000000 2.000000 3.000000\n'
>>>

A: The issue is that self.origin is a list, and you are trying to print a list using float formatting, you can unpack the list using *self.origin and then it should work, see a simple example below.
You can use string.format which works for for both python2 and python3
origin = [1,2,3]
print("{:4d} {:6f} {:6f} {:6f}".format(1, *origin))
#   1 1.000000 2.000000 3.000000

Python 2.7.10 (default, Feb 22 2019, 21:17:52)
[GCC 4.2.1 Compatible Apple LLVM 10.0.1 (clang-1001.0.37.14)] on darwin
Type "help", "copyright", "credits" or "license" for more information.
>>> origin = [1,2,3]
>>> print("{:4d} {:6f} {:6f} {:6f}".format(1, *origin))
   1 1.000000 2.000000 3.000000

Python 3.7.3 (v3.7.3:ef4ec6ed12, Mar 25 2019, 16:39:00)
[GCC 4.2.1 (Apple Inc. build 5666) (dot 3)] on darwin
Type "help", "copyright", "credits" or "license" for more information.
>>> origin = [1,2,3]
>>> print("{:4d} {:6f} {:6f} {:6f}".format(1, *origin))
   1 1.000000 2.000000 3.000000

A: In case, if someone is looking for an f string equivalent, use the following:
In [69]: arr = np.array([1.4556, 2.4, 3.3245])

# printing only 3 digits after the decimal point
In [70]: f'{" ".join(format(c, ".3f") for c in arr)}'
Out[70]: '1.456 2.400 3.325'

A diluted version of this code would be, thanks to the suggestion by NaN:
In [95]: print(("{: .3f}"*len(arr)).format(*arr))
 1.456 2.400 3.325


text:
Q: How to Fix Index Error in Differential Equation? I am trying to create a program that solves the mass-spring-damper system using backward differentiating, the only problem is that I am running into an index error that I am not sure how to solve:
import numpy as np
import matplotlib.pyplot as plt

def MSD_Solver(m,b,K):
    #input: m = mass, b = damping ratio, K = spring constant
    #output: (t,x) time vs position

    tinitial = 0
    tfinal = 15
    step = .005

    t = np.linspace(tinitial,tfinal,step)

    x = np.zeros_like(t)

    x[0]=0
    x[1]=0
    for k in range (len(t)-1):            # extra element so subtract by 1
        x[k] = (t**2)/((m+b)*t+(t**2)*k) + (x[k-2](-m))/((m+b)*t+(t**2)*k) + (x[k-1]((2*m)+(b*t)))/((m+b)*t+(t**2)*k)
    return plt.plot(t,x)

print(MSD_Solver(1,.5,5)),MSD_Solver(1,1,5),MSD_Solver(1,2,5)
plt.show()

A: The linspace doc shows that the third argument is the number of items, not the step.  Your step value got truncated to 0, so the returned array for t was empty.  As a result, x has no elements, and x[0] is out of range.
Try this:
tinitial = 0
tfinal = 15
step = .005
num = (tfinal - tinitial) / step + 1

t = np.linspace(tinitial,tfinal,num)

This will get you to the semantic errors in your complex computation.

A: You want, probably(?), use first and second order difference quotients to discretize
m*x''(t) + b*x'(t) + K*x(t) = 1

to
m*(x[j+1]-2*x[j]+x[j-1]) + 0.5*dt*b*(x[j+1]-x[j-1]) + dt^2*K*x[j] = dt**2

so that
x[j+1] = ( dt**2 + (2*m-K*dt**2)*x[j] - (m-0.5*dt*b)*x[j-1] ) / (m+0.5*dt*b)

In code
def MSD_Solver(m,b,K):
    #input: m = mass, b = damping ratio, K = spring constant
    #output: (t,x) time vs position

    tinitial = 0
    tfinal = 15
    step = .005

    t = np.arange(tinitial,tfinal,step)
    x = np.zeros_like(t)

    dt = t[1]-t[0]  # use the actual time step
    x[0:2] = [ 0, 0]
    for j in range(1,len(t)-1):
        x[j+1] = ( dt**2 + (2*m-K*dt**2)*x[j] - (m-0.5*dt*b)*x[j-1] ) / (m+0.5*dt*b)
    return t,x

t,x = MSD_Solver(1,.5,5)
plt.plot(t,x); plt.show();