text:
Q: Communications link failure: Connection reset with C3P0 I know this has been asked many a times but I am stuck at it.
I verified following things:
IP address or hostname in JDBC URL is correct.

Hostname in JDBC URL is also recognized by local DNS server.

Port number is correct in JDBC URL.

DB server is up.

Since same DB call works sometimes, I believe it to relate with "Out of Connections". We had only 50-60 connections to DB at the time of issue.
Still, I believe that C3PO connections might have exhausted.
We have following C3P0 configurations
<props>
<prop key="hibernate.c3p0.timeout">
44000
<!--  seconds  -->
</prop>
<prop key="hibernate.c3p0.min_size">5</prop>
<prop key="hibernate.c3p0.max_size">5</prop>
<prop key="hibernate.c3p0.initial_pool_size">5</prop>
<prop key="hibernate.c3p0.idle_test_period">
60
<!--  seconds  -->
</prop>
<prop key="hibernate.c3p0.acquire_increment">2</prop>
<prop key="hibernate.c3p0.max_statements">50</prop>
<prop key="hibernate.c3p0.preferredTestQuery">SELECT 1 FROM DUAL</prop>
<prop key="hibernate.show_sql">true</prop>
</props>

Most of the entries are not defined in here and default is used. Let me know if this might be the issue and reason would be very helpful.
Maximum number C3P0 connections by default are 15 but we almost cross this limit all the time and don't face this issue (again it might be bcoz of acquireIncrement property of C3P0 to support connections in this scenario).
Stacktrace:
org.springframework.dao.DataAccessResourceFailureException: could not execute query; nested exception is org.hibernate.exception.JDBCConnectionException: could not execute query
at org.springframework.orm.hibernate3.SessionFactoryUtils.convertHibernateAccessException(SessionFactoryUtils.java:625)
at org.springframework.orm.hibernate3.AbstractSessionFactoryBean.convertHibernateAccessException(AbstractSessionFactoryBean.java:303)
at org.springframework.orm.hibernate3.AbstractSessionFactoryBean.translateExceptionIfPossible(AbstractSessionFactoryBean.java:282)
at org.springframework.dao.support.ChainedPersistenceExceptionTranslator.translateExceptionIfPossible(ChainedPersistenceExceptionTranslator.java:58)
at org.springframework.dao.support.DataAccessUtils.translateIfNecessary(DataAccessUtils.java:213)
at org.springframework.dao.support.PersistenceExceptionTranslationInterceptor.invoke(PersistenceExceptionTranslationInterceptor.java:163)
at org.springframework.aop.framework.ReflectiveMethodInvocation.proceed(ReflectiveMethodInvocation.java:172)
at org.springframework.aop.framework.JdkDynamicAopProxy.invoke(JdkDynamicAopProxy.java:202)
at $Proxy34.findByName(Unknown Source)
at a.b.c.d.e.f(A.java:941)
at a.b.c.d.e.f$$FastClassByCGLIB$$a171eb15.invoke(<generated>)
at org.springframework.internal.cglib.proxy.MethodProxy.invoke(MethodProxy.java:149)
at org.springframework.aop.framework.Cglib2AopProxy$CglibMethodInvocation.invokeJoinpoint(Cglib2AopProxy.java:688)
at org.springframework.aop.framework.ReflectiveMethodInvocation.proceed(ReflectiveMethodInvocation.java:150)
at org.springframework.transaction.interceptor.TransactionInterceptor.invoke(TransactionInterceptor.java:110)
at org.springframework.aop.framework.ReflectiveMethodInvocation.proceed(ReflectiveMethodInvocation.java:172)
at org.springframework.aop.framework.Cglib2AopProxy$DynamicAdvisedInterceptor.intercept(Cglib2AopProxy.java:621)
at com.amazon.mobiusdatabase.activity.IMBatchActivity$$EnhancerByCGLIB$$42d90986.getLatestBatchByStatus(<generated>)
at com.amazon.coral.reflect.$2198.invoke(Unknown Source)
at com.amazon.coral.service.DefaultActivityInvoker.invoke(DefaultActivityInvoker.java:40)
at com.amazon.coral.service.ContinuationActivityInvokerFactory$1.invoke(ContinuationActivityInvokerFactory.java:92)
at com.amazon.coral.service.ActivityHandler.invoke(ActivityHandler.java:269)
at com.amazon.coral.service.ActivityHandler.before(ActivityHandler.java:157)
at com.amazon.coral.service.TransmutingContinuationHandler.before(TransmutingContinuationHandler.java:51)
at com.amazon.coral.service.Chain.componenteBefore(Chain.java:98)
at com.amazon.coral.service.Chain.before(Chain.java:76)
at com.amazon.coral.service.helper.ChainHelper.before(ChainHelper.java:103)
at com.amazon.coral.service.AbstractOrchestrator.doWork(AbstractOrchestrator.java:60)
at com.amazon.coral.service.PassiveOrchestrator.enqueue(PassiveOrchestrator.java:68)
at com.amazon.coral.service.GracefulShutdownOrchestrator.enqueue(GracefulShutdownOrchestrator.java:79)
at com.amazon.coral.service.helper.OrchestratorHelper.enqueue(OrchestratorHelper.java:44)
at com.amazon.coral.service.batch.BatchProtocolOrchestrator.enqueue(BatchProtocolOrchestrator.java:97)
at com.amazon.coral.service.bobcat.BobcatEndpoint.invoke(BobcatEndpoint.java:194)
at org.apache.catalina.valves.SSLValve.invoke(SSLValve.java:113)
at org.apache.catalina.connector.CoyoteAdapter.service(CoyoteAdapter.java:286)
at org.apache.coyote.http11.Http11NioProcessor.process(Http11NioProcessor.java:894)
at org.apache.coyote.http11.Http11NioProtocol$Http11ConnectionHandler.process(Http11NioProtocol.java:719)
at org.apache.tomcat.util.net.NioEndpoint$SocketProcessor.run(NioEndpoint.java:2101)
at java.util.concurrent.ThreadPoolExecutor$Worker.runTask(ThreadPoolExecutor.java:886)
at java.util.concurrent.ThreadPoolExecutor$Worker.run(ThreadPoolExecutor.java:908)
at java.lang.Thread.run(Thread.java:662)
Caused by: org.hibernate.exception.JDBCConnectionException: could not execute query
at org.hibernate.exception.SQLStateConverter.convert(SQLStateConverter.java:97)
at org.hibernate.exception.JDBCExceptionHelper.convert(JDBCExceptionHelper.java:66)
Caused by: com.mysql.jdbc.exceptions.jdbc4.CommunicationsException: Communications link failure

Last packet sent to the server was 1 ms ago.
at sun.reflect.GeneratedConstructorAccessor143.newInstance(Unknown Source)
at sun.reflect.DelegatingConstructorAccessorImpl.newInstance(DelegatingConstructorAccessorImpl.java:27)
at java.lang.reflect.Constructor.newInstance(Constructor.java:513)
at com.mysql.jdbc.Util.handleNewInstance(Util.java:406)
at com.mysql.jdbc.SQLError.createCommunicationsException(SQLError.java:1074)
at com.mysql.jdbc.MysqlIO.reuseAndReadPacket(MysqlIO.java:2985)
at com.mysql.jdbc.MysqlIO.reuseAndReadPacket(MysqlIO.java:2871)
at com.mysql.jdbc.MysqlIO.checkErrorPacket(MysqlIO.java:3414)
at com.mysql.jdbc.MysqlIO.sendCommand(MysqlIO.java:1936)
at com.mysql.jdbc.MysqlIO.sqlQueryDirect(MysqlIO.java:2060)
at com.mysql.jdbc.ConnectionImpl.execSQL(ConnectionImpl.java:2542)
at com.mysql.jdbc.PreparedStatement.executeInternal(PreparedStatement.java:1734)
at com.mysql.jdbc.PreparedStatement.executeQuery(PreparedStatement.java:1885)
at com.mchange.v2.c3p0.impl.NewProxyPreparedStatement.executeQuery(NewProxyPreparedStatement.java:76)
at org.hibernate.jdbc.AbstractBatcher.getResultSet(AbstractBatcher.java:208)
at org.hibernate.loader.Loader.getResultSet(Loader.java:1808)
at org.hibernate.loader.Loader.doQuery(Loader.java:697)
at org.hibernate.loader.Loader.doQueryAndInitializeNonLazyCollections(Loader.java:259)
at org.hibernate.loader.Loader.doList(Loader.java:2228)
... 49 more
Caused by: java.net.SocketException: Connection reset
at java.net.SocketInputStream.read(SocketInputStream.java:168)
at com.mysql.jdbc.util.ReadAheadInputStream.fill(ReadAheadInputStream.java:113)
at com.mysql.jdbc.util.ReadAheadInputStream.readFromUnderlyingStreamIfNecessary(ReadAheadInputStream.java:160)
at com.mysql.jdbc.util.ReadAheadInputStream.read(ReadAheadInputStream.java:188)
at com.mysql.jdbc.MysqlIO.readFully(MysqlIO.java:2428)

We are getting this while firing a select query on DB.

A: Maybe the connections aren't correctly closed, so you can try to decrease drastically the timeout to see if you have the same problem.
 <prop key="hibernate.c3p0.timeout">3000</prop>

At the same time you could use a JMX profiler like VisualVM to monitor the C3P0 connections, and see directly on the database server if there are "lost" connections.


text:
Q: How to make Ionic app user login? I have two text box for username and password, when each user enter data it should send to api. how can i make it work.

         Username
         <input type="text" ng-model="loginData.username">

           Password
          <input type="password" ng-model="loginData.password">

wrong credentials

         <button class="button button-block button-positive" type="submit">Log in</button>

A: You should read through the angular documentation for forms.
https://docs.angularjs.org/guide/forms
Here's a quick example of a template + controller.
html
<form action="submitLogin()">

         Username
         <input type="text" ng-model="loginData.username">

           Password
          <input type="password" ng-model="loginData.password">

wrong credentials

         <button class="button button-block button-positive" type="submit">Log in</button>

</form>

controller
var example_app = angular.module("example_app ", []);

example_app.controller("LoginController", ['$scope', '$http', function($scope, $http) {
    $scope.loginData = {};
    $scope.submitLogin= function(){
        var res = $http.post('http://login.com/postLogin', loginData);
        res.success(function(data, status, headers, config) {
            $scope.message = data;
            // go to authorized page
        });
        res.error(function(data, status, headers, config) {
            alert( "failure message: " + JSON.stringify({data: data}));
        });

    };
}]);

Documentation doesn't show the action= functionality, but shows a ng-click on the submit button instead.  Both work fine.
Edit:
Was going to mention, but forgot to, that you should try to use angular services for instead of using $http directly in your controller.
https://docs.angularjs.org/guide/services
https://github.com/johnpapa/angular-styleguide

redpajama_set_name: RedPajamaStackExchange


text:
Q: Odata V4 Client DataServiceContext Full Text Search I'm using Odata V4 DataServiceContext to fetch data from server.
I need to achieve following requirements.
public class Person
{
    public int Id{get;set;}
    public string FirstName{get;set;}
    public string LastName{get;set;}
    public string City{get;set;}
}

I need to do a full text search by querying any of the properties value is  matches to provided string value.
I can use below code to achieve this:
var searchString = "California";
IQueryable<Person> query = context.Person.Where(x=>x.Id.ToString().Contains(searchString) || x.FirstName.Contains(searchString) || x.LastName.Contains(searchString) || x.CityContains(searchString));

But I don't want to include all the properties in the expression like in above code. Also there will be an exception thrown if I compare string value with a non string property.
I need to make this more generic.
Requirement 1
IQueryable<Person> query = context.Person.Where(AnyOfPropertiesStringValue.Contains(searchString);

Here AnyOfPropertiesStringValue is a dummy method and I want to transform it to an executable code.
Requirement 2
IQueryable<Person> query = context.Person.Where(PropertiesStringValue("FirstName","LastName").Contains(searchString);

Here PropertiesStringValueis a dummy method and  I want to transform it to an executable code which will only compares the properties which name is passed as a parameter. In above example need to compare properties FirstName and LastName with provided string value.
Finally need to create an object of IQueryable<Person> type.
Could anyone help me to solve this?


text:
Q: Mule 3.4 - scripting in Python I'm having quite a bit of trouble getting started with scripting in Mule. To be quite honest, I'm falling at the first hurdle - I can't find anything in the documentation which tells me how to access the payload or how to return data to my flow.
I'm using Jython 2.5 and Mule 3.4.
My flow is extremely simple: it takes some text from an Ajax source and simply echoes it. At the moment the Python script does nothing (as I cannot figure out how to get it to do something with the payload).
<flow name="Python Script" doc:name="Python Script">
    <ajax:connector name="connector-ajax" serverUrl="http://192.168.0.1:8000" resourceBase="C:\mule\workspace\scripting\src\main\app\docroot" doc:name="Ajax" />
    <scripting:component doc:name="Python">
        <scripting:script engine="jython" file="C:\mule\workspace\scripting\src\main\app\python\myscript.py"/>
    </scripting:component>
    <echo-component doc:name="Echo"/>
</flow>

I have read through the Script Component Reference and the Scripting Module Reference - the module reference appears to have some relevant information but I can't figure out how to use it in Python.
I have also read through an article about 'Mule Punching' which seems like it would have answered my question if I was running version 2 of Mule. I attempted to use the same techniques in my Mule 3 project but it did not work.
Edit 24/07/2012
Using @ppiixx's response, I have got a little bit further with Python scripting.
Just having a single line of code, for example return len(payload) causes the Jython interpreter to throw an error as return cannot exist outside of a function. Fair enough, that's standard.
However, with the code
def main():
  return len(payload)

main()

I get an error saying that 'No serializer can be found for class org.mule.transport.NullPayload'.
The log is below:
++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++
+ Started app 'python-test'                                +
++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++
INFO  2013-07-24 09:16:08,821 [[python-test].flow.stage1.02] org.mule.component.simple.LogComponent:
********************************************************************************
* Message received in service: flow. Content is: '{NullPayload}'               *
********************************************************************************
ERROR 2013-07-24 09:16:08,849 [[python-test].flow.stage1.02] org.mule.exception.CatchMessagingExceptionStrategy:
********************************************************************************
Message               : No serializer found for class org.mule.transport.NullPayload and no properties discovered to create BeanSerializer (to avoid exception, disable SerializationConfig.Feature.FAIL_ON_EMPTY_BEANS) ) (org.codehaus.jackson.map.JsonMappingException)
Code                  : MULE_ERROR--2
--------------------------------------------------------------------------------
Exception stack is:
1. No serializer found for class org.mule.transport.NullPayload and no properties discovered to create BeanSerializer (to avoid exception, disable SerializationConfig.Feature.FAIL_ON_EMPTY_BEANS) ) (org.codehaus.jackson.map.JsonMappingException)
  org.codehaus.jackson.map.ser.impl.UnknownSerializer:52 (null)
2. No serializer found for class org.mule.transport.NullPayload and no properties discovered to create BeanSerializer (to avoid exception, disable SerializationConfig.Feature.FAIL_ON_EMPTY_BEANS) ) (org.codehaus.jackson.map.JsonMappingException) (org.mule.api.transformer.TransformerException)
  org.mule.module.json.transformers.ObjectToJson:107 (http://www.mulesoft.org/docs/site/current3/apidocs/org/mule/api/transformer/TransformerException.html)

This leads me to think that using return on its own isn't enough to return data to the flow.
I've read through the scripting module reference, and while it gives examples in Groovy, it does not give examples in Python so I'm not sure where I'm going wrong.

A: Have a look at the 'Script Context Bindings' section here.
Basically a number of variables are available in the script context including: message,payload and log.
To return data using the python engine you set the result variable.
result = len(payload)

There is a example in the mule github.


text:
Q: CSS Selector for adding content through :after / :before when HTML element is missing I would like to add content with the CSS :before selector in case an unsorted HTML list does not have any list items. I can not use :empty, because there might be white space (blanks, newlines, tabs, etc.) between ul and /ul.
As :blank is not implemented yet in most browsers, I need another solution.
Here is an example:
// CSS
ul > li::before { content: 'abc'; }   /* how to negate this? */

// 'abc' should not show up

xxx

xxx

// 'abc' should show up

The CSS above shows 'abc' when the unsorted list has children. I would like to show 'abc' when the unsorted list has no children. So I'm looking for the negation of the CSS line.

A: This won't be possible without the functionality of the :blank pseudo-class, I'm afraid.1
There are only two possible places you can insert a ::before pseudo-element in your scenario: in the ul, or in a li. Since you want to insert the generated content only when no li elements are present, that leaves you only with ul.
Although ::before and ::after are inserted before and after an element's descendant elements respectively, you can't target them relative to those descendant elements with a sibling combinator, and pseudo-elements currently do not support structural pseudo-classes. Which means, in other words, you won't be able to say "prevent ul::before from generating content in the presence of one or more li elements", nor can you apply the :only-child pseudo-class to ul::before.
In a situation where one can use :empty, it's as simple as
ul:empty::before { content: 'abc'; }

but since you cannot use :empty for the reasons you have given, if you really cannot prevent the whitespace from being generated (e.g. if the content is coming from a WYSIWYG editor or some other transformation that may result in leftover whitespace) you'll have to add a class to any ul elements with no children.

1 A recent revision to selectors-4 proposes subsuming the functionality of :blank into :empty instead, but that likewise is new and requires the cooperation of implementers.


text:
Q: Distributing task with python and zeromq I have a working application using python and zeromq and I would like to optimize it.
Briefly, a master node send the same request to all workers (about 200) and the then collect the answers. Based on the answer, it sends a message back to one node and the node answers back.
Right now I implemented a very simple pattern. Each worker has one REP socket and the server has a list of REQ sockets. The server iterates through all sockets sending the general message and then iterates through all sockets to collect the answers. Finally, based on the answers the server picks one worker, sends a message to it and waits for the reply.
This is, of course, quite slow. The slowest part is sending 200 times the same message. Collecting is also slow. The solutions that I have found to distribute tasks and collect answers do load balance which is not what I need. I need that each worker receives the message and responds.
What is the pattern recommended for this situation?
Thanks

A: If each worker should need a different job, Pub/sub wont work . What you need then is a worker pool Implementation. Either you push out the jobs in a round robin style (just use the push socket bound on the server and have each client pull from it, zeromq will do the round robin) or you have each worker request a job from the server, if the jobs are at least of some minimum complexity and the variance between jobs is high that is a better approach. There are numerous examples in the zeromq guide on its homepage and on the net:

*

*http://zguide.zeromq.org/page:all (look at the paronoid pirate pattern)

*http://blog.garambrogne.net/post/2010/10/23/simple-python-work-queue-with-zeromq

*https://github.com/marklit/zeromq-worker-queue
The concrete implementation also depends on whether or not you need to have jobs reliably processed.

A: I don't know zmq. Here's a pattern that might not work, just to get started:

a master node send the same request to all workers (about 200)

master PUB bind *:3140 send
worker SUB connect masterhost:3140 SUBSCRIBE recv

the then collect the answers

worker PUSH connect masterhost:3141 send
master PULL bind *:3141 recv

Based on the answer, it sends a message back to one node and the node answers back.

master REQ connect workerhost:3142 send recv
worker REP bind *:3142 recv send


text:
Q: :echo inside :inorea not working I'm trying to use vim plugin hints_opengl.vim, but it is not working as intended. If you look at the plugin's code, it is supposed to :echo some text using :inorea call like this:
inorea glEnd glEnd<c-o>:echoh HintHL<Bar>echo "void glEnd(void)"<Bar>echoh None<cr>

However for me it doesn't echo anything. I tried to define some inoreas with :echo command like this:
inorea hhh hhh<c-o>:echo "hello"<cr>

But those didn't work either. However doing <c-o>:echo "something" manually during typing in insert mode works fine. What should I do then to properly echo text with :inorea? How do I get this plugin to work?

A: You don't see the messages in insert mode because the default height of the command-line is one, and the -- INSERT -- immediately overwrites your message.
Either increase the height:
:set cmdheight=2

or turn off the display of the current mode:
:set noshowmode


text:
Q: How to calculate time of passing the discrete path of cells? Let's say we have a field of descrete cells (2d array or table). We have some finite path inside of it with no self-crossings and no diagonal connections. The particle starts its way in the point A and follows the pattern to the point B. One step can be done in the finite amount of time = t. So the time for the whole path will be T = t * l, where l = number of cells in the path. But! We have some cells in the field marked as 'h' and 'v'. If the particle hit the 'h' cell then it divides into 3 particles. One continue moving by the path. Second starts to move left from the 'h' cell to the left border of the field. Third starts to move right from the 'h' cell to the right border of the field. Analogically with the 'v' cell, but instead of left/right, another 2 particles start move up/down. All particles are moving simultaneously with the same speed. Additional particles can collect 'h' and 'v' too and also can be divided and spawn more particles. Need to write function in Lua that calculates time from the moment of first particle starts its way to the moment of all particles finished their ways. See related illustation. Note that once 'h' or 'v' cell have been collected it becomes a simple cell and other particles doesn't divide if hitting it.

A: There's not much of an algorithm that can be done here apart from the direct running of the simulations.
There can be no apriori knowledge of the simulation time since the movement of different particles alters the conditions for other particle movement (as in during harvest act).
If the v and h tiles remained after the interaction process then you could just perform a simple raytracing i.e. scan the route, find v and h tiles scan the lines drawn from v andh tiles, find v,h or border tiles, calculate the longest path, draw lines from newfound v,h and scan those, and so on until all lines hit the border or lock into loop. To ignore looped results you could memorize which tiles have been already visited by currently examined ray and its predecessors.
Obviously, as special tiles (v,h) can only prolong the simulation time, the result from above would give upper limit of time in simulation with disappearing special tiles. To calculate the exact runtime, you'd need to take into account the moment in time at which a particular tile is triggered. Surely, it is possible to do that with rays, but a little of thought is needed that it'd be an equivalent to a direct simulation of particles.
The code for that is pretty simple and I will only briefly outline algorithm:
%make array for particlesenter code here
particles={}

%define initial particle route
route={{x1,y1},{x2,y2},...}

%probably you should have your field defined somewhere here too
v_tiles={{x1,y1},{x2,y2}...}
h_tiles=...

%make particle, possible implementations are numerous really
%for example it could be represented by its position
%and a function which gives next position, based on current one
%for main particle it could search the route table for a current position and return next element,
%or just use external counter variable to keep track of propagation
particle={position={x,y}, propagator=function({x,y}) ....}

%put that into particles array obviously

%initialize counter
T=0
%run a cycle until there are particles
while #particles>0 do

    %perform a single step for all the particles
    for _,p in pairs(particles) do
        %move them all
        p.position=p.propagator(p.position)
    endfor
    %then check them all
    for i,p in pairs(particles) do
        %check for special tiles
        if is_v(p.position) then
            %make new particle
            table.insert(particles,{
                position={p.position.x, p.position.y+1},
                %for secondary particles propagator would be just a constant addition to a single coordinate
                propagator=function(pos) return {pos.x,pos.y+1} end
                })
            %make second new particle

        %same for h tiles
        if is_h(p.position) then ...

        %check for border tile
        if is_border(p.position) then
            %remove those that are at the border
            table.remove...
            %for the original particle you'd have to check
            %whether it has reached destination
            %probably you should check that somewhere around here too
    endfo
    %do what we're here for: increase counter
    T=T+1
endwhile
%when this reaches the end T will be the answer

It is good that when you're solving the problems in lua, you have machine powerful enough to not worry about memory footprint and just fire away with the variable size array. But for the current task it is possible to get rough upper limit for memory as : 1+2*( num_v+num_h ).
Once again, in direct simulation you might have less particles, but since every interaction with special tile removes special tile and adds a pair of particles, you will never have more than that.


text:
Q: Regex to replace stored procedure params with declarations Quite often I have to rewrite stored procedure because I don't have execution rights to a "normal" code - meaning rewriting stored procedure params to declarations + SETs.
For example:
@pParam  VARCHAR(20),
@pPlant  VARCHAR(4) = NULL,
@pDateTimeFrom  VARCHAR(30) = NULL,
@pDateTimeTo  VARCHAR(30) = NULL,
@pLanguage  VARCHAR(2) = 'EN',
@pClass  NVARCHAR(MAX) = NULL,
@pFilterCompleteDate  BIT = NULL,
@user VARCHAR(50) = NULL,
@updateKey VARCHAR(50) = NULL,
@seqnoKey INT = NULL,
@comment VARCHAR(1000) = NULL,
@testID INT = NULL,
@info NVARCHAR(MAX) = NULL

And with regex find and replace I want it in this format:
DECLARE @pParam VARCHAR(20)
SET @pParam =
DECLARE @pPlant VARCHAR(4)
SET @pPlant = NULL
DECLARE @pDateTimeFrom VARCHAR(30)
SET @pDateTimeFrom = NULL
DECLARE @pDateTimeTo VARCHAR(30)
SET @pDateTimeTo = NULL
DECLARE @pLanguage VARCHAR(2)
SET @pLanguage = 'EN'
DECLARE @pClass NVARCHAR(MAX)
SET @pClass = NULL
DECLARE @pFilterCompleteDate BIT
SET @pFilterCompleteDate = NULL
DECLARE @user VARCHAR(50)
SET @user = NULL
DECLARE @updateKey VARCHAR(50)
SET @updateKey = NULL
DECLARE @seqnoKey INT
SET @seqnoKey = NULL
DECLARE @comment VARCHAR(1000)
SET @comment = NULL
DECLARE @testID INT
SET @testID = NULL
DECLARE @info NVARCHAR(MAX)
SET @info = NULL

I came up with this regex
Find:
(@.+?)\b\s+\b(.*?)(\s=\s(.*),?|,)

Replace:
DECLARE \1 \2 \r\nSET \1 = \4

But the 4th capture group includes the , at the end of the string. When I included it in the regex, it didn't get the first line without value and last line without comma.
Could you help me find a regex which would correctly find all declarations (no value, value, no comma). Thanks!

A: You can use
(@\S+)\s+\b([^=\n]*?)(\s*=\s*(.*?))?,?(?=$|\r?\n)

And replace with DECLARE \1 \2 \r\nSET \1 = \4.
See regex demo output:
DECLARE @pParam VARCHAR(20)
SET @pParam =
DECLARE @pPlant VARCHAR(4)
SET @pPlant = NULL
DECLARE @pDateTimeFrom VARCHAR(30)
SET @pDateTimeFrom = NULL
DECLARE @pDateTimeTo VARCHAR(30)
SET @pDateTimeTo = NULL
DECLARE @pLanguage VARCHAR(2)
SET @pLanguage = 'EN'
DECLARE @pClass NVARCHAR(MAX)
SET @pClass = NULL
DECLARE @pFilterCompleteDate BIT
SET @pFilterCompleteDate = NULL
DECLARE @user VARCHAR(50)
SET @user = NULL
DECLARE @updateKey VARCHAR(50)
SET @updateKey = NULL
DECLARE @seqnoKey INT
SET @seqnoKey = NULL
DECLARE @comment VARCHAR(1000)
SET @comment = NULL
DECLARE @testID INT
SET @testID = NULL
DECLARE @info NVARCHAR(MAX)
SET @info = NULL


text:
Q: How do I run node.js in my Java script code? I'm quite new to web developing (a week or so in) and I understand I may be moving too quickly but I need some help as I don't quite understand this. What I have so far is a login page that compares the 2 inputs (username + password) to 2 constant variables. However the way I want it to work is comparing the inputs to 2 values I read from a text file, so I can have like a database of usernames/passwords.

Welcome User
 Please enter your username and password

<form method="post" name="my_form">

User Name:   <input type="text" id="UserName" name="UserNameN" />

Password:      <input type="password" id="password1" name="password1N" />

<input type="button" value="Submit" onClick="sendit()"/>
</form>

Then you need to make the php page:
<?PHP
$UserName = $_POST['UserNameN'];
$Password = $_POST['password1N'];

function redirect($url)
{
   header('Location: ' . $url);
   exit();
}

if ($UserName == "BobTim" and $Password == "Password")
{
session_start();
$_SESSION['username']= 'BobTim';
redirect("abc123.html");
exit();
}

if ($UserName == "Blake" and $Password == "12345")
{
session_start();
$_SESSION['username']= 'Blake';
redirect("abc123.html");
exit();
}

if ($UserName == "George" and $Password == "ABCDEFG")
{
session_start();
$_SESSION['username']= 'George';
redirect("abc123.html");
exit();
}

if ($UserName == "Steve" and $Password == "ILikeBlue")
{
session_start();
$_SESSION['username']= 'Steve';
redirect("abc123.html");
exit();
}

if ($UserName == "Coco" and $Password == "IceCream")
{
session_start();
$_SESSION['username']= 'Coco';
redirect("abc123.html");
exit();
}

else {
redirect("sorry.html");
exit();
}
?>

After you redirect to abc123.html, you make abc123.html with this at the top:
<?PHP
session_start();

if (!isset($_SESSION['username'])) {
header('Location: http://www.mybusinesssample.com/forbidden.html');
}

?>

<title>Main Page</title>

<?PHP
if (isset($_SESSION['username'])) {
echo "Hi {$_SESSION['username']}
Log Out

";
}
?>

Now, you need a logout page which in this case is called unset.php:
<?php
session_start();
session_destroy();
header ('Location: index.html');
?>

And if they don't make it through, you need to tell them sorry:

<title></title>

Welcome User
 Please enter your username and password

<form method="post" name="my_form">

User Name:   <input type="text" id="UserName" name="UserNameN"/>

Password:      <input type="password" id="password1" name="password1N" />

Sorry! Your Username and/or your password wasn't recognized!

<button type="button" id="button" onclick="sendit()">Submit</button>
</form>

Lastly, I would like to thank you for making this old, old project relevant again.

A: Sounds like you may need to consider creating a desktop app to work with the website.
Reading in a text file with node.js on the client side, is very easy if you use either NW or Electron. These programs take your HTML +CSS + JS and produce an executable app that has access to node.js and a Chromium window.
So your desktop app could then communicate with your website.
NW:
https://nwjs.io/
Electron:
https://electronjs.org/
I use the former and it works like a charm. In fact the only trouble I ever get is from the countless Chromium bugs.


text:
Q: Map is null after loading currencies from API Any idea why my currencies map is null in the CurrencyConverterState class? I am loading currencies from an API to my currencies map in class API (see code for class API) and also trying to set state after the loading is done. After loading the currencies from the API to my currencies map I can also access the rates from the map so that means that my map is working fine and is not null. I did that test by printing a currency rate and it was fine. But that works just in the API class. The problem is that as soon as I test my currencies map in class CurrencyConverterState it says that the map is null and I am stuck in circular progress indicator (see code for class CurrencyConverterState). I dont really know why it says that the map is null. Any help appreciated.
API class code:
class API
{
  var fromTextController = new TextEditingController();

  Map<dynamic, dynamic> currencies;

  String fromCurrency;
  String toCurrency;

  String result;

  API(String from, String to){
    fromCurrency = from;
    toCurrency = to;
  }

  Future<dynamic> loadCurrencies() async {
    String uri = "http://api.openrates.io/latest";
    var response = await http
        .get(Uri.encodeFull(uri), headers: {"Accept": "application/json"});
    var responseBody = json.decode(response.body);
    Map curMap = responseBody['rates'];
    currencies = curMap;
    setState(() {});
    print (currencies["SEK"]);
  }

  Future<dynamic> doConversion() async {
    String uri =
        "http://api.openrates.io/latest?base=$fromCurrency&symbols=$toCurrency";
    var response = await http
        .get(Uri.encodeFull(uri), headers: {"Accept": "application/json"});
    var responseBody = json.decode(response.body);
    setState(() {
      result = (double.parse(fromTextController.text) *
          (responseBody["rates"][toCurrency]))
          .toString();
    });
    setState(() {});
    return "Success";
  }

  void setState(Null Function() param0) {}
}

CurrencyConverterState class code:
class CurrencyConverterState extends State<CurrencyConverter> {
  final API api = new API("USD", "SEK");

  CurrencyConverterState();

  int i = 1;

  @override
  void initState() {
    super.initState();
     api.loadCurrencies();
    api.fromTextController.addListener(doConversion);
    setState(() {

    });
  }

  @override
  Widget build(BuildContext context) {
    return Scaffold(
        resizeToAvoidBottomPadding: false,
        backgroundColor: Theme.of(context).primaryColor,
        body: api.currencies?.keys == null
            ? Center(child: CircularProgressIndicator())
            : Stack(children: [
                Positioned(
                  top: 30,
                  child: Container(
                    alignment: Alignment.center,
                    height: MediaQuery.of(context).size.height / 2,
                    width: MediaQuery.of(context).size.width,
                    child: Padding(
                      padding: const EdgeInsets.all(8.0),
                      child: Card(
                          elevation: 10,
                          child: Column(
                            mainAxisAlignment: MainAxisAlignment.spaceEvenly,
                            children: [
                              Text(
                                'Converter',
                                style: TextStyle(
                                    color: Colors.black, fontSize: 22.0),
                              ),
                              ListTile(
                                title: TextField(
                                  controller: api.fromTextController,
                                  decoration: InputDecoration(
                                      hintText: 'Enter a number'),
                                  style: TextStyle(
                                      fontSize: 20.0, color: Colors.black),
                                  keyboardType: TextInputType.numberWithOptions(
                                      decimal: true),
                                ),
                                trailing:
                                    buildDropDownButton(api.fromCurrency),
                              ),
                              ListTile(
                                title: Chip(
                                    label: api.result != null
                                        ? Container(
                                            width: 1000,
                                            height: 40,
                                            child: Text(
                                              api.result,
                                              style: Theme.of(context)
                                                  .textTheme
                                                  .headline4,
                                            ),
                                          )
                                        : Container(
                                            width: 1000,
                                            height: 40,
                                            child: Text(" "))),
                                trailing:
                                    buildDropDownButton(api.toCurrency),
                              ),
                            ],
                          )),
                    ),
                  ),
                ),
              ]));
  }

  Widget buildDropDownButton(String currencyCategory) {
    return DropdownButton(
        value: currencyCategory,
        dropdownColor: Colors.white,
        icon: Icon(Icons.arrow_downward),
        iconSize: 24,
        items: api.currencies.keys.map((dynamic value) => DropdownMenuItem(
                value: value,
                child: Row(children: <Widget>[
                  Text(value),
                ])))
            .toList(),
        onChanged: (dynamic value) {
          if (currencyCategory == api.fromCurrency) {
            api.fromCurrency = value;
          } else {
            api.toCurrency = value;
          }
          setState(() {});
        });
  }

  doConversion() {
    api.doConversion();
    setState(() {});
  }
}

A: Actually, you are retrieving currencies before they get retrieved and you are never updating the UIs when they are retrieved.
This is a possible solution:
//In API class
Future<Map<String,dynamic>> loadCurrencies() async {
    String uri = "http://api.openrates.io/latest";
    var response = await http
        .get(Uri.encodeFull(uri), headers: {"Accept": "application/json"});
    var responseBody = json.decode(response.body);
    Map<String,dynamic> curMap = responseBody['rates'];
    print (currencies["SEK"]);
    return curMap;
}

Then in your main class use a futureBuilder:
return Scaffold(
        resizeToAvoidBottomPadding: false,
        backgroundColor: Theme.of(context).primaryColor,
        body: FutureBuilder(
           future: api.loadCurrencies(),
           builder: (context, currencies) =>{
             return currencies==null?
             ? Center(child: CircularProgressIndicator())
             : Stack(/*rest of your code*/);
        })
);


text:
Q: Android use System app without root to write to file I am currently developing an AOSP ROM and I need to make a system app which is able to write data to CPU text files. The thing is I am able to do it while I have root access but the ROM needs to be flashed and provided to a non-root phone which should still be able to use that system app.
Could someone with prior experience please provide some guidance ?


text:
Q: Is it possible to do a dynamic LLVM assembler (from a higher level language like Java)? In this example - the author

*

*takes input in a higher level language (eg Scala),

*takes a String,

*skips over the JVM via the sun.misc.Unsafe library,

*allocates memory dynamically,

*creates a function dynamically, and

*executes the function.

all effectively on the REPL. (As per the live coding presentation at Devoxx FR16).
Now I don't know enough about the LLVM toolchain. I understand that for both the JVM and LLVM you can compile some code and run it. The JVM also has dynamic facilities via Classloaders, invokedynamic and reflection.
My question is: Is it possible to do a dynamic LLVM assembler (from a higher level language like Java)?

A: There are folks doing projects like that - Scala Native and Scala Offheap

A: Yes, you can use LLVM MC JIT along with ExecutionEngine to runtime compile and execute code.


text:
Q: Where has all the RAM gone? I have 1GB of RAM, and when I run NetBeans and Firefox, they get about 300MB of RAM. At some point, the system becomes very slow, probably 100 times slower than normal, switching windows (Alt+Tab) becomes a huge task and the computer is practically useless. This is probably the moment when it starts to swap.
Two questions:

*

*According to images provided, where has all the RAM gone? When I calculate all the processes memory, it is far smaller then 1GB.

*Is it normal for system to become 100 times slower when the RAM is full and using swap space?

On another computer with 4GB of RAM I have no problems.

Update: I added 2GB of RAM, now I have 3GB. Anyone who wants to use heavy apps with 1GB on Unity, I don't think it's going to work. Works fine on an empty desktop :)

A: Yes, it's normal for your system to be extremely slow, or entirely unusable when your RAM is full (Trust me, I only have 2GB of RAM).

A: I suggest you take a look at this article
https://help.ubuntu.com/community/SwapFaq
you can tune your swap usage here (make it use swap later/earlier)

A: *

*Under View make sure you have selected All Processes :

*Yes, that's normal. Swap space on a hard drive is muuuuuch slower than RAM.

A: Did you encrypt your home folder by any chance?
I did and it also created an encrypted swap (it only does so on when installing ubuntu).
That swap besides slowing my boot time seems to be extremely slow:
For compassion I used a Pentium 4, 1GB of RAM as my main PC (home encrypted but not swap I think) and never swapping was so bad like now that I switched to a Core I5 laptop with 4GB of RAM.
I need to use swap when working with PDF's (most related programs seem to forget that /tmp exists..)


text:
Q: Image Sprites in Single Image VB.Net App How can I use image sprites in single image using vb.net just like the css feature in web app.

A: What exactly do you want to do ? You can easily put an image sprite and use that sprite using CSS at the required place.


text:
Q: Formatting values of plot axis I have produced two pngs of the same size with the command:
figure; plot(...);
print('-dpng', 'plotname1', '-S500,360');
figure; plot(...);
print('-dpng', 'plotname2', '-S500,360');

As you can see, these images aren't aligned (the first one is "wider").
Is it possible to set the format of numbers in the y-axis? I would like to force the y-axis to use, for example, always only 1 digit base thus removing values like "2.5e-13" in favor of "3e-13" or "2e-13".
(The x-axis is a bit ugly now, but it's not a problem since I will print these plots wider eventually)

A: You can explicitly specify the tick marks to use on the y axis, for example:
set(gca, 'YTick', 0:1e-13:3e-13)

but you need to know the minimum, maximum and spacing you want to use.


text:
Q: Calculating Percentages with SUM and Group by I am trying to create an Over Time Calculation based on some set criteria. It goes as follows.
Overtime is posted on any day that is over 8 hrs but an employee has to reach 40 total hrs first and the calculation starts at the 1st day moving forward in the week. The Overtime is calculated based on the  percentage taken of the SUM total of the cost codes worked.
First you have to find the percentage of each cost code worked for the entire week per employee id. See Example below
Then each day that is Over 8 hrs you take the time on that code for the day and multiply it by the calculated percentage. At the end of the week the regular hours must total 40hrs if they have gone over 40 for the week.  See below example
CREATE TABLE [Totals](
    [Day] nvarchar (10) null,
    [EmployeeID] [nvarchar](100) NULL,
    [CostCode] [nvarchar](100) NULL,
    [TotalTime] [real] NULL,)

INSERT  Into Totals (day,employeeid, CostCode, TotalTime) VALUES
('1','1234','1', 2),
('1','1234','2', 7.5),
('2','1234','1', 1.5),
('2','1234','2', 8),
('3','1234','1', 1),
('3','1234','2', 6),
('4','1234','1', 2),
('4','1234','2', 8),
('5','1234','1', 2),
('5','1234','2', 8),
('1','4567','1', 2),
('1','4567','2', 8.5),
('2','4567','1', 1.5),
('2','4567','2', 7.6),
('3','4567','1', 1),
('3','4567','2', 5),
('4','4567','1', 2),
('4','4567','2', 8),
('5','4567','1', 2),
('5','4567','2', 8)

To get the percentage of each cost Worked it is the SUM total time of each cost per week / SUM total time  of the entire week
   SELECT employeeid,CostCode,SUM(totaltime) As TotalTime ,
   ROUND(SUM(Totaltime) / (select SUM(TotalTime) from Totals where employeeid = '1234') * 100,0) as Percentage
    from Totals WHERE EmployeeID = '1234' group by EmployeeID, CostCode

Percentage Calculated for the Week by Cost = 18% worked on Cost 1 and 82% on Cost 2
I would like to take the percentage results for the week and calculate the total time each day in the query
Results Example Day 1: for EmployeeID  1234
Day CostCode RegTime OverTime
 1     1        1.73     .27
 1     2        6.27    1.23

A: After editing i get your result, try this:
select calc.*
--select [day], CostCode, EmployeeID
--, CPr * DayEmpRT RegTime_old
, TotalTime - CPr * DayEmpOT RegTime
, CPr * DayEmpOT OverTime
from (
  select Agr.*
  --, round(EmpC1T / EmpT, 2) C1Pr
  --, round(1 - (EmpC1T / EmpT), 2) C2Pr
  , round(EmpCT / EmpT, 2) CPr
  , case when DayEmpT > 8 then 8 else DayEmpT end DayEmpRT
  , case when DayEmpT > 8 then DayEmpT - 8 else 0 end DayEmpOT
  from (
    select Totals.*
    , SUM(TotalTime) over (partition by EmployeeID, [day]) DayEmpT
    --, SUM(case when CostCode = 1 then TotalTime end) over (partition by EmployeeID) EmpC1T
    , SUM(TotalTime) over (partition by EmployeeID, CostCode) EmpCT
    , SUM(TotalTime) over (partition by EmployeeID) EmpT
    from Totals
    WHERE EmployeeID = '1234' ) Agr ) calc
order by 1,2,3

here is simplest way to calculate this:
select calc.*
, TotalTime * pr4R RegTime
, TotalTime * pr4O OverTime
from(
  select Agr.*
  , case when EmpT > 40 then round(40/EmpT, 2) else 1 end pr4R
  , case when EmpT > 40 then round(1 - 40/EmpT, 2) else 1 end pr4O
  from (
    select Totals.*
    , SUM(TotalTime) over (partition by EmployeeID) EmpT
    from Totals
    WHERE EmployeeID = '1234' ) Agr ) calc

but be watch on day 3, because there is only 7h.
The 1st query calculate days separately and live day 3.
The 2nd query scale all hours.
it could be another one, that calculate all emp rows but scale separatly RegTime and OverTime, with exception on day where is no 8h and increment it to 8h from OverTime.

A: This should help you get started...
-- % based on hours worked for each code on a DAILY basis (The original 21% in the question was based on this)
SELECT
T.EmployeeId,
T.Day,
T.CostCode,
T.TotalTime,
CAST(100.0 * T.TotalTime / X.DailyHours AS DECIMAL(10,2)) AS PercentageWorked
FROM #Totals T
INNER JOIN (
    SELECT
    EmployeeId,
    Day,
    SUM(TotalTime) AS DailyHours
    FROM #Totals
    GROUP BY EmployeeId, Day
) X ON X.EmployeeId = T.EmployeeId AND X.Day = T.Day

-- % based on hours worked for each code on a WEEKLY basis (The revised question)
SELECT
T.EmployeeId,
T.CostCode,
SUM(T.TotalTime) AS TotalTime,
CAST(100.0 * SUM(T.TotalTime) / X.WeeklyHours AS DECIMAL(10,2)) AS PercentageWorked
FROM #Totals T
INNER JOIN (
    SELECT
    EmployeeId,
    SUM(TotalTime) AS WeeklyHours
    FROM #Totals
    GROUP BY EmployeeId
) X ON X.EmployeeId = T.EmployeeId
GROUP BY
T.EmployeeId,
T.CostCode,
X.WeeklyHours


text:
Q: Stop prepend after first click $('#home-btn').on('click', function(e) {
    $('.settings-container').css('display', 'none');
    $('.container').css('display', 'block');
    $('.panel-heading').prepend(global_recipient);
});

So when i press the button (more than once), it will prepend over my panel heading of the container. I haven't figured out how to make it only prepend once so it doesn't overflow my heading. Any tips/help is much appreciated, thank you.

A: If you don't want to prepend you probably want to replace.
In that case I'd simply use:
$('.panel-heading').html(global_recipient);


text:
Q: Python memory shoot I have a Python app deployed on my ec2 machine via uwsgi-nginx. There are 2 scenarios.

*

*Integrating with a third-party service that takes > 10-15secs

*Firing an expensive DB query on AWS RDS that takes > 15secs.

I want to understand whether making these 2 operations would shoot up my ec2 memory/RAM. I'm in a dilemma right now, although the CPU process is blocked (for 10-15secs), however, both the above 2 operations are done on external services, ie RDS and third-party servers.
So, in the time of load-testing my app, why should I receive 503? Why does uwsgi stops accepting new requests?


text:
Q: Performance comparison of Nativescript vs Tabris.js Has anyone performed an analysis between NativeScript and Tabris.js to check which one performs better in Android and iOS? For example: in overall application responsiveness and any other metrics of system performance or benchmarks.

A: I don't have metrics, but from my experience TabrisJs is the fastest javascript framework currently, it is as fast as Flutter if not slightly faster.
NativeScript is slower than ReactNative which itself is not the top of speed.


text:
Q: Facebook plugin on Squarespace blog I added the Facebook plug-in in the post-code injection block, but then every new blog post includes the same "test" comment of mine. Any idea how to correct so that each new blog has a cleared FB comment section??

A: The code, as provided to you by Facebook, does not produce a dynamically changing URL for each new blog post. So, we must set the data-href attribute dynamically. The simplest way to do this is to use the following instead of what you're using now:

In the code above, we leave the data-href attribute empty, and then fill it in using JavaScript immediately following the div. The script then inserts the URL of the current page, making the comments unique to that page.


text:
Q: How does one write a decorator for dynamic properties? I have written an answer where I had to write some decorators so I can hook into some function calls.  However, I also want to hook into property setter calls as well but I'm not sure how that can be done.
In the answer, I wanted to hook into localStorage so that I can listen in on any changes.  I did this by decorating the setItem() and removeItem() functions.
I know I could decorate functions by creating new ones that at some point calls the original.
var _setItem = localStorage.setItem;
localStorage.setItem = function () {
    _setItem.apply(this, arguments);
    localStorageObserver.notifySubscribers(arguments[0]);
};

This works well but there are other uses I wish to hook into, property accesses.  The following is all equivalent for Storage objects:
localStorage.setItem('someProperty', 'value');
localStorage.someProperty = 'value';
localStorage['someProperty'] = 'value';

So I would need to hook into the last two cases but I'm not sure how that can be accomplished.
How does one write a decorator for dynamic properties?  Is it at all possible?
I suppose I could manually create properties as they are set to hide what is done by the storage object but that doesn't seem very scalable.  If there was a simple setProperty(name, value) function that I could hook into, I could decorate that.  But as far as I know, that doesn't exist.

A:
How does one write a decorator for dynamic properties? Is it at all possible?

As of ES5, with true JavaScript objects, you can decorate properties you can find the names of, but not ones you don't yet know the names of, by replacing the property with a getter/setter pair via Object.defineProperty. In ES6, it will be possible to create "proxies" which allow you to completely put a facade in front of an existing object, intercepting get/set even on proeprties whose names you don't yet know, provided you're allow to replace the object with the facade.
In the ES5 case, the object in question would have to be a true JavaScript object, and there's no guarantee of that with host-provided objects like localStorage. In the ES6 case, you'd have to be able to overwrite localStorage with your own facade object, but as localStorage is host-provided there's no guarantee you can and good reason to believe you won't be allowed to (and having tried it on Chrome, you can't on Chrome).


text:
Q: Bucket_script aggregation on filters aggregation not showing results I have "event" (like clicks on websites) documents in a index. Now I want to to calculate the ratio between events with name=x and events with name=y. I first use a "filters" agg to split up my documents into two buckets and then I use a bucket_script aggregation for calculating the ratio, but the result of it is not shown in the output...
Here is my query:
GET /_search
{
  "query": { ... },
  "aggs": {
    "all_my_documents": {
      "filters": {
        "filters": {
          "all": { "match_all": {} }
        }
      },
      "aggs": {

        "bucket-aggregation-for-clicks-per-conversation": {
          "filters": {
            "filters": {
              "presentation-clicks": { "term" : { "name" : "presentation-anchor-click" }},
              "conversation-starts": { "term" : { "name" : "conversation-start" }}
            }
          }
        },
        "how-many-clicks-per-conversation": {
          "bucket_script": {
              "buckets_path": {
                  "my_clicks": "bucket-aggregation-for-clicks-per-conversation['presentation-clicks']>_count",
                  "my_starts": "bucket-aggregation-for-clicks-per-conversation['conversation-starts']>_count"
              },
              "script": "params.my_clicks / params.my_starts"
          }
        }

      }
    }

  }
}

The query runs and as a result I get my two buckets but the "how-many-clicks-per-conversation" script does not seem to be run at all, because the value is missing from the output:
...
"aggregations" : {
  "all_my_documents" : {
    "buckets" : {
      "all" : {
        "doc_count" : 5,
        "bucket-aggregation-for-clicks-per-conversation" : {
          "buckets" : {
            "conversation-starts" : {
              "doc_count" : 4
            },
            "presentation-clicks" : {
              "doc_count" : 1
            }
          }
        }
      }
    }
  }
}

So, why is my bucket_script "how-many-clicks-per-conversation" not showing up in the output? Every help is greatly appreciated!
Thanks in advance
Anton


text:
Q: Using Dynamic proxy POCO's in Entity Framework As an example I have a database with two tables , company and employee with a one to many relationship. I am using EF 4
I was going through Julie Lerman's book and the firestarter sessions on channel 9 and have some questions on using dynamic proxies

*

*It is mentioned that when using dynamic proxies, creation of new objects should be done through ObjectContext.CreateObject and not by saying new Object() (for reference 1:09 in the video mentioned above). She clearly says that if you try adding an object in this manner it wont get added to the database and I won't even get an error. However I tried the following and it worked
try
    {
        using (var context = new sandeepTestEntities1())
        {
            var company1 = (from c1 in context.Companies
                            where c1.Name == "xyz"
                            select c1).Single();

            Employee e = new Employee();
            e.CompanyId = company1.Id;
            e.Age = 25;
            e.Name = "James";

            context.Employees.AddObject(e);

            context.SaveChanges();
        }
    }
    catch (Exception ex)
    {
        MessageBox.Show(ex.ToString());
    }

I am unable to understand the use of the CreateObject method in this scenario. I felt that it might have something to do with relationship and foreign key fixup but even that works when using the code above.

*It is also mentioned that if we have any custom code in the setters for the entities and we are using dynamic proxies the code doesnt get called. (1:14 in the video). In my example for the Employee entity I have the following code for the name property
public virtual string Name
{
       get{return _name;}
        set
            {
                if (value != null && value.Length > 50)
                 {throw new ArgumentException("Name must be less than 50 characters");}
            else
            { _name = value;}
            }

    }

I chnaged the code above for creating an employee to
   try
        {
            using (var context = new sandeepTestEntities1())
            {
                var company1 = (from c1 in context.Companies
                                where c1.Name == "xyz"
                                select c1).Single();

                var e = context.CreateObject<Employee>();
                e.CompanyId = company1.Id;
                e.Age = 25;
                e.Name = "X".PadLeft(51,'.');

                context.Employees.AddObject(e);

                context.SaveChanges();
            }
        }
        catch (Exception ex)
        {
            MessageBox.Show(ex.ToString());
        }

and I still get an exception when assigning the Name indicating that my custom code is being called. Is my understanding of both these points incorrect ?


text:
Q: Create a session when i select any option in select box using PHP? I am trying to create a session when I select an option in a select box. But it's not working, I am not even getting the value from the select box. I am using isset($_POST['SelectBoxName']), is there any alternative?
I am trying the below code, but it's not working.
I already have another session in the same program, will it be a problem ? It is used for some other process, and I want to create another session for some other process, but both should be in the same program. The another session is working perfectly, but this is not.
<?php
echo "<select name='cartQuantity' style='width:50px;' onchange='ajaxQuantityChange()'";
    for($q=1;$q<=30;$q++)
    {
        foreach($value as $key2 => $value2)
        {
    ?>
    <option value="<?php echo $q; ?>" <?php if($q==$key2){ ?>selected="selected" <?php } ?>><?php echo $q; ?></option>
    <?php
        }
    }
echo "</select>	";

//CREATE A SESSION
if(isset($_POST['cartQuantity']))
{
    $_SESSION['cartQuantity']=$_POST['cartQuantity'];
}
?>

This is "ajaxquantitychange" function:

My whole code is in this link. Please check it and can someone give me the solution for my question? https://www.mediafire.com/?8iv6gcaox2crogh

A: There is a problem in your line,
echo "<select name='cartQuantity' style='width:50px;' onchange='ajaxQuantityChange()'";

You didn't closed select tag. It should be
echo "<select name='cartQuantity' style='width:50px;' onchange='ajaxQuantityChange()'>";

A: That code is rather untidy. You could write it like:
<?php
    echo "<select name='cartQuantity' style='width:50px;' onchange='ajaxQuantityChange()'>";
    for ($q = 1; $q < 30; $q++)
        echo "<option value='$q'" . ($q == $key2 ? " SELECTED" : "") . ">$q</option>";
    echo "</select>	"
?>

To use sessions, you must first use session_start();
You can end a session with session_destroy();


text:
Q: Proving there are only two groups of order $4$, up to isomorphism I am trying to prove, for self-study, that there are two groups of order $4$ up to isomorphism. I have a characterization of the Klein four-group as $\{e, a, b, c\}$ where $ a,b,c$ have order $2$ and the product of any two non-identity elements gives the third non-identity element. I also have proven that any finite cyclic group is isomorphic to $\mathbb{Z}/4$. I haven't proved that the Klein group is isomorphic to $\mathbb{Z}/2 \times \mathbb{Z}/2$, but I assume this is as simple as writing down its elements and verifying that they match the defining relations of the klein group.
Here is my attempt.

Let $G$ be a group of order $4$. By Lagrange's theorem, the order of any element of $g$ must divide $4$, so the possible order of $g \in G$ can be $1$, $2$, or $4$. The identity element is, of course, the unique element of order $1$. If $G$ admits an element of order $4$, $g$, then $\langle g \rangle = G \cong \mathbb{Z}/4$. Suppose that $G$ lacks an element of order $4$. Then the three non-identity elements $a,b,c$ of $G$ must have order $2$. That is, $a^2 = b^2 = c^2 = e$. Furthermore, $ab \neq a$ and $ab \neq b$; by cancellation, $ab = a$ would imply that $b = e$ and $ab = b$ would imply that $a = e$. Finally, $ab \neq e$ because, otherwise,  $a = b^{-1}$, though because $a$ and $b$ have order $2$, they are their own inverses, and group inverses are unique. Therefore, $ab = c$. By exactly analogous arguments, interchanging labels, we find that $ac = b$ and $bc = a$. Therefore, the entire multiplication table is determined, and in fact $G$ is isomorphic to the Klein four-group.

How does this look?

A: Looks good to me. This answer must be 30 comments long.


text:
Q: Crossings in tikz knots package How can I create a crossing in the picture below? I tried to follow examples in the manual for tikz Knots package.
\documentclass[11pt]{amsart}
\usepackage{tikz}
\usetikzlibrary{knots}

\begin{document}
\begin{tikzpicture}[scale=0.75]
\begin{knot}[clip width=5, clip radius=8pt, consider self intersections]
  \strand[thick] (0,0)
    to[out=up, in=down] (0,1)
    to[out=up, in=left] (0.5,1.5)
    to[out=right, in=up]  (1,1)
    to[out=down, in=right]  (0.5,0.5)
    to[out=left, in=down]  (0,1)
    to[out=up, in=down]  (0,2);
\end{knot}
\end{tikzpicture}
\end{document}

EDIT: I am trying to illustrate the first Reidemeister move. Responding to Andrew's comment, I modified my code so that the crossing is not at the endpoint of a section and the crossing has tangents in different directions. However, the problem still persists:
\begin{knot}[clip width=10, clip radius=15pt, consider self intersections]
  \strand[thick] (0,0)
    to[out=up, in=down] (0,0.7)
    to[out=up, in=left] (0.5,1.5)
    to[out=right, in=up]  (1,1)
    to[out=down, in=right]  (0.5,0.5)
    to[out=left, in=down]  (0,1.3)
    to[out=up, in=down]  (0,2);
\end{knot}

A: Finding the intersections in a knot diagram is a lengthy process so the knots library makes a few optimisations, which can be turned off if needed.  These are:

*

*By default, it only looks at intersections between separate paths.  consider self intersections=true overrides this.

*When looking at self intersections then it has to split the path into sections and consider intersections between these sections.  Successive sections obviously intersect at their end points, these are considered spurious intersections and would crowd out the wanted ones so by default it ignores intersections that are near an endpoint of a section.  What it considers to be "near" is determined by end tolerance=<dimen> (for simplicity, it uses the l^1 norm).

*Ignoring endpoint intersections can be disabled altogether by the key ignore endpoint intersections=false.

Here are three solutions.  The first adjusts the path so that the intersection is not near an section endpoint (that is, near a specified point on the path).  The second uses a smaller adjustment and adjusts end tolerance=<dimen> as well.  The third uses the key ignore endpoint intersections=false on the original path.
\documentclass{article}

\usepackage{tikz}
\usetikzlibrary{knots}

\title{Untitled}
\author{}
\date{2020-11-11}
\begin{document}
\maketitle

\begin{tikzpicture}
\begin{knot}[clip width=10, clip radius=15pt, consider self intersections]
  \strand[thick] (0,0)
    to[out=up, in=down] (0,0.5)
    to[out=up, in=left] (0.5,1.5)
    to[out=right, in=up]  (1,1)
    to[out=down, in=right]  (0.5,0.5)
    to[out=left, in=down]  (0,1.5)
    to[out=up, in=down]  (0,2);
\end{knot}
\end{tikzpicture}

\begin{tikzpicture}
\begin{knot}[clip width=10, clip radius=15pt, consider self intersections, end tolerance=3pt]
  \strand[thick] (0,0)
    to[out=up, in=down] (0,0.7)
    to[out=up, in=left] (0.5,1.5)
    to[out=right, in=up]  (1,1)
    to[out=down, in=right]  (0.5,0.5)
    to[out=left, in=down]  (0,1.3)
    to[out=up, in=down]  (0,2);
\end{knot}
\end{tikzpicture}

\begin{tikzpicture}[scale=0.75]
\begin{knot}[clip width=5, clip radius=8pt, consider self intersections, ignore endpoint intersections=false]
  \strand[thick] (0,0)
    to[out=up, in=down] (0,1)
    to[out=up, in=left] (0.5,1.5)
    to[out=right, in=up]  (1,1)
    to[out=down, in=right]  (0.5,0.5)
    to[out=left, in=down]  (0,1)
    to[out=up, in=down]  (0,2);
\end{knot}
\end{tikzpicture}

\end{document}


text:
Q: Unchecking all desktop effects in Kubuntu 14.10 Plasma 4 I use Kubuntu 14.10 Plasma 4. Is there any way to uncheck all desktop effects at once, or do I have to do it one by one?

A: No, there is not.

*

*The list is not big

*People who want it are rather rare.

You can totally disable compostion manager with (by default) the Ctrl+Alt+F12 key combo. But it is not the same as disabling all effects.
If you wanted it for some sort of script, you could do it with manual config editing. Ask separate question for it.


text:
Q: opamp comparator circuit question battery discharger tester arduino
http://forum.arduino.cc/index.php?topic=8377.0
I have wanting to build a battery discharger/tester for age. I saw this circuit years ago, and thought it's great, but was too complicated to me to build back then. now I come back to this, and I have few questions for this circuit design.

*

*why there isn't a current limiting resistor between the output of the op-amp and the base of the NPN? and won't this current from the op-amp added to the total capacity of the battery?

*D2 is the voltage reading point. It uses a 0.5 ohm resistor as current sensor. if the discharging current is 500ma, then the voltage is v=IR= 0.5A * 0.5 ohm = 0.25v; 1A>0.5V; 100ma>0.05V; For an arduino analog pin with limited resolution.(5-0v 1024; 5/1024=0.0048v) How accurate will it be?

*A relay is used to end the discharging process. Will it be more simple by using a LOW digital output on the base of the NPN instead? Or maybe it's also okay to use a LOW digital output on the Vref of the op-amp?

A:
why there isn't a current limiting resistor between the output of the
  op-amp and the base of the NPN? and won't this current from the op-amp
  added to the total capacity of the battery?

The emitter is forced to be at Vref (due to feedback) so, in effect the circuit can be regarded as an emitter follower and, as such a base resistor is not needed. However, given that a relay can disconnect the main power source to the TIP41C, I would think it's a good idea to use one.

For an arduino analog pin with limited resolution.(5-0v 1024;
  5/1024=0.0048v) How accurate will it be?

You are confusing resolution with accuracy. If you want to understand the accuracy take into account INL, DNL, zero offset and gain slope errors stated inside the data sheet for the Arduino.

A relay is used to end the discharging process. Will it be more simple
  by using a LOW digital output on the base of the NPN instead? Or maybe
  it's also okay to use a LOW digital output on the Vref of the op-amp?

I would go for clamping Vref to 0V to limit the current but bear in mind the input offset voltage of the LM324 can add a small error and cause several tens of microamps still to flow. Maybe choose a much better op-amp. I would use a MOSFET to clamp Vref or maybe an analogue switch.

A: To your first question. Putting a resistor in series with the op amp would require more voltage from the op amp, and for an LM324 powered by 5 volts, there isn't a lot of voltage swing to spare. Also, an op amp is typically protected against output short circuits.
As for the op amp current, that actually decreases the battery current, rather than increasing it. The sense resistor sets the current in the resistor at some level, but that current is equal to the sum of the base and collector currents. This is not a problem in your case, since the transistor will typically have a gain of 20 to 40, which means that the error produced by the base current will be in the range of 2 1/2 to 5 per cent. If you need more accuracy, either use a transistor with higher gain, or use a MOSFET, which draws no current through the gate (for low frequencies).
Responding to your second question. If you want to drive this circuit from an Arduino analog output, you should not use the circuit as shown.
Start by determining what your maximum current should be. Let's say 1 amp. As you have realized, this means 0.5 volts across the sense resistor, and about 0.5 volts at the op amp. Instead of your circuit as shown, try

simulate this circuit – Schematic created using CircuitLab
R1 and R2 form a 10 to 1 voltage divider, and 0 to 5 volts in will produce 0 to 0.5 volts at the op amp. Since the input voltage scales exactly to the load current, the tester's resolution will be $$ \Delta i = \frac{1 \text{ amp}}{1023} = .977\text{ mA}$$


text:
Q: how to provide custom css for ngbDatepicker in angular 4 my html code is as follows:

Date Range:

          <input class="form-control" value="2017-01-01"
                 name="dp1" [(ngModel)]="model" ngbDatepicker
                 #dp1="ngbDatepicker"
                 (click)="dp1.toggle()"  [ngClass]="'my_group'"
                 (ngModelChange)="changeValue()">
          TO
          <input class="form-control" value="2017-01-01"
                 name="dp2" [(ngModel)]="model" ngbDatepicker
                 #dp2="ngbDatepicker"
                 (click)="dp2.toggle()" [ngClass]="'my_group'"
                 (ngModelChange)="changeValue()">

I want tot change ngbDatepicker remove left poisition to zero. So, i tried to put css as follows:
  .my_group {

        left: 0px;
        right: 0px;

}

It still didn't worked, any help is appreciated.

A: This works for me :
:host /deep/ ngb-datepicker {
    left: 0px !important;
    right: 0px !important;}

A:
This is working

.use_your_Main_class /deep/ .ngb-dp-header  {
    width: 100% !important;
    text-align: center !important;
    border-bottom: 2px solid #e2e2e2 !important;
    box-shadow: 0px 10px 10px -6px rgba(0, 0, 0, 0.10) !important;
    padding: 10px 0 !important;
    background:transparent !important;

}

A: Use this example:
:host ::ng-deep .ngb-dp-months {
  background:green;
}
:host ::ng-deep .ngb-dp-month {
  background:blue;
}

:host ::ng-deep .the-ngb-dp-class {
  background:red;
}

A: You're not targeting a class - try .my_group (notice the period before the name my_group)
Like this:
.my_group {
    left: 0px;
    right: 0px;
}

Are you sure it's absolute or fixed (assuming it's parent is relative)?
.my_group {
    left: 0px;
    right: 0px;
    position: absolute;
}

A: Inspect the style classes of datepicker in the node_modules. And check which class you want to override, then use :host /deep/ for that. As an example, this is how I override the header css for datepicker:
:host /deep/ .ngb-dp-header  {
  //...
}


text:
Q: Фокус и клавиатура в EditText При повторном нажатии на EditText с фокусом и уже открытой клавиатурой, клавиатура и фокус на долю секунды пропадают и появляются заново, получается что клавиатура как-то "выпрыгивает", не нравится глазу. Посмотрел другие приложения, например "Поиск" в TikTok, там такого исчезновения и появления нет. Это можно как то настроить?
UPD: Убрал эту часть кода, "обновление" пропало, но этот метод позволял убирать фокус с клавиатурой просто по клику на экран, и был достаточно важным, его можно как то по другому реализовать ?
@Override
public boolean dispatchTouchEvent(@NonNull MotionEvent event) {
    if (event.getAction() == MotionEvent.ACTION_DOWN) {
        View v = getCurrentFocus();
        if (v instanceof EditText) {
            v.clearFocus();
            InputMethodManager imm = (InputMethodManager) getBaseContext().getSystemService(Context.INPUT_METHOD_SERVICE);
            imm.hideSoftInputFromWindow(v.getWindowToken(), 0);
        }
    }
    return super.dispatchTouchEvent(event);
}

A: Можно добавить слушатель который будет проверять наличие фокуса у поля для ввода:
editText.setOnFocusChangeListener(new View.OnFocusChangeListener() {
    @Override
    public void onFocusChange(View v, boolean hasFocus) {
        if (hasFocus) {
            dialog.getWindow().setSoftInputMode(WindowManager.LayoutParams.SOFT_INPUT_STATE_ALWAYS_VISIBLE);
        }
    }
});

таким образом, если фокуса нет то показывать клавиатуру. Так же для проверки видимости клавиатуры можно воспользоваться этим и этим способами.
UPDATE
Убирать фокус при клике можно кликнув на родительский макет поля для ввода, вот например так:
FrameLayout touchInterceptor = (FrameLayout)findViewById(R.id.touchInterceptor);
touchInterceptor.setOnTouchListener(new OnTouchListener() {
    @Override
    public boolean onTouch(View v, MotionEvent event) {
        if (event.getAction() == MotionEvent.ACTION_DOWN) {
            if (mEditText.isFocused()) {
                Rect outRect = new Rect();
                mEditText.getGlobalVisibleRect(outRect);
                if (!outRect.contains((int)event.getRawX(), (int)event.getRawY())) {
                    mEditText.clearFocus();
                    InputMethodManager imm = (InputMethodManager) v.getContext().getSystemService(Context.INPUT_METHOD_SERVICE);
                    imm.hideSoftInputFromWindow(v.getWindowToken(), 0);
                }
            }
        }
        return false;
    }
});

так же в xml можно добавить такие поля:
android:focusableInTouchMode="true"
android:clickable="true"
android:focusable="true"

Вот вопрос по данной тематике.


text:
Q: TypeOrm find relations with object data mapper I have users who can have multiple emails associated. I want to accomplish two things given below using data object mapper. How can I do that?

*

*I want to find all users in a given array.

const emails = ['xyz@opc.com', 'abc@hdc.com'];
const users = await findUsersWithEmails(emails);

*Find a user with an email.

const email = 'xyz@opc.com';
const user = await findUserWithEmail(email);

Entities
@Entity('email')
export class Email extends BaseEntity {
    @Column({ nullable: false, unique: true })
    email: string;

    @Column({ default: false })
    verified: boolean;

    @ManyToOne(type => User, user => user.emails)
    user: Promise<User>;
}

@Entity('users')
export class User extends BaseEntity {
    @Column({ nullable: false })
    name: string;

    @OneToMany(type => Phone, phone => phone.user)
    emails: Promise<Email[]>;
}


text:
Q: Ajax alert message persists after clicking okay button my code works alright but the alert message in the browser doesn't go away after I click the okay button inside the alert success prompt. I've tried all I can but still persists. Please help.
HTML
<button  id="flag-post" data-post-id="{{ $counter->id }}">Report this</button>

Route
Route::get('/flag', [App\Http\Controllers\ApplicationsController::class, 'flagPost'])->name('flag.post');

Controller
 public function flagPost(Request $request)
{

    $postId = $request->input('post_id');

    $post = Job::findOrFail($postId);

    $post->increment('flags');

    return response()->json(['success' => true]);
}

Javascript
<script>
    $(function() {
    $('#flag-post').click(function() {
    // Retrieve the post ID from the button's data attribute
    var postId = $(this).data('post-id');

    // Send an AJAX request to the flag post route
    $.ajax({
        url: "{{ route('flag.post') }}",
        type: "GET",
        data: {
            post_id: postId,
            _token: "{{ csrf_token() }}"
        },
        success: function(response) {
            // Alert the user that the post has been flagged
            alert("Thank you for flagging this post!");
        },
        error: function(xhr, status, error) {
            // Alert the user that there was an error
            alert("Error: " + error);
        }
    });
});
});

    </script>

A: try this way:
function flagPost() {
  $(document).on('click', '#flag-post', function() {
    // Retrieve the post ID from the button's data attribute
    let postId = $(this).data('post-id');
    $.get('{{route("flag.post")}}', {
      post_id: postId,
      _token: "{{ csrf_token() }}"
    }).done(function (resp){
      alert("Thank you for flagging this post!");
    }).fail(function () {
      alert("Error");
    });
  });
}

$(document).ready(function () {
  flagPost();
});

However i advise you to use post with method put


text:
Q: How to create logical variable based on logical condition? I have a data frame with factor variables
> a <- c("a", "b", "c")
> b <- c("c", "b", "a")
> df <- as.data.frame(cbind(a,b))
> df$a <- as.factor(df$a)
> df$b <- as.factor(df$b)
> df
  a b
1 a c
2 b b
3 c a

I create new logical variable based on the similarity of var a and var b.
> df$result <- isTRUE(df$a == df$b)

But I get the result:
> df
  a b result
1 a c  FALSE
2 b b  FALSE
3 c a  FALSE

When I expected
> df
  a b result
  1 a c  FALSE
  2 b b  TRUE
  3 c a  FALSE

(I'm using factors to replicate my real data)
What am I doing wrong? How can I achieve my goal of identifying similar variables? Thanks

A: Just do
df$result <- with(df, a==b)
df
#  a b result
#1 a c  FALSE
#2 b b   TRUE
#3 c a  FALSE

The a==b already returns a logical vector and we don't need isTRUE to wrap it.
As @Frank mentioned in the comments, it is better to evaluate between character class columns as difference in factor levels can result in error.  We can either convert the factor to character for evaluating
 with(df, as.character(a)==as.character(b))

or make the levels the same as in both columns
 Un1 <- union(levels(df$a), levels(df$b))
 df[] <- lapply(df, factor, levels=Un1)
 with(df, a==b)


text:
Q: Using .NET for Windows Forms based Product Development .NET has become a popular technology among software developers and comsumers. I was thinking if it would be a wise decision to develop a Windows Forms based product in .NET that can be downloaded by thousands of customers around the world. The real problem could be the framework installation that has grown considerably with the .NET versions.
v2.0 had a decent 22MB install but the latest v3.5 goes beyond 150MB and can prove to be a deciding factor for customers. I have heard of some tools that do a type of "static" linking for .NET assemblies (e.g. ILMerge) and can be used to create small self contained executables but the question is can these tools be used in production environment? he ILMerge tool was a Research tool and I think it never made it to VS installation.
I have a product to develop that needs a very nice looking user interface which can be accomplished using the WPF support. But I am not sure if customers would like to download a 150MB framework (Not sure how big is v3.0) for a 4MB application. If I develop in .NET 2.0, I loose support for WPF.
Does XP, Vista, Windows 7 come with a preinstalled .NET framework?
-- UPDATED BASED ON COMMENTS --
The application will be downloaded from a website and will not have a distributable media.

*

*Use .NET 2.0 - This wont let me use WPF so I will loose on the fancy stuff unless I use some third party skinning tool.

*Use the Client Profile to strip down the installation - The installation will come down to around 30 Megs and I will retain WPF/WCF support along with the new framework features.

*Supported OSes
  Win 98, ME, 2000 - Full install of Runtime required
  Win XP SP2, SP3, 2003 (I think these have .NET 2.0)
  Vista, 2008 - All version have atleast v3.0
  Windows 7 - v3.5

A: Various versions of the .NET framework do come pre installed with Vista and Windows 7:

*

*XP - Nothing

*Vista - .NET 3.0

*Windows 7 - .NET 3.5

If you are really concerned about the download size you should take a look at the client profile. This is a cut down version of the framework that includes just the bits most important for client application development. I believe its ~30 MB in size. Support for it was patchy in 3.5. It only worked on XP 32bit and only if no other framework versions were installed, but looks to be much better in 4.0. It now works on all platforms that support the full .NET framework even if they already have another framework version and comes in re-distributable form as well as a web installer See here
Going beyond the technical details, you do need to consider your target market. Different markets have different base lines and requirements. Remember you can always bundle up the .NET installer with your application all on one CD if you are physically distributing the media. I'd say in most cases it shouldn't be a problem (particularly if you target the client profile), I'd only be worried if you were targeting a specific and small market sector that had very strict requirements on what software was allowed.

A: If you worried about the size of the install then I would target the .Net 2.0 framework over the .Net 3.5 framework - if you are just doing a basic windows forms application (no WCF, WPF or Linq etc...) then the .Net 2.0 framework has 90% of the functionality of .Net 3.0 or 3.5, and it also present on a much higher percentage of machines (80% according to this blog)
In VS2008 I've modified my project templates to make this the default.

A: It can certainly be a concern for users with slow network connections. One solution is to restrict development to not use newer features (that is what I do) and providing a link to the .NET 2.0 runtime on your application's installation instructions web page. This will work fine for Windows Forms (although it will not be possible to use WPF and some of the newer language features).

A: There is also the .NET Framework Client Profile Preview that should reduce the .NET Framework download size to 28 MB. It includes WPF.

A: I don't think it's a deciding factor, most of the time. Vista has .NET 3.0 already packaged with it, I believe. Plus, Java is in the same boat (requiring a JRE) and I don't know of any software who has really suffered from the "overhead" of downloading a run-time platform like Java's or .NET.
I strongly believe it's better to think of these platforms as de facto standards; So many applications require them nowadays; chances are most of your potential users already has them installed.

A: Ok, so let me ask this stupid question. Why have you confined yourself to a standalone Desktop client rather than a Web application? You could do the fancy stuff using Silverlight. One of the client with whom I worked, does have a stand alone client in the market but eventually wants to move it to the Web since he needs the Mac users too.

A: Make it so wonderful clients would download a 1GB framework :).
Now seriously, as XP and all versions above come with .NET preinstalled, what are you worrying about?
You could just target .NET 2.0 for now (unless commited to WPF) and, after 3.5 gains enough popularity, switch.

A: If off-line installation of .NET is not required then the online installer can be used
and the actual download size will be below 60 megs (depending on how much is already installed).


text:
Q: SQLite GROUP BY 2 Tabelas e SUM entre valores das tabelas Olá, eu tenho as seguintes tabelas e estou utilizando o SQLite:
Transação cartão:
id, valor, data
1, 20, Janeiro
2, 40, Janeiro
3, 10, Fevereiro

Transação banco:
id, valor, data,
1, 10, Janeiro
2, 10, Janeiro
3, 5, Fevereiro
4, 45, Março

Eu preciso que o retorno seja o agrupamento por mês com o retorno da soma dos valores ordenado pela data crescente o decrescente. No caso do exemplo acima, o retorno teria que ser:
Valor, data
80, Janeiro
15, Fevereiro
45, Março

Considerando que pode ter datas que tem em uma tabela e em outra não.
Como seria o comando para o retorno esperado?
O que eu tentei foi algo do tipo abaixo, porém, o resultado está sendo ele somar todos os valores para todas as linhas.
SELECT SUM(b.valor + c.valor) valor, b.data, c.data  FROM cartaoTransacoes as c, bancoTransacoes as b GROUP BY c.data, b.data ORDER BY c.data, b.data ASC

A: Como as tabelas não tem um campo em comum, o que você pode fazer é um UNION para juntar as consultas em separado, e sobre este resultado fazer o agrupamento. Sua consulta ficaria da seguinte forma:
SELECT data, sum(valor) as valor FROM (
SELECT data, valor
FROM cartaoTransacoes
UNION
SELECT data, valor
FROM bancoTransacoes
) GROUP BY data

Mais informações:
https://www.sqlitetutorial.net/sqlite-union/


text:
Q: Is it possible to create a new book from the rows found under a "Find All" search? The way I do it now is:

*

*CTRL + F

*Enter Data to Find (e.g. "57011-141")

*Click Find All

*Usually 10-20 rows will come up.  I then go one by one copying and pasting into a new book.

I am looking to automate this process as it is time consuming and error prone.

A: If the 57011-141 appears in a single column (sorting irrelevant)
Filter the data (This image is from Excel 2010)

The down arrow next to the column name will allow you to set the filter under TextFilters -> Contains
Once the filter is applied, select all the displayed data - use ALT+;
Copy the data (use menu or CTRL+C)
Find your destination and paste (use menu or CTRL+V)
This will copy column headers, as well as the filtered data, so if you have multiple copies to do, you will have to remove the extra headers

A: If 57011-141 appears in single column, here is the solution.

*

*Sort the book with that particular column.

*CTRL + F

*Data to Find (e.g. "57011-141")

*Click Find All

*Cntrl + A

*Close Find & Replace Dialog

*Shift + Space to select all rows which returned by Find

*Copy and paste into new sheet

Edit:
if "57011-141" found in middle of a string in cell,

*

*Add a new column (D) next to the search column (C)

*Formula in column D1 =ISNUMBER(SEARCH("57011-141",C1,1))

*Copy & Paste the formula to all rows

*Sort column D

Now you will get all the identified rows in column D if value TRUE


text:
Q: For counter variable not working in the if else statement The i variable from the for counter works when getting each API for each Twitch streamer, however when I use it to generate divs it just comes out as 8. Is there a way I can make the counter work when getting the API data and iterating through the streamers?
$(document).ready(function(){

// streamers I want to look up

 var streamers = ["ESL_SC2", "OgamingSC2", "cretetion", "freecodecamp", "storbeck", "habathcx", "RobotCaleb", "noobs2ninjas"]

// counts the number of streamers in the array

  for (var i = 0; i < streamers.length; i++){

// gets each streamer, one by one

  $.getJSON("https://wind-bow.gomix.me/twitch-api/streams/" + streamers[i] +"?callback=?", function(json) {

//if they are not offline, pulls information from them and adds it to a div

if ((json.stream) !== null) {
  $("#results").prepend("
" + json.stream.channel.display_name + "
");

// if they are offline, marks them as offline

} else {
  $("#results").append("
" + streamers[i] + " is offline
");

}

  });

  };

A: try this
$(document).ready(function(){

    // streamers I want to look up

     var streamers = ["ESL_SC2", "OgamingSC2", "cretetion", "freecodecamp", "storbeck", "habathcx", "RobotCaleb", "noobs2ninjas"]

    // counts the number of streamers in the array
      var index = 0;
      for (var i = 0; i < streamers.length; i++){

    // gets each streamer, one by one

      $.getJSON("https://wind-bow.gomix.me/twitch-api/streams/" + streamers[i] +"?callback=?", function(json) {

    //if they are not offline, pulls information from them and adds it to a div

    if ((json.stream) !== null) {
      $("#results").prepend("
" + json.stream.channel.display_name + "
");

    // if they are offline, marks them as offline

    } else {
      $("#results").append("
" + streamers[index] + " is offline
");

    }
    index++;

      });

      };

A: If I'm not mistaken, getJSON is a promise based function, so try to use .then(json => function() ...).
This code should work properly.
$(document).ready(function() {
  // streamers I want to look up
  var streamers = [
    "ESL_SC2",
    "OgamingSC2",
    "cretetion",
    "freecodecamp",
    "storbeck",
    "habathcx",
    "RobotCaleb",
    "noobs2ninjas"
  ];

  // counts the number of streamers in the array
  var streamerLength = streamers.length;
  for (var i = 0; i < streamerLength; i++) {
    // gets each streamer, one by one
    $.getJSON(
      "https://wind-bow.glitch.me/twitch-api/streams/" + streamers[i]
    ).then(json => appendStreamerInfo(json));
  }

  function appendStreamerInfo(json) {
    //if they are not offline, pulls information from them and adds it to a div
    if (json.stream !== null) {
      $("#results").prepend(
        '
' +
          json.stream.channel.display_name +
          "
"
      );

      // if they are offline, marks them as offline
    } else {
      $("#results").append(
        '
' + streamers[i] + " is offline
"
      );
    }
  }
});


text:
Q: tkinter - Changing main window label with toplevel class from another module Just starting to code and picked up Python and tkinter recently. Currently trying to understand a few things such as tkinter toplevel and parent window relationship and accessing variables in a class. I'm exploring a few ways to achieve that just so I could challenge myself in understanding things better. But I'm stuck in one of my challenges. I look at this code from here and I modified it a bit by changing the text to label and moving the toplevel to another module. So what I hope to achieve is by clicking the button on the toplevel, the label on main window can change accordingly.
main.py
from tkinter import *
import top

class GUI(Frame):
    def __init__(self, master, *args, **kwargs):
        Frame.__init__(self, master, *args, **kwargs)

        self.master = master
        self.my_frame = Frame(self.master)
        self.my_frame.pack()

        self.button1 = Button(self.master, text="Open New Window",
                              command = top.open_toplevel_window)   #Managed to access the toplevel by importing the module in
        self.button1.pack()

        self.text = Label(self.master, width = 30, height = 3, text="Before Top window")
        self.text.pack()

if __name__ == "__main__":
    root = Tk()
    app = GUI(root)
    root.mainloop()

top.py
from tkinter import *
from main import *         #I thought by importing the main module i could solve it

class open_toplevel_window(Toplevel):
    def __init__(self, *args, **kwargs):
        Toplevel.__init__(self, *args, **kwargs)
        self.grab_set()

        def replace_text():
            app.text.delete(1.0, END)                    #Error here. What do I put to refer to the object instead of 'app'?
            app.text.insert(END, "Text From\nToplevel")  #Same problem

        top_button = Button(self, text = "Replace text in main window",
                            command = replace_text)
        top_button.pack()

So the problem is I don't know what to do to get access to the variable so the text label can be changed.
I apologize if there's a similar question to this but I've scoured and I could not find any that is as specific to my problem. And since I'm new to these I might've missed some useful answers so I'd appreciate it so much if anyone could help me with these or at the very least point me to the solutions.


text:
Q: How to install verse package? How can I install the verse package? I did not find it in my Ubuntu 10.1. Through a Google search I went to:
http://www.ctan.org/tex-archive/macros/latex/contrib/verse
and followed the instructions. It gave me the following error:
(./verse.ins
*** Generating the LaTeX2e package files ***

Generating file(s) ./verse.sty
! Cannot find file verse.dtx.
\readsource ...ot find file \uptospace #1 \qStop }
                                                  \else \processedLines \z@ ...
l.56 ...e{\file{verse.sty}{\from{verse.dtx}{usc}}}

? ^C! Interruption.
\readsource ...t \refusedfiles \empty \csname b@#1
                                                  \endcsname \Name \let {b@#...
l.56 ...e{\file{verse.sty}{\from{verse.dtx}{usc}}}

?

A: If you installed TeX from the repositiories, look in the operating system package manager of the verse package in the comments to the packages. I list links to Debian packages, since Ubuntu uses Debian packages:

*

*texlive-humanities

A collection of LaTeX packages for law, linguistics, the social sciences,
and the humanities.
This package includes the following CTAN packages:
  ....
verse -- Aids for typesetting simple verse.

*or texlive-latex-extra

A large collection of add-on packages for LaTeX.
This package includes the following CTAN packages:
  ....
verse -- Aids for typesetting simple verse.

Also apt-search can help, such as:
sudo apt-cache search verse | grep tex

You can install by Synaptic or another manager or on the command line:
sudo apt-get install texlive-humanities