text:
Q: When I work with ubuntu 18.04 server on aws, I get this error When I work with ubuntu 18.04 server on aws, I get this error
I tried to delete monog from the server and then install it from the beginning, but it gives me this error

I've searched google stackoverflow and other places but to no avail


text:
Q: Synchronization between two sql express server I need to be able to sync mainDB server with clientDB server,whenever client press sync button. Whenever conflict occurs i want to preserve insertion/deletion made by both client and master.I'm using sync framework.
EDIT
Auto increment primary key creates problem.Is it necessary to use GUID/UUID as primary key.Or is there any other solution?

A: If you only have two SQL Server Express Edition instances then your best option is Sync Framework since Merge Replication requires at least one instance to be Standard Edition or higher to act as the Publisher.  A SQL Server Express Edition instance can only function as a Subscriber.
If you have a Standard Edition or higher license then Merge Replication would be the easiest solution to achieve your goal.

redpajama_set_name: RedPajamaStackExchange


text:
Q: Dash icons Not Showing properly in Menu Using Wordpress The Mega Menu plugin works well except when activated it affects But some WordPress Dash icons not showing properly.
I have already installed cache plugins like Autoptimize and WP Rocket as well.
After clear cache from admin side but don't work till now. Also not giving any error in the Browser console.
URL: https://www.socomtactical.net
Max Mega Menu Plugin: https://wordpress.org/plugins/megamenu/
Note: I can't use Elemetor on my Website.
Screenshot:

Please let me know what is actually issue?
Thank you.

A: If you want to add Dashicons on WordPress frontend, you will need to enqueue them using PHP code in your theme functions.php file:
/* Add Dashicons in WordPress Front-end */
add_action( 'wp_enqueue_scripts', 'load_dashicons_front_end' );
function load_dashicons_front_end() {
   wp_enqueue_style( 'dashicons' );
}

Sample :
<i class="dashicons dashicons-admin-comments"></i>

Chose icon


text:
Q: is there a simple way to check if 2 floats are approximately equal? In LUA, is there a way to check if it floats are approximately equal?

A: Just set a threshold value. If the difference between two values is less than the threshold, consider them equal:
a = 1.23456789
b = 1.23456777

threshold = 0.000001

diff = math.abs(a - b) -- Absolute value of difference
print(diff < threshold) -- True if difference is less than threshold

Output:
true

A: You also compare their decimal representations:
function decimal(x)
  return string.format("%.3f",x)
end

print(decimal(x)==decimal(y))


text:
Q: Android BLE API strange behavior I connect to my Bluetooth Low Energy device like it's described in : https://developer.android.com/guide/topics/connectivity/bluetooth-le.html

*

*I get device:
@Override
public void onLeScan(final BluetoothDevice device, final int rssi, final byte[] scanRecord) {

    if(device.getName().startsWith("BLE device")){
        mDevice = device;
        mDevice.connectGatt(RGBLight.this, false, bgc);

    }
}

*Getting a gatt from Device:
public void onConnectionStateChange(final android.bluetooth.BluetoothGatt gatt, int status, int newState) {
    if (newState == BluetoothProfile.STATE_CONNECTED) {
       //My app should keep connection to the BLE device as long as app lives.
        RGBLight.this.gatt = gatt;
        gatt.discoverServices();
    }
}

3.When gatt is connected and services are discovered i'm trying to send a messages queue to the characteristic.
new Thread(new Runnable() {

        @Override
        public void run() {

            if (mService == null)
                mService = gatt.getService(UUID_SERVICE);
            if (mCharacteristic == null)
                mCharacteristic = mService.getCharacteristic(UUID_CHAR);

            for(int i = 0; i < 100; i++){

                int r = Color.red(colorParsed);
                int g = Color.green(colorParsed);
                int b = Color.blue(colorParsed);
                int br = Color.blue(brParsed);

                mCharacteristic.setValue(new byte[] { COMMAND_SET_RGBW, (byte) r, (byte) g, (byte) b, (byte) br, 0, 0, 0, 0 });
                gatt.writeCharacteristic(mCharacteristic);

                TimeUnit.MILLISECONDS.sleep(100);
                }
            }

    }).start();

When i run this code, most of commands are missed. Execution speed is about 1 command per second. And there is an error in LogCat:
     06-23 12:34:25.627: E/bt-btif(18002): already has a pending command!!

This low speed worsens user experience of my app.
I investigated a few days and found very interesting behavior. If I start the app and quickly send message queue, it works fast.(1 command per 100ms). But after 10-15 seconds after start it begin to slow down and error message occures again:
     06-23 12:34:25.627: E/bt-btif(18002): already has a pending command!!

Maybe someone already faced with a such problem and there is a way to reset a message queue  with Android API or something else.

A: You MUST wait for onCharacteristicWritten before you continue or you flood the buffers. That gatt.write characteristic returns merely means it is on its way through the ble stack and air.


text:
Q: Changing the mouse cursor on an iframe I want to cancel the mouse cursor from hand to default (where that white arrow appears instead). I have a simple iframe..but I think that there is a link inside the iframe that causes the cursor to change to pointer/hand.. how do I change that behavior?
This doesnt work:
iframe{
        cursor:default;
    }

A: If you have access to the CSS of iframe src. Add -
a{ cursor: default; } //in iframe src CSS

if not you can do this with jquery if the iframe is in the same domain -
$("#iframe").contents().find("a").css('cursor', 'default');

EDIT:
If it is facebook like button then check this facebook developer portal, it gives you options to style its components -
http://developers.facebook.com/docs/reference/plugins/like/


text:
Q: What is the most straightforward way to assign html to an HTML element? I have an html file in my project's Contents folder. I have a div with an ID of "FictionContent" that I want to assign the contents of that HTML file.
Is the following a good way to do that:
$('#FictionContent').html('Content/huckfinn.html');

?
Will the jQuery understand "Content" as a subfolder and thus know where to grab the html? If not, what is a workaround for doing something as similar as possible?

A: Two examples over here:
Content from a variable
var mycontent = "Hello World";
$('#FictionContent').html(mycontent);

Content from your html file
$('#FictionContent').load('Content/huckfinn.html');

A: Try this:
$('#FictionContent').load('Content/huckfinn.html');


text:
Q: Relationship between differential twisted with complex structure and $\partial$, $\bar\partial$ on a complex manifold Let $(M,J)$ be a complex manifold and $d^c := - J d J$, where $J$ acts on forms by acting on their arguments and does nothing to functions. I have seen the claim that $d^c$ is proportional to $\partial - \bar \partial$. I can't find this again anywhere and I'm wondering why it holds.
I thought of using that if $Q$ denotes complex conjugation, then $Q \bar\partial Q = \partial$. If this would hold for $J$ instead of $Q$, using that $\partial^2 = \bar\partial^2 = \bar\partial \partial + \partial \bar\partial = 0 $ it would follow immediately that $ d^c = \bar\partial - \partial$. But I don't see why $J \bar\partial J = \partial$ - I think this might be false.

A: As you said, $J$ acts on a form by acting on the inputs. If $\alpha$ is a $(p, q)$-form, then it takes $p + q$ vector fields as inputs, and by linearity we can reduce to considering the case where each vector field is either a vector field of type $(1,0)$ or $(0,1)$. In this restricted case, $\alpha$ can only evaluate to something non-zero when there are $p$ vector fields of type $(1,0)$ and $q$ of type $(0, 1)$. If $X$ is a vector field of type $(1, 0)$, then $JX = iX$, while if $Y$ is a vector field of type $(0, 1)$, we have $JY = -iY$. Therefore, if $X_1, \dots, X_p$ are vector fields of type $(1, 0)$ and $Y_1, \dots, Y_q$ are vector fields of type $(0, 1)$, then
\begin{align*}
(J\alpha)(X_1, \dots, X_p, Y_1, \dots, Y_q) &= \alpha(JX_1, \dots, JX_p, JY_1, \dots, JY_q)\\
&= \alpha(iX_1, \dots, iX_p, -iY_1, \dots, -iY_q)\\
&= i^p(-i)^q\alpha(X_1, \dots, X_p, Y_1, \dots, Y_q)\\
&= i^{p-q}\alpha(X_1, \dots, X_p, Y_1, \dots, Y_q).
\end{align*}
Therefore $J\alpha = i^{p-q}\alpha$ so
\begin{align*}
-JdJ\alpha &= -Jd(i^{p-q}\alpha)\\
&= -i^{p-q}Jd\alpha\\
&= -i^{p-q}J(\partial\alpha + \bar{\partial}\alpha)\\
&= -i^{p-q}(J\partial\alpha + J\bar{\partial}\alpha)\\
&= -i^{p-q}(i^{(p+1)-q}\partial\alpha + i^{p-(q+1)}\bar{\partial}\alpha)\\
&= -i\partial\alpha + i\bar{\partial}\alpha\\
&= -i(\partial - \bar{\partial})\alpha.
\end{align*}
That is $d^c = -JdJ = -i(\partial - \bar{\partial})$.


text:
Q: register a copy of the process with windows registry for multi threading I am trying to run a program that can only run on one core. I have a 12 core machine and I had this idea, possibly wrong, that I could maybe register the program multiple times with windows registry and convince windows that its 12 different programs and in the end run it on all cores.
Has anyone tried something like this before because I haven't been successful with this yet. The program I have has a lot of subkeys and is it possible to just copy the whole key structure instead of doing it one by one ?

A: Look into application virtualization.  Something like VMWare ThinApp would do what you want.  The additional overhead would be more than worth the simplicity of deployment IMO.
http://en.wikipedia.org/wiki/Application_virtualization


text:
Q: i am trying to install apache and mysql server on ubuntu 16 please can someone tell me why my terminal ins showing :
root@prince-HP-ProBook-6470b:~# apt-get install mysql-server mysql-client
Reading package lists... Done
Building dependency tree
Reading state information... Done
The following packages were automatically installed and are no longer required:
  galera-3 iproute libdbd-mysql-perl libdbi-perl libjemalloc1
  libmariadbclient18 libmysqlclient18 libreadline5 mariadb-common socat
Use 'sudo apt autoremove' to remove them.
The following additional packages will be installed:
  mysql-server-5.7
Suggested packages:
  mailx tinyca
The following NEW packages will be installed:
  mysql-client mysql-server mysql-server-5.7
0 upgraded, 3 newly installed, 0 to remove and 4 not upgraded.
Need to get 0 B/2,592 kB of archives.
After this operation, 48.6 MB of additional disk space will be used.
Do you want to continue? [Y/n] y
Preconfiguring packages ...
(Reading database ... 189575 files and directories currently installed.)
Preparing to unpack .../mysql-server-5.7_5.7.15-0ubuntu0.16.04.1_amd64.deb ...
Aborting downgrade from (at least) 10.1 to 5.7.
If are sure you want to downgrade to 5.7, remove the file
/var/lib/mysql/debian-*.flag and try installing again.
dpkg: error processing archive /var/cache/apt/archives/mysql-server-5.7_5.7.15-0ubuntu0.16.04.1_amd64.deb (--unpack):
 subprocess new pre-installation script returned error exit status 1
Selecting previously unselected package mysql-client.
Preparing to unpack .../mysql-client_5.7.15-0ubuntu0.16.04.1_all.deb ...
Unpacking mysql-client (5.7.15-0ubuntu0.16.04.1) ...
Selecting previously unselected package mysql-server.
Preparing to unpack .../mysql-server_5.7.15-0ubuntu0.16.04.1_all.deb ...
Unpacking mysql-server (5.7.15-0ubuntu0.16.04.1) ...
Errors were encountered while processing:
 /var/cache/apt/archives/mysql-server-5.7_5.7.15-0ubuntu0.16.04.1_amd64.deb
E: Sub-process /usr/bin/dpkg returned an error code (1)
root@prince-HP-ProBook-6470b:~# systemctl start apache2
root@prince-HP-ProBook-6470b:~# apt-get purge apache2
Reading package lists... Done
Building dependency tree
Reading state information... Done
You might want to run 'apt-get -f install' to correct these:
The following packages have unmet dependencies:
 mysql-server : Depends: mysql-server-5.7 but it is not going to be installed
E: Unmet dependencies. Try 'apt-get -f install' with no packages (or specify a solution).

A:  sudo apt-get autoclean

remove sources.list file.and create new sources.list...
sudo rm /etc/apt/sources.list

Then, type in
sudo software-properties-gtk

This will open software-properties-gtk and a newsources.list will be created automatically.
Then change the server to US or to any other server of your choice. You must enable repositories from the new dialog in order to create new sources.list.
Tick all the boxes then click on Revert then click close.
Need to restore default repositories
 sudo apt-get update && sudo apt-get dist-upgrade -y

(it is good practice to backup this file before installing to recover if such things happen)
Now install anything!

A: Well this op shows that , you have installed mariadb prior to this and you are installing mysql server now which seems to cause this problem. Better remove mariadb, mysql-server and apache and clean cache and try reinstalling mysql-server and apache.
Remove mariadb.
sudo apt-get remove --purge mariadb-*

Remove mysql-server and apache2 if installed.
sudo apt-get remove --purge mysql-server apache2

Remove unwanted dependencies and clean.
 sudo apt-get autoremove
 sudo apt-get autoclean

Now go ahead installing one by one.  Note: Don't install mariadb and mysql-server both because fromer is a fork of the latter and both caters the same purpose.


text:
Q: Any big projects using Pypy? I have a very large heterogeneous Python codebase that uses Django as the front-end. This codebase is deployed alongside several servers that are beginning to show the strain and we're looking for ways to speed things up while we re-architect the codebase, and to keep the new code running fast.
We're currently looking at Pypy but it seems a bit iffy. It has many limitations and requires refactoring a lot of code (can't concatenate strings with "+"?).
Does anyone have experience with it? Are there any large scale websites using it?

A: Migration from CPython to PyPy is the last thing you should consider when thinking about web site performance (after architecture, database, caching, distributed queues, etc.). And if you absolutely need code-level optimizations (as shown by thorough profiling), then consider going straight to C/C++ for ultimate speed.
PyPy is mostly compatible with CPython on language and standard library level, but it's incompatible with many CPython C extensions (and the compatible ones may actually work slower). If your site is pure Python and has proper test coverage, you can easily check if it works with PyPy and if it's considerably faster or not. If you don't have tests, things are getting risky. If you use C extensions, you'll face issues and it's likely more trouble than it's worth.
See also:

*

*Why wasn't PyPy included in standard Python?

*Why shouldn't I use PyPy over CPython if PyPy is 6.3 times faster?

*PyPy and CPython differences

*PyPy compatibility with packages


text:
Q: Bootstrap Date Paginator datepicker I would like to make redirect when a date is changed and transmit selected date parameter (via window.location.href). I'm using Bootstrap Date Paginator, which contains Bootstrap datepicker, but I don't know how to change these lines of code to work properly:
this.$calendar
  .datepicker({
    options...
  })
  .datepicker('update', this.options.selectedDate.toDate())
  .on('changeDate', $.proxy(this._calendarSelect, this));

I know I would use changeDate event but there aren't any examples of using this event. Can you help me, please?

A: Would this do?
You can use .on('change', ..) like this,
this.$calendar
  .datepicker({
    options...
  }).on('change', function() {
       var changedDate = this.$calendar.val();
       //alert("value of date is "+ x);
    var theUrl = 'your URL';
    window.location.href = theUrl+"date="changedDate
    });

Else use, on('change.dp', ..) event like this,
this.$calendar
      .datepicker({
        options...
      }).on('change.dp', function() {
           var changedDate = this.$calendar.val();
           //alert("value of date is "+ x);
        var theUrl = 'your URL';
        window.location.href = theUrl+"date="changedDate
        });

Alternatively have a look at this too.

A: May be it's too late, but I have same problem and come up with this solution,
while setting options for Bootstrap Date Paginator keep track of onSelectedDateChanged function and assign the date value to a variable and send that variable to location.href.


text:
Q: Check file extension in sftp batch file I have one bat file which checks for .csv file in sftp location.
If csv file is present on sftp server, then it successfully downloads the file in local and exit with 0.
If .csv file is not present, then bat file completes processing with exit status 1.
I am using below bat file for sftp:
echo open sftp://<username>:<password><server_name> -hostkey="<server host key>" >> ftpcmd.dat
echo get /shared/sftp/test.csv >> ftpcmd.dat
echo exit >> ftpcmd.dat
D:\Winscp\winscp.com /script=ftpcmd.dat
del ftpcmd.dat

Problem -
I need to check for file extension also in same script, as part of the requirement. If in sftp server location, a file with other extensions is present, then sftp script will fail or exit with some status.
Current behavior -
If .txt file is present in sftp location, then batch file is exiting with status 1. I need to exit this condition with some other exit status.
Please suggest how can i implement this file extension checking condition in same bat file which sftp the file.

A: A straightforward/simplistic approach would be to additionally check for .txt when there is no .csv and in case of success set the exit code to 2:
for %%a in (csv txt) do (
    winscp.com /command ^
        "open sftp://<username>:<password><server_name> -hostkey=""<server host key>""" ^
        "get /shared/sftp/test.%%a" ^
        "exit"
    if "%errorlevel%" equ 0 if %%a==csv (exit /b 0) else (exit /b 2)
)

Exit codes:

*

*0: CSV was downloaded

*1: CSV and TXT both are absent

*2: TXT was downloaded

More info on command line parameters: official docs.


text:
Q: Does this diagram successfully construct a Kepler triangle? Assuming the starting circle is a unit circle with radius $1$, does this successfully create a Kepler triangle? The legs are $1$ (radius of unit circle), and $\phi$ (radius of circle equal to Odom construction length), leaving the hypotenuse to be $\phi^2$.

Some references

*

*Wikipedia "Kepler triangle"

*Wikipedia "George Phillips Odom, Jr.", noting Odom's construction of the golden ratio by extending an equilateral triangle's midpoint segment to its circumcircle.

I'm new to this, I just find it interesting. Sorry if I'm not providing the proper amount of info for my question to make sense.


text:
Q: Android - Image cache using volley I'm using volley for my all network connections. For image cache as well we're using volley to download images.
We're using below class to cache images -
public class BitmapCache extends LruCache<String, Bitmap> implements
        ImageCache {
    public static int getDefaultLruCacheSize() {
        final int maxMemory = (int) (Runtime.getRuntime().maxMemory() / 1024);
        final int cacheSize = maxMemory / 8;
        return cacheSize;
    }

    public BitmapCache() {
        this(getDefaultLruCacheSize());
    }

    public BitmapCache(int sizeInKiloBytes) {
        super(sizeInKiloBytes);
    }

    @Override
    protected int sizeOf(String key, Bitmap value) {
        return value.getRowBytes() * value.getHeight() / 1024;
    }

    @Override
    public Bitmap getBitmap(String url) {
        return get(url);
    }

    @Override
    public void putBitmap(String url, Bitmap bitmap) {
        put(url, bitmap);
    }
}

But issue is that when we clear app form app stack (kill app), volley downloading same images again. I wanted to do it like till then we clear image cache, it should stored in app file location (don't want to use sdcard storage).
The volley library we're using which don't have DiscLruCache. I've heard about DiscLruCache many posts, but don't know that how we could use as I've restriction to not to change volley library which we're already using.

A: Meybe this example from Google I/O 2013 will help You
https://github.com/rdrobinson3/VolleyImageCacheExample


text:
Q: How to order by and select top 2 for each group I have a table as below:
Logs:
ID | GroupCode | Date | Description

So ID is unique for each entry in the table.
GroupCode is the way to group entries.
I would like to sort the table by GroupCode and Date DESC. Then look at the top 2 entries for each group to find out whether the description has changed from one to another in each group entry.
Description contains some key words such as "New", "Update" ,"delete" etc.
Complete Description is always differ from one to another but I should be able to just check the key words in latest 2 entries Description for each group and identify whether it has gone from New to Update or Update to New or Delete to New etc. If the key word has changed from one to another in the latest 2 entries Description for that group then my selection result should include that group and also the key word change. For example if the key word in the Description was New and gone to Update, the result should say as below:
GroupCode | Change
 x      "from New to Update"

Would this be possible to do with SQL query or a console application is required to analyse the entries?

A: Yes, it's possible. First create a subquery to get top 2 entries for each group using ROW_NUMBER. Just partition by GroupName, sort by Date and take the rows with rownumbercolumn in (1,2)
Then you can compare current row with a previous one using LAG function to compose the Change column. Just make a simple check to make sure you don't compare rows from different groups.
if exists(select * from [sys].[tables] where [name]='Logs' )
    drop table [Logs]

go

create table [Logs](
[Id] int identity not null primary key,
[GroupCode] varchar(50) not null,
[Date] date not null,
[Description] varchar(100) not null
)

insert [Logs]([GroupCode], [Date], [Description]) values('Group1', '2016-05-01', 'New')
insert [Logs]([GroupCode], [Date], [Description]) values('Group1', '2016-05-03', 'Update')
insert [Logs]([GroupCode], [Date], [Description]) values('Group1', '2016-05-04', 'Update')
insert [Logs]([GroupCode], [Date], [Description]) values('Group1', '2016-05-05', 'Delete')

insert [Logs]([GroupCode], [Date], [Description]) values('Group2', '2016-05-06', 'New')
insert [Logs]([GroupCode], [Date], [Description]) values('Group2', '2016-05-08', 'Update')
insert [Logs]([GroupCode], [Date], [Description]) values('Group2', '2016-05-15', 'Delete')
insert [Logs]([GroupCode], [Date], [Description]) values('Group2', '2016-05-20', 'New')

insert [Logs]([GroupCode], [Date], [Description]) values('Group3', '2016-05-21', 'New')
insert [Logs]([GroupCode], [Date], [Description]) values('Group3', '2016-06-03', 'Update')
insert [Logs]([GroupCode], [Date], [Description]) values('Group3', '2016-06-04', 'Update')
insert [Logs]([GroupCode], [Date], [Description]) values('Group3', '2016-06-05', 'Update')

select [GroupCode], [Change] from
(select *,
case when LAG([Description]) OVER (ORDER BY [GroupCode] ASC, [Date] asc) = [Description] then 'No Change Visible' else
'From ' + LAG([Description]) OVER (ORDER BY [GroupCode] ASC, [Date] asc) + ' to ' + [Description] end [Change] from
(select [GroupCode], [Date], [Description], row_number() OVER(PARTITION BY [GroupCode] ORDER BY [Date] DESC) AS RowNumber
from Logs) Q1 -- Q1 query takes top 2 by date DESC for each group
where RowNumber in (1,2)) Q2 -- Q2 composes the change column by taking prev row value
where RowNumber = 1 -- here we just take last row fpr each group

The result is
GroupCode    Description
Group1       From Update to Delete
Group2       From Delete to New
Group3       No Change Visible

Hope it helps!


text:
Q: Eclipse can't find my MinGW toolchain for C/C++ I have a problem. Many have the same question but I didn't find the answer.
I installed gcc-4.9.0 on my PC but Eclipse won't find it.
I used the default installation path:
C:\MinGW

A: *

*Setting PATH variable, add something like: "C:\Program Files (x86)\mingw-w64\i686-6.2.0-win32-dwarf-rt_v5-rev1\mingw32\bin"

*DO COPY gcc.exe to mingw32-gcc.exe in your path above

For more information, see:
http://wiki.eclipse.org/CDT/User/FAQ#I_installed_MinGW_toolchain_on_my_PC_but_Eclipse_won.27t_find_it.

A: I also had this problem recently.  I had some difficulty getting my Eclipse Luna SR2 4.4.2 running on Win 7 SP1 to see my newly-installed MinGW-w64 but I was able to resolve it by adding a MINGW_HOME environmental variable to my Win 7 installation, and then restarting Eclipse.  (I didn't need to restart Windows.)
In my case, MinGW-w64 had installed itself at "C:Program Files\mingw-w64\x86_64-4.9.2-win32-seh-rt_v4_rev2" and so I needed to set MINGW_HOME to "C:Program Files\mingw-w64\x86_64-4.9.2-win32-seh-rt_v4_rev2\mingw64" so that it would point to the appropriate subdirectories (bin, etc, include, lib, ...).
In Win 7, environmental variables can be set via the "Environment Variables" button on the Control Panel -> System and Security -> System -> Advanced system settings.  I added my MINGW_HOME variable to the "User variables" section.

A: This steps helped me when I faced the same problem:
First add the MinGW directory to your path system environment variable as in this link:
(https://www.youtube.com/watch?v=zLpaYVIoXqc)
After this when you want to create a project uncheck "Show project types and toolchains only if they are supported on the platorm" option. Choose MinGW GCC
Create your code but first build it with CTRL+B, after this mine worked perfectly.
I wish it will be helpful for other people who see this

A: Eclipse uses the system environment variable "PATH" to find a toolchain. So, in order to Eclipse could find MinGW toolchain, the path the to bin-directory of MinGW (e.g. "C:\MinGW\bin") should be specified in the "PATH" environment variable.
P.S. And don't forget to re-launch Eclipse after modifying the environment variable :)

A: OPEN ECLIPSE > WINDOW (view image)  > BUILD > ENVIRONMENT (view image)  >
and click the Select button you can see your variable list and Select the PATH variable and press ok button. (view image) >
after this done you can edit the value of PATH put your path of mingw eg:'C:\mingw64\bin' after the semi colon';' and apply and close then restart the eclipse its done.(view image)

A: I had this problem for a while and just now got it to work.
Here's what I did:
In Eclipse, go to Window>Preferences>C/C++>Build>Environment. Double click the row that has PATH in the leftmost column to open the list. Make sure you've got \bin at the end of your C:\MinGW in that list. Mine didn't have the \bin. I changed it to read C:\MinGW\bin and now it works like a charm.
Hope this helps.

A: As indicated in the above steps one thing I missed to do was saving user settings after adding the path variable. This suggested that the path for MinGW was not saved correctly.
Please check-in that aspect as well.

A: A mismatch of 32 and 64 bit versions of eclipse and mingw can also contribute the gcc/g++ not-found problem. Make sure you stick to one version all the way from java, mingw, to eclipse.

A: After updating the environment path variable, you must restart os.


text:
Q: Error Estimation Using Taylor's Theorem I missed the lecture on this and was wondering if someone could explain the steps involved with this problem. I think that what I have to do is evaluate the polynomial up to the second derivative (degree $2$) and then I can choose $x=7$ and evaluate the polynomial at that point. Then with those values plug it into the error series? However I do not know the error series. Am I on the right track?
Finally, Part B I have absolutely NO idea what it is asking.
Thanks!
(a) Use Taylor's Theorem to estimate the error in using the Taylor Polynomial of $f(x)$=$\sqrt{x}$ of degree $2$ to approximate $\sqrt{8}$. (The answer should be something like $1/2  \times  8^{-7/2}$).
(b) Find a bound on the difference of $\sin(x)$ and $\,x-\frac{x^{3}}{6} + \frac{x^{5}}{120}$ for $x \in [0,1]$

A: A not unreasonable thing to do, and probably what you are expected to do, is to expand $\sqrt{x}$ in powers of $x-9$.
The formula for the $n$-th degree Taylor polynomial for $f(x)$ in powers of $x-a$ is
$$f(a)+\frac{f'(a)}{1!}(x-a)+\frac{f''(a)}{2!}(x-a)^2+\cdots +\frac{f^{(n)}(a)}{n!}(x-a)^n.$$
In our case we have $f(x)=x^{1/2}$, $a=9$, and $n=2$. To finish getting the second degree polynomial, you need to calculate $f(9)$, $f'(9)$, and $f''(9)$.
We now turn to the error term. By the Lagrange form of the remainder, the absolute value of the error if we use the Taylor polynomial of degree $2$ is
$$\frac{|f'''(\xi)|}{3!}|x-9|^3,$$
where $f(x)=x^{1/2}$ and $\xi$ is a number between $x$ and $9$. In our case, we have  $x=8$.
Note that $f'''(x)=\frac{3}{8}x^{-5/2}$. Between $8$ and $9$, it is positive and bounded above by $\frac{3}{8}8^{-5/2}$. Thus, putting things together, and noting that $|8-9|=1$, we find that the absolute value of the error is less than $\frac{3}{(8)(3!)}8^{-5/2}$.
For the sine function, the best thing to do is to note that when $|x|\lt 1$ then the usual series for $\sin x$ is an alternating series. For such a series, the absolute value of the error is less than the absolute value of the first "neglected"  term. In our case, that term is $-\frac{x^7}{7!}$, so in the interval $[0,1]$ the error has absolute value $\lt \frac{1}{7!}$.
Alternately, but less attractively, we can use the Lagrange formula  for the remainder. It is useful to note that the given series up to $\frac{x^5}{5!}$ can be considered to be the expansion up to the term in $x^6$, which happens to be $0$. Thus the Lagrange formula gives absolute value of the error equal to
$$\frac{|f^{(7)}(\xi)|}{7!}|x|^7,$$
where $f(x)=\sin x$. The $7$-th derivative of $f(x)$ is $-\cos x$, so the absolute value of the $7$-th derivative is $\lt 1$. That gives us that the absolute value of the error if $|x|\lt 1$ is $\lt \frac{1}{7!}$.


text: Q: What happens to previous docker containers when you run its image one more time? I had a docker image and inside it, I had a container (a). I accidentally used the command 'docker run '. Now I cannot see container a anymore. Is it possible to access it? How can I do that?


text:
Q: wget seems to crawl only first page when using -A, despite using both -r, -e robots=off, -l inf, etc What I want wget to do is to crawl the entire site recursively below a certain directory and download all, say, png files.
I'll use Wikipedia as an example. This is the command:
wget -r -p -e robots=off -H -D en.wikipedia.org --no-parent -A png http://en.wikipedia.org/wiki/Main_Page

This is what I get:
URL transformed to HTTPS due to an HSTS policy
--2016-07-20 11:02:51--  https://en.wikipedia.org/wiki/Main_Page
Resolving en.wikipedia.org (en.wikipedia.org)... 91.198.174.192, 2620:0:862:ed1a::1
Connecting to en.wikipedia.org (en.wikipedia.org)|91.198.174.192|:443... connected.
HTTP request sent, awaiting response... 200 OK
Length: unspecified [text/html]
Saving to: 'en.wikipedia.org/wiki/Main_Page'

en.wikipedia.org/wi     [  <=>               ]  64.72K   298KB/s    in 0.2s

2016-07-20 11:02:51 (298 KB/s) - 'en.wikipedia.org/wiki/Main_Page' saved [66278]

Removing en.wikipedia.org/wiki/Main_Page since it should be rejected.

URL transformed to HTTPS due to an HSTS policy
--2016-07-20 11:02:51--  https://en.wikipedia.org/static/images/wikimedia-button.png
Reusing existing connection to en.wikipedia.org:443.
HTTP request sent, awaiting response... 200 OK
Length: 2426 (2.4K) [image/png]
Saving to: 'en.wikipedia.org/static/images/wikimedia-button.png'

en.wikipedia.org/st 100%[===================>]   2.37K  --.-KB/s    in 0s

2016-07-20 11:02:51 (147 MB/s) - 'en.wikipedia.org/static/images/wikimedia-button.png' saved [2426/2426]

URL transformed to HTTPS due to an HSTS policy
--2016-07-20 11:02:51--  https://en.wikipedia.org/static/images/poweredby_mediawiki_88x31.png
Reusing existing connection to en.wikipedia.org:443.
HTTP request sent, awaiting response... 200 OK
Length: 1585 (1.5K) [image/png]
Saving to: 'en.wikipedia.org/static/images/poweredby_mediawiki_88x31.png'

en.wikipedia.org/st 100%[===================>]   1.55K  --.-KB/s    in 0s

2016-07-20 11:02:51 (102 MB/s) - 'en.wikipedia.org/static/images/poweredby_mediawiki_88x31.png' saved [1585/1585]

FINISHED --2016-07-20 11:02:51--
Total wall clock time: 1.0s
Downloaded: 3 files, 69K in 0.2s (316 KB/s)

The same happens even if I add -l inf.
When I run the same code, but remove -A png, wget keeps on downloading, with no end in sight, as it's supposed to do.
So, what's the problem? How do I get it to crawl the entire site, but download only certain file types?

A: The result obtained by the o/p, stanny, is surprising but true.
I get the same result, yet I also get a successful result from an ordinary Wikipedia page, with the following command:-
wget --no-check-certificate --span-hosts -e robots=off -p -A png https://en.wikipedia.org/wiki/Antimatter

I am using wget 1.16, running on a Windows PC using Windows 7 64-bit.


text:
Q: How do I make the image and name of categories show on screen For this I am using Firebase as the database and Picasso to load the images on screen. After I login I am unable to see the images and the names of each category.
I have used a model name "Category" with setters and getters but these messages keep on coming up on my logcat:

My model looks like this at the moment:
public class Category {

    private String name, image;

    public Category() {
    }

    public Category(String name, String image) {
        this.name = name;
        this.image = image;
    }

    public String getName() {
        return name;
    }

    public void setName(String name) {
        this.name = name;
    }

    public String getImage() {
        return image;
    }

    public void setImage(String image) {
        this.image = image;
    }
}

This is a sample of my database. it shows the category image link and the name of it.

The list of categories are supposed to show in a fragment. This is my fragment class.
public class CategoryFragment extends Fragment {

    View myFragment;

    RecyclerView categoryList;
    RecyclerView.LayoutManager layoutManager;
    FirebaseRecyclerAdapter<Category, CategoryViewHolder> adapter;

    // Firebase Tings
    FirebaseDatabase database;
    DatabaseReference categories;

    public static CategoryFragment newInstance() {
        CategoryFragment categoryFragment = new CategoryFragment();
        return categoryFragment;
    }

    @Override
    public void onCreate(@Nullable Bundle savedInstanceState) {
        super.onCreate(savedInstanceState);

        database = FirebaseDatabase.getInstance();
        categories = database.getReference("Category");
    }

    @Nullable
    @Override
    public View onCreateView(LayoutInflater inflater, @Nullable ViewGroup container, @Nullable Bundle savedInstanceState) {
        myFragment = inflater.inflate(R.layout.fragment_category, container, false);
        categoryList = (RecyclerView) myFragment.findViewById(R.id.categoryList);
        categoryList.setHasFixedSize(true);
        layoutManager = new LinearLayoutManager(container.getContext());
        categoryList.setLayoutManager(layoutManager);

        loadCategories();

        return myFragment;
    }

    private void loadCategories() {
        adapter = new FirebaseRecyclerAdapter<Category, CategoryViewHolder>(
                Category.class,
                R.layout.category_item,
                CategoryViewHolder.class,
                categories
        ) {
            @Override
            protected void populateViewHolder(CategoryViewHolder viewHolder, final Category model, int position) {
                viewHolder.tvCategoryName.setText(model.getName());
                Picasso.with(getActivity())
                        .load(model.getImage())
                        .into(viewHolder.ivCategoryImage);

                viewHolder.setItemClickListener(new ItemClickListener() {
                    @Override
                    public void onClick(View view, int position, boolean isLongClick) {
                        Toast.makeText(getActivity(), String.format("%s | %s", adapter.getRef(position).getKey(), model.getName()), Toast.LENGTH_SHORT).show();
                    }
                });
            }
        };
        adapter.notifyDataSetChanged();
        categoryList.setAdapter(adapter);
    }
}

This is my CategoryViewHolder class
public class CategoryViewHolder extends RecyclerView.ViewHolder implements View.OnClickListener {

    public TextView tvCategoryName;
    public ImageView ivCategoryImage;

    private ItemClickListener itemClickListener;

    public CategoryViewHolder(View itemView) {
        super(itemView);

        ivCategoryImage = (ImageView) itemView.findViewById(R.id.ivCategoryImage);
        tvCategoryName = (TextView) itemView.findViewById(R.id.tvCategoryName);

        itemView.setOnClickListener(this);
    }

    public void setItemClickListener(ItemClickListener itemClickListener) {
        this.itemClickListener = itemClickListener;
    }

    @Override
    public void onClick(View view) {
        itemClickListener.onClick(view, getAdapterPosition(), false);
    }
}

I have looked for different solutions view the category image and names, but no luck.
UPDATE:
I have updated the database to this structure
I have tried using these 2 ways of showing the data on device
 categories=FirebaseDatabase.getInstance().getReference().child("Category");

    /*database = FirebaseDatabase.getInstance();
    categories = database.getReference("Category");*/

But still no success.
Instead it shows the same errors. I have not changed my model in any way
Thanks for the help in advance.
P.S thanks for the solutions mentioned before, too bad it did work.
Any more help would be suffice.

A: The database structure from your link seems to be like this
category

|-category

|01

-------name
-------image

you should refer to the second category node to be able to reach your data
but you don't seem to do that.
So instead of using these 2 lines of code
database = FirebaseDatabase.getInstance();
categories = database.getReference("Category");

try to use this
DatabaseReference categories;

//and refer to your database like that

categories=FirebaseDatabase.getInstance().getReference().child("Category").child("Category");

according to the link you added this should be the correct way to refer to your database

A: Your current database structure has Category objects nested under the /Category/Category node, but the reference you are using for your FirebaseRecyclerAdapter is pointing to the parent /Category node.
This is causing the errors in your logs - the FirebaseRecyclerAdapter is trying to marshal the children of the /Category node into the Category class, but there are no matching direct children at that location.
To fix this, you can adjust the reference that the FirebaseRecyclerAdapter is using:
@Override
public void onCreate(@Nullable Bundle savedInstanceState) {
    super.onCreate(savedInstanceState);

    database = FirebaseDatabase.getInstance();
    categories = database.getReference("Category").child("Category");
}

Or, change your database structure so that categories are listed as direct children of the /Category node:
{
  "Category" : {
    "01" : {
      "Name" : "Animals",
      "image" : "..."
    },
    "02" : {
      ...
    }
  }
}


text:
Q: Learning-curve for classification in python To plot the learning-curve in a regression problem, we should use 'RMSE' as a measure of analysis, like:
def plot_learning_curves(model, X_train, y_train, X_val, y_val):
    plt.figure(figsize=(15, 5))
    train_errors, val_errors = [], []
    for m in range(5, len(X_train)):
        model.fit(X_train[:m], y_train[:m])
        y_train_predict = model.predict(X_train[:m])
        y_val_predict = model.predict(X_val)
        train_errors.append(metrics.mean_squared_error(y_train_predict, y_train[:m]))
        val_errors.append(metrics.mean_squared_error(y_val_predict, y_val))
    plt.plot(np.sqrt(train_errors), "r-+", linewidth=1, label="training data")
    plt.plot(np.sqrt(val_errors), "b-", linewidth=1, label="validation data")
    plt.legend(loc="upper right", fontsize=10)
    plt.xlabel("Size", fontsize=10)
    plt.ylabel("RMSE", fontsize=10)
    plt.title("Learning Curves")
    plt.show()

However, I would like to have a learning curve for the classification problem, and I know that we should use accuracy as a metric for analysis instead of 'RMSE'.
So far, I've only found snippet codes for this problem using the 'learning-curve' class in sklearn , like:
from sklearn.model_selection import learning_curve
from sklearn.model_selection import ShuffleSplit

def plot_learning_curve(estimator, X, y, ax=None, cv=None, n_jobs=4, train_sizes=np.linspace(.1, 1.0, 5)):

train_sizes, train_scores, test_scores = \
    learning_curve(estimator, X, y, cv=cv, n_jobs=n_jobs, train_sizes=train_sizes)
train_scores_mean = np.mean(train_scores, axis=1)
train_scores_std = np.std(train_scores, axis=1)
test_scores_mean = np.mean(test_scores, axis=1)
test_scores_std = np.std(test_scores, axis=1)

# Plot learning curve
ax.set_xlabel("Training examples")
ax.set_ylabel("Score")
ax.plot(train_sizes, train_scores_mean, 'o-', color="r", label="Training score")
ax.plot(train_sizes, test_scores_mean, 'o-', color="g", label="Cross-validation score")
ax.legend(loc="best")

return plt

However, as you can see in this solution, we need to pass the x and y datasets and it uses cross-validation to split them into train and test datasets.
But, I've already split my dataset and applied a lot of preprocessing to x-train and x-test.
So, I intend to use my train and test dataset just like the code I wrote for the regression problem, which is based on the "RMSE" metric (without using the "learning-curve" class in sklearn).


text:
Q: Add a native lib to an APK I'm developing an Android application that uses native code.
I need to add an external native library to my APK's lib folder on every build.
How can I do that?
Thanks.

A: Put the library in the native library path which defaults to "libs" in your project folder.
If you built the native code for the 'armeabi' target then put it under libs/armeabi. If it was built with armeabi-v7a then put it under libs/armeabi-v7a.
<project>/libs/armeabi/libstuff.so


text:
Q: How to change date format from yyyy-MM-dd to dd-MMM-yyyy I am retrieving date from database. Datatype is'date' with date format 2015-12-16.
I need to set that date to my bean class variable.Datatype is Date with format 16-Dec-2015
These are the date formats i am using
      SimpleDateFormat formatter = new SimpleDateFormat("dd-MMM-yyyy");
              SimpleDateFormat formatter1 = new SimpleDateFormat("yyyy-MM-dd");

              Date date = null;
              String formatteddate = null;

                try {
                    formatteddate = formatter.format(rs.getDate("dol"));
                    System.out.println("formatteddate=============="+formatteddate);
                    date = formatter.parse(formatteddate);
                    System.out.println("date========="+date);
                } catch (ParseException e) {
                    e.printStackTrace();
                }

              joborderbean.setDol(date);

formatteddate==============15-Dec-2015
I want to display the above format i.e,15-Dec-2015. But it is diplaying the below format
date=========Tue Dec 15 00:00:00 IST 2015
Please help me

A: Do like following:
SimpleDateFormat formatter = new SimpleDateFormat("dd-MMM-yyyy");
String dateformat=fromatter.format(mysqldate);
System.out.println("first date format"+ dateformat);
SimpleDateFormat formatter1 = new SimpleDateFormat("yyyy-MM-dd");
String dateformat1=formatter1.format(mysqldate);
System.out.println("second date format"+dateforamt1);

also you can edit the sql fired to get the result like
 select DATE_FORMAT(date_field,'%Y-%b-%d')

and
select DATE_FORMAT(date_field,'%d-%b-%Y')

A: First of all the Resultset objects getDate method return a java.sql.Date object. So in order to store the Date in the date object use :
date = rs.getDate("dol");

instead of the code:
formatteddate = formatter.format(rs.getDate("dol"));
System.out.println("formatteddate=============="+formatteddate);
date = formatter.parse(formatteddate);
System.out.println("date========="+date);

now in order to test the date you can use:
SimpleDateFormat formatter = new SimpleDateFormat("dd-MMM-yyyy");
System.out.printLn("date========="+formatter.format(date));

This will give you the required output.
The last output you are getting because of the code System.out.println("date========="+date); Here the toString method of the date object is getting called which has a default as in the documentation as :

Converts this Date object to a String of the form:
dow mon dd hh:mm:ss zzz yyyy

where:

*

*dow is the day of the week (Sun, Mon, Tue, Wed, Thu, Fri, Sat).

*mon is the month (Jan, Feb, Mar, Apr, May, Jun, Jul, Aug, Sep, Oct, Nov, Dec).

*dd is the day of the month (01 through 31), as two decimal digits.

*hh is the hour of the day (00 through 23), as two decimal digits.

*mm is the minute within the hour (00 through 59), as two decimal digits.

*ss is the second within the minute (00 through 61, as two decimal digits.

*zzz is the time zone (and may reflect daylight saving time). Standard time zone abbreviations include those recognized by the method parse. If time zone information is not available, then zzz is empty - that is, it consists of no characters at all.

*yyyy is the year, as four decimal digits.


text:
Q: Why can't AND and NOT be represented with only IMPLICATION? Can someone please explain why I can't use only IMPLICATION to represent AND and NOT with proof as well?
I know that I can represent OR simply by using IMPLICATION. Was thinking if I could find representation of NOT, then I can easily find representation of AND.
From my understanding, we can represent IMPLICATION by using OR and NOT set. Which is a functionally complete. Does this mean that Implication is also functionally complete?

A: One way of approaching a formal proof of this, is by induction, I'll do negation for you, and you can see if you can modify it to do conjunction.
Notice that if you have an expression $\phi$ which is equivalent to $\neg A$, which has any occurrences of any propositional variables other than $A$, then, you can just replace them with $A$. Hence, we only need to consider sentences in $A$ and $\rightarrow$.
Claim: Any sentence in $A$ and $\rightarrow$ evaluates to true, when $A$ is true.
Proof: By induction on the length of the sentence. The base case is the sentence $A$, and clearly this is true with $A$ is true. In the induction step the expression is of the form $\phi \rightarrow \psi$, for some sentences $\phi$ and $\psi$ in only $A$ and $\rightarrow$. Also $\phi$ and $\psi$ are shorter, so, we can apply the induction hypothesis. In particular when $A$ is true $\phi$ and $\psi$ are both true. But then, by the semantics for $\rightarrow$, when $A$ is true $\phi\rightarrow \psi$ is true too.
Q.E.D.
So, any expression we can make preserves truth, and so, can't be equivalent to negation.

A: $$\begin{align}\lnot A &\iff (A\implies \bot)\\
A\land B&\iff \lnot (A\implies\lnot B)\end{align}$$
If you can use $\bot$ as an argument to $\implies$ then I think this works. If you can not use $\bot$, then implementing $\lnot A$ is impossible. You are left with just $A$ and $\implies$. $A\implies A$ gives you $\top$, but it does not help. $\top\implies A$ is just $A$ and $A\implies\top$ is just $\top$ (as is $\top\implies\top$), so your return value can never be anything but $A$ or $\top$.

A: The problem with using $\Rightarrow$ as the only operator is that you cannot construct an universally false statement - which is required for a set of operators to be functionally complete. You can do this with for example $\lor$ and $\neg$, for example $\neg (\phi \lor \neg \phi)$.
To see why this is we can break down any statement into the form $\phi \Rightarrow \psi$, we also know that there should be a minimal such statement that is universally false (that is $\phi$ and $\psi$ are not universally false - or we could use $\phi$ or $\psi$ instead). But for $\phi\Rightarrow\psi$ to be false we must have $\phi$ being true and $\psi$ being false, and to be universally false we must have $\psi$ being universally false.
On the other hand if we had a universally false statement $\bot$ you could create the rest. For example $\phi\Rightarrow\bot$ is the same as $\neg\phi$ and when we constructed the $\neg$ operator we can construct the $\lor$ by observing that $\neg\phi\Rightarrow\psi$ is the same as $\phi\lor\psi$. The rest follows from that $\lor$ and $\neg$ are functionally complete.

Another way to see that $\Rightarrow$ is not functional complete is to consult characterization of functional completeness due to Post. This case is that $\Rightarrow$ is truth conserving connectives. This means that if all variables are true the result will be true and thereby any construct will be that as well. But a functionally complete set of connectives must be able to represent a statement that is false even though all variables are being true.

A: First I will show that $\land$ can not be represented using only $\to.$
Let $\mathcal S$ be the set of all formulas $\phi$ such that $\phi$ is a consequence of some propositional variable. Of course, every propositional variable belongs to $\mathcal S;$ moreover, for any formulas $\phi$ and $\psi,$ if $\phi\in\mathcal S$ then $\psi\to\phi\in\mathcal S.$ It follows (by induction on the length of formulas) that every formula, which contains no connectives other than $\to,$ belongs to $\mathcal S.$ Since the conjunction $p\land q$ is not a consequence of any single variable, it follows that $p\land q$ is not equivalent to (or even a consequence of) any formula in $\mathcal S;$ in particular $p\land q$ is not equivalent to any formula containing no connectives other than $\to.$
Since $\land$ can be represented using $\to$ and $\neg$, namely $p\land q=\neg(p\to\neg q),$ it follows that $\neg$ can not be represented using only $\to.$


text:
Q: Controller for a DC motor for moving 18 cm constantly I am working on designing a micro mouse that solves a maze. The objective is to reach the centre of the maze. The mouse needs to move one block distance at a time, which is 18 m. Currently, I am using a position control which calculates the error in distance and converts that into PWM value. So, as the error gets lower, the PWM decreases. Below is the code for it:
if( distanceRight < 60 || distanceLeft < 60)    // Encoder Pulses from the left and the right wheel
        {
            //Finding the error and converting into fraction values to be used as PWM
            errorRight = (60.0 - distanceRight)/60;
            errorLeft = (60.0 - distanceLeft)/60;

            PWM_RightWheel = (errorRight);
            PWM_LeftWheel = (errorLeft);

            distanceRight = abs(encoder1.getPulses());
            distanceLeft = abs(encoder2.getPulses());
        }

But, here is the problem. Sometimes the mouse overshoots due to its inertia. The encoder that I am using to measure the distance has a max of 48 state changes for one revolution. Considering the radius of the wheel, this gives me the ability to measure 0.25cm distances accurately.
What kind of controller can I use to reduce the problem of overshoot? This overshoot problem also occurs when I use the encoders to calculate distance while turning right or left. Again, in both the cases, sometimes I have the problem of overshoot.
Do I need to use a PID controller? If yes then how can I find the transfer function for the motion of the wheel and implement it in code?

A: It looks like you are only using distance remaining as your control variable.
You also need to use velocity, that is, rate of arrival of pulses, or number of pulses per sample cycle.
You can then use that to calculate your required speed/deceleration rate and come to a halt where you desire, possibly even back driving the motor(s) to act as a brake if need be.


text:
Q: Использование домена второго уровня для размещения нескольких сайтов Как будут восприниматься поисковиком несколько различных по назначению и дизайну сайтов, расположенных на одном домене?

A: Будут воспринимать как один сайт. В том числе ТИЦ для них всех будет один. Если важна SEO, лучше такие штуки делать на поддоменах.
Адреса вида site.ru/site1,  site.ru/site2, лучше привести к виду site1.site.ru и site2.site.ru.
При этом, если у вас уже настроен первый вариант, можно настроить проксирующий nginx например, если вы планируете их добавлять в неограниченном количестве и не лазить для этого каждый раз в настройки DNS зоны.


text:
Q: OpenCV-Python VideoCapture only loads part of video I am currently trying to load a ultra-HD video (3840 × 2160) frame-by-frame using OpenCV in Python. I am using the VideoCapture object from the OpenCV library, and it seems to work fine except for the fact, that it only loads 26 frames.
The video is a 8:54 minutes long .mp4 with 30fps and H.264 coding.
A simplification of my code looks like the following
import cv2

def get_frames(filepath):
    cap = cv2.VideoCapture(filepath)
    while cap.isOpened():
        success, frame = cap.read()

        if not success:
            break

        frame = cv2.cvtColor(frame, cv2.COLOR_BGR2RGB)
        yield frame

The code seems to work fine for other videos at lower resolution.
I use Python 3.5.1 and version 3.1.0 of cv2.
Has anyone experienced the same problem or can recommend any other library for fast loading of video frames in Python?
Thanks.
EDIT:
According to VLC's Median Information the video have the following properties:
Codec:              H264 - MPEG-4 AVC (part 10)(avc 1)
Resolution:         3840x2178
Display resolution: 3840x2160
Frame rate:         29.970030
Decoded format:     Planar 4:2:0 YUV full scale

I tried converting the movie first using ffmpeg with the following command
ffmpeg -i video.mp4 -crf 18 video_converted.mp4

which actually made the code work even though the properties are exactly the same (according to VLC).


text:
Q: How do I overwrite the file_path function in scrapy 1.7.3? Without overwriting the file_path function, the spider download all the images with the default 'request URL hash' filenames. However when I try to overwrite the function it just doesn't work. There is nothing in the default output attribute, images.
I have tried both relative and absolute paths for the IMAGES_STORE variable in settings.py as well as the file_path function to no avail. Even when I overwrite the file_path function with the exact same default file_path function, the images do not download.
Any help would be much appreciated!
settings.py
BOT_NAME = 'HomeApp2'

SPIDER_MODULES = ['HomeApp2.spiders']
NEWSPIDER_MODULE = 'HomeApp2.spiders'

USER_AGENT = 'Mozilla/5.0 (Windows NT 6.2; WOW64) AppleWebKit/537.36 (KHTML, like Gecko) Chrome/27.0.1453.93 Safari/537.36'

# ScrapySplash settings
SPLASH_URL = 'http://192.168.99.100:8050'
DOWNLOADER_MIDDLEWARES = {
        'scrapy_splash.SplashCookiesMiddleware': 723,
        'scrapy_splash.SplashMiddleware': 725,
        'scrapy.downloadermiddlewares.httpcompression.HttpCompressionMiddleware': 810,
        }
SPIDER_MIDDLEWARES = {
        'scrapy_splash.SplashDeduplicateArgsMiddleware': 100,
        }
DUPEFILTER_CLASS = 'scrapy_splash.SplashAwareDupeFilter'
HTTPCACHE_STORAGE = 'scrapy_splash.SplashAwareFSCacheStorage'

# Configure item pipelines
# See https://docs.scrapy.org/en/latest/topics/item-pipeline.html
ITEM_PIPELINES = {
    'HomeApp2.pipelines.DuplicatesPipeline': 250,
    'HomeApp2.pipelines.ProcessImagesPipeline': 251,
    'HomeApp2.pipelines.HomeApp2Pipeline': 300,
}

IMAGES_STORE = 'files'

pipelines.py
import json
import scrapy
from scrapy.exceptions import DropItem
from scrapy.pipelines.images import ImagesPipeline

class DuplicatesPipeline(object):
    def __init__(self):
        self.sku_seen = set()

    def process_item(self, item, spider):
        if item['sku'] in self.sku_seen:
            raise DropItem("Repeated item found: %s" % item)
        else:
            self.sku_seen.add(item['sku'])
            return item

class ProcessImagesPipeline(ImagesPipeline):

    '''
    def file_path(self, request):
        print('!!!!!!!!!!!!!!!!!!!!!!!!!')
        sku = request.meta['sku']
        num = request.meta['num']
        return '%s/%s.jpg' % (sku, num)
    '''

    def get_media_requests(self, item, info):
        print('- - - - - - - - - - - - - - - - - -')
        sku = item['sku']
        for num, image_url in item['image_urls'].items():
            yield scrapy.Request(url=image_url, meta = {'sku': sku,
                                                        'num': num})

class HomeApp2Pipeline(object):
    def __init__(self):
        self.file = open('items.jl', 'w')

    def process_item(self, item, spider):
        line = json.dumps(dict(item)) + '\n'
        self.file.write(line)
        return item

AppScrape2.py
import scrapy
from scrapy_splash import SplashRequest
from HomeApp2.items import HomeAppItem

class AppScrape2Spider(scrapy.Spider):
    name = 'AppScrape2'

    def start_requests(self):
        yield SplashRequest(
            url = 'https://www.appliancesonline.com.au/product/samsung-sr400lstc-400l-top-mount-fridge?sli_sku_jump=1',
            callback = self.parse,
        )

    def parse(self, response):

        item = HomeAppItem()

        product = response.css('aol-breadcrumbs li:nth-last-of-type(1) .breadcrumb-link ::text').extract_first().rsplit(' ', 1)
        if product is None:
            return {}
        item['sku'] = product[-1]
        item['image_urls'] = {}

        root_url = 'https://www.appliancesonline.com.au'
        product_picture_count = 0
        for pic in response.css('aol-product-media-gallery-main-image-portal img.image'):
            product_picture_count = product_picture_count + 1
            item['image_urls']['p'+str(product_picture_count)] = (
            root_url + pic.css('::attr(src)').extract_first())

        feature_count = 0
        for feat in response.css('aol-product-features .feature'):
            feature_count = feature_count + 1
            item['image_urls']['f'+str(feature_count)] = (
            root_url + feat.css('.feature-image ::attr(src)').extract_first())

        yield item

items.py
import scrapy

class HomeAppItem(scrapy.Item):
    # define the fields for your item here like:
    # name = scrapy.Field()

    sku = scrapy.Field()
    image_urls = scrapy.Field()
    images = scrapy.Field()

    pass

A: After much trial and error, I found the solution. It was simply adding the rest of the parameters to the file_path method.
Changing
def file_path(self, request):

to
def file_path(self, request, response=None, info=None):

It seems that the my original code overrode the method incorrectly causing calls to the method to fail.


text:
Q: How to set the client certificate for AWS API gateway deployment stage using aws-cli I am in the process of automating API gateway deployment using AWS CLI commands.
The cli command used to deploy an API goes like this.
aws apigateway create-deployment \
               --rest-api-id abcd1234 \
               --stage-name v1 \
               --variables elbDomain=xxx.yyy.zzz.io

Unfortunately, do not understand what would be the command to configure client certificate for that stage.

Through API gateway UI you can achieve that and can be found here.

A: You'll need to use aws apigateway update-domain-name.
http://docs.aws.amazon.com/cli/latest/reference/apigateway/update-domain-name.html

A:
I got the following answer from AWS technical support and it works
  fine as expected. Also, they promised about updating their
  documentation.

Answer:
I understand that you are trying to automate the process of API Gateway deployment using AWS CLI commands but you are not able to find configure Client Certificate for the stage.
There is no way to configure Client certificate using "create-deployment" command directly. After executing "create-deployment" command you need to use "update-stage" command to add client certificate as follows:
[+] http://docs.aws.amazon.com/cli/latest/reference/apigateway/update-usage.html
aws apigateway update-stage --rest-api-id API_ID --stage-name STAGE_NAME --patch-operations '[{"op":"replace","path":"/clientCertificateId","value":"CERTIFICATE_ID"}]'

If you want to generate new certificate, we can use "generate-client-certificate" command.
[+] http://docs.aws.amazon.com/cli/latest/reference/apigateway/generate-client-certificate.html
I kindly apologize for the inconvenience that this is not mentioned clearly in our documentation. I will request to our documentation team regarding the same.


text:
Q: Solving a QCQP problem with sparse regularization I want to solve the follong QCQP problem:
$$
\mbox{Minimize}\quad\beta^TA\beta+\mu\Omega(\beta)$$
$$
\mbox{s.t.}\quad\beta^TB\beta=1 \quad\mbox{and}\quad\beta\ge0
$$
where $A$ and $B$ are both positive definite, and $\Omega(\cdot)$ is a sparse(thus non-smooth, but still convex) norm, like $\ell_1$ norm or $\ell_1/\ell_2$ norm for a certain group set.
My tentative plan is to combine FISTA algorithm and Homotopy methods (a relevant paper I've found) for $f(\beta)=\beta^TA\beta++\lambda(\beta^TB\beta-1)+\mu\Omega(\beta)$, which can handle both $\beta$ and the Lagrange multiplier $\lambda$, but I did not find an algorithm considering the constraint $\beta\ge 0$(in the entry-wise sense). So can I improve the algorithm to embrace the conic constraits? Thank you.

A: There are several methods that one could apply to this problem. I don't have time to write out a full solution, but here's a quick idea. Replace $\Omega$ by $\hat\Omega = \Omega + \delta_+$, where $\delta_+$ is the indicator function for the nonnnegative orthant. Now, if you can reduce your problem to a proximal splitting method that works roughly as (not exactly this because of your equality constraints)
$$
 \beta^{k+1} \gets \mbox{prox}(\beta^k - \eta_k\nabla L(\beta^k)),
$$
where $L$ is the differentiable part of the problem, and $\mbox{prox}$ is the proximity-operator that handles $\hat\Omega$, then you are done.
Fortunately, the proximity-operator of $\hat\Omega$ is merely the composition of the proximity operator of $\Omega$ with projection onto the nonnegative orthant. Thus, in some sense, you can easily use FISTA style methods.


text:
Q: How to determine whether WCF Service is hosted within IIS or something else? I have a WCF Service that is sometimes hosted within IIS and sometimes hosted within a Windows Service. This is necessary for different deployment options for my application. What's a good way within the service object to determine where it is hosted?
The reason I want this is that when my service is hosted in IIS it gets connection string info from the web.config file in the normal way. When it's hosted by the windows service it gets config info in a different way (from info in the registry). Within the constructor of my service object I want to note where to get connection string info from, e.g. something like this:
public void MyServiceObject()
{
     _hostedInIis = isHostedInIis();
}
private string ConnectionString()
{
     if (_hostedInIis)
         return ConfigurationManager.ConnectionStrings["MyDatabase"].ConnectionString;
     else
         return GetConnectionStringFromRegistry();
}

Alternatively, is there a way I can pass some configuration information to it when I'm hosting it within the windows service? e.g. pass it the connection string or a flag saying it's hosted within the windows service.

A: I needed something similar when I set up a service to run either standalone with config, or under IIS with no config file at all. I ended up using a custom ServiceHostFactory for the IIS case. After the factory constructs the ServiceHost, it adds a custom configuration object to its Extensions property with the information that I couldn't put into web.config. Something like this:
protected override ServiceHost CreateServiceHost(Type serviceType, Uri[] baseAddresses)
{
  var host = base.CreateServiceHost(serviceType, baseAddresses);
  host.Extensions.Add(new CustomConfigurer());
  return host;
}

Then in the .svc file for the service, you can specify the custom factory, and IIS will just use it:
<%@ ServiceHost Service="..." Factory="..." %>

When your service operation is called, it can look for the config object on the host's extensions:
public int Add(int x, int y)
{
  var config = OperationContext.Current.Host.Extensions.Find<CustomConfigurer>();
  if (config == null)
  {
    // Load elsewhere
  }
}

A: I opted to subclass my service class and used the subclass when hosting in my Windows Service. The only difference in the subclass is that it knows to get its config info from the registry instead of the default location: the config manager. This is kinda nicer that what I originally wanted because the service doesn't need to know where it is.

A: probabily is not the best way but you can check HttpContext which is normally present in an Asp.net application
 private string ConnectionString()
        {
            if (HttpContext.Current!=null)
                return ConfigurationManager.ConnectionStrings["MyDatabase"].ConnectionString;
            else
                return GetConnectionStringFromRegistry();
        }


text:
Q: primefaces select tab when button is clicked I assume this is a rather simple issue, but I'm very new to Primefaces. I have a form that's including a few Primefaces tabs. Naturally I can view each tab when I click on it, but I'm looking for a way to go to a certain tab when a commandButton is clicked. Is there any way to do this?
Basically I'm looking for something like:
<h:commandButton value="Submit"
                onclick="<open a certain tab>"
                action="#{doSomeJavaWork}"
                update=":main_tabs:some_form" />

Thanks!

A: <h:commandButton ... onclick="tabViewWidgetVar.selectTab(2);" .../>


text:
Q: Could I move several files with terminal command "mv" on macOS? I have this problem when I try to move several files. I have 3 files that I need to move without putting on a subfolder.
These files have long names, which makes the task more difficult.
Example:
Lógica_matemática_para_ingeniería_de_sistemas_y_co..._----_(Pg_81--102).pdf
Lógica_matemática_para_ingeniería_de_sistemas_y_co..._----_(Pg_103--122).pdf
Lógica_matemática_para_ingeniería_de_sistemas_y_co..._----_(Pg_123--155).pdf

How to solve this problem in terminal?
I'll be very grateful.

A: If you're just trying to simplify the entry of long file names on the command lines, in bash you can use tab key to simplify the entry. e.g. enter the start of a command, e.g. mv L and then hit the tab key, and it will automatically autocomplete up to the point that the names are ambiguous (e.g. up to the page numbers). Autocomplete makes entering these names really easy.
If you're looking to rename a bunch of files, a common trick is to

*

*use ls to get list of relevant files and use sed to build script for renaming these files, e.g.:

$ ls L* | sed 's/^[^0-9]*\([0-9]*\)--\([0-9]*\)).pdf/mv "&" Pages\1-\2.pdf/'

That looks for a string of characters that aren't digits, then grabs the digits before and after the -- and then outputs a string mv followed by original name followed by new name that incorporates the page numbers. I know it's a bit hairy, but it's the power of regular expressions. And this doesn't actually do the renaming yet, but rather creates commands that can do the renaming should you choose to do so.
Anyway, that produces text output like:

mv "Lógica_matemática_para_ingeniería_de_sistemas_y_co..._----_(Pg_103--122).pdf" Pages103-122.pdf
mv "Lógica_matemática_para_ingeniería_de_sistemas_y_co..._----_(Pg_123--155).pdf" Pages123-155.pdf
mv "Lógica_matemática_para_ingeniería_de_sistemas_y_co..._----_(Pg_81--102).pdf" Pages81-102.pdf

You can google sed tutorials/examples if you want to figure out the rich array of alternatives available. And, if it gets really complicated, there are alternatives including awk and/or shell scripts.

*Anyway, once you visually inspect it and decide those generated mv commands look good, you can repeat the process, this time piping the output to sh to actually perform the renaming:

$ ls L* | sed 's/^[^0-9]*\([0-9]*\)--\([0-9]*\)).pdf/mv "&" Pages\1-\2.pdf/' | sh

There are other file renaming utilities that you can install, but old-school Unix folk will generally get sed do the process for us.


text:
Q: Pass user's session across activities What's the best strategy for authenticating users and holding their state throughout an app-run ? So far, I've thought about preferences and, probably, saving state through onSaveInstanceState. I'm not sure whether these approaches are applicable - what would you suggest ?

A: Look at the Application class, this may help you maintain global state variables between activities.


text:
Q: HttpServletResponseWrapper java.lang.ClassCastException using Java 4 and struts 1.3 I am currently working on a Legacy System. The system is using Java 4 and Struts 1.3. Well they're security is strict. Anyway
I was asked to create a logger for the request and response for their system. The idea is to have some audit for their new user interface and feature if there is a customer complain we can trace what happened by the logged request and response.
The idea is not to put a log on every module. Since they're using struts 1.3 my initial proposal is implement a module using Servlet Filter, ActionServlet or Requestprocessor. I have tried Servlet Filter but it can't work because they're web.xml is using http__java.sun.com_dtd_web_app_2.2.dtd. I have probelm find the 2.3 which is when Servlet Filter was introduced.
When I tried implementing a module using ActionServlet or Requestprocessor. I am atleast able to get the HttpServletRequest. However since this version of struts and java the HttpServletResponse really has no getter. I implemented a class that derives from HttpServletResponseWrapper.
When I used nothing is being received in the web browser. When I checked. I am getting a run time exception - java.lang.ClassCastException. I am not sure if HttpServletResponseWrapper can only be used with Servlet Filter or the library I have is old.
Basically this how I used in the Action Servlet.
public void doGet (HttpServletRequest request, HttpServletResponse response) throws IOException, ServletException
{

       responseCapture = new M2UResponseWrapper((HttpServletResponse) response);

        try
        {

            super.doGet(request, responseCapture);

        }
        catch (Exception e)
        {
            Logger.error("Exception Type 1 : " + e);
        }

    }

Below is my HttpServletResponseWrapper implementation. This is just my initial test.
public class MyResponseWrapper extends HttpServletResponseWrapper {

private final HttpServletResponse httpResponse;

private int responseStatus;
private String errMessage;
private String redirectURL;
private ArrayList responseCookieList;
private Map responseDateHeader;
private Map responseHeader;
private Map responseIntHeader;

protected M2UServletOutputStreamWrapper output;
protected CharArrayWriter charWriter;
protected PrintWriter writer;
protected boolean getOutputStreamCalled;
protected boolean getWriterCalled;

public M2UResponseWrapper (HttpServletResponse httpResponse) {
    super(httpResponse);
    this.httpResponse = httpResponse;
    getOutputStreamCalled = false;
    getWriterCalled = false;
    charWriter = new CharArrayWriter();
    output = new M2UServletOutputStreamWrapper();
    responseCookieList = new ArrayList();
    responseDateHeader = new HashMap();
    responseHeader = new HashMap();
    responseIntHeader = new HashMap();
}

public String toString() {
  return charWriter.toString();
}

public boolean containsHeader(String name) {
    return httpResponse.containsHeader(name);
}

public void addIntHeader(String name, int value) {
    responseIntHeader.put(name, Integer.toString(value));
    httpResponse.addIntHeader(name, value);
}

public void addDateHeader(String name, long date) {
    responseDateHeader.put(name,String.valueOf(date));
    httpResponse.addDateHeader(name,date);
}

public void addHeader(String name, String value) {
    responseHeader.put(name,value);
    httpResponse.addHeader(name, value);
}

public void setDateHeader(String name, long date) {
    responseDateHeader.put(name,String.valueOf(date));
    httpResponse.setDateHeader(name, date);
}

public void setHeader(String name, String value) {
    responseHeader.put(name,value);
    httpResponse.setHeader(name, value);
}

public void setIntHeader(String name, int value) {
    responseIntHeader.put(name, Integer.toString(value));
    httpResponse.setIntHeader(name, value);
}

public Iterator getHeader() {
    return responseHeader.keySet().iterator();
}

public Iterator getDateHeader() {
    return responseDateHeader.keySet().iterator();
}

public Iterator getIntHeader() {
    return responseIntHeader.keySet().iterator();
}

public void sendError(int sc) throws IOException {
    responseStatus = sc;
    try {
        httpResponse.sendError(sc);
    } catch (IOException e) {
        e.printStackTrace();
    }
}

public void sendError(int sc, String msg) throws IOException {
    responseStatus = sc;
    errMessage = msg;
    try {
        httpResponse.sendError(sc, msg);
    } catch (IOException e) {
        e.printStackTrace();
    }
}

public void setStatus(int sc) {
    responseStatus = sc;
    httpResponse.setStatus(sc);
}

public void setStatus(int sc, String sm) {
    responseStatus = sc;
    errMessage = sm;
    httpResponse.setStatus(sc, sm);
}

public String getErrorMessage() {
    return errMessage;
}

public int getStatus() {
    return responseStatus;
}

public String getRedirectURL() {
    return redirectURL;
}

public void sendRedirect(String location) throws IOException {
    responseStatus = 302;
    redirectURL = location;
    try {
        httpResponse.sendRedirect(location);
    } catch (IOException e) {
        e.printStackTrace();
    }
}

public  void addCookie(Cookie cookie) {
    responseCookieList.add(cookie);
    httpResponse.addCookie(cookie);
}

public ArrayList getCookie() {
    return responseCookieList;
}

public PrintWriter getWriter() throws IOException{

    if (getOutputStreamCalled) {
        throw new IllegalStateException("getOutputStream() has already been called on this response.");
    }

    try {
        if (writer != null) {
            writer = new PrintWriter(charWriter);
        }
    } catch (Exception e) {
        e.printStackTrace();
    }

    getWriterCalled = true;

    return writer;
}

public boolean isOutputStreamCalled() {
    return getOutputStreamCalled;
}

public boolean isWriterCalled() {
    return getWriterCalled;
}

public ServletOutputStream getOutputStream() throws IOException {

    if (getWriterCalled) {
        throw new IllegalStateException("getWriterCalled() has already been called on this response.");
    }

    getOutputStreamCalled = true;

    return (ServletOutputStream) output;
}

}

I have seen many example that HttpServletResponseWrapper is used to get HttpServletResponse but they are all implemented in the Servlet Filter. I don't know if I really can't use HttpServletResponseWrapper on Action Servlet or Requestprocessor because Servlet Filter the request and response are ServletRequest and ServletResponse objects.
Please note I am working on legacy system so upgrading to struts 3 or spring or using java web app 2.3 and above dtd is not really an option. I am just hoping I made a mistake with my wrapper implementation. If you guys have other suggestion.
I did pitch in to them I will use command shell run an admin sniffing tool for the logging. It was immediately rejected.

A: I don't know if its correct to post another question here. But I have found out what is wrong. The cast exception is originating from Broadvision version 6. It seems it has problem with HttpServletResponseWrapper. Does anyone have experience developing applications on broadvision, the documents I have on hand here, I believe is not complete.
I need maybe an example on how to create broadvision filter. I saw in on pdf that there is a broadvision filter but it mentions about creating a filter.xml which is similar to web.xml. But did not go into detail about what are methods that can be exploited in the broadvision filter class which I think is similar to Servlet Filter. It did not mention the sequence that will be followed like which has precedence the one in web.xml or filter.xml.


text:
Q: How to open a txt file and allocate its contents to a 2D array? So I have a txt file that represents a matrix. what I need to do is open it up and allocate its contents to a Matrix.
For example:
in my txt file I have:
 39  -1 -42 -42
 -6 -46  89  86
 76 -62  35  92
-20  24 -10  38
 52   1 -86  41

And I have int matrix[5][4];
I need to open up a file read its content and allocate each value respectively into a matrix
#include <stdio.h>
#include <stdlib.h>
#include <sys/types.h>
#include <sys/stat.h>
#include <fcntl.h>
#include <unistd.h>

int main(int argc, char **argv) {
  int matrix[4][5];

  FILE *files;
  char str[100];

  files = fopen("./matrix-samples/m-5-10-a.txt", "r");
  if(files == NULL) {
    printf("%s\n","error" );
    }
  else{
    fgets (str, 60, files);
    printf("%s", str);
        // now i have to get a single element from that line segment
  }

    return 0;
}

I have tried this method and I can get to the point where i slice the txt files into single line segments. Now all I need to do is get a single element and stick it to a required index and I got lost.


text:
Q: Why my GPU load is low when is rendering a scene with Blender? I have a scene in Blender and I render it with GPU Compute, Cycles.
The problem is when the scene is rendering, my GPU load is under the 5% while the CPU is doing all the render work.
My GPU is a Nvidia GTX 745 and my Cpu an Intel core I5. The blender version that I am using for render is 2.82a.
Anybody knows why is this happening?

A: You could go into the blender preferences, (edit>preferences>system>cycles render devices) and try looking for your GPU, as you may have 'none' selected.
It might be under a different path tracing GPU option


text:
Q: How to skip over a certain index position for txt file I have an assignment that requires me to analyze data for presidential job creation without using dictionaries. I have to open a text file and average data that applies to the democratic and republican presidents. I am having trouble understanding how to skip over certain lines (in my case I don't want to include the first line and index position 0, the years and months). This is what I have so far and a bit of the input file:
Year,Jan,Feb,Mar,Apr,May,Jun,Jul,Aug,Sep,Oct,Nov,Dec
1979,14090,14135,14152,14191,14221,14239,14288,14328,14422,14484,14532,14559
1980,14624,14747,14754,14795,14827,14784,14861,14870,14824,14900,14903,14946
1981,14969,14981,14987,14985,14971,14963,14993,15007,14971,15028,15073,15075
1982,15056,15056,15050,15075,15132,15207,15299,15328,15403,15463,15515,15538

def g_avg():
infile = open("government_employment_Windows.txt", 'r')

lines = []
for line in infile:
    print(line)
    lines.append(line)
infile.close()
print(lines)

mean = 0
for line in lines:
    number = float(line)
    mean = mean + number
mean = mean / len(lines)
print(mean)

A: Its a very very pythonic way to calculate this
with open('filename') as f:
        lines = f.readlines() #Read the lines of the txt
sum = 0
n = 0
for line in lines[1:]:     #Use the [1:] to skip the first row with the months
    row = line.split(',')  #Use the split to convert the line in a list separated by comma
    for element in row[1:]:  #Use the [1:] to skip the years
        sum += float(element)
        n += 1
mean = sum/ n

A: This also looks like a csv file, in which case you can use the built in csv module
import csv

total = 0
count = 0
with open("government_employment_Windows.txt", 'r') as f:
    reader = csv.reader(f)
    next(reader) #skips the headers
    for line in reader:
        for item in line[1:]:
            count += 1
            total += float(item)

print(total)
print(count)
print('average: ', total/count)

A: Use a slice to skip over the first line, i.e file.readlines[1:]
# foo.txt
line, that, you, want, to, skip
important, stuff
other, important, stuff

with open('foo.txt') as file:
    for line in file.readlines()[1:]:
        print(line)

important, stuff
other, important, stuff

Note that since I have used with to open a file, Python will close it for me automatically. If you have just done file = open(..) you will have to also do file.close()


text:
Q: Is there a way to update certain objects 'live' on a webpage with Python 3? I'm busy with my own http handler and I have managed to make a neat website with my own-written database handler.
However, is it someway possible to update a certain object live on a webpage? For example:

Hello

To:

Bye

LIVE? Because writing something to the webpage uses
self.wfile.write('
Hello
')

Is there something for example self.wfile.change (doesn't exist) that can change a certain object written to a user?
I know how to update data non-live(so by refreshing the webpage), but I really want the user to stay on a certain webpage and still get data updated...
... without javascript or php but Python 3

A: No, you can't. The fact is that the data was already sent to the client, and there is no way to perform such a replacement server-side. You need to instruct the client to perform said update, and Javascript is your only realistic option here.
If you want to stick with Python, you can explore projects like Brython, which allows you to execute a subset of Python client-side, but keep in mind that most online learning and help resources are focused on Javascript.

A: Anything you can do in PHP you can do in Python 3, so long as your web server supports Python apps.
There are two ways to change a portion of a page. One way is to rewrite the DOM using JavaScript. That's fine unless you already have a lot of viewers who have turned off JavaScript in their browsers. The other way is to divide the page into boxes, each containing a separate HTML document with a separate URL, and reference each box with an  element in the main page. Then you can have each  refresh itself periodically.
seamless.html:
<!DOCTYPE HTML><title>SO Example</title>

no main refresh

headerbar.html:
<!DOCTYPE HTML>
<meta http-equiv="refresh" content="5">

Inner refresh!

body.html:
<!DOCTYPE HTML>
Lorem ipsum


text:
Q: Two-way-binding for golang structs TLDR: Can I register callback functions in golang to get notified if a struct member is changed?

I would like to create a simple two-way-binding between a go server and an angular client. The communication is done via websockets.
Example:
Go:
type SharedType struct {
    A int
    B string
}
sharedType := &SharedType{}
...
sharedType.A = 52

JavaScript:
var sharedType = {A: 0, B: ""};
...
sharedType.A = 52;

Idea:
In both cases, after modifying the values, I want to trigger a custom callback function, send a message via the websocket, and update the value on the client/server side accordingly.
The sent message should only state which value changed (the key / index) and what the new value is. It should also support nested types (structs, that contain other structs) without the need of transmitting everything.
On the client side (angular), I can detect changes of JavaScript objects by registering a callback function.
On the server side (golang), I could create my own map[] and slice[] implementations to trigger callbacks everytime a member is modified (see the Cabinet class in this example: https://appliedgo.net/generics/).
Within these callback-functions, I could then send the modified data to the other side, so two-way binding would be possible for maps and slices.
My Question:
I would like to avoid things like
sharedType.A = 52
sharedType.MemberChanged("A")
// or:
sharedType.Set("A", 52) //.. which is equivalent to map[], just with a predifined set of allowed keys

Is there any way in golang to get informed if a struct member is modified? Or is there any other, generic way for easy two-way binding without huge amounts of boiler-plate code?

A: No, it's not possible.

But the real question is: how do you suppose to wield all such magic in your Go program?
Consider what you'd like to have would be indeed possible.
Now an innocent assignment
v.A = 42

would—among other things—trigger sending stuff
over a websocket connection to the client.
Now what happens if the connection is closed (client disconnected),
and the sending fails?
What happens if sending fails to complete before a deadline is reached?
OK, suppose you get it at least partially right and actual modification of the local field happens only if sending succeeds.
Still, how should sending errors be handled?
Say, what should happen if the third assignment in
 v.A = 42
 v.B = "foo"
 v.C = 1e10-23

fails?

A: you could try using server sent events (SSE) to send realtime data to the frontend, while sending a single post request with ur changes. That way you can monitor in the back and send data every second.


text:
Q: Gradle delete task dir cannot convert URL to a file I'm trying to delete some files from a folder that's in my server network through sftp.
task deleteTask(type: Delete, description: "Deletes the files in sftp://my.server.com") {
    delete fileTree(dir: "sftp://my.server.com")
}

And when I run ./gradlew deleteTask I get:
// my.server.com is just an example
> Cannot convert URL "sftp://my.server.com" to a file.

Tried looking for it on SO as well as other places but I didn't get anywhere. What's the proper way to point gradle to the server network for deleting files?

A: I guess using the delte is not the right approach. I would try using ant's FTP task to delete that file:
configurations {
   ftpAntTask
}

dependencies {
    ftpAntTask("org.apache.ant:ant-commons-net:1.9.4") {
        module("commons-net:commons-net:1.4.1") {
            dependencies "oro:oro:2.0.8:jar"
        }
    }
}

task ftp << {
    ant {
        taskdef(name: 'ftp',
                classname: 'org.apache.tools.ant.taskdefs.optional.net.FTP',
                classpath: configurations.ftpAntTask.asPath)
        ftp(server: "ftp.apache.org", userid: "anonymous", password: "me@myorg.com" action: "delete") {
            fileset(dir: "htdocs/manual")
        }
    }
}

This is copied and modified from the gradle docs: https://docs.gradle.org/current/userguide/organizing_build_logic.html


text:
Q: Mac graphical emacs printing $(D when I press delete When I press the delete (not backspace) key in the GUI version of emacs, it prints $(D to the file (all 3 separate characters plus a space at the end).
The question is how can I fix this so that pressing delete performs a forward delete?
This only happens in my D Language Mode, so in an effort to debug this, I eliminated as much of the d-mode.el file as I could while still having the problem/being able to load the file at all... the result looks like this:
    (require 'cc-mode)
    (define-derived-mode d-mode nil "" "" nil)

I load this file with the following lines in my .emacs file:
    (autoload 'd-mode "~/.emacs.d/vendor/d-mode" "Major mode for editing D code." t)
    (add-to-list 'auto-mode-alist '("\\.d[i]?\\'" . d-mode))

I do not experience this problem when:

*

*Using emacs in the terminal

*In another mode, cpp mode, java mode, etc

I also get the same character sequence printed when I press C-d as an alternative to delete.
It may be helpful to know that I am using emacs on a Mac and that I downloaded emacs from here.


text:
Q: How to commit inside a CURSOR Loop? I am trying to see if its possible to perform Update within a cursor loop and this updated data gets reflected during the second iteration in the loop.
DECLARE cur CURSOR
FOR SELECT [Product], [Customer], [Date], [Event] FROM MyTable
WHERE [Event] IS NULL

OPEN cur
FETCH NEXT INTO @Product, @Customer, @Date, @Event
WHILE @@FETCH_STATUS = 0
BEGIN
  SELECT * FROM MyTable WHERE [Event] = 'No Event' AND [Date] < @DATE
  -- Now I update my Event value to 'No Event' for records whose date is less than @Date
  UPDATE MyTable SET [Event] = 'No Event' WHERE [Product] = @Product AND [Customer] = @Customer AND [Date] < @DATE
   FETCH NEXT INTO @Product, @Customer, @Date, @Event
END
CLOSE cur
DEALLOCATE cur

Assume when the sql executes the Event column is NULL for all records
In the above sql, I am doing a select inside the cursor loop to query MyTable where Event value is 'No Event' but the query returns no value even though I am doing an update in the next line.
So, I am thinking if it is even possible to update a table and the updated data get reflected in the next iteration of the cursor loop.
Thanks for any help,
Javid

A: Firstly You shouldn't need a cursor here. Something like the following would have the same semantics (from a starting position where all Event are NULL) and be more efficient.
WITH T
     AS (SELECT [Event],
                RANK() OVER (PARTITION BY [Product], [Customer]
                                 ORDER BY [Date] DESC) AS Rnk
         FROM   MyTable)
UPDATE T
SET    [Event] = 'No Event'
WHERE  Rnk > 1

Secondly regarding the question in the title to commit inside a cursor loop is the same as anywhere else. You just need a COMMIT statement. However if you aren't running this inside a larger transaction the UPDATE statement will be auto committed anyway.
Thirdly Your real question doesn't seem to be about commit anyway. It is about the cursor reflecting updates to the data on subsequent iterations. For the case in the question you would need a DYNAMIC cursor

Defines a cursor that reflects all data changes made to the rows in
  its result set as you scroll around the cursor. The data values,
  order, and membership of the rows can change on each fetch.

Not all queries support dynamic cursors. The code in the question would but without an ORDER BY it is undeterministic what order the rows would be processed in and thus whether you would see visible results. I have added an ORDER BY and an index to support this to allow a dynamic cursor to be used.
If you try the following you will see the cursor only fetches one row as the dates are processed in descending order and when the first row is processed the table is updated such that no more rows qualify for the next fetch. If you comment out the UPDATE inside the cursor loop all three rows are fetched.
CREATE TABLE MyTable
  (
     [Product]  INT,
     [Customer] INT,
     [Date]     DATETIME,
     [Event]    VARCHAR(10) NULL,
     PRIMARY KEY ([Date], [Product], [Customer])
  )

INSERT INTO MyTable
VALUES (1,1,'20081201',NULL),
       (1,1,'20081202',NULL),
       (1,1,'20081203',NULL)

DECLARE @Product  INT,
        @Customer INT,
        @Date     DATETIME,
        @Event    VARCHAR(10)

DECLARE cur CURSOR DYNAMIC TYPE_WARNING FOR
  SELECT [Product],
         [Customer],
         [Date],
         [Event]
  FROM   MyTable
  WHERE  [Event] IS NULL
  ORDER  BY [Date] DESC

OPEN cur

FETCH NEXT FROM cur INTO @Product, @Customer, @Date, @Event

WHILE @@FETCH_STATUS = 0
  BEGIN
      SELECT @Product,
             @Customer,
             @Date,
             @Event

      -- Now I update my Event value to 'No Event' for records whose date is less than @Date
      UPDATE MyTable
      SET    [Event] = 'No Event'
      WHERE  [Product] = @Product
             AND [Customer] = @Customer
             AND [Date] < @Date

      FETCH NEXT FROM cur INTO @Product, @Customer, @Date, @Event
  END

CLOSE cur

DEALLOCATE cur

DROP TABLE MyTable

A: Even if this worked, this would not guarantee the correct result since you miss an ORDER BY clause in your query.
Depending on this, all records, no records or any random subset of records could be updated.
Could you please explain in plain English what your stored procedure should do?

A: Use Below template
DECLARE @CCount int = 100
    DECLARE @Count int = 0
    DECLARE  @id AS BigInt

    DECLARE cur Cursor fast_forward for
        SELECT t1.Id
             FROM Table1 t1 WITH (NOLOCK) WHERE  <Some where clause>
    OPEN cur
    Begin Tran

    While (1=1)
    Begin
        Fetch next from cur into @id
        If @@Fetch_Status <> 0
            break
    -- do some DML actions
        Delete From Table1 WITH (ROWLOCK) where Id = @id
        Set @count = @count + @@Rowcount

        if (@count % @CCount = 0)
        Begin
            if (@count % 100 = 0)
                Print 'Table1: DML action ' + Cast(@count as Varchar(15)) + ' rows'
    -- for every 100 rows commit tran will trigger , and starts a new one.
            While @@Trancount > 0 Commit Tran
            Begin Tran
        End
    End

    While @@Trancount > 0 Commit Tran
    Close cur
    Deallocate cur


text:
Q: How to overcome limitations of itsdangerous for SSO: encryption and expired tokens I have built several related applications using Python and Flask. One is an authentication app where the user logs in and receives a token. The others are business apps, which authenticate and authorize the user based on the token. Of course it's necessary to sign the token to prevent tampering. Since I'm using Python, the itsdangerous module is a natural choice. But it doesn't provide some features that seem important. Writing one's own security code is rarely a good idea, but I feel forced to add my own code on top of itsdangerous to address some limitations. I'd like to know:
a. Are the concerns below valid?
b. If so, can anyone recommend a good open-source security solution for Python/Flask that addresses them?
The two limitations that most concern me are:

*

*Lack of encryption. Itsdangerous can sign the token but can't encrypt it. The token might contain information the user shouldn't see, such as a list of which roles he or she has been granted.

*Leaking information about whether an expired token was ever valid. A malicious user who got hold of a token could use itsdangerous to differentiate between tokens that were never valid, and tokens that used to be valid but have expired. It would be better if such a user could tell only that the token is invalid, with no indication as to why.

A:

*

*Lack of encryption. Itsdangerous can sign the token but can't encrypt it. The token might contain information the user shouldn't see, such as a list of which roles he or she has been granted.

I don't see the harm in letting a user see what roles he's been grated. But if you don't want that visible in the token, you could simply treat the token as an identifier and establish a relationship between the token and the user and consequently the user's roles.
If the token truly contains private data, then you should encrypt it first (e.g., using PyCrypto), and then sign it (e.g., using itsdangerous or hmac).
See Should we MAC-then-encrypt or encrypt-then-MAC? for information about the order of signing and encrypting data.

*Leaking information about whether an expired token was ever valid. A malicious user who got hold of a token could use itsdangerous to differentiate between tokens that were never valid, and tokens that used to be valid but have expired. It would be better if such a user could tell only that the token is invalid, with no indication as to why.

If you encrypt the token, or if the token is simply an identifier, then a malicious user should only be able to tell if the token is currently valid (i.e., it works right now) but not whether any other token would be valid without directly using it. But why would knowing ahead of time whether a token is valid or not affect security?


text:
Q: Calculation of integral around circle I had the equation$$\int(xdy-ydx)$$around the circle
$$x^2+y^2=1$$
I tried this:
$$\begin{align}x&=(1-y^2)^{1/2}\\y&=(1-x^2)^{1/2}\end{align}$$
$$\int(1-y^2)^{1/2}dy-\int(1-x^2)^{1/2}dx=0$$
The limits of both $x$ and $y$ are same so both should cancel out and give ans$= 0$
but the answer is $2\pi$.

A: I don't know whether you took the correct Cartesian limits, but it's more convenient to work in polar coordinates. Since the circle is $r=1$,$$xdy-ydx=\cos\theta\cdot\cos\theta d\theta-\sin\theta(-\sin\theta)d\theta=d\theta.$$Now it's obvious the answer is $2\pi$.

A: Alternatively we can use Green's theorem:  $$\int_C Pdx + Qdy=\int_D(Q_x-P_y)dA$$
where C is a simple closed curve, D is the area bounded by C.  In your integral, we have $$P=-y$$, $$Q=x$$, C is the unit circle, D is the unit disk. So $$P_y=-1$$$$Q_x=1$$
and our integral switches to just
$$\int_D(1-(-1))dA$$
and since the area of the unit circle is $\pi$,  there you go.