text:
Q: Python dbfpy and FoxPro I am using an ancient database format here, dbf files. Don't ask why, just know a certain software decided to extend foxpro support because microsoft decided to extend foxpro support. Now, I'm getting the following error on a specific file. I have successfully loaded another file and I'm curious if there is something wrong with this database. I'm sure you probably need to look at the database to determine that, but its way to huge to post so I'll take what I can get.
Traceback (most recent call last):
  File "billsapi.py", line 250, in <module>
    x.getUsedGuns()
  File "billsapi.py", line 72, in getUsedGuns
    itemdb = dbf.Dbf('item.dbf', readOnly=True, ignoreErrors=True)
  File "C:\Python27\lib\site-packages\dbfpy\dbf.py", line 135, in __init__
    self.header = self.HeaderClass.fromStream(self.stream)
  File "C:\Python27\lib\site-packages\dbfpy\header.py", line 127, in fromStream
    _fld = fields.lookupFor(_data[11]).fromString(_data, _pos)
  File "C:\Python27\lib\site-packages\dbfpy\fields.py", line 455, in lookupFor
    return _fieldsRegistry[typeCode]
KeyError: '0'

And heres my simple code that is returning this error:
def getUsedGuns(self):
    itemdb = dbf.Dbf('item.dbf', readOnly=True, ignoreErrors=True)

Like I said, I can load other files with out a problem but maybe there is a work around for this specific error?
EDIT: I'd also like to point out that the file can be opened and viewed and modified in DBF View Plus.

A: Your traceback is dbfpy's way of telling you that your file has an unsupported-by-dbfpy field type code, 0. It's a Visual FoxPro ("VFP") thing.
This is nothing to do with memo files. Yes, if there are memo fields, they are stored in a .FPT file. foo.fpt needs to be present when you access foo.dbf.
You say """I actually ended up using the python dBase module""" ... presumably you mean Ethan Furman's dbf module, which according to its PyPI entry doesn't support null fields.
I have a DBF reading module (pydbfrw) which I've been meaning to release "one of these days". Here's an extract from its docs:
Field Type      Description  DBF variety  Python 2.x type
0 (digit zero)  _NullFlags   VFP          N/A

Notes: This field type is used only for the hidden _NullFlags field which
is a bit mask saying which fields in the record should be interpreted as NULL.

My module implements recognising that and returning None for a field value where required. If you would like a copy of the module, find my e-mail address -- e.g. google("john machin xlrd") -- e-mail me and I'll send it to you.

A: Could be that item.dbf uses more advanced dbf capabilities that the other dbf does not.  For instance, auto increment integers were introduced very late and are not supported by most odbc drivers.

A: You should take a look at Sybase's Advantage Database Server. This product has excellent support for VFP DBF files. I have been using their ODBC drivers with Python via pyodbc for a few years, and have had excellent results using their recently released a DB-API 2.0 compliant Python driver.
I too have been put in the position where I must support DBF tables. The Advantage Database Server has been an absolute lifesaver.

A: I actually ended up using the python dBase module. I think my main problem was not having the memo files around (whatever they are, it has a .fpt file extension). Here is what I am using at the moment:
from dbf.tables import VfpTable
itemdb = VfpTable('item.db')
for rec in itemdb:
    print rec['MY_COLUM_NAME']

This answer was posted as an edit to the question Python dbfpy and FoxPro by the OP Dalton Conley under CC BY-SA 2.5.


text:
Q: Previous frame is shown when I set the paused time and call play on MPMoviePlayerController I am using MPMoviePlayerController to play the movie in iPhone. When I switch to some other UIViewController I pause the movie. When I come back to MPMoviePlayerController, user should be able to resume from the point where it was paused.
When I switch to some other UIViewController:

*

*Pause the movie

*Cache the movie time when it was paused.

*Remove the view of MPMoviePlayerController from its superview due to some flickering issue.

When I come back,
a) create and add the view of MPMoviePlayerController to the superview
b) Set the cached time to the MPMoviePlayerController
c) Call play on MPMoviePlayerController.
Sometimes, the previous frame (which is far by the frame where it was paused by observable amount) is shown when I call play.
How do I solve this?

redpajama_set_name: RedPajamaStackExchange


text:
Q: How do you efficiently return the order of an increasing index? I have the following index vector:
TestVec = rep(c(6,8,9,11,18), each = 10)

This reads c(6, 6, ..., 6, 8, 8, ..., 8, 9, 9, ..., 9, ...).
I would like to convert this vector into c(1, 1, ..., 1, 2, 2, ..., 2, 3, 3, ..., 3, ...)

Try
I have improvised a quick-and-dirty method, as follows:
sapply(TestVec, function(x) {which(x == unique(TestVec))})

This works fine, but this takes a lot of time in a large dataset.
Is there any efficient way to improve?

A: match(TestVec, unique(TestVec))

A: Another option:
as.numeric(as.factor(TestVec))
# [1] 1 1 1 1 1 1 1 1 1 1 2 2 2 2 2 2 2 2 2 2 3 3 3 3 3 3 3 3 3 3 4 4 4 4 4 4 4 4 4 4 5 5 5 5 5 5 5 5 5 5

A: Requiring data.table:
rleid(TestVec)

A: Here is another one,
c(1, cumsum(diff(TestVec) != 0)) + 1


text:
Q: Can keras progress bar show instantaneous metrics rather than running average? By "progress bar" I mean the standard progress bar that shows up with tf.keras.Model.fit
As I understand, it shows a running average of your selected metrics (over the current epoch), but I want it to show the value at the last completed iteration.
Is there a built-in way to make this change? And if not, what would be the easiest way?

A: I made a callback a while ago to solve this problem.
class print_on_end(Callback):
  def on_batch_end(self, batch, logs={}):
    print()

You want to call it like this.
model.fit(training_dataset, steps_per_epoch=num_training_samples, epochs=EPOCHS,validation_data=validation_dataset, callbacks=[print_on_end()])

But this callback prints the everages, just on different lines, so i don't thinks its what you want.
This instead:
class LossAndErrorPrintingCallback(keras.callbacks.Callback):
    def on_train_batch_end(self, batch, logs=None):
        print("For batch {}, loss is {:7.2f}.".format(batch, logs["loss"]))
            )
        )

This callback prints the loss of every batch, so it should be what you are looking for.
( if you need the metric just change logs["loss"] with logs["name of the metric"]  ex. logs["mean_absolute_error"]
EDIT:
to check the name of the metric inside logs you could print the keys of the log and find the ona you are searching.
class PrintKeys(keras.callbacks.Callback):
    def on_train_batch_end(self, batch, logs=None):
        keys = list(logs.keys())
        print(keys)
            )
        )

In that method you should only find the keys for the loss and the metric.
source:
https://keras.io/guides/writing_your_own_callbacks/

A: An example of the class hierarchy of the MeanSquaredError metric is
MeanSquaredError->MeanMetricWrapper->Mean->Reduce->Metric

Is there a built-in way ?

The main problem is that all metrics are subclasses of the Reduce metric, which performs the aggregation, and there is nothing foreseen to change the behaviour of the Reduce base class.

How to achieve this the most easily

Given the schema above  you can achieve what you want by means of creating a new metric subclass of the MeanMetricWrapper
which overrides the update_state method of the MeanMetricWrapper
by means of first calling self.reset_state and then  MeanMetricWrapper.update_state.
Like this, the aggregates in the underlying Reduce base class will aggregate only a single value. Working Example below:
#! /usr/bin/env python
import numpy as np
import keras
from keras.metrics import MeanMetricWrapper

x=np.linspace(0, 1, 20000)[:,np.newaxis,np.newaxis]
y=np.sin(x*2*np.pi)

model = keras.Sequential()
model.add(keras.layers.Dense(4, activation="tanh", input_shape=(1,1)))
model.add(keras.layers.Dense(4, activation="tanh"))
model.add(keras.layers.Dense(4))

#####
# Here the Instantaneous metric variant
class InstMetric(MeanMetricWrapper):
    def __init__(self, fn, **kwargs):
        """ fn is the callable loss function you want to use in your metric """
        super().__init__(fn=fn, **kwargs)

    def update_state(self, y_true, y_pred, sample_weight=None):
        self.reset_states()
        return super().update_state(y_true, y_pred, sample_weight=sample_weight)
#####

model.compile(optimizer='adam', loss='mean_squared_error',
              metrics=[
                 keras.metrics.MeanSquaredError(name="MSE"),
                 InstMetric(keras.metrics.mean_squared_error, name="IMSE")
              ]
)

model.fit(x=x, y=y, epochs=1, batch_size=5, steps_per_epoch=1000)

Storing this script as inst_demo.py and running it through tr to unfold the progress bar in the terminal
you get
$> ./inst_demo.py | tr \\r \\n

   1/1000 [..............................] - ETA: 8:07 - loss: 0.4656 - MSE: 0.4656 - IMSE: 0.4656
  42/1000 [>.............................] - ETA: 1s - loss: 0.4874 - MSE: 0.4874 - IMSE: 0.4133
  87/1000 [=>............................] - ETA: 1s - loss: 0.4685 - MSE: 0.4685 - IMSE: 0.4764
 132/1000 [==>...........................] - ETA: 1s - loss: 0.4627 - MSE: 0.4627 - IMSE: 0.5445
 175/1000 [====>.........................] - ETA: 0s - loss: 0.4558 - MSE: 0.4558 - IMSE: 0.7689
 217/1000 [=====>........................] - ETA: 0s - loss: 0.4443 - MSE: 0.4443 - IMSE: 0.1058
 264/1000 [======>.......................] - ETA: 0s - loss: 0.4258 - MSE: 0.4258 - IMSE: 0.4162
 311/1000 [========>.....................] - ETA: 0s - loss: 0.4090 - MSE: 0.4090 - IMSE: 0.1716
 356/1000 [=========>....................] - ETA: 0s - loss: 0.3889 - MSE: 0.3889 - IMSE: 0.3417
 400/1000 [===========>..................] - ETA: 0s - loss: 0.3707 - MSE: 0.3707 - IMSE: 0.1271
 445/1000 [============>.................] - ETA: 0s - loss: 0.3532 - MSE: 0.3532 - IMSE: 0.0729
 489/1000 [=============>................] - ETA: 0s - loss: 0.3383 - MSE: 0.3383 - IMSE: 0.2310
 535/1000 [===============>..............] - ETA: 0s - loss: 0.3248 - MSE: 0.3248 - IMSE: 0.1228
 580/1000 [================>.............] - ETA: 0s - loss: 0.3143 - MSE: 0.3143 - IMSE: 0.2670
 625/1000 [=================>............] - ETA: 0s - loss: 0.3048 - MSE: 0.3048 - IMSE: 0.1762
 671/1000 [===================>..........] - ETA: 0s - loss: 0.2962 - MSE: 0.2962 - IMSE: 0.0751
 715/1000 [====================>.........] - ETA: 0s - loss: 0.2896 - MSE: 0.2896 - IMSE: 0.0650
 756/1000 [=====================>........] - ETA: 0s - loss: 0.2831 - MSE: 0.2831 - IMSE: 0.2332
 799/1000 [======================>.......] - ETA: 0s - loss: 0.2773 - MSE: 0.2773 - IMSE: 0.1026
 841/1000 [========================>.....] - ETA: 0s - loss: 0.2721 - MSE: 0.2721 - IMSE: 0.1238
 888/1000 [=========================>....] - ETA: 0s - loss: 0.2673 - MSE: 0.2673 - IMSE: 0.1471
 936/1000 [===========================>..] - ETA: 0s - loss: 0.2631 - MSE: 0.2631 - IMSE: 0.2242
 986/1000 [============================>.] - ETA: 0s - loss: 0.2580 - MSE: 0.2580 - IMSE: 0.2704
1000/1000 [==============================] - 2s 1ms/step - loss: 0.2574 - MSE: 0.2574 - IMSE: 0.2773

So you get an instant value each time the progressbar is updated.
You can also derive the InstMetric from any of the available keras metrics, if you don't want to be able to select the metric you will use.


text:
Q: knowing user refresh the page, web stats hiks ... im stack again ...
I try to make a simple visitor statistic, and i have a problem.
How to make the statistic don't update if user refresh the page ?
here my snippet
public function saveData($sid)
{
    global $database;

    $reff = parse_url($_SERVER['HTTP_REFERER']);
    $referrer = isset($reff['host']) ? $reff['host'] : 'direct';
    $own = $_SERVER['HTTP_HOST'];

    if($referrer!=$own){
        $ip       = ip2long($_SERVER['REMOTE_ADDR']);
        $time     = time();
        $page     = $_SERVER['REQUEST_URI'];
        $add = $database->tableAdd("eu_shop_pageview", "shop_id, ip, timestamp, page, referrer", "'$sid', '$ip', '$time', '$page', '$referrer'");
    }
}

thanks :)
Regards, Stecy

A: Check if the IP address exist in the table within a time frame, if it does then don't enter it, just update the time. This is something for which you cant calculate the exact number, just an approximate count.

A: Personally, when I do view tracking, I have the following columns:
`id`
`identifier` : this is either the person's username or if they don't have an account, their IP
`date` : inserted using CURDATE()
`page_url`

Before adding to this table, I run the following query and if there are no rows returned, then I insert into that table to add a view to that page:
SELECT id FROM views WHERE identifier = '$user_id' AND date = CURDATE() AND page_url = '$url' LIMIT 1

You would want to change how you select the date if you want more/less than a day's timeframe for deciding to count new views.


text:
Q: Using bash to replace html character entities in the xml file I have a string like this in xml file:

Styled here with: FRS blo, Os Cutes&nbsp;and Dor Sho
</short-description>
I need to replace /p&gt part with /h3&gt.
I tried to do this with the help of sed like below:
sed -i -e 's/
Styled here with\:.*\/p>/
Styled here with\:.*\/h3>/g' new_exp_dev02.xml
but this did not work at all and just doubled the result.
Maybe I forgot to escape some more symbols in order to replace /p&gt part with /h3&gt correctly?

A: sed can use nearly any character as a delimiter for its expression, I have found it best to not use a delimiter that is in the string one is attempting to replace to limit escaping mistakes.
sed -e 's!/p&gt!/h3\&gt!g' new_exp_dev02.xml would replace /p&gt with /h3&gt.  The ampersand (&) in the replacement needs to be escaped as that character has a special meaning in sed replacement expressions.
Your posted sed expression is very hard to read and I am not sure what you are attempting to achieve with it, but it seems to have a different goal then "replace /p&gt part with /h3&gt."
EDIT: if you have to write the expression in that long form, this should work:
sed -e 's!\(
Styled here with:.*\)/p>!\1/h3\>!g' new_exp_dev02.xml
This puts the whole matched part aside from /p&gt into a back reference which we can use in the replacement section as \1.  You cannot use regular expression on the replacement side of a sed replacement, as regular expressions are only used for matching.
The first expression in this answer will replace all occurrences of /p&gt with /h3&gt, the second expression will only replace /p&gt if it occurs immediately after matching the regular expression "
Styled here with:.*"

A: You can try with below perl command
 perl -pne "s/p&gt/h3&gt/g" filename

output

Styled here with: FRS blo, Os Cutes&nbsp;and Dor Sho
</short-description>


text:
Q: What happens to the Objects in the heap when JVM exits? When JVM is started OS allocates memory to it and then that memory is used as the heap and the stack. When we create an object in the heap, what happens to the object after the JVM exits? Does it quietly stay there and OS reallocates that memory when JVM restarts? Or does something else happen?

A: Most objects simply "evaporate" when the JVM exits — i.e., they vanish without the normal garbage collection process (including finalization) taking place.  (It is possible to request finalization for them, but it is unwise because they may still be reachable and in use.)  If those objects represent OS resources like open files, those resources are released (closed), but without guaranteeing that all outstanding data is saved (as happens when you close them yourself).
More generally, when a process exits, all of its normal stack and heap memory is immediately freed by the OS (although some of it, like that used to store the executable and other files that were read, can sometimes be reused (or left in use) for other processes that need those files).  Exceptions include things like shared memory used for interprocess communication, which you're probably not using without knowing it.

A: Objects in the heap are freed when the JVM exits (most of the time).
The reason I say most of the time is because freeing the heap is the responsibility of the operating system, not the JVM alone. The operating system does the effort of cleaning up and making memory allocations available for leasing. But this also depends on the operating system, I'm sure there are operating systems out there where they don't follow this mainstream method.


text:
Q: How to parse Json response in Angular 4 Hi i am beginner in ionic with angular app development and using below code for Http calls and i got response in json format, Now i want show response title in list,I tried lot but not getting result can some one help me please
Api url:
https://www.reddit.com/r/gifs/top/.json?limit=2&sort=hot
home.ts:
this.http.get('https://www.reddit.com/r/gifs/top/.json?limit=2&sort=hot',{ observe:'response'}).subscribe( res => { console.log(res) ;
          var info=JSON.parse(JSON.stringify(res));
          this.countries = info.data.children;
      });

home.html:
<ion-content padding>
  <ion-list>
  <ion-item *ngFor="let c of countries">

{{c.title}}

  </ion-item>
</ion-list>
</ion-content>

A: You are using the wrong key to fetch value in HTML part, the code should be -

{{c.data.title}}

instead of

{{c.title}}

also why are you using parse then stringify , just simply assign value using json() like this -
this.http.get('https://www.reddit.com/r/gifs/top/.json?limit=2&sort=hot', {observe:'response'}).subscribe( res => {
      console.log(res) ;
      let response = res.body;
      this.countries = response.data.children;
    });

Working Example
Update
If you are using httpClient  then no need to use json() also remove {observe:'response'} as there is no need of this in your use case.

A: Use rxmap
import 'rxjs/add/operator/map';

this.http.post('https://www.reddit.com/r/gifs/top/.json?limit=2&sort=hot',{ observe:'response'}).map(res => res.json()).subscribe(data => {
   console.log(data.data);
});

A: try with this
this.http.get('https://www.reddit.com/r/gifs/top/.json?limit=2&sort=hot',{ observe:'response'}).subscribe( res => { console.log(res) ;
      this.countries = info['data'].children;
  });


text:
Q: Puppeteer find list of shadowed elements and get list of ElementHandles I'm running Node 12 along with Puppeteer 2.2.1 (both can't be upgraded right now).
The challenge is to find DOM elements inside shadowed roots and passing them to another function of my main class. Additionally, I'm scraping different websites, so the code has to find shadowed roots dynamically. Using page.$() or page.$$() I'm not able to check if element has a shadowRoot, using page.$$eval() or page.evaluate() it seems, I cannot pass back element handles to main function (at least I don't know how to do this).
For example, this code I'm able to traverse over all elements and find elements with matching criteria, but evaluate() returns texts and evaluateHandle() returns a JSHandle only, which are not iterable.
#!/usr/bin/env node

'use strict';

const puppeteer = require('puppeteer');

class Generator {
    main() {
        const url = 'https://www.example.com';
        const browser = await puppeteer.launch();
        const page = await browser.newPage();
        await page.goto(url, {waitUntil: 'networkidle2'});
        await this.scrape(page);
    }

    async process(page, element) {
        await page.evaluate(element => {
            element.click();
        }, element);
        this.doOtherThingsWithElement(element);
    }

    async scrape(page) {
        const elements = await page.evaluateHandle(() => {
            const walk = root => [
            ...[...root.querySelectorAll('[class*=shadowed-child] button')],
            ...[...root.querySelectorAll('*')]
                .filter(e => e.shadowRoot)
                .flatMap(e => walk(e.shadowRoot))
            ];
            return walk(document);
        });
        // THIS does not work
        for (const element of elements) {
            await this.process(page, element);
        }
    }
}

How can I access the DOM elements in for loop?

A:
How can I access the DOM elements in for loop?

You can't, as of the time of writing. A JSHandle is not iterable and has no length or indexing capabilities. As this answer shows, the only way to work with this JSHandle is to run it through another evaluate, at which point the array is accessible:
const puppeteer = require("puppeteer"); // ^19.1.0

const html = `<!DOCTYPE html>

foo

bar

baz

`;

let browser;
(async () => {
  browser = await puppeteer.launch();
  const [page] = await browser.pages();
  await page.setContent(html);
  const handle = await page.evaluateHandle(() =>
    document.querySelectorAll("h1")
  );
  const text = await handle.evaluate(els =>
    [...els].map(e => e.textContent)
  );
  console.log(text); // => [ 'foo', 'bar', 'baz' ]
})()
  .catch(err => console.error(err))
  .finally(() => browser?.close());

It's unimportant that the above example doesn't use shadow roots; the behavior is the same either way:
const html = `<!DOCTYPE html>

`;

let browser;
(async () => {
  browser = await puppeteer.launch();
  const [page] = await browser.pages();
  await page.setContent(html);
  const handle = await page.evaluateHandle(() =>
    document
      .querySelector("div")
      .shadowRoot
      .querySelectorAll("h1")
  );
  const text = await handle.evaluate(els =>
    [...els].map(e => e.textContent)
  );
  console.log(text); // => [ 'foo', 'bar', 'baz' ]
})()
  .catch(err => console.error(err))
  .finally(() => browser?.close());

I'll just use the non-shadow root boilerplate for the rest of this post for simplicity, keeping in mind page.$$ is not an option, which is the primary relevance of the shadow roots to this particular problem.

Now, there are some additional workarounds I can offer. These are generic since I'm not sure what your actual use case is, so hopefully you can figure it out from here. One approach is to store the shadow roots in a variable in the DOM, then return the length and use that in a loop:
// ... same boilerplate
const length = await page.evaluate(() => {
  window.nodes = [...document.querySelectorAll("h1")];
  return window.nodes.length;
});

for (let i = 0; i < length; i++) {
  const text = await page.evaluate(i =>
    window.nodes[i].textContent, i
  );
  console.log(text);
}
// ...

A more naive approach is to just do the traversal and selection every time you need to evaluate, which avoids storing the array on the window which can potentially go stale after a mutation or clash with a global.
Taking the approach a step further, you can make an array that works sort of like page.$$'s ElementHandle[] return value enough for your intended use case:
// ...
const length = await page.evaluate(() => {
  window.nodes = [...document.querySelectorAll("h1")];
  return window.nodes.length;
});
const nodes = await Promise.all([...Array(length)].map((_, i) =>
  page.evaluateHandle(i => window.nodes[i], i)
));

// make up a silly process function
const process = element =>
  // element.click() will now work, but for simplicity:
  element.evaluate(el => el.textContent);

// now go and do the thing you wanted to do originally
for (const node of nodes) {
  console.log(await process(node));
}
// ...

Note that window.nodes is just an example, probably not the best property to avoid unlikely clashes, and of course replace window.nodes = [...document.querySelectorAll("h1")]; with your shadow root traversal.
Also, if length is large, const nodes = await Promise.all might be too much parallelism, in which case you can use a traditional imperative serial loop:
// ...
const nodes = [];
for (let i = 0; i < length; i++) {
  nodes.push(await page.evaluateHandle(i => window.nodes[i], i));
};

for (const node of nodes) { /* ... */ }
// ...

For some use cases, the :nth-child CSS pseudoselector can work for indexing as well.
Depending on your use case, page.exposeFunction may help too, letting you trigger Node code from the browser context depending on each element you're processing.
Additionally, you may be able to use native DOM functions for clicking and doing whatever else you need to do, avoiding the need to make an array of handles in Node context and keeping all of your activity inside evaluate(s).


text:
Q: How to enable Live Service Controller Reporting? Application Screenshot:

Application Code:
Dim myController As New System.ServiceProcess.ServiceController("SQL Server (SQLEXPRESS)")
Sub ed()
    If txtNum.Text = "Started" Then
        btnStart.Enabled = False
        btnStop.Enabled = True
    ElseIf txtNum.Text = "Stopped" Then
        btnStop.Enabled = False
        btnStart.Enabled = True
    End If
End Sub
Sub Na1()
    If myController.Status = ServiceProcess.ServiceControllerStatus.Running Then
        txtNum.Text = "Started"
    ElseIf myController.Status = ServiceProcess.ServiceControllerStatus.Stopped Then
        txtNum.Text = "Stopped"
    End If
End Sub
Private Sub Test_Load(sender As Object, e As EventArgs) Handles MyBase.Load
    Na1()
    ed()
End Sub
Private Sub Test_MouseMove(sender As Object, e As MouseEventArgs) Handles Me.MouseMove
    Me.Refresh() '////////This one is not required
End Sub

Private Sub btnStart_Click(sender As Object, e As EventArgs) Handles btnStart.Click
    ProgressBar1.Value = 0
    Try
        myController.Start()
    Catch ex As Exception
        MsgBox(ex.Message)
    Finally
        ProgressBar1.Value = 100
        Na1()'//////////////////////////////////////////////Edit Code here
    End Try
End Sub

Private Sub txtNum_TextChanged(sender As Object, e As EventArgs) Handles txtNum.TextChanged
    ed()
End Sub

Private Sub btnStop_Click(sender As Object, e As EventArgs) Handles btnStop.Click
    ProgressBar1.Value = 0
    Try
        myController.Stop()
    Catch ex As Exception
        MsgBox(ex.Message)
    Finally
        ProgressBar1.Value = 100
        Na1() '//////////////////////////////////////////////Edit Code here
    End Try
End Sub

You need to stop SQL Service to Copy .mdf File and it is very irritating by Stopping/Starting the service manually from 'Services' so I tried to make it easier by using Vb.Net coding...

A: Edit the Following codes,
Private Sub btnStart_Click(sender As Object, e As EventArgs) Handles btnStart.Click
ProgressBar1.Value = 0
Try
    myController.Start()
Catch ex As Exception
    MsgBox(ex.Message)
Finally
    ProgressBar1.Value = 100
    Na1()'//////////////////////////////////////////////Edit Code here
End Try
End Sub

To
Private Sub btnStart_Click(sender As Object, e As EventArgs) Handles btnStart.Click
    ProgressBar1.Value = 0
    Try
        myController.Start()
    Catch ex As Exception
        MsgBox(ex.Message)
    Finally
        ProgressBar1.Value = 100
        myController.WaitForStatus(ServiceProcess.ServiceControllerStatus.Running)'//Add
        Na1()
    End Try
End Sub

And
Private Sub btnStop_Click(sender As Object, e As EventArgs) Handles btnStop.Click
ProgressBar1.Value = 0
Try
    myController.Stop()
Catch ex As Exception
    MsgBox(ex.Message)
Finally
    ProgressBar1.Value = 100
    Na1() '//////////////////////////////////////////////Edit Code here
End Try
End Sub

To
Private Sub btnStop_Click(sender As Object, e As EventArgs) Handles btnStop.Click
    ProgressBar1.Value = 0
    Try
        myController.Stop()
    Catch ex As Exception
        MsgBox(ex.Message)
    Finally
        ProgressBar1.Value = 100
        myController.WaitForStatus(ServiceProcess.ServiceControllerStatus.Stopped) '//Add
        Na1()
    End Try
End Sub

And all is done!


text: Q: SPFx Application customizer not loading I have an application customizer that is deployed to tenant app catalog. App is added to a site and I have verified the feature is activated but the extension never loads. I added a console log after the onInit() and it never fires. I never even see the JavaScript file called in network tab. Work fine when debugging. Has anyone else ran into this issue?


text:
Q: Calculate transformation matrix between 4 points in 3D space I have 2 sets of 4 vertices of the same object, calculated from different position in 3D space. Like that:
Relative to position 1:
    p0 = [10.9651660037735,  -1732.84852242907, -2077.46947601362]
    p1 = [-28.2892402763447, -1731.04816455574, -2273.71719218789]
    p2 = [168.546146377346,  -1737.13196368097, -2312.30780650516]
    p3 = [206.483925998667,  -1738.21953548907, -2116.14490306792]

Relative to position 2:
    p0 = [-322.364164317381, -1161.90839935893, -2013.94533203480]
    p1 = [-240.373482014670, -1177.43805826682, -1832.26745097626]
    p2 = [-422.125535145367, -1172.37193516593, -1749.48740754854]
    p3 = [-504.665226201976, -1158.25483667854, -1931.16712127311]

The coordinates are received from analog sensors so it may have some inaccuracy. How can i calculate or approximate the transformation matrix between them?

A: If its "viewed" from different position and perspective is involved than shape and size might be different. So are you sure you do not have perspective involved? Many ranging sensors do include perspective like LIDAR , RADAR etc and some are countering it by processing other are not. So if the object is more distant to sensor is it still the same size or not?

*

*No perspective
see Problem superimposing and aligning 3D triangles
The idea is to create transform matrix for each object and then just convert one matrix to the other one.

*Perspective
This is way more complicated. Either use fitting (slooooow) or use some prior knowledge of the sensor (ease up the fitting). Anyway if you have certain geometric features in "view" then you can avoid fitting see:

*

*Transformation of 3D objects related to vanishing points and horizon line
that one exploits the fact that you know any 2 perpendicular planes with the points selected on the same altitude ... You can may be exploit similar properties of your data like known size of object or include markers into the "scene".
After this you just un-project all the stuff you need and then proceed with #1


text:
Q: Receiving SMS Messages using WMA in Java ME I am trying to develop a sms sending and receiving test application in J2ME using the WMA API. I have separate threads for sending and receiving.
The Sending thread's run method -
public void run() {
        try {

            MessageConnection connection = (MessageConnection) Connector.open("sms://+" + number + ":1234");
            BinaryMessage messageBody = (BinaryMessage) connection.newMessage(connection.BINARY_MESSAGE);
            messageBody.setPayloadData(message.getBytes());
            connection.send(messageBody);
            connection.close();

        } catch (IOException ex) {

        }
    }

The receiving thread's run method
public void run() {
        try {
            while (true) {
                MessageConnection connection = (MessageConnection) Connector.open("sms://:1234");
                BinaryMessage messageBody = (BinaryMessage) connection.receive();
                message = new String(messageBody.getPayloadData());
                number = messageBody.getAddress();
                number = number.substring(6, 15);
                App.setDisplay(number, message);
                connection.close();
            }
        } catch (IOException ex) {
            ex.printStackTrace();

        }
    }

I am initializing the receiving thread in the startApp() and initializing the sending thread when the send command is pressed. The problem I have is that if I use two Emulators, both sides can't send messages. One emulator can continuously send messages to the other but when the other emulator tries to send a message the message isn't received.
When a message is received by the emulator console shows -

[INFO] [sms     ] ## javacall: SMS
  sending...

when that line appears the emulator doesn't receive any messages. Where is the problem in my code?
PS: I saw that their is a way to use a listener to work around this problem with using a separate thread for receiving but I want to know where is the problem is in the above code?
Any help is really appreciated ^^

A: If you are running in emulator, use wma console available to send or receive messages. You can't do it from emulator to emulator. wma console is available at
utilities -> wma console

A: I found the problem... It's because SMS doesn't work in Netbeans above versions. It only works in Netbeans 6.1 ... Something is wrong with the emulator


text:
Q: Handling Model Inheritance in Django and REST I'm trying to achieve the following model structure:
class X(models.Model):
    class Meta:
        abstract = True

    objects  = InheritanceManager()
    agroup   = models.ForeignKey(A, related_name="%(class)s_set")
    xfield   = models.CharField()

class A(models.Model):

class Y(X):
    yfield   = models.CharField()

class Z(X):
    zfield   = models.CharField()

The first issue is, the Base X class can't be abstract it seems because I need to be able to iterate over all subclasses of X (Y,Y,Y,Z,Z) so I need access to the manager. While X is abstract, X.objects doesn't work.
Second issue is in the REST serializer. I can only reference x_set in ASerializer, as it is the only property that exists on A. And that only display the xfield in the nested list. What I would really like is y_set and z_set on the ASerializer with their respective yfield and zfield displayed.
I can achieve some of this with different configurations (iteration over children by removing abstract, or separation of children in the rest serializer by places the FK field on Y and Z directly), but never all the same time.
Thank you.

A: Phew!
I stuck with X being abstract, the way to then iterate over X's children:
for x_child_class in X.__subclasses__():
    for child in x_child_class.objects.all():
        #Do your stuff

And as long as X is abstract, Class A should have y_set and z_set on it, so you can just:
class ASerializer(serializers.HyperlinkedModelSerializer):
    y_set = YSerializer(many=True)
    z_set = ZSerializer(many=True)

    class Meta:
        model = A

Trivial, but took a long time for some reason.


text:
Q: Can I expose all the attributes for a terraform resource in a single output variable? I need to expose all the attributes for a specific resource in a single output variable for a terraform module.
Is this doable in terraform?

A: Yes,
output "my_vm" {
  value = aws_instance.my_vm
}

But you'll get a ton of weird junk in there so it may not be worth it.


text:
Q: No module Found error in Linux but Works fine in Windows I am trying to run a Program that I coded in Python in Windows environment
When I am trying to copy the program and running it in Linux(Debian),
It won't work,
It is giving the following error,
Traceback (most recent call last):
  File "BlackBox.py", line 26, in <module>
    from BB_Files import BB_Expand
ImportError: No module named BB_Files

Despite the presence of the file BB_Expand inside BB_Files folder, I am still getting the error.
I have also tried appending the path of my current directories in Python,
sys.path.append("/home/pe/Desktop/AES")
# Sub-Folders of AES are also accessible
sys.path.append("/home/pe/Desktop/AES/BB_Files")

But Still no Luck,
This is the File Structure,
/home/pe/Desktop/AES/Main.py
/home/pe/Desktop/AES/BB_Files
/home/pe/Desktop/AES/BB_Files/BB_Days.py
/home/pe/Desktop/AES/BB_Files/BB_Expand.py
/home/pe/Desktop/AES/BB_Files/BB_Steps.py

this is the output of ls -l command,
drwxrwx--x 4 pe users  4096 Oct 26 21:43 BB_Files
-rw-rw---- 1 pe users 15284 Oct 26 22:04 Main.py

This is some initial code in the file,
import sys    # sys.argv ; sys.path, sys.exit
import os
import hashlib
import struct # Interpret strings as packed binary data
import getopt # for Runtime arguments
import time
from datetime import date

# Append Paths from where the Files would be Imported.
sys.path.append("/home/pe/Desktop/AES")
# Sub-Folders of AES are also accessible
sys.path.append("/home/pe/Desktop/AES/BB_Files")
# Sub-Fodlers of BB_Files are also accessible now (Tables)
from BB_Files import BB_Expand
from BB_Files import BB_Steps
from BB_Files import BB_Days

This is the line giving an error,
from BB_Files import BB_Expand

The program doesn't run after this line because the Python couldn't find this Module.
The same code works absolutely fine in Windows.
could anyone please help me out with this ?

A: You need to create a (possible empty) file called __init__.py in your BB_Files folder. From the docs:

The __init__.py files are required to make Python treat the directories as containing packages; this is done to prevent directories with a common name, such as string, from unintentionally hiding valid modules that occur later on the module search path. In the simplest case, __init__.py can just be an empty file, but it can also execute initialization code for the package


text:
Q: Pregunta sobre super, extends get y set en javascript soy nuevo en esto, tengo una duda=>
Mi clase superheroe podra hacer cosas que tiene su clase padre Persona, por eso encarni puede gritar, pero como lo hago al reves, para que una persona pueda tener superpoderes?
Todo esto no tiene nada que ver con get y set no? Tengo entendido que el metodo get almacena una propiedad de su PROPIA CLASE, pero que podria hacer con set aqui, y como podria hacer para que una persona tenga superpoderes?
Muchas gracias

class Persona{
  constructor(nombre, apellido, edad, cm, hijos, celiacos){
    this._nombre = nombre;
    this._apellido = apellido;
    this._edad = edad;
    this._cm = cm;
    this._hijos = hijos;
    this._celiacos = celiacos;
  }
  get presentacion(){
    return  'Hola mi nombre es ' + this._nombre + ' y tengo ' + this._edad + 'años';
  }

  gritar(volumen = ' a un volumen desconocido'){ // metodo no necesita function
    console.log(this._nombre +  ' he pegado un grito' + volumen)
  }
}

let amigo1 = new Persona('ivan', 'garcia lopez', 33, 185, false, true)
let amigo2 = new Persona('Fran', 'Manrique', 33, 185, false, true)

console.log(amigo1.presentacion);
amigo1.gritar(' a un volumen estratosferico')
amigo2.gritar();

class Superheroe extends Persona{
  constructor(nombre, apellidos, edad, altura, celiaco, hijos, poderes){
    super(nombre, apellidos, edad, altura, celiaco, hijos);
    this._poderes = poderes;
  }

  relatarPoder(){
    console.log('Tengo ' + this._poderes.length + ' poderes y el primero es ' + this._poderes[0]);
  }

  get misPoderes(){
    return this._poderes;
  }
}
let poderes = ['volar', 'escupir fuego', 'matar']
let wonderWoman = new Superheroe('encarni', 'garcia', 35, 178, false, false, poderes);
wonderWoman.gritar(); // Puede gritar ya que extiendo persona a mi superheroe
wonderWoman.relatarPoder();
amigo2.relatarPoder(); // AMIGO 2 NO PUEDE TENER PODER


text:
Q: Why I am getting the error regarding maven libraries? Java:cannot access com.azure.core.util.BinaryData
class file for com.azure.core.util.BinaryData not found.
While running the main application I am getting this error, how to resolve this, I tried maven installation in local & checked the libraries, still some of the libraries are missing

A: This means that either you're missing the neccessary dependency or the repository for that class is missing. If you are missing the dependency add this:
<dependency>
    <groupId>com.microsoft.azure</groupId>
    <artifactId>azure-core</artifactId>
    <version>0.9.8</version>
</dependency>

It shouldn't be a problem to find it since it is in the central repo


text:
Q: where to put css and javascript files in eclipse dynamic web project I decided to add an external css file for a dynamic web project created in eclipse. If I create "fooStyle.css" and refer to it within a jsp file where should I put the css file in the project folder?
<html>
    <head><title>Foo</title>
    <link rel="stylesheet" href="fooStyle.css">
    </head>
     <body>....</body>
</html>

[update]
The below link gives me some idea where to put. It says I should put it under theme, but I am not sure this is a directory I have to create manually under WebContent or at the same level as of WebContent.
http://help.eclipse.org/indigo/index.jsp?topic=%2Forg.eclipse.wst.webtools.doc.user%2Ftopics%2Fccwebprj.html


text:
Q: Changing network device name of a nfsroot used device So to the context, I have a couple of machines starting up via an pxeboot that use an nfs share as their root.
Being able to use it you can/have to specify an device name in the pxelinux.cfg which you want to use for that boot.
Now I know that renaming of the devices would work with adding the /etc/udev/rules.d/70-persistent-net.rules and adding content like this:
SUBSYSTEM=="net", ACTION=="add", DRIVERS=="?*", ATTR{address}=="xx:xx:xx:xx:xx:xx", ATTR{dev_id}=="0x0", ATTR{type}=="1", NAME="mynewname"

It als works for all devices besides that one device that you have to leave in the /etc/network/interfaces on manually like this:
iface enp8s0f2 inet manual

So the system doesn't try to restart the device and while doing it crash the system.
However now while trying around with renaming the device names I noticed it's also not possible (at least I couldn't find an obvious way) of renaming this used device. I'm assuming it's because the system is blocked by the loaded kernel to restart the device that is used as an nfsroot.
Now my question would be, is there a way to rename it?
Like adjusting the name during the boot (so before the nfs mount happens) and not afterwards, via an append command or adjusting the kernel used for booting?


text:
Q: Parallel.ForEach with MatchCollection First off, I know this is a duplicate of this question, but I can't get the solution listed there to work for me.  I understand that MatchCollection does not implement the IEnumerable Parallel.ForEach uses, and thus the need for OfType()... any idea what I'm doing wrong?  Here's my setup:
MatchCollection startMatches = Regex.Matches(tempRTB.Text, startPattern);

System.Threading.Tasks.Parallel.ForEach(startMatches.OfType<Match>, m =>
{
    // do stuff with m
});

And here's the compile error I get:
Error   11  The type arguments for method 'System.Threading.Tasks.Parallel.ForEach<TSource>(System.Collections.Generic.IEnumerable<TSource>, System.Action<TSource>)' cannot be inferred from the usage. Try specifying the type arguments explicitly.

A: All you are missing is () (OfType is a static extension method)
System.Threading.Tasks.Parallel.ForEach(startMatches.OfType<Match>(), m =>
        {
            // do stuff with m
        });


text:
Q: How do I enable the cscfg overrides to work with NServiceBus Azure configuration When using NServiceBus the Transport connection string doesn't seem to be fetched from the applicable Cloud configuration first but immediately from the app.config.
Options I've tried:
Using the configuration section (:
cscfg
<ConfigurationSettings>
  <Setting name="AzureServiceBusQueueConfig.ConnectionString" value="Endpoint=sb://xxx.servicebus.windows.net/;SharedAccessKeyName=RootManageSharedAccessKey;SharedAccessKey=yyy" />
</ConfigurationSettings>

app.config
<AzureServiceBusQueueConfig ConnectionString="Endpoint=sb://xxx.servicebus.windows.net/;SharedAccessKeyName=RootManageSharedAccessKey;SharedAccessKey=yyy" />

Using a custom connection string name:
cscfg
<ConfigurationSettings>
  <Setting name="NServiceBus.Transport" value="Endpoint=sb://xxx.servicebus.windows.net/;SharedAccessKeyName=RootManageSharedAccessKey;SharedAccessKey=yyy" />
</ConfigurationSettings>

app.config
<connectionStrings>
    <add name="NServiceBus.Transport" connectionString="Endpoint=sb://xxx.servicebus.windows.net/;SharedAccessKeyName=RootManageSharedAccessKey;SharedAccessKey=yyy"/>
</connectionStrings>

Also tried to override it by using the following line of code, since this issue is still open (https://github.com/Particular/NServiceBus.AzureServiceBus/issues/20):
configuration.UseTransport<AzureServiceBusTransport>().ConnectionString(CloudConfigurationManager.GetSetting("AzureServiceBusQueueConfig.ConnectionString"));

Or tried to set the connection string name manually, which works again using the app.config but doesn't let the cscfg override.
configuration.UseTransport<AzureServiceBusTransport>().ConnectionStringName("NServiceBus.Transport");

A: Did you turn the azure configuration source on? You can do so using following extension method on the bus configuration:
.AzureConfigurationSource()


text:
Q: How to iterate user list, change a variable, and save to database? I'm new to Identity, EF6, and SQL databases. Please bear with me.
The idea is this: For each user in the database, change a user variable, and save that user. However, I must be going about it incorrectly, as I trip an InvalidOperationException (the infamous: Attaching an entity of type 'Models.ApplicationUser' failed because another entity of the same type already has the same primary key value.)
var _db = new ApplicationDbContext();

IQueryable<ApplicationUser> query = _db.Users; // from IdentityDbContext

// search for matching user
List<ApplicationUser> subordinates = query.Where(p => (p.ParentId == userEmployeeId)).ToList();

if (subordinates != null)
{
  foreach (var sub in subordinates)
  {
    sub.Nickname = "Scooby"; // change an example test variable

    IdentityResult result = manager.Update(sub); // EXCEPTION here! Boom.
    if (!result.Succeeded)
    {
      Console.WriteLine("User did not save");
    }
  }
}

Q: What am I doing wrong here? Or, how should I attack this differently?

A: Assuming manager is an instance of the ASP.NET Identity UserManager, the error is because Update() is trying to add the entity to the context when it was already added to the context when it was queried.
There are a couple ways to solve this. One is to update the user directly using EF (note that this bypasses any logic that would've been applied if saved via UserManager)...
foreach (var sub in subordinates)
{
    sub.Nickname = "Scooby"; // change an example test variable
}
_db.SaveChanges();

The other option is to use AsNoTracking() to prevent it from being added to the context during the query. After that, manager.Update(sub) should work...
List<ApplicationUser> subordinates = query.AsNoTracking()
                                       .Where(p => (p.ParentId == userEmployeeId))
                                       .ToList();


text:
Q: Ruby gem Mechanize with jRuby 1.6.0 (Ruby 1.9.2) When I tried to access a web site with SSL using Mechanize, I got the following error.
jruby-1.6.0 :009 > page = mechanize_agent.submit(form)
NoMethodError: undefined method `read_nonblock' for #<OpenSSL::SSL::SSLSocket:0x44cae5b8>

I tried with Mechanize both 2.0.pre.2 and 1.0.0.
jRuby installed is:
jruby 1.6.0 (ruby 1.9.2 patchlevel 136) (2011-03-15 f3b6154) (Java HotSpot(TM) 64-Bit Server VM 1.6.0_24)
I also installed the gem jruby-openssl.
Any help will be greatly appreciated.

A: It's a bug, and there's a monkey patch you can use to get around it. http://jira.codehaus.org/browse/JRUBY-5529
Link to monkey patch at the bottom.


text:
Q: Comma inside quotes Is it correct to have a comma inside the quotes below for this excerpt from a story, or should it be outside?

Bob wanted to see the world and meet other people; he would watch the planes fly past and thought, "Why can't I travel too," but he couldn't afford it, after all, he was only a young boy.

A: There can be no comma - a questionmark is required.
"... he would watch the planes fly past and thought, "Why can't I travel too**?**" but he couldn't afford it[no comma] after all,


text:
Q: How to populate ListView in a Preloaded Database I'm trying to create a listview using a preloaded database, the app is running but the data is not showing. Pls help me. Im using Database Browser for Sqlite. Or can someone give me an example of this?
This is my DataListView.java
package com.example.thetrial;
import java.util.ArrayList;
import android.app.Activity;
import android.app.ListActivity;
import android.content.Context;
import android.database.Cursor;
import android.database.sqlite.SQLiteDatabase;
import android.database.sqlite.SQLiteException;
import android.os.Bundle;
import android.util.Log;
import android.view.LayoutInflater;
import android.view.View;
import android.view.ViewGroup;
import android.widget.ArrayAdapter;
import android.widget.CursorAdapter;
import android.widget.ListView;
import android.widget.TextView;

public class DataListView extends Activity {
private DBHelper dbDBHelper = null;
private Cursor ourCursor = null;
private DBAdapter adapter = null;

@Override
public void onCreate(Bundle savedInstanceState) {
    // TODO Auto-generated method stub
    try{
    super.onCreate(savedInstanceState);
    setContentView(R.layout.main);
    ListView myListView = (ListView)findViewById(R.id.myListView);
dbDBHelper = new DBHelper(this);
dbDBHelper.createDataBase();
dbDBHelper.openDataBase();
ourCursor = dbDBHelper.getCursor();
startManagingCursor(ourCursor);
adapter = new DBAdapter(ourCursor);
myListView.setAdapter(adapter);
}catch (Exception e){

    Log.e("Error", "Error in code: " + e.toString());
    e.printStackTrace();
}
}
class DBAdapter extends CursorAdapter{
    DBAdapter(Cursor c){
        super(DataListView.this,c,0);
    }

    @Override
    public void bindView(View view, Context context, Cursor cursor) {
        // TODO Auto-generated method stub
        DBHolder holder = (DBHolder)view.getTag();
        holder.populateFrom(cursor, dbDBHelper);
    }

    @Override
    public View newView(Context context, Cursor cursor, ViewGroup parent) {
        // TODO Auto-generated method stub
        LayoutInflater inflater = getLayoutInflater();
        View view=inflater.inflate(R.layout.row, parent, false);
        DBHolder holder = new DBHolder(view);
        view.setTag(holder);
        return(view);
    }

}
static class DBHolder {
    private TextView name = null;
    DBHolder (View view){
        name = (TextView)view.findViewById(R.id.text);

    }
    void populateFrom(Cursor c, DBHelper r){
    name.setText(r.getName(c));
    }
    }
}

DBHelper.java
package com.example.thetrial;

import java.io.FileOutputStream;
import java.io.IOException;
import java.io.InputStream;
import java.io.OutputStream;
import java.util.Locale;
import android.content.Context;
import android.database.Cursor;
import android.database.SQLException;
import android.database.sqlite.SQLiteDatabase;
import android.database.sqlite.SQLiteException;
import android.database.sqlite.SQLiteOpenHelper;
import android.database.sqlite.SQLiteQueryBuilder;

public class DBHelper extends SQLiteOpenHelper{

public SQLiteDatabase DB;
private static String DB_Path = "/data/data/com.example.thetrial/databases/";
private static String DB_Name = "trialakoagain.db";
public  static final String TABLE_Name = "linux_comm";
public static final String Column_Id = "_id";
public static final String Column_Comm = "comm";
public static final String Column_Desc = "desc";
private final Context myContext;

public DBHelper(Context context) {
    super(context, DB_Name, null, 1);
    this.myContext = context;
}

 public void createDataBase(){

        boolean dbExist = checkDataBase();
        if(!dbExist){
            this.getReadableDatabase();
            copyDataBase();
        }
 }
        /*
        if(dbExist){
            //do nothing - database already exist
        }else{

            //By calling this method and empty database will be created into the default system path
               //of your application so we are gonna be able to overwrite that database with our database.
            this.getReadableDatabase();

            try {

                copyDataBase();

            } catch (IOException e) {

                throw new Error("Error copying database");

            }
        }

    }*/
 private boolean checkDataBase() {
        // TODO Auto-generated method stub
     SQLiteDatabase checkDB = null;

        try{
            String myPath = DB_Path + DB_Name;
            checkDB = SQLiteDatabase.openDatabase(myPath, null, SQLiteDatabase.OPEN_READWRITE);
            checkDB.setLocale(Locale.getDefault());
            //checkDB.setLockingEnabled(true);
            checkDB.setVersion(1);

        }catch(SQLiteException e){

            //database does't exist yet.

        }

        if(checkDB != null){

            checkDB.close();

        }

        return checkDB != null ? true : false;
    }

private void copyDataBase()  {
InputStream inputStream = null;
OutputStream outStream = null;
String outFileName = DB_Path + DB_Name;
try{
    inputStream = myContext.getAssets().open(DB_Name);
    outStream = new FileOutputStream(outFileName);
    byte[] buffer = new byte[1024];
    int length;
    while ((length = inputStream.read(buffer)) > 0){
        outStream.write(buffer,0,length);
    }
    outStream.flush();
    outStream.close();
    inputStream.close();
}catch (IOException e){
    throw new Error("Problem copying db to resource!");
}

}
public void openDataBase() throws SQLException{

        //Open the database
        String myPath = DB_Path + DB_Name;
        DB = SQLiteDatabase.openDatabase(myPath, null, SQLiteDatabase.OPEN_READWRITE);

    }

    @Override
    public synchronized void close() {

            if(DB != null)
                DB.close();

            super.close();

    }

    @Override
    public void onCreate(SQLiteDatabase db) {

    }

    @Override
    public void onUpgrade(SQLiteDatabase db, int oldVersion, int newVersion) {

    }

        // Add your public helper methods to access and get content from the database.
       // You could return cursors by doing "return myDataBase.query(....)" so it'd be easy
       // to you to create adapters for your views.

    public Cursor getCursor(){
        SQLiteQueryBuilder queryBuilder = new SQLiteQueryBuilder();
        queryBuilder.setTables (TABLE_Name);
        String [] asColumnToReturn = new String [] {Column_Id,Column_Comm,Column_Desc};

        Cursor mCursor = queryBuilder.query(DB, asColumnToReturn, null, null, null, null, null);
        return mCursor;

    }
    public String getName(Cursor c){
        return(c.getString(2));
    }

}

Manifest.xml
<?xml version="1.0" encoding="utf-8"?>
<manifest xmlns:android="http://schemas.android.com/apk/res/android"
package="com.example.thetrial"
android:versionCode="1"
android:versionName="1.0" >

<uses-sdk
    android:minSdkVersion="14"
    android:targetSdkVersion="21" />

<application
    android:allowBackup="true"
    android:icon="@drawable/ic_launcher"
    android:label="@string/app_name"
    android:theme="@style/AppTheme" >
    <activity
        android:name=".DataListView"
        android:label="@string/app_name" >
        <intent-filter>
            <action android:name="android.intent.action.MAIN" />

            <category android:name="android.intent.category.LAUNCHER" />
        </intent-filter>
    </activity>
</application>

I'm not sure if these are correct I just watched a tutorial and it never said what are the needs of main.xml and row.xml
main.xml
<?xml version="1.0" encoding="utf-8"?>
<LinearLayout xmlns:android="http://schemas.android.com/apk/res/android"
android:orientation="vertical"
android:layout_width="fill_parent"
android:layout_height="fill_parent"
>
<ListView
android:id="@+id/myListView"
android:layout_width="match_parent"
android:layout_height="wrap_content" >
</ListView>

row.xml
<?xml version="1.0" encoding="utf-8"?>
<LinearLayout xmlns:android="http://schemas.android.com/apk/res/android"
android:layout_width="match_parent"
android:layout_height="match_parent"
android:orientation="vertical" >

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

A: I think the problem occurred because you forgot to add the items from database to your adapter :
adapter = new DBAdapter(ourCursor);
myListView.setAdapter(adapter);
//add your adapter data here
adapter.notifyDataSetChanged(); //dont forget to refresh your list


text:
Q: Java unicode question This may be a silly question but... Say I have a String like 4e59 which represents a special unicode character. How can I add the \u to the beginning of that character so that it displays correctly? I've tried the simplest solution of:
String str = "4e59";
System.out.println("\\u"+str);

And several other variants, what am I missing?

A: The \u is parsed at compile time, not run time, so just prefixing your string with "\u" isn't going to work.
You can use Integer.parseInt to do this parsing at runtime:
System.out.println((char)Integer.parseInt("4e59", 16));

A: Others have already answered with how to do this, but if you're interested I can explain why prepending "\u" didn't work: the "\uXXXX" sequences are converted to the corresponding unicode character at compile time by javac (by the lexer, which is the first step in compilation, in fact). In your code, the lexer sees a string containing just "\u" and so doesn't touch it.
The \uXXXX encoding will work anywhere, not just inside strings. Both of these lines are identical if you put them in a Java source file:
int i;

\u0069\u006E\u0074 \u0069\u003B

A: You need to convert it to a char:
System.out.println((char) Integer.parseInt("4e59", 16));


text:
Q: Is there a way to find and interact with specific processes in Windows using .NET? I'm trying to find the process responsible for managing calls in Teams.
https://i.stack.imgur.com/05Tub.png
As shown in the printscreen, there are 9 processes inside Teams looking through the Task Manager.
I've seen that it is possible to identify the process responsible for calls looking at the CPU and GPU usage when you call someone.
I wanted to identify this process in a more reliable way using System.Diagnostics, with IDs or something, but I found nothing in the code that could help me with that, as the process ID changes by the time I kill the process.
This is my code:
        List<object> Lista;
        Lista = new List<object>();
        var processes = Process.GetProcesses();
        foreach (var process in processes)

            if (process.ProcessName.ToUpper().Contains("TEAMS"))
            {
                Lista.Add(process.Id);
            }
        }
        var log = Lista;

(It's my first post here, I would appreciate some tips)


text:
Q: Multiple ManyToMany relationships using "mappedBy" with Super class member I am developing an application using Hibernate and am trying to model the following scenario:
I have an Activity Abstract class, defined as follows:
@Entity
@Inheritance(strategy=InheritanceType.SINGLE_TABLE)
@DiscriminatorColumn(name="activityType")
@Table(name = "BF_ACTIVITY")
public abstract class Activity extends PersistableObject {

    @ManyToOne
    @JoinColumn(name = "ASSIGNED_TO")
    protected  Contactable assignedTo;

    @ManyToOne
    @JoinColumn(name = "RAISED_BY")
    protected  Contactable raisedBy;

Note I am using Single Table inheritance (so all implementing objects will use the same table) and have set a DiscriminatorColumn.
Now I have two objects that extend Activity: ToDo and Status:
@Entity
@Table(name = "BF_TODO")
@DiscriminatorValue("Todo")
public class ToDo extends Activity {
...

@Entity
@Table(name = "BF_STATUS")
@DiscriminatorValue("Status")
public class Status extends Activity {
...

Again note that for both implementations i have set a DiscriminatorValue.
Finally, I want to have a Person object, and the person can have a list of Status and a list of ToDo - I also want to capture the bi-directional relationship, so am modelling it using the mappedBy configuration, but in both cases using the "raisedBy" field that exists in the super class "Activity":
public abstract class Person {

    @ManyToMany(mappedBy="raisedBy", targetEntity=Activity.class)
    private List<ToDo> todoItems = new ArrayList<ToDo>();

As i am using mappedBy with the member variable "raisedBy" from the super class I have also specified the targetEntity (otherwise it is not able to find the field in the ToDo object).
The problem is when I try to call getTodoItems() - it is actually just returning all "Activity" objects linked by "raisedBy" to the current person. e.g. it throws a cast exception because it is expecting the list of ToDos but Hibernate is returning Status objects in the list as well.
I was hoping the mappedBy config along with DiscriminatorValue would be enough to make this work - has anyone come across this or resolved it?
Thanks

EDIT
I have just found this post:
Can someone point me in the direction of a good @Where overview and example? could I just update my person as follows to use @Where with the discriminator column?
public abstract class Person {

    @ManyToMany(mappedBy="raisedBy", targetEntity=Activity.class)
    @Where(clause="activityType=Todo")
    private List<ToDo> todoItems = new ArrayList<ToDo>();

A: Add the annotation :
@Where(clause = "activityType= 'Todo'")
But it's a hibernate annotation, not JPA


text:
Q: cargo comandline arguments parse minus float How to parse a minus float in cargo? like
#[test]
fn test1() {
    let args: Vec<String> = env::args().collect();
    println!("{:?}", args);
}

and run it with
cargo test --release test1 -- -1.0 --nocapture --exact
cargo test --release test1 -- '-1.0' --nocapture --exact
cargo test --release test1 -- "-1.0" --nocapture --exact
cargo test --release test1 -- `-1.0` --nocapture --exact
/xxx/test_bin test1 -1.0 --nocapture

It says error: Unrecognized option: '1'
with rustc 1.64.0-nightly (6dba4ed21 2022-07-09)


text:
Q: How to give CornerRadius to UIViewController Object iPhone can't i give the cornerRadius to UIViewController Object.

A: cornerRadius is a property of a CALayer, which is associated with a UIView. A view controller can't have one, but it's view property can have:
#import <QuartzCore/QuartzCore.h>

At the top of your view controller's .m file
In viewDidLoad:
self.view.layer.cornerRadius = 10;

You will probably also want to set the borderWidth and borderColor properties of the layer, if you are looking for a visible rounded rect border, or masksToBounds if you just want to round off the corners.

A: try this:-
CALayer *l = [*yourcontrolobject* layer];
[l setMasksToBounds:YES];
[l setCornerRadius:10.0];

Make sure you import quartzCore framework and #import <QuartzCore/QuartzCore.h> in your view controller.h file


text:
Q: How to show the intersection of a prime ideal and a subring is a prime ideal I am a self-studier. This is a problem (1.5b) from Andrew Baker's excellent notes (freely available for download) on Galois Theory.
$R \subseteq S$ are rings containing $1$. $Q$ is a prime ideal of $S$. Show $Q \cap R$ is a prime ideal of $R$.
I have seen this can be proved knowing that the inverse of a ring homomorphism (where $1$ maps to $1$) of a prime ideal is a prime ideal. And considering $\phi: R \rightarrow S$ as an inclusion map and taking the inverse of $Q$, one can get the desired result.
I was trying to prove this more "directly" and it is here I would appreciate help.
The approach I am taking is to show that if $ab \in Q \cap R$, then WLOG $a \in Q \cap R$. Since $Q$ is prime, $a \in Q$.
I would appreciate help as to how to show $a \in R$. Is it valid to say that since $1 \in R$ then $a1 \in R$?
As always thanks for you help.

A: You are making it harder than it needs to be.  To show $Q \cap R$ is a prime ideal, we need only consider a pair of elements $a,b \in R$ such that $ab \in Q \cap R$.  Then since this also happens in $Q$, we know one of $a$ or $b$ is in $Q$ (and both already are in $R$).  The desired result follows, one of them is in $Q \cap R$ and thus the latter is a prime ideal.


text:
Q: Having a servlet to setup the WebApplication In my web application I have two servlets which act as a controller. One servlet is used to handle web requests and another servlet is used to handle AJAX requests.
//This servlet manages web requests, and forwards to JSP to display data
WebController extends HttpServlet:

// This servlet manages AJAX requests. And returns JSON to user
AJAXController extends HttpServlet: This servlet manages

In my web.xml I have the following mapping defined:
<servlet>
  <servlet-name>WebController</servlet-name>
  <servlet-class>com.frontend.WebController</servlet-class>
  <load-on-startup>1</load-on-startup>
</servlet>

<servlet-mapping>
  <servlet-name>WebController</servlet-name>
  <url-pattern>*.do</url-pattern>
</servlet-mapping>
<servlet>

  <servlet-name>AJAXController</servlet-name>
  <servlet-class>com.AJAXController</servlet-class>
  <load-on-startup>2</load-on-startup>
</servlet>

<servlet-mapping>
  <servlet-name>AJAXController</servlet-name>
  <url-pattern>*.xhr</url-pattern>
</servlet-mapping>

So you can see I load WebController before AJAXController.
In the init() method of webController, I do all the initialization tasks.
loading the database driver
initializing the configuration
and other stuff that I need for my web application

The load-on-startup makes sure that before any AJAX request come to the server, the web app is initialized and I can be sure to make database access.
However, I do not like the idea of initializing web application in one servlet. I am thinking of having a separate servlet called InitServlet and move the code from WebController's init method to InitServlet's init() method
Questions

*

*Is it a good idea? Are there other approaches to solve this problem?

*What should my servlet-mapping look like given that init servlet's sole purpose is to initialize the web application and as such it should not be mapped to any URL

I will send HttpServletResponse.SC_FORBIDDEN in their doPost() and doGet() method. But if possible I want ths servlet not to be mapped to anything.

A: It's a better idea to move your initialize code to ServletContextListener.
When your app starts it will execute contextInitialized(ServletContextEvent sce) and you'll get a chance to init everything.
And this is how you hook it to your web.xml

A: I think it is not necessarily a bad idea. Just define your initialization server to load first in the web.xml. As far as the entry goes, it needs to define the servlet class, of course and the load on startup order.
Put your initialization code in an implemented init method. Leave the doGet doPost methods empty so if they get called nothing happens. The init method will only get called once when the servlet is loaded.
The only issues I see is if this is being run into the context of a clustered set of application servers and you have resources that are truly singleton (like a connection pool), but in that case you can initialize these through application configuration in the application server. They will get intialized when the application starts and before the servlets are loaded.


text:
Q: Erro ao gerar arquivo excel Quando o sistema é executado no servidor ocorre esse erro:
ERRO:
Retrieving the COM class factory for component with CLSID {00024500-0000-0000-C000-000000000046} failed due to the following error: 80070005 Access is denied. (Exception from HRESULT: 0x80070005 (E_ACCESSDENIED)).

Tem outras sistemas no mesmo servidor que não dá erro, esse é o erro gerado:

Na minha maquina funciona perfeitamente, esse é o código que gera o arquivo excel:
protected void TESTE_GerarExcel()
        {

            #region :: GERAR ARQUIVO EXCEL ::

            var excelApp = new Excel.Application();

            excelApp.Workbooks.Add();
            Excel._Worksheet workSheet = (Excel.Worksheet)excelApp.ActiveSheet;
            workSheet.Cells[1, "A"] = "NOME CLIENTE";
            workSheet.Cells[1, "B"] = "DESCRIÇÃO";
            workSheet.Cells[1, "C"] = "QTDE PARCELA";
            workSheet.Cells[1, "D"] = "VALOR PARCELA";
            workSheet.Cells[1, "E"] = "DATA VENCIMENTO";
            workSheet.Cells[1, "F"] = "SITUAÇÃO";
            workSheet.Cells[1, "G"] = "BOLETO ENVIADO";
            var row = 1;

            row++;
            workSheet.Cells[row, "A"] = "IND. FARMACÊUTICA";
            workSheet.Cells[row, "B"] = "ALUGUE DE SALA";
            workSheet.Cells[row, "C"] = "2";
            workSheet.Cells[row, "D"] = "200,10";
            workSheet.Cells[row, "E"] = "30/05/2016";
            workSheet.Cells[row, "F"] = "PENDENTE";
            workSheet.Cells[row, "G"] = "NÃO ENVIADO";

            workSheet.Columns[1].AutoFit();
            workSheet.Columns[2].AutoFit();
            workSheet.Columns[3].AutoFit();
            workSheet.Columns[4].AutoFit();
            workSheet.Columns[5].AutoFit();
            workSheet.Columns[6].AutoFit();
            workSheet.Columns[7].AutoFit();

            workSheet.Range["A1", "G1"].AutoFormat(Excel.XlRangeAutoFormat.xlRangeAutoFormatSimple);

            excelApp.Columns.AutoFit();

            string nome = "Contas_a_Receber_" + System.DateTime.Now.ToString().Replace(" ", "_").Replace("/", "_").Replace(":", "_");

            var path = Path.Combine(Server.MapPath("~/Content/Uploads"), nome);

            excelApp.ActiveWorkbook.SaveCopyAs(path + ".xlsx");

            #endregion

        }

A: Evite usar a Microsoft.Office.Interop.Excel em projetos ASP.NET MVC. Ela depende de registro como biblioteca COM.
Em seu lugar, use a biblioteca EPPlus. Ela não precisa de registro COM e é bastante semelhante de usar.
Veja aqui exemplos de uso.


text:
Q: Parsing integers with JsonCpp I am using JsonCpp v1.6.5 to parse a JSON file that contains the following:
{ "some-property" : 32 }

After parsing the type of the value is intValue rather than uintValue.
How does the parser interpret an integer as unsigned?

A: Everything below 2**31 is considered int, rather than unsigned int.


text:
Q: How to Create an CommonsMultipartFile instance I try to create CommonsMultipartFile instance by this way,but a java.lang.NullPointerException happened.
 DiskFileItemFactory factory = new DiskFileItemFactory(1024*1024,null);
 FileItem fileitem = factory.createItem("file", "application/vnd.ms-excel;charset=utf-8", true, "d:\\a.xls");//Method threw 'java.lang.NullPointerException' exception. Cannot evaluate org.apache.commons.fileupload.disk.DiskFileItem.toString()
    CommonsMultipartFile commonFile=new CommonsMultipartFile(fileitem);

A: You can't pass null as the second parameter to the constructor.
Pass some sort of temp folder like so:
DiskFileItemFactory factory = new DiskFileItemFactory(1024*1024, Files.createTempDirectory("mytemp").toFile());


text:
Q: find the paragraph and url in text using beautfulsoup and put in the dataframe I want to extract the paragraph in this XML file (between   tags)
'
jo\\section{$430 \\quad$ Part $4 \\quad$ The First Inequality, from Physical Causes}
\n
center $A$, with radius $A M$, let the arc $M N$ be described, intersecting $P V$ at $O$, and $P B$ at $N$. So, by analogy with the above, just as we are taking I in place of F, let us now take $N$ for $O$, and let us consider that just as $A N$ is the correct distance in length, it is also correct in position. Now the points $I, N$, and the like do indeed make the planet\'s path puff-cheeked. For the arcs $G D$ and $Q P$ are equal. And $B D, B P$, projected from a common center, intersect the lunule cut off. But DI and PN, the breadths of the lunule extended towards the center are unequal. And DI is smaller breadihs of the lunule extended towaras the center, are unequal. And DI is smaller, and $P N$ greater. For since $E D$ and $M P$ are equal, and $E D I, M P N$ are right, while EI is a greater circle, since its radius $A E$ is greater, and $M N$ is a smaller circle, since its radius AM is smaller, therefore, PN will definitely be greater, and DI smaller. Therefore the lunule cut off is narrower above at $D$ and broader belowe at $P$. In Therefore, the lunule cut off is narrower above, at $D$, and broader below, at $P$. In the ellipse, in contrast, this iunule is of equal breadth at points equally removed from the apsides $G$ and $Q .$ So it is clear that the path is puff-cheeked, so it is not an ellipse. And since the ellipse gives the correct equations, this puff-cheeked path should by rights give incorrect ones.
\n

and put them in one column of dataframe, in the second column I want to collect the URL that existed in the text
here is my file  which I read it so
with open('../AN_markdown/kapitel_{0}.mmd'.format(ch), 'r',encoding='utf-8') as fin:
    rendered = mistletoe.markdown(fin)

I used beautifulsoup but still can not add link, here is my code
from bs4 import BeautifulSoup
text = BeautifulSoup(rendered,'html.parser')
para=[]
for p in text.find_all("p"):
     para.append(p)

df = pd.DataFrame({"Paragraphs":para})

it only find the paragraph, I do not know how to extract the link and add them as column behind the paragraph
thank you in advance

A: Try the following approach. It spots the 3
 tags and extracts the text, the last one has no text but does have the image:
import pandas as pd
from bs4 import BeautifulSoup

data = []

xml = """
jo\\section{$430 \\quad$ Part $4 \\quad$ The First Inequality, from Physical Causes}
\n
center $A$, with radius $A M$, let the arc $M N$ be described, intersecting $P V$ at $O$, and $P B$ at $N$. So, by analogy with the above, just as we are taking I in place of F, let us now take $N$ for $O$, and let us consider that just as $A N$ is the correct distance in length, it is also correct in position. Now the points $I, N$, and the like do indeed make the planet\'s path puff-cheeked. For the arcs $G D$ and $Q P$ are equal. And $B D, B P$, projected from a common center, intersect the lunule cut off. But DI and PN, the breadths of the lunule extended towards the center are unequal. And DI is smaller breadihs of the lunule extended towaras the center, are unequal. And DI is smaller, and $P N$ greater. For since $E D$ and $M P$ are equal, and $E D I, M P N$ are right, while EI is a greater circle, since its radius $A E$ is greater, and $M N$ is a smaller circle, since its radius AM is smaller, therefore, PN will definitely be greater, and DI smaller. Therefore the lunule cut off is narrower above at $D$ and broader belowe at $P$. In Therefore, the lunule cut off is narrower above, at $D$, and broader below, at $P$. In the ellipse, in contrast, this iunule is of equal breadth at points equally removed from the apsides $G$ and $Q .$ So it is clear that the path is puff-cheeked, so it is not an ellipse. And since the ellipse gives the correct equations, this puff-cheeked path should by rights give incorrect ones.
\n
"""
soup = BeautifulSoup(xml, 'html.parser')

for p in soup.find_all('p'):
    text = p.get_text(strip=True)

    if p.find('img'):
        url = p.img['src']
    else:
        url = ''

    data.append([text, url])

df = pd.DataFrame(data, columns=['Paragraphs', 'URLs'])
print(df)

Giving you a dataframe as:
                                          Paragraphs                                               URLs
0  jo\section{$430 \quad$ Part $4 \quad$ The Firs...
1  center $A$, with radius $A M$, let the arc $M ...
2                                                     https://cdn.mathpix.com/cropped/2022_01_11_c20...

A: It turns out I can do it using "BeautifulSoup" and "mistletoe", here is my code:
from pathlib import Path
import pandas as pd
from bs4 import BeautifulSoup
import mistletoe
with open(my_file, 'r',encoding='utf-8') as fin:
    rendered = mistletoe.markdown(fin)
XML = BeautifulSoup(rendered,'html.parser')
para=XML.find_all("p")
df = pd.DataFrame({"Paragraphs":para})
df = df.rename(columns={"0":'Paragraph'})

def urlFinder(text):
    links=[]
    for link in text.find_all('img'):
        #print(link.get('src'))
        links.append(link.get('src'))
    return(links)

df['Links'] = df['Paragraphs'].apply(lambda x: urlFinder(x))

however, the solution of @Martin Evans is also perfect!
here is my result:


text:
Q: Unable to create a new ASP.NET Core project I have installed Visual Studio 2019.
I am trying to create ASP.NET Core Web Application with Razor page.
After selecting the 'ASP.NET Core Web Application' template, providing name for the application and then selecting 'Web Application' from the list as shown below:
selecting Web Application
After I click Create, the following 'Creating Project ' comes up for around 10 minutes before Visual Studio Not Responding message comes and I have to close the application.
Creating Project

A: Try to run a Repair on on Visual Studio 2019 installation. That will take an hour or so and than retry. If it doesn't work than uninstall and than re-install again.


text:
Q: Ghost script changing dimensions of the input pdf I am using gs 9.20 and trying to generate eps file using below command from a pdf file.
gs -q -dNOCACHE -dNOPAUSE -dBATCH -dSAFER -sDEVICE=eps2write -sOutputFile=tempEpsFile.eps tempCmykPdfFile.pdf

Now the problem is that eps file is getting generated successfully but the dimension of the generated eps file different from the pdf file.

The area outside the content area (gray color) is white space.
The PDF consist of standard Area, while the eps file generated is contains only the content area.
Attaching the pdf and eps image screenshot
PDF: here dimension is in points (Screen shot from Adobe Illustrator)

EPS:  here dimension is in points (Screen shot from Adobe Illustrator)

I am not sure why its happening or how to resolve it.
Below is the output of pdfinfo -box command on the pdf file.
  $pdfinfo -box tempCmykPdfFile.pdf
   Producer:       GPL Ghostscript 9.20
   CreationDate:   Tue Mar  7 09:48:56 2017
   ModDate:        Tue Mar  7 09:48:56 2017
   Tagged:         no
   Pages:          1
   Encrypted:      no
   Page size:      212.6 x 113.39 pts
   MediaBox:           0.00     0.00   212.60   113.39
   CropBox:            0.00     0.00   212.60   113.39
   BleedBox:           0.00     0.00   212.60   113.39
   TrimBox:            0.00     0.00   212.60   113.39
   ArtBox:             0.00     0.00   212.60   113.39
   File size:      20886 bytes
   Optimized:      no
   PDF version:    1.5

Also, output of gs -sDevice=bbox
   %%BoundingBox: 14 48 199 100

To summarize the problem: pdf has the page size of  212.6 x 113.39 pts while for the generated eps Page size is : 576x 792 pts. If we look from the first image then the Sandard Area is getting changed while the Content Area remain same

A: I would need to see the input file at the very least to be able to comment, but the most likely explanation is that the original PDF file has both a MediaBox and a CropBox. Ghostscript defaults to using the MediaBox (and that's what will get emitted in the EPS) while Acrobat defaults to using the CropBox.
Put the input file somewhere, and post the URL here and I can take a look at it.
Note; EPS files are intended for inclusion in other documents, thus the BoundingBox of an EPS file is defined as the smallest rectangle which includes all the marks made by the EPS program. So, when generating an EPS file, its perfectly correct for eps2write to create an EPS where the BoundingBox only includes the area of the marks, and does not include any white space. If you want white space around it, you should add that in the enclosing document.


text:
Q: How to automatically generate new input fields by filling previous? To be as simple as I can:
I have condition where I do not know where I'm going to have 3 or more input elements (type of "text") and I'm looking for solution which will generate 4th input type text when I start to fill 3th input field with characters, and so on.
Something similar Adminer have for adding new columns when creating/altering database:

here you click on + to add new input and x to remove it. This would also be good to me.
How to achieve that/what library should I use?

A: It's difficult to tell what you're trying to get without a code sample, but do you want something like this?
HTML:
<input type='text' />

JS:
$('input').on( 'change', function() {
    $(this).after( '<input type="text" />' );
    $('input').off( 'change' );
});

jsFiddle is down and jsBin can't handle the extra load, but here's a demo.

A: You can clone full row, and append it to parent table. Have a look at jQuery clone() and append().
Sample code:
$('#yourtableid').on('click', '.add', function() {

   // clone first row
   var row = $('#yourtableid tbody tr:first').clone();

   // reset inputs
   row.find('input[type!=button]').val('');

   // append cloned row
   $('#yourtableid tbody').append(row);

});

Live DEMO.
EDIT: To add row automatically when filled some text in last row, you can go with:
$('#tbl').on('change', 'input', function() {

  // check that some input was entered and that it is in the last tr
  if($(this).val() != '' &&
     $(this).closest('tr').is(':last-child')) {
    addRow();
  }
});


text:
Q: How to return to a hyperlink(the CTRL+CLICK link) on word for mac with a keyboard shortcut? The alternative for this on word for windows is ALT + LeftArrow.I would like to know what the mac equivalent is?
I found an answer here https://superuser.com/a/746208/1097561


text:
Q: Python Post request fails with 400/ConnectionResetError(10054) if params are lengthy I am relatively three months new to building tools with requests. In my institution, we have webapp and it calls 'POST' method to trigger an export query. I got the code right and it was working fine, except if the queried items are huge it fails throwing 400 Bad request or error out without completing the request as "requests.exceptions.ConnectionError: ('Connection aborted.', ConnectionResetError(10054, 'An existing connection was forcibly closed by the remote host', None, 10054, None))"
s = requests.Session()
var_list = ["var1", "var2", "var3", "var4"]
params_str = '%0D%0A'.join(var_list)
r = s.post(f'https://internaltools.org/export?variableids={params_str}')
print(r.status_code())

it works if len(var_list) =<300, fails if len(var_list) > 300
Is it the sever side or am i doing something wrong? Please help me out!


text:
Q: How to construct AST of Hy lang snippets I have several Hy Lang code snippets that I use in my python project.
I was wondering if there is a relatively easy way for me to get an Abstract Syntax Tree of the Hy code with some python library or maybe even the Hy compiler itself (I've looked into the compiler code but I'm having a hard time understanding it).
I know that Hy transforms all the Hy lang code to a python AST before making that bytecode and looking at the compiler  I do not see a function that would help me convert the Hy code to a Hy object that I can feed to HyASTCompiler for example.
I'm hoping I can leverage something already built and not have to use something like ANTLER and write my own grammar.
Thanks!
Using Hy Version 0.12 and python3

A: I'm not clear if you want Python ast objects or just Hy code as data. The latter is provided by read and read-str. For the former, no public interface is currently provided, but take a look at the docstring of the internal function hy.compiler.hy_compile.
Hy 0.12 is ancient, though, so you'll probably need to upgrade.


text:
Q: Select rows based on comparison with other rows in same view I have a table which x, y points and need to find points where there are less than three other rows in the table with either a higher x value or higher y value.
  x  |  y
-----+-----
  85 | 996
 109 | 989
 116 | 987
 164 | 983

         create or replace function sk(tableName text)
             returns integer
         as $$
         declare
            count integer;
            r record;

         begin
            count :=3;
            for r in execute 'select * from TABLE'
            if
                  loop
                  count := count - 1;

                  end loop;
                  return count;

         end
         $$ language plpgsql;

The expected result is a new view which has only those points which have less than 3 with greater x or y.

A: Why do this in a function?  You can do this with a single query, such as:
select t.x, t.y, count(t2.x) as numBiggerXY
from t left join
     t2
     on t2.x > t.x or t2.y > t.y
group by t.x, t.y;

You can turn this into a flag:
select t.x, t.y, (count(t2.x) < 3) as biggerFlag
from t left join
     t2
     on t2.x > t.x or t2.y > t.y
group by t.x, t.y;

A: Assuming a PK column id, so this is the test case:
CREATE TABLE tbl (id serial PRIMARY KEY, x int, y int);
INSERT INTO tbl(x,y) VALUES
  ( 85, 996)
, (109, 989)
, (116, 987)
, (164, 983);

If you have no PK, create one. Else you have to use other techniques in the query to distinguish possible duplicates on (x,y) - which have not been ruled out.
SELECT t.*, count(t2.x) AS ct_greater
FROM        tbl t
LEFT   JOIN tbl t2 ON t2.x > t.x OR t2.y > t.y
GROUP  BY t.id
HAVING count(t2.x) < 3;

Empty result for the test case because there are always 3 other rows with bigger x or bigger y.


text:
Q: Update file references while looping I'm trying to loop through files in a folder and take data for that files using references, im using below code , but still getting Update Values window popped up at every file in which I have to manually select path of files. How to do this reference automatically
[Salary.Value is name of a cell in files in that folder]
Dim myfolder As String
Dim myfile As String
Dim wbk As Workbook

With Application.FileDialog(msoFileDialogFolderPicker)
    .Title = "please select a folder"
    .Show
    .AllowMultiSelect = False

myfolder = .SelectedItems(1) & "\"
End With
myfile = Dir(myfolder)

Do While myfile <> ""
Set wbk = Workbooks.Open(Filename:=myfolder & myfile)

' the next line is the one in question
Range("I6").FormulaR1C1 = "='myfile'!Salary.value"

myfile = Dir
Loop
End Sub

A browse window named update values is popping up

A: 'MyFile' is a variable name. But how you use it, it is considered as name of the workbook.
Try
Range("I6").FormulaR1C1 = "='" + MyFile + "'!Salary.value"

instead


text:
Q: Problem Updating List Item using Ecmascript I'm trying to update an item with a specific ID in my sharepoint list. Everything works until it gets to the set_item or targetListItem.update() part. Can someone tell me where I'm going wrong please? I'm using the alerts to gauge where it is not working. I'm still really new to ecmascript and the COM. Thanks in advance!
<script>

var itemId = 1;
var PacketNum;
var targetListItem;

function OnLoadList() {
  // Connect to list by Title
   var clientContext = new SP.ClientContext();
   var targetList = clientContext.get_web().get_lists().getByTitle('Exchange of Notice Packet Number Creator');
   targetListItem = targetList.getItemById(itemId);
   clientContext.load(targetListItem, 'Packet');
   clientContext.executeQueryAsync(Function.createDelegate(this, this.IncrementPacket), Function.createDelegate(this, this.onQueryFailed));
}

function IncrementPacket() {
    PacketNum = targetListItem.get_item('Packet');
    alert('Retrieved Item Value is: ' + PacketNum);
    PacketNum = PacketNum + 1;
    targetListItem.set_item('Packet', PacketNum);
    targetListItem.update();
    alert('New Item Value is: ' + PacketNum);
    clientContext.executeQueryAsync(Function.createDelegate(this, this.onQuerySucceeded), Function.createDelegate(this, this.onQueryFailed));
}

function onQuerySucceeded() {
     alert('Success!');
}

function onQueryFailed(sender, args) {
   alert('Request failed. \nError: ' + args.get_message() + '\nStackTrace: ' + args.get_stackTrace());
}

</script>

A: The error occurs since clientContext is declared as a local variable in function OnLoadList and apparently it is not accessible in IncrementPacket callback function.
"Quick" fix:
In function IncrementPacket replace the line:
clientContext.executeQueryAsync(Function.createDelegate(this, this.onQuerySucceeded), Function.createDelegate(this, this.onQueryFailed));

with:
var ctx = targetListItem.get_context(); //get client context
ctx.executeQueryAsync(Function.createDelegate(this, this.onQuerySucceeded), Function.createDelegate(this, this.onQueryFailed));

Some recommendations
Avoid global variables
Wrap your code in a scoping function and use variables local to that scoping function, and make your other functions closures within it
(function() { // Begin scoping function
    var clientContext; // Global to your code, invisible outside the scoping function
    function loadListItems(listTitle) {
        // ...
    }
})();

Usage of Function.createDelegate
In most cases, there is no need to wrap handlers using Function.createDelegate, instead you could write:
ctx.executeQueryAsync(succeeded,failed);

or
ctx.executeQueryAsync(function(){
    //...
  },
  function(sender,args){
    //Error handling goes here
  }
);


text:
Q: Traverse a list starting from ends and towards the centre Suppose I have a list like this:
[4, 5, 7, 2, 3, 1, 9]
I want the traversal for it to be like this:
4, 9, 5, 1, 7, 3, 2
Can someone share a solution for this? The solution can be language agnostic - even pseudocode is fine.
One solution I have in mind is to make a doubly ended queue and dequeue elements from alternate ends. But the problem is I want to traverse this list multiple times and dequeuing will remove those elements for future use. Is there any other solution that can avoid me from making a copy of the queue each time before traversing it in my desired order?

A: How about:
i = 0;
j = arr.size() - 1;

while(i < j){
    print(arr[i++]);
    print(arr[j--]);
}
// center still needs to be printed
if(i == j){
    print(arr[i]);
}


text:
Q: Sort a List based on a Pre-Sorted List How can I sort a list based on a pre-sorted list.
I have a list which is already sorted. Say, my sorted list is
{"Junior Developer", "Developer", "Senior Developer", "Project Lead"}

Now, I want to sort any subset of the above list in the same order as the above list. That is, if I have as input
{"Developer", "Junior Developer"}, I want the output as {"Junior Developer", "Developer"}
If the input is {"Project Lead", "Junior Developer", "Developer"}, I want the output as
{"Junior Developer", "Developer", "Project Lead"}.

How can I achieve the same?

A: If there are no duplicates in either of the two lists then you can simply use Intersect, which will preserve the order:
var allRoles = new[] {"Junior Developer", "Developer",
                      "Senior Developer", "Project Lead"};
var roles = new[] {"Developer", "Junior Developer"};
var sortedRoles = allRoles.Intersect(roles);

That would probably be more efficient than sorting by IndexOf but you're not likely to notice much difference unless the lists are very long.

A: The simplest way would be to use LINQ's .OrderBy extension method, along with the IndexOf method (or equivalent) of your pre-sorted collection. The idea here is to sort using a different value as the "sort key" (this is quite useful, since often we'll want to sort objects based on one of their properties).
var sorted = listToSort.OrderBy(s => listPreSorted.IndexOf(s)).ToList();

And here's an example with arrays: http://ideone.com/7oshhZ

Note that if your lists are very large, this will likely be slow, since each item in your target list has to be sequentially looked up in your pre-sorted collection (O(N * M), where N is the length of the target list, and M is the length of the pre-sorted list).
To overcome this limitation, you could generate a lookup mapping the items of your pre-sorted list to their indices, then use this lookup in your .OrderBy (this would have a runtime of O(N + M), and you could re-use the lookup if needed):
var preSortedLookup =
        listPreSorted.Select((v, i) => new { Key = v, Value = i })
                     .ToDictionary(kvp => kvp.Key, kvp => kvp.Value);

var sorted = listToSort.OrderBy(s => preSortedLookup[s]).ToList();

A: Say you have a sorted list, listA, and the other list you would have is listB.
every time you read from listB, check if the element is in listA, and based upon that order your list.

A: if you get big load , try a dictionary?
1,
dictionary<string,int>

use this dictionary to store string and index
2,
generate a list<string> result set length as your number of strings with Dummy data
3
then locate the proper index number
write the string into  result by index


text:
Q: Element is not clickable at point because another element  obscures it I solved this issue with the following code, I didn't find a solution in other posts so I tried to make myself and worked just fine. I don't now if it's a good code because I'm new in Python and programming but it worked.
As I wanted to select the element using visible text (not by value or option number), I used the following code, which consist in finding the element by Xpath [contains(text(), 'text')] and then changing the html. Maybe it's useful for another one.
self.driver.execute_script(
    "arguments[0].selected=true",
    self.driver.find_element_by_xpath(
        '//*[contains(text(), "%s" )]' % 'your_visible_text'
    ),
)

A: this issue usually occurs in chrome browser as chrome uses point location. this happens when element is loaded in DOM but postion not fixed on UI. There can be certains solutions you could use to fix this:

*

*Wait:
Use of WebDriverwait and Expected Conditions classes.
Eg:
visiblityOfElementLocated(By locator)
or
visibilityOf(WebElement element)
we are waiting for element to be present and visible before performing action

*try to maximise the browser window before selecting dropdown
driver .manage().window().maximize();
Hope this help. Code is using Java selenium please use its corresponding Python code.


text:
Q: Why are scala Vals not lazy by default I have noticed that I almost exclusively use lazy val assignments as they often avoid unnecessary computations, and I can't see that many situations where one would not want to do so (dependency on mutable variables being a notable exceptions of course).
It would seem to me that this is one of the great advantages of functional programming and one should encourage its use whenever possible and, if I understood correctly, Haskell does exactly this by default.
So why are Scala values not lazy by default? Is it solely to avoid issues relating to mutable variables?

A: Scala is a strict language. Laziness is not only about vals, it's about an evaluation strategy. Should arguments to a function be evaluated before calling the function (what if they are not used?)? In Scala (like most other languages) they are. This strategy carries over to other contexts, including vals and vars.
It would be awkward to break this rule for vals, but laziness can be useful and provided as an opt-in.

A: The big difference here between Scala and Haskell is that Scala allows side-effects whereas Haskell does not.
Laziness results in all sorts of problems in a language which allows side-effects at arbitrary points in the program, as the order in which the side-effects take place becomes non-deterministic.
Nearly transparent Java interoperability plays a large role in the design of Scala, and Java libraries are typically full of side-effects.

A: As you noted, dependency on mutable variables is incompatible incompatible  with lazy evaluations.
Note, that scala is JVM language and Scala programs often use Java libraries, wich are not functional at all. Laziness by default will cause a lot of problems with Java libraries.


text:
Q: How can I cause a setter method to encrypt data before setting it in ActiveRecord? I'd like to implement a Rails User model that has a DB column called password. I want to make it so that when I call...
user_instance.password = 'cleartext'

the method hashes the cleartext before setting it on the instance like so:
Digest::SHA1.hexdigest(cleartext)

I've tried using a callback, but the problem is that is hashes the pw every time the user is saved, even if the pw isn't updated. So it gets hashed and rehashed over and over.
I tried redefining the password= method...
alias password= old_password=
def password=(cleartext)
  old_password=(Digest::SHA1.hexdigest(cleartext))
end

but got an error saying password= does not exist.

A: FYI, you may want to check out restful_authentication plugin as it will do this for you. Why roll your own?
The way acts_as_authenticated does it:

*

*Database/model has a column called "encrypted_password"

*Create a virtual attribute called password

*Password isn't populated on a find(..) so if the password is blank, don't encrypt

*If the password is nonblank, that means the user entered one, so go ahead and encrypt and stuff in encrypted_password

Code snip (random copy-paste from my user class, so don't blindly paste this in):
require 'digest/sha1'
class User < ActiveRecord::Base

  # stuff

  # callback
  before_save   :encrypt_password
  attr_accessor :password

  # methods
    def encrypt_password
      return if password.blank?
      salt = Digest::SHA1.hexdigest("--#{Time.now.to_s}--#{login}--") if new_record?
      crypted_password = Digest::SHA1.hexdigest("--#{salt}--#{self.password}--")
    end

A: In response to Ethan's comment, what is a virtual attribute, a virtual attribute is one that is not in the database, like Matt's attr_accessor :password, this way you can accept that input from the user, but no necessarily store it in that form, in this instance we want to be able to accept a clear text password, but we want to store it encrypted. To do this we have a virtual attribute :password, and in the database we store it as encrypted_password.

A: Well, you could override the setter:
def password=(value)
  self[:password] = Digest::SHA1.hexdigest(value)
end

And this would always encrypt the value. You don't need a before_save or an attr_accessor.

A: Note that it might be a good idea to choose a random n-bit value per user (upon creation of that user) and prepend that to the password when you hash it.
The reason being: if anyone gets a hold of your database, not only can't they immediately see the users' password, they also can't see if two users have identical passwords (important if one of those users grabs your database) and a certain class of hash-cracking attacks (rainbow tables) becomes harder.