text:
Q: Why is $(x- x_{0})^n$ zero around $x_{0}$ on graph? We where tought that the Taylor power serie centred at the point $x_{0}$ is given by:
$\Sigma \frac{ f^{n}(x_{0})}{n!}(x- x_{0})^n$
Where the $\frac{ f^{n}(x_{0})}{n!}$ are the coefficient of the power serie. Now this is one of the most beautiful matematical tool i ever learned about since it can approximate most functions around the desired point $x_{0}$.
Now if i only consider the terme $(x- x_{0})^n $ we could expand it
$(x- x_{0})^n=(x- x_{0})(x- x_{0})(x- x_{0})...(x- x_{0})$. n times
This means that $x_{0}$ is a root of multiplicity n to this polynomial. Naively i would think that this polynomial would have to cross the the x axis at the point $x_{0}$ n times but how ? So i graphed it for $x_{0}=2$ and different values of n to get this result. Graph of $(x-2)^{n}$ for different value of n
After looking at these images i see that for even n the fonction seems to be zero on an interval close to 2, this interval reach a limit at 2-1 and 2+1 as n grows. the same is true for odd numers also, the only difference is that the fonction becomes negative after passing by zero. Why is the function zero around 2, or more generaly around $x_{0}$ ?

A: It becomes flatter and flatter as n increases. However if you zoom in, you will see it is not zero except at $x_0$.

A: Hint:
You don't need the Taylor series. Simply notes that if $|x-x_0|<1$ than $(x-x_0)^n \to 0$ for $n\to +\infty$,
(this means that $|x-x_0|^n$ becomes smaller as $n$ increase).

A: First, we can take $x_0$ to be zero without loss of generality because this is just a translation of the graph. Second because $x^n$ is either even or odd, we are free to only consider positive $x.$ What happens on the negative x axis is just a reflection of what happens on the positive axis, as I'm sure you can see on your graphs.
So consider a positive number $x.$ If $x<1$ then $x>x^2>x^3,$ etc since at each step we are multiplying by a number less than one. For $x>1,$ it is just the opposite and taking higher and higher powers increases the value. So if $n$ is very large, the values $x^n$ for the points $x<1$ will be pushed close to zero, unless they are very close to one. As others have commented they won't be zero, but just close to it. So in the limit where $n$ is large you will see a function that is very close to zero for $x<1$ and then jumps suddenly to a very large value for $x>1.$ The jump becomes very fast but still maintains continuity, passing through the point $(1,1)$ on its way up.


text:
Q: Fatal error: Uncaught Error: Call to a member function fetch() using SQLite I have a php project using SQLite as the database. I have a class called SQLiteConnection
namespace App;

/**
 * SQLite connection
 */
class SQLiteConnection {
    /**
     * PDO instance
     * @var type
     */
    private $pdo;

    /**
     * return in instance of the PDO object that connects to the SQLite database
     * @return \PDO
     */
    public function connect() {
        if ($this->pdo == null) {
            $this->pdo = new \PDO("sqlite:" . Config::PATH_TO_SQLITE_FILE);
        }
        return $this->pdo;
    }
}

when I make a call to $stmt->fetch() in the code below, I get this error:
Fatal error: Uncaught Error: Call to a member function fetch() on boolean in...
use App\SQLiteConnection;
$pdo = (new SQLiteConnection())->connect();
if (!$pdo)
{
  die("Execute query error, because: ". print_r($this->pdo->errorInfo(),true) );
}
else
{
$stmt = $pdo->query('select id, fullname from employees order by fullname');
$employees = [];
while ($row = $stmt->fetch(\PDO::FETCH_ASSOC)) {
    $employees[] = [
        'id' => $row['id'],
        'fullname' => $row['fullname']
    ];
}

I have not worked with pdo much and so I am not sure what to look for. I have read some other posts about the pdo object being boolean because a connection was not made or a table was missing. My query table is there and I am not sure about the connection, but my code to catch a false pdo value does not run.
Thank you.

redpajama_set_name: RedPajamaStackExchange


text:
Q: Unable to launch the uiautomatorviewer.bat I'm facing the below issue while launching the uiautomatorviewer.bat.
In my laptop I have both 32 bit and 64 bit JVMs. But I have setting to use only 64 bit JVM. Still I'm facing this issue.
Could you please help on the same.


text:
Q: Restoring Ubuntu on another device I have installed Ubuntu on a Dell PC. Made an image of it with our imaging software.
When I restored the image on another pc. There is only a white cursor blinking, GRUB does not come up.
Is there something like SYSPREP that makes the system ready and shuts it down to make a system independent image?

A: I have found the solution.
Linux uses system dependent UUID's on the disks and in Grub.
This is why my second pc does not boot after the restore.
Step1: Install all needed extra applications like CLAMAV / CLAMTK / LibreOffice / ... on a clean Ubuntu
Step2: Use remastersys to create a backup of your system that can be restored on any kind of system.
wget -O - http://www.remastersys.com/ubuntu/remastersys.gpg.key | sudo apt-key add -
deb http://www.remastersys.com/ubuntu precise main
apt-get update
apt-get install remastersys
apt-get install remastersys-gui

Step3: Start remastersys and select backup. This creates a live boot cd which is saved in ~/custom.iso
Step4: Install UNetbootin to create a bootable USB stick with this custom image.
Step5: Install a new system with the new USB stick.
Now you have a system independent USB imaging restore stick.

Another way is to use FOG.
FOG is a Linux-based, free and open source computer imaging solution for Windows XP, Vista and 7 that ties together a few open-source tools with a php-based web interface. FOG doesn't use any boot disks, or CDs; everything is done via TFTP and PXE. Also with fog many drivers are built into the kernel, so you don't really need to worry about drivers (unless there isn't a linux kernel driver for it).
You can just create an image of an Ubuntu system and restore it on any other device.
No need to wory about UUID's this is all handled by FOG.


text:
Q: Remove Sku Column from Transactional Email I am trying to remove sku column from New order mail template.
I tried this. But there were still no changes in mail. I made changes in both base theme as well as in rwd theme which is by current theme. Any Ideas?
I have my cache disabled.
I did the same changes in rwd too.But no changes in my emails.

A: Check whether a custom e-mail template is configured in System > Configuration > SALES > Sales Emails > Order > New Order Confirmation Template.
If the value is different from New Order (Default Template from Local) it means that Magento is using a custom template defined in System > Transactional Emails and it may be the root cause of your issue.
Hope it helps.

A: Follow bellow steps:
Step : 1 Open file at location \app\design\frontend\rwd\default\template\email\order\items\order\default.phtml
Find bellow code in above file

<?php echo $this->__('SKU'); ?>: <?php echo $this->escapeHtml($this->getSku($_item)) ?>

Now comment above code live this
<?php /*?>
<?php echo $this->__('SKU'); ?>: <?php echo $this->escapeHtml($this->getSku($_item)) ?>
<?php */?>


text:
Q: ListActivity or Normal Activity I am developing a tic tac toe game in android (mentioned here and here). There are 3 activities, one each for Bluetooth device discovery, rock/paper/scissor, and the actual game. I have a base class that extends Activity and contains some common static resources. Each of the three activities I need extend this base class.
Now the problem is I need a ListView for the bluetooth activity. The other two activities don't need this. As far as I understand, I can either make the base class extend ListActivity and have an empty list element in the layouts for rock/paper/scissor and game. Or I can implement the ListView manually inside bluetooth activity only. Which of these approaches should I take, or is there some other solution altogether?


text:
Q: Logical vector across many columns I am trying to run a logical or statement across many columns in data.table but I am having trouble coming up with the code. My columns have a pattern like the one shown in the table below. I could use a regular logical vector if needed, but I was wondering if I could figure out a way to iterate across a1, a2, a3, etc. as my actual dataset has many "a" type columns.
Thanks in advance.
library(data.table)
x <- data.table(a1 = c(1, 4, 5, 6), a2 = c(2, 4, 1, 10), z = c(9, 10, 12, 12))

# this works but does not work for lots of a1, a2, a3 colnames
# because code is too long and unwieldy
x[a1 == 1 | a2 == 1 , b:= 1]

# this is broken and returns the following error
x[colnames(x)[grep("a", names(x))] == 1, b := 1]

Error in `[.data.table`(x, colnames(x)[grep("a", names(x))] == 1, `:=`(b,  :
  i evaluates to a logical vector length 2 but there are 4 rows. Recycling of logical i is no longer allowed as it hides more bugs than is worth the rare convenience. Explicitly use rep(...,length=.N) if you really need to recycle.

Output looks like below:
   a1 a2  z  b
1:  1  2  9  1
2:  4  4 10 NA
3:  5  1 12  1
4:  6 10 12 NA

A: Try using a mask:
x$b <- 0
x[rowSums(ifelse(x[, list(a1, a2)] == 1, 1, 0)) > 0, b := 1]

Now imagine you have 100 a columns and they are the first 100 columns in your data table. Then you can select the columns using:
x[rowSums(ifelse(x[, c(1:100)] == 1, 1, 0) > 0, b := 1]

ifelse(x[, list(a1, a2)] == 1, 1, 0) returns a data table that only has the values 1 where there is a 1 in the a columns. Then I used rowSums to sum horizontally, and if any of these sums is > 0, it means there was a 1 in at least one of the columns of a given row, so I simply selected those rows and set b to 1.


text:
Q: OpenCVSharp - Compare two images, and return back the matched area with coordinates Its been awhile since I have posted on here and I am finally getting a little time to work on a personal project again.
I just started working with for the first time today, OpenCVSharp in C# .NET 4.8 and working on a small code spike.
I have found samples online as OpenCVSharp has a nice examples library; however I am uncertain as to which one of them would point me in the right direction. I started off using their SIFT/SURF one.
So what I am trying to do is as follows:
1.) Image1 is a picture which is a full resolution image (3440x1440).
2.) Image2 is a cropped picture from Image1, which is what I will use as the target to find and identify in Image1.
3.) Return back the pixel coordinates of the rectangular or square area "my boundries".
4.) Return back or calculate the dead center of the rectangular or square area.
Thank you all in advance for any help and support on this topic!
EDIT:
After being informed to try keypoint matching, I found that the https://github.com/shimat/opencvsharp_samples/blob/master/SamplesCS/Samples/DrawBestMatch.cs works exactly as I need it to.
The part where I am now stuck is trying to figure out the exact pixel location from the returned match image, on the original. I get back the matched image which is great, however I am trying to figure out step #3 in my original post now.


text:
Q: How to filter based on a word in a sentence with special characters regex snowflake? I have a string that looks like
***z|Alphanumeric | Jhon Jones| PA | String |Date:73/65/86-58/82/03,44/79/11-26/33/60|Date:Not Valid | Arbitrary Fees|Amount:11111|Frequency:Monthly |

How do I ignore everything and just fetch rows based on "Arbitrary Fees"? I tried the below query and it doesn't work
select
MSTR_APLN_ID,
CMNT_LN_1_TXT_TOK
from SFAAP.V_SOT_DIRBNK_CLB_DPL_MRD.apln_cmnt_hist
where lower(CMNT_LN_1_TXT_TOK) Rlike '.* Arbitrary Fees.*'

A: Greg's answer is correct and I'm a big fan of REGEX functions, but your query doesn't seem to use the power of regex. Why don't you use LIKE or ILIKE?
Case-insensitive:
select
MSTR_APLN_ID,
CMNT_LN_1_TXT_TOK
from SFAAP.V_SOT_DIRBNK_CLB_DPL_MRD.apln_cmnt_hist
where CMNT_LN_1_TXT_TOK ILIKE '%Arbitrary Fees%'

Case-sensitive:
select
MSTR_APLN_ID,
CMNT_LN_1_TXT_TOK
from SFAAP.V_SOT_DIRBNK_CLB_DPL_MRD.apln_cmnt_hist
where CMNT_LN_1_TXT_TOK LIKE '%Arbitrary Fees%'

A: You have the column's string wrapped in the lower function, but your string has two capital letters:
lower(CMNT_LN_1_TXT_TOK) Rlike '.* Arbitrary Fees.*'

You can change to:
 CMNT_LN_1_TXT_TOK Rlike '.*Arbitrary Fees.*'

If you want to match any case for the search term:
lower(CMNT_LN_1_TXT_TOK) Rlike '.*arbitrary fees.*'


text:
Q: Error: initMap is not a function I have a unique problem, namely I have a social website with a lot of interesting places. Every place has a google map. And today I see a problem.
When I add new place with address to make map from google api, it doesn't work.
I was checked previously added places and they normally have map, though error

"initMap is not a function".

Whats wrong? Why in newly created places map from google api doesn't work? I use it with my api key:
 <script async defer src="https://maps.googleapis.com/maps/api/js?key=MY_API&callback=initMap"></script>

A: Probably comes from script position in your code. Make sure;
<script src="https://maps.googleapis.com/maps/api/js?key=MY_API_KEY"></script>

load after script block containing initMap function.
<script type="text/javascript">
function initMap() {
 //
}
<script src="https://maps.googleapis.com/maps/api/js?key=MY_API_KEY"></script>

A: Is there a function called "initMap" in your code? If not you will get this error. The async attribute lets the browser render the rest of your website while the Maps JavaScript API loads. When the API is ready, it will call the function specified using the callback parameter. If you want to have a different callback function with a different name, that is perfectly fine, but you will have to modify this request URL accordingly. You can also remove the callback parameter entirely if you wish to do so, but you will need to make a function call in your code to load the map. You will also need to remove async defer if you do this, otherwise you will get an error saying google is not defined. The modified script tag would be:
<script src="https://maps.googleapis.com/maps/api/js?key=MY_API_KEY"></script>

I have an example demonstrating this here:
https://jsfiddle.net/gy3yg9ma/11/
Please insert your own API key to use the sample. Notice how I had to call initMap(); manually in my code since I removed the callback parameter. The map will not load until a function is called to load it.
I hope this helps!


text:
Q: geb passing test case as a parameter from maven commandline How do I pass the test case to geb via maven commandline:
I have a test case class named GebishOrgSpec2.groovy
I want to pass this test case maven and let geb run it over the command line.
I am having successful build but no run of the test case
How do I solve this problem?
This is my pom.xml
  <plugin>
        <groupId>org.apache.maven.plugins</groupId>
        <artifactId>maven-surefire-plugin</artifactId>
        <version>2.19</version>
        <configuration>
          <includes>
            <include>${inc.TestCase}</include>
          </includes>
          <systemPropertyVariables>
            <geb.build.reportsDir>target/test-reports/geb</geb.build.reportsDir>
          </systemPropertyVariables>
        </configuration>
      </plugin>

I have tried the following codes and they are all not running the testcase
mvn -Dinc.TestCase=GebishOrgSpec2.groovy test
mvn -Dinclude=GebishOrgSpec2.groovy test
mvn install -Dinc.TestCase=GebishOrgSpec2.groovy
mvn install -Dinclude=GebishOrgSpec2.groovy

I have tried these links
How to run Geb TestCases from windows command line?
Grails geb getting parameters from commandline
Geb exception when running tests in maven
they are all not working

System.getProperty("inc.TestCase") is returning null as well
  I want to add that if I add the test case directly into the pom it does run successfully
  can you please help

A: Don't use in-/excludes in your POM for something you want to do from the command line. It is much easier, both for

*

*Surefire (unit tests) via mvn -Dtest=TestCircle test and

*Failsafe (integration tests) via mvn -Dit.test=ITCircle verify
This works beautifully for Spock/Geb tests.


text:
Q: tkinter submit button handle function only once unless different input is given I am new to tkinter and this is a simple method but I don't know how to do it. I want to create a submit button where if the same user input is given and submitted again the button will disable but if new input is given it will carry out its function. Can someone help me with this? Thanks

A: If I understand problem - you have to create list to remeber submitted data and check it with new input
import tkinter as tk

# --- functions ---

def submit():
    data = e.get()

    if data in already_submitted:
        print('Sorry already submitted:', data)
    else:
        print('Submit:', data)
        already_submitted.append(data)

# --- main ---

# don't submit empty string
already_submitted = ['']

root = tk.Tk()

e = tk.Entry(root)
e.pack()

b = tk.Button(root, text="Submit", command=submit)
b.pack()

root.mainloop()

BTW: you could also bind() function to Entry and check input after every key and disable/enable button.
import tkinter as tk

# --- functions ---

def submit():
    data = e.get()

    if data in already_submitted:
        print('Sorry already submitted:', data)
    else:
        print('Submit:', data)
        already_submitted.append(data)
        b['state'] = 'disable'

def check(event):
    #data = event.widget.get()
    data = e.get()

    if data in already_submitted:
        b['state'] = 'disable'
    else:
        b['state'] = 'normal'

# --- main ---

# don't submit empty string
already_submitted = ['']

root = tk.Tk()

e = tk.Entry(root)
e.pack()
e.bind('<KeyRelease>', check)

b = tk.Button(root, text="Submit", command=submit, state='disable')
b.pack()

root.mainloop()


text:
Q: Unit testing with jest in React Native project ("Not a function" error) I am working on a React Native project (v0.46). I've been able to write component snapshot tests successfully, but I'm having trouble wrapping my head around unit testing JavaScript ES6 functions.
Here are my functions in FakeUtils.js:
export function sum(a, b) {
    return a + b;
}

export function subtract(a, b) {
    return a - b;
}

And here are my tests for them:
import sum from '../src/utils/FakeUtils.js';
import subtract from '../src/utils/FakeUtils.js';

describe('sum', () => {
    it('should sum 2 nums', () => {
        expect(sum(1,2)).toBe(3);
    });
});

describe('subtract', () => {
    it('should subtract 2 nums', () => {
        expect(subtract(2,1)).toBe(1);
    });
});

When I run npm test, this is the output I receive:
FAIL  __tests__/FakeUtilsTest.js
  ● sum › should sum 2 nums

    TypeError: (0 , _FakeUtils2.default) is not a function

      at Object.<anonymous> (__tests__/FakeUtilsTest.js:6:31)
      at tryCallTwo (node_modules/promise/lib/core.js:45:5)
      at doResolve (node_modules/promise/lib/core.js:200:13)
      at new Promise (node_modules/promise/lib/core.js:66:3)
      at Promise.resolve.then.el (node_modules/p-map/index.js:42:16)
      at tryCallOne (node_modules/promise/lib/core.js:37:12)
      at node_modules/promise/lib/core.js:123:15

  ● subtract › should subtract 2 nums

    TypeError: (0 , _FakeUtils2.default) is not a function

      at Object.<anonymous> (__tests__/FakeUtilsTest.js:12:31)
      at tryCallTwo (node_modules/promise/lib/core.js:45:5)
      at doResolve (node_modules/promise/lib/core.js:200:13)
      at new Promise (node_modules/promise/lib/core.js:66:3)
      at Promise.resolve.then.el (node_modules/p-map/index.js:42:16)
      at tryCallOne (node_modules/promise/lib/core.js:37:12)
      at node_modules/promise/lib/core.js:123:15

Any idea what I'm doing wrong here?

A: Your import statements are off a bit. Try this instead:
import { sum, subtract } from '../src/utils/FakeUtils.js';

Since you aren't exporting with the default keyword, you need to place your imports in curly braces. You can only have one default export, so this approach makes sense.

A: I happens because you are exporting your functions incorrectly in relation to import.
You should export it this way
const function sum(a, b) {
  return a + b;
}

const function subtract(a, b) {
  return a - b;
}
export { sum, subtract}

or import it this way
import {sum, subtract } from '../src/utils/FakeUtils.js';

A: You are importing the functions wrong.
You can't do import sum from '../src/utils/FakeUtils.js';
import subtract from '../src/utils/FakeUtils.js'
Unless you are default exporting the functions , like:
default export sum;

It works that way to ease with importing modules with one exported object.
In your case you need to import not default functions , like:
import {subtract,sum} from '../src/utils/FakeUtils.js'


text:
Q: Is there a way to deploy DropWizard in JBoss?
   Is there a way to deploy DropWizard in JBoss? We are required to use JBoss anyway but don't want to miss out trying DropWizard. Came to know about wiztowar but current DropWizard version 0.7.1 (which is tailored to support JDK 7+ and likely to be supported in future) does not seem to have equivalent in wiztowar, whose last version is suited only for DropWizard 0.6.2? Is there a way out?
Thanks,
Padmanabhan

A: Have a look at https://github.com/rvs-fluid-it/dw-jar-to-war. The project is in its early stages. But it is already working on Tomcat 7 and Weblogic 12c. The DropWizard version is 0.8. Feel free to test it on JBoss. I welcome feedback.


text:
Q: Configure Duplicity to use pinentry? Duplicity by default asks for passwords to GnuPG keys on start up and caches them in memory throughout process lifetime. Is there a way to have it use /usr/bin/pinentry instead so I know I'm not passing the passphrase through Duplicity?
I'm using GnuPG hardware smart cards, so generally when a sign or decrypt operation is requested, I usually get a pinentry dialogue that pops up. I can configure gpg-agent to cache my passphrases for a set amount of time.
Is there a way to have Duplicity not know my GnuPG keys and use the GnuPG agent and pinentry to bypass inputting my passphrase into Duplicity?

A: Duplicity does not cache gpg pass phrases by default (you can give them as env vars though). All prompts you see are from the gpg binary run underneath. Hence, when you configure your gpg into the desired state, duplicity will use it as configured and you are set.
For using gpg-agent read what the parameter --use-agent does on the manpage: http://duplicity.nongnu.org/duplicity.1.html


text:
Q: Changing position of a row in sql
In the above t-sql table I would like very much for the Total row to appear at the bottom. I have been wracking my head against this and in all of my other Queries simply using ORDER BY Status works as Total is alphabetically much farther down the list than most of our row values.
This is not the case here and I just can't figure out how to change it
I'm pretty new to sql and I'be been having a lot of difficulty even determining how to phrase a google search. So far I've just gotten results pertaining to Order By

A: The results of a select query, unless an order is explicitly specified via an 'order by' clause, can be returned in any order. Moreover, the order in which they are returned is not even deterministic. Running the exact same query 3 times in succession might return the exact same result set in 3 different orderings.
So if you want a particular order to your table, you need to order it. An order by clause like
select *
from myTable t
where ...
order by case Status when 'Total' then 1 else 0 end ,
         Status

would do you. The 'Total' row will float to the bottom, the other rows will be ordered in collating sequence. You can also order things arbitrarily with this technique:
select *
from myTable t
where ...
order by case Status
           when 'Deceased'  then 1
           when 'Total'     then 2
           when 'Active'    then 3
           when 'Withdrawn' then 4
           else                  5
         end

will list the row(s) with a status of 'Deceased' first, followed by the row(s) with a status of 'Total', then 'Active' and 'Withdrawn', and finally anything that didn't match up to an item in the list.

A: In SQL Server (and most other databases), you can use case to sort certain statūs above others:
order by
        case Status
        when 'Total' then 2
        else 1
        end
,       Status

In MS Access, you can use iif:
order by
        iif(Status = 'Total', 2, 1)
,       Status

A: ORDER BY CASE WHEN STATUS = 'Total' THEN 'zzz' ELSE STATUS END

A: You can use conditional expressions in order by:
order by (case when status = 'Total' then 1 else 0 end),
         status


text:
Q: How do I spawn a Skeleton spawner? I need to spawn in a spawner, what's the command? I have already tried a few times and can't get the command right.

A: You can use this command to set a block to a skeleton spawner:
/setblock <pos> minecraft:spawner{SpawnData:{id:"minecraft:skeleton"}}


text:
Q: How to define precisely the radius size when using 'select features by radius' in QGIS I'd like to select features with circles having precise radius in QGIS.
By default this tool is freehand so it is hard to get a precise value.

A: Not sure if there's a direct approach to this but there are alternative methods:

*

*Fast, less precise
Use the Measure Line tool from the toolbar to draw a radius as precise as you can (remember to right-click to stop drawing the line):

Then use the Select Features by Radius tool to draw the circle from each point of the measured line:

*

*Slow, more precise
Create a point layer and add a point. Use the Buffer tool (Vector > Geoprocessing Tools > Buffer(s) to create a polygon of the point (maximise the "Segments to approximate" and set your buffer distance to what you want the radius to be, becareful as this is dependent on your CRS).
Then use one of the Select by location tools (either from the Processing Toolbox or from Vector > Research Tools > Select by location), select both layers and check the intersect option:

A: *Updated answer to this question
There is now a new plugin called "Select by radius plus" tool which can be downloaded from the plugins menu in QGIS.
The user interface is as follows:

The user can select from either meters, kilometers or miles and also has the option to use centroid as the selection parameter.
The plugin was created by Lutra Consulting https://www.lutraconsulting.co.uk/,
and the code repository can be found here:
https://github.com/lutraconsulting/qgis-select-by-radius-plus-plugin

A: The selection by radius should come in meters as default.


text:
Q: Android performance hit on later versions than 2.3.5 (phonegap/cordova) Currently I'm developing an Android App with Phonegap/Cordova (2.1.0/2.2.0) , JQ-Mobi(not jQueryMobile), HTML5 and Javascript and CSS3. The App contains 2 native exstensions.
Somehow, when I export my project to a device with the lastest Android version, the app runs so much slower than an 2.3.5 device.
I've tried enabling the HardwareAcceleration and removed all of the box-shadows and other tough to render css3 stuff. Still on a 4.1.1 or 4.0.4 it runs crappy.
I also upgraded to the latest version of Cordova (now 2.2.0) and it doesn't seem to make it better.
Javascript DOM manipulation happens for about 80-90% when the app is started.
The worst performance is in switching panels and scrolling through forms, most of them have some transitions in them.
I tested it on a Samsung Galaxy S2 android 2.3.5 and it look fine and performs well.
Same device, but 4.0.4 runs crappy.
Samsung Galaxy S3 4.1.1 runs even crappier.
HTC Flyer P512 with android 3.2.1 runs it how it should be running.
Can anyone help me out here? How do I get this performance up? Any Hint or Tips which I havn't mentioned?
I'd like to add that I don't get the issues on an Iphone 3gs and up to explain that it is definitly an Android problem.

A: My phonegap apps run smoothly on iOS, but perform extremely poorly on Android. As I understand it this is just because Android is much slower at interpreting JavaScript than iOS.
One thing that can help a lot is cutting down on the use of libraries such as jQuery and JQM. If you want to include them, don't use them where you don't have to.
functions such as jQuery.animate run notoriously slow on Android and you'd be better of iterating over arrays with raw JS rather than using jQuery.each etc. etc.
The problem is not just with graphical rendering, but with the speed at which JavaScript is executed. Although lowering the screen resolution can boost your performance.
Edit
I am trying to get to the bottom of this myself and the only answer I can get is to keep computational operations at a minimal.

*

*Use libraries sparingly and solve your problems with raw and well written JavaScript when possible

*Keep a small DOM and manipulate it as seldom as possible

*Make use of JavaScript performance enhancing techniques

So it really seems that this is a core performance issue, rather than something that could be solved on the Phonegap layer. As a non-scientific example, the exact same init() function on one of my apps executes in about 1.2 seconds in iPhone 4s on average, while taking a sluggish 5 seconds to complete on my samsung galaxy s3.

A: The core of the problem is that everything is loaded and running in a single page (execution context), personally, though single page apps (sencha, jqmobile etc) are all the rage, the performance on modern devices does not do the user experience any justice.  I would separate the app into different pages, this will significantly reduce the size of the DOM and create separate execution contexts for each new page, meaning that your main page (execution context) is nice and lean (DOM is small).

A: I had the exact same problem.  I asked a similar question and eventually answered it myself here after a tonne of research:
Cordova/Phonegap slow performance with Open Layers on new Tablet, but fine on new phone
I won't repeat the entire answer I gave, but the slow performance on certain Android versions is due to what is essentially a bug in WebView which throttles the CPU support for GPU based processes, but doesn't provide GPU support to compensate.
Kitkat V4.4.3 upwards have this fixed, but older versions such as V4.4.2 which are still being used on some devices still suffer.
You can avoid this by not using WebView at all for the HTML rendering, and instead use Crosswalk.  For our project this solved the problem entirely and we now have a smooth running application across all Android versions we're targeting. It's quite trivial to do as well.
https://crosswalk-project.org/documentation/cordova.html
https://blog.nraboy.com/2014/10/use-crosswalk-ionic-framework-android-apps/

A: Try using multithreading and background processing for resource extensive operations.
That worked for me when i had similar problem with one of my apps when it crashes when it runs on versions later than 2.3.3. I never worked with PhoneGap so I'm not sure how you are going to do it.


text:
Q: Is there any way to save snippets in CMD Is there any way so save snippets in CMD(win7). I mean, I type: command01 + trigger and it converts to something like: git config --global core.editor "vim". Or if there is some 3th party program or scripts that does that.

A: aliases
For full aliases of complex commands, just write one-line batch files:
E.g. git-set-vim.cmd:
@git config --global core.editor "vim"

These would correspond to Bash functions or aliases.
snippets
For snippets (i.e. parts of a command where you still need to do additional editing beyond appending command arguments), you indeed need a third-party extension.
I'd recommend AutoHotkey, which allows you to define macros trigger by key combinations (and other system automation), also depending on the currently active type of program.

A: The free Autohotkey allows you to repeat strings and paragraphs of text very easily.
Autohotkey is a tool that uses a config text file and it can include lines like this:
::.c::[code]echo Here is my code[/code]

::.b::[b]This is Bold[/b]

::address1::
send Peter PumpkinEater{enter}
send 213 The Patch{enter}
send Fairyland{enter}
return

and when you type .c and space then it will print [code]echo Here is my code[/code] to the text editor or website forum or program you are using at the time.
When you type .b and space it will print [b]This is Bold[/b]
and when you type address1 and space it will type this:
Peter PumpkinEater
213 The Patch
Fairyland
It is far more powerful than just the hotstrings that I have outlined and is a wonderful tool.


text:
Q: Regex for multiple word match seperated by spaces I want to match all occurences of a word in a string having spaces at front and back.
Eg: String: " Apple Apple Apple Apple ".
Here I want the match to be " Apple " and there should be 4 matches for the above scenario.
If I just put regex as / Apple /, then only 1st and 3rd are matched.
I know that we can do this with lookahead and lookbehind in regex but it is not supported in safari and IE.

A: You can match  Apple and assert a space to the right. As you know that the space is there, you can add it in the result.

const regex = / Apple(?= )/g;
const s = " Apple Apple Apple Apple ";
console.log(Array.from(s.matchAll(regex), m => m[0] + " "));

Or you can capture  Apple  in group 1, and get the group 1 value denoted by m[1] in the code:

const regex = /(?=( Apple ))/g;
const s = " Apple Apple Apple Apple ";
console.log(Array.from(s.matchAll(regex), m => m[1]));

A: If you're happy to just match the Apple word, you can use (?<= )Apple(?= ).
If the space is not strictly necessary (e.g. you want also to catch the first word of the string, which is not preceded by a space), you must use word boundaries (i.e. \bApple\b).


text:
Q: tense mismatch for a reported fact with "there was"
There was a lady who spit at me yesterday.
There was a lady who spat at me yesterday.

Is the first one ungrammatical? I am thinking it is, but I am wondering if there's any situation where the first one is ok grammatically.

A: The past tense of the verb 'to spit' is mainly 'spit' in American English, and mainly 'spat' in British English.
Spit (Oxford Learners Dictionary)


text:
Q: How to use CSS for formatting Crystal Report in Winform? I am using VS 2008 for a Winform. I have crystal reports in the project which I would like to format with the help of CSS.
Can anyone point me with the right tutorial to start this?

A: Crystal Reports for Visual Studio has limited HTML formatting. see This Forum Post (Google for more).
I've been recently trying to make some formatting on my reports using HTML and saddly discovered that it doesn't even suport divs it is just for text formatting, and most CSS attributes are not supported. At the end I had to use RTF formatting (Just because I needed the Justify Paragraph option for Legal Letters).
Hope it help,

A: CSS works only in web application. If you want to customize your windows app look and feel, you can use either XML file or resource file. Specify all of your control's settings into XML or res file and use this file at runtime when your window app form loads.
sample xml
<?xml version="1.0" encoding="utf-8" ?>
<StylesSheetFile xmlns:xsi="http://www.w3.org/2001/XMLSchema-instance"
                 xmlns:xsd="http://www.w3.org/2001/XMLSchema">
    <Styles>
        <Style Name="FormType1">
            <Properties>
                <Property Name="BackColor" Value="White" />
                <Property Name="Text" Value="Personal information" />
                <Property Name="Enabled" Value="true" />
            </Properties>
        </Style>
        <Style Name="DataGridType1">
            <Properties>
                <Property Name="RowsDefaultCellStyle.BackColor"
                          Value="White" />
                <Property Name="AlternatingRowsDefaultCellStyle.BackColor"
                          Value="214,222,247" />
                <Property Name="Columns[0].HeaderText"
                          Value="Color name" />
                <Property Name="Columns[1].HeaderText" Value="My rate" />
            </Properties>
        </Style>
        <Style Name="TabControlType1">
            <Properties>
                <Property Name="Enabled" Value="true" />
                <Property Name="TabPages[0].BackColor" Value="White" />
                <Property Name="TabPages[1].BackColor" Value="White" />
                <Property Name="TabPages[2].BackColor" Value="White" />
            </Properties>
        </Style>
        <Style Name="LabelType1">
            <Properties>
                <Property Name="TextAlign" Value="TopLeft" />
                <Property Name="BorderStyle" Value="None" />
                <Property Name="ForeColor" Value="72,94,158" />
                <Property Name="Font"
                          Value="Microsoft Sans Serif,8.25pt,style=Regular" />
                <Property Name="Height" Value="20" />
                <Property Name="Enabled" Value="true" />
            </Properties>
        </Style>
        <Style Name="LabelType2">
            <Properties>
                <Property Name="ForeColor" Value="Red" />
                <Property Name="Font"
                          Value="Microsoft Sans Serif,8.25pt,style=Bold" />
            </Properties>
        </Style>
        <Style Name="TextBoxType1">
            <Properties>
                <Property Name="TextAlign" Value="Left" />
                <Property Name="BorderStyle" Value="Fixed3D" />
                <Property Name="Font" Value="Tahoma,10,style=Regular" />
                <Property Name="Height" Value="20" />
                <Property Name="Width" Value="200" />
                <Property Name="BackColor" Value="214, 222, 247" />
            </Properties>
        </Style>
        <Style Name="HyperLinkType1">
            <Properties>
                <Property Name="BorderStyle" Value="None" />
                <Property Name="ForeColor" Value="Blue" />
                <Property Name="Font"
                          Value="Tahoma,10,style=Italic,Underline" />
                <Property Name="Height" Value="30" />
                <Property Name="Width" Value="200" />
                <Property Name="Enabled" Value="true" />
            </Properties>
        </Style>
        <Style Name="ButtonType1">
            <Properties>
                <Property Name="TextAlign" Value="TopLeft" />
                <Property Name="ForeColor" Value="Black" />
                <Property Name="BackColor" Value="214;222;247" />
                <Property Name="Font" Value="Tahoma,8.25,style=Italic" />
                <Property Name="Height" Value="23" />
                <Property Name="Enabled" Value="true" />
            </Properties>
        </Style>
        <Style Name="ComboBoxType1">
            <Properties>
                <Property Name="BackColor" Value="White" />
                <Property Name="Font" Value="Tahoma,10,style=Italic" />
                <Property Name="Height" Value="30" />
                <Property Name="Width" Value="200" />
                <Property Name="Enabled" Value="true" />
            </Properties>
        </Style>
        <Style Name="RadioButtonType1">
            <Properties>
                <Property Name="ForeColor" Value="Blue" />
                <Property Name="Font" Value="Verdana,8,style=Regular" />
                <Property Name="Width" Value="150" />
                <Property Name="Enabled" Value="true" />
            </Properties>
        </Style>
    </Styles>
</StylesSheetFile>


text:
Q: Character encoding in JSP input form I would like to use hungarian character (ő,ű) in JSP input field, but i can not get these character from the JSP input (I use spring mvc), I get only õ,û from the input.
<%@ page language="java" contentType="text/html; charset=ISO-8859-2"
    pageEncoding="ISO-8859-2"%>
<% request.setCharacterEncoding("ISO-8859-2"); %>
<% response.setCharacterEncoding("ISO-8859-2"); %>
....
    `<spring:bind path="city">
        <div>
            <form:input type="text" path="city" accept-charset="ISO-8859-2"></form:input>
        </div>
    </spring:bind>`

A: I resolved this problem.
I had to insert encoding filter to the web.xml.
<filter>
    <filter-name>encoding-filter</filter-name>
    <filter-class>
        org.springframework.web.filter.CharacterEncodingFilter
    </filter-class>
    <init-param>
        <param-name>encoding</param-name>
        <param-value>UTF-8</param-value>
    </init-param>
</filter>

<filter-mapping>
    <filter-name>encoding-filter</filter-name>
    <url-pattern>/*</url-pattern>
</filter-mapping>


text:
Q: Site is not resizing to window size. Site cut off at 800px Im currently have a problem with small screen displaying my site, the site is adapting to 100% height of the browser, but the content inside it is not accomodating to the height. It is causing the content to be cut off. Currently, displaying at 19" screen is okay, lower will have a problem. While mobile is perfectly displaying.
the site is http://emailblasting.epizy.com/index2.html
i have adjusted my container div to 100% height, but it still cut off. or is the content inside it i need to set width and such?

A: As I can see you are using media queries (@media rules), avoid setting your widths and heights for outer containers in pixels and go for responsive values. For example;
html, body, .container {
    width: auto;
    max-width: 100%;
    height: 100%;
}

img {
    width: auto;
    height: auto;
    max-width: 100%;
    max-height: 100%;
}

You can then control the layout of individual inner containers with margins or padding (or as a last result pixel widths) where necessary.
That way you'll have your page and content being responsive and fit in the different browser windows.

A: Heyy...I guess it is because your container has margin-left and margin-right
    .container {
    display: block;
    max-width: 600px;
    width: 100%;
    height: 100%;
    max-height: 800px;
    margin: 0 auto;
    overflow: hidden;
}

here margin: 0 auto..
that "auto" part is creating issue for you..
Try to check that and i guess it will work for you..
and you can set your height to 100vh instade of 100%...
It wont make your page scrollable
Regards


text:
Q: How can I override blueprint's styles? Hi I'm using blueprint and for some reason I can't override some of their built-in styling (screen.css). So far I've tried:
 #asset-index-desc .container
       div
         li
           :border dashed !important

...and this does nothing. I'd appreciate any help.

A: Does your SASS-created CSS come before or after screen.css? The one that comes after should override the one that comes before.
Look at the styles with Firebug for Firefox -- it has a really good UI to see what styles are active and which have been overridden further down the chain.

A: hmm I can think of a few things:
1) try adding color and thickness: i.e.
#asset-index-desc .container
      div
        li
          :border 1px dashed red !important

2) I presume that the code you provided is not as it appears in your document as otherwise you would get a Sass error about the div tag being too deeply nested....  :)
3) the following does NOT work in my own app,
#sidebar
  div
    li
      border: 1px dashed red !important

BUT if I remove the div tag, then it's all good:
#sidebar
  li
    border: 1px dashed red !important

Hope this helps.....
I LOVE Sass and blueprint....  Especially with compass gem.  It takes all of the pain out of styling....

A: Don't know exactly what you are trying to override, but you may need to get more specific in your selector. Maybe add an additional class to the markup and reference the additional class in your style sheet


text:
Q: ASP.NET MVC. CodeFirst. Связь один к одному Есть готовая база данных. Необходимо к ней сделать Web-приложение на ASP.NET MVC. Подключаю базу в режиме CodeFirst, но никак не получается связать две таблицы имеющие связь Один-к-одному.
Таблицы следующие
CREATE TABLE USERS (
   ID_U                INTEGER NOT NULL,
   ID_EMPLOYEE         INTEGER,
   PW                  VARCHAR(250) DEFAULT ''
);
ALTER TABLE USERS ADD CONSTRAINT PK_USERS PRIMARY KEY (ID_U);
ALTER TABLE USERS ADD CONSTRAINT FK_USERS_1 FOREIGN KEY (ID_EMPLOYEE) REFERENCES EMPLOYEE (ID_EM) ON DELETE CASCADE;

CREATE TABLE EMPLOYEE (
   ID_EM        SMALLINT NOT NULL,
   LAST_NAME    VARCHAR(50) DEFAULT '',
   FIRST_NAME   VARCHAR(50) DEFAULT '',
   MIDDLE_NAME  VARCHAR(50) DEFAULT '',
);
ALTER TABLE EMPLOYEE ADD PRIMARY KEY (ID_EM);

Создаю следующие классы:
[Table("USERS")]
public class User
{
    [Key, Column("ID_U")]
    public int Id { get; set; }

    [Column("PW"), StringLength(250)]
    public string Password { get; set; }

    [Column("ID_EMPLOYEE")]
    public int EmployeeId { get; set; }

    public Employee Employee { get; set; }
}

[Table("EMPLOYEE")]
public class Employee
{
    [Key, Column("ID_EM")]
    public int EmployeeId { get; set; }

    [Column("LAST_NAME"), StringLength(250)]
    public string LastName { get; set; }

    [Column("FIRST_NAME"), StringLength(250)]
    public string FirstName { get; set; }

    [Column("MIDDLE_NAME"), StringLength(250)]
    public string MiddleName { get; set; }
}

В DbContext прописываю
public DbSet<User> Users { get; set; }
public DbSet<Employee> Employees { get; set; }

В контроллере код для теста
 private DataBaseContext db = new DataBaseContext();
 public ActionResult Index()
 {
    foreach (User us in db.Users)
    {
        ViewBag.Message = us.Employee.FirstName;
    }
    return View();
 }

При считывании данных в классе User свойство Employee всегда null.
Не пойму как правильно прописать связи, чтобы в User.Employee были данные.
Надеюсь на вашу помощь и советы.

A: EF не подгружает связанные сущности по умолчанию. Т.е. нужно или включить Lazy Loading, сделав свойство виртуальным - тогда EF заменит его на прокси, который подгрузится при обращении:
public virtual Employee Employee { get; set; }

или явно обозначить, что вы хотите загрузить данные
foreach (User us in db.Users.Include("Employee")) ...

A: [ForeignKey("ID_EMPLOYEE")]
public virtual Employee Employee { get; set; }

[Column("ID_EMPLOYEE")]
public int EmployeeId { get; set; }

Вот так должно работать


text:
Q: How to set default styles in unordered lists in Material-UI React I'm trying to replicate a simple blog from markdown with Next.js and Material-UI but something is removing the default styles from the unordered lists.
List items (li HTML elements) have list-style: none; set and have no padding. Ordered lists look normal and have the default styles.
How it looks in the documentation's example:

What I get when I used the same content and markdown handling code:

The problem persists whether I use markdown content or ul/ol/li elements directly in JSX.
In the documentation example, the code that reads markdown and transforms it into React components doesn't seem to change the styling either.

A: My bad, I had the following fragment of code in a component:
<GlobalStyles styles={{ ul: { margin: 0, padding: 0, listStyle: 'none' } }} />

That was overriding the default styling.
It was in a old component that I didn't need anymore.
Turns out, overriding global styles recklessly can cause headaches.


text:
Q: I've just arrived to Skellige in Witcher 3. How deep am I into the game? I'm in awe with the game and I play it rarely, bits by bits, so it lasts longer, so I try to count every single chapter.
How deep in am I?

A: You can go to Skellige at about 5% of completion. The game is set up in a way for you to find Ciri by doing a bunch of different quests around all parts of the game world.
Just because you went to Skellige doesn't mean you have completed anything except the tutorial area and unlocking Novigrad.
There is no way to assume how far you are just by being in Skellige.

A: I often think about the main story line of the game in terms of Chapters.

*

*The Investigation: What has Ciri been up to?  In total, this is the better part of the main story line, if you don't count DLCs.  If done in order of recommended level, you'll investigate her Velen Story, then her Novigrad Story, then her Skellige Story, but this order is by no means important.

 It's not explicitly stated, but Ciri's personal story line seems to run in this order: Skellige Forest -> Velen (Crones -> King of Wolves -> Cocatrice) -> Novigrad -> Skellige Town

*

Cure Uma.

*Collect on Debts.  (Side quests can be important.)

*

Retrieve Ciri from her hide-out & The-Big-Fight Pt. 1.  Prior to starting this, you'll be asked if you really want to.  Ask yourself, have you collected on all available Debts?

*Collect even more powerful Allies.

*The-Big-Fight Pt. 2

Of course there is much more to the game than just the main story line.  Rich side quests & points of interest are really not to be missed.

A: If I can remember right it's the third our of 3 main zones. So 66%.
https://gamefaqs.gamespot.com/boards/702760-the-witcher-3-wild-hunt/72421500 Gamespot gives it about 60-65%.
That is only counting the main game. There are 2 DLCs that would be about the size of a zone. So if counting with DLC, about 40%.

A: Surely there are other ways to tell, e.g.: how many hours have you played? Divide that by, oh, say, 250.
That is: if you are really enjoying The Witcher, and you continue to enjoy it, it's quite likely you'll spend hundreds of hours playing it.
I believe I spent nearly 200 hours playing it, and I certainly wasn't finished by then.


text:
Q: Kotlin JavaScript Karma test fails to make any http requests I'm running JavaScript tests using Karma but it fails to make http requests.
build.gradle.kts
js(IR) {
    useCommonJs()
    browser {
        testTask {
            useKarma {
                useChromeHeadless()
            }
        }
    }
    binaries.executable()
}

I'm using Ktor Client to fetch the url content
val text = HttpClient(Js).get("https://www.google.com/") {
    header("Content-Type", "text/html; charset=utf-8")
    header("Accept", "*/*")
}.body<String>()

And this is the error:
> Task :jsTestClasses
> Task :compileTestDevelopmentExecutableKotlinJs
> Task :jsTestTestDevelopmentExecutableCompileSync
> Task :jsBrowserTest
myTest before fetch
TRACE: Adding Accept-Charset=UTF-8 to https://www.google.com/TRACE: Processing exception Error_0: Fail to fetch for request https://www.google.com/Error_0: Fail to fetch
    at http://localhost:9876/absolute/var/folders/cb/nd4gn6pn79zg52rz_l5bl1bdjfnmjy/T/_karma_webpack_293805/commons.js?58a2b80ce49dc5767b060dfe37192606438b082a:52793:26
Caused by: TypeError: Failed to fetch
    at commonFetch (http://localhost:9876/absolute/var/folders/cb/nd4gn6pn79zg52rz_l5bl1bdjfnmjy/T/_karma_webpack_293805/commons.js?58a2b80ce49dc5767b060dfe37192606438b082a:52730:13)
    at $executeCOROUTINE$16.doResume_5yljmg_k$ (http://localhost:9876/absolute/var/folders/cb/nd4gn6pn79zg52rz_l5bl1bdjfnmjy/T/_karma_webpack_293805/commons.js?58a2b80ce49dc5767b060dfe37192606438b082a:52105:29)
    at JsClientEngine.execute_95skru_k$ (http://localhost:9876/absolute/var/folders/cb/nd4gn6pn79zg52rz_l5bl1bdjfnmjy/T/_karma_webpack_293805/commons.js?58a2b80ce49dc5767b060dfe37192606438b082a:52224:16)
    at HttpClientEngine$executeWithinCallContext$slambda.doResume_5yljmg_k$ (http://localhost:9876/absolute/var/folders/cb/nd4gn6pn79zg52rz_l5bl1bdjfnmjy/T/_karma_webpack_293805/commons.js?58a2b80ce49dc5767b060dfe37192606438b082a:46100:44)
    at HttpClientEngine$executeWithinCallContext$slambda.invoke_1yhb3o_k$ (http://localhost:9876/absolute/var/folders/cb/nd4gn6pn79zg52rz_l5bl1bdjfnmjy/T/_karma_webpack_293805/commons.js?58a2b80ce49dc5767b060dfe37192606438b082a:46082:16)
    at l (http://localhost:9876/absolute/var/folders/cb/nd4gn6pn79zg52rz_l5bl1bdjfnmjy/T/_karma_webpack_293805/commons.js?58a2b80ce49dc5767b060dfe37192606438b082a:46133:16)
    at _no_name_provided__qut3iv_6.doResume_5yljmg_k$ (http://localhost:9876/absolute/var/folders/cb/nd4gn6pn79zg52rz_l5bl1bdjfnmjy/T/_karma_webpack_293805/commons.js?58a2b80ce49dc5767b060dfe37192606438b082a:31198:43)
    at CoroutineImpl.resumeWith_7onugl_k$ (http://localhost:9876/absolute/var/folders/cb/nd4gn6pn79zg52rz_l5bl1bdjfnmjy/T/_karma_webpack_293805/commons.js?58a2b80ce49dc5767b060dfe37192606438b082a:31062:33)
    at CoroutineImpl.resumeWith_s3a3yh_k$ (http://localhost:9876/absolute/var/folders/cb/nd4gn6pn79zg52rz_l5bl1bdjfnmjy/T/_karma_webpack_293805/commons.js?58a2b80ce49dc5767b060dfe37192606438b082a:31108:17)
    at DispatchedTask.run_mw4iiu_k$ (http://localhost:9876/absolute/var/folders/cb/nd4gn6pn79zg52rz_l5bl1bdjfnmjy/T/_karma_webpack_293805/commons.js?58a2b80ce49dc5767b060dfe37192606438b082a:41652:24)

Trying to make the same request using window.fetch:
val response = window.fetch(url).await()
println("response: ${response.body}")

This fails with:
> Task :jsTestTestDevelopmentExecutableCompileSync
> Task :jsBrowserTest
getFileText before fetch
TypeError: Failed to fetch
TypeError: Failed to fetch
    at 2.doResume_5yljmg(/var/folders/cb/nd4gn6pn79zg52rz_l5bl1bdjfnmjy/T/_karma_webpack_124481/commons.js:3883)
    at <global>.httpGet(/var/folders/cb/nd4gn6pn79zg52rz_l5bl1bdjfnmjy/T/_karma_webpack_124481/commons.js:3765)
    at 1.doResume_5yljmg(/var/folders/cb/nd4gn6pn79zg52rz_l5bl1bdjfnmjy/T/_karma_webpack_124481/commons.js:3845)
    at HtmlResourceLoader.getFileText_6u54xq(/var/folders/cb/nd4gn6pn79zg52rz_l5bl1bdjfnmjy/T/_karma_webpack_124481/commons.js:3920)
    at slambda.doResume_5yljmg(/var/folders/cb/nd4gn6pn79zg52rz_l5bl1bdjfnmjy/T/_karma_webpack_124481/commons.js:992)
    at slambda.invoke_pbb09x(/var/folders/cb/nd4gn6pn79zg52rz_l5bl1bdjfnmjy/T/_karma_webpack_124481/commons.js:978)
    at slambda.$block(/var/folders/cb/nd4gn6pn79zg52rz_l5bl1bdjfnmjy/T/_karma_webpack_124481/commons.js:1023)
    at slambda.doResume_5yljmg(/var/folders/cb/nd4gn6pn79zg52rz_l5bl1bdjfnmjy/T/_karma_webpack_124481/commons.js:3792)
    at slambda.invoke_d6gbsu(/var/folders/cb/nd4gn6pn79zg52rz_l5bl1bdjfnmjy/T/_karma_webpack_124481/commons.js:3778)
    at <global>.l(/var/folders/cb/nd4gn6pn79zg52rz_l5bl1bdjfnmjy/T/_karma_webpack_124481/commons.js:3825)

A: I had to enable cors in Express server.
var express = require('express')
var cors = require('cors')
var app = express()

app.use(cors())

https://expressjs.com/en/resources/middleware/cors.html


text:
Q: xlsxwriter not being able to write to an excel file I was trying to make a basic data collector that will put information in excel and i was successful at doing so with the titles of the data sets but i cant figure out why it cant write the data entered into an excel file. Its far from done and i am fairly new to python (about a month into learning) so if my code looks terrible then my apologies but for any help thank you.
below is my full code and the error message along with it:
import xlsxwriter
import os
file = open("Datasheet.xlsx", "w+")
databook = xlsxwriter.Workbook("Datasheet.xlsx")
data = databook.add_worksheet()

titles = []
masterdata = {}
data_entry = 0
data_filled = 0
project_start = True
while project_start == True:
    data_entires = input("How many data entries will you need? ")
    if data_entires.isdigit() == False:
        print("Sorry that is not a valid input please enter a numerical integer")
        project_start = True
    if data_entires.isdigit() == True:
        project_start = False

while int(data_entires) != data_entry:
    data_title = input("Please enter a title for a dataset ")
    titles.append(data_title)
    data_entry += 1

for value in range(len(titles)):
    data.write(0, value + 1, titles[value])

# dictionary with created lists for the amount of titles made
for i in range(len(titles)):
    dict = masterdata["list " + str(i + 1)] = []

for i in range(len(masterdata)):
    data_in = True
    while data_in == True:
        data = input(f"Please input data for {titles[i]} ")
        data_fill = masterdata["list " + str(i + 1)].append(data)
        fin = input("Do you want to input more data? ")
        if "yes" in fin:
            data_in = True
        if "no" in fin:
            data_in = False

lis = [list(x) for x in masterdata.values()]

for part in lis:
    l = list(str(part))

for value in l:
    data.write(value + 1, value + 1, l[value])

#os.startfile("Datasheet.xlsx")
#databook.close()

Error message : "Traceback (most recent call last):
File "f'{filelocation}'", line 49, in
data.write(value + 1, value + 1, l[value])
AttributeError: 'str' object has no attribute 'write' "


text:
Q: Image of a close set of a continuous function is not necessarily closed Suppose a function $f: [a, b] \rightarrow \mathbb{R}$ which is continuous. What can we say on its image? I thought the image has to be closed, but it seems not true.

A: A continuous function on a closed and bounded segment attains its minimum and maximum values and each value between them. So the image of this closed segment is again a closed segment whose bounds are the minimum and maximum of this function.
See the Bolzano's Theorem.

A: Continuous functions have a property that they map compact sets to compact sets.
That is if $X,Y$ are metric spaces then for any continuous function $f:X\to Y$, the range of $f$ that is the set $f(X)=\{f(x):x\in X  \}$ is compact.
In $\mathbb R$, compact set is equivalent to closed and bounded set. (This follows from Heine-Borel Theorem).
So coming back to your question: $f:[a,b]\to \mathbb R$ is continuous and therefore its range that is the set $f[a,b]=\{f(x):x\in [a,b]\}$ must be compact (equivalently closed and bounded as we are in $\mathbb R$).
So image of your $f$ can't be $\mathbb R,[0,\infty), [0,1)$ or $[1,\infty)$.

A: No. A continuous function maps compact sets to compact sets. To map to sets that are not closed you need a closed set that is not compact; in the case of the real line that means that the set has to be unbounded.

A: To give the most general answer: it does have to be closed because $[a,b]$ is a compact set, images of compact sets under continuous functions are compact (this is trivial to prove), and maps from compact to Hausdorff spaces are closed.


text:
Q: How to get MAC address of a device through a React app? In npm we have a facility called as "get-mac-address" which returns the MAC address as an object. I want it to be embedded in my react web app. I feel difficulty bcoz react ES6 doesn't support var getMacAddress = require("get-mac-address") code.
This link has output in normal js:-get-mac-address.
Could anyone provide the equal react version of it please.


text:
Q: scope of callback in a .connect() (nodejs, mongodb) im trying to use a global database object to handle the data on my nodejs server. It shall contain all data of all connected users. Ready to be accessed anytime out of ram.
Therefore i created a module:
function Database() {
var MongoClient = require('mongodb').MongoClient;
this.dbcon; //database connection

// Connect to the db
MongoClient.connect("mongodb://localhost:27017/dbname", this.givedatabasevars);
};

As i want to reuse the database connection instead of opening new ones everytime i want to access the propertys of my object using the callback function and give them the connection object:
Database.prototype.givedatabasevars = function(err, getdbcon) {
if(err) {console.log(err)};
this.dbcon = getdbcon; //not working(scoped changed when used as callback?)
db.dbcom = getdbcon; //also not working(db object maybe not there yet as its a callback in constructor?)

};

I create the object using this globaly:
var Database = require('./node_modules/database/database.js');
var db = new Database();

Now im pretty new to nodejs and javascript all together. I tryed to get my head around how to access the objects scope, but from within the callback i cant even access the global scope.
Is this even possible?
Its the same for what to do with the data when using .find() with a callback. How do i get the data out of there to be used by my application? I need to store it, not to use it directly.
Regards,
Michael

A: You can access the global object using the global variable. Do console.log(this) on a plain file to see all the globals.
And for mongodb maybe mafintosh/mongojs can give you a more shareable interface. In fact I think with that you don't even need to have a global necessarily ;)


text:
Q: Replacing tag content with html string I have the following xml:
<foo><toReplace/></foo>

I want to replace <toReplace/> tag with the following string:
"bar"

How can I do that?
Right now I have the following code:
var xml = "<foo><toReplace/></foo>";
var parser = new dom.DOMParser().parseFromString(xml, "text/xml");
parser.getElementsByTagName("toReplacce")[0].textNode = "bar";
console.log(parser.toString()); // "<foo><b>bar</b>"

The problem is that is escapes HTML. How can I replace the content with the HTML string here?

A: you can always use the module from npm
var unescape = require('unescape');

console.log(unescape(parser.toString()))

When I tested your code there is a small typo:  (toReplacce instead of toReplace)
var dom = require('xmldom');

var xml = "<foo><toReplace/></foo>";
var parser = new dom.DOMParser().parseFromString(xml, "text/xml");
var a = parser.getElementsByTagName("toReplace")[0];
//console.dir(a);
a.textvalue = "bar";
console.log(parser.toString());


text:
Q: jquery dialog not triggering media queries on IE8 I'm trying to use jquery dialog to pop open a modal with an iframe to another page of the same website.
The problem is with media queries not triggering in IE8 and IE7 when the modal is resized.
(Note: the queries DO work on IE7 and IE8 on other places - thanks to css3-mediaqueries.js library, just not when modal is resized)
The relevant markup is as follows:

Javascript to invoke the jquery dialog
$("#lotrIframe").attr("src", "/leaders-on-the-road/");
$( "#lotrModal" ).dialog({ height: 615, width:800, modal: true });

In the CSS files, there is various media queries used to decrease # of columns depending on the screen size.
@media screen and (max-width: 1155px) {

.record {
    width: 42%;
    margin-left: 5%;
} }

I dont have this problem on any other browser and I know that the media queries do work for me on IE8 and IE7 (if I manually go to leaders-on-the-road, the src page and resize the screen, then the columns ARE being changed)
Anyone have any ideas why dialog resize in IE8 and below is not triggering the media queries when it works everywhere else? I've looked around but haven't hit any relevant posts on this - any assistance is greatly appreciated!


text:
Q: Why my cpp code is showing segmentation fault? I try to develop a solution to this given problem: This code is the solution to: https://www.hackerrank.com/challenges/tree-level-order-traversal/problem.
In short: I have to do a level order teversal of a tree.
Unfortunately, I have a segmentation fault error.
I have been debugging it but stuck! I can't find the problem.
My implementation is the following:
struct que{
    struct node *a;
    int cap;
    int front;
    int rear;
};
struct que* createq()
{
    struct que *q=(struct que *)malloc(sizeof(struct que));
    q->front=-1;
    q->rear=-1;
    q->cap=1;
    q->a=(struct node *)malloc(sizeof(q->cap));
    return q;
}
struct que* resize(struct que* q)
{   q->cap=q->cap*2;
    q->a=(struct node *)realloc(q->a,sizeof(q->cap));
return q;
}
int isempty(struct que* q)
{
    if(q->front==-1&&q->rear==-1)
        return 1;
    return 0;
}
int isfull(struct que* q)
{
    if((q->rear+1)%q->cap==q->front)
        return 1;
    return 0;
}
void insertion(struct que *q,struct node *n)
{
    if(isempty(q)==1)
    {
        q->front=0;
        q->rear=0;

    }
    if(isfull(q)==1)
    {
       q->a=(struct node *)realloc(q->a,q->cap);
    }
    q->a[q->rear]=*n;
    q->rear=q->rear+1;
    q->rear=q->rear%q->cap;

}
struct node* del(struct que *q)
{
   struct node *temp;
    (*temp)=q->a[q->front];
    if(q->front==q->rear)
    {
         q->front=-1;
        q->rear=-1;
        return temp;
    }
    q->front= q->front+1;
    q->front=q->front%q->cap;
    return temp;
}
void levelOrder(node * root) {

  if(root==NULL)
      return;
  struct que *q=createq();
    insertion(q,root);
    struct node *temp;
    while(isempty(q)!=1)
    {
        temp=del(q);
        printf("%d ",temp->data);

        if(root->left!=NULL)
            insertion(q,root->left);
            if(root->right!=NULL)
                insertion(q,root->right);
    }

}

A: q->a=(struct node *)malloc(sizeof(q->cap));

q->a=(struct node *)realloc(q->a,sizeof(q->cap));

Surely sizeof(q->cap), which is equivalent to sizeof(int), is not what you want here.
Also:
struct node *temp;
(*temp)=q->a[q->front];

You need to assign temp a value before you attempt to use its value.


text:
Q: Передача содержимого консоли Python 3 в .txt файл Ежедневно скрипт отправляет на ftp-сервер некий файл. У ftplib есть функция set_debuglevel(). Задал нужный мне аргумент "1" и в консоль красиво начали выводиться сообщения типа:
*cmd* 'USER ftpusr'
*resp* '331 Password required for ftpusr.'
*cmd* 'PASS ********'
*resp* '230 User logged in.'
*cmd* 'CWD r0'
*resp* '250 CWD command successful.'
*cmd* 'TYPE I'
*resp* '200 Type set to I.'
*cmd* 'PASV'
*resp* '227 Entering Passive Mode (192,168,10,67,4,34).'
*cmd* 'STOR 150419'
*resp* '125 Data connection already open; Transfer starting.'
*resp* '226 Transfer complete.'
*cmd* 'QUIT'
*resp* '221 Goodbye.'

Подскажите пожалуйста, как содержимое консоли передать в .txt файлик.
И есть ли возможность замены штатных сообщений на свои? Например не "resp '226 Transfer complete.'", а "Файл успешно загружен!"
Мне необходимо каждый раз удостоверяться, что файл передан на ftp-сервер.

A: Посмотрел в исходники ftplib.py и могу сказать, что тот точно не работает через logger, там через print выводятся сообщения, например:
if self.debugging > 1:
    print('get', self.sanitize(line))`

Как вариант, можно перехватывать вывод в stdout и выводить в файл.
Пример через redirect_stdout:
from contextlib import redirect_stdout
from ftplib import FTP

with open('ftp_log.txt', 'w') as f, redirect_stdout(f):
    # Пример кода взял из https://docs.python.org/3/library/ftplib.html

    ftp = FTP('ftp.debian.org')     # connect to host, default port
    ftp.login()                     # user anonymous, passwd anonymous@

    ftp.cwd('debian')               # change into "debian" directory
    ftp.retrlines('LIST')           # list directory contents

    ftp.retrbinary('RETR README', open('README', 'wb').write)

    ftp.quit()

A: Если скрипт запускается в bash, то можно перенаправить ввод в нужный вам файл с помощью встроенных методов.
Выглядит примерно так:
python your_script > file_name.txt

Судя по описанию, файл запускается с периодичностью, этот вариант может подойти для элементарного сохранения, без изменений в коде библиотеки.
Но рекомендовал бы вам дописать/отредактировать под себя библиотеку сделав свой форк.


text:
Q: Oozie > ssh action > how to add ssh options I am trying to use Oozie ssh action to copy files from a local directory to a remote server. The main problem is that I am using a private key, so I have to use the -i option to define the private key. But the Oozie ssh action does not have the option node, which I can define the -i option.
Is there any workaround for this? Thanks in advance


text:
Q: Visual Basic code- Having trouble displaying the Total. New to VB I have to write a program that calculates costs for a catering company. i have that part down, but whats stumping me is I have trouble displaying the total. What also is stumping me is that i have to make a summary button that adds everything up into a grand total from the previous calculations and display it in a message box. displaying and calculations aren't really my issues, but getting the data to calculate is.
Thank you
HERE's the code.
Const decPRIME_RIB As Decimal = 25.95D
Const decCHICKEN As Decimal = 18.95D
Const decPASTA As Decimal = 12.95D
Const decOPEN_BAR As Decimal = 25D
Const decWINE As Decimal = 8D
Const decBEER As Decimal = 10D

'Declare module-level variables for summary information.
Private TotalDollar As Decimal
Private AmountDue As Decimal
Private SubTotalDecimal As Decimal
Private TotalDecimal As Decimal
Private Guest As Integer
Private EventCountInteger As Integer

Private Sub CalcBtn_Click(sender As Object, e As EventArgs) Handles CalcBtn.Click
    ' Calculate and display the current amounts and add to totals.
    Dim FoodChoiceDecimal As Decimal
    Dim OpenBarDecimal As Decimal
    Dim WineDecimal As Decimal
    Dim DrinksDecimal As Decimal

    ' Find the price.
    If PrimeRB.Checked Then
        FoodChoiceDecimal = decPRIME_RIB
    ElseIf ChickRB.Checked Then
        FoodChoiceDecimal = decCHICKEN
    ElseIf PastaRB.Checked Then
        FoodChoiceDecimal = decPASTA
    End If

    If OpenCB.Checked Then
        OpenBarDecimal = decOPEN_BAR
    End If
    If WineCB.Checked Then
        WineDecimal = decWINE
    End If

    'Multiply price by number of guest and drink selection.
    Try
        DrinksDecimal = (OpenBarDecimal + WineDecimal)
        AmountDue = (FoodChoiceDecimal + DrinksDecimal) * Guest

        ' display totals.
        TotalLbl.Text = TotalLbl.ToString("C")

        ' Allow change for new event.
        OpenCB.Enabled = False
        WineCB.Enabled = False
        ClearBtn.Enabled = True
        SummaryBtn.Enabled = True

    Catch NumberOfGuestsException As FormatException
        MessageBox.Show("Number of Guests must be Numeric", _
        "Data entry Error", MessageBoxButtons.OK, _
        MessageBoxIcon.Information)

    End Try
End Sub

Private Sub SummaryBtn_Click(sender As Object, e As EventArgs) Handles SummaryBtn.Click
    ' Calculate total dollar amounts and number of events.

    Dim MessageString As String
    If EventCountInteger > 0 Then
        ' Calculate the summary sales totals.
        TotalDollar += AmountDue

        'Concatenate the message string.
        MessageString = "Number of Events:" & EventCountInteger.ToString() _
        & Environment.NewLine & Environment.NewLine _
        & "Total Sales: " & TotalDollar.ToString("C")
        MessageBox.Show(MessageString, "Sales Summary", _
        MessageBoxButtons.OK, MessageBoxIcon.Information)
    End If


text: Q: Syntax error: invalid syntax. File ", line 1 I have just started python and stuck in this error. While typing python helloworld.py this error is occurring My helloworld.py file is openning in windows cmd but it's not opening in python.exe


text:
Q: How to block a small IP range in csf I'm looking for a way to block a small ip range in csf, e.g. 151.80.31.103 to 151.80.31.115
I know how to block each ip by issuing a cmmand csf -d IP, but it is a lot more effective to have a way to block a small set of ip range, as the given example.
I have searched for a while, but not finding any relevant information.
Thanks for any hint!

A: If you have SSH access, you can manually edit the file /etc/csf/csf.deny with vim or emacs or your favorite text editor.
Here's a portion of the top of that file with some comments:
# The following IP addresses will be blocked in iptables
# One IP address per line
# CIDR addressing allowed with a quaded IP (e.g. 192.168.254.0/24)
# Only list IP addresses, not domain names (they will be ignored)
#
# Note: If you add the text "do not delete" to the comments of an entry then
# DENY_IP_LIMIT will ignore those entries and not remove them

Given that information, use a subnet calculator (such as this one from MXtoolbox) to determine the smaller subnet. Given your criteria, one possible subnet suggested by mxtoolbox would be 151.80.31.96/27, which would filter everything from 151.80.31.96 through 151.80.31.127.
Make sure that you restart CSF afterwards with csf -r and then restart lfd with lfd -r.


text:
Q: Delphi ClientDataSet - Delete Operation - Why is it so slow? I'm using TClientDataSet in an application for managing a load of data imported from multiple CSV files. This can be a million or more entries in total. I want to be able to delete all the dataset entries associated with a particular CSV file but the time to delete large numbers of items is cripplingly slow.
As a test to try and work out if I was doing something stupid I created a simple console application. All it does is:

*

*Create a TClientDataSet instance with 1 field defined (ID):
CDS := TClientDataSet.Create(nil);
 CDS.FieldDefs.Add('ID', ftInteger);
 CDS.CreateDataSet;
 CDS.LogChanges := False;

*Append 100,000 items (takes 0.1 seconds):
for i := 1 to 100000 do
 begin
  CDS.AppendRecord([i]);
 end;

*Delete 50,000 items (takes ~4 secs, or ~4.4 secs with LogChanges=TRUE):
CDS.First;
 while CDS['ID'] <= 50000 do
  CDS.Delete;
If I had 1.5M items in my dataset and wanted to remove 0.5M entries it would take so long to delete items by this method that I can't even measure it.
As a workaround for now I'm having to create a new dataset, then copy all the items that I want to keep to the new copy and delete the original copy. Unless I am only removing a small % of entries from the original dataset this method is much faster.
Perhaps I am not using the most appropriate method for trying to remove items from the dataset? I am guessing it is triggering a bunch of internal processing with every item I delete. Is there some method to delete a range of items at once that I am missing? Perhaps I can set an index and a range based on that index, and then delete all the items in the current range with one operation?
Maybe the problem is with ClientDataSet and not me? Perhaps I need to use a different component. Any suggestions?

A: Thought I might as well provide details of my own (temporary/maybe permanent?) workaround in case anyone with the same problem is interested.
PROBLEM: Delete a large proportion of records from a large TClientDataSet (100k or more records) takes a long time when using the Delete operation in comparison to initial time for adding the items (factor of 40 or more).
SOLUTION: Copy all the records you do not wish to delete to a new dataset, then delete the original. [Downsides: Loss of changelog, extra RAM requirements?]
var
 CDS: TClientDataSet;

// initialize new CDS instance
function CreateNewCDSInstance: TCLientDataSet;
begin
 Result := TClientDataSet.Create(nil);
 Result.FieldDefs.Add('ID', ftInteger);
 Result.CreateDataSet;
 Result.LogChanges := False;
end;

// close + free CDS instance
procedure CloseCDS;
begin
 CDS.EmptyDataSet;
 CDS.Close;
 CDS.Free;
end;

// delete current record?
function CanDeleteCurrentRecord: boolean;
begin
 Result := CDS['ID'] < 50001; //in this simple example
 // in my application it would be more like:
 // "CDS['FILE_ID'] = AFileIDToDelete"
end;

// delete block of records:
procedure DeleteRecords;
var
 aNewCopy: TClientDataSet;
begin
 aNewCopy := CreateNewCDSInstance;
 CDS.First;
 while not CDS.EoF do
 begin
  if not CanDeleteCurrentRecord then
  begin
   // NB: AppendRecord takes array of values corresponding to field defintions
   aNewCopy.AppendRecord([CDS['ID']]);
  end;
  CDS.Next;
 end;
 CloseCDS;
 CDS := aNewCopy;
 //NB: If you have any aggregates/indexes defined, they must be redefined
end;

Using the example given above this method of removing 50k items takes 94 ms instead of ~4 secs.
However, while asking this question and reading through the comments it has become obvious to me that this solution is more of a bandage than a cure. The bigger problem is that the system I'm working on isn't really well designed to handle the amount of data it needs to. Perhaps it is not so much "problem with TClientDataSet" as "problem with how we're using TClientDataSet"! Even with the fix for delete speed there will still be issues with performance for importing increasingly large size and quantity of files and managing that data down the line.
Perhaps (on a rainy day!) I will start looking at an approach akin to SilverWarior's suggestion of using a separate dataset to hold each imported file, instead of splurging all the data out into one huge memory table. Then deleting a file just becomes deleting the dataset - among other potential benefits.


text:
Q: Display Django time variable as full hours, minutes am/pm I want to use a time variable instead of a CharField for a model, which displays multiple saved times. My issue is it displays as "9 am" instead of "9:00 am", and "noon" instead of "12:00 pm".
Can anyone help? Thanks in advance.
Relevant code below-
models.py
class Post(models.Model):
time=models.TimeField()
free=models.CharField(max_length=50, default="")
player1=models.CharField(max_length=50, default="Player 1")
player2=models.CharField(max_length=50, default="Player 2")
player3=models.CharField(max_length=50, default="Player 3")
player4=models.CharField(max_length=50, default="Player 4")

def __str__(self):
    return self.time

HTML
 <h7>{{post.time}}     Update</h7>

A: You can try using built in date template tag.
{{ post.time|date:'H:i A' }}

A: You can achieve this by just using the built-in template datetime format like so:
{{ post.time|date:"h:i A" }}
This will display the datetime as: 09:00 AM. You can read more about this in the Django docs.


text:
Q: How to convert this html table to div? can anyone advise how do i convert the below html table into div? I tried to do some googling but not able to find a specific examples on this. Would appreciate if anyone can provide me with some sample codes or point me to the right direction.
Thanks

                        List of news

                        Title

                        :

                        Name of title

                        Description

                        :

                        Content of description

A: Live demo : http://jsfiddle.net/satinder_singh1/TdAWY/
demo with content
http://jsfiddle.net/satinder_singh1/TdAWY/1/

            sd

s

 s

s

s

 s

s

.c1
{
float:left;

}

.headDiv
{
width:100%;
border:1px soild blue;
}
.w75
{
width:75%;
height:50px;

border-bottom:1px solid;
}
.w20
{
width:20%;
height:50px;

border-bottom:1px solid;
}
.w5
{
width:5%;
height:50px;
background-color:Yellow;
border-bottom:1px solid;
}

.w1
{
width:100%;
height:50px;
background-color:pink;
border-bottom:1px solid;
}

A: Use tabletodivconverter.com/ to convert html tables to div.


text:
Q: Algorithm to dynamically populate Javascript array with zeros before and after values I get a data of months dynamically with python/django and pass it to my template. There I use Javascript to manipulate the data
That means that in my template I have a javascript array, each number representing a month like so:
months = [1,2,3,4]
or so:
months = [4,5,6]
or so:
months = [6,7,8]
Depending on the array above I'd like to populate the missing positions with zeros. Missing positions means that the array should have a length of 12 at the end. Each month should be at the accurate position. For example:
months = [1,2,3,4,0,0,0,0,0,0,0,0]
or so
months = [0,0,0,4,5,6,0,0,0,0,0,0]
or so
months = [0,0,0,0,0,6,7,8,0,0,0,0]
I tried many things. Splicing seemed a good method but didn't work as expected. I couldn't solve it using Array.fill. I also tried to create a new array with 12 zeros and then pushing the values of the other array into it, but it didn't work.
Can somebody point me into the right direction or has an idea? Very much appreciated.

A: You could take a new array and fill it with the items on the index, if found or with zero.

const fill = m => Array.from({ length: 12 }, (_, i) => +m.includes(i + 1) && i + 1);

console.log(...fill([1, 2, 3, 4]));
console.log(...fill([4, 5, 6]));
console.log(...fill([6, 7, 8]));

A: Make a list of the 12 months
true_months = [1,2,3,4,5,6,7,8,9,10,11,12] (or true_months = list(range(1,13)))
then your variable
months = [4,5,6]
and by a simple if/else in a for
[x if x in months else 0 for x in true_months]
will return
[0, 0, 0, 4, 5, 6, 0, 0, 0, 0, 0, 0]

A: You may map empty array of 12 items, checking if month number is present within your source array:

const padZeroes =  arr => [...Array(12)].map((item,index) => arr.includes(index+1) ? index+1 : 0);

console.log(padZeroes([5,6,7,8]));


text:
Q: Javascript reference object by an identifier or reference it directly? I am creating quite many objects in Javascript, which I need to be able to reference to retrieve later, for example through an array. Now I am wondering how to save the object reference in the array.
The objects will interract with an external library, which can function either with object IDs or the object itself. I know Javascript treats object variables like pointers and not object copies, so is it safe to reference the objects directly ?
At first I was thinking "if I save the IDs of the objects, that would keep memory usage low", but is this true ? How much memory does an object variable* consume versus an integer variable ?
*the pointer to the object, not the object data
Also, if saving the objects directly is the way to go, is it ok to use array.push() to add the new object to the array ? Is array.push() creating a copy or does it work like a variable ?

A: Yes, you can reference the objects directly. If you really care about memory usage, I'd say the way of passing the ids will use more memory since you'll have to maintain another set of mappings.
Passing the objects directly will let the JavaScript engine to work directly with the object references. That's not affecting the memory usage, as long you don't to any cloning.

A: I believe the relevant question is weather or not saving an integer and using that as an identifier later is more effective than saving a reference to the object.
I'd go with the reference in an array. the size of a reference vs a number is going to be negligible.


text:
Q: Inheritance of JPA Entities I have a question.
Lets say I have an Entity Class called BaseEntity. I annotate this class with @Entity as follows.
@Entity
public class BaseEntity implements Serializable {
    .....
}

If I write another class called Employee that extends BaseEntity as
public class Employee extends BaseEntity{
    ....
}

and I do not annotate it with @Entity, will my employee class have Entity like behaviour?
What I mean to ask is will it become an Entity because its extending my BaseEntity
Or should I always need to annotate a class with @Entity to get Entity like behaviour?

A: Yes, you have to annotate it as entity. But for your base class you can use @MappedSuperclass, so that no table is required for it

A: You have to annotate it (or mark it in orm.xml) as an Entity ... for all classes that are required to be persistable


text:
Q: How to get the longest word and the most frequent word starting with a specific letter? Given a list of words and their count like this:
2 you
1 polka
2 dress
3 are
4 world

I would like to write 2 Bash piped commands which will give me:

*

*The longest word starting with the letter 'a'

*The most frequent word that starts with 'a'.
I was thinking to do it with sed grep ^a but I don't know how to write the rest of the piped command.

A: To get the longest word, we can use awk's length function. Then sort, then head and cut to get the right line and field.
awk '$2~/^a/ {print length($2), $2}' file | sort -k1 | head -1 | cut -d" " -f1

To get the most frequent A-word, a sort and awk:
sort -k1 file | awk '$2~/^a/ {print $2; exit}'

In real life I'd probably avoid piping things around so much. I'd probably do each in a single awk. Hard to say whether they'd actually perform faster though. awk is flexible but not that fast.
awk 'BEGIN{lc=0;lw=""} $2~/^a/ {l=length($2); if (l>lc){lc=l;lw=$2}} END{print lw}' file
awk 'BEGIN{fc=0;fw=""} $2~/^a/ {if ($1>fc){fc=$1;fw=$2}} END{print fw}' file

A: Here's a solution without the requirement of using a pipe using AWK:
awk '$2~/^a/{if(length($2)>length(x))x=$2}END{print x}' in
awk '$2~/^a/{if($1>x[0]){x[0]=$1;x[1]=$2}}END{print x[1]}' in

Using Perl:
perl -lane '$F[1]=~/^a/||next;if(length($F[1])>length($x)){$x=$F[1]};END{print($x)}' in
perl -lane '$F[1]=~/^a/||next;if($F[0]>$x[0]){$x[0]=$F[0];$x[1]=$F[1]};END{print($x[1])}' in

% cat in
2 you
1 polka
2 dress
3 are
4 world
1 abcd
4 abc
% awk '$2~/^a/{if(length($2)>length(x))x=$2}END{print x}' in
abcd
% awk '$2~/^a/{if($1>x[0]){x[0]=$1;x[1]=$2}}END{print x[1]}' in
abc
% perl -lane '$F[1]=~/^a/||next;if(length($F[1])>length($x)){$x=$F[1]};END{print($x)}' in
abcd
% perl -lane '$F[1]=~/^a/||next;if($F[0]>$x[0]){$x[0]=$F[0];$x[1]=$F[1]};END{print($x[1])}' in
abc

A: Assuming the file is foo:

*

*The longest word with a
% awk '$2 ~ /^a/ {print length($2),$2}' foo | sort | tail -n1
3 are

*The most frequent word with a
% awk '$2 ~ /^a/ {print $1,$2}' foo | sort | tail -n1
3 are

On the other hand, why necessarily pipes? It's an absurd requirement.


text:
Q: dynamic Url.Content I am trying to build a website in C# using MVC3 with Razor. I have to build it with themes, but I have problems setting a dynamic content to Url.Content, like it follows:

and I would like to set the value of THEME-NAME from my code. Let's say from an Application object. Is it possible?
Thanks.

A: Give the ViewBag a shot.
in your controller action I would put :
ViewBag.ThemeName = "SomeName";

in your view :

A: Would something like the code show below work for you? did not test it but may lead you in the right direction.
var themName = somevalue
var urlValue = "~/Content/themes/" + @themeName + "/images/logo.png"


text:
Q: Is there an OpenWRT feature for tracking internet data usage per user? Is there an OpenWRT feature or package I can install that would allow me to track internet data usage per user? I'm thinking of a system that requires all devices to login with a username and password so their internet data usage can be tracked regardless of device.

A: take a look at this: wrtbwmon.

A small shell script designed to run on linux powered routers
(OpenWRT, DD-WRT, Tomato, and other routers where shell access is
available). It provides per user bandwidth monitoring capabilities and
generates usage reports.

You might need only that, but i haven't tried it yet.
I got the reference from here: Bandwidth Monitoring.

A: You need to install a "port mirroring" package to forward network packets to another computer.
So you can setup an internet monitoring program to record internet activities.
http://code.google.com/p/port-mirroring/

A: You could try Coova Chilli
It is easy to install and has a lot of features. You can authenticate by mac address or by username and password and you can also create rules to limit peoples bandwidth or give them a daily allowance.
It create a web based captive portal for your users when they try to connect to the internet. Warnign: You will need to be comfortable with editing the settings on the command line for this to work well, but there are lots of tutorials out there.


text:
Q: Local notification crashes app android java My app crashes when I try to open it from local notification.
Notification should be sent after 5 seconds, but sometimes it does so, sometimes it takes longer, sometimes it is not sent at all.
public void sendPushNotificationUpdate() {
    new Print("SEND NOTIFICATION");

    AlarmManager service = (AlarmManager) getSystemService(Context.ALARM_SERVICE);
    Intent i = new Intent(MyService.this, LocalNotification.class);
    i.addFlags(Intent.FLAG_ACTIVITY_NEW_TASK);
    PendingIntent pending = PendingIntent.getBroadcast(MyService.this, 0, i, PendingIntent.FLAG_CANCEL_CURRENT);
    Calendar cal = Calendar.getInstance();
    // Start 1 month after boot completed
    cal.add(Calendar.SECOND, 5);
    new Print("send notification at " + cal.getTime());
    //
    // Fetch every 1 month
    // InexactRepeating allows Android to optimize the energy consumption
    // service.setInexactRepeating(AlarmManager.RTC_WAKEUP ,cal.getTimeInMillis(), AlarmManager.ELAPSED_REALTIME , pending);
    service.setRepeating(AlarmManager.RTC_WAKEUP, cal.getTimeInMillis(), AlarmManager.INTERVAL_HOUR, pending);
}

////////////////////////////////////////////////////////////////////////////////
 Intent notificationIntent = new Intent(context, MainActivity.class);
        notificationIntent.addFlags(Intent.FLAG_ACTIVITY_CLEAR_TOP |
                Intent.FLAG_ACTIVITY_SINGLE_TOP |
                Intent.FLAG_ACTIVITY_NEW_TASK);

        TaskStackBuilder stackBuilder = TaskStackBuilder.create(context);
        stackBuilder.addParentStack(MainActivity.class);
        stackBuilder.addNextIntent(notificationIntent);

        PendingIntent pendingIntent = stackBuilder.getPendingIntent(0, 0);

        NotificationCompat.Builder builder = new NotificationCompat.Builder(context);
        Uri soundUri = RingtoneManager.getDefaultUri(RingtoneManager.TYPE_NOTIFICATION);

        Notification notification = builder
                .setSmallIcon(R.mipmap.ic_launcher)
                .setContentTitle("TEST")
                .setContentText(title)
                .setSound(soundUri)
                .setAutoCancel(false)
                .setStyle(new NotificationCompat.BigTextStyle()
                        .bigText(title))
                .setPriority(Notification.PRIORITY_MAX)
                .setContentIntent(pendingIntent).build();

        NotificationManager notificationManager = (NotificationManager) context.getSystemService(Context.NOTIFICATION_SERVICE);
        notificationManager.notify(0, notification);

Since I send the notification this is what the log shows:
I/System.out: RECEIVE LOCAL NOTIFICATION
   I/System.out: DISABLE SERVICEEEEEEEEEEEEEEEEEEEEEEEEEEEE
   I/System.out: Database exists
   D/Background mode ->: VERIFY INTERNET CONNECTION
   D/Background mode ->: NO CONNECTION AVAILABLE
   I/System.out: DELEGATE STARTS
   V/FA: onActivityCreated
   V/ztgl: asset != NULL
   V/ztgl: asset != NULL
   V/ztgl: asset != NULL
   V/ztgl: asset != NULL
   V/ztgl: asset != NULL
   W/SQLiteConnectionPool: A SQLiteConnection object for database '/data/data/com.test/databases/db.db' was leaked!  Please fix your application to end transactions in progress properly and to close the database when it is no longer needed.
   V/ztgl: asset != NULL
   V/ztgl: asset != NULL
   V/ztgl: asset != NULL
   V/ztgl: asset != NULL
   V/ztgl: asset != NULL
   V/ztgl: asset != NULL
   V/ztgl: asset != NULL
   V/ztgl: asset != NULL
   V/ztgl: asset != NULL
   V/ztgl: asset != NULL
   V/ztgl: asset != NULL
   V/ztgl: asset != NULL
   V/ztgl: asset != NULL
   V/ztgl: asset != NULL
   V/ztgl: asset != NULL
   V/ztgl: asset != NULL
   V/ztgl: asset != NULL
   V/ztgl: asset != NULL
   V/ztgl: asset != NULL
   V/ztgl: asset != NULL
   V/ztgl: asset != NULL
   V/ztgl: asset != NULL
   V/ztgl: asset != NULL
   V/ztgl: asset != NULL
   V/ztgl: asset != NULL
   V/ztgl: asset != NULL
   V/ztgl: asset != NULL
   V/ztgl: asset != NULL
   V/ztgl: asset != NULL
   I/System.out: Between 22.02.2017 - 10:50 and 22.02.2017 - 11:20 there are:
   I/System.out: 0 days, 0 hours, 30 minutes, 0 seconds
   V/FA: Using measurement service
   V/FA: Connecting to remote service
   V/FA: Activity resumed, time: 182309534
   I/Choreographer: Skipped 30 frames!  The application may be doing too much work on its main thread.
   D/Background mode ->: Service destroyed
   I/System.out: Between 22.02.2017 - 10:50 and 22.02.2017 - 11:20 there are:
   I/System.out: 0 days, 0 hours, 30 minutes, 0 seconds
   I/Process: Sending signal. PID: 20941 SIG: 9

////////////////////////////////////////////////
that's what I have at the moment. I've had a look around on the internet but couldn't find anything to solve my problem.
thanks for your help.
Unlike Unfortunately MyApp has stopped. How can I solve this? , I'm asking a specific question regarding local notification. @Vlad Matvienko

A: See this line:

A SQLiteConnection object for database
  /data/data/com.test/databases/db.db was leaked! Please fix your
  application to end transactions in progress properly and to close the
  database when it is no longer needed.

This means you have previously used database, and didn't close that object. Now you are leaking database. Properly handle database object state.


text:
Q: Xtext: Content assist for indent aware languages For xtext languages to become indent aware, synthetic tokens are used as described here. But, at the indented locations, content assist is not proposing anything unless the first letter is typed.
For example, consider the following grammar:

Model:
 lines += Line+;

Line:
  'model' name=ID
  BEGIN
   type=(Type1 | Type2 | Type3)
  END
;

Type1:
'type1:' attr=ID;

Type2:
'type2:' attr=ID;

Type3:
'type3:' attr=ID;

// The following synthetic tokens are used for the indentation-aware blocks
terminal BEGIN: 'synthetic:BEGIN';  // increase indentation
terminal END: 'synthetic:END';      // decrease indentation

Now, after typing model and a new line and a tab, content assist does not prompt anything. But, if I type t and then ask for content assist, I get type1, type2 and type3.
Why does the content assist work only upon partial typing?

A: Your grammar rule states that the type information is mandatory between BEGIN and END tokens in the rule Line. I would assume that the parser is showing strange error recovery behavior if you omit the type there. It'll probably help if you mark the type as optional.


text:
Q: IIS-like UI for http.sys programs Does anyone know if there is a open-source or built-in way to view ALL IIS and http.sys endpoints/sites via a GUI?
The problem I have is that I'm a little wary of having no visibility for http.sys applications (e.g. SQL Reporting Services 2008) and their status, logs, security settings, etc.  I know there is documentation how to do this via command line and registry hacks but it seems there has to be a better way.

A: HTTP Server API Configuration, is a GUI tool that lists endpoints and allows you to set ACLs. The author 'Nicolas Dorier' also has a nice article 'Demystify http.sys with HttpSysManager' on CodeProject.com which describes his tool.

A: I hope this command can help you.
netsh http show urlacl


text:
Q: Angular 13 - Cannot use namespace as a type.ts(2709) Am working on angular 13 version.Trying to import and use action file inside a .spec file shows  an error like below
Cannot use namespace 'MyActions' as a type.ts(2709)

This is my spec file
import * as MyActions from '../../core/store/action/my.actions';
describe('MyActionComponent', () => {
  let myActions: MyActions;

Please excuse for full source code.
Thanks in advance

A: MyAction is a namespace and not a type, hence the error.
You object can only be of type coming from said namespace (or any other namespace). You may want to use an exporting interface of the namespace:
import * as MyActions from '../../core/store/action/my.actions';

describe('MyActionComponent', () => {
    let myActions: MyAction.SomeInterface
    ...
});


text:
Q: Function that returns a hidden state given a set of observations using Python Hmmlearn Multinomial I have been stuck on a problem regarding a python function using Multinomial HMM (from hmmlearn) for a while...
The general idea is for the HMM be capable of finding the hidden state (0, 1 or 2) given a set of observations where each is composed by 4 arrays of 0s and 1s.
Example:
#For a set of observations:

c1 = [0,1,1,0,0,0,1]
c2 = [0,0,0,0,1,1,0]
c3 = [0,0,0,1,1,0,1]
c4 = [0,0,0,0,1,1,1]

observation = [c1 , c2, c3, c4]

#Which state will be the next hidden state
state = 1 or state = 2 or state = 3

Currently my code is the following:
#Observations
c1 = [0,0,0,0,0,0,0,0,0,0,0,0,0,0,1,1,1,1,1,1,1,1,1,1,0,0,0,0,0,0,0,0,0]
c2 = [0,0,0,0,0,0,0,0,0,0,1,1,1,1,1,1,1,0,0,0,0,0,1,1,0,0,0,1,0,0,0,1,0]
c3 = [0,0,0,0,0,0,0,0,1,1,1,1,1,1,1,1,1,1,1,1,1,0,0,0,0,1,0,0,0,0,0,0,0]
c4 = [0,0,0,0,0,0,0,0,0,0,1,1,1,1,0,0,1,1,1,1,0,0,0,0,1,1,1,0,0,1,1,1,0]

#Train
model = hmm.MultinomialHMM(n_components=3, verbose=True)
model.n_features_=2
model.fit([c1,c2,c3,c4])

#Predict
pred = model.predict([[0],[1],[0],[0]])
print(pred)

The issue is that this outpus an array (for example: [1 2 0 1]) and my goal is for it to return just either 0,1 or 2... ([1]).
Any feedback, ideas or help are well received,
Thank you in advance.


text:
Q: Why this simple keras 3 class classifier is predicting only one class instead of other classes? I am trying to create a simple 3 class deep learning classifier using keras as follows:
clf = Sequential()
clf.add(Dense(20, activation='relu', input_dim=NUM_OF_FEATURES))
clf.add(Dense(10, activation='relu'))
clf.add(Dense(3, activation='relu'))
clf.add(Dense(1, activation='softmax'))

# Model Compilation
clf.compile(optimizer = 'adam',
             loss = 'categorical_crossentropy',
             metrics = ['accuracy'])

# Training the model
clf.fit(X_train,
         y_train,
         epochs=10,
         batch_size=16,
         validation_data=(X_val, y_val))

How after training while predicting, it is only predicting the same class (class 1) out of the 3 classes ALWAYS.
Is my network architecture not correct?
I am new to deep learning and AI.

A: If you want a network to classify three classes, your last dense layer should have three output nodes. In the example, the last dense layer has one output node.
clf = Sequential()
clf.add(Dense(20, activation='relu', input_dim=NUM_OF_FEATURES))
clf.add(Dense(10, activation='relu'))
clf.add(Dense(3, activation='relu'))
clf.add(Dense(3, activation='softmax'))

For each input sample, the output will be three values, all of which sum to one. These represent the probabilities that the input belongs to each class.
Regarding the loss function, if you want to use cross entropy, you have a choice between sparse categorical cross entropy and categorical cross entropy. The latter expects ground truth labels to be one-hot encoded (you can use tf.one_hot for this). In other words, the shape of the labels is the same as the shape as the network's output. Sparse categorical cross entropy, on the other hand, expects labels with a rank N-1, where N is the rank of the neural network's output. In order words, these are the labels before one-hot encoding.
When the model is used for inference, the predicted class values can be retrieved with argmax of the last dimension of the predictions.
predictions = clf.predict(x)
classes = predictions.argmax(-1)