text:
Q: Net work done on the body when we lift it and put it on the table is zero? I'm little confused here. Work done on the body when we lift it and put it on the table is zero, because according to work energy theorem, change in kinetic energy of the body is zero. So, the net work done is zero.
Fine, but now the object has $mgh$ (where $m=$mass of body; $h=$height of body) amount of potential energy stored in it. If the net work done is zero then who has increased its energy?
I'm confused and unable to think it through kindly help.

A: You did net work on the body.  Gravity did negative net work on the body.  The over all work done was zero.  The original confusion arose because the work-energy theorem demands we calculate the change in kinetic energy using the net force on the body, but your question considered only the force exerted by you, and ignored that exerted by gravity.
If  the body has mass $m$, you were putting a force $mg$ on it to raise it at constant speed.  The work-energy theorem says that if you had done this when there were no other forces on the body, the body would have gained kinetic energy $mgh$ as you moved it from the floor to the table.
That analysis ignores gravity, though.  Gravity pulled down on the box with force $-mg$.  This means the work done by gravity was $-mgh$, and so the total work done on the box was zero.  This makes sense because if you lift the box at constant speed, the net force on the box is zero by $F = ma$.
If the box starts by sitting stationary on the floor, there would have to be some small net work done on the box to get it started going up.  There would  have to be some small negative net work on it to get it to stop.

A: To answer such a question one must define the system under consideration.
System - body alone
An upward force $F$ lifts the body by a vertical distance $h$.
The two external forces acting on the body are the force $F$ and the weight of the rock $W=mg$.
The net work done on the body is $(F-W)h$ and this is equal to the change in the kinetic energy of the body which is zero if the two external forces are equal in magnitude.
System - body and Earth
The only external force is $F$ and let this force have the same magnitude as the weight of the body.
That single force $F$ cannot move the body further away from the Earth.
All that force can do is move the centre of mass of the body and Earth system.
To separate the body and the Earth two forces of magnitude $F$ but opposite in direction must act on the body and the Earth.
Because the mass of the Earth is so much greater than the mass of the body the displacement of the Earth relative to the centre of mass of the Earth and body system is very small compared to the displacement of the body.
The work done on the Earth by the external forces is negligible compared with the work done on the body.
The work done by the external forces on the Earth and body system is $Fh$.
The increase in gravitational potential energy of the system is $Fh$ which is $mgh$.
What is often not appreciated is that it is the body and the Earth system which has the gravitational potential energy not the body alone.
As a result of the mass of the Earth being so much larger than the mass of the body the motion of the Earth is always so much smaller than the motion of the body and so the motion (change in kinetic energy) of the Earth is ignored (assumed to be negligible) compared with the motion (change in kinetic energy) of the body.

A: Don't complicate things for youself.Net work done is a simple term , which means the transfer in energy to do certain work(where energy transfers , not transform into its original form) .In the above case energy is transferred and then transform into its original form (another e.g is "SPRING").

A: There is work because the box transfer from one place to another which means there is a change in position.


text:
Q: TLS 1.0 not supported between client and server I am having problems trying to get a Https connection between a desktop fat client application and a server.
After much searching I found on server system logs, the following error message, "An TLS1.0 connection was received from a remote client application , but none of the cipher suites supported by the client are supported the server. The SSL connection request has failed."
Checking in Internet explorer the connection fails with the same error message when I type in the https address. However, if I type in the address in Chrome or in Firefox the connection works and I get a successful json response. In Wireshark I note that the number of cipher algorithms being presented by IE is a lot less than Firefox and chrome.
Is there a way to fix this problem? The application I have to work with is an existing app, and needs to be https in order to link with a new restful service from a new application.
I have been banging on with this problem for a few days and run out of ideas.

A: You have a cipher suite mismatch.
The server and client (browser) will attempt to agree on a cipher suite. In your case, it sounds like Internet Explorer  and .NET are not using a cipher suite that the server supports.
Both Internet Explorer and the .NET Framework use SChannel under the covers to make HTTPS connections. More specifically, the .NET Framework classes that are part of the BCL. It is entirely possible to re-implement SSL/TLS and not use SChannel.
Without knowing what the actual cipher suites are by both the client and server, it's hard to say.
SChannel is configurable by Group Policy to tune which cipher suites are enabled. Not that SChannel is not capable of doing every cipher suite possible that servers may support. This would need to be applied the desktops where the thick client runs.
Alternatively you can configure the server to accept cipher suites that your clients support. How to do that depends on your web server.

redpajama_set_name: RedPajamaStackExchange


text:
Q: .Net Core SFTP integration tests in Bamboo on CentOS I'm writing integration tests for SFTP code, so my tests use an SFTP server library to spin up an SFTP server listening on a random port for each test case. Using .Net Core on Visual Studio 2019 for Mac, my tests all succeed. When I run on the Bamboo build server whose agents are running CentOS, I get the following error:
05:01:09.4224  ERROR Failed to connect to localhost System.Net.Sockets.SocketException (111): Connection refused
15-Aug-2020 05:01:10        at Renci.SshNet.Abstractions.SocketAbstraction.Connect(IPEndPoint remoteEndpoint, TimeSpan connectTimeout)
15-Aug-2020 05:01:10        at Renci.SshNet.Session.SocketConnect(String host, Int32 port)
15-Aug-2020 05:01:10        at Renci.SshNet.Session.Connect()
15-Aug-2020 05:01:10        at Renci.SshNet.BaseClient.CreateAndConnectSession()
15-Aug-2020 05:01:10        at Renci.SshNet.BaseClient.Connect()

The logs indicate that the SFTP server is starting up and binding to the random port correctly, so I'm not sure why the outbound connection to localhost would fail.

A: localhost didn't work, but 127.0.0.1 did work. Apparently the build agent doesn't have the localhost name configured.


text:
Q: pivot rows to columns based on condition I have a table like so
id  student_id  score
1   1           45
2   2           55
3   2           75
4   3           80
5   1           90
6   2           78
7   3           55
8   1           45
9   1           65

I want to arrange it like this
student_id s1   s2   s3   s4
1          45   90   45   65
2          55   75   78   -
3          80   55   -    -

the concept of pivot is
SELECT
  item_id,
  MAX(IF(property_name = 'property_value1', value, NULL)) AS alias1,
  MAX(IF(property_name = 'property_value2', value, NULL)) AS alias2,
  ...
  ...
  ...
FROM
  table
GROUP BY
  item_id;

which i cannot really figure out in my case, as i am creating the columns s1 - s4 by occurrence, i.e the first score for each student becomes s1, second becomes s2 etc.
how do i solve this

A: The simplest method is to put the values in a single column:
select student_id, group_concat(score order by id)
from t
group by student_id;

That is sufficient for many purposes.  If you want separate columns, you need to create a column.  One way uses variables:
select student_id,
       max(case when rn = 1 then score end) as score_1,
       max(case when rn = 2 then score end) as score_2,
       max(case when rn = 3 then score end) as score_3,
       max(case when rn = 4 then score end) as score_4
from (select t.*,
             (@rn := if(@s = student_id, @rn + 1,
                        if(@s := student_id, 1, 1)
                       )
             ) as rn
      from t cross join
           (select @s := -1, @rn := 0) params
      order by student_id, id
     ) t
group by student_id;


text:
Q: enable acl in VPS How can I enable acl in my VPS? I have the next in /etc/fstab:
proc  /proc       proc    defaults    0    0
none  /dev/pts    devpts  rw          0    0

And executing df I get:
Filesystem     1K-blocks    Used Available Use% Mounted on
/dev/simfs      52428800 1971916  50456884   4% /
none              104860      64    104796   1% /run
none                5120       0      5120   0% /run/lock
none              524288       0    524288   0% /run/shm

When I try to do:
setfacl -R -m u:www-data:rwx -m u:manolo:rwx app/cache

I get "operation not supported" for each file.

A: You are using OpenVZ. In this case you need to open a ticket with the service provider; the community cannot help.

A: You can issue the command: mount / -o remount,acl


text:
Q: Авторское право в программировании (Интеллектуальная собственность) У меня есть программа , она преследует какую то идею соответственно. Тут какой-то программист Вася Пупкин из другого конца страны увидел мою программу и сделал тоже самое (может с какими то улучшениями) назвал её также и распространяет её, и получает мою славу.
Что кроме "карма" может помешать это сделать? Или может каким-то образом я смогу уберечь программу (зарегистрировать авторские права)? Или этот вопрос абсурд?
Вообще поясните если я что-то не понимаю. Может оно и правда не надо?

A: Программа есть и всегда была интеллектуальной собственностью. Поэтому только подходя к этому вопросу с данной стороны можно пытаться судиться. Но доказать, что код ваш практически невозможно. Грубо говоря вы даже не имеете права без разрешения автора использовать в своих программах простейшие циклы, которые вы нашли в книге, например:
for(int i=0; i<var; i++) doSomth();

Что касается патентов, вы всегда можете зарегистрировать свое творение за границей. Естественно патент будет не действителен в России или других странах в зависимости от того, где патентовались, зато Василий Пупкин уже не сможет продавать данную программу в стране, патент которой вы получили.
Что касается торговых марок и названий, их так же можно регистрировать. Обычно существуют локальные регистры (например на страну), а есть глобальные, как приводили пример, Apple, товарный знак, торговая марка уже зарегистрирована и использовать ее нельзя. Но только для продукции той же специфики. Т.е., например, если вы собираете яблоки и называете себя Apple, вы так же можете зарегистрировать эту торговую марку и она будет вполне легальна и совершенно не будет идти в противовес существующей.
Регистрировать сам код тоже считаю бессмысленным, снова повторюсь, даже если он зарегистрирован, доказать что у вас код передрали будет очень проблематично.
UPD
Вот еще есть вопрос и ответ к нему, который хорошо иллюстрирует то, что происходит с кодом автора. @quyse абсолютно прав, общался я с юристом по этому вопросу.

A: Если ты придумал что-то новое, то единственный способ защитить права - патент. Причем читал как-то, что коды в России не патентуются. Можно запатентовать новые технологии. А иначе - никак. Хотя я не юрист, может, и не прав.
А вообще, нужно больше думать о благе человечества.
A: Тогда был бы у нас один гугл, и ни каких яндексов, и тому подобное. И да запатентовать "код" в России никак. да и как бы мы жили с таким - одни монополисты бы были :) здоровая конкуренция всегда хороша))
udp: на счет одинаковых названий не в курсе но, в России например мильон ООО могут иметь одинаковые названия :) а вот каким-нибудь эплом назвать уже нельзя, фактически то можно, но примерно какой-нить магазинчик в деревне)


text:
Q: dc.js heatmap colour range not getting updated after filter applied I'm using dc.js to create a dashboard, the dataset contains 3 types of reading from 1 year in a 24 hour basis. (in the example fiddle, i only use 15 days just for demonstration purpose)
Here is the link to a JSFiddle to better illustrate my problem http://jsfiddle.net/table315/hLzLzhss/
I've used a row chart to show the total of each reading, and a heatmap to show the total reading of each day at each time.
When 1 type of reading from the row chart has selected, the heatmap doesn't seems to recalculate the min and max of the colour domain. (a heatbox shows a light colour even the value is the highest in the current filtered dataset. )
dayAndTimeChart
  .width(30 * 24 + 500)
  .height(20 * 31)
  .dimension(dayAndTimeDimension)
  .group(dayAndTimeGroup)
  .keyAccessor(function(d) {
    return d.key[0];
  })
  .valueAccessor(function(d) {
    return d.key[1];
  })
  .colorAccessor(function(d) {
    return d.value;
  })
  .colors(["#fff7ec", "#fee8c8", "#fdd49e", "#fdbb84", "#fc8d59", "#ef6548", "#d7301f", "#b30000", "#7f0000"])
  .calculateColorDomain()
  .title(function(d) {
    return "Time:   " + d.key[0] + "\n" +
      "Day:  " + d.key[1] + "\n" +
      "value: " + d.value;
  });

Is there something I'm missing here? or is it a bug? if that is the case, is there any workaround?

A: This is by design, because the color mapping may have some absolute meaning.
So if you want the domain to adjust and show the full range of colors for each new set of values, you need to calculateColorDomain() each time the chart is redrawn:
.on('preRedraw', function() {
    dayAndTimeChart.calculateColorDomain();
})

Working fork of your fiddle: http://jsfiddle.net/gordonwoodhull/w1mzwv8d/2/


text:
Q: Shift the Page title away from the logo I have used the following power shell commad to add our compnay logo:-
$webApp = Get-SPWebApplication http://gvstg01:40708
$webApp.SuiteBarBrandingElementHtml = ''
$webApp.Update()

but currently the logo and the page title are being two close , so i there a way to modify the above script to shift the text to the right, away from the logo .currently the logo and text are being displayed as follow:-

A: Not that it is SharePoint specific, but you could do an inline style on the link, if you do not have the option to update the master page CSS to work as expected.
To do this workaround run this command:
$webApp = Get-SPWebApplication http://gvstg01:40708
$webApp.SuiteBarBrandingElementHtml = ''
$webApp.Update()

To make it work, since I do not have your master page or resulting markup, you might need to alter the margin, or try with a padding instead.
If it still does not work, you need to do the fix in the master page CSS files rather than in you logo element.

A: i added the following and it shofted the logo:-
#pageTitle {position: absolute; left: 400px; top: 40px;color:white; margin-left:20px;}


text:
Q: Invalid pthread_t value? I am currently writing a piece of code where I want to perform an action against every thread on a system except (possibly) a single specified thread.  I'd like to do something like:
void do_something_to_all_but(pthread_t except = PTHREAD_NULL) {
    for (pthread_t tid : myThreads)
    {
        if (pthread_equal(tid, except)) continue;
        do_something(tid);
    }
}

However, I have not (as of yet) found an appropriate value to use for PTHREAD_NULL.  I know that (at least in Linux) pthread_t is defined as an opaque unsigned long int (presumably to disguise an internal representation), but I'd hope there's a (preferably portable) way to specify a pthread_t value that is guaranteed not to compare to any valid pthread_t value.


text:
Q: How to create a notification server which informs Delphi application when database changes? We need to be able to inform a Delphi application in case there are changes to some of our tables in MySQL.
Delphi clients are in the Internet behind a firewall, and they have to be authenticated before connecting to the notification server we need to implement. The server can be programmed using for example Java, PHP or Python, and it has to support thousands of clients.
Typically one change in the database needs to be informed only to a single client, and I don't believe performance will be a bottleneck. It just has to be possible to inform any of those thousands of clients when a change affecting the specific client occurs.
I have been thinking of a solution where:

*

*MySQL trigger would inform to notification server

*Delphi client connects to a messaging queue and gets the notification using it

My questions:

*

*What would be the best to way from the trigger to inform the external server of the change

*Which message queue solution to pick?

A: Answer to the First Question:
check this question and answers on Stack Overflow:
When a new row in database is added, an external command line program must be invoked
In theory, a simple user-defined function could be used to fire a 'row changed' message to a message broker / queue. But this involves external systems (at least a network subsystem) which can fail - and bad things can happen.
A different solution which does not require dangerous modifications to the database system would be a multi-tiered design for the application. The server application which hosts the business logic then needs to generate 'database content changed' events, post them to a publish and subscribe message channel (aka 'topic') on the message broker so that every client will receive a copy of this message immediately or if the client reconnects (using 'durable subscriptions').

I wrote a related blog article about this topic here: Firebird Database Events and Message-oriented Middleware
Answer to the Second Question:
The creators of Second Life have evaluated a couple of message brokers and published their results - for some of the products, Delphi client libraries exist or can be implemented using standard protocols: Message Queue Evaluation Notes
Since then, other products have been released, some of them can also be integrated with Delphi clients through non-Java protocols, for example:

*

*Open Message Queue (OpenMQ) 4.4, which is the default JMS provider broker in the Sun GlassFish v3 application Server

*JBoss HornetQ 2.1 which will be the default JMS provider in JBoss application server 6. HornetQ 2.0.GA obtained scores up to 307% higher than previously published SPECjms2007 benchmark results, on the same server hardware and operating system set-up.

A very popular open source message broker which can be used from Delphi, Java, PHP, C# (and other) clients is

*

*Apache ActiveMQ 5.4.1 - free introduction chapter of "ActiveMQ in Action" by Bruce Snyder, Dejan Bosanac, and Rob Davies

All brokers are designed for thousands of concurrent clients and tens of thousands of messages per second. They also typically support clustering and failover, though this is not part of the JMS specification.
If speed is not so important, but you need High availability (even if your internal system is down), Amazon Simple Queue Service (Amazon SQS) is a cloud-based service which can be accessed using REST and Soap style interfaces.

A: There is apache camel and spring intergration, both provides some ways to send messages across.

A: Why not use the XMPP protocol (aka Jabbber) ?


text:
Q: how create highlighting/illumination like voicebase Is possible reproduce online final transcript, something like this:
https://app.voicebase.com/autonotes/private_detail/17519536/hash=apuaYW1qaW6WaG7FlmaTcWuPmJ2YlWZsmGjHkZluxZhmlpaUl2ebmptrl5vE?vbt=0, illuminating each word or phrase

A: The transcript was generated using Voicebase speech recognition software. One of the formats in which the transcript is provided by Voicebase is called SRT. This format has the start time and end time of the sentences. In this case, the webpage you pointed to is using the SRT and the player time of the audio to highlight the sentences.


text:
Q: Video resolutions at 60FPS with Camera2 API What is the standard way to verify if video recording supports 60fps, and at which recording resolutions is actually supported?
With the next method I can get the range of supported framerates:
CameraCharacteristics.get(CameraCharacteristics.CONTROL_AE_AVAILABLE_TARGET_FPS_RANGES)

But how can I find at which video recording resolutions is 60FPS supported?
Note that in the Camera2 API, 60fps is not a high-speed framerate, therefore cannot call: StreamConfigurationMap.getHighSpeedVideoSizesFor(fpsRange), as such throws an IllegalArgumentException if queried with a non-high-speed framerate.


text:
Q: How to selectively remove a particular value from a column which contains more than one value each separated by a comma, using SQL? for example, consider a table like below (table name=accounts)
account        owner_ids
PA account     sa123,rt458,hf678,de348f
RA account     gg678n,fk980,rt458,hf678

Here, I want to remove owner_ids "rt458" and "hf678" from the entire table and after removing the commas should be perfect (I mean after removing also the remaining owner_ids should be separated by comma as before and there should not be any unnecessary comma in the column)
Any kind of help is appreciated, Help me out guys

A: You can use REPLACE function twice:
update accounts
set owner_ids = REPLACE(REPLACE(owner_ids,
             ',rt458' ),',hf678');

REPLACE returns char with every occurrence of search_string replaced with replacement_string.

Or you can use REGEXP_REPLACE to replace/remove those values by regex:
update accounts
set owner_ids = REGEXP_REPLACE(owner_ids,
             '(\,rt458||\,hf678)', '');

REGEXP_REPLACE extends the functionality of the REPLACE function by letting you search a string for a regular expression pattern.

To support case where rt458 is the first entry in the CSV list (As @TimBiegeleisen commented) you will have to allow no comma as:
update accounts
set owner_ids = REGEXP_REPLACE(owner_ids,
             '(\,{0,1}rt458||\,{0,1}hf678)', '');

Using replace you will need to double calls:
update accounts
set owner_ids = REPLACE(REPLACE(REPLACE(REPLACE(owner_ids,
             ',rt458' ),',hf678', 'rt458,', 'hf678,');

Also you can see other solutions to remove value from comma separated string

A: UPDATE accounts
SET owner_ids = TRIM(BOTH ',' FROM
    REPLACE(REPLACE(CONCAT(',', owner_ids, ','), ',rt458,', ''), ',hf678,', '')
);

First prepend and append the field with a comma CONCAT(',', owner_ids, ',') to make it uniform.
Then, remove ,rt458, and ,hf678, from it.
Later remove commas from both at the start and end which we added to make the structure uniform.
This will maintain single commas between the values.

Please note, you should prefer normalizing owner_ids so that such updates are easy to handle.


text:
Q: How to make user menu in wordpress, different for each user I got some question regarding WordPress, I wanted to know is there any way I can achieve this type of scenario.

*

*Users can buy a photo, their own photos. For example, user A can buy only a photo with their face in it.

*Same goes for User B.

*In each of the photos that have been bought, they can see their own on their dashboard. For example, link-example.com/home will show them the menu, which will redirect to their own photos that have been bought. (Concept like a password-protected page, need to enter the password, then only the content will show up.)

*Each user will be provided a password, and will redirect to the page. And the menu will be different for each user. (Users can be many)
Are there any plugins available to achieve this issue?

Click here to view the interface draft
The idea is kinda like this website,
http://pret-a-portrait.net/
I hope the question is clear as I provide the photos of the concept

A: Woocommerce has the eCommerce side of things to be able to take payments and setup your photos as a product. It's free and easier to setup than your toaster.
The documentation with extending it is also very well written and I personally have gone to town on a my-account page in the past so anything you can dream up is possible with the right research. I think giving it a go and just having a Google of things like adding a tab to my-account woocommerce will make things more clear for you.
https://woocommerce.com/


text:
Q: TypeScript Compiler Options for strict code compliance beyond strict mode We would like to configure TSC hopefully with a command line option to generate errors when developers declare class fields using implicit type expressions instead of explicit see code below.
class Appliance {
    //coding style we want to enforce:
    private _group:Group = new Group();

    //coding style we want to prevent by issuing error:
    private _group = new Group();

    //coding style we want to enforce as it does not rely only on
    //constructor parameters list for declaration
    public assetTag:EquipmentTag;

    public constructor(assetTag:AssetTag,
        //coding style we want to prevent by issuing error if
        //no explicit declaration above constructor
        supplier:Company) {

        this.assetTag = assetTag; //coding style we want to enforce
    }

}

We use strict mode for TSC but it still allows for some casual coding style as shown.
Is there any TSC option we can use to go beyond strict mode and enforce some coding style compliance?

A: Just as Titian suggested, code style is enforced by ts-lint https://palantir.github.io/tslint/
The Rule you are looking for: https://palantir.github.io/tslint/rules/typedef/


text:
Q: How to solve (x+1)e^x=c(constant) in Python? I would like to solve the (x+1)e^x=c equation in Python.
The equation has been successfully solved by hand using lambert w functions as depicted in the figure below:

Using same steps, I would like to solve (x+1)e^x programmatically. I have coded it using the module SymPy as per the step shown in the figure above , but without success.
Is there any to solve these kinds of equations in Python?
import numpy as np
from sympy import *
n = symbols('n')
sigmao=0.06866
sigmas=0.142038295
theta=38.9
rad=(np.pi/180)*38.9076
cos=np.cos(rad)
sec=1/np.cos(rad)
out = (0.06*0.7781598455*n*(1-exp(-2*0.42*sec*n))+exp(-2*0.42*n*sec)*sigmas)/sigmao
#Apply diff for the above expression.
fin=diff(out, n)
print(solve(fin,n))

A: from scipy.optimize import fsolve
import numpy as np

const = 20
def func(x):
    return [(x[0]+1) * np.exp(x[0]) - const]

result = fsolve(func, [1])[0]
print('constant: ', const, ', solution: ', result)
#check
print('check: ', (result+1) * np.exp(result))

#Output[]:
    constant:  20.0 , solution:  1.9230907433218063
    check:  20.0

Preview : https://onlinegdb.com/By8Z2Jwgw

A: Your expression is very numeric. As sympy's solve tries to find a perfect symbolic solution, sympy gets into troubles.
To find numeric solutions, sympy has nsolve (which allows sympy's expressions but behind the scenes calls mpmath's numeric solver). Unlike solve, here an initial guess is needed:
from sympy import symbols, exp, diff, nsolve, pi, cos

n = symbols('n')
sigmao = 0.06866
sigmas = 0.142038295
theta = 38.9076
rad = (pi / 180) * theta
sec = 1 / cos(rad)
out = (0.06 * 0.7781598455 * n * (1 - exp(-2 * 0.42 * sec * n)) + exp(-2 * 0.42 * n * sec) * sigmas) / sigmao
# Apply diff for the above expression.
fin = diff(out, n)

result = nsolve(fin, n, 1)
print(result, fin.subs(n, result).evalf())

Result: 1.05992379637846 -7.28565300819065e-17
Note that when working with numeric values, you should be very careful to use as many digits as possible to avoid accumulation of errors.  Whenever you have an exact expression, it is recommended to leave that expression into the code, instead of replacing it with digits. (Usually, 64 bits or about 16 digits are used in calculations, but for intermediate calculations 80 bits can be taken into account).
To solve the original question with sympy:
from sympy import symbols, Eq, exp, solve

x = symbols('x')
solutions = solve(Eq((x + 1) * exp(x), 20))
for s in solutions:
    print(s.evalf())

Result: 1.92309074332181


text:
Q: How to run pytorch neural network as if it was in server I have a model like so that I've already trained
import torch.nn as nn
import torch.nn.functional as F

transform = transforms.Compose([
    transforms.Resize(30),
    transforms.ToTensor()
])

class Net(nn.Module):
    def __init__(self):
        super().__init__()
        self.conv1 = nn.Conv2d(3, 6, 3)
        self.pool = nn.MaxPool2d(2, 2)
        self.conv2 = nn.Conv2d(6, 10, 3)
        self.fc1 = nn.Linear(780, 70)
        self.fc2 = nn.Linear(70, 50)
        self.fc3 = nn.Linear(50, 5)

    def forward(self, x):
        x = self.pool(F.relu(self.conv1(x)))
        x = self.pool(F.relu(self.conv2(x)))
        x = torch.flatten(x, 1) # flatten all dimensions except batch
        x = F.relu(self.fc1(x))
        x = F.relu(self.fc2(x))
        x = self.fc3(x)
        return x

net = Net()
net.load_state_dict(torch.load('classifier.pth'))
net.eval()

test_img = Image.open('test.jpg')

processed_img = transform(test_img)

output = net(processed_img)
predicted = torch.max(output.data, 1)

print(predicted)

When I run this, I get

File "XXX.py", line 26, in forward
    x = F.relu(self.fc1(x))
  File "/Users/XXX/env/lib/python3.8/site-packages/torch/nn/modules/module.py", line 1190, in _call_impl
    return forward_call(*input, **kwargs)
  File "/Users/XXX/env/lib/python3.8/site-packages/torch/nn/modules/linear.py", line 114, in forward
    return F.linear(input, self.weight, self.bias)
RuntimeError: mat1 and mat2 shapes cannot be multiplied (10x36 and 780x70)

I know it means the tensor shapes don't line up, but I didn't see this problem during training or testing with the data from the loaders.
So I guess my main question is how would I get this network working in a flask app api endpoint for example. How should I process the image so that the network works, or what am I doing wrong?

A: Update:
Think I found the issue. I assumed transform.Resize made the image into a square. It doesn't.


text:
Q: Работа с картинками-ссылками вместо текстовых ссылок Добрый вечер!
Исходные данные: каталог товаров, каждый товар которого на странице отображается друг под другом. Есть возможность по ссылке "Раскрыть все" (или "Скрыть все", значение меняется) раскрыть все товары, а также раскрыть/скрыть каждый товар по отдельности ( с помощью текстовых ссылок [+] и [-] соответственно).
Собственно код:

<script type="text/javascript">
    $(document).ready(function() {
    $('.showinfo').click(function() { //при клике на .showinfo скрываем/раскрываем блок с инфой
    $(this).text($(this).text()=='[-]' ? '[+]' : '[-]');
    $(this).parent().find('.productinfo').toggle('slow');
    return false;   });
    $('#show-all').click(function() { //при клике на #show-all раскрываем все блоки, меняем тексты кнопок
    if ($('#show-all').text()=='Раскрыть все')
    {$('.productinfo').show('slow');}
    if ($('#show-all').text()=='Скрыть все')
    {$('.productinfo').hide('slow');}
    $(this).text($(this).text()=='Скрыть все' ? 'Раскрыть все' : 'Скрыть все');
    if ($('#show-all').text()=='Скрыть все') {$('.showinfo').text('[-]');}
    else {$('.showinfo').text('[+]');}
    return false;   });
    }); </script>

Проблема в следующем. Как сделать так чтобы вместо текстовых ссылок ( [+] и [-] ) вставить соответствующие картинки, да так чтобы функционал не изменился (картинки бы по клику менялись и т.д.)
Буду благодарен за любой помощь. Подскажите хоть в какую сторону копать.
A: [-] и [+] в коде видите? Вместо этих значков пишите код ваших картинок.
A: А не проще ли ссылке с классом  ".showinfo" прописать в css: display:inline-block и background:url(/plus.png), и при клике на нее, отслеживая текущее состояние, менять background-position?


text:
Q: spectrum of the Hadamard matrices A (±1)-matrix is a matrix whose entries are 1 and −1.
An $n \times n$ (±1)-matrix is called an Hadamard matrix if the rows are
orthogonal.
Equivalently,
An $n \times n$ (±1)-matrix $H$ is Hadamard ⇔ $H H^t = nI_n$,
where $I_n$ denotes the $n \times n$ identity matrix.
In this paper : http://www.sciencedirect.com/science/article/pii/0024379582902105
A note on the eigenvectors of Hadamard matrices of order $2^n$
R. Yarlagadda
J. Hershey
we have the result that,
If the order of $H$, is $2^n$, then its $2^n$ eigenvalues as follows:
$2^{n - 1}$ eigenvalues are $2^{\frac{n}{2}}$
$2^{n - 1}$ eigenvalues are $- 2^{\frac{n}{2}}$
This result says that $H_n$ has $\frac{n}{2}$ eigen values equal to $n^{\frac{1}{2}}$ and $\frac{n}{2}$ eigenvalues equalt to $- n^{\frac{1}
{2}}$ if $n = 2^n$.
My questions are,
1) Is this result true for any Hadamard matrix of order $n$ (this $n$ is any multiple of 4 for which we know there is a Hadamard matrix of that order) ?
2) What is best known result regarding their eigen values?
Thanks for your valuable timing.

A: In general, if $H$ is an $n\times n$ Hadamard matrix, then $A:=\frac{1}{\sqrt{n}}H$ is an orthogonal matrix, which implies that if
$$
Av=\lambda v,
$$
then
$$
v^*A^*=\lambda^* v^*,
$$
where the superscript "$*$" denotes Hermitian adjoint, and hence that
$$
v^*v=v^*A^*Av=\lvert\lambda\rvert^2v^*v.
$$
From this it follows that the eigenvalues of $A$ have modulus $1$ and therefore that the eigenvalues of $H$ have modulus $\sqrt{n}$.
It is not the case, however, that the eigenvalues of any Hadamard matrix are $\pm\sqrt{n}$ in equal number.  If you take the matrix $H_n$ of the article you reference, constructed by taking repeated Kronecker products of the matrix
$$
H_1=\begin{bmatrix}
1 & 1\\
1 & -1
\end{bmatrix},
$$
and, for example, permute some of the rows of the matrix, the resulting matrix may have complex eigenvalues.
The Hadamard matrix
$$
H=\begin{bmatrix}
1 & -1 & 1 & -1\\
1 & -1 & -1 & 1\\
1 & 1 & -1 & -1\\
1 & 1 & 1 & 1
\end{bmatrix},
$$
for instance, has four distinct eigenvalues of the form $\pm\sqrt{2}\pm\sqrt{2}i$.


text:
Q: How to insert/update an item in a specific column of a dynamic table? I have a dynamic table as of here As you can see, I have a column for "Status" which i hope to get status reply through this done(function()). This is what i've tried http://jsfiddle.net/yvonnezoe/nbrSR/1/
I set the id for that column as id="status_' + rowID because each row will be different. Then, i find each column of each row by setting a variable
eachStatus = $row.find('td:nth-child(5)').attr('id');

After that, i posted that to a python function and it will get a reply of either on or off (for now). In this Fiddle, it won't work because the python function and the real system aren't here. I just want to find out if i'm doing it correct by finding that column and do an .append to show the status? Well, if it is appended to a new div, the on and off can be displayed. But for this one, it never shows up in the table. Why and how should i do it? Will it be updated as well since I'm doing a setInterval, looping every 5 seconds?
    $.post('/request', {
    inputText: fbNum,
    key_pressed: fbType.toString()}).done(function (reply) {
    if (reply == "on") {
        $('#status_table tr #status_' + eachStatus).append("on ");
    } else {
        $('#status_table tr #status_' + eachStatus).append("off ");
    }
    });

FYI, you have to select an option, key in a number, check the checkbox and press "monitor". It will loop every 5 seconds.

A: $('#status_table tr #status_' + eachStatus).append("on ");

should be
$('#status_table tr #' + eachStatus).append("on ");

instead because eachStatus already included status.
you may want to do an .empty() before the .append() so that new status can replace the previous one.


text:
Q: Is there a way to add a single newline at the end of the output?
public class LabProgram {
   public static void main(String[] args) {
      Scanner in=new Scanner(System.in);
       int userNum=in.nextInt();
       int divNum=in.nextInt();
       int i=0;
       while(i<3){
       userNum=userNum/divNum;
       if(userNum==0);
   System.out.print(userNum+""+"\n");
   i++;
   }
   }
}

This results in an output formatted like this,
1000
500
250

Output is nearly correct; but whitespace differs. See highlights below.
Special character legend
Input
2000 2
Your output
1000
500
250
Expected output
1000 500 250

I want it to be like this 1000 500 250 (newline here)
How do I do this?

A: Maybe let's try this one:
System.out.print(userNum + " ");

And at the end use this:
System.out.println();

or
System.out.print("\n");

This will add you a newline :)

A: Use
System.out.println(userNum);


text:
Q: Talend- repeat header I would like to ask if how I can repeat table header for distinct ID record and write it on FileOutputtDelimited
This is my data on tOracleOutput.
  `(header)ID  owner   pet   petname
        1   Juicy   Dog   Chrysler
        1   Juicy   Cat   Ming
        1   Juicy   Frog  jush
        2   Miki    Dog   chuchu
        2   Miki    Fish  goldie  `

My output on tFileOutput should be like this,
       `(header)ID  owner   pet   petname
                1   Juicy   Dog   Chrysler
                            Cat   Ming
                            Frog  jush
        (header) ID  owner   pet   petname
                 2   Miki    Dog   chuchu
                             Fish  goldie`

is there a way to repeat header and remove Owner once already existing?
Thank You.

A: You could do it in a really round about way and I don't really see the use case but it's certainly possible.
You'll want to setup a loop (use a tLoop set to end at the last ID) followed by a filter where you filter by the loop counter. At this point you then unite the data from a tFixedFlowInput component containing the header line and then output this to a tFileOutputDelimited component set to append mode.
This gives you the repeated headers but I'm not 100% sure about how to remove the repeated ID's and owners so will need to think on that a bit.


text:
Q: multiline pattern for nested xml files in filebeat - logstash 7.0.1 I was trying to parse a typical xml log file from my windows machine using filebeat to logstash.
below is my xml example.
<?xml-stylesheet alternate="yes" href="file://c:/drive/bin/event_log.xsl" type="text/xsl"?>
<EventLog SetMinutes="800" Id="8000" Process="Player.exe">
<Clock ClockId="CLk-21e21412414=4-1341341414141"/>
<Entry serial_no="0" mcycle="2132424124-4141" Thread="player" ThreadId="tester" Seconds="11231243241.354123" Severity="info" >Local player details  - Receievd metrics
player has reached 1000 level and need to get an xp
player has reached 100 level and need to get an xp
player has reached to 70 level and need to get an xp
player has reached 1000 level and need to get an xp
player has reached 100 level and need to get an xp
player has reached to 70 level and need to get an xp
player has reached 400 level and need to get an xp
player has reached 100 level and need to get an xp
player has reached to 30 level and need to get an xp
player has reached 103 level and need to get an xp
player has reached 130 level and need to get an xp
player has reached to 70 level and need to get an xp
player has reached 1000 level and need to get an xp
player has reached 100 level and need to get an xp
player has reached to 70 level and need to get an xp
player has reached 3300 level and need to get an xp
player has reached 100 level and need to get an xp
player has reached to 70 level and need to get an xp
player has reached 1300 level and need to get an xp
player has reached 103 level and need to get an xp
player has reached 1000 level and need to get an xp
player has reached 100 level and need to get an xp
player has reached to 70 level and need to get an xp
player has reached 1000 level and need to get an xp
player has reached 100 level and need to get an xp
player has reached to 70 level and need to get an xp
player has reached 400 level and need to get an xp
player has reached 100 level and need to get an xp
player has reached to 30 level and need to get an xp
player has reached 103 level and need to get an xp
player has reached 130 level and need to get an xp
player has reached to 70 level and need to get an xp
player has reached 1000 level and need to get an xp
player has reached 100 level and need to get an xp
player has reached to 70 level and need to get an xp
player has reached 3300 level and need to get an xp
player has reached 100 level and need to get an xp
player has reached to 70 level and need to get an xp
player has reached 1300 level and need to get an xp
player has reached 103 level and need to get an xp
player has reached to 733 level and need to get an xp
</Entry>
</Eventlog>

Below is my filebeat multiline config.
multiline.pattern: '^<Entry|^=[a-z]'
    multiline.negate : false
    multiline.match: after

Below is my losgtash.conf xml filter
input{
 beats {
     port => 5044
}

}
filter{
  xml{
      source => "message"
      store_xml => true
      target => "doc"
      xpath => ["/Eventlog[@name='ThreadId']@value",  "ThreadId",
                        "/Eventlog[@name='Thread']@value",  "Thread",
                        "/Eventlog/Entry[@name='Secs']@value",  "Seconds",
                         "/Eventlog/Entry[@name='ThreadId']@value",  "ThreadID",
                        "/Eventlog/Entry/text()", "details"
                        ]
}

Can anyone help with this? Am i missing anything in the config of filebeat or logstash ?


text:
Q: What is an encoding error for sprintf that should return -1? I understand snprintf will return a negative value when "an encoding error occurs"
But what is a simple example of such an "encoding error" that will produce that result?
I'm working with gcc 10.2.0 C compiler, and I've tried malformed format specifiers, unreasonably large numbers for field length, and even null format strings.

*

*Malformed format specifiers just get printed literally

*Unreasonably large numbers as length specifiers produce fatal errors

*Null format strings also produce fatal errors

This relates to repeatedly doing something like:
length += snprintf(...

to build up a formatted string.
That might be safe if it is certain not to return a negative value.
Advancing the buffer pointer by a negative length could cause it to go out of bounds. But I'm looking for a case where that would actually happen. If there is such a case then the added complexity of this may be warranted:
length += result = snprintf(...

So far I couldn't find a scenario where it would be worth adding complexity for a check of a value that the compiler may never produce. Maybe you can give a simple example of one.

A:
What is an encoding error for sprintf that should return -1?

On my machine, "%ls" did not like the 0xFFFF - certainly an encoding error.
  char buf[42];
  wchar_t s[] = { 0xFFFF,49,50,51,0 };
  int i = snprintf(buf, sizeof buf, "<%ls>", s);
  printf("%d\n", i);

Output
-1

Below code returned -1, but not so much due to encoding error as for pathological format.
#include <stdio.h>

int main() {
  size_t n = 0xFFFFFFFFLLu + 1;
  char *fmt = malloc(n);
  if (fmt == NULL) {
    puts("OOM");
    return -42;
  }
  memset(fmt, 'x', n);
  fmt[n - 1] = '\0';
  char buf[42];
  int i = snprintf(buf, sizeof buf, fmt);
  printf("%d %x\n", i, (unsigned) i);
  free(fmt);
  return 7;
}

Output
-1 ffffffff

I did get a surprising -1 when passing a too big a size, even though the snprintf() only needed 6 bytes.
  char buf[42];
  int i = snprintf(buf, 4299195472, "Hello");
  printf("%d\n", i);

Output
-1

I was able to come up with a short example returning -1 on a *fprintf() to stdout due to orientation conflict.
#include <wchar.h>
#include <stdio.h>

int main() {
  int w = wprintf(L"Hello wide world\n");
  wprintf(L"%d\n", w);
  int s = printf("Hello world\n");
  wprintf(L"%d\n", s);
}

Output
Hello wide world
17
-1

A: Normally you only expect an error from printf and family when an output error occurs.  From the Linux man page:

If an output error is encountered, a negative value is returned.

So if you are outputting to a FILE and an output error of some kind (EPIPE, EIO) occurs, you'll get a negative return value.  For s[n]printf, since there's no output, there would never be a negative return value.
The standard talks about the possibility of an "encoding error", but only defines what that means with respect to wide character streams, with a note that byte streams might need to convert to wide streams in some cases.

An encoding error occurs if the character sequence presented to the underlying
mbrtowc function does not form a valid (generalized) multibyte character, or if the code
value passed to the underlying wcrtomb does not correspond to a valid (generalized) multibyte character. The wide character input/output functions and the byte input/output
functions store the value of the macro EILSEQ in errno if and only if an encoding error
occurs.

That would seem to imply that you can get an encoding error if you use the %ls or %lc formats to convert a wide string or characters to bytes.  Not sure if there are any other cases where it could occur.


text:
Q: Using $\lim_{x \rightarrow 0}\frac{f(x)}{x^2}=1$ to find $\lim_{x \rightarrow 0}f(x)$ and $\lim_{x \rightarrow 0}\frac{f(x)}{x}$ I'm trying to find $\lim_{x \rightarrow 0}f(x)$ and $\lim_{x \rightarrow 0}f(x)$ and $\lim_{x \rightarrow 0}\frac{f(x)}{x}$ using $\lim_{x \rightarrow 0}\frac{f(x)}{x^2}=1$. To find $\lim_{x \rightarrow 0}f(x)$ what I did was $$\lim_{x \rightarrow 0}f(x)=\lim_{x \rightarrow 0}\frac{f(x)}{x^2}\cdot\lim_{x \rightarrow 0}x^2=1\cdot \lim_{x \rightarrow 0}x^2=1\cdot 0=0$$
However I'm not so sure of finding $\lim_{x \rightarrow 0}\frac{f(x)}{x}$. What I tried doing was saying $$\lim_{x \rightarrow 0}\frac{f(x)}{x}=\lim_{x \rightarrow 0}\frac{f(x)}{x^2}\cdot \lim_{x \rightarrow 0}x=1\cdot 0=0$$
My solutions for both limits seems right but I'm just not sure how justified I am by multiplying the limits in both parts, respectively, by $\frac{\lim_{x \rightarrow 0}x^2}{\lim_{x \rightarrow 0}x^2}$ and $\frac{\lim_{x \rightarrow 0}x}{\lim_{x \rightarrow 0}x}$ even though they let me simplify the limits into the limits of functions whose limits I know.

A: It's a fact of limits that if $\lim_{x\to a} g(x)$ exists and $\lim_{x\to a} h(x)$, then $\lim_{x \to a} g(x)h(x)$ exists and is equal to the product $(\lim_{x\to a}g(x))(\lim_{x\to a}(h(x))$. That is the fact you are using for both problems. In the first case, you have $g(x)=\frac{f(x)}{x^2}$ and $h(x)=x^2$; in the second problem you have $g(x)=\frac{f(x)}{x^2}$ and $h(x)=x$.


text:
Q: how to find out when a user last visited? I'm trying to figure out when a user has last visited.So let's say I logged out of my SharePoint intranet last night at 11PM, and this morning I logged back in at 9AM, I'd like to see a message saying "you last logged in yesterday at 11PM" (and as far as I care, a console message would do just fine for now).
So. How can I see when the current user last logged in?
Preferably a solution in JavaScript, since I can't use C# for this (not allowed to do server-side coding). Also, I'm not sure if cookies are a great solution, what is your opinion on using cookies?
Thanks in advance for any help or suggestions, I really do appreciate your response.
EDIT
My plan is to eventually use this to see if there are any new items that were added to our SharePoint intranet after the user has last visited, and then show those items to the user the next time he/she logs in. I know how to do the latter, I'm just stuck at finding out when a user last visited. :/

A: needs to be done through active directory:
powershell
http://admin-sharepoint.blogspot.co.uk/2013/08/get-users-last-logon-time-and-date.html
in your case it would be through c# to get to active directory and query lastLogon:
    public DateTime Get(string attr, string UserName)
    {

        DomainConfiguration domainConfig = new DomainConfiguration();
        using (new SPMonitoredScope("AD Properties"))
        {
            using (DirectoryEntry domain = new DirectoryEntry("LDAP://" + domainConfig.DomainName, domainConfig.UserName, domainConfig.Password))
            {
                //DirectorySearcher searcher = new DirectorySearcher(domain, "(|(objectClass=organizationalUnit)(objectClass=container)(objectClass=builtinDomain)(objectClass=domainDNS))");
                DirectorySearcher searcher = new DirectorySearcher(domain);
                searcher.PageSize = 1000;
                searcher.Filter = "(SAMAccountName='" + UserName + "')";
                //searcher.Filter = "(|(objectCategory=group)(objectCategory=person))";
                searcher.Filter = "(&(objectClass=user) (cn=" + UserName + "))";
                var user = searcher.FindOne();
                DateTime LastLogon = DateTime.FromFileTime((Int64)user.Properties["lastLogon"].Value);
                return LastLogon;
            }
        }
    }

https://stackoverflow.com/questions/13796547/how-to-get-last-login-details-time-for-all-users
EDIT
i could be wrong but i dont think its possible todo that client side using the javascript client object model!
you would need to create a list, store the username, last login time and retrieve them that way! could be done through JS but be a pain! as you need to update whenever someone logs off, and get the info when they login!


text:
Q: get value of a property from one viewmodel's current instance in another I have a setup something like below:
MainWindow ------> MainWindowViewModel
  |--Menu
  |--Frame

Page1 --------> Page1ViewModel
Page2 --------> Page2ViewModel

Suppose my menu has 2 items in it namely Item1 and Item2.
Menu's SelectedMenuItem is bound to a property called SelectedItem in MainWindowViewModel.
When I click on Item1 I am navigated to Page1 and similarly when I click on Item2 I am navigated to Page2.
Now, In Page1ViewModel and in Page2ViewModel I want to have the current value of SelectedItem. How can I get that value ?
Before asking this question I have looked at Mediator Pattern as well as EventAggregator but for a newbie(in WPF) like me it is very hard to understand those patterns. Is there any other solutions that I can adopt?
Also I have looked at the accepted answer of this question. I have tried the code given there but I don't get value in Page1ViewModel or Page2ViewModel.
Update ---> @Poke
Sorry, I didn't mentioned that in question.
I have another item in my menu called Item3. When I Click on it Page1 should be visible.
So, now my setup is:
MenuItem   |      Page     |    ViewModel
-----------+---------------+-------------
Item1      |     Page1     |  Page1ViewModel
Item2      |     Page2     |  Page2ViewModel
Item3      |     Page1     |  Page1ViewModel

The only difference between Item1 Click and Item3 Click is that :

*

*When Clicking on Item1 :
A Combobox called cbEffects should be visible.

*When Clicking on Item1 :
A Combobox called cbEffects should be hidden.

A: Here's one example of maintaining ViewModel instances in a static property available anywhere in your application via SessionViewModel.GetModuleInstance('VMName'):
namespace MyProject.ViewModels
{
    public sealed class SessionViewModel : ViewModelBase
    {
        private static readonly SessionViewModel instance = new SessionViewModel();
        public static SessionViewModel Instance
        {
            get { return instance; }
        }

        private List<IModule> modulesOpen;
        public List<IModule> ModulesOpen
        {
            get { return modulesOpen; }
            set
            {
                modulesOpen = value;
                NotifyPropertyChanged(() => ModulesOpen);
            }
        }
    }

    public static IModule GetModuleInstance(string moduleName)
    {
        string finalName = "MyProject.ViewModels." + moduleName + "ViewModel";
        IModule moduleToOpen = null;
        if (Instance.ModulesOpen != null)
        {
            moduleToOpen = Instance.ModulesOpen.SingleOrDefault(mod => mod.ModuleName == moduleName);
        }
        else
        {
            Instance.ModulesOpen = new List<IModule>();
        }
        if (moduleToOpen != null) return moduleToOpen;
        Type module = Type.GetType(finalName);
        moduleToOpen = (IModule) Activator.CreateInstance(module);
        Instance.ModulesOpen.Add(moduleToOpen);
        return moduleToOpen;
    }

    public class UsageExample()
    {
        var vm = SessionViewModel.GetModuleInstance("MyVMName");
        ((MyVMName)vm).MyVMPropertyName;
    }
}

A: Not sure if this is what you are looking for, but you can access the application viewmodel through the App.Current.MainWindow.DataContext property, and store common properties in there.. or, what I do, is store variables accessible to all views in a static class..


text:
Q: Local SQLite Database in Xamarin Forms So I did an example Database outside Xamarin Forms using "DB Browser for SQLite" and put it in Assets File

and I'm trying to learn how to connect my Database to it so i did this :
XAML :

<?xml version="1.0" encoding="utf-8" ?>
<ContentPage xmlns="http://xamarin.com/schemas/2014/forms"
             xmlns:x="http://schemas.microsoft.com/winfx/2009/xaml"
             xmlns:d="http://xamarin.com/schemas/2014/forms/design"
             xmlns:mc="http://schemas.openxmlformats.org/markup-compatibility/2006"
             mc:Ignorable="d"
             x:Class="Behoerdensprache.Pages.FinanzAmt">
    <ContentPage.Content>
        <StackLayout>
            <Label Text="Welcome to Xamarin.Forms!"
                VerticalOptions="CenterAndExpand"
                HorizontalOptions="CenterAndExpand"
                   x:Name="LabelControl"/>
            <Entry Placeholder="Search" x:Name="SearchEntry"/>
            <Button Text="Press me" Clicked="Button_Clicked"/>
        </StackLayout>
    </ContentPage.Content>
</ContentPage>

C# ButtonCode :
    private void Button_Clicked(object sender, EventArgs e)
    {
        SQLiteConnection conn = new SQLiteConnection(App.DataBaseLocation);
        conn.CreateTable<Wortschatz>();
        var gets = conn.Table<Wortschatz>().Where(i => i.Wort == SearchEntry.Text).ToString();
        LabelControl.Text = gets;

        conn.Close();

    }

App.DataBaseLocation is defined in the Mainactivity and AppDelegate :
in Mainactivity :
        string dbName = "BeamtenSprache.sqlite";
        string folderPath = System.Environment.GetFolderPath(System.Environment.SpecialFolder.Personal);
        string fullPath = Path.Combine(folderPath, dbName);
        LoadApplication(new App(fullPath));

in AppDelegate :
        string dbName = "wortschatz.sqlite";
        string folderPath = Path.Combine(System.Environment.GetFolderPath(System.Environment.SpecialFolder.Personal), "..", "Library");
        string fullPath = Path.Combine(folderPath, dbName);
        LoadApplication(new App(fullPath));

new App(fullPath) this part i defined in App.cs :
 public static string DataBaseLocation = string.Empty;
    public App()
    {
        InitializeComponent();
        MainPage = new NavigationPage(new MainPage());
    }

    public App(string databaseLocation)
    {
        InitializeComponent();
        MainPage = new NavigationPage(new MainPage());
        DataBaseLocation = databaseLocation;
    }

but when i run the app and i press the Button this shows :

A: There is an Todo sample project in xamarin.forms.samples shows how to store and access data in a local SQLite database.
In Android project, he put the db file in Todo/Todo.Android/Resources/raw/
In iOS project, he put the db file in Todo/Todo.iOS/Resources/
And then he get the db path by:
public static class Constants
{
    public const string DatabaseFilename = "TodoSQLite.db3";

    public static string DatabasePath
    {
        get
        {
            var basePath = Environment.GetFolderPath(Environment.SpecialFolder.LocalApplicationData);
            return Path.Combine(basePath, DatabaseFilename);
        }
    }
}

You can download it and try with the code there in your project. For more information, you can read the document.
If you can't solve the problem, you can share your project here and I will check it:).


text:
Q: can't access parent ctrl in $compile directive I'm working on a recursive nested navigation menu in AngularJS. I have a  directive and it can have any number of  elements. It looks a bit like this:
<root-nav>
    <sub-nav-tree navData="menuItem">
</root-nav>

The root-nav directive holds a RootNav controller, I can't access this controller from the child directive in the DOM. The parent controller holds a bunch of methods which can be used in the child directive, but I can't access it. And I don't want redundant code (copy/paste methods to child controller).
What i wan't is this to work
The sub-nav-tree directive compiles a template, so I'm pretty sure its the $compile part thats the bad guy.
this is the part of the linking function in the child directive:
    if (scope.menuItem && scope.menuItem.children && scope.menuItem.children.length > 0) {

        $http.get('/markup/components/root-navigation/sub-navigation.html').then(function (response) {
            el.replaceWith($compile(response.data)(scope));
        });

    }

Hope you guys can help me out with this problem :) Thanks.
@Chandermani here's the child directives return function:
return {
    restrict: 'E',
    require: '^^rootNav',
    scope: {
        menuItem: '=navData'
    },
    link: function (scope, el, attrs, rootNavCtrl) {

        if (scope.menuItem && scope.menuItem.children && scope.menuItem.children.length > 0) {

            $http.get('/markup/components/root-navigation/sub-navigation.html').then(function (response) {
                el.replaceWith($compile(response.data)(scope);
            });

        }

    },
}


text:
Q: Mongoose Data Types how to define multiple type values ? ESLint error I would like to define a filed 'lines' as an Array of values which can be of different types ( numbers or strings or boolean or dates )
when I try :
lines: [
{
  type: String,
  content: Mixed
}

]
I get an ESLint error error : Mixed is not defined
Should I write ?
 const Schema = mongoose.Schema;
 ...
 lines: [
   Schema.Types.Mixed
 ]

A: According to mongoose documentation you can use Mixed schema type as follows
var schema = new Schema({
ofMixed:    [Schema.Types.Mixed],
})

// example use

var Thing = mongoose.model('Thing', schema);

m.ofMixed = [1, [], 'three', { four: 5 }];
m.save(callback);


text:
Q: The service does not run if the app is killed So I have a service that checks if the Screen is ON or OFF (from here).
This is the main activity:
public class MainActivity extends Activity {

    public void onCreate(Bundle savedInstanceState) {
        super.onCreate(savedInstanceState);
        onCreate();
    }
    public void onCreate() {

        IntentFilter filter = new IntentFilter(Intent.ACTION_SCREEN_ON);
        filter.addAction(Intent.ACTION_SCREEN_OFF);
        BroadcastReceiver mReceiver = new ScreenReceiver();
        registerReceiver(mReceiver, filter);
    }

    @Override
    protected void onPause() {
        if (ScreenReceiver.screenOff) {

            System.out.println("SCREEN TURNED OFF");
        } else {

            System.out.println("this is when onPause() is called when the screen state has not changed ");

        }
        super.onPause();
    }
    @Override
    protected void onResume() {
        // only when screen turns on
        if (!ScreenReceiver.screenOff) {
            System.out.println("SCREEN TURNED ON");
        } else {

            System.out.println(" this is when onResume() is called when the screen state has not changed ");
        }
        super.onResume();
    }
}

The Service class:
public class UpdateService extends Service {

    public void onCreate() {
        super.onCreate();
        // register receiver that handles screen on and screen off logic

        IntentFilter filter = new IntentFilter(Intent.ACTION_SCREEN_ON);
        filter.addAction(Intent.ACTION_SCREEN_OFF);
        BroadcastReceiver mReceiver = new ScreenReceiver();
        registerReceiver(mReceiver, filter);
    }

    @Override
    public void onStart(Intent intent, int startId) {
        boolean screenOn = intent.getBooleanExtra("screen_state", false);
        if (!screenOn) {
            System.out.println("Screen is off");
        } else {
            System.out.println("Screen is on");
        }
    }

    @Override
    public IBinder onBind(Intent intent) {
        return null;
    }
}

Receiver:
public class ScreenReceiver extends BroadcastReceiver {

    public static boolean screenOff;

    @Override
    public void onReceive(Context context, Intent intent) {

        System.out.println("onReceive ");
        if (intent.getAction().equals(Intent.ACTION_SCREEN_OFF)) {
            screenOff = true;
            System.out.println("SCREEN TURNED OFF on BroadcastReceiver");
            Log.d("Check", "SCREEN TURNED OFF" );
        } else if (intent.getAction().equals(Intent.ACTION_SCREEN_ON)) {
            screenOff = false;
            System.out.println("SCREEN TURNED ON on BroadcastReceiver");
            Log.d("Check", "SCREEN TURNED ON" );

        }
        Intent i = new Intent(context, UpdateService.class);
        i.putExtra("screen_state", screenOff);
        context.startService(i);
    }
}

The above service runs perfectly when the app is sent to the background. But when the app is killed using the task manager, the service does not work anymore. I need the service to work even when the app is killed.
What should I do to enable that? Any ideas?

A: The reason is that your service is running on the same process as the application. If you set android:process=":yourServiceName" in the manifest file, your service will start a new process and you can see your service.
Also, do check if your service is actually running using this method
private boolean isMyServiceRunning(Class<?> serviceClass) {
    ActivityManager manager = (ActivityManager) getSystemService(Context.ACTIVITY_SERVICE);
    for (ActivityManager.RunningServiceInfo service : manager.getRunningServices(Integer.MAX_VALUE)) {
        if (serviceClass.getName().equals(service.service.getClassName())) {
            return true;
        }
    }
    return false;
}

To restart the service you can use an AlarmManager inside your onTaskRemoved method of the service.
@Override
    public void onTaskRemoved(Intent rootIntent) {

        Intent restartService = new Intent(getApplicationContext(), this.getClass());
        PendingIntent pendingIntent = PendingIntent.getService(getApplicationContext(), 1, restartService, PendingIntent.FLAG_ONE_SHOT);
        AlarmManager alarmManager = (AlarmManager) getSystemService(Context.ALARM_SERVICE);
        alarmManager.set(AlarmManager.ELAPSED_REALTIME, 5000, pendingIntent);

    }

A: If they run in the same process, it is obviously that the service is terminated together with your desktop application.
Run your service as a Windows Service / Linux daemon, they have a different lifecycle compared to the processes created by the user. For example, your application will be terminated automatically on logout.


text:
Q: If $B$ is a generalised subformula of $\textbf{Q}xA$ then there exists a free term $t$ such that $B$ is a generalised subformula of $[A]_t^x$ Consider formulas $A$ of predicate calculus such that no variables can be bound and free for $A$ at the same time. Term $t$ is said to be free for $x$ in $A$ if $x\notin FV(A)$ or no variables of $t$ appears in $A$ as bound ones. Lets generalise the notion of a subformula: we say that $[A]_t^x$ is a generalised subformula of $\textbf{Q}xA,\:\textbf{Q}\in\{\forall,\exists\},$ if the term $t$ is free for $x$ in A.
Prove that if $B$ is a proper generalised subformula of $\textbf{Q}xA$ where $\textbf{Q}$ is a quantifier then there exists a term $t$ free for $x$ in $A$ such that $B$ is a generalised subformula of $[A]_t^x$.
Intuitively this statement is evident but I am not pretty sure about a formal proof. I've tried to use induction (the base is trivial) but I don't know how exactly must the step look like.
Maybe I overcomplicate and all needed to be said is: if required $t$ does not exist then $B$ is not a generalised subformula for any of $[A]_t^x$ and, hence, it must be the whole $\textbf{Q}xA$ but $B$ is proper. Contradiction.
I am not sure. What can you say?


text:
Q: Is there a simple way to "unpack" a list in Neo4j? I have a string attribute in my Neo4j database that is actually a list cast as string (e.g. "[1,1,3,10]"). I realize I can alter the load program to make those separate fields (e.g. elem1 = 1, elem2 = 1, elem3 = 3, elem4 = 10) but I want to be able to recast the ones already loaded.
I could write a python but hoping that someone has a "in cypher" way to do this.

A: Easiest to use the apoc library for that.
Depending on what you would like as an outcome:
A collection
WITH "[1,1,3,10]" AS string
UNWIND apoc.convert.fromJsonList(string) AS elements
RETURN elements

or a map
WITH "[1,1,3,10]" AS string
WITH apoc.convert.fromJsonList(string) AS collection
RETURN apoc.map.fromPairs(
         REDUCE(arr=[],i IN collection |
                arr
                +[['elem'+toString(size(arr)),i]]
         )
     ) AS map


text:
Q: Checking if job exists in Quartz.NET randomly fails When trying to check if a job exists in Quartz.NET, it randomly fails with the following error:
Couldn't commit ADO.NET transaction. Transaction not connected, or was disconnected

Here is the stack trace:
   at Quartz.Impl.AdoJobStore.JobStoreSupport.CommitConnection(ConnectionAndTransactionHolder cth, Boolean openNewTransaction) in c:\projects\quartznet\src\Quartz\Impl\AdoJobStore\JobStoreSupport.cs:line 3403
   at Quartz.Impl.AdoJobStore.JobStoreSupport.ExecuteInNonManagedTXLock[T](String lockName, Func`2 txCallback, Func`3 txValidator) in c:\projects\quartznet\src\Quartz\Impl\AdoJobStore\JobStoreSupport.cs:line 3562
   at Quartz.Impl.AdoJobStore.JobStoreTX.ExecuteInLock[T](String lockName, Func`2 txCallback) in c:\projects\quartznet\src\Quartz\Impl\AdoJobStore\JobStoreTX.cs:line 76
   at Quartz.Impl.AdoJobStore.JobStoreSupport.ExecuteWithoutLock[T](Func`2 txCallback) in c:\projects\quartznet\src\Quartz\Impl\AdoJobStore\JobStoreSupport.cs:line 3418
   at Quartz.Impl.AdoJobStore.JobStoreSupport.CheckExists(JobKey jobKey) in c:\projects\quartznet\src\Quartz\Impl\AdoJobStore\JobStoreSupport.cs:line 1739
   at Quartz.Core.QuartzScheduler.CheckExists(JobKey jobKey) in c:\projects\quartznet\src\Quartz\Core\QuartzScheduler.cs:line 1399
   at Quartz.Impl.StdScheduler.CheckExists(JobKey jobKey) in c:\projects\quartznet\src\Quartz\Impl\StdScheduler.cs:line 354

And my configuration:
        ["quartz.jobStore.type"] = "Quartz.Impl.AdoJobStore.JobStoreTX, Quartz",
        ["quartz.jobStore.driverDelegateType"] = "Quartz.Impl.AdoJobStore.SqlServerDelegate, Quartz",
        ["quartz.jobStore.tablePrefix"] = "QRTZ_",
        ["quartz.jobStore.dataSource"] = "rubis",
        ["quartz.dataSource.rubis.connectionStringName"] = "RubisEntities",
        ["quartz.dataSource.rubis.provider"] = "SqlServer-20",
        ["quartz.jobStore.useProperties"] = "true",
        ["quartz.threadPool.threadCount"] = "20"

I don't know what I'm missing, and I can't find a situation where it always occurs. It keeps failing randomly.


text:
Q: WordPress - MailChimp.php calls itself? How to stop? within my functions.php I include this MailChimp API wrapper to use it later on if somebody clicks a checkbox and submits a comment.
https://github.com/lornajane/mailchimp-api/blob/master/MailChimp.class.php
My server logs show that the Mailchimp.php calls himself everytime a user visits the page.
The IP is my server's ip:
176.28.32.232 - - [06/Aug/2015:00:00:31 +0200] "GET /wp-content/themes/gettheme/inc/MailChimp.php HTTP/1.0" 200 0 "-" "-" "myhost.com"

How can I stop this? Do I need to include the file only if someone presses the button or is this an issue in the mail chimp api wrapper file?
My functions.php looks like this:
<?php
include_once( get_stylesheet_directory_uri() . '/inc/MailChimp.php' );

add_action('comment_post', 'custom_add_meta_settings');
function custom_add_meta_settings( $comment_id, $comment_approved ) {

        //some code goes here

            if ( $subscribe == 'on' ) {
                //use Mailchimp API
                $MailChimp = new MailChimp('//mylistid');

I could now move the include_once statement direct after the function opens, but will this fix my issue?
Thanks.


text:
Q: Zipping many files with JSZip is crashing I am having a problem using JSZip to zip files and any help is greatly appreciated.
Basically, I am working on an application where users can upload a directory containing multiple files. An individual file will never be more than 2GB and most are much smaller (~10MB), but there can be thousands of files in a directory so the total size could be 20GB+.What I want to do is use JSZip to zip the files into a single zip file and then upload that single zip file to AWS S3. The problem is, my browser is crashing when I start testing with a larger number of files. When I tried with a directory containing 1000 files for a total size of ~8GB, my browser crashes and I see a Error code: SBOX_FATAL_MEMORY_EXCEEDED error. This error happens before I make it to the uploading step.
I am letting users upload files with a HTML input and saving the file in memory before the zipping and uploading happens. Here is the code I'm using to zip the files:
        const zip = new JSZip();

        files.forEach((file) => {
            zip.file(file.name, file)
        });

        zip.generateAsync({ type: "blob" })
            .then((content) => uploadToS3(content))

It seems like storing the files and the zip in memory is too much for my machine to handle and I'm sure some of my users will have smaller machines than I do. Any ideas on how I can implement this would be very helpful.
Thanks!


text:
Q: Run SQLite statement in Database Inspector Button not showing in Android studio If app uses Room, Android Studio provides gutter actions that allow to quickly run query methods that have already defined in DAO classes as the Android studio documentation . So my expection was to get the gutter action like the below image.
Expectation

But I'm not getting the gutter action called  Run SQLite statement in Database Inspector in my case. My DAO's image is attached below -
Reality

A: I was actually storing my table and column name in Java's public static final String field as  constant and using it room query. So I just simple removed the constant and add the original/direct name of table and column name then it was showing the button finally.


text:
Q: ASP.NET - Change from Web Application Project to Web Site Project I am new to Visual Studio and ASP.NET. I have a MyClass.cs file under App_Code directory, but could not able to run the function in the class file. Keep getting this error:
The name 'MyClass' does not exist in the current context

I know that code works fine since I posted the codes and others confirmed it works, but I am still receiving the error above.
I read alot more threads on the NET and somes indicated that problem is using Web Application Project instead of Web Site project, which the class file would not compile.  I am not sure if I've created it under Application Project we Web Site project.
How can I tell that my site is running under Web Application Project or Web Site Project?  and How can I change it to Web Site Project so my class can be recognized.
Thanks in advance,


text:
Q: A word or term for a physical type of a prize? Is there any phrase with the word "prize" that would describe that the prize is a material one? I.e. you would get some kind of a product or thing, not money.

A: I've never heard a specific word used, but generally I see people reference whatever the top tier prize(s).
Example:

Win a car, an Xbox 360, or a bunch of other prizes!

A: How about "non-monetary" if that is the attribute of the prize that you are most wishing to stress?

I was hoping there would be a cash jackpot but all the prizes were non-monetary.

A: It may sound a bit highbrow, but I think tangible goods fits the bill.

a : capable of being perceived especially by the sense of touch : palpable

A: You could consider swag

products given away free, typically for promotional purposes:
  check out the fun bag of swag we gave our guests!

Since the source of non-cash prizes are often donating them to advance their products, you might also call them promotional prizes.

Be careful, swag is understood by some to be an acronym for "Stuff We All Get" - see the first three acronym definitions implying that the physical things have low physical worth. if this were confused in a prize/contest context then it could send the wrong message, or reduce participation.
Also, "swag" is used in sports and music venues to indicate the things you can buy with the name of the team or band on it. The latter are not free nor a prize.

A: We can call them "non-cash prizes".

A:
Trophy

This is clearly a physical thing.  Trophies need not be non-functional.

Souvenir

Not specifically and award, but definitely physical


text:
Q: Songs imported from ipod Library not working for iOS 5.1 but Works fine for 5.0 and later OS i have implemented code like here
but it's not working for iOS 5.0, it will not storing file to document directory like other later OS.

A: Finally i got answer from here
really it's nice solution given by Albert.


text:
Q: c# - Stop all the threads started from a Form I have a form variable number of instances of which are created and shown in the runtime based on the user action. Each form instance starts a thread on its construction. The thread needs to run as long as the Form exst.
Now, I want the instances to stop the thread it started on its FormClosing event. How do I do that?
UPDATE:
The thread updates the text of the Textbox in the form in a certain interval. The interval is provided by the Thread.Sleep() method in the subroutine which is run by the thread.


text:
Q: Op-Amp suggstions for pulse trains? I want to amplify a weak pulse train lets say from 0-0.2V to 0-5V pulses.
The reason I'm asking this question; when amplifying I also want to sharpen the rising falling edges of the pulses. Original pulses to be amplified should be sharpened in case of bad shape.

A: Use a comparator and if you want really fast edges try the MAX999. It's output voltage will not quite be 5V peak-to-peak but more like 4V peak-to-peak but it's quite suitable for driving a logic input.
The MAX999 has 2.3ns rise and fall times.
Should you require a precise 5Vp-p output I'd still recommend a comparator.
It should be noted that amplifying a signal by (say) 10 does not "sharpen the rising falling edges of the pulses" by 10. If the rise time of the original pulse was 1ms then after amplification the rise time will still be 1ms. If you want to sharpen edges then use a comparator - if you want to preserve amplitude information don't use a comparator - you can't have both.

A: How fast is your input signal?  What is the range of voltage that you expect to see from the signal source?
The reason I ask is that you may be better off with a comparitor configured as a Schmitt trigger rather than an amplifier.
A straight comparitor NOT configured as a Schmitt Trigger might work well for you but the advantage of the Schmitt trigger configuration is that you avoid any ambiguity near the comparitor threshold.


text:
Q: Add caption to img title tag in wordpress I'm trying to add the caption to the image title tag in wordpress so the lightbox I'm using with display the caption, since all it shows is the title tag. I've added $caption as well as many other variations borrowed form the caption shortcode. Any suggestions?
function get_image_tag($id, $alt, $title, $align, $caption, $size='medium') {

    list( $img_src, $width, $height ) = image_downsize($id, $size);
    $hwstring = image_hwstring($width);

    $class = 'align' . esc_attr($align) .' size-' . esc_attr($size) . ' wp-image-' . $id;
    $class = apply_filters('get_image_tag_class', $class, $id, $align, $size);

    $html = '<img src="' . esc_attr($img_src) . '" alt="' . esc_attr($alt) . '" title=" ' . esc_attr($title).' | '. esc_attr($content).'" '.$hwstring.'class="'.$class.'" />';

    $html = apply_filters( 'get_image_tag', $html, $id, $alt, $title, $align, $caption, $size );

    return $html;
}

A: To add caption to the images being displayed in lightbox.Follow the below steps:

- Go to admin dashboard and click the library,it will list out all uploaded
  pictures used for lightbox.Then click on the image for which you want to give caption
  Then,that image properties will appear in that caption field is there.
                                [OR]

- You can include caption while adding image itself.For that click the media tab -> add
  new.Upload New Media will open,in that click select files and load the image from your
  local machine.After the image is uploaded.Below that image you will see the caption
  property.


text:
Q: Iterate through Avl tree in java By the function height(Node) I have the height of each node in my tree.for my each Node in tree, i want to determine subtraction of height of left Node from Right Node.
I just should iterate through the tree. but I have StackOverflow error in my code.
give me some help. I think there is something wrong in other part of my program.
    public class AvlTree {
private Node root = new Node (0,0,"","");
void devision( Node tmp){
tmp=root;
if(tmp.getLeftChild()!=null){
        tmp.devisionNumber=height(tmp.getLeftChild())-height(tmp.getRightChild());
        devision(tmp.getLeftChild());
}
 if(tmp.getRightChild()!=null){
     tmp.devisionNumber=height(tmp.getLeftChild())-height(tmp.getRightChild());
     devision(tmp.getRightChild());
 }
}

int height(Node node){
    if(node==null)
        return -1;
    int left=height(node.getLeftChild());
    int right=height(node.getRightChild());

    if(left>right)
    {
        return left+1;
    }
    else
        return right +1;
}

void insert (Node newNode ){
    Node tmp=root;
        if(root.getStdNum()==0){
            root=newNode;
            root.setLeftChild(null);
            root.setRightChild(null);
            root.setRoot(null);
        }
        else{
            while(true) {
                if(newNode.getStdNum()<tmp.getStdNum()){
                    if(tmp.getLeftChild()==null)
                        break;
                    else
                    tmp=tmp.getLeftChild();
                }

            if(newNode.getStdNum()>tmp.getStdNum()){
                if(tmp.getRightChild()==null)
                    break;
                else
                tmp=tmp.getRightChild();
            }
        }
        ////////////////////////
        if(newNode.getStdNum()<tmp.getStdNum())
        {
            tmp.setLeftChild(newNode);
            newNode.setRoot(tmp);
        }
        if(newNode.getStdNum()>tmp.getStdNum())
        {
            tmp.setRightChild(newNode);
            newNode.setRoot(tmp);

        }
    }
}
}

public  class Node {
private int StdNum;
private int Avarage;
private String Name;
private String FamillyName;
private Node Root;
public int devisionNumber;
private Node LeftChild;
private Node RightChild;

public Node(int stdNum,int Avarage,String Name,String FamillyName){
    this.StdNum=stdNum;
    this.Avarage=Avarage;
    this.Name=Name;
    this.FamillyName=FamillyName;
}
public boolean CheckForNull (Object a){
    boolean check;
    if(a==null){
        check=true;
    }
    else
        check=false;
    return check;
}

public void ShowData(){
    System.out.println("ID: "+ getStdNum());
    System.out.println("Avg: " + getAvarage());
    System.out.println("Name: "+ getName());
    System.out.println("Familly: "+ getFamillyName()+"\n");
    if(CheckForNull(this.getLeftChild())==false)
    System.out.println("leftNode ID: "+ getLeftChild().getStdNum() );
    else System.out.println("LeftChild : Null ");
    if(CheckForNull(this.getRightChild())==false)
    System.out.println("RightNode ID: "+ getRightChild().getStdNum());
    else System.out.println("RightChild : Null ");
    if(CheckForNull(this.getRoot())==false)
    System.out.println("Root ID: "+ getRoot().getStdNum());
    else System.out.println("Root : Null ");

}
public int getStdNum() {
    return StdNum;
}
public void setStdNum(int stdNum) {
    StdNum = stdNum;
}
public int getAvarage() {
    return Avarage;
}
public void setAvarage(int avarage) {
    Avarage = avarage;
}
public String getName() {
    return Name;
}
public void setName(String name) {
    Name = name;
}
public String getFamillyName() {
    return FamillyName;
}
public void setFamillyName(String famillyName) {
    FamillyName = famillyName;
}
public Node getRoot() {
    return Root;
}
public void setRoot(Node root) {
    Root = root;
}
public Node getLeftChild() {
    return LeftChild;
}
public void setLeftChild(Node leftChild) {
    LeftChild = leftChild;
}
public Node getRightChild() {
    return RightChild;
}
public void setRightChild(Node rightChild) {
    RightChild = rightChild;
}

}

A: you always set the node to root (line 2 of the method), so your recursion does not go down the subtrees, but restarts every time ... so the recursion never ends - resulting in a stack overflow.


text:
Q: What does the combination of setf(ios::left, ios::adjustfield) do? I was reading a textbook and I came across this line.
It seems to format output prettily in two columns (I'm guessing the left one get set width making the right one look even since it all starts at the same column).  I'm not too sure about what the line is really doing though.
cout.setf(ios::left, ios::adjustfield);

Can someone explain this to me?

A: It forces text in a fixed width field to be output with left justification.  See this reference.  This is using the second override of that function that takes in the mask in which to set the particular flags.
This override will clear any existing flags that are set in std::ios_base::adjustfield, which handles justification of text output through a stream object.
The override that doesn't take the flag mask (second parameter) will simply additionally set the flag specified, which doesn't make a lot of sense in the case of adjustfield since the valid values are only left, right, and internal, which all deal with text justification.
Hopefully this small example will make it clear:
#include <iostream>
#include <iomanip>
using namespace std;

int main()
{
   cout.setf(std::ios::left, std::ios::adjustfield);
   cout << setfill('^') << setw(10) << "Hello" << "\n";

   cout.setf(std::ios::right, std::ios::adjustfield);
   cout << setfill('0') << setw(10) << "99\n";

   return 0;
}

It gives the output:
Hello^^^^^
000000099


text:
Q: Plot of copula (based on data set) - R I have to do an empirical analysis for a statistics paper. For this I want to show the differences of dependence structure for a specific data set.
So I selected 2 stock prices, transformed them into the returns and started to measure the dependency with R. So far it is no problem, I have a result for Bravais-Pearson, Kendall and Spearman. Additionally I plotted the regression model for this two values.
I have read in many papers, according to Sklar's Theorem, that it is easy to get the copula function out of the distribution function, just by use the inverse.
So my question is, if there is a possibility with R to plot the copula function (and density) just by having this data set (2 returns) or if I must first estimate the parameters to be able to plot this function.
And how can I do this with R? I tried to search the answer in the handbook of the package "copula", but my search wasn't really helpful.
Thanks in advance for your help!

A: Sklar's Theorem is very powerful and reads quite easy, but in practice one will have to know the (analytical) distributions before any "inverse" can be applied. Without knowing the exact joint and marginal distributions, one can still plot the empirical copula of a data set. At times, these plots reveal e.g. asymmetric patterns that can not be captured with correlation coefficients.
Typically, the scaled ranks of a data set (scaled to the interval (0,1)) are a good estimate of a non-parametric inverse of the marginal distributions. An empirical copula's density can then be represented as a scatter plot of the data's scaled ranks. As the spread of (many) points is at times hard to grasp, a smoothed scatter plot provides a visual proxy of the empirical copula's density (see e.g. the function "smoothScatter" from the (base) graphics package or "dependencePlot" in the package spcopula available from r-forge). In case one does know the marginal distributions, one can of'course replace the scaled ranks by the marginally "inverted" data.
In case one does know the copula's family and corresponding parameter(s) (sometimes a 1-1 relationship with Kendall's tau), 3D-plots of the copula can be obtained using the function "persp" with a copula and PDF/CDF function:
library(copula)
persp(claytonCopula(2), dCopula) # plotting the PDF
persp(claytonCopula(2), pCopula) # plotting the CDF

The package copula provides as well the function "fitCopula" that helps to estimate a copula's parameter(s) using different estimators.


text:
Q: How to make buttons the same size and center all of them on the page? I'm using Bootstrap 3 and have 3 buttons of different sizes. I am trying to make them all the same size (based on the size of the largest one) and then center all of them in the middle of the page with space in between them. The buttons either end up not being the same size or not having any space in between them. I want the buttons to be dynamic so I don't want to make them conform to a certain px width.
Failed Attempt 1:

    <button type="button" class="btn btn-default">Left</button>
    <button type="button" class="btn btn-default">Middle Button</button>
    <button type="button" class="btn btn-default">Right</button>

.blocks,
.btn {
  padding: 24px 12px;
  margin: 5px 10px 5px 10px;
  border-radius: 0;
}

.container {
  background-color: pink;
  display: flex;
  justify-content: space-between;
  flex-flow: row wrap;
}

Failed Attempt 2:

        <button type="button" class="btn btn-default">Left</button>

        <button type="button" class="btn btn-default middle-btn">Middle Button</button>

        <button type="button" class="btn btn-default">Right</button>

.btn {
  padding: 24px 12px !important;
  margin: 5px 10px 5px 10px;
  border-radius: 0;
}

A: Try this code:
.blocks,
.btn {
  padding: 24px 12px;
  margin: 5px 10px 5px 10px;
  border-radius: 0;
}

.blocks {width:100%;}

.btn {max-width:150px;width:100%;}

.container {
  background-color: pink;
  display: flex;
  justify-content: space-between;
  flex-flow: row wrap;
}

for attempt1: jsfiddle link: https://jsfiddle.net/Loxn91oq/4/
for attempt2: jsfiddle link: https://jsfiddle.net/ogdfLq9c/


text:
Q: GenStage: How to handle situations where producer cannot provide events? Following scenario: A GenStage producer handles a Twitter Stream (using the Stream API and ExTwitter) and providing a set of tweets (max. the demand the consumer is asking for) to a GenStage consumer. The consumer then just prints them.
Following problem: I am looking for specific tweets so there aren't always new tweets available. If the GenStage producer is returning an empty list of events, the consumer will stop asking. See this issue and José Valims reply for more.
I am not sure how to address this issue. Any help is greatly appreciated. This is what I have so far:
defmodule MyApp.TwitterProducer do
  use GenStage
  alias MyApp.TwitterStream

  def start_link(:ok) do
    GenStage.start_link(__MODULE__, :ok)
  end

  def init(:ok) do
    # This creates a regular Elixir Stream
    # I use this as the state so that not every
    # time the consumer asks for new data
    # a new stream is initiated
    stream = TwitterStream.get_stream
    {:producer, stream}
  end

  def handle_demand(demand, stream) do
    # Take tweets from the stream and
    # turn them into a list. Then return
    # them to the consumer
    chunk = Stream.take(stream, demand)
    events = Enum.to_list(chunk)
    {:noreply, events, stream}
  end

  def handle_info(_msg, state) do
    # I as getting an "wrong message" error
    # before I implemented this function myself
    # It does nothing special to my case
    {:noreply, [], state}
  end

end

defmodule MyApp.TwitterConsumer do
  use GenStage

  def start_link() do
    GenStage.start_link(__MODULE__, :ok)
  end

  def init(:ok) do
    {:consumer, :the_state_does_not_matter}
  end

  def handle_events(events, _from, state) do

    Process.sleep(3000)
    IO.inspect(events)

    # We are a consumer, so we would never emit items.
    {:noreply, [], state}
  end

end

# Let's fire this thing up
{:ok, p} = GenStage.start_link(MyApp.TwitterProducer, :ok, name: MyApp.TwitterProducer)
{:ok, c} = GenStage.start_link(MyApp.TwitterConsumer, :ok, name: MyApp.TwitterConsumer)
GenStage.sync_subscribe(c, to: p, max_demand: 3)

What happens is: This runs for a while, then stops. As I understand as soon as there is an empty event list returned by the producer.
Edit: Interestingly enough: If I set demand to 1 it keeps running. But it is much, much slower than querying the Twitter Stream API directly. Meaning I receive ten times less tweets. My theory is that it is due to the repeated Stream.take calls instead of just calling Enum.to_list for the whole stream. But I find it still very confusing. Any ideas what I am missing?

A: There is a significant (but unfortunately not expressed in bold) sentence in the documentation on GenStage.handle_demand/2:

The producer must either store the demand or return the events requested.

That said, instead of block on Stream.take one might be explicitly aware of the task might be blocking and handle the case, collecting the demand in such a case using Task.await/2 with a reasonable timeout (maybe Task.yield/2 could be of use in more complicated checks, but here it seems to be an overkill.)
From the documentation:

If you don't want the task to fail then you must change the heavy_fun/0 code in the same way you would achieve it if you didn't have the async call. For example, to either return {:ok, val} | :error results or, in more extreme cases, by using try/rescue.

The documentation lacks the examples, though. OTOH, here it probably would be easier just to return empty list and forget about collecting demand:
def handle_demand(demand, stream) do
  try do
    task = Task.async(fn ->
      stream
      |> Stream.take(demand)
      |> Enum.to_list()
    end)
    Task.await(task, 1000) # one sec
  catch
    :exit, {:timeout, {Task, :await, [_, 1000]}} ->
      {:noreply, [], stream}
  else
    events when is_list(events) ->
      {:noreply, events, stream}
  end
end


text:
Q: Proof of divergence of harmonic series This question is more about the notation than the actual proof. My professor gave us the following proof:
$$\sum_{k=2}^{n} \frac{1}{k} \ge \sum_{k=2}^{n} \int_{k}^{k+1} \frac{1}{x} dx = \int_{2}^{n+1} \frac{1}{x} dx = ln(n+1)-ln(2) \rightarrow \infty $$
I struggle to understand what he did in the first 3 steps. I just don't see how the sum on the left is greater than the sum of the integrals, or why the limits of integration can simply be changed from k to 2 and from k+1 to n+1.
I'd appreciate any help!

A: The function $f(x)=\frac{1}{x}$ is continuous and decreasing on $\mathbb{R}^+$, hence for any $k\in\mathbb{N}^+$ we have
$$ \frac{1}{k}>\int_{k}^{k+1}\frac{1}{x}\,dx \tag{1}$$
and by summing both sides of $(1)$ for $k=1,2,3,\ldots,n$ we get:
$$ H_n = \sum_{k=1}^{n}\frac{1}{k} > \int_{1}^{n+1}\frac{dx}{x} = \log(n+1).\tag{2}$$
In the opposite direction, we may prove a slightly tighter inequality by exploiting $\frac{1}{k}<\log\left(\frac{2k+1}{2k-1}\right)$ and deducing $H_n < \log(2n+1)$.


text:
Q: gnuplot Real Time Plotting C Implementation I'm completely new to gnuplot and have only learned the basics to start plotting. I'm writing a C program that does DSP and needs to plot the result in real time. In addition, I've setup my program in such following manner to incorporate the plot '-' feature from gnuplot. The parent process will perform the DSP computation constantly, and sends the result to the child using pipe in real time. The child will receive a signal from parent, wake up, and sends the result to gnuplot via pipe.
Basically, the path of data goes as such:
Parent(Computation) -> Pipe -> Child (Wait on Input from parent) -> Pipe -> gnuplot (Plotting)
For example, in the child, enclosed in a conditional wait
getline(&lineBuffer, lineSize, stdin);
printf("%s", lineBuffer);
fflush(stdout);

where lineBuffer can be any arbitrary char*, will redirect data from parent to gnuplot. I have all the necessary data for plotting, and it can be formatted in any format. However, after trying the following, there has been no success.
If not yet defined appearances and label,
set terminal x11 persist noraise
set xlabel "Frequency"
set ylabel "Decibel"
set xrange [0:2000]
set yrange [-100:100]
set style data lines

Start initial plot command,
plot '-' using 1:2 smooth unique

Start sending data, each point is a new line, where I formatted my data to be
Frequency Decibel

at a particular time, for example
1000 -30.00
1001 -31.00
....

End data by sending
e\n

Then I restart the process sending the data, and end it with
replot

Does this seem right? On the other hand, I'm also interested in plotting the time series of a particular frequency, and after numerous searches, apparently I need a buffer or a temporary file to accomplish this, is that correct also?


text:
Q: NSString memory leak //opening DB
if(sqlite3_step(statement) == SQLITE_ROW)
    result = [NSString stringWithUTF8String:(char*)sqlite3_column_text(statement,0)];  //!
else
    result nil;
return result;
//close DB

A: This is actually not a memory leak. The NSString will be autoreleased, and the char* returned by sqlite3_column_text will be cleaned up by sqlite during the next step/reset/finalize call.

A: the string should be autoreleased by stringWithUTF8String, are you testing for memory leaks on the iPhone or on the simulator? Often the simulator code is just a touch buggier - try it on the device itself


text:
Q: I have Created a Flask Rest Api and configured in apache for production but is not executing db queries Below lines are added to httpd.conf file
    LoadModule wsgi_module modules/mod_wsgi.so
    <IfModule wsgi_module>
    <Directory D:/MGM/MGMApi>
        WSGIScriptReloading On
        Allow from all
        Require all granted
    </Directory>
    WSGIScriptAlias / D:/MGM/MGMApi/wsgi_test.wsgi
    </IfModule>

wsgi file is created as below
    # test.wsgi
    import sys
    #Expand Python classes path with your app's path
    sys.path.insert(0, "D:\\MGM\\MGMApi")
    from wsgi import app
    #Put logging code (and imports) here ...
    #Initialize WSGI app object
    # api.add_resource(Hello, "/hello", endpoint="hello")
    application = app

Finally .py file to be called from above wsgi file is created as below.
    from flask import Flask
    from flask_cors import CORS
    from flask_restful import Api
    from configparser import ConfigParser
    from flask_sqlalchemy import SQLAlchemy
    from sqlalchemy.ext.automap import automap_base
    from sqlalchemy import MetaData, create_engine
    # from flask_login import LoginManager
    from flask import Flask, request
    from flask_restful import Resource
    import os

    app = Flask(__name__)
    # app.secret_key='F12Zr47j\3yX R~X@H!jmM]Lwfi?KT'
    CORS(app)
    api = Api(app)
    config = ConfigParser()
    config.read(os.path.join(os.path.dirname(__file__),"config.INI"))
    app.config['WTF_CSRF_SECRET_KEY'] = 'random key for form'
    app.config['LDAP_PROVIDER_URL'] = 'ldap://ldap.testathon.net:389/'
    app.config['LDAP_PROTOCOL_VERSION'] = 3
    app.config["SQLALCHEMY_DATABASE_URI"] = "%s://%s:%s@%s/%s" % (config.get("DB Connection", "Driver"),
                                                                  config.get("DB Connection", "Username"),
                                                                  config.get("DB Connection", "Password"),
                                                                  config.get("DB Connection", "Server"),
                                                                  config.get("DB Connection", "Database"))
    app.config["SQLALCHEMY_TRACK_MODIFICATIONS"] = True
    app.config['SQLALCHEMY_POOL_SIZE'] = 20
    app.secret_key = 'p9Bv<3Eid9%$i01'
    db = SQLAlchemy(app)

    base_url = config.get("Run Configuration", "Base_Url")
    port = int(config.get("Run Configuration", "Port"))
    class Hello(Resource):
        def get(self):
            results = db.session.execute("select * from amount")
            print(results)
            name=request.args.get('name', '')
            return 'Hello ' + name + '!'

    api.add_resource(Hello , "/hello", endpoint="hello1")
    if __name__ == '__main__':
        app.run(host="0.0.0.0", port=5080)

When i run in development it is running fine but when i configure using above files in production server db operations are not executed.Anyone Please help me to get out of this issue, thanks in advance.


text:
Q: How can I get the index of an object in an array with a property value that matches a specific criteria? Maybe this question has already been answered before or the answer is so obvious but I've been searching for days and cannot find an answer to this problem. I would appreciate any help on this as I'm at my wits' end.
class marker {
    var latitude = Double()
    var longitude = Double()
    var coordinate = CLLocationCoordinate2DMake(latitude, longitude)
}

let someCoordinate = CLLocationCoordinate2DMake(someLatitude, someLongitude)

Now let's say that I have an array named "markers" of 10 marker objects with all properties already initialized. How can I find the index of the marker item whose coordinate value matches the value of someCoordinate?
EDIT
While trying out the suggestion of iosdk below, I found out that I was trying to compare the marker.coordinate property which is a CLLocationCoordinate2D. That did not work as I expected. Instead I tried this and it worked:
let markerIndex = indexOfMarker(markers) { $0.position.latitude == latitude && $0.position.longitude == longitude }

A: struct SomeStruct {
  let a, b: Int
}

let one = SomeStruct(a: 1, b: 1)
let two = SomeStruct(a: 2, b: 2)
let three = SomeStruct(a: 3, b: 3)

let ar = [one, two, three]

let ans = ar.indexOf { $0.a == 2 } // 1?

Or, on Swift 1, the indexOf function can be:
func indexOfOld<S : SequenceType>(seq: S, predicate: S.Generator.Element -> Bool) -> Int? {

  for (index, value) in enumerate(seq) {
    if predicate(value) {
      return index
    }
  }
  return nil
}

And you'd replace the last line above with:
let ans = indexOfOld(ar) { $0.a == 2 } // 1?